hd-wallet 0.7.0

HD wallets derivation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
//! ![License](https://img.shields.io/crates/l/hd-wallet.svg)
//! [![Docs](https://docs.rs/hd-wallet/badge.svg)](https://docs.rs/hd-wallet)
//! [![Crates io](https://img.shields.io/crates/v/hd-wallet.svg)](https://crates.io/crates/hd-wallet)
//! [![Discord](https://img.shields.io/discord/905194001349627914?logo=discord&logoColor=ffffff&label=Discord)](https://discordapp.com/channels/905194001349627914/1285268686147424388)
//!
//! # HD wallets derivation
//!
//! This crate supports the following HD derivations:
//! * [SLIP10][slip10-spec] (compatible with [BIP32][bip32-spec]), see [`Slip10`]
//! * Non-standard [`Edwards`] derivation for ed25519 curve
//!
//! To perform HD derivation, use [`HdWallet`] trait.
//!
//! ### Example: SLIP10 derivation
//!
//! Derive a master key from the seed, and then derive a child key m/1<sub>H</sub>/10:
//! ```rust
//! use hd_wallet::{slip10, curves::Secp256k1};
//!
//! let seed = b"16-64 bytes of high entropy".as_slice();
//! let master_key = slip10::derive_master_key::<Secp256k1>(seed)?;
//! let master_key_pair = hd_wallet::ExtendedKeyPair::from(master_key);
//!
//! let child_key_pair = slip10::derive_child_key_pair_with_path(
//!     &master_key_pair,
//!     [1 + hd_wallet::H, 10],
//! );
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ### Example: via [HdWallet] trait
//!
//! [`HdWallet`] trait generalizes HD derivation algorithm, you can use it with generics:
//! ```rust
//! use hd_wallet::{Slip10, curves::Secp256r1};
//!
//! fn derive_using_generic_algo<E: generic_ec::Curve, Hd: hd_wallet::HdWallet<E>>(
//!     master_key: hd_wallet::ExtendedKeyPair<E>,
//! ) -> hd_wallet::ExtendedKeyPair<E>
//! {
//!     Hd::derive_child_key_pair_with_path(
//!         &master_key,
//!         [1 + hd_wallet::H, 10],
//!     )
//! }
//!
//! // Use it with any HD derivation:
//! let seed = b"16-64 bytes of high entropy".as_slice();
//! let master_key = hd_wallet::slip10::derive_master_key(seed)?;
//! let master_key_pair = hd_wallet::ExtendedKeyPair::from(master_key);
//! let child_key = derive_using_generic_algo::<Secp256r1, Slip10>(master_key_pair);
//!
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ### Features
//! * `curve-secp256k1`, `curve-secp256r1`, `curve-ed25519`, `curve-stark` add curve implementation
//!   into the crate [curves] module
//! * `all-curves` adds all curves listed above
//! * `slip10`, `edwards`, `stark` add [`slip10`], [`edwards`], and [`stark`] HD derivations respectively
//! * `serde` adds `serde::{Serialize, Deserialize}` traits implementation to the types in the library
//!
//! ## Join us in Discord!
//! Feel free to reach out to us [in Discord](https://discordapp.com/channels/905194001349627914/1285268686147424388)!
//!
//! [slip10-spec]: https://github.com/satoshilabs/slips/blob/master/slip-0010.md
//! [bip32-spec]: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki

#![no_std]
#![forbid(missing_docs, unsafe_code)]
#![cfg_attr(not(test), forbid(unused_crate_dependencies))]

use core::ops;

use generic_ec::{Curve, Point, Scalar, SecretScalar};

pub use generic_ec::curves;

#[cfg(feature = "edwards")]
pub mod edwards;
pub mod errors;
#[cfg(feature = "slip10")]
pub mod slip10;
#[cfg(feature = "stark")]
pub mod stark;

#[cfg(feature = "edwards")]
pub use edwards::Edwards;
#[cfg(feature = "slip10")]
pub use slip10::Slip10;
#[cfg(feature = "stark")]
pub use stark::Stark;

