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
//! SLIP-10: Deterministic key generation
//!
//! [SLIP10][slip10-spec] is a specification for implementing HD wallets. It aims at supporting many
//! curves while being compatible with [BIP32][bip32-spec].
//!
//! The implementation is based on [generic-ec](generic_ec) library that provides generic
//! elliptic curve arithmetic. The crate is `no_std` and `no_alloc` friendly.
//!
//! ### Curves support
//! Implementation currently does not support ed25519 curve. All other curves are
//! supported: both secp256k1 and secp256r1. In fact, implementation may work with any
//! curve, but only those are covered by the SLIP10 specs.
//!
//! The crate also re-exports supported curves in [supported_curves] module (requires
//! enabling a feature), but any other curve implementation will work with the crate.
//!
//! ### Features
//! * `std`: enables std library support (mainly, it just implements [`Error`](std::error::Error)
//!   trait for the error types)
//! * `curve-secp256k1` and `curve-secp256r1` add curve implementation into the crate [supported_curves]
//!   module
//!
//! ### Examples
//!
//! Derive a master key from the seed, and then derive a child key m/1<sub>H</sub>/10:
//! ```rust
//! use slip_10::supported_curves::Secp256k1;
//!
//! let seed = b"16-64 bytes of high entropy".as_slice();
//! let master_key = slip_10::derive_master_key::<Secp256k1>(seed)?;
//! let master_key_pair = slip_10::ExtendedKeyPair::from(master_key);
//!
//! let child_key_pair = slip_10::derive_child_key_pair_with_path(
//!     &master_key_pair,
//!     [1 + slip_10::H, 10],
//! );
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! [slip10-spec]: https://github.com/satoshilabs/slips/blob/master/slip-0010.md
//! [bip32-spec]: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki

#![cfg_attr(not(feature = "std"), no_std)]
#![forbid(missing_docs, unsafe_code)]

use core::ops;

use generic_array::{
    typenum::{U32, U64},
    GenericArray,
};
use generic_ec::{Curve, Point, Scalar, SecretScalar};
use hmac::Mac as _;

#[cfg(any(
    feature = "curve-secp256k1",
    feature = "curve-secp256r1",
    feature = "all-curves"
))]
pub use generic_ec::curves as supported_curves;

pub mod errors;

type HmacSha512 = hmac::Hmac<sha2::Sha512>;
/// Beggining 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 slip_10::supported_curves::Secp256k1;
///
/// # let seed = b"do not use this seed in prod :)".as_slice();
/// let master_key = slip_10::derive_master_key::<Secp256k1>(seed)?;
/// let master_key_pair = slip_10::ExtendedKeyPair::from(master_key);
///
/// let hardened_child = slip_10::derive_child_key_pair(
///     &master_key_pair,
///     1 + slip_10::H,
/// );
/// #
/// # Ok::<(), slip_10::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}$ corresponing 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}$ corresponing 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())
    }
}

/// Marker for a curve supported by SLIP10 specs and this library
///
/// Only implement this trait for the curves that are supported by SLIP10 specs.
/// Curves provided by the crate out-of-box in [supported_curves] module already
/// implement this trait.
pub trait SupportedCurve {
    /// Specifies which curve it is
    const CURVE_TYPE: CurveType;
}
#[cfg(feature = "curve-secp256k1")]
impl SupportedCurve for supported_curves::Secp256k1 {
    const CURVE_TYPE: CurveType = CurveType::Secp256k1;
}
#[cfg(feature = "curve-secp256r1")]
impl SupportedCurve for supported_curves::Secp256r1 {
    const CURVE_TYPE: CurveType = CurveType::Secp256r1;
}

/// Curves supported by SLIP-10 spec
///
/// It's either secp256k1 or secp256r1. Note that SLIP-10 also supports ed25519 curve, but this library
/// does not support it.
///
/// `CurveType` is only needed for master key derivation.
#[derive(Clone, Copy, Debug)]
pub enum CurveType {
    /// Secp256k1 curve
    Secp256k1,
    /// Secp256r1 curve
    Secp256r1,
}

