Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(primitives): k256 crate fallback for secp256k1 module #9989

Merged
merged 18 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ reth-optimism-rpc = { path = "crates/optimism/rpc" }
reth-payload-builder = { path = "crates/payload/builder" }
reth-payload-primitives = { path = "crates/payload/primitives" }
reth-payload-validator = { path = "crates/payload/validator" }
reth-primitives = { path = "crates/primitives", default-features = false, features = ["std"] }
reth-primitives = { path = "crates/primitives", default-features = false, features = ["std", "secp256k1"] }
shekhirin marked this conversation as resolved.
Show resolved Hide resolved
shekhirin marked this conversation as resolved.
Show resolved Hide resolved
reth-primitives-traits = { path = "crates/primitives-traits", default-features = false }
reth-provider = { path = "crates/storage/provider" }
reth-prune = { path = "crates/prune/prune" }
Expand Down
8 changes: 5 additions & 3 deletions crates/primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ secp256k1 = { workspace = true, features = [
"global-context",
"recovery",
"rand",
] }
], optional = true }
k256 = { version = "0.13", default-features = false, features = ["ecdsa"], optional = true }
shekhirin marked this conversation as resolved.
Show resolved Hide resolved
# for eip-4844
c-kzg = { workspace = true, features = ["serde"], optional = true }

Expand Down Expand Up @@ -81,10 +82,9 @@ pprof = { workspace = true, features = [
"frame-pointer",
"criterion",
] }
secp256k1.workspace = true

