sapio_bitcoin/util/
bip32.rs

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