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/mnemonic.rs | |
| parent | 678d45e7ae09510796d27a80ecd894f6a1ad8279 (diff) | |
hd wallet impl
Diffstat (limited to 'src/mnemonic.rs')
| -rw-r--r-- | src/mnemonic.rs | 112 |
1 files changed, 88 insertions, 24 deletions
diff --git a/src/mnemonic.rs b/src/mnemonic.rs index 791b0c6..bb32d3a 100644 --- a/src/mnemonic.rs +++ b/src/mnemonic.rs @@ -6,12 +6,22 @@ mod wordlist; pub use self::{language::Language, wordlist::WORD_COUNT}; use crate::{hash, rand}; use anyhow::{anyhow, ensure, Result}; -use std::{convert::TryInto, mem}; +use hmac::Hmac; +use sha2::Sha512; +use std::{ + convert::TryInto, + fmt::{self, Display, Formatter}, + mem, + str::FromStr, +}; /// A seed generated from a BIP-0039 mnemonic used for an HD wallet. #[derive(Clone, Debug)] -pub struct Seed { - /// A buffer containing the seed bytes and hash used for checksums. +pub struct Mnemonic { + /// The language for the mnemonic phrase. + language: Language, + /// A buffer containing the mnemonic's binary representation and hash used + /// for checksums. buf: [u8; 64], /// The length of the seed bytes without the 32-byte hash. len: usize, @@ -22,7 +32,7 @@ const WORD_MASK: usize = WORD_COUNT - 1; /// The number of bits represented by each mnemonic word. const WORD_BITS: usize = WORD_MASK.count_ones() as _; -impl Seed { +impl Mnemonic { /// Generates a new cryptographically random seed for the specified mnemonic /// word length. /// @@ -30,7 +40,7 @@ impl Seed { /// length is invalid (it must be in the range `12..=24`) or if there is an /// error reading cryptographically strong entropy from the operating /// system. - pub fn random(mnemonic_length: usize) -> Result<Self> { + pub fn random(language: Language, mnemonic_length: usize) -> Result<Self> { let len = mnemonic_to_byte_length(mnemonic_length)?; let buf = { let mut buf = [0u8; 64]; @@ -42,11 +52,11 @@ impl Seed { buf }; - Ok(Seed { buf, len }) + Ok(Self { language, buf, len }) } - /// Parses a seed from a mnemonic. - pub fn from_mnemonic(mnemonic: impl AsRef<str>) -> Result<Self> { + /// Parses a mnemonic from a phrase. + pub fn from_phrase(mnemonic: impl AsRef<str>) -> Result<Self> { let (language, words) = Language::split(mnemonic.as_ref())?; let len = mnemonic_to_byte_length(words.len())?; @@ -89,23 +99,24 @@ impl Seed { buf }; - Ok(Seed { buf, len }) + Ok(Self { language, buf, len }) } - /// Gets the seed as a slice of bytes. + /// Gets the mnemonic's binary representation as a slice of bytes. + #[cfg(test)] pub fn as_bytes(&self) -> &[u8] { &self.buf[..self.len] } - /// Gets the BIP-0039 mnemonic word length for the seed. + /// Gets the BIP-0039 mnemonic word length. pub fn mnemonic_length(&self) -> usize { ((self.len * 8) / WORD_BITS) + 1 } - /// Generates a BIP-0039 mnemonic from the seed. - pub fn to_mnemonic(&self, language: Language) -> String { - let wordlist = language.wordlist(); - let separator = language.separator(); + /// Returns the BIP-0039 mnemonic phrase. + pub fn to_phrase(&self) -> String { + let wordlist = self.language.wordlist(); + let separator = self.language.separator(); let mut buf = String::new(); for i in 0..self.mnemonic_length() { @@ -127,6 +138,39 @@ impl Seed { buf.pop(); buf } + + /// Gets the PBKDF2 stretched binary seed for this mnemonic. + pub fn seed(&self) -> [u8; 64] { + const ROUNDS: u32 = 2048; + // TODO(nlordell): Support mnemonic passwords. This requires the bytes + // to be NFKD normalized. + const PASSWORD: &str = ""; + + let mut buf = [0u8; 64]; + let salt = format!("mnemonic{}", PASSWORD); + pbkdf2::pbkdf2::<Hmac<Sha512>>( + self.to_phrase().as_bytes(), + salt.as_bytes(), + ROUNDS, + &mut buf, + ); + + buf + } +} + +impl Display for Mnemonic { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + f.write_str(&self.to_phrase()) + } +} + +impl FromStr for Mnemonic { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result<Self> { + Self::from_phrase(s) + } } fn mnemonic_to_byte_length(len: usize) -> Result<usize> { @@ -149,20 +193,20 @@ mod tests { use hex_literal::hex; #[test] - fn random_seed() { + fn random_mnemonic() { for &(bit_length, mnemonic_length) in &[(128, 12), (160, 15), (192, 18), (224, 21), (256, 24)] { - let seed = Seed::random(mnemonic_length).unwrap(); - assert_eq!(seed.as_bytes().len() * 8, bit_length); - let all_zeros = seed.as_bytes().iter().all(|&byte| byte == 0); + let mnemonic = Mnemonic::random(Language::English, mnemonic_length).unwrap(); + assert_eq!(mnemonic.as_bytes().len() * 8, bit_length); + let all_zeros = mnemonic.as_bytes().iter().all(|&byte| byte == 0); assert!(!all_zeros); } } #[test] - fn roundtrip_seed_to_mnemonic() { - for &(bytes, mnemonic) in &[ + fn mnemonic_phrases() { + for &(bytes, phrase) in &[ ( &hex!("00000000000000000000000000000000")[..], "abandon abandon abandon abandon abandon abandon \ @@ -188,9 +232,29 @@ mod tests { point ten exist slush involve unfold", ), ] { - let seed = Seed::from_mnemonic(mnemonic).unwrap(); - assert_eq!(seed.as_bytes(), bytes); - assert_eq!(seed.to_mnemonic(Language::English), *mnemonic); + let mnemonic = Mnemonic::from_phrase(phrase).unwrap(); + assert_eq!(mnemonic.as_bytes(), bytes); + assert_eq!(mnemonic.to_phrase(), phrase); } } + + #[test] + fn mnemonic_seed() { + let seed = Mnemonic::from_str( + "myth like bonus scare over problem \ + client lizard pioneer submit female collect", + ) + .unwrap() + .seed(); + + assert_eq!( + seed, + hex!( + "15e7bbc6ac54a721ad440f8ef7d1fa7c + 4f77ae5ec71e24187649e9d228022655 + b9e6fb3659f8e4b2274ac3b1955bf9e5 + 8f150492c44e7aa161095ba0ad926e9e" + ) + ); + } } |