/// Derives a master key from the seed
///
/// Seed must be 16-64 bytes long, otherwise an error is returned
pub fn derive_master_key<E: Curve + SupportedCurve>(
    seed: &[u8],
) -> Result<ExtendedSecretKey<E>, errors::InvalidLength> {
    let curve_tag = match E::CURVE_TYPE {
        CurveType::Secp256k1 => "Bitcoin seed",
        CurveType::Secp256r1 => "Nist256p1 seed",
    };
    derive_master_key_with_curve_tag(curve_tag.as_bytes(), seed)
}

/// Derives a master key from the seed and the curve tag as defined in SLIP10
///
/// It's preferred to use [derive_master_key] instead, as it automatically infers
/// the curve tag for supported curves. The curve tag is not validated by the function,
/// it's caller's responsibility to make sure that it complies with SLIP10.
///
/// Seed must be 16-64 bytes long, otherwise an error is returned
pub fn derive_master_key_with_curve_tag<E: Curve>(
    curve_tag: &[u8],
    seed: &[u8],
) -> Result<ExtendedSecretKey<E>, errors::InvalidLength> {
    if !(16 <= seed.len() && seed.len() <= 64) {
        return Err(errors::InvalidLength);
    }

    let hmac = HmacSha512::new_from_slice(curve_tag)
        .expect("this never fails: hmac can handle keys of any size");
    let mut i = hmac.clone().chain_update(seed).finalize().into_bytes();

    loop {
        let (i_left, i_right) = split_into_two_halfes(&i);

        if let Ok(mut sk) = Scalar::<E>::from_be_bytes(i_left) {
            if !bool::from(subtle::ConstantTimeEq::ct_eq(&sk, &Scalar::zero())) {
                return Ok(ExtendedSecretKey {
                    secret_key: SecretScalar::new(&mut sk),
                    chain_code: (*i_right).into(),
                });
            }
        }

        i = hmac.clone().chain_update(&i[..]).finalize().into_bytes()
    }
}

/// 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 slip_10::supported_curves::Secp256k1;
///
/// # let seed = b"do not use this seed :)".as_slice();
/// let master_key = slip_10::derive_master_key::<Secp256k1>(seed)?;
/// let master_key_pair = slip_10::ExtendedKeyPair::from(master_key);
///
/// let derived_key = slip_10::derive_child_key_pair(
///     &master_key_pair,
///     1 + slip_10::H,
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn derive_child_key_pair<E: Curve>(
    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) => derive_hardened_shift(parent_key, i),
        ChildIndex::NonHardened(i) => 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 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 slip_10::supported_curves::Secp256k1;
/// # let seed = b"16-64 bytes of high entropy".as_slice();
/// let master_key = slip_10::derive_master_key::<Secp256k1>(seed)?;
/// let master_key_pair = slip_10::ExtendedKeyPair::from(master_key);
///
/// let child_key = slip_10::derive_child_key_pair_with_path(
///     &master_key_pair,
///     [1, 10, 1 + slip_10::H],
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn derive_child_key_pair_with_path<E: Curve>(
    parent_key: &ExtendedKeyPair<E>,
    path: impl IntoIterator<Item = impl Into<ChildIndex>>,
) -> ExtendedKeyPair<E> {
    let result = 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 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.
///
/// ### Example
/// Parse a path from the string and derive a child without extra allocations:
/// ```rust
/// use slip_10::supported_curves::Secp256k1;
/// # let seed = b"16-64 bytes of high entropy".as_slice();
/// let master_key = slip_10::derive_master_key::<Secp256k1>(seed)?;
/// let master_key_pair = slip_10::ExtendedKeyPair::from(master_key);
///
/// let path = "1/10/2";
/// let child_indexes = path.split('/').map(str::parse::<u32>);
/// let child_key = slip_10::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: Curve, 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 = derive_child_key_pair(&derived_key, child_index?);
    }
    Ok(derived_key)
}

