diff options
| author | Nicholas Rodrigues Lordello <[email protected]> | 2020-11-30 19:11:36 +0100 |
|---|---|---|
| committer | Nicholas Rodrigues Lordello <[email protected]> | 2020-11-30 19:11:36 +0100 |
| commit | a699b6b4fe6f0e2567f7298fd8174e779f1bd43d (patch) | |
| tree | e79f3927acc133cd05e06e22b1c95c776effe991 /src/hdk/path.rs | |
| parent | 678d45e7ae09510796d27a80ecd894f6a1ad8279 (diff) | |
hd wallet impl
Diffstat (limited to 'src/hdk/path.rs')
| -rw-r--r-- | src/hdk/path.rs | 62 |
1 files changed, 62 insertions, 0 deletions
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<Component>, +} + +impl Path { + /// Returns an iterator + pub fn components(&self) -> impl Iterator<Item = Component> + '_ { + self.components.iter().copied() + } +} + +impl FromStr for Path { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result<Self> { + let components = s + .strip_prefix("m/") + .ok_or_else(|| anyhow!("BIP-0032 path missing main node"))? + .split('/') + .map(Component::from_str) + .collect::<Result<_>>()?; + + 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<Self> { + 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) + }) + } +} |