/// Beginning of hardened child indexes
///
/// $H = 2^{31}$ defines the range of hardened indexes. All indexes $i$ such that $H \le i$ are hardened.
///
/// ## Example
/// Derive a child key with a path m/1<sub>H</sub>
/// ```rust
/// use hd_wallet::HdWallet;
///
/// # let seed = b"do not use this seed in prod :)".as_slice();
/// # let master_key = hd_wallet::slip10::derive_master_key::<hd_wallet::curves::Secp256k1>(seed)?;
/// # let master_key_pair = hd_wallet::ExtendedKeyPair::from(master_key);
/// #
/// let hardened_child = hd_wallet::Slip10::derive_child_key_pair(
///     &master_key_pair,
///     1 + hd_wallet::H,
/// );
/// #
/// # Ok::<(), hd_wallet::errors::InvalidLength>(())
/// ```
pub const H: u32 = 1 << 31;

/// Child index, whether hardened or not
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(into = "u32"))]
#[cfg_attr(feature = "serde", derive(serde::Deserialize), serde(from = "u32"))]
pub enum ChildIndex {
    /// Hardened index
    Hardened(HardenedIndex),
    /// Non-hardened index
    NonHardened(NonHardenedIndex),
}

/// Child index in range $2^{31} \le i < 2^{32}$ corresponding to a hardened wallet
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(into = "u32"))]
#[cfg_attr(feature = "serde", derive(serde::Deserialize), serde(try_from = "u32"))]
pub struct HardenedIndex(u32);

/// Child index in range $0 \le i < 2^{31}$ corresponding to a non-hardened wallet
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(into = "u32"))]
#[cfg_attr(feature = "serde", derive(serde::Deserialize), serde(try_from = "u32"))]
pub struct NonHardenedIndex(u32);

/// Extended public key
#[derive(Clone, Copy, Debug)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(bound = "")
)]
pub struct ExtendedPublicKey<E: Curve> {
    /// The public key that can be used for signature verification
    pub public_key: Point<E>,
    /// A chain code that is used to derive child keys
    pub chain_code: ChainCode,
}

/// Extended secret key
#[derive(Clone, Debug)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(bound = "")
)]
pub struct ExtendedSecretKey<E: Curve> {
    /// The secret key that can be used for signing
    pub secret_key: SecretScalar<E>,
    /// A chain code that is used to derive child keys
    pub chain_code: ChainCode,
}

/// Pair of extended secret and public keys
#[derive(Clone, Debug)]
pub struct ExtendedKeyPair<E: Curve> {
    public_key: ExtendedPublicKey<E>,
    secret_key: ExtendedSecretKey<E>,
}

/// A shift that can be applied to parent key to obtain a child key
///
/// It contains an already derived child public key as it needs to be derived
/// in process of calculating the shift value
#[derive(Clone, Copy, Debug)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(bound = "")
)]
pub struct DerivedShift<E: Curve> {
    /// Derived shift
    pub shift: Scalar<E>,
    /// Derived child extended public key
    pub child_public_key: ExtendedPublicKey<E>,
}

/// Chain code of extended key as defined in SLIP-10
pub type ChainCode = [u8; 32];

