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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
use crate::mnemonic::Mnemonic;
use anyhow::{anyhow, Result};
use byteorder::{ByteOrder, LittleEndian};
use diem_crypto::{
compat::Sha3_256,
ed25519::{Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature},
hash::CryptoHash,
hkdf::Hkdf,
traits::SigningKey,
};
use diem_types::{account_address::AccountAddress, transaction::authenticator::AuthenticationKey};
use hmac::Hmac;
use mirai_annotations::*;
use pbkdf2::pbkdf2;
use serde::{Deserialize, Serialize};
use std::{convert::TryFrom, ops::AddAssign};
pub struct Main([u8; 32]);
impl_array_newtype!(Main, u8, 32);
impl_array_newtype_show!(Main);
impl_array_newtype_encodable!(Main, u8, 32);
#[derive(Default, Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct ChildNumber(pub(crate) u64);
impl ChildNumber {
pub fn new(child_number: u64) -> Self {
Self(child_number)
}
pub fn increment(&mut self) {
self.add_assign(Self(1));
}
}
impl std::ops::AddAssign for ChildNumber {
fn add_assign(&mut self, other: Self) {
assume!(self.0 <= u64::max_value() / 2); assume!(other.0 <= u64::max_value() / 2); *self = Self(self.0 + other.0)
}
}
impl std::convert::AsRef<u64> for ChildNumber {
fn as_ref(&self) -> &u64 {
&self.0
}
}
impl std::convert::AsMut<u64> for ChildNumber {
fn as_mut(&mut self) -> &mut u64 {
&mut self.0
}
}
pub struct ExtendedPrivKey {
_child_number: ChildNumber,
private_key: Ed25519PrivateKey,
}
impl ExtendedPrivKey {
pub fn new(_child_number: ChildNumber, private_key: Ed25519PrivateKey) -> Self {
Self {
_child_number,
private_key,
}
}
pub fn get_public(&self) -> Ed25519PublicKey {
(&self.private_key).into()
}
pub fn get_address(&self) -> AccountAddress {
diem_types::account_address::from_public_key(&self.get_public())
}
pub fn get_private_key(&self) -> Ed25519PrivateKey {
self.private_key.clone()
}
pub fn get_authentication_key(&self) -> AuthenticationKey {
AuthenticationKey::ed25519(&self.get_public())
}
pub fn sign<T: CryptoHash + Serialize>(&self, msg: &T) -> Ed25519Signature {
self.private_key.sign(msg)
}
}
pub struct KeyFactory {
main: Main,
}
impl KeyFactory {
const MNEMONIC_SALT_PREFIX: &'static [u8] = b"DIEM WALLET: mnemonic salt prefix$";
const MAIN_KEY_SALT: &'static [u8] = b"DIEM WALLET: main key salt$";
const INFO_PREFIX: &'static [u8] = b"DIEM WALLET: derived key$";
pub fn new(seed: &Seed) -> Result<Self> {
let hkdf_extract = Hkdf::<Sha3_256>::extract(Some(KeyFactory::MAIN_KEY_SALT), &seed.0)?;
Ok(Self {
main: Main::from(&hkdf_extract[..32]),
})
}
pub fn main(&self) -> &[u8] {
&self.main.0[..]
}
pub fn private_child(&self, child: ChildNumber) -> Result<ExtendedPrivKey> {
let mut le_n = [0u8; 8];
LittleEndian::write_u64(&mut le_n, child.0);
let mut info = KeyFactory::INFO_PREFIX.to_vec();
info.extend_from_slice(&le_n);
let hkdf_expand = Hkdf::<Sha3_256>::expand(self.main(), Some(&info), 32)?;
let sk = Ed25519PrivateKey::try_from(hkdf_expand.as_slice()).map_err(|e| {
anyhow!(
"Unable to convert hkdf output into private key, met Error:{}",
e
)
})?;
Ok(ExtendedPrivKey::new(child, sk))
}
}
pub struct Seed([u8; 32]);
impl Seed {
pub fn new(mnemonic: &Mnemonic, salt: &str) -> Seed {
let mut output = [0u8; 32];
let mut msalt = KeyFactory::MNEMONIC_SALT_PREFIX.to_vec();
msalt.extend_from_slice(salt.as_bytes());
pbkdf2::<Hmac<Sha3_256>>(mnemonic.to_string().as_ref(), &msalt, 2048, &mut output);
Seed(output)
}
}
#[cfg(test)]
#[test]
fn assert_default_child_number() {
assert_eq!(ChildNumber::default(), ChildNumber(0));
}
#[cfg(test)]
#[test]
fn test_key_derivation() {
let data = hex::decode("7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f").unwrap();
let mnemonic = Mnemonic::from("legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will").unwrap();
assert_eq!(
mnemonic.to_string(),
Mnemonic::mnemonic(&data).unwrap().to_string()
);
let seed = Seed::new(&mnemonic, "DIEM");
let key_factory = KeyFactory::new(&seed).unwrap();
assert_eq!(
"66ae6b767defe3ea0c646f10bf31ad3b36f822064d3923adada7676703a350c0",
hex::encode(&key_factory.main())
);
let child_private_0 = key_factory.private_child(ChildNumber(0)).unwrap();
assert_eq!(
"732bc883893c716f320c01864709ca9f16f8f30342a1de42144bfcc2ddb7af10",
hex::encode(&child_private_0.private_key.to_bytes()[..])
);
let child_private_0_again = key_factory.private_child(ChildNumber(0)).unwrap();
assert_eq!(
hex::encode(&child_private_0.private_key.to_bytes()[..]),
hex::encode(&child_private_0_again.private_key.to_bytes()[..])
);
let child_private_1 = key_factory.private_child(ChildNumber(1)).unwrap();
assert_eq!(
"f6b472bd0941e315d3c34c3ac679d610d2b9e1abe85128752d04bb0f042f3391",
hex::encode(&child_private_1.private_key.to_bytes()[..])
);
let mut child_1_again = ChildNumber(0);
child_1_again.increment();
assert_eq!(ChildNumber(1), child_1_again);
let child_private_1_from_increment = key_factory.private_child(child_1_again).unwrap();
assert_eq!(
"f6b472bd0941e315d3c34c3ac679d610d2b9e1abe85128752d04bb0f042f3391",
hex::encode(&child_private_1_from_increment.private_key.to_bytes()[..])
);
}