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
//! A simple struct for dealing with derivation paths as defined by BIP32, BIP44 and BIP49 of the
//! Bitcoin protocol. This crate provides interfaces for dealing with hardened vs normal child
//! indexes, as well as display and parsing derivation paths from strings
//!
//! # Example
//!
//! ```
//! # use derivation_path::{ChildIndex, DerivationPath, DerivationPathType};
//! let path = DerivationPath::bip44(0, 1, 0, 1).unwrap();
//! assert_eq!(&path.to_string(), "m/44'/0'/1'/0/1");
//! assert_eq!(path.path()[2], ChildIndex::Hardened(1));
//!
//! let path: DerivationPath = "m/49'/0'/0'/1/0".parse().unwrap();
//! assert_eq!(path.path()[4], ChildIndex::Normal(0));
//! assert_eq!(path.path_type(), DerivationPathType::BIP49);
//! ```

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

#[cfg(not(feature = "std"))]
extern crate alloc;

#[cfg(not(feature = "std"))]
use alloc::{borrow::ToOwned, boxed::Box, string::String};

use core::fmt;
use core::iter::IntoIterator;
use core::slice::Iter;
use core::str::FromStr;
use failure::Fail;

/// Errors when building a [DerivationPath]
#[derive(Fail, Debug, Clone)]
pub enum DerivationPathError {
    #[fail(display = "path too long")]
    PathTooLong,
    #[fail(display = "invalid child index: {}", _0)]
    InvalidChildIndex(ChildIndexError),
}

/// Errors when parsing a [DerivationPath] from a [str]
#[derive(Fail, Debug, Clone)]
pub enum DerivationPathParseError {
    #[fail(display = "empty")]
    Empty,
    #[fail(display = "invalid prefix: {}", _0)]
    InvalidPrefix(String),
    #[fail(display = "invalid child index: {}", _0)]
    InvalidChildIndex(ChildIndexParseError),
}

/// A list of [ChildIndex] items
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DerivationPath(Box<[ChildIndex]>);

/// [DerivationPath] specifications as defined by BIP's
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum DerivationPathType {
    None,
    BIP32,
    BIP44,
    BIP49,
}

impl DerivationPath {
    /// Build a [DerivationPath] from a list of [ChildIndex] items
    #[inline]
    pub fn new<P>(path: P) -> Self
    where
        P: Into<Box<[ChildIndex]>>,
    {
        DerivationPath(path.into())
    }

    /// Build a BIP32 style [DerivationPath]. This will fail if the length of the path is greater
    /// than 255 items
    pub fn bip32<P>(path: P) -> Result<Self, DerivationPathError>
    where
        P: Into<Box<[ChildIndex]>>,
    {
        let path = path.into();
        if path.len() > 255 {
            return Err(DerivationPathError::PathTooLong);
        }
        Ok(Self::new(path))
    }

    /// Build a BIP44 style [DerivationPath]: `m/44'/coin'/account'/change/address`
    #[inline]
    pub fn bip44(
        coin: u32,
        account: u32,
        change: u32,
        address: u32,
    ) -> Result<Self, DerivationPathError> {
        Self::bip4x(44, coin, account, change, address)
    }

    /// Build a BIP49 style [DerivationPath]: `m/49'/coin'/account'/change/address`
    #[inline]
    pub fn bip49(
        coin: u32,
        account: u32,
        change: u32,
        address: u32,
    ) -> Result<Self, DerivationPathError> {
        Self::bip4x(49, coin, account, change, address)
    }

    #[inline]
    fn bip4x(
        purpose: u32,
        coin: u32,
        account: u32,
        change: u32,
        address: u32,
    ) -> Result<Self, DerivationPathError> {
        Ok(Self::new(
            [
                ChildIndex::hardened(purpose)?,
                ChildIndex::hardened(coin)?,
                ChildIndex::hardened(account)?,
                ChildIndex::normal(change)?,
                ChildIndex::normal(address)?,
            ]
            .as_ref(),
        ))
    }

    /// Get a reference to the list of [ChildIndex] items
    #[inline]
    pub fn path(&self) -> &[ChildIndex] {
        self.0.as_ref()
    }

    /// Get the [DerivationPathType]. This will check the "purpose" index in BIP44/49 style
    /// derivation paths or otherwise return BIP32 if the length is less than 255
    pub fn path_type(&self) -> DerivationPathType {
        let path = self.path();
        let len = path.len();
        if len == 5
            && path[1].is_hardened()
            && path[2].is_hardened()
            && path[3].is_normal()
            && path[4].is_normal()
        {
            match path[0] {
                ChildIndex::Hardened(44) => DerivationPathType::BIP44,
                ChildIndex::Hardened(49) => DerivationPathType::BIP49,
                _ => DerivationPathType::BIP32,
            }
        } else if len < 256 {
            DerivationPathType::BIP32
        } else {
            DerivationPathType::None
        }
    }
}