impl HardenedIndex {
    /// The smallest possible value of hardened index. Equals to $2^{31}$
    pub const MIN: Self = Self(H);
    /// The largest possible value of hardened index. Equals to $2^{32} - 1$
    pub const MAX: Self = Self(u32::MAX);
}
impl NonHardenedIndex {
    /// The smallest possible value of non-hardened index. Equals to $0$
    pub const MIN: Self = Self(0);
    /// The largest possible value of non-hardened index. Equals to $2^{31} - 1$
    pub const MAX: Self = Self(H - 1);
}
impl ops::Deref for HardenedIndex {
    type Target = u32;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl ops::Deref for NonHardenedIndex {
    type Target = u32;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl ops::Deref for ChildIndex {
    type Target = u32;
    fn deref(&self) -> &Self::Target {
        match self {
            Self::Hardened(i) => i,
            Self::NonHardened(i) => i,
        }
    }
}
impl From<u32> for ChildIndex {
    fn from(value: u32) -> Self {
        match value {
            H.. => Self::Hardened(HardenedIndex(value)),
            _ => Self::NonHardened(NonHardenedIndex(value)),
        }
    }
}
impl TryFrom<u32> for HardenedIndex {
    type Error = errors::OutOfRange;
    fn try_from(value: u32) -> Result<Self, Self::Error> {
        match ChildIndex::from(value) {
            ChildIndex::Hardened(v) => Ok(v),
            _ => Err(errors::OutOfRange),
        }
    }
}
impl TryFrom<u32> for NonHardenedIndex {
    type Error = errors::OutOfRange;
    fn try_from(value: u32) -> Result<Self, Self::Error> {
        match ChildIndex::from(value) {
            ChildIndex::NonHardened(v) => Ok(v),
            _ => Err(errors::OutOfRange),
        }
    }
}
impl From<ChildIndex> for u32 {
    fn from(value: ChildIndex) -> Self {
        match value {
            ChildIndex::Hardened(v) => v.0,
            ChildIndex::NonHardened(v) => v.0,
        }
    }
}
impl From<HardenedIndex> for u32 {
    fn from(value: HardenedIndex) -> Self {
        value.0
    }
}
impl From<NonHardenedIndex> for u32 {
    fn from(value: NonHardenedIndex) -> Self {
        value.0
    }
}
impl core::str::FromStr for ChildIndex {
    type Err = core::num::ParseIntError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse::<u32>().map(Into::into)
    }
}
impl core::str::FromStr for HardenedIndex {
    type Err = errors::ParseChildIndexError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let index = s
            .parse::<u32>()
            .map_err(errors::ParseChildIndexError::ParseInt)?;
        HardenedIndex::try_from(index).map_err(errors::ParseChildIndexError::IndexNotInRange)
    }
}
impl core::str::FromStr for NonHardenedIndex {
    type Err = errors::ParseChildIndexError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let index = s
            .parse::<u32>()
            .map_err(errors::ParseChildIndexError::ParseInt)?;
        NonHardenedIndex::try_from(index).map_err(errors::ParseChildIndexError::IndexNotInRange)
    }
}

impl<E: Curve> From<&ExtendedSecretKey<E>> for ExtendedPublicKey<E> {
    fn from(sk: &ExtendedSecretKey<E>) -> Self {
        ExtendedPublicKey {
            public_key: Point::generator() * &sk.secret_key,
            chain_code: sk.chain_code,
        }
    }
}

impl<E: Curve> From<ExtendedSecretKey<E>> for ExtendedKeyPair<E> {
    fn from(secret_key: ExtendedSecretKey<E>) -> Self {
        Self {
            public_key: (&secret_key).into(),
            secret_key,
        }
    }
}

impl<E: Curve> ExtendedKeyPair<E> {
    /// Returns chain code of the key
    pub fn chain_code(&self) -> &ChainCode {
        debug_assert_eq!(self.public_key.chain_code, self.secret_key.chain_code);
        &self.public_key.chain_code
    }

    /// Returns extended public key
    pub fn public_key(&self) -> &ExtendedPublicKey<E> {
        &self.public_key
    }

    /// Returns extended secret key
    pub fn secret_key(&self) -> &ExtendedSecretKey<E> {
        &self.secret_key
    }
}

#[cfg(feature = "serde")]
impl<E: Curve> serde::Serialize for ExtendedKeyPair<E> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.secret_key.serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de, E: Curve> serde::Deserialize<'de> for ExtendedKeyPair<E> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let secret_key = ExtendedSecretKey::<E>::deserialize(deserializer)?;
        Ok(secret_key.into())
    }
}

