From 73792f35da2910620c832dfb0873212cd5af7b33 Mon Sep 17 00:00:00 2001 From: Nicholas Rodrigues Lordello Date: Mon, 6 Feb 2023 20:47:28 +0000 Subject: More idiomatic format strings, version bumps --- src/account.rs | 10 +++++++--- src/account/signature.rs | 44 +++++++++++++++++++--------------------- src/cmd/new.rs | 2 +- src/cmd/sign.rs | 2 +- src/hdk.rs | 7 +++---- src/hdk/path.rs | 12 +++++------ src/main.rs | 4 ++-- src/mnemonic.rs | 6 +++--- src/mnemonic/language.rs | 13 ++++-------- src/typeddata.rs | 52 +++++++++++++++++++----------------------------- 10 files changed, 69 insertions(+), 83 deletions(-) (limited to 'src') diff --git a/src/account.rs b/src/account.rs index fb31a8a..e1da1ae 100644 --- a/src/account.rs +++ b/src/account.rs @@ -8,9 +8,10 @@ use crate::hash; use anyhow::Result; use ethaddr::Address; use k256::{ - ecdsa::{signature::hazmat::PrehashSigner as _, SigningKey}, + ecdsa::{hazmat::SignPrimitive, SigningKey}, SecretKey, }; +use sha2::Sha256; use std::fmt::{self, Debug, Formatter}; /// A struct representing an Ethereum private key. @@ -56,7 +57,10 @@ impl PrivateKey { /// Generate a signature for the specified message. pub fn try_sign(&self, message: [u8; 32]) -> Result { - Ok(Signature(SigningKey::from(&self.0).sign_prehash(&message)?)) + let (signature, recovery_id) = SigningKey::from(&self.0) + .as_nonzero_scalar() + .try_sign_prehashed_rfc6979::(message.into(), b"")?; + Ok(Signature(signature, recovery_id.unwrap())) } } @@ -88,9 +92,9 @@ mod tests { assert_eq!( key.sign(message), Signature::from_parts( - 1, hex!("408790f153cbfa2722fc708a57d97a43b24429724cf060df7c915d468c43bd84"), hex!("61c96aac95ce37d7a31087b6634f4a3ea439a9f704b5c818584fa2a32fa83859"), + 1, ), ); } diff --git a/src/account/signature.rs b/src/account/signature.rs index 550ac3d..ba3b959 100644 --- a/src/account/signature.rs +++ b/src/account/signature.rs @@ -2,10 +2,7 @@ use anyhow::bail; use ethnum::{AsU256 as _, U256}; -use k256::ecdsa::{ - self, - recoverable::{self, Id}, -}; +use k256::ecdsa::{self, RecoveryId}; use std::{ fmt::{self, Display, Formatter}, str::FromStr, @@ -13,22 +10,14 @@ use std::{ /// A secp256k1 signature. #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub struct Signature(pub recoverable::Signature); +pub struct Signature(pub ecdsa::Signature, pub RecoveryId); impl Signature { /// Returns the y-parity in its 256-bit integer representation. /// /// Return 0 for even parity, and 1 for odd parity. pub fn y_parity(&self) -> U256 { - u8::from(self.0.recovery_id()).as_u256() - } - - /// Returns the signature's V value with EIP-155 chain replay protection. - pub fn v(&self, chain_id: Option) -> U256 { - match chain_id { - Some(chain_id) => self.y_parity() + chain_id * 2 + 35, - None => self.y_parity() + 27, - } + u8::from(self.1.is_y_odd()).as_u256() } /// Returns the signature's 32-byte R-value in big-endian representation. @@ -41,14 +30,23 @@ impl Signature { U256::from_be_bytes(self.0.s().to_bytes().into()) } + /// Returns the signature's V value with EIP-155 chain replay protection. + pub fn v(&self, chain_id: Option) -> U256 { + match chain_id { + Some(chain_id) => self.y_parity() + chain_id * 2 + 35, + None => self.y_parity() + 27, + } + } + /// Creates a signature from its raw parts. - pub fn from_parts(y_parity: u8, r: [u8; 32], s: [u8; 32]) -> Self { + /// + /// # Panics + /// + /// Panics on invalid signature parts. + pub fn from_parts(r: [u8; 32], s: [u8; 32], y_parity: u8) -> Self { Self( - recoverable::Signature::new( - &ecdsa::Signature::from_scalars(r, s).unwrap(), - Id::new(y_parity).unwrap(), - ) - .unwrap(), + ecdsa::Signature::from_scalars(r, s).unwrap(), + y_parity.try_into().unwrap(), ) } } @@ -80,9 +78,9 @@ impl FromStr for Signature { }; Ok(Self::from_parts( - y_parity, signature[0..32].try_into().unwrap(), signature[32..64].try_into().unwrap(), + y_parity, )) } } @@ -93,13 +91,13 @@ mod tests { #[test] fn replay_protection() { - let signature = Signature::from_parts(0, [1; 32], [2; 32]); + let signature = Signature::from_parts([1; 32], [2; 32], 0); assert_eq!(signature.v(Some(U256::new(1))), U256::new(37)); } #[test] fn signature_to_string() { - let signature = Signature::from_parts(0, [1; 32], [2; 32]); + let signature = Signature::from_parts([1; 32], [2; 32], 0); assert_eq!( signature.to_string(), "0x0101010101010101010101010101010101010101010101010101010101010101\ diff --git a/src/cmd/new.rs b/src/cmd/new.rs index db89958..1c73bb8 100644 --- a/src/cmd/new.rs +++ b/src/cmd/new.rs @@ -18,6 +18,6 @@ pub struct Options { pub fn run(options: Options) -> Result<()> { let mnemonic = Mnemonic::random(options.language, options.length)?; - println!("{}", mnemonic); + println!("{mnemonic}"); Ok(()) } diff --git a/src/cmd/sign.rs b/src/cmd/sign.rs index a8df0df..d3005ea 100644 --- a/src/cmd/sign.rs +++ b/src/cmd/sign.rs @@ -82,7 +82,7 @@ pub fn run(options: Options) -> Result<()> { } let signature = account.sign(transaction.signing_message()); if signature_only { - println!("{}", signature); + println!("{signature}"); } else { println!("0x{}", hex::encode(transaction.encode(signature))); } diff --git a/src/hdk.rs b/src/hdk.rs index 2be1e44..c454c00 100644 --- a/src/hdk.rs +++ b/src/hdk.rs @@ -15,7 +15,7 @@ const HARDENED: u32 = 0x8000_0000; /// Creates a new extended private key for an account index using the standard /// Ethereum HD path. pub fn derive_index(seed: impl AsRef<[u8]>, account_index: usize) -> Result { - derive(seed, &format!("m/44'/60'/0'/0/{}", account_index).parse()?) + derive(seed, &format!("m/44'/60'/0'/0/{account_index}").parse()?) } /// Creates a new extended private key from a seed. @@ -50,9 +50,8 @@ fn derive_slice(seed: &[u8], path: &Path) -> Result { let mut child_key = hmac.finalize().into_bytes(); - let child_secret = SecretKey::from_be_bytes(&child_key[..32]).with_context(|| { - format!("path '{}' component #{} yields invalid child key", path, i) - })?; + let child_secret = SecretKey::from_be_bytes(&child_key[..32]) + .with_context(|| format!("path '{path}' component #{i} yields invalid child key"))?; let next_secret = SecretKey::new(*child_secret.as_scalar_core() + *secret.as_scalar_core()); child_key[..32].copy_from_slice(&next_secret.to_be_bytes()); diff --git a/src/hdk/path.rs b/src/hdk/path.rs index 3d7c0a3..0d05110 100644 --- a/src/hdk/path.rs +++ b/src/hdk/path.rs @@ -1,6 +1,6 @@ //! Module implementing parsing for BIP-0032 HD paths used for key derivation. -use anyhow::{anyhow, Context as _, Result}; +use anyhow::{Context as _, Result}; use std::{ fmt::{self, Display, Formatter}, str::FromStr, @@ -23,7 +23,7 @@ impl Display for Path { fn fmt(&self, f: &mut Formatter) -> fmt::Result { f.write_str("m")?; for component in self.components() { - write!(f, "/{}", component)?; + write!(f, "/{component}")?; } Ok(()) @@ -36,7 +36,7 @@ impl FromStr for Path { fn from_str(s: &str) -> Result { let components = s .strip_prefix("m/") - .ok_or_else(|| anyhow!("BIP-0032 path missing main node"))? + .context("BIP-0032 path missing main node")? .split('/') .map(Component::from_str) .collect::>()?; @@ -57,8 +57,8 @@ pub enum Component { impl Display for Component { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { - Self::Hardened(value) => write!(f, "{}'", value), - Self::Normal(value) => write!(f, "{}", value), + Self::Hardened(value) => write!(f, "{value}'"), + Self::Normal(value) => write!(f, "{value}"), } } } @@ -74,7 +74,7 @@ impl FromStr for Component { let value = value .parse() - .with_context(|| format!("invalid BIP-0032 path component '{}'", s))?; + .with_context(|| format!("invalid BIP-0032 path component '{s}'"))?; Ok(if hardened { Component::Hardened(value) diff --git a/src/main.rs b/src/main.rs index 3eb152f..3f91b7a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -34,9 +34,9 @@ fn main() { Options::PublicKey(options) => cmd::public_key::run(options), } { if cfg!(debug_assertions) { - eprintln!("ERROR: {:?}", err); + eprintln!("ERROR: {err:?}"); } else { - eprintln!("ERROR: {}", err); + eprintln!("ERROR: {err}"); } process::exit(-1); } diff --git a/src/mnemonic.rs b/src/mnemonic.rs index 05d9930..432c88a 100644 --- a/src/mnemonic.rs +++ b/src/mnemonic.rs @@ -5,7 +5,7 @@ mod wordlist; pub use self::{language::Language, wordlist::WORD_COUNT}; use crate::{hash, rand}; -use anyhow::{anyhow, ensure, Result}; +use anyhow::{ensure, Context as _, Result}; use hmac::Hmac; use sha2::Sha512; use std::{ @@ -78,7 +78,7 @@ impl Mnemonic { for word in &words { let index = wordlist .search(word) - .ok_or_else(|| anyhow!("invalid BIP-0039 {} word '{}'", language, word))?; + .with_context(|| format!("invalid BIP-0039 {language} word '{word}'"))?; acc = (acc << WORD_BITS) | index; bit_offset += WORD_BITS; @@ -195,7 +195,7 @@ impl Deref for Seed { } fn mnemonic_to_byte_length(len: usize) -> Result { - ensure!(matches!(len, 12..=24), "invalid mnemonic length {}", len); + ensure!(matches!(len, 12..=24), "invalid mnemonic length {len}"); // NOTE: Derived from the BIP-0039 spec where `CS` is the checksum bit // length, `ENT` is the entropy bit length (so `8 * byte_length`) and `MS` diff --git a/src/mnemonic/language.rs b/src/mnemonic/language.rs index c15101c..7c9fea9 100644 --- a/src/mnemonic/language.rs +++ b/src/mnemonic/language.rs @@ -8,8 +8,10 @@ use std::{ }; /// The mnemonic langage used to select the word list. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, Default)] pub enum Language { + // TODO(nlordell): Read the default language from the system locale. + #[default] English, // TODO(nlordell): Support more languages. Note that this is not necessarily // trivial as some have specific considerations (like 'ñ' being equivalent @@ -46,13 +48,6 @@ impl Language { } } -impl Default for Language { - fn default() -> Self { - // TODO(nlordell): Read the default language from the system locale. - Language::English - } -} - impl Display for Language { fn fmt(&self, f: &mut Formatter) -> fmt::Result { f.write_str(match self { @@ -67,7 +62,7 @@ impl FromStr for Language { fn from_str(s: &str) -> Result { Ok(match s.to_lowercase().as_str() { "english" => Language::English, - _ => bail!("unsupported language '{}'", s), + _ => bail!("unsupported language '{s}'"), }) } } diff --git a/src/typeddata.rs b/src/typeddata.rs index 2035732..35ecdd6 100644 --- a/src/typeddata.rs +++ b/src/typeddata.rs @@ -112,9 +112,7 @@ impl TypedDataBlob { .with_context(|| format!("unexpected EIP-712 domain member {}", member.name))?; ensure!( &member.kind == kind, - "expected EIP-712 domain member {} to be of type {}", - member, - kind + "expected EIP-712 domain member {member} to be of type {kind}", ); Ok(allowed_members) }, @@ -138,7 +136,7 @@ impl Types { &self.encode_value( &member.kind, data.remove(&member.name).with_context(|| { - format!("{} value missing property {}", kind, member.name) + format!("{kind} value missing property {}", member.name) })?, )?, ); @@ -146,8 +144,7 @@ impl Types { ensure!( data.is_empty(), - "additional unspecified {} properties: {}", - kind, + "additional unspecified {kind} properties: {}", data.keys().cloned().collect::>().join(", "), ); Ok(hash::keccak256(&buffer)) @@ -169,7 +166,7 @@ impl Types { let mut buffer = type_definition.to_string(); for sub_type in sub_types.values() { - write!(buffer, "{}", sub_type)?; + write!(buffer, "{sub_type}")?; } Ok(buffer) @@ -177,14 +174,14 @@ impl Types { fn type_hash(&self, kind: &str) -> Result<[u8; 32]> { let encoded_type = self.encode_type(kind)?; - Ok(hash::keccak256(&encoded_type)) + Ok(hash::keccak256(encoded_type)) } fn type_definition<'a>(&'a self, kind: &'a str) -> Result> { let members = self .0 .get(kind) - .with_context(|| format!("missing EIP-712 type definition for {}", kind))?; + .with_context(|| format!("missing EIP-712 type definition for {kind}"))?; Ok(TypeDefinition { kind, members }) } @@ -197,14 +194,13 @@ impl Types { Some(n) => { ensure!( *n == bytes.len() as u32, - "expected byte array of length {} but got {}", - n, + "expected byte array of length {n} but got {}", bytes.len() ); let mut buffer = [0_u8; 32]; buffer .get_mut(..(*n as usize)) - .with_context(|| format!("invalid byte array length {}", n))? + .with_context(|| format!("invalid byte array length {n}"))? .copy_from_slice(&bytes); buffer } @@ -215,9 +211,7 @@ impl Types { let value = permissive::deserialize::(value)?; ensure!( value.leading_zeros() + n >= 256, - "value {:#x} overflows uint{}", - value, - n, + "value {value:#x} overflows uint{n}", ); value.to_be_bytes() } @@ -225,9 +219,7 @@ impl Types { let value = permissive::deserialize::(value)?; ensure!( value.unsigned_abs().leading_zeros() + n >= 256, - "value {:#x} overflows int{}", - value, - n, + "value {value:#x} overflows int{n}", ); value.to_be_bytes() } @@ -246,20 +238,19 @@ impl Types { MemberKind::Struct(inner) => { let value = match value { Value::Object(value) => value, - value => bail!("expected JSON object but got '{}'", value), + value => bail!("expected JSON object but got '{value}'"), }; self.struct_hash(inner, value)? } MemberKind::Array(inner, size) => { let value = match value { Value::Array(value) => value, - value => bail!("expected JSON array but got '{}'", value), + value => bail!("expected JSON array but got '{value}'"), }; if let Some(size) = size { ensure!( value.len() == *size, - "expected fixed array of size {} but got {}", - size, + "expected fixed array of size {size} but got {}", value.len(), ); } @@ -291,10 +282,10 @@ impl Display for TypeDefinition<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}(", self.kind)?; if let Some(first_member) = self.members.get(0) { - write!(f, "{}", first_member)?; + write!(f, "{first_member}")?; } for member in self.members.get(1..).into_iter().flatten() { - write!(f, ",{}", member)?; + write!(f, ",{member}")?; } write!(f, ")") } @@ -373,15 +364,15 @@ impl Display for MemberKind { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { MemberKind::Bytes(None) => f.write_str("bytes"), - MemberKind::Bytes(Some(n)) => write!(f, "bytes{}", n), - MemberKind::Uint(n) => write!(f, "uint{}", n), - MemberKind::Int(n) => write!(f, "int{}", n), + MemberKind::Bytes(Some(n)) => write!(f, "bytes{n}"), + MemberKind::Uint(n) => write!(f, "uint{n}"), + MemberKind::Int(n) => write!(f, "int{n}"), MemberKind::Bool => f.write_str("bool"), MemberKind::Address => f.write_str("address"), MemberKind::String => f.write_str("string"), MemberKind::Struct(kind) => f.write_str(kind), - MemberKind::Array(kind, None) => write!(f, "{}[]", kind), - MemberKind::Array(kind, Some(n)) => write!(f, "{}[{}]", kind, n), + MemberKind::Array(kind, None) => write!(f, "{kind}[]"), + MemberKind::Array(kind, Some(n)) => write!(f, "{kind}[{n}]"), } } } @@ -669,12 +660,11 @@ mod tests { fn verify_domain_type(s: &str) -> Result<()> { serde_json::from_str::(&format!( r#"{{ - "types": {{ "EIP712Domain": {} }}, + "types": {{ "EIP712Domain": {s} }}, "primaryType": "", "domain": {{}}, "message": {{}} }}"#, - s, )) .unwrap() .verify_domain_type() -- cgit v1.2.3