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
use crate::error::Error;

pub const HARDENED: u32 = 0x80000000;

#[derive(Debug, Clone, PartialEq)]
pub struct Keypath(Vec<u32>);

impl Keypath {
    pub fn to_vec(&self) -> Vec<u32> {
        self.0.clone()
    }

    pub(crate) fn hardened_prefix(&self) -> Keypath {
        Keypath(
            self.0
                .iter()
                .cloned()
                .take_while(|&el| el >= HARDENED)
                .collect(),
        )
    }
}

fn parse_bip32_keypath(keypath: &str) -> Option<Vec<u32>> {
    let keypath = keypath.strip_prefix("m/")?;
    if keypath.is_empty() {
        return Some(vec![]);
    }
    let parts: Vec<&str> = keypath.split('/').collect();
    let mut res = Vec::new();

    for part in parts {
        let mut add_prime = 0;
        let number = if part.ends_with('\'') {
            add_prime = HARDENED;
            part[0..part.len() - 1].parse::<u32>()
        } else {
            part.parse::<u32>()
        };

        match number {
            Ok(n) if n < HARDENED => {
                res.push(n + add_prime);
            }
            _ => return None,
        }
    }

    Some(res)
}

impl TryFrom<&str> for Keypath {
    type Error = Error;
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Ok(Keypath(
            parse_bip32_keypath(value).ok_or(Error::KeypathParse(value.into()))?,
        ))
    }
}

impl From<&bitcoin::bip32::DerivationPath> for Keypath {
    fn from(value: &bitcoin::bip32::DerivationPath) -> Self {
        Keypath(value.into_iter().map(|&el| el.into()).collect())
    }
}

impl From<&Keypath> for crate::pb::Keypath {
    fn from(value: &Keypath) -> Self {
        crate::pb::Keypath {
            keypath: value.to_vec(),
        }
    }
}

#[cfg(feature = "wasm")]
impl<'de> serde::Deserialize<'de> for Keypath {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        s.as_str().try_into().map_err(serde::de::Error::custom)
    }
}

#[cfg(feature = "wasm")]
pub fn serde_deserialize<'de, D>(deserializer: D) -> Result<Vec<u32>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::Deserialize;
    Ok(Keypath::deserialize(deserializer)?.to_vec())
}

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

    #[test]
    fn test_parse_bip32_keypath() {
        // Test regular cases
        assert_eq!(parse_bip32_keypath("m/44/0/0/0"), Some(vec![44, 0, 0, 0]));
        assert_eq!(
            parse_bip32_keypath("m/44'/0'/0'/0'"),
            Some(vec![HARDENED + 44, HARDENED, HARDENED, HARDENED])
        );

        // Test edge cases
        assert_eq!(parse_bip32_keypath("m/0/0/0"), Some(vec![0, 0, 0]));
        assert_eq!(
            parse_bip32_keypath("m/0'/0'/0'"),
            Some(vec![HARDENED, HARDENED, HARDENED])
        );
        assert_eq!(
            parse_bip32_keypath("m/2147483647/2147483647/2147483647"),
            Some(vec![2147483647, 2147483647, 2147483647])
        );
        assert_eq!(
            parse_bip32_keypath("m/2147483647'/2147483647'/2147483647'"),
            Some(vec![
                HARDENED + 2147483647,
                HARDENED + 2147483647,
                HARDENED + 2147483647
            ])
        );
        assert_eq!(parse_bip32_keypath("m/"), Some(vec![]));

        // Test failure cases
        assert_eq!(parse_bip32_keypath("m/2147483648/0/0"), None);
        assert_eq!(parse_bip32_keypath("m/0/2147483648/0"), None);
        assert_eq!(parse_bip32_keypath("m/0/0/2147483648"), None);
        assert_eq!(parse_bip32_keypath("m/2147483648'/0/0"), None);
        assert_eq!(parse_bip32_keypath("m/0/2147483648'/0"), None);
        assert_eq!(parse_bip32_keypath("m/0/0/2147483648'"), None);
        assert_eq!(parse_bip32_keypath("m/abcd/0/0"), None);
        assert_eq!(parse_bip32_keypath("m/0'/abcd'/0'"), None);
        assert_eq!(parse_bip32_keypath("m/0/0'/abcd'"), None);
        assert_eq!(parse_bip32_keypath("m//0/0"), None);
        assert_eq!(parse_bip32_keypath("m/0//0"), None);
        assert_eq!(parse_bip32_keypath("m/0/0//"), None);
        assert_eq!(parse_bip32_keypath("/0/0/0"), None);
        assert_eq!(parse_bip32_keypath("44/0/0/0"), None);
    }

    #[test]
    fn test_from_derivation_path() {
        let derivation_path: bitcoin::bip32::DerivationPath =
            std::str::FromStr::from_str("m/84'/0'/0'/0/1").unwrap();
        let keypath = Keypath::from(&derivation_path);
        assert_eq!(
            keypath.to_vec().as_slice(),
            &[84 + HARDENED, HARDENED, HARDENED, 0, 1]
        );
    }
}