/// * `$t` - type to monomorphise for, like `Slip10` or `Edwards`
/// * `$m` - current module, module where these functions will appear. Used in doc
///   tests only
/// * `$e` - curve supported by this HD derivation, used in doc tests only
#[cfg(any(feature = "slip10", feature = "edwards", feature = "stark"))]
macro_rules! create_aliases {
    ($t:ty, $m:expr) => { $crate::create_aliases!($t, $m, hd_wallet::curves::Secp256k1); };
    ($t:ty, $m:expr, $e:ty) => {
        /// Derives a shift for non-hardened child
        ///
        #[doc = concat!("Alias to [`<", stringify!($t), " as DeriveShift<E>>::derive_public_shift`](crate::DeriveShift::derive_public_shift)")]
        pub fn derive_public_shift<E>(
            parent_public_key: &crate::ExtendedPublicKey<E>,
            child_index: crate::NonHardenedIndex,
        ) -> crate::DerivedShift<E>
        where
            E: generic_ec::Curve,
            $t: crate::DeriveShift<E>,
        {
            <$t as crate::DeriveShift<E>>::derive_public_shift(parent_public_key, child_index)
        }

        /// Derive a shift for hardened child
        ///
        #[doc = concat!("Alias to [`<", stringify!($t), " as DeriveShift<E>>::derive_hardened_shift`](crate::DeriveShift::derive_hardened_shift)")]
        pub fn derive_hardened_shift<E>(
            parent_key: &crate::ExtendedKeyPair<E>,
            child_index: crate::HardenedIndex,
        ) -> crate::DerivedShift<E>
        where
            E: generic_ec::Curve,
            $t: crate::DeriveShift<E>,
        {
            <$t as crate::DeriveShift<E>>::derive_hardened_shift(parent_key, child_index)
        }

        /// Derives child extended public key from parent extended public key
        ///
        #[doc = concat!("Alias to [`<", stringify!($t), " as HdWallet<E>>::derive_child_public_key`](crate::HdWallet::derive_child_public_key)")]
        ///
        /// ### Example
        /// Derive a master public key m/1
        /// ```rust,no_run
        #[doc = concat!( "# type E = ", stringify!($e), ";" )]
        /// # let seed = b"do not use this seed :)".as_slice();
        /// # let master_key: hd_wallet::ExtendedSecretKey<E> = todo!();
        /// # let master_public_key = hd_wallet::ExtendedPublicKey::from(&master_key);
        /// #
        #[doc = concat!("let derived_key = hd_wallet::", stringify!($m), "::derive_child_public_key(")]
        ///     &master_public_key,
        ///     1.try_into()?,
        /// );
        /// # Ok::<(), Box<dyn std::error::Error>>(())
        /// ```
        pub fn derive_child_public_key<E>(
            parent_public_key: &crate::ExtendedPublicKey<E>,
            child_index: crate::NonHardenedIndex,
        ) -> crate::ExtendedPublicKey<E>
        where
            E: generic_ec::Curve,
            $t: crate::HdWallet<E>,
        {
            <$t as crate::HdWallet<E>>::derive_child_public_key(parent_public_key, child_index)
        }

        /// Derives child key pair (extended secret key + public key) from parent key pair
        ///
        #[doc = concat!("Alias to [`<", stringify!($t), " as HdWallet<E>>::derive_child_key_pair`](crate::HdWallet::derive_child_key_pair)")]
        ///
        /// ### Example
        /// Derive child key m/1<sub>H</sub> from master key
        /// ```rust,no_run
        #[doc = concat!( "# type E = ", stringify!($e), ";" )]
        /// # let seed = b"do not use this seed :)".as_slice();
        /// # let master_key: hd_wallet::ExtendedSecretKey<E> = todo!();
        /// # let master_key_pair = hd_wallet::ExtendedKeyPair::from(master_key);
        /// #
        #[doc = concat!("let derived_key = hd_wallet::", stringify!($m), "::derive_child_key_pair(")]
        ///     &master_key_pair,
        ///     1 + hd_wallet::H,
        /// );
        /// # Ok::<(), Box<dyn std::error::Error>>(())
        /// ```
        pub fn derive_child_key_pair<E>(
            parent_key: &crate::ExtendedKeyPair<E>,
            child_index: impl Into<crate::ChildIndex>,
        ) -> crate::ExtendedKeyPair<E>
        where
            E: generic_ec::Curve,
            $t: crate::HdWallet<E>,
        {
            <$t as crate::HdWallet<E>>::derive_child_key_pair(parent_key, child_index)
        }

        /// Derives a child key pair with specified derivation path from parent key pair
        ///
        /// Derivation path is a fallible iterator that yields child indexes. If iterator
        /// yields an error, it's propagated to the caller.
        ///
        /// Returns:
        /// * `Ok(child_key_pair)` if derivation was successful
        /// * `Err(index_err)` if path contained `Err(index_err)`
        ///
        #[doc = concat!("Alias to [`<", stringify!($t), " as HdWallet<E>>::try_derive_child_key_pair_with_path`](crate::HdWallet::try_derive_child_key_pair_with_path)")]
        ///
        /// ### Example
        /// Parse a path from the string and derive a child without extra allocations:
        /// ```rust,no_run
        /// use hd_wallet::HdWallet;
        #[doc = concat!( "# type E = ", stringify!($e), ";" )]
        /// # let seed = b"16-64 bytes of high entropy".as_slice();
        /// # let master_key: hd_wallet::ExtendedSecretKey<E> = todo!();
        /// # let master_key_pair = hd_wallet::ExtendedKeyPair::from(master_key);
        ///
        /// let path = "1/10/2";
        /// let child_indexes = path.split('/').map(str::parse::<u32>);
        #[doc = concat!("let child_key = hd_wallet::", stringify!($m), "::try_derive_child_key_pair_with_path(")]
        ///     &master_key_pair,
        ///     child_indexes,
        /// )?;
        /// # Ok::<_, Box<dyn std::error::Error>>(())
        /// ```
        pub fn try_derive_child_key_pair_with_path<E, Err>(
            parent_key: &crate::ExtendedKeyPair<E>,
            path: impl IntoIterator<Item = Result<impl Into<crate::ChildIndex>, Err>>,
        ) -> Result<crate::ExtendedKeyPair<E>, Err>
        where
            E: generic_ec::Curve,
            $t: crate::HdWallet<E>,
        {
            <$t as crate::HdWallet<E>>::try_derive_child_key_pair_with_path(parent_key, path)
        }
        /// Derives a child key pair with specified derivation path from parent key pair
        ///
        /// Derivation path is an iterator that yields child indexes.
        ///
        /// If derivation path is empty, `parent_key` is returned
        ///
        #[doc = concat!("Alias to [`<", stringify!($t), " as HdWallet<E>>::derive_child_key_pair_with_path`](crate::HdWallet::derive_child_key_pair_with_path)")]
        ///
        /// ### Example
        /// Derive a child key with path m/1/10/1<sub>H</sub>
        /// ```rust,no_run
        /// use hd_wallet::HdWallet;
        #[doc = concat!( "# type E = ", stringify!($e), ";" )]
        /// # let seed = b"16-64 bytes of high entropy".as_slice();
        /// # let master_key: hd_wallet::ExtendedSecretKey<E> = todo!();
        /// # let master_key_pair = hd_wallet::ExtendedKeyPair::from(master_key);
        ///
        #[doc = concat!("let child_key = hd_wallet::", stringify!($m), "::derive_child_key_pair_with_path(")]
        ///     &master_key_pair,
        ///     [1, 10, 1 + hd_wallet::H],
        /// );
        /// # Ok::<(), Box<dyn std::error::Error>>(())
        /// ```
        pub fn derive_child_key_pair_with_path<E>(
            parent_key: &crate::ExtendedKeyPair<E>,
            path: impl IntoIterator<Item = impl Into<crate::ChildIndex>>,
        ) -> crate::ExtendedKeyPair<E>
        where
            E: generic_ec::Curve,
            $t: crate::HdWallet<E>,
        {
            <$t as crate::HdWallet<E>>::derive_child_key_pair_with_path(parent_key, path)
        }

        /// Derives a child public key with specified derivation path
        ///
        /// Derivation path is a fallible iterator that yields child indexes. If iterator
        /// yields an error, it's propagated to the caller.
        ///
        /// Returns:
        /// * `Ok(child_pk)` if derivation was successful
        /// * `Err(index_err)` if path contained `Err(index_err)`
        ///
        #[doc = concat!("Alias to [`<", stringify!($t), " as HdWallet<E>>::try_derive_child_public_key_with_path`](crate::HdWallet::try_derive_child_public_key_with_path)")]
        ///
        /// ### Example
        /// Parse a path from the string and derive a child without extra allocations:
        /// ```rust,no_run
        /// use hd_wallet::HdWallet;
        #[doc = concat!( "# type E = ", stringify!($e), ";" )]
        /// # let seed = b"16-64 bytes of high entropy".as_slice();
        /// # let master_key: hd_wallet::ExtendedSecretKey<E> = todo!();
        /// # let master_public_key = hd_wallet::ExtendedPublicKey::from(&master_key);
        ///
        /// let path = "1/10/2";
        /// let child_indexes = path.split('/').map(str::parse);
        #[doc = concat!("let child_key = hd_wallet::", stringify!($m), "::try_derive_child_public_key_with_path(")]
        ///     &master_public_key,
        ///     child_indexes,
        /// )?;
        /// # Ok::<_, Box<dyn std::error::Error>>(())
        /// ```
        pub fn try_derive_child_public_key_with_path<E, Err>(
            parent_public_key: &crate::ExtendedPublicKey<E>,
            path: impl IntoIterator<Item = Result<crate::NonHardenedIndex, Err>>,
        ) -> Result<crate::ExtendedPublicKey<E>, Err>
        where
            E: generic_ec::Curve,
            $t: crate::HdWallet<E>,
        {
            <$t as crate::HdWallet<E>>::try_derive_child_public_key_with_path(parent_public_key, path)
        }

        /// Derives a child public key with specified derivation path
        ///
        /// Derivation path is an iterator that yields child indexes.
        ///
        /// If derivation path is empty, `parent_public_key` is returned
        ///
        #[doc = concat!("Alias to [`<", stringify!($t), " as HdWallet<E>>::derive_child_public_key_with_path`](crate::HdWallet::derive_child_public_key_with_path)")]
        ///
        /// ### Example
        /// Derive a child key with path m/1/10
        /// ```rust,no_run
        /// use hd_wallet::HdWallet;
        #[doc = concat!( "# type E = ", stringify!($e), ";" )]
        /// # let seed = b"16-64 bytes of high entropy".as_slice();
        /// # let master_key: hd_wallet::ExtendedSecretKey<E> = todo!();
        /// # let master_public_key = hd_wallet::ExtendedPublicKey::from(&master_key);
        ///
        #[doc = concat!("let child_key = hd_wallet::", stringify!($m), "::derive_child_public_key_with_path(")]
        ///     &master_public_key,
        ///     [1.try_into()?, 10.try_into()?],
        /// );
        /// # Ok::<(), Box<dyn std::error::Error>>(())
        /// ```
        pub fn derive_child_public_key_with_path<E>(
            parent_public_key: &crate::ExtendedPublicKey<E>,
            path: impl IntoIterator<Item = crate::NonHardenedIndex>,
        ) -> crate::ExtendedPublicKey<E>
        where
            E: generic_ec::Curve,
            $t: crate::HdWallet<E>,
        {
            <$t as crate::HdWallet<E>>::derive_child_public_key_with_path(parent_public_key, path)
        }
    };
}
#[cfg(any(feature = "slip10", feature = "edwards", feature = "stark"))]
pub(crate) use create_aliases;