impl fmt::Display for DerivationPath {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("m")?;
        for index in self.path() {
            f.write_str("/")?;
            fmt::Display::fmt(index, f)?;
        }
        Ok(())
    }
}

impl FromStr for DerivationPath {
    type Err = DerivationPathParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.is_empty() {
            return Err(DerivationPathParseError::Empty);
        }
        let mut parts = s.split('/');
        match parts.next().unwrap() {
            "m" => (),
            prefix => return Err(DerivationPathParseError::InvalidPrefix(prefix.to_owned())),
        }
        let path = parts
            .map(|part| ChildIndex::from_str(part).map_err(|e| e.into()))
            .collect::<Result<Box<[ChildIndex]>, DerivationPathParseError>>()?;
        Ok(DerivationPath::new(path))
    }
}

impl AsRef<[ChildIndex]> for DerivationPath {
    fn as_ref(&self) -> &[ChildIndex] {
        self.path()
    }
}

impl<'a> IntoIterator for &'a DerivationPath {
    type IntoIter = Iter<'a, ChildIndex>;
    type Item = &'a ChildIndex;
    fn into_iter(self) -> Self::IntoIter {
        self.path().iter()
    }
}

/// An index in a [DerivationPath]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum ChildIndex {
    Normal(u32),
    Hardened(u32),
}

/// Errors when parsing a [ChildIndex] from a [str]
#[derive(Fail, Debug, Clone)]
pub enum ChildIndexParseError {
    #[fail(display = "could not parse child index: {}", _0)]
    ParseIntError(core::num::ParseIntError),
    #[fail(display = "invalid child index: {}", _0)]
    ChildIndexError(ChildIndexError),
}

/// Errors when building a [ChildIndex]
#[derive(Fail, Debug, Clone)]
pub enum ChildIndexError {
    #[fail(display = "number too large: {}", _0)]
    NumberTooLarge(u32),
}

impl ChildIndex {
    /// Create a [ChildIndex::Hardened] instance from a [u32]. This will fail if `num` is not
    /// in `[0, 2^31 - 1]`
    pub fn hardened(num: u32) -> Result<Self, ChildIndexError> {
        Ok(Self::Hardened(Self::check_size(num)?))
    }

    /// Create a [ChildIndex::Normal] instance from a [u32]. This will fail if `num` is not
    /// in `[0, 2^31 - 1]`
    pub fn normal(num: u32) -> Result<Self, ChildIndexError> {
        Ok(Self::Normal(Self::check_size(num)?))
    }

    fn check_size(num: u32) -> Result<u32, ChildIndexError> {
        if num & (1 << 31) == 0 {
            Ok(num)
        } else {
            Err(ChildIndexError::NumberTooLarge(num))
        }
    }

    /// Convert [ChildIndex] to its inner [u32]
    #[inline]
    pub fn to_u32(self) -> u32 {
        match self {
            ChildIndex::Hardened(index) => index,
            ChildIndex::Normal(index) => index,
        }
    }

    /// Convert [ChildIndex] to a [u32] representing the type and a 31 bit number. The highest bit
    /// is set for a hard derivation and clear for a normal derivation, and the remaining 31 bits are
    /// the index
    #[inline]
    pub fn to_bits(self) -> u32 {
        match self {
            ChildIndex::Hardened(index) => (1 << 31) | index,
            ChildIndex::Normal(index) => index,
        }
    }

    /// Build a [ChildIndex] from a [u32] representing the type and a 31 bit number.
    /// See [ChildIndex::to_bits] for more information
    #[inline]
    pub fn from_bits(bits: u32) -> Self {
        if bits & (1 << 31) == 0 {
            ChildIndex::Normal(bits)
        } else {
            ChildIndex::Hardened(bits & !(1 << 31))
        }
    }

    /// Check if the [ChildIndex] is "hardened"
    #[inline]
    pub fn is_hardened(self) -> bool {
        match self {
            Self::Hardened(_) => true,
            _ => false,
        }
    }

    /// Check if the [ChildIndex] is "normal"
    #[inline]
    pub fn is_normal(self) -> bool {
        match self {
            Self::Normal(_) => true,
            _ => false,
        }
    }
}

impl fmt::Display for ChildIndex {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.to_u32(), f)?;
        if self.is_hardened() {
            f.write_str("'")?;
        }
        Ok(())
    }
}