/// Derives child extended public key from parent extended public key
///
/// ### Example
/// Derive a master public key m/1
/// ```rust
/// use slip_10::supported_curves::Secp256k1;
///
/// # let seed = b"do not use this seed :)".as_slice();
/// let master_key = slip_10::derive_master_key::<Secp256k1>(seed)?;
/// let master_public_key = slip_10::ExtendedPublicKey::from(&master_key);
///
/// let derived_key = slip_10::derive_child_public_key(
///     &master_public_key,
///     1.try_into()?,
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn derive_child_public_key<E: Curve>(
    parent_public_key: &ExtendedPublicKey<E>,
    child_index: NonHardenedIndex,
) -> ExtendedPublicKey<E> {
    derive_public_shift(parent_public_key, child_index).child_public_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 slip_10::supported_curves::Secp256k1;
/// # let seed = b"16-64 bytes of high entropy".as_slice();
/// let master_key = slip_10::derive_master_key::<Secp256k1>(seed)?;
/// let master_public_key = slip_10::ExtendedPublicKey::from(&master_key);
///
/// let child_key = slip_10::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: Curve>(
    parent_public_key: &ExtendedPublicKey<E>,
    path: impl IntoIterator<Item = NonHardenedIndex>,
) -> ExtendedPublicKey<E> {
    let result = 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 {},
    }
}

/// 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.
///
/// ### Example
/// Parse a path from the string and derive a child without extra allocations:
/// ```rust
/// use slip_10::supported_curves::Secp256k1;
/// # let seed = b"16-64 bytes of high entropy".as_slice();
/// let master_key = slip_10::derive_master_key::<Secp256k1>(seed)?;
/// let master_public_key = slip_10::ExtendedPublicKey::from(&master_key);
///
/// let path = "1/10/2";
/// let child_indexes = path.split('/').map(str::parse);
/// let child_key = slip_10::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: Curve, 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 = derive_child_public_key(&derived_key, child_index?);
    }
    Ok(derived_key)
}

/// Derive a shift for hardened child
pub fn derive_hardened_shift<E: Curve>(
    parent_key: &ExtendedKeyPair<E>,
    child_index: HardenedIndex,
) -> DerivedShift<E> {
    let hmac = HmacSha512::new_from_slice(parent_key.chain_code())
        .expect("this never fails: hmac can handle keys of any size");
    let i = hmac
        .clone()
        .chain_update([0x00])
        .chain_update(parent_key.secret_key.secret_key.as_ref().to_be_bytes())
        .chain_update(child_index.to_be_bytes())
        .finalize()
        .into_bytes();
    calculate_shift(&hmac, &parent_key.public_key, *child_index, i)
}

/// Derives a shift for non-hardened child
pub fn derive_public_shift<E: Curve>(
    parent_public_key: &ExtendedPublicKey<E>,
    child_index: NonHardenedIndex,
) -> DerivedShift<E> {
    let hmac = HmacSha512::new_from_slice(&parent_public_key.chain_code)
        .expect("this never fails: hmac can handle keys of any size");
    let i = hmac
        .clone()
        .chain_update(&parent_public_key.public_key.to_bytes(true))
        .chain_update(child_index.to_be_bytes())
        .finalize()
        .into_bytes();
    calculate_shift(&hmac, parent_public_key, *child_index, i)
}

fn calculate_shift<E: Curve>(
    hmac: &HmacSha512,
    parent_public_key: &ExtendedPublicKey<E>,
    child_index: u32,
    mut i: hmac::digest::Output<HmacSha512>,
) -> DerivedShift<E> {
    loop {
        let (i_left, i_right) = split_into_two_halfes(&i);

        if let Ok(shift) = Scalar::<E>::from_be_bytes(i_left) {
            let child_pk = parent_public_key.public_key + Point::generator() * shift;
            if !child_pk.is_zero() {
                return DerivedShift {
                    shift,
                    child_public_key: ExtendedPublicKey {
                        public_key: child_pk,
                        chain_code: (*i_right).into(),
                    },
                };
            }
        }

        i = hmac
            .clone()
            .chain_update([0x01])
            .chain_update(i_right)
            .chain_update(child_index.to_be_bytes())
            .finalize()
            .into_bytes()
    }
}

/// Splits array `I` of 64 bytes into two arrays `I_L = I[..32]` and `I_R = I[32..]`
fn split_into_two_halfes(
    i: &GenericArray<u8, U64>,
) -> (&GenericArray<u8, U32>, &GenericArray<u8, U32>) {
    generic_array::sequence::Split::split(i)
}