/// HD derivation
pub trait HdWallet<E: Curve>: DeriveShift<E> {
    /// Derives child extended public key from parent extended public key
    ///
    /// ### Example
    /// Derive a master public key m/1
    /// ```rust
    /// use hd_wallet::HdWallet;
    ///
    /// # let seed = b"do not use this seed :)".as_slice();
    /// # let master_key = hd_wallet::slip10::derive_master_key::<hd_wallet::curves::Secp256k1>(seed)?;
    /// # let master_public_key = hd_wallet::ExtendedPublicKey::from(&master_key);
    /// #
    /// let derived_key = hd_wallet::Slip10::derive_child_public_key(
    ///     &master_public_key,
    ///     1.try_into()?,
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    fn derive_child_public_key(
        parent_public_key: &ExtendedPublicKey<E>,
        child_index: NonHardenedIndex,
    ) -> ExtendedPublicKey<E> {
        Self::derive_public_shift(parent_public_key, child_index).child_public_key
    }

    /// Derives child key pair (extended secret key + public key) from parent key pair
    ///
    /// ### Example
    /// Derive child key m/1<sub>H</sub> from master key
    /// ```rust
    /// use hd_wallet::HdWallet;
    ///
    /// # let seed = b"do not use this seed :)".as_slice();
    /// # let master_key = hd_wallet::slip10::derive_master_key::<hd_wallet::curves::Secp256k1>(seed)?;
    /// # let master_key_pair = hd_wallet::ExtendedKeyPair::from(master_key);
    /// #
    /// let derived_key = hd_wallet::Slip10::derive_child_key_pair(
    ///     &master_key_pair,
    ///     1 + hd_wallet::H,
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    fn derive_child_key_pair(
        parent_key: &ExtendedKeyPair<E>,
        child_index: impl Into<ChildIndex>,
    ) -> ExtendedKeyPair<E> {
        let child_index = child_index.into();
        let shift = match child_index {
            ChildIndex::Hardened(i) => Self::derive_hardened_shift(parent_key, i),
            ChildIndex::NonHardened(i) => Self::derive_public_shift(&parent_key.public_key, i),
        };
        let mut child_sk = &parent_key.secret_key.secret_key + shift.shift;
        let child_sk = SecretScalar::new(&mut child_sk);
        ExtendedKeyPair {
            secret_key: ExtendedSecretKey {
                secret_key: child_sk,
                chain_code: shift.child_public_key.chain_code,
            },
            public_key: shift.child_public_key,
        }
    }

