diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/account.rs | 100 | ||||
| -rw-r--r-- | src/account/address.rs | 115 | ||||
| -rw-r--r-- | src/account/signature.rs | 26 | ||||
| -rw-r--r-- | src/cmd.rs | 28 | ||||
| -rw-r--r-- | src/cmd/address.rs | 18 | ||||
| -rw-r--r-- | src/cmd/new.rs | 9 | ||||
| -rw-r--r-- | src/hash.rs | 10 | ||||
| -rw-r--r-- | src/hdk.rs | 86 | ||||
| -rw-r--r-- | src/hdk/path.rs | 62 | ||||
| -rw-r--r-- | src/main.rs | 4 | ||||
| -rw-r--r-- | src/mnemonic.rs | 112 |
11 files changed, 540 insertions, 30 deletions
diff --git a/src/account.rs b/src/account.rs new file mode 100644 index 0000000..338913f --- /dev/null +++ b/src/account.rs @@ -0,0 +1,100 @@ +//! Module implementing `secp256k1` private key. + +mod address; +mod signature; + +pub use self::{address::Address, signature::Signature}; +use crate::hash; +use anyhow::Result; +use secp256k1::{ + key::{PublicKey, SecretKey, ONE_KEY}, + Message, Secp256k1, +}; +use std::fmt::{self, Debug, Formatter}; + +/// A struct representing an Ethereum private key. +pub struct PrivateKey(SecretKey); + +impl PrivateKey { + /// Creates a private key from a secret. + pub fn new(secret: impl AsRef<[u8]>) -> Result<Self> { + let key = SecretKey::from_slice(secret.as_ref())?; + Ok(PrivateKey(key)) + } + + /// Returns the public address for the private key. + pub fn address(&self) -> Address { + let secp = Secp256k1::signing_only(); + let public_key = PublicKey::from_secret_key(&secp, &self.0).serialize_uncompressed(); + + // NOTE: An ethereum address is the last 20 bytes of the keccak hash of + // the public key. Note that `libsecp256k1` public key is serialized + // into 65 bytes as the first byte is always 0x04 as a tag to mark a + // uncompressed public key. Discard it for the public address + // calculation. + debug_assert_eq!(public_key[0], 0x04); + let hash = hash::keccak256(&public_key[1..]); + Address::from_slice(&hash[12..]) + } + + /// Generate a signature for the specified message. + pub fn sign(&self, message: [u8; 32]) -> Signature { + let message = Message::from_slice(&message).expect("invalid message"); + + let (recovery_id, raw_signature) = Secp256k1::signing_only() + .sign_recoverable(&message, &self.0) + .serialize_compact(); + debug_assert!(matches!(recovery_id.to_i32(), 0 | 1)); + + let mut signature = Signature::default(); + signature.v = 27 + (recovery_id.to_i32() as u8); + signature.r.copy_from_slice(&raw_signature[..32]); + signature.s.copy_from_slice(&raw_signature[32..]); + + signature + } +} + +impl Debug for PrivateKey { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + f.debug_tuple("PrivateKey").field(&self.address()).finish() + } +} + +impl Drop for PrivateKey { + fn drop(&mut self) { + self.0 = ONE_KEY + } +} + +#[cfg(test)] +mod tests { + use super::*; + use hex_literal::hex; + + const GANACHE_DETERMINISTIC_PRIVATE_KEY: [u8; 32] = + hex!("4f3edf983ac636a65a842ce7c78d9aa706d3b113bce9c46f30d7d21715b23b1d"); + + #[test] + fn ganache_determinitic_address() { + let key = PrivateKey::new(GANACHE_DETERMINISTIC_PRIVATE_KEY).unwrap(); + assert_eq!( + *key.address(), + hex!("90F8bf6A479f320ead074411a4B0e7944Ea8c9C1"), + ); + } + + #[test] + fn ganache_deterministic_signature() { + let key = PrivateKey::new(GANACHE_DETERMINISTIC_PRIVATE_KEY).unwrap(); + let message = hash::keccak256(b"\x19Ethereum Signed Message:\n12Hello World!"); + assert_eq!( + key.sign(message), + Signature { + v: 28, + r: hex!("408790f153cbfa2722fc708a57d97a43b24429724cf060df7c915d468c43bd84"), + s: hex!("61c96aac95ce37d7a31087b6634f4a3ea439a9f704b5c818584fa2a32fa83859"), + }, + ); + } +} diff --git a/src/account/address.rs b/src/account/address.rs new file mode 100644 index 0000000..ea62cc0 --- /dev/null +++ b/src/account/address.rs @@ -0,0 +1,115 @@ +use crate::hash; +use hex::FromHexError; +use std::{ + fmt::{self, Debug, Display, Formatter}, + ops::{Deref, DerefMut}, + str::{self, FromStr}, +}; + +/// An Ethereum public address. +#[derive(Copy, Clone, Default, Eq, PartialEq)] +pub struct Address(pub [u8; 20]); + +impl Address { + /// Creates an address from a slice. + /// + /// # Panics + /// + /// This method panics if the length of the slice is not 20 bytes. + pub fn from_slice(slice: &[u8]) -> Self { + let mut address = Self::default(); + address.as_mut().copy_from_slice(slice); + address + } +} + +impl Debug for Address { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + struct DisplayAsDebug<T>(T); + + impl<T> Debug for DisplayAsDebug<T> + where + T: Display, + { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + self.0.fmt(f) + } + } + + f.debug_tuple("Address") + .field(&DisplayAsDebug(self)) + .finish() + } +} + +impl Display for Address { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + let mut buf = *b"0x0000000000000000000000000000000000000000"; + let addr = &mut buf[2..]; + hex::encode_to_slice(self, addr).expect("error decoding hex"); + + let digest = hash::keccak256(&addr); + for i in 0..addr.len() { + let byte = digest[i / 2]; + let nibble = 0xf & if i % 2 == 0 { byte >> 4 } else { byte }; + if nibble >= 8 { + addr[i] = addr[i].to_ascii_uppercase(); + } + } + + f.write_str(unsafe { str::from_utf8_unchecked(&buf) }) + } +} + +impl AsRef<[u8]> for Address { + fn as_ref(&self) -> &[u8] { + &self.0 + } +} + +impl AsMut<[u8]> for Address { + fn as_mut(&mut self) -> &mut [u8] { + &mut self.0 + } +} + +impl Deref for Address { + type Target = [u8; 20]; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for Address { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl FromStr for Address { + type Err = FromHexError; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + let mut address = Self::default(); + let s = s.strip_prefix("0x").unwrap_or(s); + hex::decode_to_slice(s, address.as_mut())?; + Ok(address) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn checksum_address() { + for s in &[ + "0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1", + "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", + ] { + let address = s.parse::<Address>().unwrap(); + assert_eq!(address.to_string(), *s); + } + } +} diff --git a/src/account/signature.rs b/src/account/signature.rs new file mode 100644 index 0000000..eef37da --- /dev/null +++ b/src/account/signature.rs @@ -0,0 +1,26 @@ +//! Module containing signature data model. + +use std::fmt::{self, Display, Formatter}; + +/// A secp256k1 signature. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct Signature { + /// Signature V value in Electrum notation. + pub v: u8, + /// Signature R value. + pub r: [u8; 32], + /// Signature S value. + pub s: [u8; 32], +} + +impl Display for Signature { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + write!( + f, + "0x{}{}{:02x}", + hex::encode(&self.r), + hex::encode(&self.s), + self.v + ) + } +} @@ -1 +1,29 @@ +//! Module containing subcommands. + +pub mod address; pub mod new; + +use crate::{account::PrivateKey, hdk, mnemonic::Mnemonic}; +use anyhow::Result; +use structopt::StructOpt; + +/// Shared account options. +#[derive(Debug, StructOpt)] +struct AccountOptions { + /// The BIP-0039 mnemonic phrase for seeding the HD wallet. + #[structopt(short, long, env)] + mnemonic: Mnemonic, + + /// The BIP-44 account index for deriving a private from the mnemonic seed + /// phrase. + #[structopt(long, env, default_value = "0")] + account_index: usize, +} + +impl AccountOptions { + /// Returns the private key for the specified account options. + pub fn private_key(&self) -> Result<PrivateKey> { + let path = format!("m/44'/60'/0'/0/{}", self.account_index).parse()?; + hdk::derive(&self.mnemonic, &path) + } +} diff --git a/src/cmd/address.rs b/src/cmd/address.rs new file mode 100644 index 0000000..b0322b2 --- /dev/null +++ b/src/cmd/address.rs @@ -0,0 +1,18 @@ +//! Module implementing the `address` subcommand for displaying the public +//! address for corresponding account. + +use crate::cmd::AccountOptions; +use anyhow::Result; +use structopt::StructOpt; + +#[derive(Debug, StructOpt)] +#[structopt(about = "print account public address")] +pub struct Options { + #[structopt(flatten)] + account: AccountOptions, +} + +pub fn run(options: Options) -> Result<()> { + println!("{}", options.account.private_key()?.address()); + Ok(()) +} diff --git a/src/cmd/new.rs b/src/cmd/new.rs index 9110c34..699b825 100644 --- a/src/cmd/new.rs +++ b/src/cmd/new.rs @@ -1,7 +1,7 @@ -//! Module implementing the `new` command for generating a mnemonic for a new +//! Module implementing the `new` subcommand for generating a mnemonic for a new //! hierarchical deterministic wallet. -use crate::mnemonic::{Language, Seed}; +use crate::mnemonic::{Language, Mnemonic}; use anyhow::Result; use structopt::StructOpt; @@ -18,8 +18,7 @@ pub struct Options { } pub fn run(options: Options) -> Result<()> { - let seed = Seed::random(options.length)?; - println!("{}", seed.to_mnemonic(options.language)); - + let mnemonic = Mnemonic::random(options.language, options.length)?; + println!("{}", mnemonic); Ok(()) } diff --git a/src/hash.rs b/src/hash.rs index 6382a7a..b3091d2 100644 --- a/src/hash.rs +++ b/src/hash.rs @@ -1,6 +1,14 @@ //! Module implementing various hashing utilities. -use sha2::{Digest, Sha256}; +use sha2::{Digest as _, Sha256}; +use sha3::Keccak256; + +/// Returns the Keccak-256 hash of the specified input. +pub fn keccak256(data: impl AsRef<[u8]>) -> [u8; 32] { + let mut hasher = Keccak256::new(); + hasher.update(data.as_ref()); + hasher.finalize().into() +} /// Returns the SHA256 hash of the specified input. pub fn sha256(data: impl AsRef<[u8]>) -> [u8; 32] { diff --git a/src/hdk.rs b/src/hdk.rs new file mode 100644 index 0000000..922bb68 --- /dev/null +++ b/src/hdk.rs @@ -0,0 +1,86 @@ +//! Module implementing the hierachical deterministic key derivation scheme. + +mod path; + +pub use self::path::{Component, Path}; +use crate::{account::PrivateKey, mnemonic::Mnemonic}; +use anyhow::{anyhow, Result}; +use hmac::{Hmac, Mac as _, NewMac as _}; +use secp256k1::{ + key::{PublicKey, SecretKey}, + Secp256k1, Signing, +}; +use sha2::Sha512; + +/// A value indicating a path component is hardened. +const HARDENED: u32 = 0x80000000; + +/// Creates a new extended private key from a seed. +pub fn derive(mnemonic: &Mnemonic, 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()); + hmac.finalize().into_bytes() + }; + + let secp = Secp256k1::signing_only(); + for component in path.components() { + 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 value = match component { + Component::Hardened(value) => { + hmac.update(&[0]); + hmac.update(secret); + value | HARDENED + } + Component::Normal(value) => { + hmac.update(&public_key(&secp, secret)?); + value + } + }; + 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)?; + child_key[..32].copy_from_slice(child_secret.as_ref()); + + extended_key = child_key + } + + PrivateKey::new(&extended_key[..32]) +} + +fn public_key<C>(secp: &Secp256k1<C>, secret: &[u8]) -> Result<[u8; 33]> +where + C: Signing, +{ + let secret_key = SecretKey::from_slice(secret)?; + let public_key = PublicKey::from_secret_key(&secp, &secret_key); + Ok(public_key.serialize()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{account::Address, mnemonic::Mnemonic}; + use hex_literal::hex; + + #[test] + fn ganache_deterministic_mnemonic() { + const GANACHE_DETERMINISTIC_MNEMONIC: &str = "myth like bonus scare over problem \ + client lizard pioneer submit female collect"; + 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(); + assert_eq!( + account.address(), + Address(hex!("90F8bf6A479f320ead074411a4B0e7944Ea8c9C1")), + ); + } +} 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) + }) + } +} diff --git a/src/main.rs b/src/main.rs index 43d938e..fa6e576 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,7 @@ +mod account; mod cmd; mod hash; +mod hdk; mod mnemonic; mod rand; @@ -13,11 +15,13 @@ use structopt::StructOpt; about = "Hierarchical deterministic wallet for Ethereum" )] enum Options { + Address(address::Options), New(new::Options), } fn main() { if let Err(err) = match Options::from_args() { + Options::Address(options) => address::run(options), Options::New(options) => new::run(options), } { if cfg!(debug_assertions) { 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" + ) + ); + } } |