impl FromStr for ChildIndex {
    type Err = ChildIndexParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut chars = s.chars();
        Ok(match chars.next_back() {
            Some('\'') => Self::hardened(u32::from_str(chars.as_str())?)?,
            _ => Self::normal(u32::from_str(s)?)?,
        })
    }
}

impl From<core::num::ParseIntError> for ChildIndexParseError {
    fn from(err: core::num::ParseIntError) -> Self {
        Self::ParseIntError(err)
    }
}

impl From<ChildIndexError> for ChildIndexParseError {
    fn from(err: ChildIndexError) -> Self {
        Self::ChildIndexError(err)
    }
}

impl From<ChildIndexParseError> for DerivationPathParseError {
    fn from(err: ChildIndexParseError) -> Self {
        Self::InvalidChildIndex(err)
    }
}

impl From<ChildIndexError> for DerivationPathError {
    fn from(err: ChildIndexError) -> Self {
        Self::InvalidChildIndex(err)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[cfg(not(feature = "std"))]
    use alloc::{string::ToString, vec};

    #[test]
    fn child_index_is_normal() {
        assert!(ChildIndex::Hardened(0).is_hardened());
        assert!(!ChildIndex::Normal(0).is_hardened());
    }

    #[test]
    fn child_index_is_hardened() {
        assert!(!ChildIndex::Hardened(0).is_normal());
        assert!(ChildIndex::Normal(0).is_normal());
    }

    #[test]
    fn child_index_range() {
        assert!(ChildIndex::normal(0).is_ok());
        assert!(ChildIndex::normal(1).is_ok());
        assert!(ChildIndex::normal(100).is_ok());
        assert!(ChildIndex::normal(1 << 31).is_err());

        assert!(ChildIndex::hardened(0).is_ok());
        assert!(ChildIndex::hardened(1 << 31).is_err());
    }

    #[test]
    fn child_index_to_u32() {
        assert_eq!(ChildIndex::Normal(0).to_u32(), 0);
        assert_eq!(ChildIndex::Normal(1).to_u32(), 1);
        assert_eq!(ChildIndex::Normal(100).to_u32(), 100);
        assert_eq!(ChildIndex::Hardened(0).to_u32(), 0);
        assert_eq!(ChildIndex::Hardened(1).to_u32(), 1);
    }

    #[test]
    fn child_index_to_bits() {
        assert_eq!(ChildIndex::Normal(0).to_bits(), 0);
        assert_eq!(ChildIndex::Normal(1).to_bits(), 1);
        assert_eq!(ChildIndex::Normal(100).to_bits(), 100);
        assert_eq!(ChildIndex::Hardened(0).to_bits(), (1 << 31) | 0);
        assert_eq!(ChildIndex::Hardened(1).to_bits(), (1 << 31) | 1);
        assert_eq!(ChildIndex::Hardened(100).to_bits(), (1 << 31) | 100);
    }

    #[test]
    fn child_index_from_bits() {
        assert_eq!(ChildIndex::from_bits(0), ChildIndex::Normal(0));
        assert_eq!(ChildIndex::from_bits(1), ChildIndex::Normal(1));
        assert_eq!(ChildIndex::from_bits(100), ChildIndex::Normal(100));
        assert_eq!(
            ChildIndex::from_bits((1 << 31) | 0),
            ChildIndex::Hardened(0)
        );
        assert_eq!(
            ChildIndex::from_bits((1 << 31) | 1),
            ChildIndex::Hardened(1)
        );
        assert_eq!(
            ChildIndex::from_bits((1 << 31) | 100),
            ChildIndex::Hardened(100)
        );
    }

    #[test]
    fn child_index_to_string() {
        assert_eq!(&ChildIndex::Normal(0).to_string(), "0");
        assert_eq!(&ChildIndex::Normal(1).to_string(), "1");
        assert_eq!(&ChildIndex::Normal(100).to_string(), "100");
        assert_eq!(&ChildIndex::Hardened(0).to_string(), "0'");
        assert_eq!(&ChildIndex::Hardened(1).to_string(), "1'");
        assert_eq!(&ChildIndex::Hardened(100).to_string(), "100'");
    }

    #[test]
    fn child_index_from_str() {
        assert_eq!(ChildIndex::Normal(0), "0".parse().unwrap());
        assert_eq!(ChildIndex::Normal(1), "1".parse().unwrap());
        assert_eq!(ChildIndex::Normal(100), "100".parse().unwrap());
        assert_eq!(ChildIndex::Hardened(0), "0'".parse().unwrap());
        assert_eq!(ChildIndex::Hardened(1), "1'".parse().unwrap());
        assert_eq!(ChildIndex::Hardened(100), "100'".parse().unwrap());
        assert!(matches!(
            ChildIndex::from_str(""),
            Err(ChildIndexParseError::ParseIntError(_))
        ));
        assert!(matches!(
            ChildIndex::from_str("a"),
            Err(ChildIndexParseError::ParseIntError(_))
        ));
        assert!(matches!(
            ChildIndex::from_str("100 "),
            Err(ChildIndexParseError::ParseIntError(_))
        ));
        assert!(matches!(
            ChildIndex::from_str("99a"),
            Err(ChildIndexParseError::ParseIntError(_))
        ));
        assert!(matches!(
            ChildIndex::from_str("a10"),
            Err(ChildIndexParseError::ParseIntError(_))
        ));
        assert!(matches!(
            ChildIndex::from_str(" 10"),
            Err(ChildIndexParseError::ParseIntError(_))
        ));
        assert!(matches!(
            ChildIndex::from_str(&(1u32 << 31).to_string()),
            Err(ChildIndexParseError::ChildIndexError(_))
        ));
    }

    #[test]
    fn derivation_path_new() {
        let path = [
            ChildIndex::Normal(1),
            ChildIndex::Hardened(2),
            ChildIndex::Normal(3),
        ];
        assert_eq!(&path, DerivationPath::new(path.as_ref()).path());

        let path: [ChildIndex; 0] = [];
        assert_eq!(&path, DerivationPath::new(path.as_ref()).path());

        let path = vec![ChildIndex::Normal(0); 256];
        assert_eq!(path.as_slice(), DerivationPath::new(path.as_ref()).path());
    }

    #[test]
    fn derivation_bip32() {
        let path = [
            ChildIndex::Normal(1),
            ChildIndex::Hardened(2),
            ChildIndex::Normal(3),
        ];
        assert_eq!(&path, DerivationPath::bip32(path.as_ref()).unwrap().path());

        let path: [ChildIndex; 0] = [];
        assert_eq!(&path, DerivationPath::bip32(path.as_ref()).unwrap().path());

        let path = vec![ChildIndex::Normal(0); 256];
        assert!(matches!(
            DerivationPath::bip32(path.as_ref()),
            Err(DerivationPathError::PathTooLong)
        ));
    }

    #[test]
    fn derivation_bip44() {
        assert_eq!(
            DerivationPath::bip44(1, 2, 3, 4).unwrap().path(),
            &[
                ChildIndex::Hardened(44),
                ChildIndex::Hardened(1),
                ChildIndex::Hardened(2),
                ChildIndex::Normal(3),
                ChildIndex::Normal(4)
            ]
        );

        assert!(matches!(
            DerivationPath::bip44(1 << 31, 0, 0, 0),
            Err(DerivationPathError::InvalidChildIndex(_))
        ));
    }

    #[test]
    fn derivation_bip49() {
        assert_eq!(
            DerivationPath::bip49(1, 2, 3, 4).unwrap().path(),
            &[
                ChildIndex::Hardened(49),
                ChildIndex::Hardened(1),
                ChildIndex::Hardened(2),
                ChildIndex::Normal(3),
                ChildIndex::Normal(4)
            ]
        );

        assert!(matches!(
            DerivationPath::bip44(1 << 31, 0, 0, 0),
            Err(DerivationPathError::InvalidChildIndex(_))
        ));
    }

    #[test]
    fn derivation_path_type() {
        assert_eq!(
            DerivationPath::new(vec![
                ChildIndex::Normal(0),
                ChildIndex::Normal(0),
                ChildIndex::Normal(0)
            ])
            .path_type(),
            DerivationPathType::BIP32
        );
        assert_eq!(
            DerivationPath::new(vec![]).path_type(),
            DerivationPathType::BIP32
        );
        assert_eq!(
            DerivationPath::new(vec![
                ChildIndex::Hardened(44),
                ChildIndex::Hardened(0),
                ChildIndex::Hardened(0),
                ChildIndex::Normal(0),
                ChildIndex::Normal(0)
            ])
            .path_type(),
            DerivationPathType::BIP44
        );
        assert_eq!(
            DerivationPath::new(vec![
                ChildIndex::Hardened(44),
                ChildIndex::Hardened(0),
                ChildIndex::Hardened(0),
                ChildIndex::Normal(0),
            ])
            .path_type(),
            DerivationPathType::BIP32
        );
        assert_eq!(
            DerivationPath::new(vec![
                ChildIndex::Hardened(43),
                ChildIndex::Hardened(0),
                ChildIndex::Hardened(0),
                ChildIndex::Normal(0),
                ChildIndex::Normal(0)
            ])
            .path_type(),
            DerivationPathType::BIP32
        );
        assert_eq!(
            DerivationPath::new(vec![
                ChildIndex::Hardened(44),
                ChildIndex::Hardened(0),
                ChildIndex::Normal(0),
                ChildIndex::Normal(0),
                ChildIndex::Normal(0)
            ])
            .path_type(),
            DerivationPathType::BIP32
        );
        assert_eq!(
            DerivationPath::new(vec![
                ChildIndex::Hardened(49),
                ChildIndex::Hardened(0),
                ChildIndex::Hardened(0),
                ChildIndex::Normal(0),
                ChildIndex::Normal(0)
            ])
            .path_type(),
            DerivationPathType::BIP49
        );
        assert_eq!(
            DerivationPath::new(vec![ChildIndex::Normal(0); 256]).path_type(),
            DerivationPathType::None
        );
    }

    #[test]
    fn derivation_path_to_string() {
        assert_eq!(
            &DerivationPath::new(vec![
                ChildIndex::Hardened(1),
                ChildIndex::Hardened(2),
                ChildIndex::Normal(3),
                ChildIndex::Hardened(4)
            ])
            .to_string(),
            "m/1'/2'/3/4'"
        );
        assert_eq!(
            &DerivationPath::new(vec![
                ChildIndex::Hardened(1),
                ChildIndex::Hardened(2),
                ChildIndex::Hardened(4),
                ChildIndex::Normal(3),
            ])
            .to_string(),
            "m/1'/2'/4'/3"
        );
        assert_eq!(
            &DerivationPath::new(vec![
                ChildIndex::Normal(100),
                ChildIndex::Hardened(2),
                ChildIndex::Hardened(4),
                ChildIndex::Normal(3),
            ])
            .to_string(),
            "m/100/2'/4'/3"
        );
        assert_eq!(
            &DerivationPath::new(vec![ChildIndex::Normal(0),]).to_string(),
            "m/0"
        );
        assert_eq!(&DerivationPath::new(vec![]).to_string(), "m");
    }

    #[test]
    fn derivation_path_parsing() {
        assert_eq!(
            DerivationPath::new(vec![
                ChildIndex::Hardened(1),
                ChildIndex::Hardened(2),
                ChildIndex::Normal(3),
                ChildIndex::Hardened(4)
            ]),
            "m/1'/2'/3/4'".parse().unwrap()
        );
        assert_eq!(
            DerivationPath::new(vec![
                ChildIndex::Hardened(1),
                ChildIndex::Hardened(2),
                ChildIndex::Hardened(4),
                ChildIndex::Normal(3),
            ]),
            "m/1'/2'/4'/3".parse().unwrap()
        );
        assert_eq!(
            DerivationPath::new(vec![
                ChildIndex::Normal(100),
                ChildIndex::Hardened(2),
                ChildIndex::Hardened(4),
                ChildIndex::Normal(3),
            ]),
            "m/100/2'/4'/3".parse().unwrap()
        );
        assert_eq!(
            DerivationPath::new(vec![ChildIndex::Normal(0),]),
            "m/0".parse().unwrap()
        );
        assert_eq!(DerivationPath::new(vec![]), "m".parse().unwrap());

        assert!(matches!(
            DerivationPath::from_str(""),
            Err(DerivationPathParseError::Empty)
        ));
        assert!(matches!(
            DerivationPath::from_str("n/0"),
            Err(DerivationPathParseError::InvalidPrefix(_))
        ));
        assert!(matches!(
            DerivationPath::from_str("mn/0"),
            Err(DerivationPathParseError::InvalidPrefix(_))
        ));
        assert!(matches!(
            DerivationPath::from_str("m/0/"),
            Err(DerivationPathParseError::InvalidChildIndex(_))
        ));
        assert!(matches!(
            DerivationPath::from_str("m/0/a/1"),
            Err(DerivationPathParseError::InvalidChildIndex(_))
        ));
        assert!(matches!(
            DerivationPath::from_str("m/0///1"),
            Err(DerivationPathParseError::InvalidChildIndex(_))
        ));
        assert!(matches!(
            DerivationPath::from_str(&format!("m/0/{}/1", (1u32 << 31))),
            Err(DerivationPathParseError::InvalidChildIndex(_))
        ));
        assert!(matches!(
            DerivationPath::from_str("m|1"),
            Err(DerivationPathParseError::InvalidPrefix(_))
        ));
    }
}