From a699b6b4fe6f0e2567f7298fd8174e779f1bd43d Mon Sep 17 00:00:00 2001 From: Nicholas Rodrigues Lordello Date: Mon, 30 Nov 2020 19:11:36 +0100 Subject: hd wallet impl --- src/hdk/path.rs | 62 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/hdk/path.rs (limited to 'src/hdk') diff --git a/src/hdk/path.rs b/src/hdk/path.rs new file mode 100644 index 0000000..f67446a --- /dev/null +++ b/src/hdk/path.rs @@ -0,0 +1,62 @@ +//! Module implementing parsing for BIP-0032 HD paths used for key derivation. + +use anyhow::{anyhow, Context as _, Result}; +use std::str::FromStr; + +/// A parsed hierarchical derivation path. +#[derive(Debug)] +pub struct Path { + components: Vec, +} + +impl Path { + /// Returns an iterator + pub fn components(&self) -> impl Iterator + '_ { + self.components.iter().copied() + } +} + +impl FromStr for Path { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + let components = s + .strip_prefix("m/") + .ok_or_else(|| anyhow!("BIP-0032 path missing main node"))? + .split('/') + .map(Component::from_str) + .collect::>()?; + + Ok(Self { components }) + } +} + +/// A hierarchical path component. +#[derive(Clone, Copy, Debug)] +pub enum Component { + /// Component to generate a hardened child key. + Hardened(u32), + /// Component to generate a normal child key. + Normal(u32), +} + +impl FromStr for Component { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + let (value, hardened) = match s.strip_suffix('\'') { + Some(value) => (value, true), + None => (s, false), + }; + + let value = value + .parse() + .with_context(|| format!("invalid BIP-0032 path component '{}'", s))?; + + Ok(if hardened { + Component::Hardened(value) + } else { + Component::Normal(value) + }) + } +} -- cgit v1.2.3