    /// Derives a child key pair with specified derivation path from parent key pair
    ///
    /// Derivation path is a fallible iterator that yields child indexes. If iterator
    /// yields an error, it's propagated to the caller.
    ///
    /// Returns:
    /// * `Ok(child_key_pair)` if derivation was successful
    /// * `Err(index_err)` if path contained `Err(index_err)`
    ///
    /// ### Example
    /// Parse a path from the string and derive a child without extra allocations:
    /// ```rust
    /// use hd_wallet::HdWallet;
    /// # let seed = b"16-64 bytes of high entropy".as_slice();
    /// # let master_key = hd_wallet::slip10::derive_master_key::<hd_wallet::curves::Secp256k1>(seed)?;
    /// # let master_key_pair = hd_wallet::ExtendedKeyPair::from(master_key);
    ///
    /// let path = "1/10/2";
    /// let child_indexes = path.split('/').map(str::parse::<u32>);
    /// let child_key = hd_wallet::Slip10::try_derive_child_key_pair_with_path(
    ///     &master_key_pair,
    ///     child_indexes,
    /// )?;
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    fn try_derive_child_key_pair_with_path<Err>(
        parent_key: &ExtendedKeyPair<E>,
        path: impl IntoIterator<Item = Result<impl Into<ChildIndex>, Err>>,
    ) -> Result<ExtendedKeyPair<E>, Err> {
        let mut derived_key = parent_key.clone();
        for child_index in path {
            derived_key = Self::derive_child_key_pair(&derived_key, child_index?);
        }
        Ok(derived_key)
    }

