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
use crate::{PathValue, CustomHDPath};
use byteorder::{BigEndian, WriteBytesExt};
#[cfg(feature = "with-bitcoin")]
use bitcoin::util::bip32::{ChildNumber, DerivationPath};

/// General trait for an HDPath.
/// Common implementations are [`StandardHDPath`], [`AccountHDPath`] and [`CustomHDPath`]
///
/// [`StandardHDPath`]: struct.StandardHDPath.html
/// [`AccountHDPath`]: struct.AccountHDPath.html
/// [`CustomHDPath`]: struct.CustomHDPath.html
pub trait HDPath {

    /// Size of the HD Path
    fn len(&self) -> u8;

    /// Get element as the specified position.
    /// The implementation must return `Some<PathValue>` for all values up to `len()`.
    /// And return `None` if the position if out of bounds.
    ///
    /// See [`PathValue`](enum.PathValue.html)
    fn get(&self, pos: u8) -> Option<PathValue>;

    /// Encode as bytes, where first byte is number of elements in path (always 5 for StandardHDPath)
    /// following by 4-byte BE values
    fn to_bytes(&self) -> Vec<u8> {
        let len = self.len();
        let mut buf = Vec::with_capacity(1 + 4 * (len as usize));
        buf.push(len);
        for i in 0..len {
            buf.write_u32::<BigEndian>(self.get(i)
                .expect(format!("No valut at {}", i).as_str())
                .to_raw()).unwrap();
        }
        buf
    }

    ///
    /// Get parent HD Path.
    /// Return `None` if the current path is empty (i.e. already at the top)
    fn parent(&self) -> Option<CustomHDPath> {
        if self.len() == 0 {
            return None
        }
        let len = self.len();
        let mut parent_hd_path = Vec::with_capacity(len as usize - 1);
        for i in 0..len - 1 {
            parent_hd_path.push(self.get(i).unwrap());
        }
        let parent_hd_path = CustomHDPath::try_new(parent_hd_path)
            .expect("No parent HD Path");
        Some(parent_hd_path)
    }

    ///
    /// Convert current to `CustomHDPath` structure
    fn as_custom(&self) -> CustomHDPath {
        let len = self.len();
        let mut path = Vec::with_capacity(len as usize);
        for i in 0..len {
            path.push(self.get(i).unwrap());
        }
        CustomHDPath::try_new(path).expect("Invalid HD Path")
    }

    ///
    /// Convert current to bitcoin lib type
    #[cfg(feature = "with-bitcoin")]
    fn as_bitcoin(&self) -> DerivationPath {
        let len = self.len();
        let mut path = Vec::with_capacity(len as usize);
        for i in 0..len {
            path.push(ChildNumber::from(self.get(i).unwrap()));
        }
        DerivationPath::from(path)
    }
}

#[cfg(feature = "with-bitcoin")]
impl std::convert::From<&dyn HDPath> for DerivationPath {
    fn from(value: &dyn HDPath) -> Self {
        let mut path = Vec::with_capacity(value.len() as usize);
        for i in 0..value.len() {
            path.push(ChildNumber::from(value.get(i).expect("no-path-element")));
        }
        DerivationPath::from(path)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{StandardHDPath, AccountHDPath};
    use std::str::FromStr;

    impl StandardHDPath {
        pub fn to_trait(&self) -> &dyn HDPath {
            self
        }
    }

    #[test]
    fn get_parent_from_std() {
        let act = StandardHDPath::from_str("m/44'/0'/1'/1/2").unwrap();
        let parent = act.parent();
        assert!(parent.is_some());
        let parent = parent.unwrap();
        assert_eq!(
            "m/44'/0'/1'/1", parent.to_string()
        );
    }

    #[test]
    fn get_parent_twice() {
        let act = StandardHDPath::from_str("m/44'/0'/1'/1/2").unwrap();
        let parent = act.parent().unwrap().parent();
        assert!(parent.is_some());
        let parent = parent.unwrap();
        assert_eq!(
            "m/44'/0'/1'", parent.to_string()
        );
    }

    #[test]
    fn get_parent_from_account() {
        let act = AccountHDPath::from_str("m/84'/0'/1'").unwrap();
        let parent = act.parent();
        assert!(parent.is_some());
        let parent = parent.unwrap();
        assert_eq!(
            "m/84'/0'", parent.to_string()
        );
    }

    #[test]
    fn get_parent_from_custom() {
        let act = CustomHDPath::from_str("m/84'/0'/1'/0/16").unwrap();
        let parent = act.parent();
        assert!(parent.is_some());
        let parent = parent.unwrap();
        assert_eq!(
            "m/84'/0'/1'/0", parent.to_string()
        );
    }

    #[test]
    fn convert_account_to_custom() {
        let src = AccountHDPath::from_str("m/84'/0'/1'").unwrap();
        let act = src.as_custom();
        assert_eq!(CustomHDPath::from_str("m/84'/0'/1'").unwrap(), act);
    }

    #[test]
    fn convert_standard_to_custom() {
        let src = StandardHDPath::from_str("m/84'/0'/1'/0/2").unwrap();
        let act = src.as_custom();
        assert_eq!(CustomHDPath::from_str("m/84'/0'/1'/0/2").unwrap(), act);
    }
}

#[cfg(all(test, feature = "with-bitcoin"))]
mod tests_with_bitcoin {
    use crate::{StandardHDPath, HDPath};
    use std::str::FromStr;
    use bitcoin::util::bip32::{DerivationPath};

    #[test]
    fn convert_to_bitcoin() {
        let source = StandardHDPath::from_str("m/44'/0'/1'/1/2").unwrap();
        let act = DerivationPath::from(source.to_trait());
        assert_eq!(
            DerivationPath::from_str("m/44'/0'/1'/1/2").unwrap(),
            act
        )
    }

    #[test]
    fn convert_to_bitcoin_directly() {
        let source = StandardHDPath::from_str("m/44'/0'/1'/1/2").unwrap();
        let act = source.as_bitcoin();
        assert_eq!(
            DerivationPath::from_str("m/44'/0'/1'/1/2").unwrap(),
            act
        )
    }
}