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::ops::Index;
10use core::str::FromStr;
11use core::{fmt, slice};
12
13use hashes::{hash160, hash_newtype, sha512, Hash, HashEngine, Hmac, HmacEngine};
14use internals::{impl_array_newtype, write_err};
15use io::Write;
16use secp256k1::{Secp256k1, XOnlyPublicKey};
17
18use crate::crypto::key::{CompressedPublicKey, Keypair, PrivateKey};
19use crate::internal_macros::impl_bytes_newtype;
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<'a> IntoDerivationPath for &'a 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
513internals::impl_from_infallible!(Error);
514
515impl fmt::Display for Error {
516    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
517        use Error::*;
518
519        match *self {
520            CannotDeriveFromHardenedKey =>
521                f.write_str("cannot derive hardened key from public key"),
522            MaximumDepthExceeded => f.write_str("cannot derive child of depth 256 or higher"),
523            Secp256k1(ref e) => write_err!(f, "secp256k1 error"; e),
524            InvalidChildNumber(ref n) =>
525                write!(f, "child number {} is invalid (not within [0, 2^31 - 1])", n),
526            InvalidChildNumberFormat => f.write_str("invalid child number format"),
527            InvalidDerivationPathFormat => f.write_str("invalid derivation path format"),
528            UnknownVersion(ref bytes) => write!(f, "unknown version magic bytes: {:?}", bytes),
529            WrongExtendedKeyLength(ref len) =>
530                write!(f, "encoded extended key data has wrong length {}", len),
531            Base58(ref e) => write_err!(f, "base58 encoding error"; e),
532            Hex(ref e) => write_err!(f, "Hexadecimal decoding error"; e),
533            InvalidPublicKeyHexLength(got) =>
534                write!(f, "PublicKey hex should be 66 or 130 digits long, got: {}", got),
535            InvalidBase58PayloadLength(ref e) => write_err!(f, "base58 payload"; e),
536        }
537    }
538}
539
540#[cfg(feature = "std")]
541impl std::error::Error for Error {
542    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
543        use Error::*;
544
545        match *self {
546            Secp256k1(ref e) => Some(e),
547            Base58(ref e) => Some(e),
548            Hex(ref e) => Some(e),
549            InvalidBase58PayloadLength(ref e) => Some(e),
550            CannotDeriveFromHardenedKey
551            | MaximumDepthExceeded
552            | InvalidChildNumber(_)
553            | InvalidChildNumberFormat
554            | InvalidDerivationPathFormat
555            | UnknownVersion(_)
556            | WrongExtendedKeyLength(_)
557            | InvalidPublicKeyHexLength(_) => None,
558        }
559    }
560}
561
562impl From<secp256k1::Error> for Error {
563    fn from(e: secp256k1::Error) -> Error { Error::Secp256k1(e) }
564}
565
566impl From<base58::Error> for Error {
567    fn from(err: base58::Error) -> Self { Error::Base58(err) }
568}
569
570impl From<InvalidBase58PayloadLengthError> for Error {
571    fn from(e: InvalidBase58PayloadLengthError) -> Error { Self::InvalidBase58PayloadLength(e) }
572}
573
574impl Xpriv {
575    /// Construct a new master key from a seed value
576    pub fn new_master(network: impl Into<NetworkKind>, seed: &[u8]) -> Result<Xpriv, Error> {
577        let mut hmac_engine: HmacEngine<sha512::Hash> = HmacEngine::new(b"Bitcoin seed");
578        hmac_engine.input(seed);
579        let hmac_result: Hmac<sha512::Hash> = Hmac::from_engine(hmac_engine);
580
581        Ok(Xpriv {
582            network: network.into(),
583            depth: 0,
584            parent_fingerprint: Default::default(),
585            child_number: ChildNumber::from_normal_idx(0)?,
586            private_key: secp256k1::SecretKey::from_slice(&hmac_result[..32])?,
587            chain_code: ChainCode::from_hmac(hmac_result),
588        })
589    }
590
591    /// Constructs ECDSA compressed private key matching internal secret key representation.
592    pub fn to_priv(self) -> PrivateKey {
593        PrivateKey { compressed: true, network: self.network, inner: self.private_key }
594    }
595
596    /// Constructs BIP340 keypair for Schnorr signatures and Taproot use matching the internal
597    /// secret key representation.
598    pub fn to_keypair<C: secp256k1::Signing>(self, secp: &Secp256k1<C>) -> Keypair {
599        Keypair::from_seckey_slice(secp, &self.private_key[..])
600            .expect("BIP32 internal private key representation is broken")
601    }
602
603    /// Attempts to derive an extended private key from a path.
604    ///
605    /// The `path` argument can be both of type `DerivationPath` or `Vec<ChildNumber>`.
606    pub fn derive_priv<C: secp256k1::Signing, P: AsRef<[ChildNumber]>>(
607        &self,
608        secp: &Secp256k1<C>,
609        path: &P,
610    ) -> Result<Xpriv, Error> {
611        let mut sk: Xpriv = *self;
612        for cnum in path.as_ref() {
613            sk = sk.ckd_priv(secp, *cnum)?;
614        }
615        Ok(sk)
616    }
617
618    /// Private->Private child key derivation
619    fn ckd_priv<C: secp256k1::Signing>(
620        &self,
621        secp: &Secp256k1<C>,
622        i: ChildNumber,
623    ) -> Result<Xpriv, Error> {
624        let mut hmac_engine: HmacEngine<sha512::Hash> = HmacEngine::new(&self.chain_code[..]);
625        match i {
626            ChildNumber::Normal { .. } => {
627                // Non-hardened key: compute public data and use that
628                hmac_engine.input(
629                    &secp256k1::PublicKey::from_secret_key(secp, &self.private_key).serialize()[..],
630                );
631            }
632            ChildNumber::Hardened { .. } => {
633                // Hardened key: use only secret data to prevent public derivation
634                hmac_engine.input(&[0u8]);
635                hmac_engine.input(&self.private_key[..]);
636            }
637        }
638
639        hmac_engine.input(&u32::from(i).to_be_bytes());
640        let hmac_result: Hmac<sha512::Hash> = Hmac::from_engine(hmac_engine);
641        let sk = secp256k1::SecretKey::from_slice(&hmac_result[..32])
642            .expect("statistically impossible to hit");
643        let tweaked =
644            sk.add_tweak(&self.private_key.into()).expect("statistically impossible to hit");
645
646        Ok(Xpriv {
647            network: self.network,
648            depth: self.depth.checked_add(1).ok_or(Error::MaximumDepthExceeded)?,
649            parent_fingerprint: self.fingerprint(secp),
650            child_number: i,
651            private_key: tweaked,
652            chain_code: ChainCode::from_hmac(hmac_result),
653        })
654    }
655
656    /// Decoding extended private key from binary data according to BIP 32
657    pub fn decode(data: &[u8]) -> Result<Xpriv, Error> {
658        if data.len() != 78 {
659            return Err(Error::WrongExtendedKeyLength(data.len()));
660        }
661
662        let network = if data.starts_with(&VERSION_BYTES_MAINNET_PRIVATE) {
663            NetworkKind::Main
664        } else if data.starts_with(&VERSION_BYTES_TESTNETS_PRIVATE) {
665            NetworkKind::Test
666        } else {
667            let (b0, b1, b2, b3) = (data[0], data[1], data[2], data[3]);
668            return Err(Error::UnknownVersion([b0, b1, b2, b3]));
669        };
670
671        Ok(Xpriv {
672            network,
673            depth: data[4],
674            parent_fingerprint: data[5..9]
675                .try_into()
676                .expect("9 - 5 == 4, which is the Fingerprint length"),
677            child_number: u32::from_be_bytes(data[9..13].try_into().expect("4 byte slice")).into(),
678            chain_code: data[13..45]
679                .try_into()
680                .expect("45 - 13 == 32, which is the ChainCode length"),
681            private_key: secp256k1::SecretKey::from_slice(&data[46..78])?,
682        })
683    }
684
685    /// Extended private key binary encoding according to BIP 32
686    pub fn encode(&self) -> [u8; 78] {
687        let mut ret = [0; 78];
688        ret[0..4].copy_from_slice(&match self.network {
689            NetworkKind::Main => VERSION_BYTES_MAINNET_PRIVATE,
690            NetworkKind::Test => VERSION_BYTES_TESTNETS_PRIVATE,
691        });
692        ret[4] = self.depth;
693        ret[5..9].copy_from_slice(&self.parent_fingerprint[..]);
694        ret[9..13].copy_from_slice(&u32::from(self.child_number).to_be_bytes());
695        ret[13..45].copy_from_slice(&self.chain_code[..]);
696        ret[45] = 0;
697        ret[46..78].copy_from_slice(&self.private_key[..]);
698        ret
699    }
700
701    /// Returns the HASH160 of the public key belonging to the xpriv
702    pub fn identifier<C: secp256k1::Signing>(&self, secp: &Secp256k1<C>) -> XKeyIdentifier {
703        Xpub::from_priv(secp, self).identifier()
704    }
705
706    /// Returns the first four bytes of the identifier
707    pub fn fingerprint<C: secp256k1::Signing>(&self, secp: &Secp256k1<C>) -> Fingerprint {
708        self.identifier(secp)[0..4].try_into().expect("4 is the fingerprint length")
709    }
710}
711
712impl Xpub {
713    /// Derives a public key from a private key
714    pub fn from_priv<C: secp256k1::Signing>(secp: &Secp256k1<C>, sk: &Xpriv) -> Xpub {
715        Xpub {
716            network: sk.network,
717            depth: sk.depth,
718            parent_fingerprint: sk.parent_fingerprint,
719            child_number: sk.child_number,
720            public_key: secp256k1::PublicKey::from_secret_key(secp, &sk.private_key),
721            chain_code: sk.chain_code,
722        }
723    }
724
725    /// Constructs ECDSA compressed public key matching internal public key representation.
726    pub fn to_pub(self) -> CompressedPublicKey { CompressedPublicKey(self.public_key) }
727
728    /// Constructs BIP340 x-only public key for BIP-340 signatures and Taproot use matching
729    /// the internal public key representation.
730    pub fn to_x_only_pub(self) -> XOnlyPublicKey { XOnlyPublicKey::from(self.public_key) }
731
732    /// Attempts to derive an extended public key from a path.
733    ///
734    /// The `path` argument can be any type implementing `AsRef<ChildNumber>`, such as `DerivationPath`, for instance.
735    pub fn derive_pub<C: secp256k1::Verification, P: AsRef<[ChildNumber]>>(
736        &self,
737        secp: &Secp256k1<C>,
738        path: &P,
739    ) -> Result<Xpub, Error> {
740        let mut pk: Xpub = *self;
741        for cnum in path.as_ref() {
742            pk = pk.ckd_pub(secp, *cnum)?
743        }
744        Ok(pk)
745    }
746
747    /// Compute the scalar tweak added to this key to get a child key
748    pub fn ckd_pub_tweak(
749        &self,
750        i: ChildNumber,
751    ) -> Result<(secp256k1::SecretKey, ChainCode), Error> {
752        match i {
753            ChildNumber::Hardened { .. } => Err(Error::CannotDeriveFromHardenedKey),
754            ChildNumber::Normal { index: n } => {
755                let mut hmac_engine: HmacEngine<sha512::Hash> =
756                    HmacEngine::new(&self.chain_code[..]);
757                hmac_engine.input(&self.public_key.serialize()[..]);
758                hmac_engine.input(&n.to_be_bytes());
759
760                let hmac_result: Hmac<sha512::Hash> = Hmac::from_engine(hmac_engine);
761
762                let private_key = secp256k1::SecretKey::from_slice(&hmac_result[..32])?;
763                let chain_code = ChainCode::from_hmac(hmac_result);
764                Ok((private_key, chain_code))
765            }
766        }
767    }
768
769    /// Public->Public child key derivation
770    pub fn ckd_pub<C: secp256k1::Verification>(
771        &self,
772        secp: &Secp256k1<C>,
773        i: ChildNumber,
774    ) -> Result<Xpub, Error> {
775        let (sk, chain_code) = self.ckd_pub_tweak(i)?;
776        let tweaked = self.public_key.add_exp_tweak(secp, &sk.into())?;
777
778        Ok(Xpub {
779            network: self.network,
780            depth: self.depth.checked_add(1).ok_or(Error::MaximumDepthExceeded)?,
781            parent_fingerprint: self.fingerprint(),
782            child_number: i,
783            public_key: tweaked,
784            chain_code,
785        })
786    }
787
788    /// Decoding extended public key from binary data according to BIP 32
789    pub fn decode(data: &[u8]) -> Result<Xpub, Error> {
790        if data.len() != 78 {
791            return Err(Error::WrongExtendedKeyLength(data.len()));
792        }
793
794        let network = if data.starts_with(&VERSION_BYTES_MAINNET_PUBLIC) {
795            NetworkKind::Main
796        } else if data.starts_with(&VERSION_BYTES_TESTNETS_PUBLIC) {
797            NetworkKind::Test
798        } else {
799            let (b0, b1, b2, b3) = (data[0], data[1], data[2], data[3]);
800            return Err(Error::UnknownVersion([b0, b1, b2, b3]));
801        };
802
803        Ok(Xpub {
804            network,
805            depth: data[4],
806            parent_fingerprint: data[5..9]
807                .try_into()
808                .expect("9 - 5 == 4, which is the Fingerprint length"),
809            child_number: u32::from_be_bytes(data[9..13].try_into().expect("4 byte slice")).into(),
810            chain_code: data[13..45]
811                .try_into()
812                .expect("45 - 13 == 32, which is the ChainCode length"),
813            public_key: secp256k1::PublicKey::from_slice(&data[45..78])?,
814        })
815    }
816
817    /// Extended public key binary encoding according to BIP 32
818    pub fn encode(&self) -> [u8; 78] {
819        let mut ret = [0; 78];
820        ret[0..4].copy_from_slice(&match self.network {
821            NetworkKind::Main => VERSION_BYTES_MAINNET_PUBLIC,
822            NetworkKind::Test => VERSION_BYTES_TESTNETS_PUBLIC,
823        });
824        ret[4] = self.depth;
825        ret[5..9].copy_from_slice(&self.parent_fingerprint[..]);
826        ret[9..13].copy_from_slice(&u32::from(self.child_number).to_be_bytes());
827        ret[13..45].copy_from_slice(&self.chain_code[..]);
828        ret[45..78].copy_from_slice(&self.public_key.serialize()[..]);
829        ret
830    }
831
832    /// Returns the HASH160 of the chaincode
833    pub fn identifier(&self) -> XKeyIdentifier {
834        let mut engine = XKeyIdentifier::engine();
835        engine.write_all(&self.public_key.serialize()).expect("engines don't error");
836        XKeyIdentifier::from_engine(engine)
837    }
838
839    /// Returns the first four bytes of the identifier
840    pub fn fingerprint(&self) -> Fingerprint {
841        self.identifier()[0..4].try_into().expect("4 is the fingerprint length")
842    }
843}
844
845impl fmt::Display for Xpriv {
846    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
847        base58::encode_check_to_fmt(fmt, &self.encode()[..])
848    }
849}
850
851impl FromStr for Xpriv {
852    type Err = Error;
853
854    fn from_str(inp: &str) -> Result<Xpriv, Error> {
855        let data = base58::decode_check(inp)?;
856
857        if data.len() != 78 {
858            return Err(InvalidBase58PayloadLengthError { length: data.len() }.into());
859        }
860
861        Xpriv::decode(&data)
862    }
863}
864
865impl fmt::Display for Xpub {
866    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
867        base58::encode_check_to_fmt(fmt, &self.encode()[..])
868    }
869}
870
871impl FromStr for Xpub {
872    type Err = Error;
873
874    fn from_str(inp: &str) -> Result<Xpub, Error> {
875        let data = base58::decode_check(inp)?;
876
877        if data.len() != 78 {
878            return Err(InvalidBase58PayloadLengthError { length: data.len() }.into());
879        }
880
881        Xpub::decode(&data)
882    }
883}
884
885impl From<Xpub> for XKeyIdentifier {
886    fn from(key: Xpub) -> XKeyIdentifier { key.identifier() }
887}
888
889impl From<&Xpub> for XKeyIdentifier {
890    fn from(key: &Xpub) -> XKeyIdentifier { key.identifier() }
891}
892
893/// Decoded base58 data was an invalid length.
894#[derive(Debug, Clone, PartialEq, Eq)]
895pub struct InvalidBase58PayloadLengthError {
896    /// The base58 payload length we got after decoding xpriv/xpub string.
897    pub(crate) length: usize,
898}
899
900impl InvalidBase58PayloadLengthError {
901    /// Returns the invalid payload length.
902    pub fn invalid_base58_payload_length(&self) -> usize { self.length }
903}
904
905impl fmt::Display for InvalidBase58PayloadLengthError {
906    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
907        write!(
908            f,
909            "decoded base58 xpriv/xpub data was an invalid length: {} (expected 78)",
910            self.length
911        )
912    }
913}
914
915#[cfg(feature = "std")]
916impl std::error::Error for InvalidBase58PayloadLengthError {}
917
918#[cfg(test)]
919mod tests {
920    use hex::test_hex_unwrap as hex;
921
922    use super::ChildNumber::{Hardened, Normal};
923    use super::*;
924
925    #[test]
926    fn test_parse_derivation_path() {
927        assert_eq!(DerivationPath::from_str("n/0'/0"), Err(Error::InvalidChildNumberFormat));
928        assert_eq!(DerivationPath::from_str("4/m/5"), Err(Error::InvalidChildNumberFormat));
929        assert_eq!(DerivationPath::from_str("//3/0'"), Err(Error::InvalidChildNumberFormat));
930        assert_eq!(DerivationPath::from_str("0h/0x"), Err(Error::InvalidChildNumberFormat));
931        assert_eq!(
932            DerivationPath::from_str("2147483648"),
933            Err(Error::InvalidChildNumber(2147483648))
934        );
935
936        assert_eq!(DerivationPath::master(), DerivationPath::from_str("").unwrap());
937        assert_eq!(DerivationPath::master(), DerivationPath::default());
938
939        // Acceptable forms for a master path.
940        assert_eq!(DerivationPath::from_str("m").unwrap(), DerivationPath(vec![]));
941        assert_eq!(DerivationPath::from_str("m/").unwrap(), DerivationPath(vec![]));
942        assert_eq!(DerivationPath::from_str("").unwrap(), DerivationPath(vec![]));
943
944        assert_eq!(
945            DerivationPath::from_str("0'"),
946            Ok(vec![ChildNumber::from_hardened_idx(0).unwrap()].into())
947        );
948        assert_eq!(
949            DerivationPath::from_str("0'/1"),
950            Ok(vec![
951                ChildNumber::from_hardened_idx(0).unwrap(),
952                ChildNumber::from_normal_idx(1).unwrap()
953            ]
954            .into())
955        );
956        assert_eq!(
957            DerivationPath::from_str("0h/1/2'"),
958            Ok(vec![
959                ChildNumber::from_hardened_idx(0).unwrap(),
960                ChildNumber::from_normal_idx(1).unwrap(),
961                ChildNumber::from_hardened_idx(2).unwrap(),
962            ]
963            .into())
964        );
965        assert_eq!(
966            DerivationPath::from_str("0'/1/2h/2"),
967            Ok(vec![
968                ChildNumber::from_hardened_idx(0).unwrap(),
969                ChildNumber::from_normal_idx(1).unwrap(),
970                ChildNumber::from_hardened_idx(2).unwrap(),
971                ChildNumber::from_normal_idx(2).unwrap(),
972            ]
973            .into())
974        );
975        let want = DerivationPath::from(vec![
976            ChildNumber::from_hardened_idx(0).unwrap(),
977            ChildNumber::from_normal_idx(1).unwrap(),
978            ChildNumber::from_hardened_idx(2).unwrap(),
979            ChildNumber::from_normal_idx(2).unwrap(),
980            ChildNumber::from_normal_idx(1000000000).unwrap(),
981        ]);
982        assert_eq!(DerivationPath::from_str("0'/1/2'/2/1000000000").unwrap(), want);
983        assert_eq!(DerivationPath::from_str("m/0'/1/2'/2/1000000000").unwrap(), want);
984
985        let s = "0'/50/3'/5/545456";
986        assert_eq!(DerivationPath::from_str(s), s.into_derivation_path());
987        assert_eq!(DerivationPath::from_str(s), s.to_string().into_derivation_path());
988
989        let s = "m/0'/50/3'/5/545456";
990        assert_eq!(DerivationPath::from_str(s), s.into_derivation_path());
991        assert_eq!(DerivationPath::from_str(s), s.to_string().into_derivation_path());
992    }
993
994    #[test]
995    fn test_derivation_path_conversion_index() {
996        let path = DerivationPath::from_str("0h/1/2'").unwrap();
997        let numbers: Vec<ChildNumber> = path.clone().into();
998        let path2: DerivationPath = numbers.into();
999        assert_eq!(path, path2);
1000        assert_eq!(
1001            &path[..2],
1002            &[ChildNumber::from_hardened_idx(0).unwrap(), ChildNumber::from_normal_idx(1).unwrap()]
1003        );
1004        let indexed: DerivationPath = path[..2].into();
1005        assert_eq!(indexed, DerivationPath::from_str("0h/1").unwrap());
1006        assert_eq!(indexed.child(ChildNumber::from_hardened_idx(2).unwrap()), path);
1007    }
1008
1009    fn test_path<C: secp256k1::Signing + secp256k1::Verification>(
1010        secp: &Secp256k1<C>,
1011        network: NetworkKind,
1012        seed: &[u8],
1013        path: DerivationPath,
1014        expected_sk: &str,
1015        expected_pk: &str,
1016    ) {
1017        let mut sk = Xpriv::new_master(network, seed).unwrap();
1018        let mut pk = Xpub::from_priv(secp, &sk);
1019
1020        // Check derivation convenience method for Xpriv
1021        assert_eq!(&sk.derive_priv(secp, &path).unwrap().to_string()[..], expected_sk);
1022
1023        // Check derivation convenience method for Xpub, should error
1024        // appropriately if any ChildNumber is hardened
1025        if path.0.iter().any(|cnum| cnum.is_hardened()) {
1026            assert_eq!(pk.derive_pub(secp, &path), Err(Error::CannotDeriveFromHardenedKey));
1027        } else {
1028            assert_eq!(&pk.derive_pub(secp, &path).unwrap().to_string()[..], expected_pk);
1029        }
1030
1031        // Derive keys, checking hardened and non-hardened derivation one-by-one
1032        for &num in path.0.iter() {
1033            sk = sk.ckd_priv(secp, num).unwrap();
1034            match num {
1035                Normal { .. } => {
1036                    let pk2 = pk.ckd_pub(secp, num).unwrap();
1037                    pk = Xpub::from_priv(secp, &sk);
1038                    assert_eq!(pk, pk2);
1039                }
1040                Hardened { .. } => {
1041                    assert_eq!(pk.ckd_pub(secp, num), Err(Error::CannotDeriveFromHardenedKey));
1042                    pk = Xpub::from_priv(secp, &sk);
1043                }
1044            }
1045        }
1046
1047        // Check result against expected base58
1048        assert_eq!(&sk.to_string()[..], expected_sk);
1049        assert_eq!(&pk.to_string()[..], expected_pk);
1050        // Check decoded base58 against result
1051        let decoded_sk = Xpriv::from_str(expected_sk);
1052        let decoded_pk = Xpub::from_str(expected_pk);
1053        assert_eq!(Ok(sk), decoded_sk);
1054        assert_eq!(Ok(pk), decoded_pk);
1055    }
1056
1057    #[test]
1058    fn test_increment() {
1059        let idx = 9345497; // randomly generated, I promise
1060        let cn = ChildNumber::from_normal_idx(idx).unwrap();
1061        assert_eq!(cn.increment().ok(), Some(ChildNumber::from_normal_idx(idx + 1).unwrap()));
1062        let cn = ChildNumber::from_hardened_idx(idx).unwrap();
1063        assert_eq!(cn.increment().ok(), Some(ChildNumber::from_hardened_idx(idx + 1).unwrap()));
1064
1065        let max = (1 << 31) - 1;
1066        let cn = ChildNumber::from_normal_idx(max).unwrap();
1067        assert_eq!(cn.increment().err(), Some(Error::InvalidChildNumber(1 << 31)));
1068        let cn = ChildNumber::from_hardened_idx(max).unwrap();
1069        assert_eq!(cn.increment().err(), Some(Error::InvalidChildNumber(1 << 31)));
1070
1071        let cn = ChildNumber::from_normal_idx(350).unwrap();
1072        let path = DerivationPath::from_str("42'").unwrap();
1073        let mut iter = path.children_from(cn);
1074        assert_eq!(iter.next(), Some("42'/350".parse().unwrap()));
1075        assert_eq!(iter.next(), Some("42'/351".parse().unwrap()));
1076
1077        let path = DerivationPath::from_str("42'/350'").unwrap();
1078        let mut iter = path.normal_children();
1079        assert_eq!(iter.next(), Some("42'/350'/0".parse().unwrap()));
1080        assert_eq!(iter.next(), Some("42'/350'/1".parse().unwrap()));
1081
1082        let path = DerivationPath::from_str("42'/350'").unwrap();
1083        let mut iter = path.hardened_children();
1084        assert_eq!(iter.next(), Some("42'/350'/0'".parse().unwrap()));
1085        assert_eq!(iter.next(), Some("42'/350'/1'".parse().unwrap()));
1086
1087        let cn = ChildNumber::from_hardened_idx(42350).unwrap();
1088        let path = DerivationPath::from_str("42'").unwrap();
1089        let mut iter = path.children_from(cn);
1090        assert_eq!(iter.next(), Some("42'/42350'".parse().unwrap()));
1091        assert_eq!(iter.next(), Some("42'/42351'".parse().unwrap()));
1092
1093        let cn = ChildNumber::from_hardened_idx(max).unwrap();
1094        let path = DerivationPath::from_str("42'").unwrap();
1095        let mut iter = path.children_from(cn);
1096        assert!(iter.next().is_some());
1097        assert!(iter.next().is_none());
1098    }
1099
1100    #[test]
1101    fn test_vector_1() {
1102        let secp = Secp256k1::new();
1103        let seed = hex!("000102030405060708090a0b0c0d0e0f");
1104
1105        // m
1106        test_path(&secp, NetworkKind::Main, &seed, "m".parse().unwrap(),
1107                  "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi",
1108                  "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8");
1109
1110        // m/0h
1111        test_path(&secp, NetworkKind::Main, &seed, "m/0h".parse().unwrap(),
1112                  "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7",
1113                  "xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw");
1114
1115        // m/0h/1
1116        test_path(&secp, NetworkKind::Main, &seed, "m/0h/1".parse().unwrap(),
1117                   "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs",
1118                   "xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ");
1119
1120        // m/0h/1/2h
1121        test_path(&secp, NetworkKind::Main, &seed, "m/0h/1/2h".parse().unwrap(),
1122                  "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM",
1123                  "xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5");
1124
1125        // m/0h/1/2h/2
1126        test_path(&secp, NetworkKind::Main, &seed, "m/0h/1/2h/2".parse().unwrap(),
1127                  "xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334",
1128                  "xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV");
1129
1130        // m/0h/1/2h/2/1000000000
1131        test_path(&secp, NetworkKind::Main, &seed, "m/0h/1/2h/2/1000000000".parse().unwrap(),
1132                  "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76",
1133                  "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy");
1134    }
1135
1136    #[test]
1137    fn test_vector_2() {
1138        let secp = Secp256k1::new();
1139        let seed = hex!("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542");
1140
1141        // m
1142        test_path(&secp, NetworkKind::Main, &seed, "m".parse().unwrap(),
1143                  "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U",
1144                  "xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB");
1145
1146        // m/0
1147        test_path(&secp, NetworkKind::Main, &seed, "m/0".parse().unwrap(),
1148                  "xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt",
1149                  "xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH");
1150
1151        // m/0/2147483647h
1152        test_path(&secp, NetworkKind::Main, &seed, "m/0/2147483647h".parse().unwrap(),
1153                  "xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9",
1154                  "xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a");
1155
1156        // m/0/2147483647h/1
1157        test_path(&secp, NetworkKind::Main, &seed, "m/0/2147483647h/1".parse().unwrap(),
1158                  "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef",
1159                  "xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon");
1160
1161        // m/0/2147483647h/1/2147483646h
1162        test_path(&secp, NetworkKind::Main, &seed, "m/0/2147483647h/1/2147483646h".parse().unwrap(),
1163                  "xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc",
1164                  "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL");
1165
1166        // m/0/2147483647h/1/2147483646h/2
1167        test_path(&secp, NetworkKind::Main, &seed, "m/0/2147483647h/1/2147483646h/2".parse().unwrap(),
1168                  "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j",
1169                  "xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt");
1170    }
1171
1172    #[test]
1173    fn test_vector_3() {
1174        let secp = Secp256k1::new();
1175        let seed = hex!("4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be");
1176
1177        // m
1178        test_path(&secp, NetworkKind::Main, &seed, "m".parse().unwrap(),
1179                  "xprv9s21ZrQH143K25QhxbucbDDuQ4naNntJRi4KUfWT7xo4EKsHt2QJDu7KXp1A3u7Bi1j8ph3EGsZ9Xvz9dGuVrtHHs7pXeTzjuxBrCmmhgC6",
1180                  "xpub661MyMwAqRbcEZVB4dScxMAdx6d4nFc9nvyvH3v4gJL378CSRZiYmhRoP7mBy6gSPSCYk6SzXPTf3ND1cZAceL7SfJ1Z3GC8vBgp2epUt13");
1181
1182        // m/0h
1183        test_path(&secp, NetworkKind::Main, &seed, "m/0h".parse().unwrap(),
1184                  "xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L",
1185                  "xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y");
1186    }
1187
1188    #[test]
1189    #[cfg(feature = "serde")]
1190    pub fn encode_decode_childnumber() {
1191        serde_round_trip!(ChildNumber::from_normal_idx(0).unwrap());
1192        serde_round_trip!(ChildNumber::from_normal_idx(1).unwrap());
1193        serde_round_trip!(ChildNumber::from_normal_idx((1 << 31) - 1).unwrap());
1194        serde_round_trip!(ChildNumber::from_hardened_idx(0).unwrap());
1195        serde_round_trip!(ChildNumber::from_hardened_idx(1).unwrap());
1196        serde_round_trip!(ChildNumber::from_hardened_idx((1 << 31) - 1).unwrap());
1197    }
1198
1199    #[test]
1200    #[cfg(feature = "serde")]
1201    pub fn encode_fingerprint_chaincode() {
1202        use serde_json;
1203        let fp = Fingerprint::from([1u8, 2, 3, 42]);
1204        #[rustfmt::skip]
1205        let cc = ChainCode::from(
1206            [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]
1207        );
1208
1209        serde_round_trip!(fp);
1210        serde_round_trip!(cc);
1211
1212        assert_eq!("\"0102032a\"", serde_json::to_string(&fp).unwrap());
1213        assert_eq!(
1214            "\"0102030405060708090001020304050607080900010203040506070809000102\"",
1215            serde_json::to_string(&cc).unwrap()
1216        );
1217        assert_eq!("0102032a", fp.to_string());
1218        assert_eq!(
1219            "0102030405060708090001020304050607080900010203040506070809000102",
1220            cc.to_string()
1221        );
1222    }
1223
1224    #[test]
1225    fn fmt_child_number() {
1226        assert_eq!("000005h", &format!("{:#06}", ChildNumber::from_hardened_idx(5).unwrap()));
1227        assert_eq!("5h", &format!("{:#}", ChildNumber::from_hardened_idx(5).unwrap()));
1228        assert_eq!("000005'", &format!("{:06}", ChildNumber::from_hardened_idx(5).unwrap()));
1229        assert_eq!("5'", &format!("{}", ChildNumber::from_hardened_idx(5).unwrap()));
1230        assert_eq!("42", &format!("{}", ChildNumber::from_normal_idx(42).unwrap()));
1231        assert_eq!("000042", &format!("{:06}", ChildNumber::from_normal_idx(42).unwrap()));
1232    }
1233
1234    #[test]
1235    #[should_panic(expected = "Secp256k1(InvalidSecretKey)")]
1236    fn schnorr_broken_privkey_zeros() {
1237        /* this is how we generate key:
1238        let mut sk = secp256k1::key::ONE_KEY;
1239
1240        let zeros = [0u8; 32];
1241        unsafe {
1242            sk.as_mut_ptr().copy_from(zeros.as_ptr(), 32);
1243        }
1244
1245        let xpriv = Xpriv {
1246            network: NetworkKind::Main,
1247            depth: 0,
1248            parent_fingerprint: Default::default(),
1249            child_number: ChildNumber::Normal { index: 0 },
1250            private_key: sk,
1251            chain_code: ChainCode::from([0u8; 32])
1252        };
1253
1254        println!("{}", xpriv);
1255         */
1256
1257        // Xpriv having secret key set to all zeros
1258        let xpriv_str = "xprv9s21ZrQH143K24Mfq5zL5MhWK9hUhhGbd45hLXo2Pq2oqzMMo63oStZzF93Y5wvzdUayhgkkFoicQZcP3y52uPPxFnfoLZB21Teqt1VvEHx";
1259        Xpriv::from_str(xpriv_str).unwrap();
1260    }
1261
1262    #[test]
1263    #[should_panic(expected = "Secp256k1(InvalidSecretKey)")]
1264    fn schnorr_broken_privkey_ffs() {
1265        // Xpriv having secret key set to all 0xFF's
1266        let xpriv_str = "xprv9s21ZrQH143K24Mfq5zL5MhWK9hUhhGbd45hLXo2Pq2oqzMMo63oStZzFAzHGBP2UuGCqWLTAPLcMtD9y5gkZ6Eq3Rjuahrv17fENZ3QzxW";
1267        Xpriv::from_str(xpriv_str).unwrap();
1268    }
1269}