diff options
Diffstat (limited to 'src/hdk.rs')
| -rw-r--r-- | src/hdk.rs | 29 |
1 files changed, 16 insertions, 13 deletions
@@ -3,8 +3,8 @@ mod path; pub use self::path::{Component, Path}; -use crate::{account::PrivateKey, mnemonic::Mnemonic}; -use anyhow::{anyhow, Result}; +use crate::account::PrivateKey; +use anyhow::{Context as _, Result}; use hmac::{Hmac, Mac as _, NewMac as _}; use secp256k1::{ key::{PublicKey, SecretKey}, @@ -16,21 +16,18 @@ use sha2::Sha512; const HARDENED: u32 = 0x80000000; /// Creates a new extended private key from a seed. -pub fn derive(mnemonic: &Mnemonic, path: &Path) -> Result<PrivateKey> { +pub fn derive(seed: impl AsRef<[u8]>, path: &Path) -> Result<PrivateKey> { let mut extended_key = { - let mut hmac = - Hmac::<Sha512>::new_varkey(b"Bitcoin seed").map_err(|_| anyhow!("invalid HMAC key"))?; - hmac.update(&mnemonic.seed()); + let mut hmac = Hmac::<Sha512>::new_varkey(b"Bitcoin seed")?; + hmac.update(seed.as_ref()); hmac.finalize().into_bytes() }; let secp = Secp256k1::signing_only(); - for component in path.components() { + for (i, component) in path.components().enumerate() { let (secret, chain_code) = extended_key.split_at(32); - let mut hmac: Hmac<Sha512> = - Hmac::<Sha512>::new_varkey(chain_code).map_err(|_| anyhow!("invalid chain code"))?; - + let mut hmac: Hmac<Sha512> = Hmac::<Sha512>::new_varkey(chain_code)?; let value = match component { Component::Hardened(value) => { hmac.update(&[0]); @@ -45,8 +42,14 @@ pub fn derive(mnemonic: &Mnemonic, path: &Path) -> Result<PrivateKey> { hmac.update(&value.to_be_bytes()); let mut child_key = hmac.finalize().into_bytes(); - let mut child_secret = SecretKey::from_slice(&child_key[..32])?; - child_secret.add_assign(secret)?; + let child_secret = SecretKey::from_slice(&child_key[..32]) + .and_then(|mut key| { + key.add_assign(secret)?; + Ok(key) + }) + .with_context(|| { + format!("path '{}' component #{} yields invalid child key", path, i) + })?; child_key[..32].copy_from_slice(child_secret.as_ref()); extended_key = child_key @@ -77,7 +80,7 @@ mod tests { let mnemonic = GANACHE_DETERMINISTIC_MNEMONIC.parse::<Mnemonic>().unwrap(); let path = "m/44'/60'/0'/0/0".parse::<Path>().unwrap(); - let account = derive(&mnemonic, &path).unwrap(); + let account = derive(mnemonic.seed(""), &path).unwrap(); assert_eq!( account.address(), Address(hex!("90F8bf6A479f320ead074411a4B0e7944Ea8c9C1")), |
