Skip to main content

bitcoin/
bip32.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! BIP32 implementation.
4//!
5//! Implementation of BIP32 hierarchical deterministic wallets, as defined
6//! at <https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki>.
7//!
8
9use core::convert::Infallible;
10use core::ops::Index;
11use core::str::FromStr;
12use core::{fmt, slice};
13
14use hashes::{hash160, hash_newtype, sha512, Hash, HashEngine, Hmac, HmacEngine};
15use io::Write;
16use secp256k1::{Secp256k1, XOnlyPublicKey};
17
18use crate::crypto::key::{CompressedPublicKey, Keypair, PrivateKey};
19use crate::internal_macros::{impl_array_newtype, impl_bytes_newtype, write_err};
20use crate::network::NetworkKind;
21use crate::prelude::*;
22
23/// Version bytes for extended public keys on the Bitcoin network.
24const VERSION_BYTES_MAINNET_PUBLIC: [u8; 4] = [0x04, 0x88, 0xB2, 0x1E];
25/// Version bytes for extended private keys on the Bitcoin network.
26const VERSION_BYTES_MAINNET_PRIVATE: [u8; 4] = [0x04, 0x88, 0xAD, 0xE4];
27/// Version bytes for extended public keys on any of the testnet networks.
28const VERSION_BYTES_TESTNETS_PUBLIC: [u8; 4] = [0x04, 0x35, 0x87, 0xCF];
29/// Version bytes for extended private keys on any of the testnet networks.
30const VERSION_BYTES_TESTNETS_PRIVATE: [u8; 4] = [0x04, 0x35, 0x83, 0x94];
31
32/// The old name for xpub, extended public key.
33#[deprecated(since = "0.31.0", note = "use xpub instead")]
34pub type ExtendedPubKey = Xpub;
35
36/// The old name for xpub, extended public key (with a released typo in it).
37#[deprecated(since = "0.31.0", note = "use xpub instead")]
38pub type ExtendendPubKey = Xpub;
39
40/// The old name for xpriv, extended public key.
41#[deprecated(since = "0.31.0", note = "use xpriv instead")]
42pub type ExtendedPrivKey = Xpriv;
43
44/// The old name for xpriv, extended public key (with a released typo in it).
45#[deprecated(since = "0.31.0", note = "use xpriv instead")]
46pub type ExtendendPrivKey = Xpriv;
47
48/// A chain code
49#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
50pub struct ChainCode([u8; 32]);
51impl_array_newtype!(ChainCode, u8, 32);
52impl_bytes_newtype!(ChainCode, 32);
53
54impl ChainCode {
55    fn from_hmac(hmac: Hmac<sha512::Hash>) -> Self {
56        hmac[32..].try_into().expect("half of hmac is guaranteed to be 32 bytes")
57    }
58}
59
60/// A fingerprint
61#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
62pub struct Fingerprint([u8; 4]);
63impl_array_newtype!(Fingerprint, u8, 4);
64impl_bytes_newtype!(Fingerprint, 4);
65
66hash_newtype! {
67    /// Extended key identifier as defined in BIP-32.
68    pub struct XKeyIdentifier(hash160::Hash);
69}
70
71/// Extended private key
72#[derive(Copy, Clone, PartialEq, Eq)]
73#[cfg_attr(feature = "std", derive(Debug))]
74pub struct Xpriv {
75    /// The network this key is to be used on
76    pub network: NetworkKind,
77    /// How many derivations this key is from the master (which is 0)
78    pub depth: u8,
79    /// Fingerprint of the parent key (0 for master)
80    pub parent_fingerprint: Fingerprint,
81    /// Child number of the key used to derive from parent (0 for master)
82    pub child_number: ChildNumber,
83    /// Private key
84    pub private_key: secp256k1::SecretKey,
85    /// Chain code
86    pub chain_code: ChainCode,
87}
88#[cfg(feature = "serde")]
89crate::serde_utils::serde_string_impl!(Xpriv, "a BIP-32 extended private key");
90
91#[cfg(not(feature = "std"))]
92impl fmt::Debug for Xpriv {
93    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
94        f.debug_struct("Xpriv")
95            .field("network", &self.network)
96            .field("depth", &self.depth)
97            .field("parent_fingerprint", &self.parent_fingerprint)
98            .field("child_number", &self.child_number)
99            .field("chain_code", &self.chain_code)
100            .field("private_key", &"[SecretKey]")
101            .finish()
102    }
103}
104
105/// Extended public key
106#[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)]
107pub struct Xpub {
108    /// The network kind this key is to be used on
109    pub network: NetworkKind,
110    /// How many derivations this key is from the master (which is 0)
111    pub depth: u8,
112    /// Fingerprint of the parent key
113    pub parent_fingerprint: Fingerprint,
114    /// Child number of the key used to derive from parent (0 for master)
115    pub child_number: ChildNumber,
116    /// Public key
117    pub public_key: secp256k1::PublicKey,
118    /// Chain code
119    pub chain_code: ChainCode,
120}
121#[cfg(feature = "serde")]
122crate::serde_utils::serde_string_impl!(Xpub, "a BIP-32 extended public key");
123
124/// A child number for a derived key
125#[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)]
126pub enum ChildNumber {
127    /// Non-hardened key
128    Normal {
129        /// Key index, within [0, 2^31 - 1]
130        index: u32,
131    },
132    /// Hardened key
133    Hardened {
134        /// Key index, within [0, 2^31 - 1]
135        index: u32,
136    },
137}
138
139impl ChildNumber {
140    /// Create a [`Normal`] from an index, returns an error if the index is not within
141    /// [0, 2^31 - 1].
142    ///
143    /// [`Normal`]: #variant.Normal
144    pub fn from_normal_idx(index: u32) -> Result<Self, Error> {
145        if index & (1 << 31) == 0 {
146            Ok(ChildNumber::Normal { index })
147        } else {
148            Err(Error::InvalidChildNumber(index))
149        }
150    }
151
152    /// Create a [`Hardened`] from an index, returns an error if the index is not within
153    /// [0, 2^31 - 1].
154    ///
155    /// [`Hardened`]: #variant.Hardened
156    pub fn from_hardened_idx(index: u32) -> Result<Self, Error> {
157        if index & (1 << 31) == 0 {
158            Ok(ChildNumber::Hardened { index })
159        } else {
160            Err(Error::InvalidChildNumber(index))
161        }
162    }
163
164    /// Returns `true` if the child number is a [`Normal`] value.
165    ///
166    /// [`Normal`]: #variant.Normal
167    pub fn is_normal(&self) -> bool { !self.is_hardened() }
168
169    /// Returns `true` if the child number is a [`Hardened`] value.
170    ///
171    /// [`Hardened`]: #variant.Hardened
172    pub fn is_hardened(&self) -> bool {
173        match self {
174            ChildNumber::Hardened { .. } => true,
175            ChildNumber::Normal { .. } => false,
176        }
177    }
178
179    /// Returns the child number that is a single increment from this one.
180    pub fn increment(self) -> Result<ChildNumber, Error> {
181        // Bare addition in this function is okay, because we have an invariant that
182        // `index` is always within [0, 2^31 - 1]. FIXME this is not actually an
183        // invariant because the fields are public.
184        match self {
185            ChildNumber::Normal { index: idx } => ChildNumber::from_normal_idx(idx + 1),
186            ChildNumber::Hardened { index: idx } => ChildNumber::from_hardened_idx(idx + 1),
187        }
188    }
189}
190
191impl From<u32> for ChildNumber {
192    fn from(number: u32) -> Self {
193        if number & (1 << 31) != 0 {
194            ChildNumber::Hardened { index: number ^ (1 << 31) }
195        } else {
196            ChildNumber::Normal { index: number }
197        }
198    }
199}
200
201impl From<ChildNumber> for u32 {
202    fn from(cnum: ChildNumber) -> Self {
203        match cnum {
204            ChildNumber::Normal { index } => index,
205            ChildNumber::Hardened { index } => index | (1 << 31),
206        }
207    }
208}
209
210impl fmt::Display for ChildNumber {
211    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
212        match *self {
213            ChildNumber::Hardened { index } => {
214                fmt::Display::fmt(&index, f)?;
215                let alt = f.alternate();
216                f.write_str(if alt { "h" } else { "'" })
217            }
218            ChildNumber::Normal { index } => fmt::Display::fmt(&index, f),
219        }
220    }
221}
222
223impl FromStr for ChildNumber {
224    type Err = Error;
225
226    fn from_str(inp: &str) -> Result<ChildNumber, Error> {
227        let is_hardened = inp.chars().last().map_or(false, |l| l == '\'' || l == 'h');
228        Ok(if is_hardened {
229            ChildNumber::from_hardened_idx(
230                inp[0..inp.len() - 1].parse().map_err(|_| Error::InvalidChildNumberFormat)?,
231            )?
232        } else {
233            ChildNumber::from_normal_idx(inp.parse().map_err(|_| Error::InvalidChildNumberFormat)?)?
234        })
235    }
236}
237
238impl AsRef<[ChildNumber]> for ChildNumber {
239    fn as_ref(&self) -> &[ChildNumber] { slice::from_ref(self) }
240}
241
242#[cfg(feature = "serde")]
243impl<'de> serde::Deserialize<'de> for ChildNumber {
244    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
245    where
246        D: serde::Deserializer<'de>,
247    {
248        u32::deserialize(deserializer).map(ChildNumber::from)
249    }
250}
251
252#[cfg(feature = "serde")]
253impl serde::Serialize for ChildNumber {
254    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
255    where
256        S: serde::Serializer,
257    {
258        u32::from(*self).serialize(serializer)
259    }
260}
261
262/// Trait that allows possibly failable conversion from a type into a
263/// derivation path
264pub trait IntoDerivationPath {
265    /// Converts a given type into a [`DerivationPath`] with possible error
266    fn into_derivation_path(self) -> Result<DerivationPath, Error>;
267}
268
269/// A BIP-32 derivation path.
270#[derive(Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
271pub struct DerivationPath(Vec<ChildNumber>);
272
273#[cfg(feature = "serde")]
274crate::serde_utils::serde_string_impl!(DerivationPath, "a BIP-32 derivation path");
275
276impl<I> Index<I> for DerivationPath
277where
278    Vec<ChildNumber>: Index<I>,
279{
280    type Output = <Vec<ChildNumber> as Index<I>>::Output;
281
282    #[inline]
283    fn index(&self, index: I) -> &Self::Output { &self.0[index] }
284}
285
286impl Default for DerivationPath {
287    fn default() -> DerivationPath { DerivationPath::master() }
288}
289
290impl<T> IntoDerivationPath for T
291where
292    T: Into<DerivationPath>,
293{
294    fn into_derivation_path(self) -> Result<DerivationPath, Error> { Ok(self.into()) }
295}
296
297impl IntoDerivationPath for String {
298    fn into_derivation_path(self) -> Result<DerivationPath, Error> { self.parse() }
299}
300
301impl IntoDerivationPath for &str {
302    fn into_derivation_path(self) -> Result<DerivationPath, Error> { self.parse() }
303}
304
305impl From<Vec<ChildNumber>> for DerivationPath {
306    fn from(numbers: Vec<ChildNumber>) -> Self { DerivationPath(numbers) }
307}
308
309impl From<DerivationPath> for Vec<ChildNumber> {
310    fn from(path: DerivationPath) -> Self { path.0 }
311}
312
313impl<'a> From<&'a [ChildNumber]> for DerivationPath {
314    fn from(numbers: &'a [ChildNumber]) -> Self { DerivationPath(numbers.to_vec()) }
315}
316
317impl core::iter::FromIterator<ChildNumber> for DerivationPath {
318    fn from_iter<T>(iter: T) -> Self
319    where
320        T: IntoIterator<Item = ChildNumber>,
321    {
322        DerivationPath(Vec::from_iter(iter))
323    }
324}
325
326impl<'a> core::iter::IntoIterator for &'a DerivationPath {
327    type Item = &'a ChildNumber;
328    type IntoIter = slice::Iter<'a, ChildNumber>;
329    fn into_iter(self) -> Self::IntoIter { self.0.iter() }
330}
331
332impl AsRef<[ChildNumber]> for DerivationPath {
333    fn as_ref(&self) -> &[ChildNumber] { &self.0 }
334}
335
336impl FromStr for DerivationPath {
337    type Err = Error;
338
339    fn from_str(path: &str) -> Result<DerivationPath, Error> {
340        if path.is_empty() || path == "m" || path == "m/" {
341            return Ok(vec![].into());
342        }
343
344        let path = path.strip_prefix("m/").unwrap_or(path);
345
346        let parts = path.split('/');
347        let ret: Result<Vec<ChildNumber>, Error> = parts.map(str::parse).collect();
348        Ok(DerivationPath(ret?))
349    }
350}
351
352/// An iterator over children of a [DerivationPath].
353///
354/// It is returned by the methods [DerivationPath::children_from],
355/// [DerivationPath::normal_children] and [DerivationPath::hardened_children].
356pub struct DerivationPathIterator<'a> {
357    base: &'a DerivationPath,
358    next_child: Option<ChildNumber>,
359}
360
361impl<'a> DerivationPathIterator<'a> {
362    /// Start a new [DerivationPathIterator] at the given child.
363    pub fn start_from(path: &'a DerivationPath, start: ChildNumber) -> DerivationPathIterator<'a> {
364        DerivationPathIterator { base: path, next_child: Some(start) }
365    }
366}
367
368impl<'a> Iterator for DerivationPathIterator<'a> {
369    type Item = DerivationPath;
370
371    fn next(&mut self) -> Option<Self::Item> {
372        let ret = self.next_child?;
373        self.next_child = ret.increment().ok();
374        Some(self.base.child(ret))
375    }
376}
377
378impl DerivationPath {
379    /// Returns length of the derivation path
380    pub fn len(&self) -> usize { self.0.len() }
381
382    /// Returns `true` if the derivation path is empty
383    pub fn is_empty(&self) -> bool { self.0.is_empty() }
384
385    /// Returns derivation path for a master key (i.e. empty derivation path)
386    pub fn master() -> DerivationPath { DerivationPath(vec![]) }
387
388    /// Returns whether derivation path represents master key (i.e. it's length
389    /// is empty). True for `m` path.
390    pub fn is_master(&self) -> bool { self.0.is_empty() }
391
392    /// Create a new [DerivationPath] that is a child of this one.
393    pub fn child(&self, cn: ChildNumber) -> DerivationPath {
394        let mut path = self.0.clone();
395        path.push(cn);
396        DerivationPath(path)
397    }
398
399    /// Convert into a [DerivationPath] that is a child of this one.
400    pub fn into_child(self, cn: ChildNumber) -> DerivationPath {
401        let mut path = self.0;
402        path.push(cn);
403        DerivationPath(path)
404    }
405
406    /// Get an [Iterator] over the children of this [DerivationPath]
407    /// starting with the given [ChildNumber].
408    pub fn children_from(&self, cn: ChildNumber) -> DerivationPathIterator<'_> {
409        DerivationPathIterator::start_from(self, cn)
410    }
411
412    /// Get an [Iterator] over the unhardened children of this [DerivationPath].
413    pub fn normal_children(&self) -> DerivationPathIterator<'_> {
414        DerivationPathIterator::start_from(self, ChildNumber::Normal { index: 0 })
415    }
416
417    /// Get an [Iterator] over the hardened children of this [DerivationPath].
418    pub fn hardened_children(&self) -> DerivationPathIterator<'_> {
419        DerivationPathIterator::start_from(self, ChildNumber::Hardened { index: 0 })
420    }
421
422    /// Concatenate `self` with `path` and return the resulting new path.
423    ///
424    /// ```
425    /// use bitcoin::bip32::{DerivationPath, ChildNumber};
426    /// use std::str::FromStr;
427    ///
428    /// let base = DerivationPath::from_str("m/42").unwrap();
429    ///
430    /// let deriv_1 = base.extend(DerivationPath::from_str("0/1").unwrap());
431    /// let deriv_2 = base.extend(&[
432    ///     ChildNumber::from_normal_idx(0).unwrap(),
433    ///     ChildNumber::from_normal_idx(1).unwrap()
434    /// ]);
435    ///
436    /// assert_eq!(deriv_1, deriv_2);
437    /// ```
438    pub fn extend<T: AsRef<[ChildNumber]>>(&self, path: T) -> DerivationPath {
439        let mut new_path = self.clone();
440        new_path.0.extend_from_slice(path.as_ref());
441        new_path
442    }
443
444    /// Returns the derivation path as a vector of u32 integers.
445    /// Unhardened elements are copied as is.
446    /// 0x80000000 is added to the hardened elements.
447    ///
448    /// ```
449    /// use bitcoin::bip32::DerivationPath;
450    /// use std::str::FromStr;
451    ///
452    /// let path = DerivationPath::from_str("m/84'/0'/0'/0/1").unwrap();
453    /// const HARDENED: u32 = 0x80000000;
454    /// assert_eq!(path.to_u32_vec(), vec![84 + HARDENED, HARDENED, HARDENED, 0, 1]);
455    /// ```
456    pub fn to_u32_vec(&self) -> Vec<u32> { self.into_iter().map(|&el| el.into()).collect() }
457}
458
459impl fmt::Display for DerivationPath {
460    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
461        let mut iter = self.0.iter();
462        if let Some(first_element) = iter.next() {
463            write!(f, "{}", first_element)?;
464        }
465        for cn in iter {
466            f.write_str("/")?;
467            write!(f, "{}", cn)?;
468        }
469        Ok(())
470    }
471}
472
473impl fmt::Debug for DerivationPath {
474    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self, f) }
475}
476
477/// Full information on the used extended public key: fingerprint of the
478/// master extended public key and a derivation path from it.
479pub type KeySource = (Fingerprint, DerivationPath);
480
481/// A BIP32 error
482#[derive(Debug, Clone, PartialEq, Eq)]
483#[non_exhaustive]
484pub enum Error {
485    /// A pk->pk derivation was attempted on a hardened key
486    CannotDeriveFromHardenedKey,
487    /// Attempted to derive a child of depth 256 or higher.
488    ///
489    /// There is no way to encode such xkeys.
490    MaximumDepthExceeded,
491    /// A secp256k1 error occurred
492    Secp256k1(secp256k1::Error),
493    /// A child number was provided that was out of range
494    InvalidChildNumber(u32),
495    /// Invalid childnumber format.
496    InvalidChildNumberFormat,
497    /// Invalid derivation path format.
498    InvalidDerivationPathFormat,
499    /// Unknown version magic bytes
500    UnknownVersion([u8; 4]),
501    /// Encoded extended key data has wrong length
502    WrongExtendedKeyLength(usize),
503    /// Base58 encoding error
504    Base58(base58::Error),
505    /// Hexadecimal decoding error
506    Hex(hex::HexToArrayError),
507    /// `PublicKey` hex should be 66 or 130 digits long.
508    InvalidPublicKeyHexLength(usize),
509    /// Base58 decoded data was an invalid length.
510    InvalidBase58PayloadLength(InvalidBase58PayloadLengthError),
511}
512
513impl From<Infallible> for Error {
514    fn from(never: Infallible) -> Self { match never {} }
515}
516
517impl fmt::Display for Error {
518    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
519        use Error::*;
520
521        match *self {
522            CannotDeriveFromHardenedKey =>
523                f.write_str("cannot derive hardened key from public key"),
524            MaximumDepthExceeded => f.write_str("cannot derive child of depth 256 or higher"),
525            Secp256k1(ref e) => write_err!(f, "secp256k1 error"; e),
526            InvalidChildNumber(ref n) =>
527                write!(f, "child number {} is invalid (not within [0, 2^31 - 1])", n),
528            InvalidChildNumberFormat => f.write_str("invalid child number format"),
529            InvalidDerivationPathFormat => f.write_str("invalid derivation path format"),
530            UnknownVersion(ref bytes) => write!(f, "unknown version magic bytes: {:?}", bytes),
531            WrongExtendedKeyLength(ref len) =>
532                write!(f, "encoded extended key data has wrong length {}", len),
533            Base58(ref e) => write_err!(f, "base58 encoding error"; e),
534            Hex(ref e) => write_err!(f, "Hexadecimal decoding error"; e),
535            InvalidPublicKeyHexLength(got) =>
536                write!(f, "PublicKey hex should be 66 or 130 digits long, got: {}", got),
537            InvalidBase58PayloadLength(ref e) => write_err!(f, "base58 payload"; e),
538        }
539    }
540}
541
542#[cfg(feature = "std")]
543impl std::error::Error for Error {
544    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
545        use Error::*;
546
547        match *self {
548            Secp256k1(ref e) => Some(e),
549            Base58(ref e) => Some(e),
550            Hex(ref e) => Some(e),
551            InvalidBase58PayloadLength(ref e) => Some(e),
552            CannotDeriveFromHardenedKey
553            | MaximumDepthExceeded
554            | InvalidChildNumber(_)
555            | InvalidChildNumberFormat
556            | InvalidDerivationPathFormat
557            | UnknownVersion(_)
558            | WrongExtendedKeyLength(_)
559            | InvalidPublicKeyHexLength(_) => None,
560        }
561    }
562}
563
564impl From<secp256k1::Error> for Error {
565    fn from(e: secp256k1::Error) -> Error { Error::Secp256k1(e) }
566}
567
568impl From<base58::Error> for Error {
569    fn from(err: base58::Error) -> Self { Error::Base58(err) }
570}
571
572impl From<InvalidBase58PayloadLengthError> for Error {
573    fn from(e: InvalidBase58PayloadLengthError) -> Error { Self::InvalidBase58PayloadLength(e) }
574}
575
576impl Xpriv {
577    /// Construct a new master key from a seed value
578    pub fn new_master(network: impl Into<NetworkKind>, seed: &[u8]) -> Result<Xpriv, Error> {
579        let mut hmac_engine: HmacEngine<sha512::Hash> = HmacEngine::new(b"Bitcoin seed");
580        hmac_engine.input(seed);
581        let hmac_result: Hmac<sha512::Hash> = Hmac::from_engine(hmac_engine);
582
583        Ok(Xpriv {
584            network: network.into(),
585            depth: 0,
586            parent_fingerprint: Default::default(),
587            child_number: ChildNumber::from_normal_idx(0)?,
588            private_key: secp256k1::SecretKey::from_slice(&hmac_result[..32])?,
589            chain_code: ChainCode::from_hmac(hmac_result),
590        })
591    }
592
593    /// Constructs ECDSA compressed private key matching internal secret key representation.
594    pub fn to_priv(self) -> PrivateKey {
595        PrivateKey { compressed: true, network: self.network, inner: self.private_key }
596    }
597
598    /// Constructs BIP340 keypair for Schnorr signatures and Taproot use matching the internal
599    /// secret key representation.
600    pub fn to_keypair<C: secp256k1::Signing>(self, secp: &Secp256k1<C>) -> Keypair {
601        Keypair::from_seckey_slice(secp, &self.private_key[..])
602            .expect("BIP32 internal private key representation is broken")
603    }
604
605    /// Attempts to derive an extended private key from a path.
606    ///
607    /// The `path` argument can be both of type `DerivationPath` or `Vec<ChildNumber>`.
608    pub fn derive_priv<C: secp256k1::Signing, P: AsRef<[ChildNumber]>>(
609        &self,
610        secp: &Secp256k1<C>,
611        path: &P,
612    ) -> Result<Xpriv, Error> {
613        let mut sk: Xpriv = *self;
614        for cnum in path.as_ref() {
615            sk = sk.ckd_priv(secp, *cnum)?;
616        }
617        Ok(sk)
618    }
619
620    /// Private->Private child key derivation
621    fn ckd_priv<C: secp256k1::Signing>(
622        &self,
623        secp: &Secp256k1<C>,
624        i: ChildNumber,
625    ) -> Result<Xpriv, Error> {
626        let mut hmac_engine: HmacEngine<sha512::Hash> = HmacEngine::new(&self.chain_code[..]);
627        match i {
628            ChildNumber::Normal { .. } => {
629                // Non-hardened key: compute public data and use that
630                hmac_engine.input(
631                    &secp256k1::PublicKey::from_secret_key(secp, &self.private_key).serialize()[..],
632                );
633            }
634            ChildNumber::Hardened { .. } => {
635                // Hardened key: use only secret data to prevent public derivation
636                hmac_engine.input(&[0u8]);
637                hmac_engine.input(&self.private_key[..]);
638            }
639        }
640
641        hmac_engine.input(&u32::from(i).to_be_bytes());
642        let hmac_result: Hmac<sha512::Hash> = Hmac::from_engine(hmac_engine);
643        let sk = secp256k1::SecretKey::from_slice(&hmac_result[..32])
644            .expect("statistically impossible to hit");
645        let tweaked =
646            sk.add_tweak(&self.private_key.into()).expect("statistically impossible to hit");
647
648        Ok(Xpriv {
649            network: self.network,
650            depth: self.depth.checked_add(1).ok_or(Error::MaximumDepthExceeded)?,
651            parent_fingerprint: self.fingerprint(secp),
652            child_number: i,
653            private_key: tweaked,
654            chain_code: ChainCode::from_hmac(hmac_result),
655        })
656    }
657
658    /// Decoding extended private key from binary data according to BIP 32
659    pub fn decode(data: &[u8]) -> Result<Xpriv, Error> {
660        if data.len() != 78 {
661            return Err(Error::WrongExtendedKeyLength(data.len()));
662        }
663
664        let network = if data.starts_with(&VERSION_BYTES_MAINNET_PRIVATE) {
665            NetworkKind::Main
666        } else if data.starts_with(&VERSION_BYTES_TESTNETS_PRIVATE) {
667            NetworkKind::Test
668        } else {
669            let (b0, b1, b2, b3) = (data[0], data[1], data[2], data[3]);
670            return Err(Error::UnknownVersion([b0, b1, b2, b3]));
671        };
672
673        Ok(Xpriv {
674            network,
675            depth: data[4],
676            parent_fingerprint: data[5..9]
677                .try_into()
678                .expect("9 - 5 == 4, which is the Fingerprint length"),
679            child_number: u32::from_be_bytes(data[9..13].try_into().expect("4 byte slice")).into(),
680            chain_code: data[13..45]
681                .try_into()
682                .expect("45 - 13 == 32, which is the ChainCode length"),
683            private_key: secp256k1::SecretKey::from_slice(&data[46..78])?,
684        })
685    }
686
687    /// Extended private key binary encoding according to BIP 32
688    pub fn encode(&self) -> [u8; 78] {
689        let mut ret = [0; 78];
690        ret[0..4].copy_from_slice(&match self.network {
691            NetworkKind::Main => VERSION_BYTES_MAINNET_PRIVATE,
692            NetworkKind::Test => VERSION_BYTES_TESTNETS_PRIVATE,
693        });
694        ret[4] = self.depth;
695        ret[5..9].copy_from_slice(&self.parent_fingerprint[..]);
696        ret[9..13].copy_from_slice(&u32::from(self.child_number).to_be_bytes());
697        ret[13..45].copy_from_slice(&self.chain_code[..]);
698        ret[45] = 0;
699        ret[46..78].copy_from_slice(&self.private_key[..]);
700        ret
701    }
702
703    /// Returns the HASH160 of the public key belonging to the xpriv
704    pub fn identifier<C: secp256k1::Signing>(&self, secp: &Secp256k1<C>) -> XKeyIdentifier {
705        Xpub::from_priv(secp, self).identifier()
706    }
707
708    /// Returns the first four bytes of the identifier
709    pub fn fingerprint<C: secp256k1::Signing>(&self, secp: &Secp256k1<C>) -> Fingerprint {
710        self.identifier(secp)[0..4].try_into().expect("4 is the fingerprint length")
711    }
712}
713
714impl Xpub {
715    /// Derives a public key from a private key
716    pub fn from_priv<C: secp256k1::Signing>(secp: &Secp256k1<C>, sk: &Xpriv) -> Xpub {
717        Xpub {
718            network: sk.network,
719            depth: sk.depth,
720            parent_fingerprint: sk.parent_fingerprint,
721            child_number: sk.child_number,
722            public_key: secp256k1::PublicKey::from_secret_key(secp, &sk.private_key),
723            chain_code: sk.chain_code,
724        }
725    }
726
727    /// Constructs ECDSA compressed public key matching internal public key representation.
728    pub fn to_pub(self) -> CompressedPublicKey { CompressedPublicKey(self.public_key) }
729
730    /// Constructs BIP340 x-only public key for BIP-340 signatures and Taproot use matching
731    /// the internal public key representation.
732    pub fn to_x_only_pub(self) -> XOnlyPublicKey { XOnlyPublicKey::from(self.public_key) }
733
734    /// Attempts to derive an extended public key from a path.
735    ///
736    /// The `path` argument can be any type implementing `AsRef<ChildNumber>`, such as `DerivationPath`, for instance.
737    pub fn derive_pub<C: secp256k1::Verification, P: AsRef<[ChildNumber]>>(
738        &self,
739        secp: &Secp256k1<C>,
740        path: &P,
741    ) -> Result<Xpub, Error> {
742        let mut pk: Xpub = *self;
743        for cnum in path.as_ref() {
744            pk = pk.ckd_pub(secp, *cnum)?
745        }
746        Ok(pk)
747    }
748
749    /// Compute the scalar tweak added to this key to get a child key
750    pub fn ckd_pub_tweak(
751        &self,
752        i: ChildNumber,
753    ) -> Result<(secp256k1::SecretKey, ChainCode), Error> {
754        match i {
755            ChildNumber::Hardened { .. } => Err(Error::CannotDeriveFromHardenedKey),
756            ChildNumber::Normal { index: n } => {
757                let mut hmac_engine: HmacEngine<sha512::Hash> =
758                    HmacEngine::new(&self.chain_code[..]);
759                hmac_engine.input(&self.public_key.serialize()[..]);
760                hmac_engine.input(&n.to_be_bytes());
761
762                let hmac_result: Hmac<sha512::Hash> = Hmac::from_engine(hmac_engine);
763
764                let private_key = secp256k1::SecretKey::from_slice(&hmac_result[..32])?;
765                let chain_code = ChainCode::from_hmac(hmac_result);
766                Ok((private_key, chain_code))
767            }
768        }
769    }
770
771    /// Public->Public child key derivation
772    pub fn ckd_pub<C: secp256k1::Verification>(
773        &self,
774        secp: &Secp256k1<C>,
775        i: ChildNumber,
776    ) -> Result<Xpub, Error> {
777        let (sk, chain_code) = self.ckd_pub_tweak(i)?;
778        let tweaked = self.public_key.add_exp_tweak(secp, &sk.into())?;
779
780        Ok(Xpub {
781            network: self.network,
782            depth: self.depth.checked_add(1).ok_or(Error::MaximumDepthExceeded)?,
783            parent_fingerprint: self.fingerprint(),
784            child_number: i,
785            public_key: tweaked,
786            chain_code,
787        })
788    }
789
790    /// Decoding extended public key from binary data according to BIP 32
791    pub fn decode(data: &[u8]) -> Result<Xpub, Error> {
792        if data.len() != 78 {
793            return Err(Error::WrongExtendedKeyLength(data.len()));
794        }
795
796        let network = if data.starts_with(&VERSION_BYTES_MAINNET_PUBLIC) {
797            NetworkKind::Main
798        } else if data.starts_with(&VERSION_BYTES_TESTNETS_PUBLIC) {
799            NetworkKind::Test
800        } else {
801            let (b0, b1, b2, b3) = (data[0], data[1], data[2], data[3]);
802            return Err(Error::UnknownVersion([b0, b1, b2, b3]));
803        };
804
805        Ok(Xpub {
806            network,
807            depth: data[4],
808            parent_fingerprint: data[5..9]
809                .try_into()
810                .expect("9 - 5 == 4, which is the Fingerprint length"),
811            child_number: u32::from_be_bytes(data[9..13].try_into().expect("4 byte slice")).into(),
812            chain_code: data[13..45]
813                .try_into()
814                .expect("45 - 13 == 32, which is the ChainCode length"),
815            public_key: secp256k1::PublicKey::from_slice(&data[45..78])?,
816        })
817    }
818
819    /// Extended public key binary encoding according to BIP 32
820    pub fn encode(&self) -> [u8; 78] {
821        let mut ret = [0; 78];
822        ret[0..4].copy_from_slice(&match self.network {
823            NetworkKind::Main => VERSION_BYTES_MAINNET_PUBLIC,
824            NetworkKind::Test => VERSION_BYTES_TESTNETS_PUBLIC,
825        });
826        ret[4] = self.depth;
827        ret[5..9].copy_from_slice(&self.parent_fingerprint[..]);
828        ret[9..13].copy_from_slice(&u32::from(self.child_number).to_be_bytes());
829        ret[13..45].copy_from_slice(&self.chain_code[..]);
830        ret[45..78].copy_from_slice(&self.public_key.serialize()[..]);
831        ret
832    }
833
834    /// Returns the HASH160 of the chaincode
835    pub fn identifier(&self) -> XKeyIdentifier {
836        let mut engine = XKeyIdentifier::engine();
837        engine.write_all(&self.public_key.serialize()).expect("engines don't error");
838        XKeyIdentifier::from_engine(engine)
839    }
840
841    /// Returns the first four bytes of the identifier
842    pub fn fingerprint(&self) -> Fingerprint {
843        self.identifier()[0..4].try_into().expect("4 is the fingerprint length")
844    }
845}
846
847impl fmt::Display for Xpriv {
848    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
849        base58::encode_check_to_fmt(fmt, &self.encode()[..])
850    }
851}
852
853impl FromStr for Xpriv {
854    type Err = Error;
855
856    fn from_str(inp: &str) -> Result<Xpriv, Error> {
857        let data = base58::decode_check(inp)?;
858
859        if data.len() != 78 {
860            return Err(InvalidBase58PayloadLengthError { length: data.len() }.into());
861        }
862
863        Xpriv::decode(&data)
864    }
865}
866
867impl fmt::Display for Xpub {
868    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
869        base58::encode_check_to_fmt(fmt, &self.encode()[..])
870    }
871}
872
873impl FromStr for Xpub {
874    type Err = Error;
875
876    fn from_str(inp: &str) -> Result<Xpub, Error> {
877        let data = base58::decode_check(inp)?;
878
879        if data.len() != 78 {
880            return Err(InvalidBase58PayloadLengthError { length: data.len() }.into());
881        }
882
883        Xpub::decode(&data)
884    }
885}
886
887impl From<Xpub> for XKeyIdentifier {
888    fn from(key: Xpub) -> XKeyIdentifier { key.identifier() }
889}
890
891impl From<&Xpub> for XKeyIdentifier {
892    fn from(key: &Xpub) -> XKeyIdentifier { key.identifier() }
893}
894
895/// Decoded base58 data was an invalid length.
896#[derive(Debug, Clone, PartialEq, Eq)]
897pub struct InvalidBase58PayloadLengthError {
898    /// The base58 payload length we got after decoding xpriv/xpub string.
899    pub(crate) length: usize,
900}
901
902impl InvalidBase58PayloadLengthError {
903    /// Returns the invalid payload length.
904    pub fn invalid_base58_payload_length(&self) -> usize { self.length }
905}
906
907impl fmt::Display for InvalidBase58PayloadLengthError {
908    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
909        write!(
910            f,
911            "decoded base58 xpriv/xpub data was an invalid length: {} (expected 78)",
912            self.length
913        )
914    }
915}
916
917#[cfg(feature = "std")]
918impl std::error::Error for InvalidBase58PayloadLengthError {}
919
920#[cfg(test)]
921mod tests {
922    use hex::test_hex_unwrap as hex;
923
924    use super::ChildNumber::{Hardened, Normal};
925    use super::*;
926
927    #[test]
928    fn test_parse_derivation_path() {
929        assert_eq!(DerivationPath::from_str("n/0'/0"), Err(Error::InvalidChildNumberFormat));
930        assert_eq!(DerivationPath::from_str("4/m/5"), Err(Error::InvalidChildNumberFormat));
931        assert_eq!(DerivationPath::from_str("//3/0'"), Err(Error::InvalidChildNumberFormat));
932        assert_eq!(DerivationPath::from_str("0h/0x"), Err(Error::InvalidChildNumberFormat));
933        assert_eq!(
934            DerivationPath::from_str("2147483648"),
935            Err(Error::InvalidChildNumber(2147483648))
936        );
937
938        assert_eq!(DerivationPath::master(), DerivationPath::from_str("").unwrap());
939        assert_eq!(DerivationPath::master(), DerivationPath::default());
940
941        // Acceptable forms for a master path.
942        assert_eq!(DerivationPath::from_str("m").unwrap(), DerivationPath(vec![]));
943        assert_eq!(DerivationPath::from_str("m/").unwrap(), DerivationPath(vec![]));
944        assert_eq!(DerivationPath::from_str("").unwrap(), DerivationPath(vec![]));
945
946        assert_eq!(
947            DerivationPath::from_str("0'"),
948            Ok(vec![ChildNumber::from_hardened_idx(0).unwrap()].into())
949        );
950        assert_eq!(
951            DerivationPath::from_str("0'/1"),
952            Ok(vec![
953                ChildNumber::from_hardened_idx(0).unwrap(),
954                ChildNumber::from_normal_idx(1).unwrap()
955            ]
956            .into())
957        );
958        assert_eq!(
959            DerivationPath::from_str("0h/1/2'"),
960            Ok(vec![
961                ChildNumber::from_hardened_idx(0).unwrap(),
962                ChildNumber::from_normal_idx(1).unwrap(),
963                ChildNumber::from_hardened_idx(2).unwrap(),
964            ]
965            .into())
966        );
967        assert_eq!(
968            DerivationPath::from_str("0'/1/2h/2"),
969            Ok(vec![
970                ChildNumber::from_hardened_idx(0).unwrap(),
971                ChildNumber::from_normal_idx(1).unwrap(),
972                ChildNumber::from_hardened_idx(2).unwrap(),
973                ChildNumber::from_normal_idx(2).unwrap(),
974            ]
975            .into())
976        );
977        let want = DerivationPath::from(vec![
978            ChildNumber::from_hardened_idx(0).unwrap(),
979            ChildNumber::from_normal_idx(1).unwrap(),
980            ChildNumber::from_hardened_idx(2).unwrap(),
981            ChildNumber::from_normal_idx(2).unwrap(),
982            ChildNumber::from_normal_idx(1000000000).unwrap(),
983        ]);
984        assert_eq!(DerivationPath::from_str("0'/1/2'/2/1000000000").unwrap(), want);
985        assert_eq!(DerivationPath::from_str("m/0'/1/2'/2/1000000000").unwrap(), want);
986
987        let s = "0'/50/3'/5/545456";
988        assert_eq!(DerivationPath::from_str(s), s.into_derivation_path());
989        assert_eq!(DerivationPath::from_str(s), s.to_string().into_derivation_path());
990
991        let s = "m/0'/50/3'/5/545456";
992        assert_eq!(DerivationPath::from_str(s), s.into_derivation_path());
993        assert_eq!(DerivationPath::from_str(s), s.to_string().into_derivation_path());
994    }
995
996    #[test]
997    fn test_derivation_path_conversion_index() {
998        let path = DerivationPath::from_str("0h/1/2'").unwrap();
999        let numbers: Vec<ChildNumber> = path.clone().into();
1000        let path2: DerivationPath = numbers.into();
1001        assert_eq!(path, path2);
1002        assert_eq!(
1003            &path[..2],
1004            &[ChildNumber::from_hardened_idx(0).unwrap(), ChildNumber::from_normal_idx(1).unwrap()]
1005        );
1006        let indexed: DerivationPath = path[..2].into();
1007        assert_eq!(indexed, DerivationPath::from_str("0h/1").unwrap());
1008        assert_eq!(indexed.child(ChildNumber::from_hardened_idx(2).unwrap()), path);
1009    }
1010
1011    fn test_path<C: secp256k1::Signing + secp256k1::Verification>(
1012        secp: &Secp256k1<C>,
1013        network: NetworkKind,
1014        seed: &[u8],
1015        path: DerivationPath,
1016        expected_sk: &str,
1017        expected_pk: &str,
1018    ) {
1019        let mut sk = Xpriv::new_master(network, seed).unwrap();
1020        let mut pk = Xpub::from_priv(secp, &sk);
1021
1022        // Check derivation convenience method for Xpriv
1023        assert_eq!(&sk.derive_priv(secp, &path).unwrap().to_string()[..], expected_sk);
1024
1025        // Check derivation convenience method for Xpub, should error
1026        // appropriately if any ChildNumber is hardened
1027        if path.0.iter().any(|cnum| cnum.is_hardened()) {
1028            assert_eq!(pk.derive_pub(secp, &path), Err(Error::CannotDeriveFromHardenedKey));
1029        } else {
1030            assert_eq!(&pk.derive_pub(secp, &path).unwrap().to_string()[..], expected_pk);
1031        }
1032
1033        // Derive keys, checking hardened and non-hardened derivation one-by-one
1034        for &num in path.0.iter() {
1035            sk = sk.ckd_priv(secp, num).unwrap();
1036            match num {
1037                Normal { .. } => {
1038                    let pk2 = pk.ckd_pub(secp, num).unwrap();
1039                    pk = Xpub::from_priv(secp, &sk);
1040                    assert_eq!(pk, pk2);
1041                }
1042                Hardened { .. } => {
1043                    assert_eq!(pk.ckd_pub(secp, num), Err(Error::CannotDeriveFromHardenedKey));
1044                    pk = Xpub::from_priv(secp, &sk);
1045                }
1046            }
1047        }
1048
1049        // Check result against expected base58
1050        assert_eq!(&sk.to_string()[..], expected_sk);
1051        assert_eq!(&pk.to_string()[..], expected_pk);
1052        // Check decoded base58 against result
1053        let decoded_sk = Xpriv::from_str(expected_sk);
1054        let decoded_pk = Xpub::from_str(expected_pk);
1055        assert_eq!(Ok(sk), decoded_sk);
1056        assert_eq!(Ok(pk), decoded_pk);
1057    }
1058
1059    #[test]
1060    fn test_increment() {
1061        let idx = 9345497; // randomly generated, I promise
1062        let cn = ChildNumber::from_normal_idx(idx).unwrap();
1063        assert_eq!(cn.increment().ok(), Some(ChildNumber::from_normal_idx(idx + 1).unwrap()));
1064        let cn = ChildNumber::from_hardened_idx(idx).unwrap();
1065        assert_eq!(cn.increment().ok(), Some(ChildNumber::from_hardened_idx(idx + 1).unwrap()));
1066
1067        let max = (1 << 31) - 1;
1068        let cn = ChildNumber::from_normal_idx(max).unwrap();
1069        assert_eq!(cn.increment().err(), Some(Error::InvalidChildNumber(1 << 31)));
1070        let cn = ChildNumber::from_hardened_idx(max).unwrap();
1071        assert_eq!(cn.increment().err(), Some(Error::InvalidChildNumber(1 << 31)));
1072
1073        let cn = ChildNumber::from_normal_idx(350).unwrap();
1074        let path = DerivationPath::from_str("42'").unwrap();
1075        let mut iter = path.children_from(cn);
1076        assert_eq!(iter.next(), Some("42'/350".parse().unwrap()));
1077        assert_eq!(iter.next(), Some("42'/351".parse().unwrap()));
1078
1079        let path = DerivationPath::from_str("42'/350'").unwrap();
1080        let mut iter = path.normal_children();
1081        assert_eq!(iter.next(), Some("42'/350'/0".parse().unwrap()));
1082        assert_eq!(iter.next(), Some("42'/350'/1".parse().unwrap()));
1083
1084        let path = DerivationPath::from_str("42'/350'").unwrap();
1085        let mut iter = path.hardened_children();
1086        assert_eq!(iter.next(), Some("42'/350'/0'".parse().unwrap()));
1087        assert_eq!(iter.next(), Some("42'/350'/1'".parse().unwrap()));
1088
1089        let cn = ChildNumber::from_hardened_idx(42350).unwrap();
1090        let path = DerivationPath::from_str("42'").unwrap();
1091        let mut iter = path.children_from(cn);
1092        assert_eq!(iter.next(), Some("42'/42350'".parse().unwrap()));
1093        assert_eq!(iter.next(), Some("42'/42351'".parse().unwrap()));
1094
1095        let cn = ChildNumber::from_hardened_idx(max).unwrap();
1096        let path = DerivationPath::from_str("42'").unwrap();
1097        let mut iter = path.children_from(cn);
1098        assert!(iter.next().is_some());
1099        assert!(iter.next().is_none());
1100    }
1101
1102    #[test]
1103    fn test_vector_1() {
1104        let secp = Secp256k1::new();
1105        let seed = hex!("000102030405060708090a0b0c0d0e0f");
1106
1107        // m
1108        test_path(&secp, NetworkKind::Main, &seed, "m".parse().unwrap(),
1109                  "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi",
1110                  "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8");
1111
1112        // m/0h
1113        test_path(&secp, NetworkKind::Main, &seed, "m/0h".parse().unwrap(),
1114                  "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7",
1115                  "xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw");
1116
1117        // m/0h/1
1118        test_path(&secp, NetworkKind::Main, &seed, "m/0h/1".parse().unwrap(),
1119                   "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs",
1120                   "xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ");
1121
1122        // m/0h/1/2h
1123        test_path(&secp, NetworkKind::Main, &seed, "m/0h/1/2h".parse().unwrap(),
1124                  "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM",
1125                  "xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5");
1126
1127        // m/0h/1/2h/2
1128        test_path(&secp, NetworkKind::Main, &seed, "m/0h/1/2h/2".parse().unwrap(),
1129                  "xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334",
1130                  "xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV");
1131
1132        // m/0h/1/2h/2/1000000000
1133        test_path(&secp, NetworkKind::Main, &seed, "m/0h/1/2h/2/1000000000".parse().unwrap(),
1134                  "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76",
1135                  "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy");
1136    }
1137
1138    #[test]
1139    fn test_vector_2() {
1140        let secp = Secp256k1::new();
1141        let seed = hex!("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542");
1142
1143        // m
1144        test_path(&secp, NetworkKind::Main, &seed, "m".parse().unwrap(),
1145                  "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U",
1146                  "xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB");
1147
1148        // m/0
1149        test_path(&secp, NetworkKind::Main, &seed, "m/0".parse().unwrap(),
1150                  "xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt",
1151                  "xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH");
1152
1153        // m/0/2147483647h
1154        test_path(&secp, NetworkKind::Main, &seed, "m/0/2147483647h".parse().unwrap(),
1155                  "xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9",
1156                  "xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a");
1157
1158        // m/0/2147483647h/1
1159        test_path(&secp, NetworkKind::Main, &seed, "m/0/2147483647h/1".parse().unwrap(),
1160                  "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef",
1161                  "xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon");
1162
1163        // m/0/2147483647h/1/2147483646h
1164        test_path(&secp, NetworkKind::Main, &seed, "m/0/2147483647h/1/2147483646h".parse().unwrap(),
1165                  "xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc",
1166                  "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL");
1167
1168        // m/0/2147483647h/1/2147483646h/2
1169        test_path(&secp, NetworkKind::Main, &seed, "m/0/2147483647h/1/2147483646h/2".parse().unwrap(),
1170                  "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j",
1171                  "xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt");
1172    }
1173
1174    #[test]
1175    fn test_vector_3() {
1176        let secp = Secp256k1::new();
1177        let seed = hex!("4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be");
1178
1179        // m
1180        test_path(&secp, NetworkKind::Main, &seed, "m".parse().unwrap(),
1181                  "xprv9s21ZrQH143K25QhxbucbDDuQ4naNntJRi4KUfWT7xo4EKsHt2QJDu7KXp1A3u7Bi1j8ph3EGsZ9Xvz9dGuVrtHHs7pXeTzjuxBrCmmhgC6",
1182                  "xpub661MyMwAqRbcEZVB4dScxMAdx6d4nFc9nvyvH3v4gJL378CSRZiYmhRoP7mBy6gSPSCYk6SzXPTf3ND1cZAceL7SfJ1Z3GC8vBgp2epUt13");
1183
1184        // m/0h
1185        test_path(&secp, NetworkKind::Main, &seed, "m/0h".parse().unwrap(),
1186                  "xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L",
1187                  "xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y");
1188    }
1189
1190    #[test]
1191    #[cfg(feature = "serde")]
1192    pub fn encode_decode_childnumber() {
1193        serde_round_trip!(ChildNumber::from_normal_idx(0).unwrap());
1194        serde_round_trip!(ChildNumber::from_normal_idx(1).unwrap());
1195        serde_round_trip!(ChildNumber::from_normal_idx((1 << 31) - 1).unwrap());
1196        serde_round_trip!(ChildNumber::from_hardened_idx(0).unwrap());
1197        serde_round_trip!(ChildNumber::from_hardened_idx(1).unwrap());
1198        serde_round_trip!(ChildNumber::from_hardened_idx((1 << 31) - 1).unwrap());
1199    }
1200
1201    #[test]
1202    #[cfg(feature = "serde")]
1203    pub fn encode_fingerprint_chaincode() {
1204        use serde_json;
1205        let fp = Fingerprint::from([1u8, 2, 3, 42]);
1206        #[rustfmt::skip]
1207        let cc = ChainCode::from(
1208            [1u8,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2]
1209        );
1210
1211        serde_round_trip!(fp);
1212        serde_round_trip!(cc);
1213
1214        assert_eq!("\"0102032a\"", serde_json::to_string(&fp).unwrap());
1215        assert_eq!(
1216            "\"0102030405060708090001020304050607080900010203040506070809000102\"",
1217            serde_json::to_string(&cc).unwrap()
1218        );
1219        assert_eq!("0102032a", fp.to_string());
1220        assert_eq!(
1221            "0102030405060708090001020304050607080900010203040506070809000102",
1222            cc.to_string()
1223        );
1224    }
1225
1226    #[test]
1227    fn fmt_child_number() {
1228        assert_eq!("000005h", &format!("{:#06}", ChildNumber::from_hardened_idx(5).unwrap()));
1229        assert_eq!("5h", &format!("{:#}", ChildNumber::from_hardened_idx(5).unwrap()));
1230        assert_eq!("000005'", &format!("{:06}", ChildNumber::from_hardened_idx(5).unwrap()));
1231        assert_eq!("5'", &format!("{}", ChildNumber::from_hardened_idx(5).unwrap()));
1232        assert_eq!("42", &format!("{}", ChildNumber::from_normal_idx(42).unwrap()));
1233        assert_eq!("000042", &format!("{:06}", ChildNumber::from_normal_idx(42).unwrap()));
1234    }
1235
1236    #[test]
1237    #[should_panic(expected = "Secp256k1(InvalidSecretKey)")]
1238    fn schnorr_broken_privkey_zeros() {
1239        /* this is how we generate key:
1240        let mut sk = secp256k1::key::ONE_KEY;
1241
1242        let zeros = [0u8; 32];
1243        unsafe {
1244            sk.as_mut_ptr().copy_from(zeros.as_ptr(), 32);
1245        }
1246
1247        let xpriv = Xpriv {
1248            network: NetworkKind::Main,
1249            depth: 0,
1250            parent_fingerprint: Default::default(),
1251            child_number: ChildNumber::Normal { index: 0 },
1252            private_key: sk,
1253            chain_code: ChainCode::from([0u8; 32])
1254        };
1255
1256        println!("{}", xpriv);
1257         */
1258
1259        // Xpriv having secret key set to all zeros
1260        let xpriv_str = "xprv9s21ZrQH143K24Mfq5zL5MhWK9hUhhGbd45hLXo2Pq2oqzMMo63oStZzF93Y5wvzdUayhgkkFoicQZcP3y52uPPxFnfoLZB21Teqt1VvEHx";
1261        Xpriv::from_str(xpriv_str).unwrap();
1262    }
1263
1264    #[test]
1265    #[should_panic(expected = "Secp256k1(InvalidSecretKey)")]
1266    fn schnorr_broken_privkey_ffs() {
1267        // Xpriv having secret key set to all 0xFF's
1268        let xpriv_str = "xprv9s21ZrQH143K24Mfq5zL5MhWK9hUhhGbd45hLXo2Pq2oqzMMo63oStZzFAzHGBP2UuGCqWLTAPLcMtD9y5gkZ6Eq3Rjuahrv17fENZ3QzxW";
1269        Xpriv::from_str(xpriv_str).unwrap();
1270    }
1271}