    /// Derives a child key pair with specified derivation path from parent key pair
    ///
    /// Derivation path is an iterator that yields child indexes.
    ///
    /// If derivation path is empty, `parent_key` is returned
    ///
    /// ### Example
    /// Derive a child key with path m/1/10/1<sub>H</sub>
    /// ```rust
    /// use hd_wallet::HdWallet;
    /// # let seed = b"16-64 bytes of high entropy".as_slice();
    /// # let master_key = hd_wallet::slip10::derive_master_key::<hd_wallet::curves::Secp256k1>(seed)?;
    /// # let master_key_pair = hd_wallet::ExtendedKeyPair::from(master_key);
    ///
    /// let child_key = hd_wallet::Slip10::derive_child_key_pair_with_path(
    ///     &master_key_pair,
    ///     [1, 10, 1 + hd_wallet::H],
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    fn derive_child_key_pair_with_path(
        parent_key: &ExtendedKeyPair<E>,
        path: impl IntoIterator<Item = impl Into<ChildIndex>>,
    ) -> ExtendedKeyPair<E> {
        let result = Self::try_derive_child_key_pair_with_path(
            parent_key,
            path.into_iter().map(Ok::<_, core::convert::Infallible>),
        );
        match result {
            Ok(key) => key,
            Err(err) => match err {},
        }
    }

