stack_epic_keychain/
extkey_bip32.rs

1// Copyright 2019 The Grin Developers
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Rust Bitcoin Library
16// Written in 2014 by
17//     Andrew Poelstra <apoelstra@wpsoftware.net>
18// To the extent possible under law, the author(s) have dedicated all
19// copyright and related and neighboring rights to this software to
20// the public domain worldwide. This software is distributed without
21// any warranty.
22//
23// You should have received a copy of the CC0 Public Domain Dedication
24// along with this software.
25// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
26//
27
28//! Implementation of BIP32 hierarchical deterministic wallets, as defined
29//! at https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
30//! Modified from above to integrate into epic and allow for different
31//! hashing algorithms if desired
32
33#[cfg(feature = "serde")]
34use serde;
35use std::default::Default;
36use std::io::Cursor;
37use std::str::FromStr;
38use std::{error, fmt};
39
40use crate::mnemonic;
41use crate::util::secp::key::{PublicKey, SecretKey};
42use crate::util::secp::{self, ContextFlag, Secp256k1};
43use byteorder::{BigEndian, ByteOrder, ReadBytesExt};
44
45use digest::generic_array::GenericArray;
46use digest::Digest;
47use hmac::{Hmac, Mac, NewMac};
48use ripemd160::Ripemd160;
49use sha2::{Sha256, Sha512};
50
51use crate::base58;
52
53// Create alias for HMAC-SHA512
54type HmacSha512 = Hmac<Sha512>;
55
56/// A chain code
57pub struct ChainCode([u8; 32]);
58impl_array_newtype!(ChainCode, u8, 32);
59impl_array_newtype_show!(ChainCode);
60impl_array_newtype_encodable!(ChainCode, u8, 32);
61
62/// A fingerprint
63pub struct Fingerprint([u8; 4]);
64impl_array_newtype!(Fingerprint, u8, 4);
65impl_array_newtype_show!(Fingerprint);
66impl_array_newtype_encodable!(Fingerprint, u8, 4);
67
68impl Default for Fingerprint {
69	fn default() -> Fingerprint {
70		Fingerprint([0, 0, 0, 0])
71	}
72}
73
74/// Allow different implementations of hash functions used in BIP32 Derivations
75/// Epic uses blake2 everywhere but the spec calls for SHA512/Ripemd160, so allow
76/// this in future and allow us to unit test against published BIP32 test vectors
77/// The function names refer to the place of the hash in the reference BIP32 spec,
78/// not what the actual implementation is
79
80pub trait BIP32Hasher {
81	fn network_priv(&self) -> [u8; 4];
82	fn network_pub(&self) -> [u8; 4];
83	fn master_seed() -> [u8; 12];
84	fn init_sha512(&mut self, seed: &[u8]);
85	fn append_sha512(&mut self, value: &[u8]);
86	fn result_sha512(&mut self) -> [u8; 64];
87	fn sha_256(&self, input: &[u8]) -> [u8; 32];
88	fn ripemd_160(&self, input: &[u8]) -> [u8; 20];
89}
90
91/// Implementation of the above that uses the standard BIP32 Hash algorithms
92#[derive(Clone, Debug)]
93pub struct BIP32GrinHasher {
94	is_floo: bool,
95	hmac_sha512: Hmac<Sha512>,
96}
97
98impl BIP32GrinHasher {
99	/// New empty hasher
100	pub fn new(is_floo: bool) -> BIP32GrinHasher {
101		BIP32GrinHasher {
102			is_floo: is_floo,
103			hmac_sha512: HmacSha512::new(GenericArray::from_slice(&[0u8; 128])),
104		}
105	}
106}
107
108impl BIP32Hasher for BIP32GrinHasher {
109	fn network_priv(&self) -> [u8; 4] {
110		match self.is_floo {
111			true => [0x03, 0x27, 0x3A, 0x10],  // fprv
112			false => [0x03, 0x3C, 0x04, 0xA4], // gprv
113		}
114	}
115	fn network_pub(&self) -> [u8; 4] {
116		match self.is_floo {
117			true => [0x03, 0x27, 0x3E, 0x4B],  // fpub
118			false => [0x03, 0x3C, 0x08, 0xDF], // gpub
119		}
120	}
121	fn master_seed() -> [u8; 12] {
122		b"IamVoldemort".to_owned()
123	}
124	fn init_sha512(&mut self, seed: &[u8]) {
125		self.hmac_sha512 = HmacSha512::new_from_slice(seed).expect("HMAC can take key of any size");
126	}
127	fn append_sha512(&mut self, value: &[u8]) {
128		self.hmac_sha512.update(value);
129	}
130	fn result_sha512(&mut self) -> [u8; 64] {
131		let mut result = [0; 64];
132		result.copy_from_slice(&self.hmac_sha512.to_owned().finalize().into_bytes());
133		result
134	}
135	fn sha_256(&self, input: &[u8]) -> [u8; 32] {
136		let mut sha2_res = [0; 32];
137		let mut sha2 = Sha256::new();
138		sha2.update(input);
139		sha2_res.copy_from_slice(sha2.finalize().as_slice());
140		sha2_res
141	}
142	fn ripemd_160(&self, input: &[u8]) -> [u8; 20] {
143		let mut ripemd_res = [0; 20];
144		let mut ripemd = Ripemd160::new();
145		ripemd.update(input);
146		ripemd_res.copy_from_slice(ripemd.finalize().as_slice());
147		ripemd_res
148	}
149}
150
151/// Extended private key
152#[derive(Clone, PartialEq, Eq, Debug)]
153pub struct ExtendedPrivKey {
154	/// The network this key is to be used on
155	pub network: [u8; 4],
156	/// How many derivations this key is from the master (which is 0)
157	pub depth: u8,
158	/// Fingerprint of the parent key (0 for master)
159	pub parent_fingerprint: Fingerprint,
160	/// Child number of the key used to derive from parent (0 for master)
161	pub child_number: ChildNumber,
162	/// Secret key
163	pub secret_key: SecretKey,
164	/// Chain code
165	pub chain_code: ChainCode,
166}
167
168/// Extended public key
169#[derive(Copy, Clone, PartialEq, Eq, Debug)]
170pub struct ExtendedPubKey {
171	/// The network this key is to be used on
172	pub network: [u8; 4],
173	/// How many derivations this key is from the master (which is 0)
174	pub depth: u8,
175	/// Fingerprint of the parent key
176	pub parent_fingerprint: Fingerprint,
177	/// Child number of the key used to derive from parent (0 for master)
178	pub child_number: ChildNumber,
179	/// Public key
180	pub public_key: PublicKey,
181	/// Chain code
182	pub chain_code: ChainCode,
183}
184
185/// A child number for a derived key
186#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
187pub enum ChildNumber {
188	/// Non-hardened key
189	Normal {
190		/// Key index, within [0, 2^31 - 1]
191		index: u32,
192	},
193	/// Hardened key
194	Hardened {
195		/// Key index, within [0, 2^31 - 1]
196		index: u32,
197	},
198}
199
200impl ChildNumber {
201	/// Create a [`Normal`] from an index, panics if the index is not within
202	/// [0, 2^31 - 1].
203	///
204	/// [`Normal`]: #variant.Normal
205	pub fn from_normal_idx(index: u32) -> Self {
206		assert_eq!(
207			index & (1 << 31),
208			0,
209			"ChildNumber indices have to be within [0, 2^31 - 1], is: {}",
210			index
211		);
212		ChildNumber::Normal { index: index }
213	}
214
215	/// Create a [`Hardened`] from an index, panics if the index is not within
216	/// [0, 2^31 - 1].
217	///
218	/// [`Hardened`]: #variant.Hardened
219	pub fn from_hardened_idx(index: u32) -> Self {
220		assert_eq!(
221			index & (1 << 31),
222			0,
223			"ChildNumber indices have to be within [0, 2^31 - 1], is: {}",
224			index
225		);
226		ChildNumber::Hardened { index: index }
227	}
228
229	/// Returns `true` if the child number is a [`Normal`] value.
230	///
231	/// [`Normal`]: #variant.Normal
232	pub fn is_normal(&self) -> bool {
233		!self.is_hardened()
234	}
235
236	/// Returns `true` if the child number is a [`Hardened`] value.
237	///
238	/// [`Hardened`]: #variant.Hardened
239	pub fn is_hardened(&self) -> bool {
240		match *self {
241			ChildNumber::Hardened { .. } => true,
242			ChildNumber::Normal { .. } => false,
243		}
244	}
245}
246
247impl From<u32> for ChildNumber {
248	fn from(number: u32) -> Self {
249		if number & (1 << 31) != 0 {
250			ChildNumber::Hardened {
251				index: number ^ (1 << 31),
252			}
253		} else {
254			ChildNumber::Normal { index: number }
255		}
256	}
257}
258
259impl From<ChildNumber> for u32 {
260	fn from(cnum: ChildNumber) -> Self {
261		match cnum {
262			ChildNumber::Normal { index } => index,
263			ChildNumber::Hardened { index } => index | (1 << 31),
264		}
265	}
266}
267
268impl fmt::Display for ChildNumber {
269	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270		match *self {
271			ChildNumber::Hardened { index } => write!(f, "{}'", index),
272			ChildNumber::Normal { index } => write!(f, "{}", index),
273		}
274	}
275}
276
277#[cfg(feature = "serde")]
278impl<'de> serde::Deserialize<'de> for ChildNumber {
279	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
280	where
281		D: serde::Deserializer<'de>,
282	{
283		u32::deserialize(deserializer).map(ChildNumber::from)
284	}
285}
286
287#[cfg(feature = "serde")]
288impl serde::Serialize for ChildNumber {
289	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
290	where
291		S: serde::Serializer,
292	{
293		u32::from(*self).serialize(serializer)
294	}
295}
296
297/// A BIP32 error
298#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
299pub enum Error {
300	/// A pk->pk derivation was attempted on a hardened key
301	CannotDeriveFromHardenedKey,
302	/// A secp256k1 error occured
303	Ecdsa(secp::Error),
304	/// A child number was provided that was out of range
305	InvalidChildNumber(ChildNumber),
306	/// Error creating a master seed --- for application use
307	RngError(String),
308	/// Error converting mnemonic to seed
309	MnemonicError(mnemonic::Error),
310}
311
312impl fmt::Display for Error {
313	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
314		match *self {
315			Error::CannotDeriveFromHardenedKey => {
316				f.write_str("cannot derive hardened key from public key")
317			}
318			Error::Ecdsa(ref e) => fmt::Display::fmt(e, f),
319			Error::InvalidChildNumber(ref n) => write!(f, "child number {} is invalid", n),
320			Error::RngError(ref s) => write!(f, "rng error {}", s),
321			Error::MnemonicError(ref e) => fmt::Display::fmt(e, f),
322		}
323	}
324}
325
326impl error::Error for Error {
327	fn cause(&self) -> Option<&dyn error::Error> {
328		if let Error::Ecdsa(ref e) = *self {
329			Some(e)
330		} else {
331			None
332		}
333	}
334}
335
336impl From<secp::Error> for Error {
337	fn from(e: secp::Error) -> Error {
338		Error::Ecdsa(e)
339	}
340}
341
342impl ExtendedPrivKey {
343	/// Construct a new master key from a seed value
344	pub fn new_master<H>(
345		secp: &Secp256k1,
346		hasher: &mut H,
347		seed: &[u8],
348	) -> Result<ExtendedPrivKey, Error>
349	where
350		H: BIP32Hasher,
351	{
352		hasher.init_sha512(&H::master_seed());
353		hasher.append_sha512(seed);
354		let result = hasher.result_sha512();
355
356		Ok(ExtendedPrivKey {
357			network: hasher.network_priv(),
358			depth: 0,
359			parent_fingerprint: Default::default(),
360			child_number: ChildNumber::from_normal_idx(0),
361			secret_key: SecretKey::from_slice(secp, &result[..32]).map_err(Error::Ecdsa)?,
362			chain_code: ChainCode::from(&result[32..]),
363		})
364	}
365
366	/// Construct a new master key from a mnemonic and a passphrase
367	pub fn from_mnemonic(
368		secp: &Secp256k1,
369		mnemonic: &str,
370		passphrase: &str,
371		is_floo: bool,
372	) -> Result<ExtendedPrivKey, Error> {
373		let seed = match mnemonic::to_seed(mnemonic, passphrase) {
374			Ok(s) => s,
375			Err(e) => return Err(Error::MnemonicError(e)),
376		};
377		let mut hasher = BIP32GrinHasher::new(is_floo);
378		let key = ExtendedPrivKey::new_master(secp, &mut hasher, &seed)?;
379		Ok(key)
380	}
381
382	/// Attempts to derive an extended private key from a path.
383	pub fn derive_priv<H>(
384		&self,
385		secp: &Secp256k1,
386		hasher: &mut H,
387		cnums: &[ChildNumber],
388	) -> Result<ExtendedPrivKey, Error>
389	where
390		H: BIP32Hasher,
391	{
392		let mut sk: ExtendedPrivKey = self.clone();
393		for cnum in cnums {
394			sk = sk.ckd_priv(secp, hasher, *cnum)?;
395		}
396		Ok(sk)
397	}
398
399	/// Private->Private child key derivation
400	pub fn ckd_priv<H>(
401		&self,
402		secp: &Secp256k1,
403		hasher: &mut H,
404		i: ChildNumber,
405	) -> Result<ExtendedPrivKey, Error>
406	where
407		H: BIP32Hasher,
408	{
409		hasher.init_sha512(&self.chain_code[..]);
410		let mut be_n = [0; 4];
411		match i {
412			ChildNumber::Normal { .. } => {
413				// Non-hardened key: compute public data and use that
414				hasher.append_sha512(
415					&PublicKey::from_secret_key(secp, &self.secret_key)?.serialize_vec(secp, true)
416						[..],
417				);
418			}
419			ChildNumber::Hardened { .. } => {
420				// Hardened key: use only secret data to prevent public derivation
421				hasher.append_sha512(&[0u8]);
422				hasher.append_sha512(&self.secret_key[..]);
423			}
424		}
425		BigEndian::write_u32(&mut be_n, u32::from(i));
426
427		hasher.append_sha512(&be_n);
428		let result = hasher.result_sha512();
429		let mut sk = SecretKey::from_slice(secp, &result[..32]).map_err(Error::Ecdsa)?;
430		sk.add_assign(secp, &self.secret_key)
431			.map_err(Error::Ecdsa)?;
432
433		Ok(ExtendedPrivKey {
434			network: self.network,
435			depth: self.depth + 1,
436			parent_fingerprint: self.fingerprint(hasher),
437			child_number: i,
438			secret_key: sk,
439			chain_code: ChainCode::from(&result[32..]),
440		})
441	}
442
443	/// Returns the HASH160 of the chaincode
444	pub fn identifier<H>(&self, hasher: &mut H) -> [u8; 20]
445	where
446		H: BIP32Hasher,
447	{
448		let secp = Secp256k1::with_caps(ContextFlag::SignOnly);
449		// Compute extended public key
450		let pk: ExtendedPubKey = ExtendedPubKey::from_private::<H>(&secp, self, hasher);
451		// Do SHA256 of just the ECDSA pubkey
452		let sha2_res = hasher.sha_256(&pk.public_key.serialize_vec(&secp, true)[..]);
453		// do RIPEMD160
454		let ripemd_res = hasher.ripemd_160(&sha2_res);
455		// Return
456		ripemd_res
457	}
458
459	/// Returns the first four bytes of the identifier
460	pub fn fingerprint<H>(&self, hasher: &mut H) -> Fingerprint
461	where
462		H: BIP32Hasher,
463	{
464		Fingerprint::from(&self.identifier(hasher)[0..4])
465	}
466}
467
468impl ExtendedPubKey {
469	/// Derives a public key from a private key
470	pub fn from_private<H>(secp: &Secp256k1, sk: &ExtendedPrivKey, hasher: &mut H) -> ExtendedPubKey
471	where
472		H: BIP32Hasher,
473	{
474		ExtendedPubKey {
475			network: hasher.network_pub(),
476			depth: sk.depth,
477			parent_fingerprint: sk.parent_fingerprint,
478			child_number: sk.child_number,
479			public_key: PublicKey::from_secret_key(secp, &sk.secret_key).unwrap(),
480			chain_code: sk.chain_code,
481		}
482	}
483
484	/// Attempts to derive an extended public key from a path.
485	pub fn derive_pub<H>(
486		&self,
487		secp: &Secp256k1,
488		hasher: &mut H,
489		cnums: &[ChildNumber],
490	) -> Result<ExtendedPubKey, Error>
491	where
492		H: BIP32Hasher,
493	{
494		let mut pk: ExtendedPubKey = *self;
495		for cnum in cnums {
496			pk = pk.ckd_pub(secp, hasher, *cnum)?
497		}
498		Ok(pk)
499	}
500
501	/// Compute the scalar tweak added to this key to get a child key
502	pub fn ckd_pub_tweak<H>(
503		&self,
504		secp: &Secp256k1,
505		hasher: &mut H,
506		i: ChildNumber,
507	) -> Result<(SecretKey, ChainCode), Error>
508	where
509		H: BIP32Hasher,
510	{
511		match i {
512			ChildNumber::Hardened { .. } => Err(Error::CannotDeriveFromHardenedKey),
513			ChildNumber::Normal { index: n } => {
514				hasher.init_sha512(&self.chain_code[..]);
515				hasher.append_sha512(&self.public_key.serialize_vec(secp, true)[..]);
516				let mut be_n = [0; 4];
517				BigEndian::write_u32(&mut be_n, n);
518				hasher.append_sha512(&be_n);
519
520				let result = hasher.result_sha512();
521
522				let secret_key = SecretKey::from_slice(secp, &result[..32])?;
523				let chain_code = ChainCode::from(&result[32..]);
524				Ok((secret_key, chain_code))
525			}
526		}
527	}
528
529	/// Public->Public child key derivation
530	pub fn ckd_pub<H>(
531		&self,
532		secp: &Secp256k1,
533		hasher: &mut H,
534		i: ChildNumber,
535	) -> Result<ExtendedPubKey, Error>
536	where
537		H: BIP32Hasher,
538	{
539		let (sk, chain_code) = self.ckd_pub_tweak(secp, hasher, i)?;
540		let mut pk = self.public_key.clone();
541		pk.add_exp_assign(secp, &sk).map_err(Error::Ecdsa)?;
542
543		Ok(ExtendedPubKey {
544			network: self.network,
545			depth: self.depth + 1,
546			parent_fingerprint: self.fingerprint(secp, hasher),
547			child_number: i,
548			public_key: pk,
549			chain_code: chain_code,
550		})
551	}
552
553	/// Returns the HASH160 of the chaincode
554	pub fn identifier<H>(&self, secp: &Secp256k1, hasher: &mut H) -> [u8; 20]
555	where
556		H: BIP32Hasher,
557	{
558		// Do SHA256 of just the ECDSA pubkey
559		let sha2_res = hasher.sha_256(&self.public_key.serialize_vec(secp, true)[..]);
560		// do RIPEMD160
561		let ripemd_res = hasher.ripemd_160(&sha2_res);
562		// Return
563		ripemd_res
564	}
565
566	/// Returns the first four bytes of the identifier
567	pub fn fingerprint<H>(&self, secp: &Secp256k1, hasher: &mut H) -> Fingerprint
568	where
569		H: BIP32Hasher,
570	{
571		Fingerprint::from(&self.identifier(secp, hasher)[0..4])
572	}
573}
574
575impl fmt::Display for ExtendedPrivKey {
576	fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
577		let mut ret = [0; 78];
578		ret[0..4].copy_from_slice(&self.network[0..4]);
579		ret[4] = self.depth as u8;
580		ret[5..9].copy_from_slice(&self.parent_fingerprint[..]);
581
582		BigEndian::write_u32(&mut ret[9..13], u32::from(self.child_number));
583
584		ret[13..45].copy_from_slice(&self.chain_code[..]);
585		ret[45] = 0;
586		ret[46..78].copy_from_slice(&self.secret_key[..]);
587		fmt.write_str(&base58::check_encode_slice(&ret[..]))
588	}
589}
590
591impl FromStr for ExtendedPrivKey {
592	type Err = base58::Error;
593
594	fn from_str(inp: &str) -> Result<ExtendedPrivKey, base58::Error> {
595		let s = Secp256k1::without_caps();
596		let data = base58::from_check(inp)?;
597
598		if data.len() != 78 {
599			return Err(base58::Error::InvalidLength(data.len()));
600		}
601
602		let cn_int: u32 = Cursor::new(&data[9..13]).read_u32::<BigEndian>().unwrap();
603		let child_number: ChildNumber = ChildNumber::from(cn_int);
604
605		let mut network = [0; 4];
606		network.copy_from_slice(&data[0..4]);
607
608		Ok(ExtendedPrivKey {
609			network: network,
610			depth: data[4],
611			parent_fingerprint: Fingerprint::from(&data[5..9]),
612			child_number: child_number,
613			chain_code: ChainCode::from(&data[13..45]),
614			secret_key: SecretKey::from_slice(&s, &data[46..78])
615				.map_err(|e| base58::Error::Other(e.to_string()))?,
616		})
617	}
618}
619
620impl fmt::Display for ExtendedPubKey {
621	fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
622		let secp = Secp256k1::without_caps();
623		let mut ret = [0; 78];
624		ret[0..4].copy_from_slice(&self.network[0..4]);
625		ret[4] = self.depth as u8;
626		ret[5..9].copy_from_slice(&self.parent_fingerprint[..]);
627
628		BigEndian::write_u32(&mut ret[9..13], u32::from(self.child_number));
629
630		ret[13..45].copy_from_slice(&self.chain_code[..]);
631		ret[45..78].copy_from_slice(&self.public_key.serialize_vec(&secp, true)[..]);
632		fmt.write_str(&base58::check_encode_slice(&ret[..]))
633	}
634}
635
636impl FromStr for ExtendedPubKey {
637	type Err = base58::Error;
638
639	fn from_str(inp: &str) -> Result<ExtendedPubKey, base58::Error> {
640		let s = Secp256k1::without_caps();
641		let data = base58::from_check(inp)?;
642
643		if data.len() != 78 {
644			return Err(base58::Error::InvalidLength(data.len()));
645		}
646
647		let cn_int: u32 = Cursor::new(&data[9..13]).read_u32::<BigEndian>().unwrap();
648		let child_number: ChildNumber = ChildNumber::from(cn_int);
649
650		let mut network = [0; 4];
651		network.copy_from_slice(&data[0..4]);
652
653		Ok(ExtendedPubKey {
654			network: network,
655			depth: data[4],
656			parent_fingerprint: Fingerprint::from(&data[5..9]),
657			child_number: child_number,
658			chain_code: ChainCode::from(&data[13..45]),
659			public_key: PublicKey::from_slice(&s, &data[45..78])
660				.map_err(|e| base58::Error::Other(e.to_string()))?,
661		})
662	}
663}
664
665#[cfg(test)]
666mod tests {
667
668	use std::str::FromStr;
669	use std::string::ToString;
670
671	use crate::util::from_hex;
672	use crate::util::secp::Secp256k1;
673
674	use super::*;
675
676	use digest::generic_array::GenericArray;
677	use digest::Digest;
678	use hmac::{Hmac, Mac};
679	use ripemd160::Ripemd160;
680	use sha2::{Sha256, Sha512};
681
682	/// Implementation of the above that uses the standard BIP32 Hash algorithms
683	pub struct BIP32ReferenceHasher {
684		hmac_sha512: Hmac<Sha512>,
685	}
686
687	impl BIP32ReferenceHasher {
688		/// New empty hasher
689		pub fn new() -> BIP32ReferenceHasher {
690			BIP32ReferenceHasher {
691				hmac_sha512: HmacSha512::new(GenericArray::from_slice(&[0u8; 128])),
692			}
693		}
694	}
695
696	impl BIP32Hasher for BIP32ReferenceHasher {
697		fn network_priv(&self) -> [u8; 4] {
698			// bitcoin network (xprv) (for test vectors)
699			[0x04, 0x88, 0xAD, 0xE4]
700		}
701		fn network_pub(&self) -> [u8; 4] {
702			// bitcoin network (xpub) (for test vectors)
703			[0x04, 0x88, 0xB2, 0x1E]
704		}
705		fn master_seed() -> [u8; 12] {
706			b"Bitcoin seed".to_owned()
707		}
708		fn init_sha512(&mut self, seed: &[u8]) {
709			self.hmac_sha512 =
710				HmacSha512::new_from_slice(seed).expect("HMAC can take key of any size");
711		}
712		fn append_sha512(&mut self, value: &[u8]) {
713			self.hmac_sha512.update(value);
714		}
715		fn result_sha512(&mut self) -> [u8; 64] {
716			let mut result = [0; 64];
717			result.copy_from_slice(&self.hmac_sha512.to_owned().finalize().into_bytes());
718			result
719		}
720		fn sha_256(&self, input: &[u8]) -> [u8; 32] {
721			let mut sha2_res = [0; 32];
722			let mut sha2 = Sha256::new();
723			sha2.update(input);
724			sha2_res.copy_from_slice(sha2.finalize().as_slice());
725			sha2_res
726		}
727		fn ripemd_160(&self, input: &[u8]) -> [u8; 20] {
728			let mut ripemd_res = [0; 20];
729			let mut ripemd = Ripemd160::new();
730			ripemd.update(input);
731			ripemd_res.copy_from_slice(ripemd.finalize().as_slice());
732			ripemd_res
733		}
734	}
735
736	fn test_path(
737		secp: &Secp256k1,
738		seed: &[u8],
739		path: &[ChildNumber],
740		expected_sk: &str,
741		expected_pk: &str,
742	) {
743		let mut h = BIP32ReferenceHasher::new();
744		let mut sk = ExtendedPrivKey::new_master(secp, &mut h, seed).unwrap();
745		let mut pk = ExtendedPubKey::from_private::<BIP32ReferenceHasher>(secp, &sk, &mut h);
746
747		// Check derivation convenience method for ExtendedPrivKey
748		assert_eq!(
749			&sk.derive_priv(secp, &mut h, path).unwrap().to_string()[..],
750			expected_sk
751		);
752
753		// Check derivation convenience method for ExtendedPubKey, should error
754		// appropriately if any ChildNumber is hardened
755		if path.iter().any(|cnum| cnum.is_hardened()) {
756			assert_eq!(
757				pk.derive_pub(secp, &mut h, path),
758				Err(Error::CannotDeriveFromHardenedKey)
759			);
760		} else {
761			assert_eq!(
762				&pk.derive_pub(secp, &mut h, path).unwrap().to_string()[..],
763				expected_pk
764			);
765		}
766
767		// Derive keys, checking hardened and non-hardened derivation one-by-one
768		for &num in path.iter() {
769			sk = sk.ckd_priv(secp, &mut h, num).unwrap();
770			match num {
771				ChildNumber::Normal { .. } => {
772					let pk2 = pk.ckd_pub(secp, &mut h, num).unwrap();
773					pk = ExtendedPubKey::from_private::<BIP32ReferenceHasher>(secp, &sk, &mut h);
774					assert_eq!(pk, pk2);
775				}
776				ChildNumber::Hardened { .. } => {
777					assert_eq!(
778						pk.ckd_pub(secp, &mut h, num),
779						Err(Error::CannotDeriveFromHardenedKey)
780					);
781					pk = ExtendedPubKey::from_private::<BIP32ReferenceHasher>(secp, &sk, &mut h);
782				}
783			}
784		}
785
786		// Check result against expected base58
787		assert_eq!(&sk.to_string()[..], expected_sk);
788		assert_eq!(&pk.to_string()[..], expected_pk);
789		// Check decoded base58 against result
790		let decoded_sk = ExtendedPrivKey::from_str(expected_sk);
791		let decoded_pk = ExtendedPubKey::from_str(expected_pk);
792		assert_eq!(Ok(sk), decoded_sk);
793		assert_eq!(Ok(pk), decoded_pk);
794	}
795
796	#[test]
797	fn test_vector_1() {
798		let secp = Secp256k1::new();
799		let seed = from_hex("000102030405060708090a0b0c0d0e0f".to_owned()).unwrap();
800
801		// m
802		test_path(&secp, &seed, &[],
803                  "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi",
804                  "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8");
805
806		// m/0h
807		test_path(&secp, &seed, &[ChildNumber::from_hardened_idx(0)],
808                  "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7",
809                  "xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw");
810
811		// m/0h/1
812		test_path(&secp, &seed, &[ChildNumber::from_hardened_idx(0), ChildNumber::from_normal_idx(1)],
813                   "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs",
814                   "xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ");
815
816		// m/0h/1/2h
817		test_path(&secp, &seed, &[ChildNumber::from_hardened_idx(0), ChildNumber::from_normal_idx(1), ChildNumber::from_hardened_idx(2)],
818                  "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM",
819                  "xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5");
820
821		// m/0h/1/2h/2
822		test_path(&secp, &seed, &[ChildNumber::from_hardened_idx(0), ChildNumber::from_normal_idx(1), ChildNumber::from_hardened_idx(2), ChildNumber::from_normal_idx(2)],
823                  "xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334",
824                  "xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV");
825
826		// m/0h/1/2h/2/1000000000
827		test_path(&secp, &seed, &[ChildNumber::from_hardened_idx(0), ChildNumber::from_normal_idx(1), ChildNumber::from_hardened_idx(2), ChildNumber::from_normal_idx(2), ChildNumber::from_normal_idx(1000000000)],
828                  "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76",
829                  "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy");
830	}
831
832	#[test]
833	fn test_vector_2() {
834		let secp = Secp256k1::new();
835		let seed = from_hex("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542".to_owned()).unwrap();
836
837		// m
838		test_path(&secp, &seed, &[],
839                  "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U",
840                  "xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB");
841
842		// m/0
843		test_path(&secp, &seed, &[ChildNumber::from_normal_idx(0)],
844                  "xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt",
845                  "xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH");
846
847		// m/0/2147483647h
848		test_path(&secp, &seed, &[ChildNumber::from_normal_idx(0), ChildNumber::from_hardened_idx(2147483647)],
849                  "xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9",
850                  "xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a");
851
852		// m/0/2147483647h/1
853		test_path(&secp, &seed, &[ChildNumber::from_normal_idx(0), ChildNumber::from_hardened_idx(2147483647), ChildNumber::from_normal_idx(1)],
854                  "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef",
855                  "xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon");
856
857		// m/0/2147483647h/1/2147483646h
858		test_path(&secp, &seed, &[ChildNumber::from_normal_idx(0), ChildNumber::from_hardened_idx(2147483647), ChildNumber::from_normal_idx(1), ChildNumber::from_hardened_idx(2147483646)],
859                  "xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc",
860                  "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL");
861
862		// m/0/2147483647h/1/2147483646h/2
863		test_path(&secp, &seed, &[ChildNumber::from_normal_idx(0), ChildNumber::from_hardened_idx(2147483647), ChildNumber::from_normal_idx(1), ChildNumber::from_hardened_idx(2147483646), ChildNumber::from_normal_idx(2)],
864                  "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j",
865                  "xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt");
866	}
867
868	#[test]
869	fn test_vector_3() {
870		let secp = Secp256k1::new();
871		let seed = from_hex("4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be".to_owned()).unwrap();
872
873		// m
874		test_path(&secp, &seed, &[],
875                  "xprv9s21ZrQH143K25QhxbucbDDuQ4naNntJRi4KUfWT7xo4EKsHt2QJDu7KXp1A3u7Bi1j8ph3EGsZ9Xvz9dGuVrtHHs7pXeTzjuxBrCmmhgC6",
876                  "xpub661MyMwAqRbcEZVB4dScxMAdx6d4nFc9nvyvH3v4gJL378CSRZiYmhRoP7mBy6gSPSCYk6SzXPTf3ND1cZAceL7SfJ1Z3GC8vBgp2epUt13");
877
878		// m/0h
879		test_path(&secp, &seed, &[ChildNumber::from_hardened_idx(0)],
880                  "xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L",
881                  "xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y");
882	}
883
884	#[test]
885	#[cfg(all(feature = "serde", feature = "strason"))]
886	pub fn encode_decode_childnumber() {
887		serde_round_trip!(ChildNumber::from_normal_idx(0));
888		serde_round_trip!(ChildNumber::from_normal_idx(1));
889		serde_round_trip!(ChildNumber::from_normal_idx((1 << 31) - 1));
890		serde_round_trip!(ChildNumber::from_hardened_idx(0));
891		serde_round_trip!(ChildNumber::from_hardened_idx(1));
892		serde_round_trip!(ChildNumber::from_hardened_idx((1 << 31) - 1));
893	}
894}