stellar_ledger/
hd_path.rs

1use crate::Error;
2
3#[derive(Clone, Copy)]
4pub struct HdPath(pub u32);
5
6impl HdPath {
7    #[must_use]
8    pub fn depth(&self) -> u8 {
9        let path: slip10::BIP32Path = self.into();
10        path.depth()
11    }
12}
13
14impl From<u32> for HdPath {
15    fn from(index: u32) -> Self {
16        HdPath(index)
17    }
18}
19
20impl From<&u32> for HdPath {
21    fn from(index: &u32) -> Self {
22        HdPath(*index)
23    }
24}
25
26impl HdPath {
27    /// # Errors
28    ///
29    /// Could fail to convert the path to bytes
30    pub fn to_vec(&self) -> Result<Vec<u8>, Error> {
31        hd_path_to_bytes(&self.into())
32    }
33}
34
35impl From<&HdPath> for slip10::BIP32Path {
36    fn from(value: &HdPath) -> Self {
37        let index = value.0;
38        format!("m/44'/148'/{index}'").parse().unwrap()
39    }
40}
41
42fn hd_path_to_bytes(hd_path: &slip10::BIP32Path) -> Result<Vec<u8>, Error> {
43    let hd_path_indices = 0..hd_path.depth();
44    let result = hd_path_indices
45        .into_iter()
46        .map(|index| {
47            Ok(hd_path
48                .index(index)
49                .ok_or_else(|| Error::Bip32PathError(format!("{hd_path}")))?
50                .to_be_bytes())
51        })
52        .collect::<Result<Vec<_>, Error>>()?;
53    Ok(result.into_iter().flatten().collect())
54}