[features]
default = ["c-kzg", "alloy-compat", "std", "reth-codec"]
default = ["c-kzg", "alloy-compat", "std", "reth-codec", "secp256k1"]
shekhirin marked this conversation as resolved.
Show resolved Hide resolved
std = ["thiserror-no-std?/std", "reth-primitives-traits/std"]
reth-codec = ["dep:reth-codecs", "dep:zstd", "dep:modular-bitfield"]
asm-keccak = ["alloy-primitives/asm-keccak"]
Expand All @@ -100,6 +100,8 @@ arbitrary = [
"dep:proptest",
"reth-codec",
]
secp256k1 = ["dep:secp256k1"]
k256 = ["dep:k256"]
c-kzg = ["dep:c-kzg", "revm-primitives/c-kzg", "dep:tempfile", "alloy-eips/kzg", "dep:thiserror-no-std"]
optimism = [
"reth-chainspec/optimism",
Expand Down
20 changes: 10 additions & 10 deletions crates/primitives/src/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1653,18 +1653,14 @@ impl<T> WithEncoded<Option<T>> {
#[cfg(test)]
mod tests {
use crate::{
hex, sign_message,
transaction::{
signature::Signature, TxEip1559, TxKind, TxLegacy, PARALLEL_SENDER_RECOVERY_THRESHOLD,
},
hex,
transaction::{signature::Signature, TxEip1559, TxKind, TxLegacy},
Address, Bytes, Transaction, TransactionSigned, TransactionSignedEcRecovered,
TransactionSignedNoHash, B256, U256,
};
use alloy_primitives::{address, b256, bytes};
use alloy_rlp::{Decodable, Encodable, Error as RlpError};
use proptest_arbitrary_interop::arb;
use reth_codecs::Compact;
use secp256k1::{Keypair, Secp256k1};
use std::str::FromStr;

#[test]
Expand Down Expand Up @@ -1934,23 +1930,27 @@ mod tests {
assert_eq!(data.as_slice(), b.as_slice());
}

#[cfg(feature = "secp256k1")]
proptest::proptest! {
#![proptest_config(proptest::prelude::ProptestConfig::with_cases(1))]

#[test]
fn test_parallel_recovery_order(txes in proptest::collection::vec(arb::<Transaction>(), *PARALLEL_SENDER_RECOVERY_THRESHOLD * 5)) {
fn test_parallel_recovery_order(txes in proptest::collection::vec(
proptest_arbitrary_interop::arb::<Transaction>(),
*crate::transaction::PARALLEL_SENDER_RECOVERY_THRESHOLD * 5
)) {
let mut rng =rand::thread_rng();
let secp = Secp256k1::new();
let secp = secp256k1::Secp256k1::new();
let txes: Vec<TransactionSigned> = txes.into_iter().map(|mut tx| {
if let Some(chain_id) = tx.chain_id() {
// Otherwise we might overflow when calculating `v` on `recalculate_hash`
tx.set_chain_id(chain_id % (u64::MAX / 2 - 36));
}

let key_pair = Keypair::new(&secp, &mut rng);
let key_pair = secp256k1::Keypair::new(&secp, &mut rng);

let signature =
sign_message(B256::from_slice(&key_pair.secret_bytes()[..]), tx.signature_hash()).unwrap();
crate::sign_message(B256::from_slice(&key_pair.secret_bytes()[..]), tx.signature_hash()).unwrap();

TransactionSigned::from_transaction_and_signature(tx, signature)
}).collect();
Expand Down
106 changes: 95 additions & 11 deletions crates/primitives/src/transaction/util.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
pub(crate) mod secp256k1 {
use crate::{Address, Signature};
use revm_primitives::B256;

// Silence the `unused_imports` warning for the `k256` feature if both `secp256k1` and `k256` are
// enabled.
#[cfg(all(feature = "k256", feature = "secp256k1"))]
#[allow(unused_imports)]
use k256 as _;

#[cfg(feature = "secp256k1")]
mod impl_secp256k1 {
use super::*;
use crate::{keccak256, Address, Signature};
use crate::keccak256;
pub(crate) use ::secp256k1::Error;
use ::secp256k1::{
ecdsa::{RecoverableSignature, RecoveryId},
Message, PublicKey, SecretKey, SECP256K1,
};
use revm_primitives::{B256, U256};
use revm_primitives::U256;

/// Recovers the address of the sender using secp256k1 pubkey recovery.
///
Expand All @@ -24,7 +34,7 @@ pub(crate) mod secp256k1 {

/// Signs message with the given secret key.
/// Returns the corresponding signature.
pub fn sign_message(secret: B256, message: B256) -> Result<Signature, secp256k1::Error> {
pub fn sign_message(secret: B256, message: B256) -> Result<Signature, Error> {
let sec = SecretKey::from_slice(secret.as_ref())?;
let s = SECP256K1.sign_ecdsa_recoverable(&Message::from_digest(message.0), &sec);
let (rec_id, data) = s.serialize_compact();
Expand All @@ -47,17 +57,91 @@ pub(crate) mod secp256k1 {
}
}

#[cfg(feature = "k256")]
// If both `secp256k1` and `k256` are enabled, then we need to silence the warnings
#[cfg_attr(all(feature = "k256", feature = "secp256k1"), allow(unused, unreachable_pub))]
mod impl_k256 {
use super::*;
use crate::keccak256;
pub(crate) use ::k256::ecdsa::Error;
use k256::ecdsa::{RecoveryId, SigningKey, VerifyingKey};
use revm_primitives::U256;

/// Recovers the address of the sender using secp256k1 pubkey recovery.
///
/// Converts the public key into an ethereum address by hashing the public key with keccak256.
///
/// This does not ensure that the `s` value in the signature is low, and _just_ wraps the
/// underlying secp256k1 library.
pub fn recover_signer_unchecked(sig: &[u8; 65], msg: &[u8; 32]) -> Result<Address, Error> {
let mut signature = k256::ecdsa::Signature::from_slice(&sig[0..64])?;
let mut recid = sig[64];

// normalize signature and flip recovery id if needed.
if let Some(sig_normalized) = signature.normalize_s() {
signature = sig_normalized;
recid ^= 1;
}
let recid = RecoveryId::from_byte(recid).expect("recovery ID is valid");

// recover key
let recovered_key = VerifyingKey::recover_from_prehash(&msg[..], &signature, recid)?;
Ok(public_key_to_address(recovered_key))
}

/// Signs message with the given secret key.
/// Returns the corresponding signature.
pub fn sign_message(secret: B256, message: B256) -> Result<Signature, Error> {
let sec = SigningKey::from_slice(secret.as_ref())?;
let (s, rec_id) = sec.sign_recoverable(&message.0)?;
let data = s.to_bytes();

let signature = Signature {
r: U256::try_from_be_slice(&data[..32]).expect("The slice has at most 32 bytes"),
s: U256::try_from_be_slice(&data[32..64]).expect("The slice has at most 32 bytes"),
odd_y_parity: rec_id.is_y_odd(),
};
Ok(signature)
}

/// Converts a public key into an ethereum address by hashing the encoded public key with
/// keccak256.
pub fn public_key_to_address(public: VerifyingKey) -> Address {
let hash = keccak256(&public.to_encoded_point(/* compress = */ false).as_bytes()[1..]);
Address::from_slice(&hash[12..])
}
}

// Do not check `not(feature = "k256")` because then compilation with `--all-features` will fail.
#[cfg(feature = "secp256k1")]
pub(crate) mod secp256k1 {
pub use super::impl_secp256k1::*;
}

#[cfg(all(feature = "k256", not(feature = "secp256k1")))]
pub(crate) mod secp256k1 {
pub use super::impl_k256::*;
}

#[cfg(test)]
mod tests {
use super::*;
use crate::{address, hex};
#[cfg(feature = "secp256k1")]
#[test]
fn sanity_ecrecover_call_secp256k1() {
let sig = crate::hex!("650acf9d3f5f0a2c799776a1254355d5f4061762a237396a99a0e0e3fc2bcd6729514a0dacb2e623ac4abd157cb18163ff942280db4d5caad66ddf941ba12e0300");
let hash = crate::hex!("47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad");
let out = crate::address!("c08b5542d177ac6686946920409741463a15dddb");

assert_eq!(super::impl_secp256k1::recover_signer_unchecked(&sig, &hash), Ok(out));
}

#[cfg(feature = "k256")]
#[test]
fn sanity_ecrecover_call() {
let sig = hex!("650acf9d3f5f0a2c799776a1254355d5f4061762a237396a99a0e0e3fc2bcd6729514a0dacb2e623ac4abd157cb18163ff942280db4d5caad66ddf941ba12e0300");
let hash = hex!("47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad");
let out = address!("c08b5542d177ac6686946920409741463a15dddb");
fn sanity_ecrecover_call_k256() {
let sig = crate::hex!("650acf9d3f5f0a2c799776a1254355d5f4061762a237396a99a0e0e3fc2bcd6729514a0dacb2e623ac4abd157cb18163ff942280db4d5caad66ddf941ba12e0300");
let hash = crate::hex!("47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad");
let out = crate::address!("c08b5542d177ac6686946920409741463a15dddb");

assert_eq!(secp256k1::recover_signer_unchecked(&sig, &hash), Ok(out));
assert_eq!(super::impl_k256::recover_signer_unchecked(&sig, &hash).ok(), Some(out));
}
}
Loading