diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/account.rs | 74 | ||||
| -rw-r--r-- | src/account/prehashed.rs | 61 | ||||
| -rw-r--r-- | src/account/public.rs | 17 | ||||
| -rw-r--r-- | src/account/signature.rs | 91 | ||||
| -rw-r--r-- | src/cmd/public_key.rs | 2 | ||||
| -rw-r--r-- | src/hdk.rs | 32 | ||||
| -rw-r--r-- | src/transaction/eip1559.rs | 12 | ||||
| -rw-r--r-- | src/transaction/eip2930.rs | 9 | ||||
| -rw-r--r-- | src/transaction/legacy.rs | 13 |
9 files changed, 176 insertions, 135 deletions
diff --git a/src/account.rs b/src/account.rs index 375afd4..7cf21bb 100644 --- a/src/account.rs +++ b/src/account.rs @@ -1,20 +1,19 @@ //! Module implementing `secp256k1` private key. mod address; +mod prehashed; +mod public; mod signature; -pub use self::{ - address::Address, - signature::{Signature, YParity}, -}; +use self::prehashed::Prehashed; +pub use self::{address::Address, public::PublicKey, signature::Signature}; use crate::hash; use anyhow::Result; -pub use secp256k1::PublicKey; -use secp256k1::{Message, Secp256k1, SecretKey, ONE_KEY}; -use std::{ - convert::TryInto, - fmt::{self, Debug, Formatter}, +use k256::{ + ecdsa::{signature::DigestSigner as _, SigningKey}, + SecretKey, }; +use std::fmt::{self, Debug, Formatter}; /// A struct representing an Ethereum private key. pub struct PrivateKey(SecretKey); @@ -22,54 +21,39 @@ 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())?; + let key = SecretKey::from_be_bytes(secret.as_ref())?; Ok(PrivateKey(key)) } /// Returns the public key for the private key. pub fn public(&self) -> PublicKey { - let secp = Secp256k1::signing_only(); - PublicKey::from_secret_key(&secp, &self.0) + PublicKey(self.0.public_key()) } /// Returns the public address for the private key. pub fn address(&self) -> Address { - let public_key = self.public().serialize_uncompressed(); + let encoded = self.public().encode_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..]); + // the concatenated elliptic curve coordinates of the public key. Note + // that an encoded uncompressed public key is serialized into 65 bytes + // where the first byte is a SEC1 tag that is always 0x04 (representing + // an uncompressed point) and the subsequent bytes are the coordinates + // we want. So discard the first byte for the address calculation. + debug_assert_eq!(encoded[0], 0x04); + let hash = hash::keccak256(&encoded[1..]); + Address::from_slice(&hash[12..]) } /// Returns the private key's 32 byte secret. pub fn secret(&self) -> [u8; 32] { - *self.0.as_ref() + self.0.to_be_bytes().into() } /// 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_ecdsa_recoverable(&message, &self.0) - .serialize_compact(); - debug_assert!(matches!(recovery_id.to_i32(), 0 | 1)); - debug_assert_eq!(raw_signature.len(), 64); - - Signature { - y_parity: match recovery_id.to_i32() { - 0 => YParity::Even, - 1 => YParity::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(), - } + Signature(SigningKey::from(&self.0).sign_digest(Prehashed::Message(message))) } } @@ -79,12 +63,6 @@ impl Debug for PrivateKey { } } -impl Drop for PrivateKey { - fn drop(&mut self) { - self.0 = ONE_KEY; - } -} - #[cfg(test)] mod tests { use super::*; @@ -106,11 +84,11 @@ mod tests { let message = hash::keccak256(b"\x19Ethereum Signed Message:\n12Hello World!"); assert_eq!( key.sign(message), - Signature { - y_parity: YParity::Odd, - r: hex!("408790f153cbfa2722fc708a57d97a43b24429724cf060df7c915d468c43bd84"), - s: hex!("61c96aac95ce37d7a31087b6634f4a3ea439a9f704b5c818584fa2a32fa83859"), - }, + Signature::from_parts( + 1, + hex!("408790f153cbfa2722fc708a57d97a43b24429724cf060df7c915d468c43bd84"), + hex!("61c96aac95ce37d7a31087b6634f4a3ea439a9f704b5c818584fa2a32fa83859"), + ), ); } } diff --git a/src/account/prehashed.rs b/src/account/prehashed.rs new file mode 100644 index 0000000..5952164 --- /dev/null +++ b/src/account/prehashed.rs @@ -0,0 +1,61 @@ +//! The `k256` crate only supports signing messages by passing message bytes and +//! specifying a hasher, or specifying an already partially updated hasher. +//! +//! This module provides a `Digest` implementation that can be used as an +//! allowing `k256` signing to be done on a prehashed messsage. + +use k256::ecdsa::digest::{ + consts::U32, generic_array::GenericArray, BlockInput, FixedOutput, Reset, Update, +}; +use sha2::{digest::core_api::BlockSizeUser, Digest as _, Sha256}; +use std::mem; + +/// A pre-hashed meessage. +#[derive(Clone)] +pub enum Prehashed { + /// The pre-hashed message to use for signing. + Message([u8; 32]), + /// The hasher used for rfc-6979 nonce generation for deterministic ECDSA + /// signature computation. + Rfc6979(Sha256), +} + +impl Default for Prehashed { + fn default() -> Self { + Self::Rfc6979(Sha256::default()) + } +} + +impl BlockInput for Prehashed { + type BlockSize = <Sha256 as BlockSizeUser>::BlockSize; +} + +impl FixedOutput for Prehashed { + type OutputSize = U32; + + fn finalize_into(self, out: &mut GenericArray<u8, Self::OutputSize>) { + match self { + Self::Message(message) => *out = message.into(), + Self::Rfc6979(hasher) => hasher.finalize_into(out), + } + } + + fn finalize_into_reset(&mut self, out: &mut GenericArray<u8, Self::OutputSize>) { + mem::take(self).finalize_into(out) + } +} + +impl Reset for Prehashed { + fn reset(&mut self) { + *self = Default::default(); + } +} + +impl Update for Prehashed { + fn update(&mut self, data: impl AsRef<[u8]>) { + match self { + Prehashed::Message(_) => unimplemented!(), + Prehashed::Rfc6979(hasher) => hasher.update(data), + } + } +} diff --git a/src/account/public.rs b/src/account/public.rs new file mode 100644 index 0000000..c5d0aec --- /dev/null +++ b/src/account/public.rs @@ -0,0 +1,17 @@ +//! Module implementing public key operations. + +use k256::elliptic_curve::sec1::ToEncodedPoint as _; + +/// A public key. +pub struct PublicKey(pub k256::PublicKey); + +impl PublicKey { + /// Returns an uncompressed encoded bytes for the public key. + pub fn encode_uncompressed(&self) -> [u8; 65] { + self.0 + .to_encoded_point(false) + .as_bytes() + .try_into() + .expect("unexpected uncompressed private key length") + } +} diff --git a/src/account/signature.rs b/src/account/signature.rs index f017756..5afa0ca 100644 --- a/src/account/signature.rs +++ b/src/account/signature.rs @@ -1,44 +1,37 @@ //! Module containing signature data model. -use ethnum::{AsU256, U256}; +use ethnum::{AsU256 as _, U256}; +use k256::ecdsa::recoverable; use std::fmt::{self, Display, Formatter}; -/// The parity of the y-value of a secp256k1 signature. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -#[repr(u8)] -pub enum YParity { - /// Even parity. - Even = 0, - /// Odd parity. - Odd = 1, -} - -impl AsU256 for YParity { - fn as_u256(self) -> U256 { - U256::new(self as _) - } -} - /// A secp256k1 signature. #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub struct Signature { - /// Signature V value in Electrum notation. - pub y_parity: YParity, - /// Signature R value. - pub r: [u8; 32], - /// Signature S value. - pub s: [u8; 32], -} +pub struct Signature(pub recoverable::Signature); impl Signature { - /// Returns the signature's V value in Electrum notation. - pub fn v(&self) -> u8 { - 27 + (self.y_parity as u8) + /// 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_replay_protected(&self, chain_id: U256) -> U256 { - self.y_parity.as_u256() + chain_id * 2 + 35 + 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, + } + } + + /// Returns the signature's 32-byte R-value in big-endian representation. + pub fn r(&self) -> U256 { + U256::from_be_bytes(self.0.r().to_bytes().into()) + } + + /// Returns the signature's 32-byte S-value in big-endian representation. + pub fn s(&self) -> U256 { + U256::from_be_bytes(self.0.s().to_bytes().into()) } } @@ -46,10 +39,10 @@ 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(), + "0x{:064x}{:064x}{:02x}", + self.r(), + self.s(), + self.v(None), ) } } @@ -57,24 +50,32 @@ impl Display for Signature { #[cfg(test)] mod tests { use super::*; + use k256::ecdsa::{self, recoverable::Id}; + + impl Signature { + /// Creates a signature from its raw parts. + /// + /// Convinience method used for testing. + pub fn from_parts(y_parity: u8, r: [u8; 32], s: [u8; 32]) -> Self { + Self( + recoverable::Signature::new( + &ecdsa::Signature::from_scalars(r, s).unwrap(), + Id::new(y_parity).unwrap(), + ) + .unwrap(), + ) + } + } #[test] fn replay_protection() { - let signature = Signature { - y_parity: YParity::Even, - r: [1; 32], - s: [2; 32], - }; - assert_eq!(signature.v_replay_protected(U256::new(1)), U256::new(37)); + let signature = Signature::from_parts(0, [1; 32], [2; 32]); + assert_eq!(signature.v(Some(U256::new(1))), U256::new(37)); } #[test] fn signature_to_string() { - let signature = Signature { - y_parity: YParity::Even, - r: [1; 32], - s: [2; 32], - }; + let signature = Signature::from_parts(0, [1; 32], [2; 32]); assert_eq!( signature.to_string(), "0x0101010101010101010101010101010101010101010101010101010101010101\ diff --git a/src/cmd/public_key.rs b/src/cmd/public_key.rs index 360255b..1f724ba 100644 --- a/src/cmd/public_key.rs +++ b/src/cmd/public_key.rs @@ -19,7 +19,7 @@ pub fn run(options: Options) -> Result<()> { .account .private_key()? .public() - .serialize_uncompressed() + .encode_uncompressed() ) ); Ok(()) @@ -6,7 +6,7 @@ pub use self::path::{Component, Path}; use crate::account::PrivateKey; use anyhow::{Context as _, Result}; use hmac::{Hmac, Mac as _}; -use secp256k1::{PublicKey, Secp256k1, SecretKey, Signing}; +use k256::{elliptic_curve::sec1::ToEncodedPoint as _, SecretKey}; use sha2::Sha512; /// A value indicating a path component is hardened. @@ -30,34 +30,31 @@ fn derive_slice(seed: &[u8], path: &Path) -> Result<PrivateKey> { hmac.finalize().into_bytes() }; - let secp = Secp256k1::signing_only(); for (i, component) in path.components().enumerate() { let (secret, chain_code) = extended_key.split_at(32); + let secret = SecretKey::from_be_bytes(secret)?; let mut hmac: Hmac<Sha512> = Hmac::<Sha512>::new_from_slice(chain_code)?; let value = match component { Component::Hardened(value) => { hmac.update(&[0]); - hmac.update(secret); + hmac.update(&secret.to_be_bytes()); value | HARDENED } Component::Normal(value) => { - hmac.update(&public_key(&secp, secret)?); + hmac.update(secret.public_key().to_encoded_point(true).as_bytes()); value } }; hmac.update(&value.to_be_bytes()); let mut child_key = hmac.finalize().into_bytes(); - let child_secret = SecretKey::from_slice(&child_key[..32]) - .and_then(|mut key| { - key.add_assign(secret)?; - Ok(key) - }) - .with_context(|| { - format!("path '{}' component #{} yields invalid child key", path, i) - })?; - child_key[..32].copy_from_slice(child_secret.as_ref()); + + let child_secret = SecretKey::from_be_bytes(&child_key[..32]).with_context(|| { + format!("path '{}' component #{} yields invalid child key", path, i) + })?; + 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()); extended_key = child_key } @@ -65,15 +62,6 @@ fn derive_slice(seed: &[u8], path: &Path) -> Result<PrivateKey> { 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::*; diff --git a/src/transaction/eip1559.rs b/src/transaction/eip1559.rs index c6acf8b..765ce97 100644 --- a/src/transaction/eip1559.rs +++ b/src/transaction/eip1559.rs @@ -6,7 +6,7 @@ use crate::{ transaction::accesslist::AccessList, transaction::rlp, }; -use ethnum::{AsU256 as _, U256}; +use ethnum::U256; use serde::Deserialize; /// An EIP-1559 Ethereum transaction. @@ -19,10 +19,11 @@ pub struct Eip1559Transaction { /// The nonce for the transaction. #[serde(with = "serialization::u256")] pub nonce: U256, - /// The gas price in Wei for the transaction. + /// The maximum priority fee in Wei for the transaction. #[serde(rename = "maxPriorityFeePerGas")] #[serde(with = "serialization::u256")] pub max_priority_fee_per_gas: U256, + /// The maximum gas price in Wei for the transaction. #[serde(rename = "maxFeePerGas")] #[serde(with = "serialization::u256")] pub max_fee_per_gas: U256, @@ -62,9 +63,9 @@ impl Eip1559Transaction { let tail = signature.map(|signature| { [ - rlp::uint(signature.y_parity.as_u256()), - rlp::uint(U256::from_be_bytes(signature.r)), - rlp::uint(U256::from_be_bytes(signature.s)), + rlp::uint(signature.y_parity()), + rlp::uint(signature.r()), + rlp::uint(signature.s()), ] }); @@ -80,6 +81,7 @@ impl Eip1559Transaction { mod tests { use super::*; use crate::transaction::accesslist::StorageSlot; + use ethnum::AsU256 as _; use hex_literal::hex; use serde_json::json; diff --git a/src/transaction/eip2930.rs b/src/transaction/eip2930.rs index 9de2d2c..4a8bcf8 100644 --- a/src/transaction/eip2930.rs +++ b/src/transaction/eip2930.rs @@ -6,7 +6,7 @@ use crate::{ transaction::accesslist::AccessList, transaction::rlp, }; -use ethnum::{AsU256 as _, U256}; +use ethnum::U256; use serde::Deserialize; /// An EIP-2930 Ethereum transaction. @@ -57,9 +57,9 @@ impl Eip2930Transaction { let tail = signature.map(|signature| { [ - rlp::uint(signature.y_parity.as_u256()), - rlp::uint(U256::from_be_bytes(signature.r)), - rlp::uint(U256::from_be_bytes(signature.s)), + rlp::uint(signature.y_parity()), + rlp::uint(signature.r()), + rlp::uint(signature.s()), ] }); @@ -75,6 +75,7 @@ impl Eip2930Transaction { mod tests { use super::*; use crate::transaction::accesslist::StorageSlot; + use ethnum::AsU256 as _; use hex_literal::hex; use serde_json::json; diff --git a/src/transaction/legacy.rs b/src/transaction/legacy.rs index 6680c74..9e0f9bc 100644 --- a/src/transaction/legacy.rs +++ b/src/transaction/legacy.rs @@ -5,7 +5,7 @@ use crate::{ serialization, transaction::rlp, }; -use ethnum::{AsU256 as _, U256}; +use ethnum::U256; use serde::Deserialize; /// A Legacy Ethereum transaction. @@ -48,15 +48,7 @@ impl LegacyTransaction { ]; let tail = signature - .map(|signature| { - ( - self.chain_id.map_or(signature.v().as_u256(), |chain_id| { - signature.v_replay_protected(chain_id) - }), - U256::from_be_bytes(signature.r), - U256::from_be_bytes(signature.s), - ) - }) + .map(|signature| (signature.v(self.chain_id), signature.r(), signature.s())) .or_else(|| Some((self.chain_id?, U256::ZERO, U256::ZERO))) .map(|(v, r, s)| [rlp::uint(v), rlp::uint(r), rlp::uint(s)]); @@ -67,6 +59,7 @@ impl LegacyTransaction { #[cfg(test)] mod tests { use super::*; + use ethnum::AsU256 as _; use hex_literal::hex; use serde_json::json; |
