1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use crate::{
error::WalletError,
io_utils,
key_factory::{ChildNumber, KeyFactory, Seed},
mnemonic::Mnemonic,
};
use anyhow::Result;
use diem_crypto::ed25519::Ed25519PrivateKey;
use diem_types::{
account_address::AccountAddress,
transaction::{
authenticator::AuthenticationKey, helpers::TransactionSigner, RawTransaction,
SignedTransaction,
},
};
use rand::{rngs::OsRng, Rng};
use std::{collections::HashMap, path::Path};
pub struct WalletLibrary {
mnemonic: Mnemonic,
key_factory: KeyFactory,
addr_map: HashMap<AccountAddress, ChildNumber>,
key_leaf: ChildNumber,
}
impl WalletLibrary {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
let mut rng = OsRng;
let data: [u8; 32] = rng.gen();
let mnemonic = Mnemonic::mnemonic(&data).unwrap();
Self::new_from_mnemonic(mnemonic)
}
pub fn new_from_mnemonic(mnemonic: Mnemonic) -> Self {
let seed = Seed::new(&mnemonic, "DIEM");
WalletLibrary {
mnemonic,
key_factory: KeyFactory::new(&seed).unwrap(),
addr_map: HashMap::new(),
key_leaf: ChildNumber(0),
}
}
pub fn mnemonic(&self) -> String {
self.mnemonic.to_string()
}
pub fn write_recovery(&self, output_file_path: &Path) -> Result<()> {
io_utils::write_recovery(self, &output_file_path)?;
Ok(())
}
pub fn recover(input_file_path: &Path) -> Result<WalletLibrary> {
io_utils::recover(&input_file_path)
}
pub fn key_leaf(&self) -> u64 {
self.key_leaf.0
}
pub fn generate_addresses(&mut self, depth: u64) -> Result<()> {
let current = self.key_leaf.0;
if current > depth {
return Err(WalletError::DiemWalletGeneric(
"Addresses already generated up to the supplied depth".to_string(),
)
.into());
}
while self.key_leaf != ChildNumber(depth) {
let _ = self.new_address();
}
Ok(())
}
pub fn new_address_at_child_number(
&mut self,
child_number: ChildNumber,
) -> Result<AccountAddress> {
let child = self.key_factory.private_child(child_number)?;
Ok(child.get_address())
}
pub fn new_address(&mut self) -> Result<(AuthenticationKey, ChildNumber)> {
let child = self.key_factory.private_child(self.key_leaf)?;
let authentication_key = child.get_authentication_key();
let old_key_leaf = self.key_leaf;
self.key_leaf.increment();
if self
.addr_map
.insert(authentication_key.derived_address(), old_key_leaf)
.is_none()
{
Ok((authentication_key, old_key_leaf))
} else {
Err(WalletError::DiemWalletGeneric(
"This address is already in your wallet".to_string(),
)
.into())
}
}
pub fn get_addresses(&self) -> Result<Vec<AccountAddress>> {
let mut ret = Vec::with_capacity(self.addr_map.len());
let rev_map = self
.addr_map
.iter()
.map(|(&k, &v)| (v.as_ref().to_owned(), k.to_owned()))
.collect::<HashMap<_, _>>();
for i in 0..self.addr_map.len() as u64 {
match rev_map.get(&i) {
Some(account_address) => {
ret.push(*account_address);
}
None => {
return Err(WalletError::DiemWalletGeneric(format!(
"Child num {} not exist while depth is {}",
i,
self.addr_map.len()
))
.into())
}
}
}
Ok(ret)
}
pub fn sign_txn(&self, txn: RawTransaction) -> Result<SignedTransaction> {
if let Some(child) = self.addr_map.get(&txn.sender()) {
let child_key = self.key_factory.private_child(*child)?;
let signature = child_key.sign(&txn);
Ok(SignedTransaction::new(
txn,
child_key.get_public(),
signature,
))
} else {
Err(WalletError::DiemWalletGeneric(
"Well, that address is nowhere to be found... This is awkward".to_string(),
)
.into())
}
}
pub fn get_private_key(&self, address: &AccountAddress) -> Result<Ed25519PrivateKey> {
if let Some(child) = self.addr_map.get(address) {
Ok(self.key_factory.private_child(*child)?.get_private_key())
} else {
Err(WalletError::DiemWalletGeneric("missing address".to_string()).into())
}
}
pub fn get_authentication_key(&self, address: &AccountAddress) -> Result<AuthenticationKey> {
if let Some(child) = self.addr_map.get(address) {
Ok(self
.key_factory
.private_child(*child)?
.get_authentication_key())
} else {
Err(WalletError::DiemWalletGeneric("missing address".to_string()).into())
}
}
}
impl TransactionSigner for WalletLibrary {
fn sign_txn(&self, raw_txn: RawTransaction) -> Result<SignedTransaction, anyhow::Error> {
self.sign_txn(raw_txn)
}
}