diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/account.rs | 15 | ||||
| -rw-r--r-- | src/account/signature.rs | 57 | ||||
| -rw-r--r-- | src/cmd/sign.rs | 2 | ||||
| -rw-r--r-- | src/hdk.rs | 2 | ||||
| -rw-r--r-- | src/main.rs | 22 | ||||
| -rw-r--r-- | src/mnemonic.rs | 10 | ||||
| -rw-r--r-- | src/mnemonic/language.rs | 1 | ||||
| -rw-r--r-- | src/mnemonic/wordlist.rs | 6 | ||||
| -rw-r--r-- | src/transaction.rs | 38 |
9 files changed, 99 insertions, 54 deletions
diff --git a/src/account.rs b/src/account.rs index 6233f6a..511d6aa 100644 --- a/src/account.rs +++ b/src/account.rs @@ -3,7 +3,10 @@ mod address; mod signature; -pub use self::{address::Address, signature::Signature}; +pub use self::{ + address::Address, + signature::{Parity, Signature}, +}; use crate::hash; use anyhow::Result; use secp256k1::{ @@ -61,7 +64,11 @@ impl PrivateKey { debug_assert_eq!(raw_signature.len(), 64); Signature { - v: 27 + (recovery_id.to_i32() as u8), + y_parity: match recovery_id.to_i32() { + 0 => Parity::Even, + 1 => Parity::Odd, + n => unreachable!("non 0 or 1 signature y-parity bit {}", n), + }, r: raw_signature[..32].try_into().unwrap(), s: raw_signature[32..].try_into().unwrap(), } @@ -76,7 +83,7 @@ impl Debug for PrivateKey { impl Drop for PrivateKey { fn drop(&mut self) { - self.0 = ONE_KEY + self.0 = ONE_KEY; } } @@ -102,7 +109,7 @@ mod tests { assert_eq!( key.sign(message), Signature { - v: 28, + y_parity: Parity::Odd, r: hex!("408790f153cbfa2722fc708a57d97a43b24429724cf060df7c915d468c43bd84"), s: hex!("61c96aac95ce37d7a31087b6634f4a3ea439a9f704b5c818584fa2a32fa83859"), }, diff --git a/src/account/signature.rs b/src/account/signature.rs index 4c4195b..012aea5 100644 --- a/src/account/signature.rs +++ b/src/account/signature.rs @@ -1,18 +1,41 @@ //! Module containing signature data model. +use ethnum::U256; use std::fmt::{self, Display, Formatter}; +/// Signature Y-parity value. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(u8)] +pub enum Parity { + /// Even parity. + Even = 0, + /// Odd parity. + Odd = 1, +} + /// A secp256k1 signature. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Signature { /// Signature V value in Electrum notation. - pub v: u8, + pub y_parity: Parity, /// Signature R value. pub r: [u8; 32], /// Signature S value. pub s: [u8; 32], } +impl Signature { + /// Returns the signature's V value in Electrum notation. + pub fn v(&self) -> u8 { + 27 + (self.y_parity as u8) + } + + /// Returns the signature's V value with EIP-155 chain replay protection. + pub fn v_replay_protected(&self, chain_id: U256) -> U256 { + U256::new(self.y_parity as _) + chain_id * 2 + 35 + } +} + impl Display for Signature { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!( @@ -20,7 +43,37 @@ impl Display for Signature { "0x{}{}{:02x}", hex::encode(&self.r), hex::encode(&self.s), - self.v + self.v(), ) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn replay_protection() { + let signature = Signature { + y_parity: Parity::Even, + r: [1; 32], + s: [2; 32], + }; + assert_eq!(signature.v_replay_protected(U256::new(1)), U256::new(37)); + } + + #[test] + fn signature_to_string() { + let signature = Signature { + y_parity: Parity::Even, + r: [1; 32], + s: [2; 32], + }; + assert_eq!( + signature.to_string(), + "0x0101010101010101010101010101010101010101010101010101010101010101\ + 0202020202020202020202020202020202020202020202020202020202020202\ + 1b", + ); + } +} diff --git a/src/cmd/sign.rs b/src/cmd/sign.rs index 2dc8881..dd3203d 100644 --- a/src/cmd/sign.rs +++ b/src/cmd/sign.rs @@ -30,7 +30,7 @@ enum Data { /// The chain ID to sign this transaction for. Use 0 to indicate no /// relay protection should be used. #[structopt(short, long, env)] - chain_id: u64, + chain_id: U256, /// Only output the transaction signature instead of the RLP-encoded /// signed transaction. @@ -13,7 +13,7 @@ use secp256k1::{ use sha2::Sha512; /// A value indicating a path component is hardened. -const HARDENED: u32 = 0x80000000; +const HARDENED: u32 = 0x8000_0000; /// Creates a new extended private key from a seed. pub fn derive(seed: impl AsRef<[u8]>, path: &Path) -> Result<PrivateKey> { diff --git a/src/main.rs b/src/main.rs index 8385469..01480e7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,10 +9,10 @@ mod transaction; #[cfg(test)] mod ganache; -use crate::cmd::*; use std::process; use structopt::StructOpt; +#[allow(clippy::large_enum_variant)] #[derive(Debug, StructOpt)] #[structopt( name = "hdwallet", @@ -20,30 +20,30 @@ use structopt::StructOpt; )] enum Options { #[structopt(about = "Print account public address")] - Address(address::Options), + Address(cmd::address::Options), #[structopt(about = "Export a private key")] - Export(export::Options), + Export(cmd::export::Options), #[structopt(about = "Keccak256 hash data")] Hash(cmd::hash::Options), #[structopt(about = "Hex encoding and decoding")] Hex(cmd::hex::Options), #[structopt(about = "Generate a new HD wallet mnemonic")] - New(new::Options), + New(cmd::new::Options), #[structopt(about = "Export the public key for an account")] - PublicKey(public_key::Options), + PublicKey(cmd::public_key::Options), #[structopt(about = "Sign a message")] - Sign(sign::Options), + Sign(cmd::sign::Options), } fn main() { if let Err(err) = match Options::from_args() { - Options::Address(options) => address::run(options), - Options::Export(options) => export::run(options), + Options::Address(options) => cmd::address::run(options), + Options::Export(options) => cmd::export::run(options), Options::Hash(options) => cmd::hash::run(options), Options::Hex(options) => cmd::hex::run(options), - Options::New(options) => new::run(options), - Options::Sign(options) => sign::run(options), - Options::PublicKey(options) => public_key::run(options), + Options::New(options) => cmd::new::run(options), + Options::Sign(options) => cmd::sign::run(options), + Options::PublicKey(options) => cmd::public_key::run(options), } { if cfg!(debug_assertions) { eprintln!("ERROR: {:?}", err); diff --git a/src/mnemonic.rs b/src/mnemonic.rs index ff0718c..02f9f25 100644 --- a/src/mnemonic.rs +++ b/src/mnemonic.rs @@ -45,7 +45,7 @@ impl Mnemonic { 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]; + let mut buf = [0; 64]; let (seed, hash) = buf.split_at_mut(len); rand::get_entropy(&mut *seed)?; @@ -65,10 +65,10 @@ impl Mnemonic { let buf = { let wordlist = language.wordlist(); - let mut buf = [0u8; 64]; + let mut buf = [0; 64]; let (seed, hash) = buf.split_at_mut(len); - let mut acc = 0usize; + let mut acc = 0; let mut bit_offset = 0; let mut byte_offset = 0; for word in &words { @@ -134,7 +134,7 @@ impl Mnemonic { & WORD_MASK; buf.push_str(wordlist.word(index as _)); - buf.push(separator) + buf.push(separator); } buf.pop(); @@ -145,7 +145,7 @@ impl Mnemonic { pub fn seed(&self, password: impl AsRef<str>) -> Seed { const ROUNDS: u32 = 2048; - let mut buf = [0u8; 64]; + let mut buf = [0; 64]; let salt = format!("mnemonic{}", password.as_ref()); pbkdf2::pbkdf2::<Hmac<Sha512>>( self.to_phrase().as_bytes(), diff --git a/src/mnemonic/language.rs b/src/mnemonic/language.rs index 9ed40ca..7474d31 100644 --- a/src/mnemonic/language.rs +++ b/src/mnemonic/language.rs @@ -42,6 +42,7 @@ impl Language { // TODO(nlordell): Languages such as Chinese use a special Unicode // whitepace character as a word separator for their BIP-0039 mnemonic // phrase. + let _ = self; ' ' } } diff --git a/src/mnemonic/wordlist.rs b/src/mnemonic/wordlist.rs index 5feffa8..702f745 100644 --- a/src/mnemonic/wordlist.rs +++ b/src/mnemonic/wordlist.rs @@ -12,11 +12,7 @@ pub const WORD_COUNT: usize = 2048; impl<'a> Wordlist<'a> { /// Parses a list of newline-separated words. fn parse(words: &'a str) -> Wordlist<'a> { - let words = words - .trim() - .split('\n') - .map(|word| word.trim()) - .collect::<Vec<_>>(); + let words = words.trim().split('\n').map(str::trim).collect::<Vec<_>>(); debug_assert_eq!(words.len(), WORD_COUNT); debug_assert!(words diff --git a/src/transaction.rs b/src/transaction.rs index fe4eb35..5c473f2 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -27,28 +27,24 @@ pub struct Transaction { impl Transaction { /// Returns the RLP encoded transaction with an optional signature. - pub fn encode(&self, chain_id: u64, signature: Option<Signature>) -> Vec<u8> { + pub fn encode(&self, chain_id: U256, signature: Option<Signature>) -> Vec<u8> { // NOTE: This is currently not at all optimal in terms of memory // allocations, but we don't really care. - let (v, r, s) = if let Some(Signature { v, r, s }) = signature { + let (v, r, s) = signature.map_or((chain_id, U256::ZERO, U256::ZERO), |signature| { ( - replay_protection(chain_id, v), - U256::from_be_bytes(r), - U256::from_be_bytes(s), + signature.v_replay_protected(chain_id), + U256::from_be_bytes(signature.r), + U256::from_be_bytes(signature.s), ) - } else { - (chain_id, U256::ZERO, U256::ZERO) - }; + }); rlp::list(&[ &rlp::uint(self.nonce)[..], &rlp::uint(self.gas_price), &rlp::uint(self.gas), - &if let Some(address) = self.to { - rlp::bytes(&*address) - } else { - rlp::bytes(b"") - }, + &self + .to + .map_or_else(|| rlp::bytes(b""), |to| rlp::bytes(&*to)), &rlp::uint(self.value), &rlp::bytes(&self.data), &rlp::uint(v), @@ -58,14 +54,14 @@ impl Transaction { } /// Returns the 32-byte message used for signing. - pub fn signing_message(&self, chain_id: u64) -> [u8; 32] { + pub fn signing_message(&self, chain_id: U256) -> [u8; 32] { hash::keccak256(self.encode(chain_id, None)) } } /// Tiny RLP encoding implementation. mod rlp { - use ethnum::AsU256; + use ethnum::U256; /// RLP encode some bytes. pub fn bytes(bytes: &[u8]) -> Vec<u8> { @@ -107,27 +103,19 @@ mod rlp { /// RLP encode a unsigned integer. This ensures that it is shortned to its /// shortest little endian byte representation. - pub fn uint(value: impl AsU256) -> Vec<u8> { - let value = value.as_u256(); + pub fn uint(value: U256) -> Vec<u8> { let start = value.leading_zeros() / 8; bytes(&value.to_be_bytes()[start as usize..]) } } -/// Apply EIP-155 replay protection to the specified `v` value. -fn replay_protection(chain_id: u64, v: u8) -> u64 { - assert!(v == 27 || v == 28, "invalid signature v-value"); - let v = v as u64; - v + 8 + chain_id * 2 -} - #[cfg(test)] mod tests { use super::*; use crate::{account::PrivateKey, ganache::DETERMINISTIC_PRIVATE_KEY}; use hex_literal::hex; - const CHAIN_ID: u64 = 0x1337; + const CHAIN_ID: U256 = U256::new(0x1337); fn transaction() -> Transaction { Transaction { |