    /// Derives a child public key with specified derivation path
    ///
    /// Derivation path is a fallible iterator that yields child indexes. If iterator
    /// yields an error, it's propagated to the caller.
    ///
    /// Returns:
    /// * `Ok(child_pk)` if derivation was successful
    /// * `Err(index_err)` if path contained `Err(index_err)`
    ///
    /// ### Example
    /// Parse a path from the string and derive a child without extra allocations:
    /// ```rust
    /// use hd_wallet::HdWallet;
    /// # let seed = b"16-64 bytes of high entropy".as_slice();
    /// # let master_key = hd_wallet::slip10::derive_master_key::<hd_wallet::curves::Secp256k1>(seed)?;
    /// # let master_public_key = hd_wallet::ExtendedPublicKey::from(&master_key);
    ///
    /// let path = "1/10/2";
    /// let child_indexes = path.split('/').map(str::parse);
    /// let child_key = hd_wallet::Slip10::try_derive_child_public_key_with_path(
    ///     &master_public_key,
    ///     child_indexes,
    /// )?;
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    fn try_derive_child_public_key_with_path<Err>(
        parent_public_key: &ExtendedPublicKey<E>,
        path: impl IntoIterator<Item = Result<NonHardenedIndex, Err>>,
    ) -> Result<ExtendedPublicKey<E>, Err> {
        let mut derived_key = *parent_public_key;
        for child_index in path {
            derived_key = Self::derive_child_public_key(&derived_key, child_index?);
        }
        Ok(derived_key)
    }

    /// Derives a child public key with specified derivation path
    ///
    /// Derivation path is an iterator that yields child indexes.
    ///
    /// If derivation path is empty, `parent_public_key` is returned
    ///
    /// ### Example
    /// Derive a child key with path m/1/10
    /// ```rust
    /// use hd_wallet::HdWallet;
    /// # let seed = b"16-64 bytes of high entropy".as_slice();
    /// # let master_key = hd_wallet::slip10::derive_master_key::<hd_wallet::curves::Secp256k1>(seed)?;
    /// # let master_public_key = hd_wallet::ExtendedPublicKey::from(&master_key);
    ///
    /// let child_key = hd_wallet::Slip10::derive_child_public_key_with_path(
    ///     &master_public_key,
    ///     [1.try_into()?, 10.try_into()?],
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    fn derive_child_public_key_with_path(
        parent_public_key: &ExtendedPublicKey<E>,
        path: impl IntoIterator<Item = NonHardenedIndex>,
    ) -> ExtendedPublicKey<E> {
        let result = Self::try_derive_child_public_key_with_path(
            parent_public_key,
            path.into_iter().map(Ok::<_, core::convert::Infallible>),
        );
        match result {
            Ok(key) => key,
            Err(err) => match err {},
        }
    }
}

impl<E: Curve, S: DeriveShift<E>> HdWallet<E> for S {}

/// Core functionality of HD wallet derivation, everything is defined on top of it
pub trait DeriveShift<E: Curve> {
    /// Derives a shift for non-hardened child
    ///
    /// We support only HD derivations that are always defined. This function may not panic.
    fn derive_public_shift(
        parent_public_key: &ExtendedPublicKey<E>,
        child_index: NonHardenedIndex,
    ) -> DerivedShift<E>;

    /// Derive a shift for hardened child
    ///
    /// We support only HD derivations that are always defined. This function may not panic.
    fn derive_hardened_shift(
        parent_key: &ExtendedKeyPair<E>,
        child_index: HardenedIndex,
    ) -> DerivedShift<E>;
}