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

use std::str::FromStr;

const HARDENED_BIT: u32 = 1 << 31;

/// A child number for a derived key
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct ChildNumber(u32);

impl ChildNumber {
	pub fn is_hardened(&self) -> bool {
		self.0 & HARDENED_BIT == HARDENED_BIT
	}

	pub fn is_normal(&self) -> bool {
		self.0 & HARDENED_BIT == 0
	}

	pub fn to_bytes(&self) -> [u8; 4] {
		self.0.to_be_bytes()
	}

	pub fn hardened_from_u32(index: u32) -> Self {
		ChildNumber(index | HARDENED_BIT)
	}

	pub fn non_hardened_from_u32(index: u32) -> Self {
		ChildNumber(index)
	}
}

impl FromStr for ChildNumber {
    type Err = Error;

    fn from_str(child: &str) -> Result<ChildNumber, Error> {
    	let (child, mask) = if child.ends_with('\'') {
    		(&child[..child.len() - 1], HARDENED_BIT)
    	} else {
    		(child, 0)
    	};

        let index: u32 = child.parse().map_err(|_| Error::InvalidChildNumber)?;

        if index & HARDENED_BIT == 0 {
        	Ok(ChildNumber(index | mask))
        } else {
        	Err(Error::InvalidChildNumber)
        }
    }
}

#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub struct DerivationPath {
    path: Vec<ChildNumber>,
}

impl FromStr for DerivationPath {
    type Err = Error;

    fn from_str(path: &str) -> Result<DerivationPath, Error> {
        let mut path = path.split('/');

        if path.next() != Some("m") {
            return Err(Error::InvalidDerivationPath);
        }

        Ok(DerivationPath {
            path: path.map(str::parse).collect::<Result<Vec<ChildNumber>, Error>>()?
        })
    }
}

impl DerivationPath {
	pub fn as_ref(&self) -> &[ChildNumber] {
		&self.path
	}

	pub fn iter(&self) -> impl Iterator<Item = &ChildNumber> {
		self.path.iter()
	}
}

pub trait IntoDerivationPath {
	fn into(self) -> Result<DerivationPath, Error>;
}

impl IntoDerivationPath for DerivationPath {
	fn into(self) -> Result<DerivationPath, Error> {
		Ok(self)
	}
}

impl IntoDerivationPath for &str {
	fn into(self) -> Result<DerivationPath, Error> {
		self.parse()
	}
}

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

	#[test]
	fn derive_path() {
		let path: DerivationPath = "m/44'/60'/0'/0".parse().unwrap();

		assert_eq!(path, DerivationPath {
			path: vec![
				ChildNumber(44 | HARDENED_BIT),
				ChildNumber(60 | HARDENED_BIT),
				ChildNumber(0  | HARDENED_BIT),
				ChildNumber(0),
			],
		});
	}
}