From f007fca552851e18131a9c6705611a85972f0c20 Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin <5773434+shekhirin@users.noreply.github.com> Date: Mon, 15 Dec 2025 15:11:46 +0000 Subject: [PATCH] replace with keccak256_cached --- crates/chain-state/src/memory_overlay.rs | 7 ++++-- crates/cli/commands/src/db/account_storage.rs | 4 ++-- .../engine/invalid-block-hooks/src/witness.rs | 8 +++---- .../src/tree/payload_processor/multiproof.rs | 6 ++--- .../src/tree/payload_processor/prewarm.rs | 6 ++--- crates/ethereum/evm/tests/execute.rs | 12 ++++++---- crates/ethereum/node/tests/e2e/rpc.rs | 2 +- crates/ethereum/primitives/src/transaction.rs | 6 ++--- crates/net/discv4/src/node.rs | 4 ++-- crates/net/discv4/src/proto.rs | 12 +++++----- crates/optimism/cli/src/ovm_file_codec.rs | 6 ++--- .../consensus/src/validation/isthmus.rs | 4 ++-- crates/optimism/evm/src/l1.rs | 6 ++--- crates/optimism/payload/src/payload.rs | 4 ++-- .../primitives/src/transaction/signed.rs | 6 ++--- crates/primitives-traits/src/account.rs | 4 ++-- crates/primitives-traits/src/header/sealed.rs | 4 ++-- .../src/transaction/signed.rs | 4 ++-- crates/ress/provider/src/recorder.rs | 8 +++---- crates/revm/src/test_utils.rs | 4 ++-- crates/revm/src/witness.rs | 6 ++--- crates/rpc/rpc-eth-api/src/core.rs | 3 ++- crates/rpc/rpc/src/admin.rs | 4 ++-- crates/rpc/rpc/src/web3.rs | 4 ++-- crates/stages/stages/src/stages/execution.rs | 8 +++---- .../stages/src/stages/hashing_account.rs | 8 +++---- .../stages/src/stages/hashing_storage.rs | 21 ++++++++-------- crates/stages/stages/src/stages/merkle.rs | 10 ++++---- crates/stages/stages/src/stages/mod.rs | 4 ++-- .../stages/stages/src/test_utils/test_db.rs | 6 ++--- crates/stateless/src/trie.rs | 12 +++++----- crates/stateless/src/validation.rs | 4 ++-- crates/storage/db-common/src/init.rs | 6 ++--- .../src/providers/database/provider.rs | 20 ++++++++++------ .../src/providers/static_file/manager.rs | 6 +++-- .../storage/provider/src/test_utils/mock.rs | 6 ++--- crates/storage/provider/src/writer/mod.rs | 14 +++++------ crates/trie/common/src/account.rs | 6 ++--- crates/trie/common/src/hashed_state.rs | 24 +++++++++---------- crates/trie/common/src/key.rs | 4 ++-- crates/trie/common/src/proofs.rs | 20 ++++++++-------- crates/trie/db/src/proof.rs | 8 +++---- crates/trie/db/src/storage.rs | 7 +++--- crates/trie/db/tests/proof.rs | 10 ++++---- crates/trie/db/tests/trie.rs | 24 +++++++++---------- crates/trie/db/tests/witness.rs | 20 ++++++++-------- crates/trie/parallel/src/proof.rs | 4 ++-- crates/trie/parallel/src/root.rs | 6 ++--- crates/trie/sparse/src/trie.rs | 6 ++--- crates/trie/trie/benches/hash_post_state.rs | 11 ++++----- crates/trie/trie/src/proof/mod.rs | 10 ++++---- crates/trie/trie/src/proof_v2/value.rs | 2 +- crates/trie/trie/src/trie.rs | 4 ++-- crates/trie/trie/src/verify.rs | 17 ++++++------- crates/trie/trie/src/witness.rs | 14 +++++++---- examples/custom-node/src/primitives/header.rs | 4 ++-- examples/db-access/src/main.rs | 4 ++-- testing/ef-tests/src/models.rs | 4 ++-- 58 files changed, 244 insertions(+), 224 deletions(-) diff --git a/crates/chain-state/src/memory_overlay.rs b/crates/chain-state/src/memory_overlay.rs index cf5f8421b4..b7f2a4fc9b 100644 --- a/crates/chain-state/src/memory_overlay.rs +++ b/crates/chain-state/src/memory_overlay.rs @@ -1,6 +1,8 @@ use super::ExecutedBlock; use alloy_consensus::BlockHeader; -use alloy_primitives::{keccak256, Address, BlockNumber, Bytes, StorageKey, StorageValue, B256}; +use alloy_primitives::{ + utils::keccak256_cached, Address, BlockNumber, Bytes, StorageKey, StorageValue, B256, +}; use reth_errors::ProviderResult; use reth_primitives_traits::{Account, Bytecode, NodePrimitives}; use reth_storage_api::{ @@ -63,7 +65,8 @@ impl<'a, N: NodePrimitives> MemoryOverlayStateProviderRef<'a, N> { fn merged_hashed_storage(&self, address: Address, storage: HashedStorage) -> HashedStorage { let state = &self.trie_input().state; - let mut hashed = state.storages.get(&keccak256(address)).cloned().unwrap_or_default(); + let mut hashed = + state.storages.get(&keccak256_cached(address)).cloned().unwrap_or_default(); hashed.extend(&storage); hashed } diff --git a/crates/cli/commands/src/db/account_storage.rs b/crates/cli/commands/src/db/account_storage.rs index f01fcce9c0..53c10678c6 100644 --- a/crates/cli/commands/src/db/account_storage.rs +++ b/crates/cli/commands/src/db/account_storage.rs @@ -1,4 +1,4 @@ -use alloy_primitives::{keccak256, Address}; +use alloy_primitives::{utils::keccak256_cached, Address}; use clap::Parser; use human_bytes::human_bytes; use reth_codecs::Compact; @@ -60,7 +60,7 @@ impl Command { let hashed_size_estimate = if slot_count > 0 { plain_size + 12 } else { 0 }; let total_estimate = plain_size + hashed_size_estimate; - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); println!("Account: {address}"); println!("Hashed address: {hashed_address}"); diff --git a/crates/engine/invalid-block-hooks/src/witness.rs b/crates/engine/invalid-block-hooks/src/witness.rs index 7388f61775..82d16d025e 100644 --- a/crates/engine/invalid-block-hooks/src/witness.rs +++ b/crates/engine/invalid-block-hooks/src/witness.rs @@ -1,5 +1,5 @@ use alloy_consensus::BlockHeader; -use alloy_primitives::{keccak256, Address, Bytes, B256, U256}; +use alloy_primitives::{utils::keccak256_cached, Address, Bytes, B256, U256}; use alloy_rpc_types_debug::ExecutionWitness; use pretty_assertions::Comparison; use reth_engine_primitives::InvalidBlockHook; @@ -124,12 +124,12 @@ fn collect_execution_data( // Collect codes db.cache.contracts.values().chain(bundle_state.contracts.values()).for_each(|code| { let code_bytes = code.original_bytes(); - codes.insert(keccak256(&code_bytes), code_bytes); + codes.insert(keccak256_cached(&code_bytes), code_bytes); }); // Collect preimages for (address, account) in db.cache.accounts { - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); hashed_state .accounts .insert(hashed_address, account.account.as_ref().map(|a| a.info.clone().into())); @@ -143,7 +143,7 @@ fn collect_execution_data( for (slot, value) in account_data.storage { let slot_bytes = B256::from(slot); - let hashed_slot = keccak256(slot_bytes); + let hashed_slot = keccak256_cached(slot_bytes); storage.storage.insert(hashed_slot, value); preimages.insert(hashed_slot, alloy_rlp::encode(slot_bytes).into()); } diff --git a/crates/engine/tree/src/tree/payload_processor/multiproof.rs b/crates/engine/tree/src/tree/payload_processor/multiproof.rs index 85614646d7..cd4900d3d6 100644 --- a/crates/engine/tree/src/tree/payload_processor/multiproof.rs +++ b/crates/engine/tree/src/tree/payload_processor/multiproof.rs @@ -2,8 +2,8 @@ use alloy_evm::block::StateChangeSource; use alloy_primitives::{ - keccak256, map::{B256Set, HashSet}, + utils::keccak256_cached, B256, }; use crossbeam_channel::{unbounded, Receiver as CrossbeamReceiver, Sender as CrossbeamSender}; @@ -182,7 +182,7 @@ pub(crate) fn evm_state_to_hashed_post_state(update: EvmState) -> HashedPostStat for (address, account) in update { if account.is_touched() { - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); trace!(target: "engine::tree::payload_processor::multiproof", ?address, ?hashed_address, "Adding account to state update"); let destroyed = account.is_selfdestructed(); @@ -193,7 +193,7 @@ pub(crate) fn evm_state_to_hashed_post_state(update: EvmState) -> HashedPostStat .storage .into_iter() .filter(|(_slot, value)| value.is_changed()) - .map(|(slot, value)| (keccak256(B256::from(slot)), value.present_value)) + .map(|(slot, value)| (keccak256_cached(B256::from(slot)), value.present_value)) .peekable(); if destroyed { diff --git a/crates/engine/tree/src/tree/payload_processor/prewarm.rs b/crates/engine/tree/src/tree/payload_processor/prewarm.rs index 056fdc8e0c..5a3838080d 100644 --- a/crates/engine/tree/src/tree/payload_processor/prewarm.rs +++ b/crates/engine/tree/src/tree/payload_processor/prewarm.rs @@ -23,7 +23,7 @@ use crate::tree::{ use alloy_consensus::transaction::TxHashRef; use alloy_eips::Typed2718; use alloy_evm::Database; -use alloy_primitives::{keccak256, map::B256Set, B256}; +use alloy_primitives::{map::B256Set, utils::keccak256_cached, B256}; use crossbeam_channel::Sender as CrossbeamSender; use metrics::{Counter, Gauge, Histogram}; use reth_evm::{execute::ExecutableTxFor, ConfigureEvm, Evm, EvmFor, SpecFor}; @@ -571,11 +571,11 @@ fn multiproof_targets_from_state(state: EvmState) -> (MultiProofTargets, usize) continue } - storage_set.insert(keccak256(B256::new(key.to_be_bytes()))); + storage_set.insert(keccak256_cached(B256::new(key.to_be_bytes()))); } storage_targets += storage_set.len(); - targets.insert(keccak256(addr), storage_set); + targets.insert(keccak256_cached(addr), storage_set); } (targets, storage_targets) diff --git a/crates/ethereum/evm/tests/execute.rs b/crates/ethereum/evm/tests/execute.rs index 61e0c1c4b6..45b8474e7e 100644 --- a/crates/ethereum/evm/tests/execute.rs +++ b/crates/ethereum/evm/tests/execute.rs @@ -9,7 +9,7 @@ use alloy_eips::{ eip7685::EMPTY_REQUESTS_HASH, }; use alloy_evm::block::BlockValidationError; -use alloy_primitives::{b256, fixed_bytes, keccak256, Bytes, TxKind, B256, U256}; +use alloy_primitives::{b256, fixed_bytes, utils::keccak256_cached, Bytes, TxKind, B256, U256}; use reth_chainspec::{ChainSpecBuilder, EthereumHardfork, ForkCondition, MAINNET}; use reth_ethereum_primitives::{Block, BlockBody, Transaction}; use reth_evm::{ @@ -35,7 +35,7 @@ fn create_database_with_beacon_root_contract() -> CacheDB { let beacon_root_contract_account = AccountInfo { balance: U256::ZERO, - code_hash: keccak256(BEACON_ROOTS_CODE.clone()), + code_hash: keccak256_cached(BEACON_ROOTS_CODE.clone()), nonce: 1, code: Some(Bytecode::new_raw(BEACON_ROOTS_CODE.clone())), }; @@ -51,7 +51,7 @@ fn create_database_with_withdrawal_requests_contract() -> CacheDB { let withdrawal_requests_contract_account = AccountInfo { nonce: 1, balance: U256::ZERO, - code_hash: keccak256(WITHDRAWAL_REQUEST_PREDEPLOY_CODE.clone()), + code_hash: keccak256_cached(WITHDRAWAL_REQUEST_PREDEPLOY_CODE.clone()), code: Some(Bytecode::new_raw(WITHDRAWAL_REQUEST_PREDEPLOY_CODE.clone())), }; @@ -331,12 +331,14 @@ fn eip_4788_high_base_fee() { fn create_database_with_block_hashes(latest_block: u64) -> CacheDB { let mut db = CacheDB::new(Default::default()); for block_number in 0..=latest_block { - db.cache.block_hashes.insert(U256::from(block_number), keccak256(block_number.to_string())); + db.cache + .block_hashes + .insert(U256::from(block_number), keccak256_cached(block_number.to_string())); } let blockhashes_contract_account = AccountInfo { balance: U256::ZERO, - code_hash: keccak256(HISTORY_STORAGE_CODE.clone()), + code_hash: keccak256_cached(HISTORY_STORAGE_CODE.clone()), code: Some(Bytecode::new_raw(HISTORY_STORAGE_CODE.clone())), nonce: 1, }; diff --git a/crates/ethereum/node/tests/e2e/rpc.rs b/crates/ethereum/node/tests/e2e/rpc.rs index c149580ca6..75348c489c 100644 --- a/crates/ethereum/node/tests/e2e/rpc.rs +++ b/crates/ethereum/node/tests/e2e/rpc.rs @@ -32,7 +32,7 @@ alloy_sol_types::sol! { contract GasWaster { constructor(uint256 iterations) { for (uint256 i = 0; i < iterations; i++) { - bytes32 slot = keccak256(abi.encode(block.number, i)); + bytes32 slot = keccak256_cached(abi.encode(block.number, i)); assembly { sstore(slot, slot) } diff --git a/crates/ethereum/primitives/src/transaction.rs b/crates/ethereum/primitives/src/transaction.rs index 28782c2ac6..703512a5dd 100644 --- a/crates/ethereum/primitives/src/transaction.rs +++ b/crates/ethereum/primitives/src/transaction.rs @@ -13,7 +13,7 @@ use alloy_eips::{ eip7702::SignedAuthorization, }; use alloy_primitives::{ - bytes::BufMut, keccak256, Address, Bytes, ChainId, Signature, TxHash, TxKind, B256, U256, + bytes::BufMut, utils::keccak256_cached, Address, Bytes, ChainId, Signature, TxHash, TxKind, B256, U256, }; use alloy_rlp::{Decodable, Encodable}; use core::hash::{Hash, Hasher}; @@ -320,7 +320,7 @@ pub struct TransactionSigned { impl TransactionSigned { fn recalculate_hash(&self) -> B256 { - keccak256(self.encoded_2718()) + keccak256_cached(self.encoded_2718()) } } @@ -653,7 +653,7 @@ impl SignerRecoverable for TransactionSigned { fn recover_unchecked_with_buf(&self, buf: &mut Vec) -> Result { self.encode_for_signing(buf); - let signature_hash = keccak256(buf); + let signature_hash = keccak256_cached(buf); recover_signer_unchecked(&self.signature, signature_hash) } } diff --git a/crates/net/discv4/src/node.rs b/crates/net/discv4/src/node.rs index 7e993ff833..5c1620dbf9 100644 --- a/crates/net/discv4/src/node.rs +++ b/crates/net/discv4/src/node.rs @@ -1,4 +1,4 @@ -use alloy_primitives::keccak256; +use alloy_primitives::utils::keccak256_cached; use reth_network_peers::{NodeRecord, PeerId}; /// The key type for the table. @@ -13,7 +13,7 @@ impl From for NodeKey { impl From for discv5::Key { fn from(value: NodeKey) -> Self { - let hash = keccak256(value.0.as_slice()); + let hash = keccak256_cached(value.0.as_slice()); Self::new_raw(value, hash.0.into()) } } diff --git a/crates/net/discv4/src/proto.rs b/crates/net/discv4/src/proto.rs index 2aabd45d99..3c4d848134 100644 --- a/crates/net/discv4/src/proto.rs +++ b/crates/net/discv4/src/proto.rs @@ -3,7 +3,7 @@ use crate::{error::DecodePacketError, MAX_PACKET_SIZE, MIN_PACKET_SIZE}; use alloy_primitives::{ bytes::{Buf, BufMut, Bytes, BytesMut}, - keccak256, B256, + utils::keccak256_cached, B256, }; use alloy_rlp::{ Decodable, Encodable, Error as RlpError, Header, RlpDecodable, RlpEncodable, @@ -115,7 +115,7 @@ impl Message { // Sign the payload with the secret key using recoverable ECDSA let signature: RecoverableSignature = SECP256K1.sign_ecdsa_recoverable( - &secp256k1::Message::from_digest(keccak256(&payload).0), + &secp256k1::Message::from_digest(keccak256_cached(&payload).0), secret_key, ); @@ -126,7 +126,7 @@ impl Message { sig_bytes.unsplit(payload); // Calculate the hash of the signature bytes and append it to the datagram - let hash = keccak256(&sig_bytes); + let hash = keccak256_cached(&sig_bytes); datagram.extend_from_slice(hash.as_slice()); // Append the signature bytes to the datagram @@ -146,10 +146,10 @@ impl Message { // parses the wire-protocol, every packet starts with a header: // packet-header = hash || signature || packet-type - // hash = keccak256(signature || packet-type || packet-data) + // hash = keccak256_cached(signature || packet-type || packet-data) // signature = sign(packet-type || packet-data) - let header_hash = keccak256(&packet[32..]); + let header_hash = keccak256_cached(&packet[32..]); let data_hash = B256::from_slice(&packet[..32]); if data_hash != header_hash { return Err(DecodePacketError::HashMismatch) @@ -160,7 +160,7 @@ impl Message { let recoverable_sig = RecoverableSignature::from_compact(signature, recovery_id)?; // recover the public key - let msg = secp256k1::Message::from_digest(keccak256(&packet[97..]).0); + let msg = secp256k1::Message::from_digest(keccak256_cached(&packet[97..]).0); let pk = SECP256K1.recover_ecdsa(&msg, &recoverable_sig)?; let node_id = pk2id(&pk); diff --git a/crates/optimism/cli/src/ovm_file_codec.rs b/crates/optimism/cli/src/ovm_file_codec.rs index 83f3e48728..a4563e30ec 100644 --- a/crates/optimism/cli/src/ovm_file_codec.rs +++ b/crates/optimism/cli/src/ovm_file_codec.rs @@ -9,7 +9,7 @@ use alloy_eips::{ }; use alloy_primitives::{ bytes::{Buf, BytesMut}, - keccak256, Signature, TxHash, B256, U256, + keccak256_cached, Signature, TxHash, B256, U256, }; use alloy_rlp::{Decodable, Error as RlpError, RlpDecodable}; use derive_more::{AsRef, Deref}; @@ -96,7 +96,7 @@ impl OvmTransactionSigned { /// Calculate transaction hash, eip2728 transaction does not contain rlp header and start with /// tx type. pub fn recalculate_hash(&self) -> B256 { - keccak256(self.encoded_2718()) + keccak256_cached(self.encoded_2718()) } /// Create a new signed transaction from a transaction and its signature. @@ -146,7 +146,7 @@ impl OvmTransactionSigned { let s: U256 = Decodable::decode(data)?; let tx_length = header.payload_length + header.length(); - let hash = keccak256(&original_encoding[..tx_length]); + let hash = keccak256_cached(&original_encoding[..tx_length]); // Handle both pre-bedrock and regular cases let (signature, chain_id) = if v == 0 && r.is_zero() && s.is_zero() { diff --git a/crates/optimism/consensus/src/validation/isthmus.rs b/crates/optimism/consensus/src/validation/isthmus.rs index f35f4ea69a..74ba8ef9b8 100644 --- a/crates/optimism/consensus/src/validation/isthmus.rs +++ b/crates/optimism/consensus/src/validation/isthmus.rs @@ -130,7 +130,7 @@ mod test { use alloc::sync::Arc; use alloy_chains::Chain; use alloy_consensus::Header; - use alloy_primitives::{keccak256, B256, U256}; + use alloy_primitives::{keccak256_cached, B256, U256}; use core::str::FromStr; use reth_db_common::init::init_genesis; use reth_optimism_chainspec::OpChainSpecBuilder; @@ -146,7 +146,7 @@ mod test { #[test] fn l2tol1_message_passer_no_withdrawals() { - let hashed_address = keccak256(L2_TO_L1_MESSAGE_PASSER_ADDRESS); + let hashed_address = keccak256_cached(L2_TO_L1_MESSAGE_PASSER_ADDRESS); // create account storage let init_storage = HashedStorage::from_iter( diff --git a/crates/optimism/evm/src/l1.rs b/crates/optimism/evm/src/l1.rs index 2afe6e9d3a..04f8c99c1f 100644 --- a/crates/optimism/evm/src/l1.rs +++ b/crates/optimism/evm/src/l1.rs @@ -15,7 +15,7 @@ const L1_BLOCK_ECOTONE_SELECTOR: [u8; 4] = hex!("440a5e20"); const L1_BLOCK_ISTHMUS_SELECTOR: [u8; 4] = hex!("098999be"); /// The function selector of the "setL1BlockValuesJovian" function in the `L1Block` contract. -/// This is the first 4 bytes of `keccak256("setL1BlockValuesJovian()")`. +/// This is the first 4 bytes of `keccak256_cached("setL1BlockValuesJovian()")`. const L1_BLOCK_JOVIAN_SELECTOR: [u8; 4] = hex!("3db6be2b"); /// Extracts the [`L1BlockInfo`] from the L2 block. The L1 info transaction is always the first @@ -354,7 +354,7 @@ mod tests { use super::*; use alloy_consensus::{Block, BlockBody}; use alloy_eips::eip2718::Decodable2718; - use alloy_primitives::keccak256; + use alloy_primitives::keccak256_cached; use reth_optimism_chainspec::OP_MAINNET; use reth_optimism_forks::OpHardforks; use reth_optimism_primitives::OpTransactionSigned; @@ -383,7 +383,7 @@ mod tests { #[test] fn test_verify_set_jovian() { - let hash = &keccak256("setL1BlockValuesJovian()")[..4]; + let hash = &keccak256_cached("setL1BlockValuesJovian()")[..4]; assert_eq!(hash, L1_BLOCK_JOVIAN_SELECTOR) } diff --git a/crates/optimism/payload/src/payload.rs b/crates/optimism/payload/src/payload.rs index 3f7b3d401e..0a015e6d34 100644 --- a/crates/optimism/payload/src/payload.rs +++ b/crates/optimism/payload/src/payload.rs @@ -6,7 +6,7 @@ use alloy_consensus::{Block, BlockHeader}; use alloy_eips::{ eip1559::BaseFeeParams, eip2718::Decodable2718, eip4895::Withdrawals, eip7685::Requests, }; -use alloy_primitives::{keccak256, Address, Bytes, B256, B64, U256}; +use alloy_primitives::{keccak256_cached, Address, Bytes, B256, B64, U256}; use alloy_rlp::Encodable; use alloy_rpc_types_engine::{ BlobsBundleV1, ExecutionPayloadEnvelopeV2, ExecutionPayloadFieldV2, ExecutionPayloadV1, @@ -376,7 +376,7 @@ pub fn payload_id_optimism( for tx in txs { // we have to just hash the bytes here because otherwise we would need to decode // the transactions here which really isn't ideal - let tx_hash = keccak256(tx); + let tx_hash = keccak256_cached(tx); // maybe we can try just taking the hash and not decoding hasher.update(tx_hash) } diff --git a/crates/optimism/primitives/src/transaction/signed.rs b/crates/optimism/primitives/src/transaction/signed.rs index fc2f63abd8..4096a0ea30 100644 --- a/crates/optimism/primitives/src/transaction/signed.rs +++ b/crates/optimism/primitives/src/transaction/signed.rs @@ -13,7 +13,7 @@ use alloy_eips::{ eip2930::AccessList, eip7702::SignedAuthorization, }; -use alloy_primitives::{keccak256, Address, Bytes, Signature, TxHash, TxKind, Uint, B256}; +use alloy_primitives::{utils::keccak256_cached, Address, Bytes, Signature, TxHash, TxKind, Uint, B256}; use alloy_rlp::Header; use core::{ hash::{Hash, Hasher}, @@ -138,7 +138,7 @@ impl SignerRecoverable for OpTransactionSigned { OpTypedTransaction::Eip1559(tx) => tx.encode_for_signing(buf), OpTypedTransaction::Eip7702(tx) => tx.encode_for_signing(buf), }; - recover_signer_unchecked(&self.signature, keccak256(buf)) + recover_signer_unchecked(&self.signature, keccak256_cached(buf)) } } @@ -156,7 +156,7 @@ impl IsTyped2718 for OpTransactionSigned { impl SignedTransaction for OpTransactionSigned { fn recalculate_hash(&self) -> B256 { - keccak256(self.encoded_2718()) + keccak256_cached(self.encoded_2718()) } } diff --git a/crates/primitives-traits/src/account.rs b/crates/primitives-traits/src/account.rs index 8c4a496dab..2e9ca7d13d 100644 --- a/crates/primitives-traits/src/account.rs +++ b/crates/primitives-traits/src/account.rs @@ -1,7 +1,7 @@ use crate::InMemorySize; use alloy_consensus::constants::KECCAK_EMPTY; use alloy_genesis::GenesisAccount; -use alloy_primitives::{keccak256, Bytes, B256, U256}; +use alloy_primitives::{utils::keccak256_cached, Bytes, B256, U256}; use alloy_trie::TrieAccount; use derive_more::Deref; use revm_bytecode::{Bytecode as RevmBytecode, BytecodeDecodeError}; @@ -206,7 +206,7 @@ impl From<&GenesisAccount> for Account { Self { nonce: value.nonce.unwrap_or_default(), balance: value.balance, - bytecode_hash: value.code.as_ref().map(keccak256), + bytecode_hash: value.code.as_ref().map(keccak256_cached), } } } diff --git a/crates/primitives-traits/src/header/sealed.rs b/crates/primitives-traits/src/header/sealed.rs index bcf69813f9..680afc8201 100644 --- a/crates/primitives-traits/src/header/sealed.rs +++ b/crates/primitives-traits/src/header/sealed.rs @@ -2,7 +2,7 @@ use crate::{sync::OnceLock, InMemorySize, NodePrimitives}; pub use alloy_consensus::Header; use alloy_consensus::Sealed; use alloy_eips::{eip1898::BlockWithParent, BlockNumHash}; -use alloy_primitives::{keccak256, BlockHash, Sealable}; +use alloy_primitives::{utils::keccak256_cached, BlockHash, Sealable}; use alloy_rlp::{Decodable, Encodable}; use bytes::BufMut; use core::mem; @@ -173,7 +173,7 @@ impl Decodable for SealedHeader { // hash the consumed bytes, the rlp encoded header let consumed = started_len - b.len(); - let hash = keccak256(&buf[..consumed]); + let hash = keccak256_cached(&buf[..consumed]); // update original buffer *buf = *b; diff --git a/crates/primitives-traits/src/transaction/signed.rs b/crates/primitives-traits/src/transaction/signed.rs index a6212a6c68..5ec00bd28e 100644 --- a/crates/primitives-traits/src/transaction/signed.rs +++ b/crates/primitives-traits/src/transaction/signed.rs @@ -7,7 +7,7 @@ use alloy_consensus::{ EthereumTxEnvelope, SignableTransaction, }; use alloy_eips::eip2718::{Decodable2718, Encodable2718, IsTyped2718}; -use alloy_primitives::{keccak256, Address, Signature, B256}; +use alloy_primitives::{utils::keccak256_cached, Address, Signature, B256}; use alloy_rlp::{Decodable, Encodable}; use core::hash::Hash; @@ -76,7 +76,7 @@ pub trait SignedTransaction: /// Calculate transaction hash, eip2728 transaction does not contain rlp header and start with /// tx type. fn recalculate_hash(&self) -> B256 { - keccak256(self.encoded_2718()) + keccak256_cached(self.encoded_2718()) } /// Tries to recover signer and return [`Recovered`] by cloning the type. diff --git a/crates/ress/provider/src/recorder.rs b/crates/ress/provider/src/recorder.rs index ec5afacbf0..496df8a33e 100644 --- a/crates/ress/provider/src/recorder.rs +++ b/crates/ress/provider/src/recorder.rs @@ -1,4 +1,4 @@ -use alloy_primitives::{keccak256, Address, B256, U256}; +use alloy_primitives::{utils::keccak256_cached, Address, B256, U256}; use reth_revm::{ state::{AccountInfo, Bytecode}, Database, @@ -29,15 +29,15 @@ impl Database for StateWitnessRecorderDatabase { fn basic(&mut self, address: Address) -> Result, Self::Error> { let maybe_account = self.database.basic(address)?; - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); self.state.accounts.insert(hashed_address, maybe_account.as_ref().map(|acc| acc.into())); Ok(maybe_account) } fn storage(&mut self, address: Address, index: U256) -> Result { let value = self.database.storage(address, index)?; - let hashed_address = keccak256(address); - let hashed_slot = keccak256(B256::from(index)); + let hashed_address = keccak256_cached(address); + let hashed_slot = keccak256_cached(B256::from(index)); self.state .storages .entry(hashed_address) diff --git a/crates/revm/src/test_utils.rs b/crates/revm/src/test_utils.rs index e0d4007087..404d5f5d04 100644 --- a/crates/revm/src/test_utils.rs +++ b/crates/revm/src/test_utils.rs @@ -1,6 +1,6 @@ use alloc::vec::Vec; use alloy_primitives::{ - keccak256, map::HashMap, Address, BlockNumber, Bytes, StorageKey, B256, U256, + utils::keccak256_cached, map::HashMap, Address, BlockNumber, Bytes, StorageKey, B256, U256, }; use reth_primitives_traits::{Account, Bytecode}; use reth_storage_api::{ @@ -31,7 +31,7 @@ impl StateProviderTest { storage: HashMap, ) { if let Some(bytecode) = bytecode { - let hash = keccak256(&bytecode); + let hash = keccak256_cached(&bytecode); account.bytecode_hash = Some(hash); self.contracts.insert(hash, Bytecode::new_raw(bytecode)); } diff --git a/crates/revm/src/witness.rs b/crates/revm/src/witness.rs index b59d72116c..6de8422e35 100644 --- a/crates/revm/src/witness.rs +++ b/crates/revm/src/witness.rs @@ -1,5 +1,5 @@ use alloc::vec::Vec; -use alloy_primitives::{keccak256, Bytes, B256}; +use alloy_primitives::{utils::keccak256_cached, Bytes, B256}; use reth_trie::{HashedPostState, HashedStorage}; use revm::database::State; @@ -47,7 +47,7 @@ impl ExecutionWitnessRecord { .collect(); for (address, account) in &statedb.cache.accounts { - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); self.hashed_state .accounts .insert(hashed_address, account.account.as_ref().map(|a| (&a.info).into())); @@ -63,7 +63,7 @@ impl ExecutionWitnessRecord { for (slot, value) in &account.storage { let slot = B256::from(*slot); - let hashed_slot = keccak256(slot); + let hashed_slot = keccak256_cached(slot); storage.storage.insert(hashed_slot, *value); self.keys.push(slot.into()); diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index 6ca5585858..84ba0d0101 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -361,7 +361,8 @@ pub trait EthApi< #[method(name = "sendRawTransactionSync")] async fn send_raw_transaction_sync(&self, bytes: Bytes) -> RpcResult; - /// Returns an Ethereum specific signature with: sign(keccak256("\x19Ethereum Signed Message:\n" + /// Returns an Ethereum specific signature with: sign(keccak256_cached("\x19Ethereum Signed + /// Message:\n" /// + len(message) + message))). #[method(name = "sign")] async fn sign(&self, address: Address, message: Bytes) -> RpcResult; diff --git a/crates/rpc/rpc/src/admin.rs b/crates/rpc/rpc/src/admin.rs index af5e1ae2ef..afb36602af 100644 --- a/crates/rpc/rpc/src/admin.rs +++ b/crates/rpc/rpc/src/admin.rs @@ -14,7 +14,7 @@ use reth_network_types::PeerKind; use reth_rpc_api::AdminApiServer; use reth_rpc_server_types::ToRpcResult; use reth_transaction_pool::TransactionPool; -use revm_primitives::keccak256; +use alloy_primitives::utils::keccak256_cached; /// `admin` API implementation. /// @@ -76,7 +76,7 @@ where for peer in peers { infos.push(PeerInfo { - id: keccak256(peer.remote_id.as_slice()).to_string(), + id: keccak256_cached(peer.remote_id.as_slice()).to_string(), name: peer.client_version.to_string(), enode: peer.enode, enr: peer.enr, diff --git a/crates/rpc/rpc/src/web3.rs b/crates/rpc/rpc/src/web3.rs index 8a890efbe7..13c0adc984 100644 --- a/crates/rpc/rpc/src/web3.rs +++ b/crates/rpc/rpc/src/web3.rs @@ -1,4 +1,4 @@ -use alloy_primitives::{keccak256, Bytes, B256}; +use alloy_primitives::{utils::keccak256_cached, Bytes, B256}; use async_trait::async_trait; use jsonrpsee::core::RpcResult; use reth_network_api::NetworkInfo; @@ -33,7 +33,7 @@ where /// Handler for `web3_sha3` fn sha3(&self, input: Bytes) -> RpcResult { - Ok(keccak256(input)) + Ok(keccak256_cached(input)) } } diff --git a/crates/stages/stages/src/stages/execution.rs b/crates/stages/stages/src/stages/execution.rs index c8428f93f3..957052e6e8 100644 --- a/crates/stages/stages/src/stages/execution.rs +++ b/crates/stages/stages/src/stages/execution.rs @@ -668,7 +668,7 @@ where mod tests { use super::*; use crate::{stages::MERKLE_STAGE_DEFAULT_REBUILD_THRESHOLD, test_utils::TestStageDB}; - use alloy_primitives::{address, hex_literal::hex, keccak256, Address, B256, U256}; + use alloy_primitives::{address, hex_literal::hex, keccak256_cached, Address, B256, U256}; use alloy_rlp::Decodable; use assert_matches::assert_matches; use reth_chainspec::ChainSpecBuilder; @@ -884,7 +884,7 @@ mod tests { let acc2 = address!("0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b"); let code = hex!("5a465a905090036002900360015500"); let balance = U256::from(0x3635c9adc5dea00000u128); - let code_hash = keccak256(code); + let code_hash = keccak256_cached(code); db_tx .put::( acc1, @@ -1021,7 +1021,7 @@ mod tests { // variables let code = hex!("5a465a905090036002900360015500"); let balance = U256::from(0x3635c9adc5dea00000u128); - let code_hash = keccak256(code); + let code_hash = keccak256_cached(code); // pre state let provider = factory.provider_rw().unwrap(); @@ -1135,7 +1135,7 @@ mod tests { let code = hex!("73095e7baea6a6c7c4c2dfeb977efac326af552d8731ff00"); let balance = U256::from(0x0de0b6b3a7640000u64); - let code_hash = keccak256(code); + let code_hash = keccak256_cached(code); // pre state let caller_info = Account { nonce: 0, balance, bytecode_hash: None }; diff --git a/crates/stages/stages/src/stages/hashing_account.rs b/crates/stages/stages/src/stages/hashing_account.rs index 1e48f2d38e..da05760ce7 100644 --- a/crates/stages/stages/src/stages/hashing_account.rs +++ b/crates/stages/stages/src/stages/hashing_account.rs @@ -1,4 +1,4 @@ -use alloy_primitives::{keccak256, B256}; +use alloy_primitives::{utils::keccak256_cached, B256}; use itertools::Itertools; use reth_config::config::{EtlConfig, HashingConfig}; use reth_db_api::{ @@ -175,7 +175,7 @@ where rayon::spawn(move || { for (address, account) in chunk { let address = address.key().unwrap(); - let _ = tx.send((RawKey::new(keccak256(address)), account)); + let _ = tx.send((RawKey::new(keccak256_cached(address)), account)); } }); @@ -382,7 +382,7 @@ mod tests { let mut hashed_acc_cursor = tx.cursor_read::()?; while let Some((address, account)) = acc_cursor.next()? { - let hashed_addr = keccak256(address); + let hashed_addr = keccak256_cached(address); if let Some((_, acc)) = hashed_acc_cursor.seek_exact(hashed_addr)? { assert_eq!(acc, account) } @@ -407,7 +407,7 @@ mod tests { balance: balance - U256::from(1), bytecode_hash: None, }; - let hashed_addr = keccak256(address); + let hashed_addr = keccak256_cached(address); if let Some((_, acc)) = hashed_acc_cursor.seek_exact(hashed_addr)? { assert_eq!(acc, old_acc) } diff --git a/crates/stages/stages/src/stages/hashing_storage.rs b/crates/stages/stages/src/stages/hashing_storage.rs index c52f800a01..f03e052f48 100644 --- a/crates/stages/stages/src/stages/hashing_storage.rs +++ b/crates/stages/stages/src/stages/hashing_storage.rs @@ -1,4 +1,4 @@ -use alloy_primitives::{bytes::BufMut, keccak256, B256}; +use alloy_primitives::{bytes::BufMut, utils::keccak256_cached, B256}; use itertools::Itertools; use reth_config::config::{EtlConfig, HashingConfig}; use reth_db_api::{ @@ -103,8 +103,8 @@ where rayon::spawn(move || { for (address, slot) in chunk { let mut addr_key = Vec::with_capacity(64); - addr_key.put_slice(keccak256(address).as_slice()); - addr_key.put_slice(keccak256(slot.key).as_slice()); + addr_key.put_slice(keccak256_cached(address).as_slice()); + addr_key.put_slice(keccak256_cached(slot.key).as_slice()); let _ = tx.send((addr_key, CompactU256::from(slot.value))); } }); @@ -368,7 +368,7 @@ mod tests { for _ in 0..2 { let new_entry = StorageEntry { - key: keccak256([rng.random::()]), + key: keccak256_cached([rng.random::()]), value: U256::from(rng.random::() % 30 + 1), }; self.insert_storage_entry( @@ -391,7 +391,7 @@ mod tests { tx, (block_number, Address::random()).into(), StorageEntry { - key: keccak256("mining"), + key: keccak256_cached("mining"), value: U256::from(rng.random::()), }, progress.number == stage_progress, @@ -455,9 +455,9 @@ mod tests { let mut expected = 0; while let Some((address, entry)) = storage_cursor.next()? { - let key = keccak256(entry.key); - let got = - hashed_storage_cursor.seek_by_key_subkey(keccak256(address), key)?; + let key = keccak256_cached(entry.key); + let got = hashed_storage_cursor + .seek_by_key_subkey(keccak256_cached(address), key)?; assert_eq!( got, Some(StorageEntry { key, ..entry }), @@ -493,8 +493,9 @@ mod tests { tx.put::(bn_address.address(), entry)?; if hash { - let hashed_address = keccak256(bn_address.address()); - let hashed_entry = StorageEntry { key: keccak256(entry.key), value: entry.value }; + let hashed_address = keccak256_cached(bn_address.address()); + let hashed_entry = + StorageEntry { key: keccak256_cached(entry.key), value: entry.value }; if let Some(e) = tx .cursor_dup_write::()? diff --git a/crates/stages/stages/src/stages/merkle.rs b/crates/stages/stages/src/stages/merkle.rs index a3a3ac8848..71d4e7117d 100644 --- a/crates/stages/stages/src/stages/merkle.rs +++ b/crates/stages/stages/src/stages/merkle.rs @@ -445,7 +445,7 @@ mod tests { stage_test_suite_ext, ExecuteStageTestRunner, StageTestRunner, StorageKind, TestRunnerError, TestStageDB, UnwindStageTestRunner, }; - use alloy_primitives::{keccak256, U256}; + use alloy_primitives::{keccak256_cached, U256}; use assert_matches::assert_matches; use reth_db_api::cursor::{DbCursorRO, DbCursorRW, DbDupCursorRO}; use reth_primitives_traits::{SealedBlock, StorageEntry}; @@ -781,9 +781,9 @@ mod tests { break } - tree.entry(keccak256(bn_address.address())) + tree.entry(keccak256_cached(bn_address.address())) .or_default() - .insert(keccak256(entry.key), entry.value); + .insert(keccak256_cached(entry.key), entry.value); } for (hashed_address, storage) in tree { for (hashed_slot, value) in storage { @@ -814,13 +814,13 @@ mod tests { if let Some(acc) = account_before_tx.info { tx.put::( - keccak256(account_before_tx.address), + keccak256_cached(account_before_tx.address), acc, ) .unwrap(); } else { tx.delete::( - keccak256(account_before_tx.address), + keccak256_cached(account_before_tx.address), None, ) .unwrap(); diff --git a/crates/stages/stages/src/stages/mod.rs b/crates/stages/stages/src/stages/mod.rs index 4434f153c8..00411d085f 100644 --- a/crates/stages/stages/src/stages/mod.rs +++ b/crates/stages/stages/src/stages/mod.rs @@ -50,7 +50,7 @@ mod tests { use crate::test_utils::{StorageKind, TestStageDB}; use alloy_consensus::{SignableTransaction, TxLegacy}; use alloy_primitives::{ - address, hex_literal::hex, keccak256, BlockNumber, Signature, B256, U256, + address, hex_literal::hex, keccak256_cached, BlockNumber, Signature, B256, U256, }; use alloy_rlp::Decodable; use reth_chainspec::ChainSpecBuilder; @@ -122,7 +122,7 @@ mod tests { // insert pre state let provider_rw = test_db.factory.provider_rw().unwrap(); let code = hex!("5a465a905090036002900360015500"); - let code_hash = keccak256(hex!("5a465a905090036002900360015500")); + let code_hash = keccak256_cached(hex!("5a465a905090036002900360015500")); provider_rw .tx_ref() .put::( diff --git a/crates/stages/stages/src/test_utils/test_db.rs b/crates/stages/stages/src/test_utils/test_db.rs index 5df7707df0..9fb0a3d684 100644 --- a/crates/stages/stages/src/test_utils/test_db.rs +++ b/crates/stages/stages/src/test_utils/test_db.rs @@ -1,4 +1,4 @@ -use alloy_primitives::{keccak256, Address, BlockNumber, TxHash, TxNumber, B256}; +use alloy_primitives::{utils::keccak256_cached, Address, BlockNumber, TxHash, TxNumber, B256}; use reth_chainspec::MAINNET; use reth_db::{ test_utils::{create_test_rw_db, create_test_rw_db_with_path, create_test_static_files_dir}, @@ -369,7 +369,7 @@ impl TestStageDB { { self.commit(|tx| { accounts.into_iter().try_for_each(|(address, (account, storage))| { - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); // Insert into account tables. tx.put::(address, account)?; @@ -377,7 +377,7 @@ impl TestStageDB { // Insert into storage tables. storage.into_iter().filter(|e| !e.value.is_zero()).try_for_each(|entry| { - let hashed_entry = StorageEntry { key: keccak256(entry.key), ..entry }; + let hashed_entry = StorageEntry { key: keccak256_cached(entry.key), ..entry }; let mut cursor = tx.cursor_dup_write::()?; if cursor diff --git a/crates/stateless/src/trie.rs b/crates/stateless/src/trie.rs index 49d1f6cf0f..13c11ccc70 100644 --- a/crates/stateless/src/trie.rs +++ b/crates/stateless/src/trie.rs @@ -1,6 +1,6 @@ use crate::validation::StatelessValidationError; use alloc::{format, vec::Vec}; -use alloy_primitives::{keccak256, map::B256Map, Address, B256, U256}; +use alloy_primitives::{utils::keccak256_cached, map::B256Map, Address, B256, U256}; use alloy_rlp::{Decodable, Encodable}; use alloy_rpc_types_debug::ExecutionWitness; use alloy_trie::{TrieAccount, EMPTY_ROOT_HASH}; @@ -67,7 +67,7 @@ impl StatelessSparseTrie { /// This method will error if the `ExecutionWitness` is not able to guarantee /// that the account is missing from the Trie _and_ the witness was complete. pub fn account(&self, address: Address) -> Result, ProviderError> { - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); if let Some(bytes) = self.inner.get_account_value(&hashed_address) { let account = TrieAccount::decode(&mut bytes.as_slice())?; @@ -88,8 +88,8 @@ impl StatelessSparseTrie { /// This method will error if the `ExecutionWitness` is not able to guarantee /// that the storage was missing from the Trie _and_ the witness was complete. pub fn storage(&self, address: Address, slot: U256) -> Result { - let hashed_address = keccak256(address); - let hashed_slot = keccak256(B256::from(slot)); + let hashed_address = keccak256_cached(address); + let hashed_slot = keccak256_cached(B256::from(slot)); if let Some(raw) = self.inner.get_storage_slot_value(&hashed_address, &hashed_slot) { return Ok(U256::decode(&mut raw.as_slice())?) @@ -181,11 +181,11 @@ fn verify_execution_witness( let mut bytecode = B256Map::default(); for rlp_encoded in &witness.state { - let hash = keccak256(rlp_encoded); + let hash = keccak256_cached(rlp_encoded); state_witness.insert(hash, rlp_encoded.clone()); } for rlp_encoded in &witness.codes { - let hash = keccak256(rlp_encoded); + let hash = keccak256_cached(rlp_encoded); bytecode.insert(hash, Bytecode::new_raw(rlp_encoded.clone())); } diff --git a/crates/stateless/src/validation.rs b/crates/stateless/src/validation.rs index 08d84f8466..a3b7d2f100 100644 --- a/crates/stateless/src/validation.rs +++ b/crates/stateless/src/validation.rs @@ -12,7 +12,7 @@ use alloc::{ vec::Vec, }; use alloy_consensus::{BlockHeader, Header}; -use alloy_primitives::{keccak256, B256}; +use alloy_primitives::{utils::keccak256_cached, B256}; use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_consensus::{Consensus, HeaderValidator}; use reth_errors::ConsensusError; @@ -185,7 +185,7 @@ where .headers .iter() .map(|bytes| { - let hash = keccak256(bytes); + let hash = keccak256_cached(bytes); alloy_rlp::decode_exact::
(bytes) .map(|h| SealedHeader::new(h, hash)) .map_err(|_| StatelessValidationError::HeaderDeserializationFailed) diff --git a/crates/storage/db-common/src/init.rs b/crates/storage/db-common/src/init.rs index f2790dfe23..66e5f64a5b 100644 --- a/crates/storage/db-common/src/init.rs +++ b/crates/storage/db-common/src/init.rs @@ -2,7 +2,7 @@ use alloy_consensus::BlockHeader; use alloy_genesis::GenesisAccount; -use alloy_primitives::{keccak256, map::HashMap, Address, B256, U256}; +use alloy_primitives::{map::HashMap, utils::keccak256_cached, Address, B256, U256}; use reth_chainspec::EthChainSpec; use reth_codecs::Compact; use reth_config::config::EtlConfig; @@ -563,13 +563,13 @@ where let (account, _) = GenesisAccount::from_compact(account.as_slice(), account.len()); // Add to prefix sets - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); prefix_sets.account_prefix_set.insert(Nibbles::unpack(hashed_address)); // Add storage keys to prefix sets if storage exists if let Some(ref storage) = account.storage { for key in storage.keys() { - let hashed_key = keccak256(key); + let hashed_key = keccak256_cached(key); prefix_sets .storage_prefix_sets .entry(hashed_address) diff --git a/crates/storage/provider/src/providers/database/provider.rs b/crates/storage/provider/src/providers/database/provider.rs index f36b0c8bb6..e3bdb113e2 100644 --- a/crates/storage/provider/src/providers/database/provider.rs +++ b/crates/storage/provider/src/providers/database/provider.rs @@ -27,7 +27,7 @@ use alloy_consensus::{ }; use alloy_eips::BlockHashOrNumber; use alloy_primitives::{ - keccak256, + utils::keccak256_cached, map::{hash_map, B256Map, HashMap, HashSet}, Address, BlockHash, BlockNumber, TxHash, TxNumber, B256, }; @@ -2489,7 +2489,7 @@ impl HashingWriter for DatabaseProvi // changes are applied in the correct order. let hashed_accounts = changesets .into_iter() - .map(|(_, e)| (keccak256(e.address), e.info)) + .map(|(_, e)| (keccak256_cached(e.address), e.info)) .collect::>() .into_iter() .rev() @@ -2525,8 +2525,10 @@ impl HashingWriter for DatabaseProvi changesets: impl IntoIterator)>, ) -> ProviderResult>> { let mut hashed_accounts_cursor = self.tx.cursor_write::()?; - let hashed_accounts = - changesets.into_iter().map(|(ad, ac)| (keccak256(ad), ac)).collect::>(); + let hashed_accounts = changesets + .into_iter() + .map(|(ad, ac)| (keccak256_cached(ad), ac)) + .collect::>(); for (hashed_address, account) in &hashed_accounts { if let Some(account) = account { hashed_accounts_cursor.upsert(*hashed_address, account)?; @@ -2545,7 +2547,11 @@ impl HashingWriter for DatabaseProvi let mut hashed_storages = changesets .into_iter() .map(|(BlockNumberAddress((_, address)), storage_entry)| { - (keccak256(address), keccak256(storage_entry.key), storage_entry.value) + ( + keccak256_cached(address), + keccak256_cached(storage_entry.key), + storage_entry.value, + ) }) .collect::>(); hashed_storages.sort_by_key(|(ha, hk, _)| (*ha, *hk)); @@ -2592,10 +2598,10 @@ impl HashingWriter for DatabaseProvi let hashed_storages = storages.into_iter().fold(BTreeMap::new(), |mut map, (address, storage)| { let storage = storage.into_iter().fold(BTreeMap::new(), |mut map, entry| { - map.insert(keccak256(entry.key), entry.value); + map.insert(keccak256_cached(entry.key), entry.value); map }); - map.insert(keccak256(address), storage); + map.insert(keccak256_cached(address), storage); map }); diff --git a/crates/storage/provider/src/providers/static_file/manager.rs b/crates/storage/provider/src/providers/static_file/manager.rs index e06c67f069..38f4a3ed56 100644 --- a/crates/storage/provider/src/providers/static_file/manager.rs +++ b/crates/storage/provider/src/providers/static_file/manager.rs @@ -9,7 +9,9 @@ use crate::{ }; use alloy_consensus::{transaction::TransactionMeta, Header}; use alloy_eips::{eip2718::Encodable2718, BlockHashOrNumber}; -use alloy_primitives::{b256, keccak256, Address, BlockHash, BlockNumber, TxHash, TxNumber, B256}; +use alloy_primitives::{ + b256, utils::keccak256_cached, Address, BlockHash, BlockNumber, TxHash, TxNumber, B256, +}; use dashmap::DashMap; use notify::{RecommendedWatcher, RecursiveMode, Watcher}; use parking_lot::RwLock; @@ -2218,7 +2220,7 @@ where { let (tx_id, tx) = entry; tx.encode_2718(rlp_buf); - Ok((keccak256(rlp_buf), tx_id)) + Ok((keccak256_cached(rlp_buf), tx_id)) } #[cfg(test)] diff --git a/crates/storage/provider/src/test_utils/mock.rs b/crates/storage/provider/src/test_utils/mock.rs index 1ddd03652f..691c14c301 100644 --- a/crates/storage/provider/src/test_utils/mock.rs +++ b/crates/storage/provider/src/test_utils/mock.rs @@ -12,8 +12,8 @@ use alloy_consensus::{ }; use alloy_eips::{BlockHashOrNumber, BlockId, BlockNumberOrTag}; use alloy_primitives::{ - keccak256, map::HashMap, Address, BlockHash, BlockNumber, Bytes, StorageKey, StorageValue, - TxHash, TxNumber, B256, U256, + utils::keccak256_cached, map::HashMap, Address, BlockHash, BlockNumber, Bytes, StorageKey, + StorageValue, TxHash, TxNumber, B256, U256, }; use parking_lot::Mutex; use reth_chain_state::{CanonStateNotifications, CanonStateSubscriptions}; @@ -217,7 +217,7 @@ impl ExtendedAccount { /// Set bytecode and bytecode hash on the extended account pub fn with_bytecode(mut self, bytecode: Bytes) -> Self { - let hash = keccak256(&bytecode); + let hash = keccak256_cached(&bytecode); self.account.bytecode_hash = Some(hash); self.bytecode = Some(Bytecode::new_raw(bytecode)); self diff --git a/crates/storage/provider/src/writer/mod.rs b/crates/storage/provider/src/writer/mod.rs index 0c67634dbf..091da7f483 100644 --- a/crates/storage/provider/src/writer/mod.rs +++ b/crates/storage/provider/src/writer/mod.rs @@ -3,7 +3,7 @@ mod tests { use crate::{ test_utils::create_test_provider_factory, AccountReader, StorageTrieWriter, TrieWriter, }; - use alloy_primitives::{keccak256, map::HashMap, Address, B256, U256}; + use alloy_primitives::{keccak256_cached, map::HashMap, Address, B256, U256}; use reth_db_api::{ cursor::{DbCursorRO, DbCursorRW, DbDupCursorRO}, models::{AccountBeforeTx, BlockNumberAddress}, @@ -37,9 +37,9 @@ mod tests { let addresses = (0..10).map(|_| Address::random()).collect::>(); let destroyed_address = *addresses.first().unwrap(); - let destroyed_address_hashed = keccak256(destroyed_address); + let destroyed_address_hashed = keccak256_cached(destroyed_address); let slot = B256::with_last_byte(1); - let hashed_slot = keccak256(slot); + let hashed_slot = keccak256_cached(slot); { let provider_rw = provider_factory.provider_rw().unwrap(); let mut accounts_cursor = @@ -48,7 +48,7 @@ mod tests { provider_rw.tx_ref().cursor_write::().unwrap(); for address in addresses { - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); accounts_cursor .insert(hashed_address, &Account { nonce: 1, ..Default::default() }) .unwrap(); @@ -897,12 +897,12 @@ mod tests { // insert initial state to the database let tx = provider_rw.tx_ref(); for (address, (account, storage)) in &prestate { - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); tx.put::(hashed_address, *account).unwrap(); for (slot, value) in storage { tx.put::( hashed_address, - StorageEntry { key: keccak256(slot), value: *value }, + StorageEntry { key: keccak256_cached(slot), value: *value }, ) .unwrap(); } @@ -1095,7 +1095,7 @@ mod tests { #[test] fn hashed_state_storage_root() { let address = Address::random(); - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); let provider_factory = create_test_provider_factory(); let provider_rw = provider_factory.provider_rw().unwrap(); let tx = provider_rw.tx_ref(); diff --git a/crates/trie/common/src/account.rs b/crates/trie/common/src/account.rs index b8a86907a1..47f22185e5 100644 --- a/crates/trie/common/src/account.rs +++ b/crates/trie/common/src/account.rs @@ -7,7 +7,7 @@ mod tests { use crate::root::storage_root_unhashed; use alloy_consensus::constants::KECCAK_EMPTY; use alloy_genesis::GenesisAccount; - use alloy_primitives::{keccak256, Bytes, B256, U256}; + use alloy_primitives::{utils::keccak256_cached, Bytes, B256, U256}; use std::collections::BTreeMap; use alloy_trie::EMPTY_ROOT_HASH; @@ -56,14 +56,14 @@ mod tests { assert_eq!(trie_account.nonce, 10); assert_eq!(trie_account.balance, U256::from(1000)); assert_eq!(trie_account.storage_root, expected_storage_root); - assert_eq!(trie_account.code_hash, keccak256([0x60, 0x61])); + assert_eq!(trie_account.code_hash, keccak256_cached([0x60, 0x61])); // Check that the Account converts to the same TrieAccount assert_eq!( Account { nonce: 10, balance: U256::from(1000), - bytecode_hash: Some(keccak256([0x60, 0x61])) + bytecode_hash: Some(keccak256_cached([0x60, 0x61])) } .into_trie_account(expected_storage_root), trie_account diff --git a/crates/trie/common/src/hashed_state.rs b/crates/trie/common/src/hashed_state.rs index edfb821bc6..f7a125d860 100644 --- a/crates/trie/common/src/hashed_state.rs +++ b/crates/trie/common/src/hashed_state.rs @@ -8,7 +8,7 @@ use crate::{ }; use alloc::{borrow::Cow, vec::Vec}; use alloy_primitives::{ - keccak256, + utils::keccak256_cached, map::{hash_map, B256Map, HashMap, HashSet}, Address, B256, U256, }; @@ -431,7 +431,7 @@ impl HashedStorage { ) -> Self { Self::from_iter( status.was_destroyed(), - storage.into_iter().map(|(key, value)| (keccak256(B256::from(*key)), *value)), + storage.into_iter().map(|(key, value)| (keccak256_cached(B256::from(*key)), *value)), ) } @@ -889,7 +889,7 @@ mod tests { // Validate the account info. assert_eq!( - *hashed_state.accounts.get(&keccak256(address)).unwrap(), + *hashed_state.accounts.get(&keccak256_cached(address)).unwrap(), Some(account_info.into()) ); } @@ -908,16 +908,16 @@ mod tests { }; // Create hashed accounts with addresses. - let account_1 = (keccak256(address_1), Some(account_info_1.into())); - let account_2 = (keccak256(address_2), None); + let account_1 = (keccak256_cached(address_1), Some(account_info_1.into())); + let account_2 = (keccak256_cached(address_2), None); // Add accounts to the hashed post state. let hashed_state = HashedPostState::default().with_accounts(vec![account_1, account_2]); // Validate the hashed post state. assert_eq!(hashed_state.accounts.len(), 2); - assert!(hashed_state.accounts.contains_key(&keccak256(address_1))); - assert!(hashed_state.accounts.contains_key(&keccak256(address_2))); + assert!(hashed_state.accounts.contains_key(&keccak256_cached(address_1))); + assert!(hashed_state.accounts.contains_key(&keccak256_cached(address_2))); } #[test] @@ -926,16 +926,16 @@ mod tests { let address_1 = Address::random(); let address_2 = Address::random(); - let storage_1 = (keccak256(address_1), HashedStorage::new(false)); - let storage_2 = (keccak256(address_2), HashedStorage::new(true)); + let storage_1 = (keccak256_cached(address_1), HashedStorage::new(false)); + let storage_2 = (keccak256_cached(address_2), HashedStorage::new(true)); // Add storages to the hashed post state. let hashed_state = HashedPostState::default().with_storages(vec![storage_1, storage_2]); // Validate the hashed post state. assert_eq!(hashed_state.storages.len(), 2); - assert!(hashed_state.storages.contains_key(&keccak256(address_1))); - assert!(hashed_state.storages.contains_key(&keccak256(address_2))); + assert!(hashed_state.storages.contains_key(&keccak256_cached(address_1))); + assert!(hashed_state.storages.contains_key(&keccak256_cached(address_2))); } #[test] @@ -946,7 +946,7 @@ mod tests { // Add an account and validate the state is no longer empty. let non_empty_state = HashedPostState::default() - .with_accounts(vec![(keccak256(Address::random()), Some(Account::default()))]); + .with_accounts(vec![(keccak256_cached(Address::random()), Some(Account::default()))]); assert!(!non_empty_state.is_empty()); } diff --git a/crates/trie/common/src/key.rs b/crates/trie/common/src/key.rs index 5a42bcd1f6..9510f75d3d 100644 --- a/crates/trie/common/src/key.rs +++ b/crates/trie/common/src/key.rs @@ -1,4 +1,4 @@ -use alloy_primitives::{keccak256, B256}; +use alloy_primitives::{utils::keccak256_cached, B256}; /// Trait for hashing keys in state. pub trait KeyHasher: Default + Clone + Send + Sync + 'static { @@ -13,6 +13,6 @@ pub struct KeccakKeyHasher; impl KeyHasher for KeccakKeyHasher { #[inline] fn hash_key>(bytes: T) -> B256 { - keccak256(bytes) + keccak256_cached(bytes) } } diff --git a/crates/trie/common/src/proofs.rs b/crates/trie/common/src/proofs.rs index a8e0bb59b9..702d210f12 100644 --- a/crates/trie/common/src/proofs.rs +++ b/crates/trie/common/src/proofs.rs @@ -4,8 +4,8 @@ use crate::{Nibbles, TrieAccount}; use alloc::{borrow::Cow, vec::Vec}; use alloy_consensus::constants::KECCAK_EMPTY; use alloy_primitives::{ - keccak256, map::{hash_map, B256Map, B256Set, HashMap}, + utils::keccak256_cached, Address, Bytes, B256, U256, }; use alloy_rlp::{encode_fixed_size, Decodable, EMPTY_STRING_CODE}; @@ -221,7 +221,7 @@ impl MultiProof { address: Address, slots: &[B256], ) -> Result { - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); let nibbles = Nibbles::unpack(hashed_address); // Retrieve the account proof. @@ -350,7 +350,7 @@ impl DecodedMultiProof { address: Address, slots: &[B256], ) -> Result { - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); let nibbles = Nibbles::unpack(hashed_address); // Retrieve the account proof. @@ -475,7 +475,7 @@ impl StorageMultiProof { /// Return storage proofs for the target storage slot (unhashed). pub fn storage_proof(&self, slot: B256) -> Result { - let nibbles = Nibbles::unpack(keccak256(slot)); + let nibbles = Nibbles::unpack(keccak256_cached(slot)); // Retrieve the storage proof. let proof = self @@ -527,7 +527,7 @@ impl DecodedStorageMultiProof { /// Return storage proofs for the target storage slot (unhashed). pub fn storage_proof(&self, slot: B256) -> Result { - let nibbles = Nibbles::unpack(keccak256(slot)); + let nibbles = Nibbles::unpack(keccak256_cached(slot)); // Retrieve the storage proof. let proof = self @@ -684,7 +684,7 @@ impl AccountProof { self.info.unwrap_or_default().into_trie_account(self.storage_root), )) }; - let nibbles = Nibbles::unpack(keccak256(self.address)); + let nibbles = Nibbles::unpack(keccak256_cached(self.address)); verify_proof(root, nibbles, expected, &self.proof) } } @@ -742,7 +742,7 @@ pub struct StorageProof { impl StorageProof { /// Create new storage proof from the storage slot. pub fn new(key: B256) -> Self { - let nibbles = Nibbles::unpack(keccak256(key)); + let nibbles = Nibbles::unpack(keccak256_cached(key)); Self { key, nibbles, ..Default::default() } } @@ -817,7 +817,7 @@ pub struct DecodedStorageProof { impl DecodedStorageProof { /// Create new storage proof from the storage slot. pub fn new(key: B256) -> Self { - let nibbles = Nibbles::unpack(keccak256(key)); + let nibbles = Nibbles::unpack(keccak256_cached(key)); Self { key, nibbles, ..Default::default() } } @@ -842,7 +842,7 @@ impl DecodedStorageProof { /// for compatibility with `triehash` crate. #[cfg(any(test, feature = "test-utils"))] pub mod triehash { - use alloy_primitives::{keccak256, B256}; + use alloy_primitives::{utils::keccak256_cached, B256}; use alloy_rlp::RlpEncodable; use hash_db::Hasher; use plain_hasher::PlainHasher; @@ -860,7 +860,7 @@ pub mod triehash { const LENGTH: usize = 32; fn hash(x: &[u8]) -> Self::Out { - keccak256(x) + keccak256_cached(x) } } } diff --git a/crates/trie/db/src/proof.rs b/crates/trie/db/src/proof.rs index 597fe7a039..7250e4965c 100644 --- a/crates/trie/db/src/proof.rs +++ b/crates/trie/db/src/proof.rs @@ -1,5 +1,5 @@ use crate::{DatabaseHashedCursorFactory, DatabaseTrieCursorFactory}; -use alloy_primitives::{keccak256, map::HashMap, Address, B256}; +use alloy_primitives::{map::HashMap, utils::keccak256_cached, Address, B256}; use reth_db_api::transaction::DbTx; use reth_execution_errors::StateProofError; use reth_trie::{ @@ -113,7 +113,7 @@ impl<'a, TX: DbTx> DatabaseStorageProof<'a, TX> slot: B256, storage: HashedStorage, ) -> Result { - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); let prefix_set = storage.construct_prefix_set(); let state_sorted = HashedPostStateSorted::new( Default::default(), @@ -134,8 +134,8 @@ impl<'a, TX: DbTx> DatabaseStorageProof<'a, TX> slots: &[B256], storage: HashedStorage, ) -> Result { - let hashed_address = keccak256(address); - let targets = slots.iter().map(keccak256).collect(); + let hashed_address = keccak256_cached(address); + let targets = slots.iter().map(keccak256_cached).collect(); let prefix_set = storage.construct_prefix_set(); let state_sorted = HashedPostStateSorted::new( Default::default(), diff --git a/crates/trie/db/src/storage.rs b/crates/trie/db/src/storage.rs index 42d0d464c7..fe506cd64e 100644 --- a/crates/trie/db/src/storage.rs +++ b/crates/trie/db/src/storage.rs @@ -1,5 +1,5 @@ use crate::{DatabaseHashedCursorFactory, DatabaseTrieCursorFactory}; -use alloy_primitives::{keccak256, map::hash_map, Address, BlockNumber, B256}; +use alloy_primitives::{utils::keccak256_cached, map::hash_map, Address, BlockNumber, B256}; use reth_db_api::{ cursor::DbCursorRO, models::BlockNumberAddress, tables, transaction::DbTx, DatabaseError, }; @@ -66,7 +66,8 @@ impl<'a, TX: DbTx> DatabaseStorageRoot<'a, TX> ) -> Result { let prefix_set = hashed_storage.construct_prefix_set().freeze(); let state_sorted = - HashedPostState::from_hashed_storage(keccak256(address), hashed_storage).into_sorted(); + HashedPostState::from_hashed_storage(keccak256_cached(address), hashed_storage) + .into_sorted(); StorageRoot::new( DatabaseTrieCursorFactory::new(tx), HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(tx), &state_sorted), @@ -86,7 +87,7 @@ impl DatabaseHashedStorage for HashedStorage { for entry in storage_changesets_cursor.walk_range(BlockNumberAddress((from, address))..)? { let (BlockNumberAddress((_, storage_address)), storage_change) = entry?; if storage_address == address { - let hashed_slot = keccak256(storage_change.key); + let hashed_slot = keccak256_cached(storage_change.key); if let hash_map::Entry::Vacant(entry) = storage.storage.entry(hashed_slot) { entry.insert(storage_change.value); } diff --git a/crates/trie/db/tests/proof.rs b/crates/trie/db/tests/proof.rs index 402f0cabff..253b4949ef 100644 --- a/crates/trie/db/tests/proof.rs +++ b/crates/trie/db/tests/proof.rs @@ -1,7 +1,7 @@ #![allow(missing_docs)] use alloy_consensus::EMPTY_ROOT_HASH; -use alloy_primitives::{address, b256, keccak256, Address, Bytes, B256, U256}; +use alloy_primitives::{address, b256, keccak256_cached, Address, Bytes, B256, U256}; use alloy_rlp::EMPTY_STRING_CODE; use reth_chainspec::{Chain, ChainSpec, HOLESKY, MAINNET}; use reth_primitives_traits::Account; @@ -213,7 +213,7 @@ fn holesky_deposit_contract_proof() { storage_proofs: Vec::from([ StorageProof { key: slot_22, - nibbles: Nibbles::unpack(keccak256(slot_22)), + nibbles: Nibbles::unpack(keccak256_cached(slot_22)), value: U256::from_str( "0xf5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b", ) @@ -226,7 +226,7 @@ fn holesky_deposit_contract_proof() { }, StorageProof { key: slot_23, - nibbles: Nibbles::unpack(keccak256(slot_23)), + nibbles: Nibbles::unpack(keccak256_cached(slot_23)), value: U256::from_str( "0xdb56114e00fdd4c1f85c892bf35ac9a89289aaecb1ebd0a96cde606a748b5d71", ) @@ -239,7 +239,7 @@ fn holesky_deposit_contract_proof() { }, StorageProof { key: slot_24, - nibbles: Nibbles::unpack(keccak256(slot_24)), + nibbles: Nibbles::unpack(keccak256_cached(slot_24)), value: U256::from_str( "0xc78009fdf07fc56a11f122370658a353aaa542ed63e44c4bc15ff4cd105ab33c", ) @@ -252,7 +252,7 @@ fn holesky_deposit_contract_proof() { }, StorageProof { key: slot_100, - nibbles: Nibbles::unpack(keccak256(slot_100)), + nibbles: Nibbles::unpack(keccak256_cached(slot_100)), value: U256::ZERO, proof: convert_to_proof([ "0xf9019180a0aafd5b14a6edacd149e110ba6776a654f2dbffca340902be933d011113f2750380a0a502c93b1918c4c6534d4593ae03a5a23fa10ebc30ffb7080b297bff2446e42da02eb2bf45fd443bd1df8b6f9c09726a4c6252a0f7896a131a081e39a7f644b38980a0a9cf7f673a0bce76fd40332afe8601542910b48dea44e93933a3e5e930da5d19a0ddf79db0a36d0c8134ba143bcb541cd4795a9a2bae8aca0ba24b8d8963c2a77da0b973ec0f48f710bf79f63688485755cbe87f9d4c68326bb83c26af620802a80ea0f0855349af6bf84afc8bca2eda31c8ef8c5139be1929eeb3da4ba6b68a818cb0a0c271e189aeeb1db5d59d7fe87d7d6327bbe7cfa389619016459196497de3ccdea0e7503ba5799e77aa31bbe1310c312ca17b2c5bcc8fa38f266675e8f154c2516ba09278b846696d37213ab9d20a5eb42b03db3173ce490a2ef3b2f3b3600579fc63a0e9041059114f9c910adeca12dbba1fef79b2e2c8899f2d7213cd22dfe4310561a047c59da56bb2bf348c9dd2a2e8f5538a92b904b661cfe54a4298b85868bbe4858080", diff --git a/crates/trie/db/tests/trie.rs b/crates/trie/db/tests/trie.rs index 8f543a711d..4aa1c85b7b 100644 --- a/crates/trie/db/tests/trie.rs +++ b/crates/trie/db/tests/trie.rs @@ -2,7 +2,7 @@ use alloy_consensus::EMPTY_ROOT_HASH; use alloy_primitives::{ - address, b256, hex_literal::hex, keccak256, map::HashMap, Address, B256, U256, + address, b256, hex_literal::hex, keccak256_cached, map::HashMap, Address, B256, U256, }; use alloy_rlp::Encodable; use proptest::{prelude::ProptestConfig, proptest}; @@ -34,7 +34,7 @@ fn insert_account( account: Account, storage: &BTreeMap, ) { - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); tx.put::(hashed_address, account).unwrap(); insert_storage(tx, hashed_address, storage); } @@ -43,7 +43,7 @@ fn insert_storage(tx: &impl DbTxMut, hashed_address: B256, storage: &BTreeMap( hashed_address, - StorageEntry { key: keccak256(k), value: *v }, + StorageEntry { key: keccak256_cached(k), value: *v }, ) .unwrap(); } @@ -117,13 +117,13 @@ fn arbitrary_storage_root() { proptest!(ProptestConfig::with_cases(10), |(item in arb::<(Address, std::collections::BTreeMap)>())| { let (address, storage) = item; - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); let factory = create_test_provider_factory(); let tx = factory.provider_rw().unwrap(); for (key, value) in &storage { tx.tx_ref().put::( hashed_address, - StorageEntry { key: keccak256(key), value: *value }, + StorageEntry { key: keccak256_cached(key), value: *value }, ) .unwrap(); } @@ -160,7 +160,7 @@ fn test_empty_account() { Account { nonce: 155, balance: U256::from(414241124u32), - bytecode_hash: Some(keccak256("test")), + bytecode_hash: Some(keccak256_cached("test")), }, BTreeMap::from([ (B256::ZERO, U256::from(3)), @@ -183,7 +183,7 @@ fn test_empty_storage_root() { let account = Account { nonce: 155, balance: U256::from(414241124u32), - bytecode_hash: Some(keccak256(code)), + bytecode_hash: Some(keccak256_cached(code)), }; insert_account(tx.tx_ref(), address, account, &Default::default()); tx.commit().unwrap(); @@ -207,7 +207,7 @@ fn test_storage_root() { let account = Account { nonce: 155, balance: U256::from(414241124u32), - bytecode_hash: Some(keccak256(code)), + bytecode_hash: Some(keccak256_cached(code)), }; insert_account(tx.tx_ref(), address, account, &storage); @@ -302,7 +302,7 @@ fn storage_root_regression() { let tx = factory.provider_rw().unwrap(); // Some address whose hash starts with 0xB041 let address3 = address!("0x16b07afd1c635f77172e842a000ead9a2a222459"); - let key3 = keccak256(address3); + let key3 = keccak256_cached(address3); assert_eq!(key3[0], 0xB0); assert_eq!(key3[1], 0x41); @@ -359,7 +359,7 @@ fn account_and_storage_trie() { // Some address whose hash starts with 0xB040 let address2 = address!("0x7db3e81b72d2695e19764583f6d219dbee0f35ca"); - let key2 = keccak256(address2); + let key2 = keccak256_cached(address2); assert_eq!(key2[0], 0xB0); assert_eq!(key2[1], 0x40); let account2 = Account { nonce: 0, balance: ether, ..Default::default() }; @@ -368,7 +368,7 @@ fn account_and_storage_trie() { // Some address whose hash starts with 0xB041 let address3 = address!("0x16b07afd1c635f77172e842a000ead9a2a222459"); - let key3 = keccak256(address3); + let key3 = keccak256_cached(address3); assert_eq!(key3[0], 0xB0); assert_eq!(key3[1], 0x41); let code_hash = b256!("0x5be74cad16203c4905c068b012a2e9fb6d19d036c410f16fd177f337541440dd"); @@ -451,7 +451,7 @@ fn account_and_storage_trie() { // Add an account // Some address whose hash starts with 0xB1 let address4b = address!("0x4f61f2d5ebd991b85aa1677db97307caf5215c91"); - let key4b = keccak256(address4b); + let key4b = keccak256_cached(address4b); assert_eq!(key4b.0[0], key4a.0[0]); let account4b = Account { nonce: 0, balance: U256::from(5).mul(ether), bytecode_hash: None }; hashed_account_cursor.upsert(key4b, &account4b).unwrap(); diff --git a/crates/trie/db/tests/witness.rs b/crates/trie/db/tests/witness.rs index 14457fccc6..6922f1c865 100644 --- a/crates/trie/db/tests/witness.rs +++ b/crates/trie/db/tests/witness.rs @@ -2,7 +2,7 @@ use alloy_consensus::EMPTY_ROOT_HASH; use alloy_primitives::{ - keccak256, + keccak256_cached, map::{HashMap, HashSet}, Address, Bytes, B256, U256, }; @@ -23,7 +23,7 @@ fn includes_empty_node_preimage() { let provider = factory.provider_rw().unwrap(); let address = Address::random(); - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); let hashed_slot = B256::random(); // witness includes empty state trie root node @@ -60,7 +60,7 @@ fn includes_empty_node_preimage() { .unwrap(); assert!(witness.contains_key(&state_root)); for node in multiproof.account_subtree.values() { - assert_eq!(witness.get(&keccak256(node)), Some(node)); + assert_eq!(witness.get(&keccak256_cached(node)), Some(node)); } // witness includes empty state trie root node assert_eq!(witness.get(&EMPTY_ROOT_HASH), Some(&Bytes::from([EMPTY_STRING_CODE]))); @@ -72,9 +72,9 @@ fn includes_nodes_for_destroyed_storage_nodes() { let provider = factory.provider_rw().unwrap(); let address = Address::random(); - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); let slot = B256::random(); - let hashed_slot = keccak256(slot); + let hashed_slot = keccak256_cached(slot); // Insert account and slot into database provider.insert_account_for_hashing([(address, Some(Account::default()))]).unwrap(); @@ -103,10 +103,10 @@ fn includes_nodes_for_destroyed_storage_nodes() { .unwrap(); assert!(witness.contains_key(&state_root)); for node in multiproof.account_subtree.values() { - assert_eq!(witness.get(&keccak256(node)), Some(node)); + assert_eq!(witness.get(&keccak256_cached(node)), Some(node)); } for node in multiproof.storages.iter().flat_map(|(_, storage)| storage.subtree.values()) { - assert_eq!(witness.get(&keccak256(node)), Some(node)); + assert_eq!(witness.get(&keccak256_cached(node)), Some(node)); } } @@ -116,7 +116,7 @@ fn correctly_decodes_branch_node_values() { let provider = factory.provider_rw().unwrap(); let address = Address::random(); - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); let hashed_slot1 = B256::with_last_byte(1); let hashed_slot2 = B256::with_last_byte(2); @@ -154,9 +154,9 @@ fn correctly_decodes_branch_node_values() { .unwrap(); assert!(witness.contains_key(&state_root)); for node in multiproof.account_subtree.values() { - assert_eq!(witness.get(&keccak256(node)), Some(node)); + assert_eq!(witness.get(&keccak256_cached(node)), Some(node)); } for node in multiproof.storages.iter().flat_map(|(_, storage)| storage.subtree.values()) { - assert_eq!(witness.get(&keccak256(node)), Some(node)); + assert_eq!(witness.get(&keccak256_cached(node)), Some(node)); } } diff --git a/crates/trie/parallel/src/proof.rs b/crates/trie/parallel/src/proof.rs index 433c13fb08..d90c26d6fe 100644 --- a/crates/trie/parallel/src/proof.rs +++ b/crates/trie/parallel/src/proof.rs @@ -253,7 +253,7 @@ mod tests { use super::*; use crate::proof_task::{ProofTaskCtx, ProofWorkerHandle}; use alloy_primitives::{ - keccak256, + keccak256_cached, map::{B256Set, DefaultHashBuilder, HashMap}, Address, U256, }; @@ -310,7 +310,7 @@ mod tests { let mut targets = MultiProofTargets::default(); for (address, (_, storage)) in state.iter().take(10) { - let hashed_address = keccak256(*address); + let hashed_address = keccak256_cached(*address); let mut target_slots = B256Set::default(); for (slot, _) in storage.iter().take(5) { diff --git a/crates/trie/parallel/src/root.rs b/crates/trie/parallel/src/root.rs index 5c9294e8f9..1442edd42f 100644 --- a/crates/trie/parallel/src/root.rs +++ b/crates/trie/parallel/src/root.rs @@ -279,7 +279,7 @@ fn get_runtime_handle() -> Handle { #[cfg(test)] mod tests { use super::*; - use alloy_primitives::{keccak256, Address, U256}; + use alloy_primitives::{keccak256_cached, Address, U256}; use rand::Rng; use reth_primitives_traits::{Account, StorageEntry}; use reth_provider::{test_utils::create_test_provider_factory, HashingWriter}; @@ -341,7 +341,7 @@ mod tests { let mut hashed_state = HashedPostState::default(); for (address, (account, storage)) in &mut state { - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); let should_update_account = rng.random_bool(0.5); if should_update_account { @@ -352,7 +352,7 @@ mod tests { let should_update_storage = rng.random_bool(0.3); if should_update_storage { for (slot, value) in storage.iter_mut() { - let hashed_slot = keccak256(slot); + let hashed_slot = keccak256_cached(slot); *value = U256::from(rng.random::()); hashed_state .storages diff --git a/crates/trie/sparse/src/trie.rs b/crates/trie/sparse/src/trie.rs index acad15bc15..72ba3b8f87 100644 --- a/crates/trie/sparse/src/trie.rs +++ b/crates/trie/sparse/src/trie.rs @@ -11,7 +11,7 @@ use alloc::{ vec::Vec, }; use alloy_primitives::{ - hex, keccak256, + hex, utils::keccak256_cached, map::{Entry, HashMap, HashSet}, B256, }; @@ -928,7 +928,7 @@ impl SparseTrieInterface for SerialSparseTrie { if let Some(root_hash) = rlp_node.as_hash() { root_hash } else { - keccak256(rlp_node) + keccak256_cached(rlp_node) } } @@ -2298,7 +2298,7 @@ mod find_leaf_tests { let leaf_node_child5 = LeafNode::new(revealed_leaf_suffix, revealed_value.clone()); let leaf_node_child5_rlp_buf = alloy_rlp::encode(&leaf_node_child5); - let hash_of_child5 = keccak256(&leaf_node_child5_rlp_buf); + let hash_of_child5 = keccak256_cached(&leaf_node_child5_rlp_buf); let rlp_node_child5 = RlpNode::word_rlp(&hash_of_child5); // 2. Construct the root BranchNode using the RLP of its children diff --git a/crates/trie/trie/benches/hash_post_state.rs b/crates/trie/trie/benches/hash_post_state.rs index 15b567b7c8..84ded02dcc 100644 --- a/crates/trie/trie/benches/hash_post_state.rs +++ b/crates/trie/trie/benches/hash_post_state.rs @@ -1,5 +1,5 @@ #![allow(missing_docs, unreachable_pub)] -use alloy_primitives::{keccak256, map::HashMap, Address, B256, U256}; +use alloy_primitives::{utils::keccak256_cached, map::HashMap, Address, B256, U256}; use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; use proptest::{prelude::*, strategy::ValueTree, test_runner::TestRunner}; use reth_trie::{HashedPostState, HashedStorage, KeccakKeyHasher}; @@ -34,15 +34,14 @@ fn from_bundle_state_seq(state: &HashMap) -> HashedPostS let mut this = HashedPostState::default(); for (address, account) in state { - let hashed_address = keccak256(address); + let hashed_address = keccak256_cached(address); this.accounts.insert(hashed_address, account.info.as_ref().map(Into::into)); let hashed_storage = HashedStorage::from_iter( account.status.was_destroyed(), - account - .storage - .iter() - .map(|(key, value)| (keccak256(B256::new(key.to_be_bytes())), value.present_value)), + account.storage.iter().map(|(key, value)| { + (keccak256_cached(B256::new(key.to_be_bytes())), value.present_value) + }), ); this.storages.insert(hashed_address, hashed_storage); } diff --git a/crates/trie/trie/src/proof/mod.rs b/crates/trie/trie/src/proof/mod.rs index c0b9012355..18b8acef1b 100644 --- a/crates/trie/trie/src/proof/mod.rs +++ b/crates/trie/trie/src/proof/mod.rs @@ -10,7 +10,7 @@ use crate::{ HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE, }; use alloy_primitives::{ - keccak256, + utils::keccak256_cached, map::{B256Map, B256Set, HashMap, HashSet}, Address, B256, }; @@ -108,8 +108,8 @@ where ) -> Result { Ok(self .multiproof(MultiProofTargets::from_iter([( - keccak256(address), - slots.iter().map(keccak256).collect(), + keccak256_cached(address), + slots.iter().map(keccak256_cached).collect(), )]))? .account_proof(address, slots)?) } @@ -221,7 +221,7 @@ pub struct StorageProof<'a, T, H, K = AddedRemovedKeys> { impl StorageProof<'static, T, H> { /// Create a new [`StorageProof`] instance. pub fn new(t: T, h: H, address: Address) -> Self { - Self::new_hashed(t, h, keccak256(address)) + Self::new_hashed(t, h, keccak256_cached(address)) } /// Create a new [`StorageProof`] instance with hashed address. @@ -337,7 +337,7 @@ where self, slot: B256, ) -> Result { - let targets = HashSet::from_iter([keccak256(slot)]); + let targets = HashSet::from_iter([keccak256_cached(slot)]); Ok(self.storage_multiproof(targets)?.storage_proof(slot)?) } diff --git a/crates/trie/trie/src/proof_v2/value.rs b/crates/trie/trie/src/proof_v2/value.rs index 9f5f97a271..e422658ff2 100644 --- a/crates/trie/trie/src/proof_v2/value.rs +++ b/crates/trie/trie/src/proof_v2/value.rs @@ -131,7 +131,7 @@ where nodes.first().expect("storage_proof always returns at least the root"); root_node.node.encode(buf); - let storage_root = alloy_primitives::keccak256(buf.as_slice()); + let storage_root = alloy_primitives::utils::keccak256_cached(buf.as_slice()); // Clear the buffer so we can re-use it to encode the TrieAccount buf.clear(); diff --git a/crates/trie/trie/src/trie.rs b/crates/trie/trie/src/trie.rs index 17cdd1f96c..b42c6566a2 100644 --- a/crates/trie/trie/src/trie.rs +++ b/crates/trie/trie/src/trie.rs @@ -13,7 +13,7 @@ use crate::{ HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE, }; use alloy_consensus::EMPTY_ROOT_HASH; -use alloy_primitives::{keccak256, Address, B256}; +use alloy_primitives::{utils::keccak256_cached, Address, B256}; use alloy_rlp::{BufMut, Encodable}; use alloy_trie::proof::AddedRemovedKeys; use reth_execution_errors::{StateRootError, StorageRootError}; @@ -486,7 +486,7 @@ impl StorageRoot { Self::new_hashed( trie_cursor_factory, hashed_cursor_factory, - keccak256(address), + keccak256_cached(address), prefix_set, #[cfg(feature = "metrics")] metrics, diff --git a/crates/trie/trie/src/verify.rs b/crates/trie/trie/src/verify.rs index 4299a66916..21f29b18c3 100644 --- a/crates/trie/trie/src/verify.rs +++ b/crates/trie/trie/src/verify.rs @@ -474,7 +474,7 @@ mod tests { hashed_cursor::mock::MockHashedCursorFactory, trie_cursor::mock::{MockTrieCursor, MockTrieCursorFactory}, }; - use alloy_primitives::{address, keccak256, map::B256Map, U256}; + use alloy_primitives::{address, utils::keccak256_cached, map::B256Map, U256}; use alloy_trie::TrieMask; use assert_matches::assert_matches; use reth_primitives_traits::Account; @@ -537,20 +537,20 @@ mod tests { let mut storage_tries = B256Map::default(); // Create test accounts - let addr1 = keccak256(address!("0000000000000000000000000000000000000001")); + let addr1 = keccak256_cached(address!("0000000000000000000000000000000000000001")); accounts.insert( addr1, Account { nonce: 1, balance: U256::from(1000), - bytecode_hash: Some(keccak256(b"code1")), + bytecode_hash: Some(keccak256_cached(b"code1")), }, ); // Add storage for the account let mut storage1 = BTreeMap::new(); - storage1.insert(keccak256(B256::from(U256::from(1))), U256::from(100)); - storage1.insert(keccak256(B256::from(U256::from(2))), U256::from(200)); + storage1.insert(keccak256_cached(B256::from(U256::from(1))), U256::from(100)); + storage1.insert(keccak256_cached(B256::from(U256::from(2))), U256::from(200)); storage_tries.insert(addr1, storage1); let factory = MockHashedCursorFactory::new(accounts, storage_tries); @@ -606,20 +606,21 @@ mod tests { // Create multiple test addresses for i in 1u8..=3 { - let addr = keccak256([i; 20]); + let addr = keccak256_cached([i; 20]); accounts.insert( addr, Account { nonce: i as u64, balance: U256::from(i as u64 * 1000), - bytecode_hash: (i == 2).then(|| keccak256([i])), + bytecode_hash: (i == 2).then(|| keccak256_cached([i])), }, ); // Add some storage for each account let mut storage = BTreeMap::new(); for j in 0..i { - storage.insert(keccak256(B256::from(U256::from(j))), U256::from(j as u64 * 10)); + storage + .insert(keccak256_cached(B256::from(U256::from(j))), U256::from(j as u64 * 10)); } if !storage.is_empty() { storage_tries.insert(addr, storage); diff --git a/crates/trie/trie/src/witness.rs b/crates/trie/trie/src/witness.rs index 763908c242..148ea319a5 100644 --- a/crates/trie/trie/src/witness.rs +++ b/crates/trie/trie/src/witness.rs @@ -10,7 +10,7 @@ use reth_trie_common::HashedPostState; use reth_trie_sparse::SparseTrieInterface; use alloy_primitives::{ - keccak256, + utils::keccak256_cached, map::{B256Map, B256Set, Entry, HashMap}, Bytes, B256, }; @@ -126,7 +126,7 @@ where let (root_hash, root_node) = if let Some(root_node) = multiproof.account_subtree.into_inner().remove(&Nibbles::default()) { - (keccak256(&root_node), root_node) + (keccak256_cached(&root_node), root_node) } else { (EMPTY_ROOT_HASH, Bytes::from([EMPTY_STRING_CODE])) }; @@ -135,12 +135,16 @@ where // Record all nodes from multiproof in the witness for account_node in multiproof.account_subtree.values() { - if let Entry::Vacant(entry) = self.witness.entry(keccak256(account_node.as_ref())) { + if let Entry::Vacant(entry) = + self.witness.entry(keccak256_cached(account_node.as_ref())) + { entry.insert(account_node.clone()); } } for storage_node in multiproof.storages.values().flat_map(|s| s.subtree.values()) { - if let Entry::Vacant(entry) = self.witness.entry(keccak256(storage_node.as_ref())) { + if let Entry::Vacant(entry) = + self.witness.entry(keccak256_cached(storage_node.as_ref())) + { entry.insert(storage_node.clone()); } } @@ -199,7 +203,7 @@ where } while let Ok(node) = rx.try_recv() { - self.witness.insert(keccak256(&node), node); + self.witness.insert(keccak256_cached(&node), node); } } diff --git a/examples/custom-node/src/primitives/header.rs b/examples/custom-node/src/primitives/header.rs index 946bad5189..4643ea7b1c 100644 --- a/examples/custom-node/src/primitives/header.rs +++ b/examples/custom-node/src/primitives/header.rs @@ -3,7 +3,7 @@ use alloy_primitives::{Address, BlockNumber, Bloom, Bytes, Sealable, B256, B64, use alloy_rlp::{Encodable, RlpDecodable, RlpEncodable}; use reth_codecs::Compact; use reth_ethereum::primitives::{serde_bincode_compat::RlpBincode, BlockHeader, InMemorySize}; -use revm_primitives::keccak256; +use revm_primitives::keccak256_cached; use serde::{Deserialize, Serialize}; /// The header type of this node @@ -50,7 +50,7 @@ impl Sealable for CustomHeader { fn hash_slow(&self) -> B256 { let mut out = Vec::new(); self.encode(&mut out); - keccak256(&out) + keccak256_cached(&out) } } diff --git a/examples/db-access/src/main.rs b/examples/db-access/src/main.rs index 1042ac55be..f2c1489130 100644 --- a/examples/db-access/src/main.rs +++ b/examples/db-access/src/main.rs @@ -1,6 +1,6 @@ #![warn(unused_crate_dependencies)] -use alloy_primitives::{keccak256, Address, B256}; +use alloy_primitives::{keccak256_cached, Address, B256}; use reth_ethereum::{ chainspec::ChainSpecBuilder, node::EthereumNode, @@ -181,7 +181,7 @@ fn receipts_provider_example< let contract_addr = Address::random(); let indexed_from = Address::random(); let indexed_to = Address::random(); - let transfer_signature = keccak256("Transfer(address,address,uint256)"); + let transfer_signature = keccak256_cached("Transfer(address,address,uint256)"); // This matches ERC-20 Transfer events emitted by contract_addr where both indexed addresses are // fixed. If your event declares a third indexed parameter, continue with topic3(...). diff --git a/testing/ef-tests/src/models.rs b/testing/ef-tests/src/models.rs index bc9af3fab1..980e805d4d 100644 --- a/testing/ef-tests/src/models.rs +++ b/testing/ef-tests/src/models.rs @@ -4,7 +4,7 @@ use crate::{assert::assert_equal, Error}; use alloy_consensus::Header as RethHeader; use alloy_eips::eip4895::Withdrawals; use alloy_genesis::GenesisAccount; -use alloy_primitives::{keccak256, Address, Bloom, Bytes, B256, B64, U256}; +use alloy_primitives::{keccak256_cached, Address, Bloom, Bytes, B256, B64, U256}; use reth_chainspec::{ChainSpec, ChainSpecBuilder, EthereumHardfork, ForkCondition}; use reth_db_api::{cursor::DbDupCursorRO, tables, transaction::DbTx}; use reth_primitives_traits::SealedHeader; @@ -220,7 +220,7 @@ impl Account { assert_equal(self.nonce.to(), account.nonce, "Nonce does not match")?; if let Some(bytecode_hash) = account.bytecode_hash { - assert_equal(keccak256(&self.code), bytecode_hash, "Bytecode does not match")?; + assert_equal(keccak256_cached(&self.code), bytecode_hash, "Bytecode does not match")?; } else { assert_equal( self.code.is_empty(),