diff options
| -rw-r--r-- | Cargo.lock | 114 | ||||
| -rw-r--r-- | Cargo.toml | 2 | ||||
| -rw-r--r-- | src/account.rs | 10 | ||||
| -rw-r--r-- | src/account/signature.rs | 44 | ||||
| -rw-r--r-- | src/cmd/new.rs | 2 | ||||
| -rw-r--r-- | src/cmd/sign.rs | 2 | ||||
| -rw-r--r-- | src/hdk.rs | 7 | ||||
| -rw-r--r-- | src/hdk/path.rs | 12 | ||||
| -rw-r--r-- | src/main.rs | 4 | ||||
| -rw-r--r-- | src/mnemonic.rs | 6 | ||||
| -rw-r--r-- | src/mnemonic/language.rs | 13 | ||||
| -rw-r--r-- | src/typeddata.rs | 52 |
12 files changed, 131 insertions, 137 deletions
@@ -4,9 +4,9 @@ version = 3 [[package]] name = "anyhow" -version = "1.0.68" +version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cb2f989d18dd141ab8ae82f64d1a8cdd37e0840f73a406896cf5e99502fab61" +checksum = "224afbd727c3d6e4b90103ece64b8d1b67fbb1973b1046c2281eed3f3803f800" [[package]] name = "base16ct" @@ -37,9 +37,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.78" +version = "1.0.79" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a20104e2335ce8a659d6dd92a51a767a0c062599c73b343fd152cb401e828c3d" +checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" [[package]] name = "cfg-if" @@ -49,9 +49,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "clap" -version = "4.0.32" +version = "4.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7db700bc935f9e43e88d00b0850dae18a63773cfbec6d8e070fccf7fef89a39" +checksum = "f13b9c79b5d1dd500d20ef541215a6423c75829ef43117e1b4d17fd8af0b5d76" dependencies = [ "bitflags", "clap_derive", @@ -64,9 +64,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.0.21" +version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0177313f9f02afc995627906bbd8967e2be069f5261954222dac78290c2b9014" +checksum = "684a277d672e91966334af371f1a7b5833f9aa00b07c84e92fbce95e00208ce8" dependencies = [ "heck", "proc-macro-error", @@ -77,9 +77,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d4198f73e42b4936b35b5bb248d81d2b595ecb170da0bac7655c54eedfa8da8" +checksum = "783fe232adfca04f90f56201b26d79682d4cd2625e0bc7290b95123afe558ade" dependencies = [ "os_str_bytes", ] @@ -144,9 +144,9 @@ dependencies = [ [[package]] name = "ecdsa" -version = "0.14.8" +version = "0.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413301934810f597c1d19ca71c8710e99a3f1ba28a0d2ebc01551a2daeea3c5c" +checksum = "12844141594ad74185a926d030f3b605f6a903b4e3fec351f3ea338ac5b7637e" dependencies = [ "der", "elliptic-curve", @@ -289,18 +289,15 @@ dependencies = [ [[package]] name = "heck" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" [[package]] name = "hermit-abi" -version = "0.2.6" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" -dependencies = [ - "libc", -] +checksum = "856b5cb0902c2b6d65d5fd97dfa30f9b70c7538e770b98eab5ed52d8db923e01" [[package]] name = "hex" @@ -325,9 +322,9 @@ dependencies = [ [[package]] name = "io-lifetimes" -version = "1.0.3" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46112a93252b123d31a119a8d1a1ac19deac4fac6e0e8b0df58f0d4e5870e63c" +checksum = "1abeb7a0dd0f8181267ff8adc397075586500b81b28a73e8a0208b00fc170fb3" dependencies = [ "libc", "windows-sys", @@ -335,9 +332,9 @@ dependencies = [ [[package]] name = "is-terminal" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28dfb6c8100ccc63462345b67d1bbc3679177c75ee4bf59bf29c8b1d110b8189" +checksum = "22e18b0a45d56fe973d6db23972bf5bc46f988a4a2385deac9cc29572f09daef" dependencies = [ "hermit-abi", "io-lifetimes", @@ -353,14 +350,16 @@ checksum = "fad582f4b9e86b6caa621cabeb0963332d92eea04729ab12892c2533951e6440" [[package]] name = "k256" -version = "0.11.6" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72c1e0b51e7ec0a97369623508396067a486bd0cbed95a2659a4b863d28cfc8b" +checksum = "92a55e0ff3b72c262bcf041d9e97f1b84492b68f1c1a384de2323d3dc9403397" dependencies = [ "cfg-if", "ecdsa", "elliptic-curve", + "once_cell", "sha2", + "signature", ] [[package]] @@ -447,9 +446,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.49" +version = "1.0.51" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57a8eca9f9c4ffde41714334dee777596264c7825420f521abc92b5b5deb63a5" +checksum = "5d727cae5b39d21da60fa540906919ad737832fe0b1c165da3a34d6548c849d6" dependencies = [ "unicode-ident", ] @@ -485,9 +484,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.36.6" +version = "0.36.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4feacf7db682c6c329c4ede12649cd36ecab0f3be5b7d74e6a20304725db4549" +checksum = "f43abb88211988493c1abb44a70efa56ff0ce98f233b7b276146f1f3f7ba9644" dependencies = [ "bitflags", "errno", @@ -539,9 +538,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.91" +version = "1.0.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877c235533714907a8c2464236f5c4b2a17262ef1bd71f38f35ea592c8da6883" +checksum = "7434af0dc1cbd59268aa98b4c22c131c0584d2232f6fb166efb993e2832e896a" dependencies = [ "itoa", "ryu", @@ -571,9 +570,9 @@ dependencies = [ [[package]] name = "signature" -version = "1.6.4" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c" +checksum = "8fe458c98333f9c8152221191a77e2a44e8325d0193484af2e9421a53019e57d" dependencies = [ "digest", "rand_core", @@ -614,9 +613,9 @@ dependencies = [ [[package]] name = "termcolor" -version = "1.1.3" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" +checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6" dependencies = [ "winapi-util", ] @@ -632,9 +631,9 @@ dependencies = [ [[package]] name = "tinyvec_macros" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "typenum" @@ -702,9 +701,18 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-sys" -version = "0.42.0" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" +checksum = "8e2522491fbfcd58cc84d47aeb2958948c4b8982e9a2d8a2a35bbaed431390e7" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", @@ -717,45 +725,45 @@ dependencies = [ [[package]] name = "windows_aarch64_gnullvm" -version = "0.42.0" +version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e" +checksum = "8c9864e83243fdec7fc9c5444389dcbbfd258f745e7853198f365e3c4968a608" [[package]] name = "windows_aarch64_msvc" -version = "0.42.0" +version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4" +checksum = "4c8b1b673ffc16c47a9ff48570a9d85e25d265735c503681332589af6253c6c7" [[package]] name = "windows_i686_gnu" -version = "0.42.0" +version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7" +checksum = "de3887528ad530ba7bdbb1faa8275ec7a1155a45ffa57c37993960277145d640" [[package]] name = "windows_i686_msvc" -version = "0.42.0" +version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246" +checksum = "bf4d1122317eddd6ff351aa852118a2418ad4214e6613a50e0191f7004372605" [[package]] name = "windows_x86_64_gnu" -version = "0.42.0" +version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf7b1b21b5362cbc318f686150e5bcea75ecedc74dd157d874d754a2ca44b0ed" +checksum = "c1040f221285e17ebccbc2591ffdc2d44ee1f9186324dd3e84e99ac68d699c45" [[package]] name = "windows_x86_64_gnullvm" -version = "0.42.0" +version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028" +checksum = "628bfdf232daa22b0d64fdb62b09fcc36bb01f05a3939e20ab73aaf9470d0463" [[package]] name = "windows_x86_64_msvc" -version = "0.42.0" +version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5" +checksum = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd" [[package]] name = "zeroize" @@ -16,7 +16,7 @@ ethaddr = { version = "0.1", features = ["macros", "serde"] } ethnum = { version = "1", features = ["serde"] } hex = "0.4" hmac = { version = "0.12", features = ["std"] } -k256 = "0.11" +k256 = "0.12" pbkdf2 = { version = "0.11", default-features = false } serde = { version = "1", features = ["derive"] } serde_json = "1" 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<Signature> { - Ok(Signature(SigningKey::from(&self.0).sign_prehash(&message)?)) + let (signature, recovery_id) = SigningKey::from(&self.0) + .as_nonzero_scalar() + .try_sign_prehashed_rfc6979::<Sha256>(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>) -> 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>) -> 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))); } @@ -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<PrivateKey> { - 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<PrivateKey> { 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<Self> { 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::<Result<_>>()?; @@ -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<usize> { - 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<Self> { 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::<Vec<_>>().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<TypeDefinition<'a>> { 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::<U256, _>(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::<I256, _>(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::<TypedDataBlob>(&format!( r#"{{ - "types": {{ "EIP712Domain": {} }}, + "types": {{ "EIP712Domain": {s} }}, "primaryType": "", "domain": {{}}, "message": {{}} }}"#, - s, )) .unwrap() .verify_domain_type() |
