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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
use elliptic_curve::sec1::ToEncodedPoint;
use k256::{ProjectivePoint, PublicKey as K256PublicKey, Scalar, SecretKey};
use crate::{HARDENED_KEY_OFFSET, XPUB_VERSION_BYTE};
use std::io::{Cursor, Read, Write};
use crate::{hash::Hash, BSVErrors, ExtendedPrivateKey, PublicKey};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use getrandom::*;
use wasm_bindgen::{prelude::*, throw_str};
#[wasm_bindgen]
pub struct ExtendedPublicKey {
public_key: PublicKey,
chain_code: Vec<u8>,
depth: u8,
index: u32,
parent_fingerprint: Vec<u8>,
}
impl ExtendedPublicKey {
pub fn new(public_key: &PublicKey, chain_code: &[u8], depth: &u8, index: &u32, parent_fingerprint: Option<&[u8]>) -> Self {
let fingerprint = parent_fingerprint.unwrap_or(&[0, 0, 0, 0]);
ExtendedPublicKey {
public_key: public_key.clone(),
chain_code: chain_code.to_vec(),
depth: *depth,
index: *index,
parent_fingerprint: fingerprint.to_vec(),
}
}
pub fn to_string_impl(&self) -> Result<String, BSVErrors> {
let mut cursor: Cursor<Vec<u8>> = Cursor::new(Vec::new());
cursor
.write_u32::<BigEndian>(XPUB_VERSION_BYTE)
.and_then(|_| cursor.write_u8(self.depth))
.and_then(|_| cursor.write(&self.parent_fingerprint))
.and_then(|_| cursor.write_u32::<BigEndian>(self.index))
.and_then(|_| cursor.write(&self.chain_code))?;
let pub_key_bytes = self.public_key.to_bytes_impl()?;
cursor.write_all(&pub_key_bytes)?;
let mut serialised = Vec::new();
cursor.set_position(0);
cursor.read_to_end(&mut serialised)?;
let checksum = &Hash::sha_256d(&serialised).to_bytes()[0..4];
cursor.write_all(checksum)?;
serialised = Vec::new();
cursor.set_position(0);
cursor.read_to_end(&mut serialised)?;
Ok(bs58::encode(serialised).into_string())
}
pub fn from_string_impl(xpub_string: &str) -> Result<Self, BSVErrors> {
let mut cursor = Cursor::new(bs58::decode(xpub_string).into_vec()?);
cursor.set_position(4);
let depth = cursor.read_u8()?;
let mut parent_fingerprint = vec![0; 4];
cursor.read_exact(&mut parent_fingerprint)?;
let index = cursor.read_u32::<BigEndian>()?;
let mut chain_code = vec![0; 32];
cursor.read_exact(&mut chain_code)?;
let mut pub_key_bytes = vec![0; 33];
cursor.read_exact(&mut pub_key_bytes)?;
let public_key = PublicKey::from_bytes_impl(&pub_key_bytes)?;
let mut checksum = vec![0; 4];
cursor.read_exact(&mut checksum)?;
Ok(ExtendedPublicKey {
public_key,
chain_code,
depth,
index,
parent_fingerprint,
})
}
pub fn from_random_impl() -> Result<Self, BSVErrors> {
let mut seed = vec![0; 64];
getrandom(&mut seed)?;
Self::from_seed_impl(&seed)
}
pub fn from_seed_impl(seed: &[u8]) -> Result<Self, BSVErrors> {
let xpriv = ExtendedPrivateKey::from_seed_impl(seed)?;
Ok(Self::from_xpriv(&xpriv))
}
pub fn derive_impl(&self, index: u32) -> Result<ExtendedPublicKey, BSVErrors> {
if index >= HARDENED_KEY_OFFSET {
return Err(BSVErrors::DerivationError(format!(
"Cannot generate a hardened xpub, choose an index between 0 and {}.",
HARDENED_KEY_OFFSET - 1
)));
}
let mut key_data: Vec<u8> = vec![];
let pub_key_bytes = &self.public_key.clone().to_bytes_impl()?;
key_data.extend_from_slice(pub_key_bytes);
key_data.extend_from_slice(&index.to_be_bytes());
let pub_key_bytes = &self.public_key.clone().to_bytes_impl()?;
let hash = Hash::hash_160(pub_key_bytes);
let fingerprint = &hash.to_bytes()[0..4];
let hmac = Hash::sha_512_hmac(&key_data, &self.chain_code.clone());
let seed_bytes = hmac.to_bytes();
let mut seed_chunks = seed_bytes.chunks_exact(32_usize);
let child_public_key_bytes = match seed_chunks.next() {
Some(b) => b,
None => return Err(BSVErrors::InvalidSeedHmacError("Could not get 32 bytes for private key".into())),
};
let child_chain_code = match seed_chunks.next() {
Some(b) => b,
None => return Err(BSVErrors::InvalidSeedHmacError("Could not get 32 bytes for chain code".into())),
};
let parent_pub_key_bytes = self.public_key.to_bytes_impl()?;
let parent_pub_key_point = K256PublicKey::from_sec1_bytes(&parent_pub_key_bytes)?.to_projective();
let il_scalar = Scalar::from_bytes_reduced(&SecretKey::from_bytes(child_public_key_bytes)?.to_secret_scalar().to_bytes());
let child_pub_key_point = parent_pub_key_point + (ProjectivePoint::generator() * il_scalar);
let internal_pub_key: K256PublicKey = K256PublicKey::from_affine(child_pub_key_point.to_affine())?;
let child_pub_key = PublicKey::from_bytes_impl(internal_pub_key.to_encoded_point(true).as_bytes())?;
Ok(ExtendedPublicKey {
chain_code: child_chain_code.to_vec(),
public_key: child_pub_key,
depth: self.depth + 1,
index,
parent_fingerprint: fingerprint.to_vec(),
})
}
pub fn derive_from_path_impl(&self, path: &str) -> Result<ExtendedPublicKey, BSVErrors> {
if !path.to_ascii_lowercase().starts_with('m') {
return Err(BSVErrors::DerivationError("Path did not begin with 'm'".into()));
}
let children = path[1..].split('/').filter(|x| -> bool { !x.is_empty() });
let child_indices = children.map(Self::parse_str_to_idx).collect::<Result<Vec<u32>, BSVErrors>>()?;
if child_indices.is_empty() {
return Err(BSVErrors::DerivationError(format!(
"No path was provided. Please provide a string of the form m/0. Given path: {}",
path
)));
}
let mut xpriv = self.derive_impl(child_indices[0])?;
for index in child_indices[1..].iter() {
xpriv = xpriv.derive_impl(*index)?;
}
Ok(xpriv)
}
fn parse_str_to_idx(x: &str) -> Result<u32, BSVErrors> {
let is_hardened = x.ends_with('\'') || x.to_lowercase().ends_with('h');
let index_str = x.trim_end_matches('\'').trim_end_matches('h').trim_end_matches('H');
let index = match index_str.parse::<u32>() {
Ok(v) => v,
Err(e) => return Err(BSVErrors::DerivationError(e.to_string())),
};
if index >= HARDENED_KEY_OFFSET {
return Err(BSVErrors::DerivationError(format!("Indicies may not be greater than {}", HARDENED_KEY_OFFSET - 1)));
}
Ok(match is_hardened {
true => index + HARDENED_KEY_OFFSET,
false => index,
})
}
}
#[wasm_bindgen]
impl ExtendedPublicKey {
#[wasm_bindgen(js_name = getPublicKey)]
pub fn get_public_key(&self) -> PublicKey {
self.public_key.clone()
}
#[wasm_bindgen(js_name = fromXPriv)]
pub fn from_xpriv(xpriv: &ExtendedPrivateKey) -> Self {
Self {
public_key: xpriv.get_public_key(),
chain_code: xpriv.get_chain_code(),
depth: xpriv.get_depth(),
index: xpriv.get_index(),
parent_fingerprint: xpriv.get_parent_fingerprint(),
}
}
#[wasm_bindgen(js_name = getChainCode)]
pub fn get_chain_code(&self) -> Vec<u8> {
self.chain_code.clone()
}
#[wasm_bindgen(js_name = getDepth)]
pub fn get_depth(&self) -> u8 {
self.depth
}
#[wasm_bindgen(js_name = getParentFingerprint)]
pub fn get_parent_fingerprint(&self) -> Vec<u8> {
self.parent_fingerprint.clone()
}
#[wasm_bindgen(js_name = getIndex)]
pub fn get_index(&self) -> u32 {
self.index
}
}
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
impl ExtendedPublicKey {
#[wasm_bindgen(js_name = deriveChild)]
pub fn derive(&self, index: u32) -> Result<ExtendedPublicKey, JsValue> {
match Self::derive_impl(&self, index) {
Ok(v) => Ok(v),
Err(e) => throw_str(&e.to_string()),
}
}
#[wasm_bindgen(js_name = derive)]
pub fn derive_from_path(&self, path: &str) -> Result<ExtendedPublicKey, JsValue> {
match Self::derive_from_path_impl(&self, path) {
Ok(v) => Ok(v),
Err(e) => throw_str(&e.to_string()),
}
}
#[wasm_bindgen(js_name = fromSeed)]
pub fn from_seed(seed: &[u8]) -> Result<ExtendedPublicKey, JsValue> {
match Self::from_seed_impl(seed) {
Ok(v) => Ok(v),
Err(e) => throw_str(&e.to_string()),
}
}
#[wasm_bindgen(js_name = fromRandom)]
pub fn from_random() -> Result<ExtendedPublicKey, JsValue> {
match Self::from_random_impl() {
Ok(v) => Ok(v),
Err(e) => throw_str(&e.to_string()),
}
}
#[wasm_bindgen(js_name = fromString)]
pub fn from_string(xpub_string: &str) -> Result<ExtendedPublicKey, JsValue> {
match Self::from_string_impl(xpub_string) {
Ok(v) => Ok(v),
Err(e) => throw_str(&e.to_string()),
}
}
#[wasm_bindgen(js_name = toString)]
pub fn to_string(&self) -> Result<String, JsValue> {
match Self::to_string_impl(&self) {
Ok(v) => Ok(v),
Err(e) => throw_str(&e.to_string()),
}
}
}
#[cfg(not(target_arch = "wasm32"))]
impl ExtendedPublicKey {
pub fn derive(&self, index: u32) -> Result<ExtendedPublicKey, BSVErrors> {
Self::derive_impl(self, index)
}
pub fn derive_from_path(&self, path: &str) -> Result<ExtendedPublicKey, BSVErrors> {
Self::derive_from_path_impl(self, path)
}
pub fn from_seed(seed: &[u8]) -> Result<ExtendedPublicKey, BSVErrors> {
Self::from_seed_impl(seed)
}
pub fn from_random() -> Result<ExtendedPublicKey, BSVErrors> {
Self::from_random_impl()
}
pub fn from_string(xpub_string: &str) -> Result<ExtendedPublicKey, BSVErrors> {
Self::from_string_impl(xpub_string)
}
pub fn to_string(&self) -> Result<String, BSVErrors> {
Self::to_string_impl(self)
}
}