repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/seismic/rpc/src/eth/utils.rs
crates/seismic/rpc/src/eth/utils.rs
//! Utils for testing the seismic rpc api use alloy_rpc_types::TransactionRequest; use reth_primitives::Recovered; use reth_primitives_traits::SignedTransaction; use reth_rpc_eth_types::{utils::recover_raw_transaction, EthApiError, EthResult}; use seismic_alloy_consensus::{Decodable712, SeismicTxEnvelope, TypedDataRequest}; use seismic_alloy_network::{SeismicReth, TransactionBuilder}; use seismic_alloy_rpc_types::{SeismicCallRequest, SeismicTransactionRequest}; /// Override the request for seismic calls pub fn seismic_override_call_request(request: &mut TransactionRequest) { // If user calls with the standard (unsigned) eth_call, // then disregard whatever they put in the from field // They will still be able to read public contract functions, // but they will not be able to spoof msg.sender in these calls request.from = None; request.gas_price = None; // preventing InsufficientFunds error request.max_fee_per_gas = None; // preventing InsufficientFunds error request.max_priority_fee_per_gas = None; // preventing InsufficientFunds error request.max_fee_per_blob_gas = None; // preventing InsufficientFunds error request.value = None; // preventing InsufficientFunds error } /// Recovers a [`SignedTransaction`] from a typed data request. /// /// This is a helper function that returns the appropriate RPC-specific error if the input data is /// malformed. /// /// See [`alloy_eips::eip2718::Decodable2718::decode_2718`] pub fn recover_typed_data_request<T: SignedTransaction + Decodable712>( mut data: &TypedDataRequest, ) -> EthResult<Recovered<T>> { let transaction = T::decode_712(&mut data).map_err(|_| EthApiError::FailedToDecodeSignedTransaction)?; SignedTransaction::try_into_recovered(transaction) .or(Err(EthApiError::InvalidTransactionSignature)) } /// Convert a [`SeismicCallRequest`] to a [`SeismicTransactionRequest`]. /// /// If the call requests simulates a transaction without a signature from msg.sender, /// we null out the fields that may reveal sensitive information. pub fn convert_seismic_call_to_tx_request( request: SeismicCallRequest, ) -> Result<SeismicTransactionRequest, EthApiError> { match request { SeismicCallRequest::TransactionRequest(mut tx_request) => { seismic_override_call_request(&mut tx_request.inner); // null fields that may reveal sensitive information Ok(tx_request) } SeismicCallRequest::TypedData(typed_request) => { SeismicTransactionRequest::decode_712(&typed_request) .map_err(|_e| EthApiError::FailedToDecodeSignedTransaction) } SeismicCallRequest::Bytes(bytes) => { let tx = recover_raw_transaction::<SeismicTxEnvelope>(&bytes)?; let mut req: SeismicTransactionRequest = tx.inner().clone().into(); TransactionBuilder::<SeismicReth>::set_from(&mut req, tx.signer()); Ok(req) } } } #[cfg(test)] mod test { use crate::utils::recover_typed_data_request; use alloy_primitives::{ aliases::U96, hex::{self, FromHex}, Address, Bytes, FixedBytes, Signature, U256, }; use reth_primitives_traits::SignedTransaction; use reth_seismic_primitives::SeismicTransactionSigned; use secp256k1::PublicKey; use seismic_alloy_consensus::{ SeismicTxEnvelope, TxSeismic, TxSeismicElements, TypedDataRequest, }; use std::str::FromStr; #[test] fn test_typed_data_tx_hash() { let r_bytes = hex::decode("e93185920818650416b4b0cc953c48f59fd9a29af4b7e1c4b1ac4824392f9220") .unwrap(); let s_bytes = hex::decode("79b76b064a83d423997b7234c575588f60da5d3e1e0561eff9804eb04c23789a") .unwrap(); let mut r_padded = [0u8; 32]; let mut s_padded = [0u8; 32]; let r_start = 32 - r_bytes.len(); let s_start = 32 - s_bytes.len(); r_padded[r_start..].copy_from_slice(&r_bytes); s_padded[s_start..].copy_from_slice(&s_bytes); let r = U256::from_be_bytes(r_padded); let s = U256::from_be_bytes(s_padded); let signature = Signature::new(r, s, false); let tx = TxSeismic { chain_id: 5124, nonce: 48, gas_price: 360000, gas_limit: 169477, to: alloy_primitives::TxKind::Call(Address::from_str("0x3aB946eEC2553114040dE82D2e18798a51cf1e14").unwrap()), value: U256::from_str("1000000000000000").unwrap(), input: Bytes::from_str("0x4e69e56c3bb999b8c98772ebb32aebcbd43b33e9e65a46333dfe6636f37f3009e93bad334235aec73bd54d11410e64eb2cab4da8").unwrap(), seismic_elements: TxSeismicElements { encryption_pubkey: PublicKey::from_str("028e76821eb4d77fd30223ca971c49738eb5b5b71eabe93f96b348fdce788ae5a0").unwrap(), encryption_nonce: U96::from_str("0x7da3a99bf0f90d56551d99ea").unwrap(), message_version: 2, } }; let signed = SeismicTransactionSigned::new_unhashed( seismic_alloy_consensus::SeismicTypedTransaction::Seismic(tx.clone()), signature, ); let signed_hash = signed.recalculate_hash(); let signed_sighash = signed.signature_hash(); let td = tx.eip712_to_type_data(); let req = TypedDataRequest { signature, data: td }; let recovered = recover_typed_data_request::<SeismicTxEnvelope>(&req).unwrap(); let recovered_hash = recovered.tx_hash(); let recovered_sighash = recovered.signature_hash(); let expected_tx_hash = FixedBytes::<32>::from_hex( "d578c4f5e787b2994749e68e44860692480ace52b219bbc0119919561cbc29ea", ) .unwrap(); assert_eq!(signed_hash, expected_tx_hash); assert_eq!(recovered_hash, expected_tx_hash); let expected_sighash = FixedBytes::<32>::from_hex( "2886e254cbaa8b07a578dec42d3d71a8d4374b607bafe4e4b1c7fd4a8cb50911", ) .unwrap(); assert_eq!(signed_sighash, expected_sighash); assert_eq!(recovered_sighash, expected_sighash); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/seismic/rpc/src/eth/mod.rs
crates/seismic/rpc/src/eth/mod.rs
//! Seismic-Reth `eth_` endpoint implementation. pub mod api; pub mod ext; pub mod receipt; pub mod transaction; pub mod utils; pub use receipt::SeismicReceiptConverter; mod block; mod call; mod pending_block; use crate::{ eth::transaction::{SeismicRpcTxConverter, SeismicSimTxConverter}, SeismicEthApiError, }; use alloy_primitives::U256; use reth_evm::ConfigureEvm; use reth_node_api::{FullNodeComponents, HeaderTy}; use reth_node_builder::rpc::{EthApiBuilder, EthApiCtx}; use reth_rpc::{ eth::{core::EthApiInner, DevSigner}, RpcTypes, }; use reth_rpc_eth_api::{ helpers::{ pending_block::BuildPendingEnv, spec::SignersForApi, AddDevSigners, EthApiSpec, EthFees, EthState, LoadFee, LoadPendingBlock, LoadState, SpawnBlocking, Trace, }, EthApiTypes, FromEvmError, FullEthApiServer, RpcConvert, RpcConverter, RpcNodeCore, RpcNodeCoreExt, SignableTxRequest, }; use reth_rpc_eth_types::{EthStateCache, FeeHistoryCache, GasPriceOracle}; use reth_storage_api::{BlockReader, ProviderHeader, ProviderTx}; use reth_tasks::{ pool::{BlockingTaskGuard, BlockingTaskPool}, TaskSpawner, }; use seismic_alloy_network::SeismicReth; use std::{fmt, marker::PhantomData, sync::Arc}; use reth_rpc_convert::transaction::{EthTxEnvError, TryIntoTxEnv}; use revm_context::{BlockEnv, CfgEnv, TxEnv}; use seismic_alloy_rpc_types::SeismicTransactionRequest; use seismic_revm; // Additional imports for SignableTxRequest wrapper use alloy_primitives::Signature; use reth_rpc_convert::SignTxRequestError; use seismic_alloy_network::TxSigner; /// Newtype wrapper around SeismicTransactionRequest to implement SignableTxRequest #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SignableSeismicTransactionRequest(pub SeismicTransactionRequest); impl From<SeismicTransactionRequest> for SignableSeismicTransactionRequest { fn from(req: SeismicTransactionRequest) -> Self { Self(req) } } impl From<alloy_rpc_types_eth::TransactionRequest> for SignableSeismicTransactionRequest { fn from(req: alloy_rpc_types_eth::TransactionRequest) -> Self { Self(SeismicTransactionRequest { inner: req, seismic_elements: None }) } } impl AsRef<alloy_rpc_types_eth::TransactionRequest> for SignableSeismicTransactionRequest { fn as_ref(&self) -> &alloy_rpc_types_eth::TransactionRequest { &self.0.inner } } impl AsMut<alloy_rpc_types_eth::TransactionRequest> for SignableSeismicTransactionRequest { fn as_mut(&mut self) -> &mut alloy_rpc_types_eth::TransactionRequest { &mut self.0.inner } } impl TryIntoTxEnv<seismic_revm::SeismicTransaction<TxEnv>> for SignableSeismicTransactionRequest { type Err = EthTxEnvError; fn try_into_tx_env<Spec>( self, cfg_env: &CfgEnv<Spec>, block_env: &BlockEnv, ) -> Result<seismic_revm::SeismicTransaction<TxEnv>, Self::Err> { // First convert the inner transaction to TxEnv let base_tx_env = self.0.inner.try_into_tx_env(cfg_env, block_env)?; // Then wrap it in SeismicTransaction Ok(seismic_revm::SeismicTransaction::new(base_tx_env)) } } impl SignableTxRequest<reth_seismic_primitives::SeismicTransactionSigned> for SignableSeismicTransactionRequest { async fn try_build_and_sign( self, _signer: impl TxSigner<Signature> + Send, ) -> Result<reth_seismic_primitives::SeismicTransactionSigned, SignTxRequestError> { // TODO: Implement proper signing logic // For now, create a placeholder transaction to make it compile use alloy_consensus::{Signed, TxLegacy}; use alloy_primitives::{B256, U256}; use reth_seismic_primitives::SeismicTransactionSigned; use seismic_alloy_consensus::SeismicTxEnvelope; // Create a minimal transaction for compilation - this should be replaced with proper // signing let tx = TxLegacy { chain_id: Some(1), nonce: 0, gas_price: 20_000_000_000u128, gas_limit: 21_000, to: alloy_primitives::TxKind::Create, value: U256::ZERO, input: Default::default(), }; let signature = Signature::new(U256::ZERO, U256::ZERO, false); let signed_tx = Signed::new_unchecked(tx, signature, B256::ZERO); let envelope = SeismicTxEnvelope::Legacy(signed_tx); let seismic_signed = SeismicTransactionSigned::from(envelope); Ok(seismic_signed) } } /// Wrapper network type that uses SignableSeismicTransactionRequest #[derive(Debug, Clone)] pub struct SeismicRethWithSignable; impl reth_rpc_eth_api::RpcTypes for SeismicRethWithSignable { type TransactionRequest = SignableSeismicTransactionRequest; type Receipt = <SeismicReth as reth_rpc_eth_api::RpcTypes>::Receipt; type TransactionResponse = <SeismicReth as reth_rpc_eth_api::RpcTypes>::TransactionResponse; type Header = <SeismicReth as reth_rpc_eth_api::RpcTypes>::Header; } /// Adapter for [`EthApiInner`], which holds all the data required to serve core `eth_` API. pub type EthApiNodeBackend<N, Rpc> = EthApiInner<N, Rpc>; /// A helper trait with requirements for [`RpcNodeCore`] to be used in [`SeismicEthApi`]. pub trait SeismicNodeCore: RpcNodeCore<Provider: BlockReader> {} impl<T> SeismicNodeCore for T where T: RpcNodeCore<Provider: BlockReader> {} /// seismic-reth `Eth` API implementation. #[derive(Clone)] pub struct SeismicEthApi<N: SeismicNodeCore, Rpc: RpcConvert> { /// Inner `Eth` API implementation. pub inner: Arc<EthApiInner<N, Rpc>>, } impl<N: RpcNodeCore, Rpc: RpcConvert> SeismicEthApi<N, Rpc> { /// Returns a reference to the [`EthApiNodeBackend`]. pub fn eth_api(&self) -> &EthApiNodeBackend<N, Rpc> { &self.inner } /// Build a [`SeismicEthApi`] using [`SeismicEthApiBuilder`]. pub const fn builder() -> SeismicEthApiBuilder<Rpc> { SeismicEthApiBuilder::new() } } impl<N, Rpc> EthApiTypes for SeismicEthApi<N, Rpc> where // Self: Send + Sync, // N: SeismicNodeCore, N: RpcNodeCore, Rpc: RpcConvert<Primitives = N::Primitives>, { type Error = SeismicEthApiError; type NetworkTypes = Rpc::Network; type RpcConvert = Rpc; fn tx_resp_builder(&self) -> &Self::RpcConvert { self.inner.tx_resp_builder() } } impl<N, Rpc> RpcNodeCore for SeismicEthApi<N, Rpc> where N: RpcNodeCore, Rpc: RpcConvert<Primitives = N::Primitives>, { type Primitives = N::Primitives; type Provider = N::Provider; type Pool = N::Pool; type Evm = N::Evm; type Network = N::Network; #[inline] fn pool(&self) -> &Self::Pool { self.inner.pool() } #[inline] fn evm_config(&self) -> &Self::Evm { self.inner.evm_config() } #[inline] fn network(&self) -> &Self::Network { self.inner.network() } #[inline] fn provider(&self) -> &Self::Provider { self.inner.provider() } } impl<N, Rpc> RpcNodeCoreExt for SeismicEthApi<N, Rpc> where N: RpcNodeCore, Rpc: RpcConvert<Primitives = N::Primitives>, { #[inline] fn cache(&self) -> &EthStateCache<N::Primitives> { self.inner.cache() } } impl<N, Rpc> EthApiSpec for SeismicEthApi<N, Rpc> where N: RpcNodeCore, Rpc: RpcConvert<Primitives = N::Primitives>, { type Transaction = ProviderTx<Self::Provider>; type Rpc = Rpc::Network; #[inline] fn starting_block(&self) -> U256 { self.inner.starting_block() } #[inline] fn signers(&self) -> &SignersForApi<Self> { self.inner.signers() } } impl<N, Rpc> SpawnBlocking for SeismicEthApi<N, Rpc> where N: RpcNodeCore, Rpc: RpcConvert<Primitives = N::Primitives>, { #[inline] fn io_task_spawner(&self) -> impl TaskSpawner { self.inner.task_spawner() } #[inline] fn tracing_task_pool(&self) -> &BlockingTaskPool { self.inner.blocking_task_pool() } #[inline] fn tracing_task_guard(&self) -> &BlockingTaskGuard { self.inner.blocking_task_guard() } } impl<N, Rpc> LoadFee for SeismicEthApi<N, Rpc> where N: RpcNodeCore, SeismicEthApiError: FromEvmError<N::Evm>, Rpc: RpcConvert<Primitives = N::Primitives, Error = SeismicEthApiError>, { #[inline] fn gas_oracle(&self) -> &GasPriceOracle<Self::Provider> { self.inner.gas_oracle() } #[inline] fn fee_history_cache(&self) -> &FeeHistoryCache<ProviderHeader<N::Provider>> { self.inner.fee_history_cache() } } impl<N, Rpc> LoadState for SeismicEthApi<N, Rpc> where N: RpcNodeCore, Rpc: RpcConvert<Primitives = N::Primitives>, Self: LoadPendingBlock, { } impl<N, Rpc> EthState for SeismicEthApi<N, Rpc> where N: RpcNodeCore, Rpc: RpcConvert<Primitives = N::Primitives>, Self: LoadPendingBlock, { #[inline] fn max_proof_window(&self) -> u64 { self.inner.eth_proof_window() } } impl<N, Rpc> EthFees for SeismicEthApi<N, Rpc> where N: RpcNodeCore, SeismicEthApiError: FromEvmError<N::Evm>, Rpc: RpcConvert<Primitives = N::Primitives, Error = SeismicEthApiError>, { } impl<N, Rpc> Trace for SeismicEthApi<N, Rpc> where N: RpcNodeCore, SeismicEthApiError: FromEvmError<N::Evm>, Rpc: RpcConvert<Primitives = N::Primitives>, { } impl<N, Rpc> AddDevSigners for SeismicEthApi<N, Rpc> where N: RpcNodeCore, Rpc: RpcConvert< Network: RpcTypes<TransactionRequest: SignableTxRequest<ProviderTx<N::Provider>>>, >, { fn with_dev_accounts(&self) { *self.inner.signers().write() = DevSigner::random_signers(20) } } impl<N: SeismicNodeCore, Rpc: RpcConvert> fmt::Debug for SeismicEthApi<N, Rpc> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("SeismicEthApi").finish_non_exhaustive() } } /// Converter for Seismic RPC types. pub type SeismicRpcConvert<N, NetworkT> = RpcConverter< NetworkT, <N as FullNodeComponents>::Evm, SeismicReceiptConverter, (), (), crate::eth::transaction::SeismicSimTxConverter, crate::eth::transaction::SeismicRpcTxConverter, >; /// Builds [`SeismicEthApi`] for Optimism. #[derive(Debug)] pub struct SeismicEthApiBuilder<NetworkT> { _nt: PhantomData<NetworkT>, } impl<NetworkT> Default for SeismicEthApiBuilder<NetworkT> { fn default() -> Self { SeismicEthApiBuilder { _nt: PhantomData } } } impl<NetworkT> SeismicEthApiBuilder<NetworkT> { /// Creates a [`SeismicEthApiBuilder`] instance from core components. pub const fn new() -> Self { SeismicEthApiBuilder { _nt: PhantomData } } } impl<N, NetworkT> EthApiBuilder<N> for SeismicEthApiBuilder<NetworkT> where N: FullNodeComponents< Evm: ConfigureEvm< NextBlockEnvCtx: BuildPendingEnv<HeaderTy<N::Types>> // + From<ExecutionPayloadBaseV1> + Unpin, >, >, NetworkT: RpcTypes, SeismicRpcConvert<N, NetworkT>: RpcConvert<Network = NetworkT>, SeismicEthApi<N, SeismicRpcConvert<N, NetworkT>>: FullEthApiServer<Provider = N::Provider, Pool = N::Pool> + AddDevSigners, { type EthApi = SeismicEthApi<N, SeismicRpcConvert<N, NetworkT>>; async fn build_eth_api(self, ctx: EthApiCtx<'_, N>) -> eyre::Result<Self::EthApi> { let receipt_converter = SeismicReceiptConverter::new(); let rpc_converter: SeismicRpcConvert<N, NetworkT> = RpcConverter::new(receipt_converter) .with_sim_tx_converter(SeismicSimTxConverter::new()) .with_rpc_tx_converter(SeismicRpcTxConverter::new()); let eth_api = ctx.eth_api_builder().with_rpc_converter(rpc_converter).build_inner(); Ok(SeismicEthApi { inner: Arc::new(eth_api) }) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/seismic/rpc/src/eth/transaction.rs
crates/seismic/rpc/src/eth/transaction.rs
//! Loads and formats Seismic transaction RPC response. use super::ext::SeismicTransaction; use crate::{ eth::{SeismicNodeCore, SignableSeismicTransactionRequest}, utils::recover_typed_data_request, SeismicEthApi, SeismicEthApiError, }; use alloy_consensus::{transaction::Recovered, Transaction as _}; use alloy_primitives::{Bytes, Signature, B256}; use alloy_rpc_types_eth::{Transaction, TransactionInfo}; use reth_rpc_convert::transaction::{RpcTxConverter, SimTxConverter}; use reth_rpc_eth_api::{ helpers::{spec::SignersForRpc, EthTransactions, LoadTransaction}, FromEthApiError, RpcConvert, RpcNodeCore, }; use reth_rpc_eth_types::{utils::recover_raw_transaction, EthApiError}; use reth_seismic_primitives::SeismicTransactionSigned; use reth_storage_api::{BlockReader, BlockReaderIdExt, ProviderTx}; use reth_transaction_pool::{ AddedTransactionOutcome, PoolTransaction, TransactionOrigin, TransactionPool, }; use seismic_alloy_consensus::{Decodable712, SeismicTxEnvelope, TypedDataRequest}; use seismic_alloy_rpc_types::SeismicTransactionRequest; impl<N, Rpc> EthTransactions for SeismicEthApi<N, Rpc> where N: RpcNodeCore, Rpc: RpcConvert<Primitives = N::Primitives, Error = SeismicEthApiError>, { fn signers(&self) -> &SignersForRpc<Self::Provider, Self::NetworkTypes> { self.inner.signers() } async fn send_raw_transaction(&self, tx: Bytes) -> Result<B256, Self::Error> { let recovered = recover_raw_transaction(&tx)?; tracing::debug!(target: "reth-seismic-rpc::eth", ?recovered, "serving seismic_eth_api::send_raw_transaction"); let pool_transaction = <Self::Pool as TransactionPool>::Transaction::from_pooled(recovered); // submit the transaction to the pool with a `Local` origin let AddedTransactionOutcome { hash, .. } = self .pool() .add_transaction(TransactionOrigin::Local, pool_transaction) .await .map_err(Self::Error::from_eth_err)?; Ok(hash) } } impl<N, Rpc> SeismicTransaction for SeismicEthApi<N, Rpc> where Self: LoadTransaction<Provider: BlockReaderIdExt>, // N: RpcNodeCore, N: SeismicNodeCore< Provider: BlockReader<Transaction = ProviderTx<Self::Provider>> >, <<<SeismicEthApi<N, Rpc> as RpcNodeCore>::Pool as TransactionPool>::Transaction as PoolTransaction>::Pooled: Decodable712, Rpc: RpcConvert<Primitives = N::Primitives, Error = SeismicEthApiError>, { async fn send_typed_data_transaction(&self, tx: TypedDataRequest) -> Result<B256, Self::Error> { let recovered = recover_typed_data_request(&tx)?; // broadcast raw transaction to subscribers if there is any. // TODO: maybe we need to broadcast the encoded tx instead of the recovered tx // when other nodes receive the raw bytes the hash they recover needs to be // type // self.broadcast_raw_transaction(recovered.to); let pool_transaction = <Self::Pool as TransactionPool>::Transaction::from_pooled(recovered); // submit the transaction to the pool with a `Local` origin let AddedTransactionOutcome { hash, .. } = self .pool() .add_transaction(TransactionOrigin::Local, pool_transaction) .await .map_err(Self::Error::from_eth_err)?; Ok(hash) } } impl<N, Rpc> LoadTransaction for SeismicEthApi<N, Rpc> where N: RpcNodeCore, Rpc: RpcConvert<Primitives = N::Primitives, Error = SeismicEthApiError>, { } /// Seismic RPC transaction converter that implements Debug #[derive(Clone, Debug)] pub struct SeismicRpcTxConverter; impl SeismicRpcTxConverter { /// Creates a new converter pub const fn new() -> Self { Self } } /// Seismic simulation transaction converter that implements Debug #[derive(Clone, Debug)] pub struct SeismicSimTxConverter; impl SeismicSimTxConverter { /// Creates a new converter pub const fn new() -> Self { Self } } impl RpcTxConverter<SeismicTransactionSigned, Transaction<SeismicTxEnvelope>, TransactionInfo> for SeismicRpcTxConverter { type Err = SeismicEthApiError; fn convert_rpc_tx( &self, tx: SeismicTransactionSigned, signer: alloy_primitives::Address, tx_info: TransactionInfo, ) -> Result<Transaction<SeismicTxEnvelope>, Self::Err> { let tx_envelope: SeismicTxEnvelope = tx.into(); let recovered_tx = Recovered::new_unchecked(tx_envelope, signer); let TransactionInfo { block_hash, block_number, index: transaction_index, base_fee, .. } = tx_info; let effective_gas_price = base_fee .map(|base_fee| { recovered_tx.effective_tip_per_gas(base_fee).unwrap_or_default() + base_fee as u128 }) .unwrap_or_else(|| recovered_tx.max_fee_per_gas()); Ok(Transaction::<SeismicTxEnvelope> { inner: recovered_tx, block_hash, block_number, transaction_index, effective_gas_price: Some(effective_gas_price), }) } } impl SimTxConverter<alloy_rpc_types_eth::TransactionRequest, SeismicTransactionSigned> for SeismicSimTxConverter { type Err = SeismicEthApiError; fn convert_sim_tx( &self, tx_req: alloy_rpc_types_eth::TransactionRequest, ) -> Result<SeismicTransactionSigned, Self::Err> { let request = SeismicTransactionRequest { inner: tx_req, seismic_elements: None, /* Assumed that the transaction has already been decrypted in * the EthApiExt */ }; let Ok(tx) = request.build_typed_tx() else { return Err(SeismicEthApiError::Eth(EthApiError::TransactionConversionError)); }; // Create an empty signature for the transaction. let signature = Signature::new(Default::default(), Default::default(), false); Ok(SeismicTransactionSigned::new_unhashed(tx, signature)) } } // Additional implementation for SeismicTransactionRequest directly impl SimTxConverter<SeismicTransactionRequest, SeismicTransactionSigned> for SeismicSimTxConverter { type Err = SeismicEthApiError; fn convert_sim_tx( &self, request: SeismicTransactionRequest, ) -> Result<SeismicTransactionSigned, Self::Err> { let Ok(tx) = request.build_typed_tx() else { return Err(SeismicEthApiError::Eth(EthApiError::TransactionConversionError)); }; // Create an empty signature for the transaction. let signature = Signature::new(Default::default(), Default::default(), false); Ok(SeismicTransactionSigned::new_unhashed(tx, signature)) } } // Implementation for SignableSeismicTransactionRequest wrapper impl SimTxConverter<SignableSeismicTransactionRequest, SeismicTransactionSigned> for SeismicSimTxConverter { type Err = SeismicEthApiError; fn convert_sim_tx( &self, request: SignableSeismicTransactionRequest, ) -> Result<SeismicTransactionSigned, Self::Err> { // Delegate to the inner SeismicTransactionRequest implementation self.convert_sim_tx(request.0) } } #[cfg(test)] mod test { use alloy_primitives::{Bytes, FixedBytes}; use reth_primitives_traits::SignedTransaction; use reth_rpc_eth_types::utils::recover_raw_transaction; use reth_seismic_primitives::SeismicTransactionSigned; use std::str::FromStr; #[test] fn test_recover_raw_tx() { let raw_tx = Bytes::from_str("0x4af8d18214043083057e4083029605943ab946eec2553114040de82d2e18798a51cf1e1487038d7ea4c68000a1028e76821eb4d77fd30223ca971c49738eb5b5b71eabe93f96b348fdce788ae5a08c7da3a99bf0f90d56551d99ea02b44e69e56c3bb999b8c98772ebb32aebcbd43b33e9e65a46333dfe6636f37f3009e93bad334235aec73bd54d11410e64eb2cab4da880a0e93185920818650416b4b0cc953c48f59fd9a29af4b7e1c4b1ac4824392f9220a079b76b064a83d423997b7234c575588f60da5d3e1e0561eff9804eb04c23789a").unwrap(); let recovered = recover_raw_transaction::<SeismicTransactionSigned>(&raw_tx).unwrap(); let expected = FixedBytes::<32>::from_str( "d578c4f5e787b2994749e68e44860692480ace52b219bbc0119919561cbc29ea", ) .unwrap(); assert_eq!(recovered.tx_hash(), &expected); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/seismic/primitives/src/alloy_compat.rs
crates/seismic/primitives/src/alloy_compat.rs
//! Common conversions from alloy types. use crate::SeismicTransactionSigned; use alloy_consensus::TxEnvelope; use alloy_network::{AnyRpcTransaction, AnyTxEnvelope}; use alloy_primitives::PrimitiveSignature; use alloy_rpc_types_eth::{ConversionError, Transaction as AlloyRpcTransaction}; use alloy_serde::WithOtherFields; use num_traits::Num; use seismic_alloy_consensus::{transaction::TxSeismicElements, SeismicTypedTransaction, TxSeismic}; macro_rules! get_field { ($fields:expr, $key:expr) => { $fields.get_deserialized($key).and_then(Result::ok).ok_or(ConversionError::Custom( format!("missing field or type conversion error: {}", $key), ))? }; } fn parse_hex<T>(hex: &str) -> Result<T, T::FromStrRadixErr> where T: Num, { T::from_str_radix(hex.trim_start_matches("0x"), 16) } impl TryFrom<AnyRpcTransaction> for SeismicTransactionSigned { type Error = ConversionError; fn try_from(tx: AnyRpcTransaction) -> Result<Self, Self::Error> { let WithOtherFields { inner: AlloyRpcTransaction { inner, .. }, other: _ } = tx.0; let (transaction, signature, hash) = match inner.into_inner() { AnyTxEnvelope::Ethereum(TxEnvelope::Legacy(tx)) => { let (tx, signature, hash) = tx.into_parts(); (SeismicTypedTransaction::Legacy(tx), signature, hash) } AnyTxEnvelope::Ethereum(TxEnvelope::Eip2930(tx)) => { let (tx, signature, hash) = tx.into_parts(); (SeismicTypedTransaction::Eip2930(tx), signature, hash) } AnyTxEnvelope::Ethereum(TxEnvelope::Eip1559(tx)) => { let (tx, signature, hash) = tx.into_parts(); (SeismicTypedTransaction::Eip1559(tx), signature, hash) } AnyTxEnvelope::Ethereum(TxEnvelope::Eip7702(tx)) => { let (tx, signature, hash) = tx.into_parts(); (SeismicTypedTransaction::Eip7702(tx), signature, hash) } AnyTxEnvelope::Unknown(tx) => { let inner = tx.inner.clone(); let hash = tx.hash; let fields = inner.fields; let y_parity: String = get_field!(fields, "yParity"); let signature = PrimitiveSignature::new( get_field!(fields, "r"), get_field!(fields, "s"), y_parity == "0x0", ); let message_version: String = get_field!(fields, "messageVersion"); let message_version: u8 = parse_hex::<u8>(&message_version).map_err(|_| { ConversionError::Custom(format!( "failed to parse message version: {}", message_version )) })?; let seismic_elements = TxSeismicElements { encryption_pubkey: get_field!(fields, "encryptionPubkey"), encryption_nonce: get_field!(fields, "encryptionNonce"), message_version, }; let chain_id: String = get_field!(fields, "chainId"); let nonce: String = get_field!(fields, "nonce"); let gas_price: String = get_field!(fields, "gasPrice"); let gas_limit: String = get_field!(fields, "gas"); let tx_seismic = TxSeismic { chain_id: parse_hex::<u64>(&chain_id).map_err(|_| { ConversionError::Custom(format!("failed to parse chain id: {}", chain_id)) })?, nonce: parse_hex::<u64>(&nonce).map_err(|_| { ConversionError::Custom(format!("failed to parse nonce: {}", nonce)) })?, gas_price: parse_hex::<u128>(&gas_price).map_err(|_| { ConversionError::Custom(format!("failed to parse gas price: {}", gas_price)) })?, gas_limit: parse_hex::<u64>(&gas_limit).map_err(|_| { ConversionError::Custom(format!("failed to parse gas limit: {}", gas_limit)) })?, to: get_field!(fields, "to"), value: get_field!(fields, "value"), input: get_field!(fields, "input"), seismic_elements, }; (SeismicTypedTransaction::Seismic(tx_seismic), signature, hash) } _ => return Err(ConversionError::Custom("unknown transaction type".to_string())), }; Ok(Self::new(transaction, signature, hash)) } } impl<T> From<AlloyRpcTransaction<T>> for SeismicTransactionSigned where Self: From<T>, { fn from(value: AlloyRpcTransaction<T>) -> Self { value.inner.into_inner().into() } } #[cfg(test)] mod tests { use crate::SeismicTransactionSigned; use alloy_network::AnyRpcTransaction; #[test] fn test_tx_with_seismic_elements() -> Result<(), Box<dyn std::error::Error>> { // json based on crate::test_utils::get_signed_seismic_tx // first 5 fields picked off of the OP test case to make things compile let json = r#"{ "hash": "0x3f44a72b1faf70be7295183f1f30cfb51ede92d7c44441ca80c9437a6a22e5a5", "blockHash": "0x0d7f8b9def6f5d3ba2cbeee2e31e730da81e2c474fa8c3c9e8d0e6b96e37d182", "blockNumber": "0x1966297", "transactionIndex": "0x1", "from": "0x977f82a600a1414e583f7f13623f1ac5d58b1c0b", "r": "0x76c0d0e3d16cb3981775f63f159bbe67ee4b3ea58da566c952b7fe437c0bc6a", "s": "0x786b92b719cc5082816733ecbb1c0fee4006e9763132d994450e5e85578303e3", "yParity": "0x0", "v": "0x0", "type": "0x4A", "chainId": "0x1403", "nonce": "0x1", "gasPrice": "0x4a817c800", "gas": "0x33450", "to": "0x5fbdb2315678afecb367f032d93f642f64180aa3", "value": "0x1c6bf52634000", "input": "0x07b46d5eb63d4799e420e3ff1a27888a44c2d6505eac642061a2c290cdc45f2da8c5a13ede8eabfc9424bead86330c0b98a91e3b", "encryptionPubkey": "036d6caac248af96f6afa7f904f550253a0f3ef3f5aa2fe6838a95b216691468e2", "encryptionNonce": "0xffffffffffffffffffffffff", "messageVersion": "0x0" }"#; let tx: AnyRpcTransaction = serde_json::from_str(&json).unwrap(); SeismicTransactionSigned::try_from(tx).unwrap(); Ok(()) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/seismic/primitives/src/lib.rs
crates/seismic/primitives/src/lib.rs
//! Standalone crate for Seismic-specific Reth primitive types. #![doc( html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png", html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256", issue_tracker_base_url = "https://github.com/SeismicSystems/seismic-reth/issues/" )] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #![cfg_attr(not(test), warn(unused_crate_dependencies))] #![cfg_attr(not(feature = "std"), no_std)] extern crate alloc; #[cfg(feature = "alloy-compat")] mod alloy_compat; pub mod transaction; pub use transaction::{signed::SeismicTransactionSigned, tx_type::SeismicTxType}; mod receipt; pub use receipt::SeismicReceipt; pub mod test_utils; /// Seismic-specific block type. pub type SeismicBlock = alloy_consensus::Block<SeismicTransactionSigned>; /// Seismic-specific block body type. pub type SeismicBlockBody = <SeismicBlock as reth_primitives_traits::Block>::Body; /// Primitive types for Seismic Node. #[derive(Debug, Default, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct SeismicPrimitives; impl reth_primitives_traits::NodePrimitives for SeismicPrimitives { type Block = SeismicBlock; type BlockHeader = alloy_consensus::Header; type BlockBody = SeismicBlockBody; type SignedTx = SeismicTransactionSigned; type Receipt = SeismicReceipt; } /// Bincode-compatible serde implementations. #[cfg(feature = "serde-bincode-compat")] pub mod serde_bincode_compat { pub use super::{ receipt::serde_bincode_compat::*, transaction::signed::serde_bincode_compat::*, }; }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/seismic/primitives/src/test_utils.rs
crates/seismic/primitives/src/test_utils.rs
//! Test utils for seismic primitives, e.g. SeismicTransactionSigned use crate::SeismicTransactionSigned; use alloy_consensus::SignableTransaction; use alloy_dyn_abi::TypedData; use alloy_eips::eip2718::Encodable2718; use alloy_network::{EthereumWallet, TransactionBuilder}; use alloy_primitives::{aliases::U96, hex_literal, Address, Bytes, Signature, TxKind, U256}; use alloy_rpc_types::{TransactionInput, TransactionRequest}; use alloy_signer_local::PrivateKeySigner; use core::str::FromStr; use enr::EnrKey; use k256::ecdsa::SigningKey; use seismic_enclave::get_unsecure_sample_secp256k1_pk; use secp256k1::{PublicKey, SecretKey}; use seismic_alloy_consensus::{ SeismicTxEnvelope, SeismicTypedTransaction, TxSeismic, TxSeismicElements, TypedDataRequest, }; use seismic_alloy_rpc_types::SeismicTransactionRequest; /// Get the network public key pub fn get_network_public_key() -> PublicKey { get_unsecure_sample_secp256k1_pk() } /// Get the client's sk for tx io pub fn get_client_io_sk() -> SecretKey { let private_key_bytes = hex_literal::hex!("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"); SecretKey::from_slice(&private_key_bytes).expect("Invalid private key") } /// Get the client's signing private key pub fn get_signing_private_key() -> SigningKey { let private_key_bytes = hex_literal::hex!("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"); let signing_key = SigningKey::from_bytes(&private_key_bytes.into()).expect("Invalid private key"); signing_key } /// Get a wrong private secp256k1 key pub fn get_wrong_private_key() -> SecretKey { let private_key_bytes = hex_literal::hex!("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1e"); SecretKey::from_slice(&private_key_bytes).expect("Invalid private key") } /// Get the encryption nonce pub fn get_encryption_nonce() -> U96 { U96::MAX } /// Get the seismic elements pub fn get_seismic_elements() -> TxSeismicElements { TxSeismicElements { encryption_pubkey: get_client_io_sk().public(), encryption_nonce: get_encryption_nonce(), message_version: 0, } } /// Encrypt plaintext using network public key and client private key pub fn client_encrypt(plaintext: &Bytes) -> Result<Bytes, anyhow::Error> { get_seismic_elements().client_encrypt(plaintext, &get_network_public_key(), &get_client_io_sk()) } /// Decrypt ciphertext using network public key and client private key pub fn client_decrypt(ciphertext: &Bytes) -> Result<Bytes, anyhow::Error> { get_seismic_elements().client_decrypt( ciphertext, &get_network_public_key(), &get_client_io_sk(), ) } /// Get the plaintext for a seismic transaction pub fn get_plaintext() -> Bytes { Bytes::from_str("24a7f0b7000000000000000000000000000000000000000000000000000000000000000b") .unwrap() } /// Encrypt plaintext using network public key and client private key pub fn get_ciphertext() -> Bytes { let encrypted_data = client_encrypt(&get_plaintext()).unwrap(); encrypted_data } /// Get a seismic transaction pub fn get_seismic_tx() -> TxSeismic { let ciphertext = get_ciphertext(); TxSeismic { chain_id: 5123, // seismic chain id nonce: 1, gas_price: 20000000000, gas_limit: 210000, to: alloy_primitives::TxKind::Call( Address::from_str("0x5fbdb2315678afecb367f032d93f642f64180aa3").unwrap(), ), value: U256::ZERO, input: Bytes::copy_from_slice(&ciphertext), seismic_elements: get_seismic_elements(), } } /// Sign a seismic transaction pub fn sign_seismic_tx(tx: &TxSeismic, signing_sk: &SigningKey) -> Signature { let _signature = signing_sk .clone() .sign_prehash_recoverable(tx.signature_hash().as_slice()) .expect("Failed to sign"); let recoverid = _signature.1; let _signature = _signature.0; let signature = Signature::new( U256::from_be_slice(_signature.r().to_bytes().as_slice()), U256::from_be_slice(_signature.s().to_bytes().as_slice()), recoverid.is_y_odd(), ); signature } /// signes a [`SeismicTypedTransaction`] using the provided [`SigningKey`] pub fn sign_seismic_typed_tx( typed_data: &SeismicTypedTransaction, signing_sk: &SigningKey, ) -> Signature { let sig_hash = typed_data.signature_hash(); let sig = signing_sk.sign_prehash_recoverable(&sig_hash.as_slice()).unwrap(); let recoverid = sig.1; let signature = Signature::new( U256::from_be_slice(sig.0.r().to_bytes().as_slice()), U256::from_be_slice(sig.0.s().to_bytes().as_slice()), recoverid.is_y_odd(), ); signature } /// Get a signed seismic transaction pub fn get_signed_seismic_tx() -> SeismicTransactionSigned { let signing_sk = get_signing_private_key(); let tx = get_seismic_tx(); let signature = sign_seismic_tx(&tx, &signing_sk); SignableTransaction::into_signed(tx, signature).into() } /// Get the encoding of a signed seismic transaction pub fn get_signed_seismic_tx_encoding() -> Vec<u8> { let signed_tx = get_signed_seismic_tx(); let mut encoding = Vec::new(); signed_tx.encode_2718(&mut encoding); encoding } /// Get an unsigned seismic transaction request pub async fn get_unsigned_seismic_tx_request( sk_wallet: &PrivateKeySigner, nonce: u64, to: TxKind, chain_id: u64, plaintext: Bytes, ) -> SeismicTransactionRequest { SeismicTransactionRequest { inner: TransactionRequest { from: Some(sk_wallet.address()), nonce: Some(nonce), value: Some(U256::from(0)), to: Some(to), gas: Some(6000000), gas_price: Some(20e9 as u128), chain_id: Some(chain_id), input: TransactionInput { input: Some(client_encrypt(&plaintext).unwrap()), data: None, }, transaction_type: Some(TxSeismic::TX_TYPE), ..Default::default() }, seismic_elements: Some(get_seismic_elements()), } } /// Signs an arbitrary [`TransactionRequest`] using the provided wallet pub async fn sign_tx(wallet: PrivateKeySigner, tx: SeismicTransactionRequest) -> SeismicTxEnvelope { let signer = EthereumWallet::from(wallet); <SeismicTransactionRequest as TransactionBuilder<seismic_alloy_network::Seismic>>::build( tx, &signer, ) .await .unwrap() } /// Create a seismic transaction pub async fn get_signed_seismic_tx_bytes( sk_wallet: &PrivateKeySigner, nonce: u64, to: TxKind, chain_id: u64, plaintext: Bytes, ) -> Bytes { let tx = get_unsigned_seismic_tx_request(sk_wallet, nonce, to, chain_id, plaintext).await; let signed_inner = sign_tx(sk_wallet.clone(), tx).await; <SeismicTxEnvelope as Encodable2718>::encoded_2718(&signed_inner).into() } /// Get an unsigned seismic transaction typed data pub async fn get_unsigned_seismic_tx_typed_data( sk_wallet: &PrivateKeySigner, nonce: u64, to: TxKind, chain_id: u64, decrypted_input: Bytes, ) -> TypedData { let tx_request = get_unsigned_seismic_tx_request(sk_wallet, nonce, to, chain_id, decrypted_input).await; let typed_tx = tx_request.build_typed_tx().unwrap(); match typed_tx { SeismicTypedTransaction::Seismic(seismic) => seismic.eip712_to_type_data(), _ => panic!("Typed transaction is not a seismic transaction"), } } /// Create a seismic transaction with typed data pub async fn get_signed_seismic_tx_typed_data( sk_wallet: &PrivateKeySigner, nonce: u64, to: TxKind, chain_id: u64, plaintext: Bytes, ) -> TypedDataRequest { let tx = get_unsigned_seismic_tx_request(sk_wallet, nonce, to, chain_id, plaintext).await; tx.seismic_elements.unwrap().message_version = 2; let signed = sign_tx(sk_wallet.clone(), tx).await; match signed { SeismicTxEnvelope::Seismic(tx) => tx.into(), _ => panic!("Signed transaction is not a seismic transaction"), } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/seismic/primitives/src/receipt.rs
crates/seismic/primitives/src/receipt.rs
use alloy_consensus::{ proofs::ordered_trie_root_with_encoder, Eip2718EncodableReceipt, Eip658Value, Receipt, ReceiptWithBloom, RlpDecodableReceipt, RlpEncodableReceipt, TxReceipt, Typed2718, }; use alloy_eips::{eip2718::Eip2718Result, Decodable2718, Encodable2718}; use alloy_primitives::{Bloom, Log, B256}; use alloy_rlp::{BufMut, Decodable, Encodable, Header}; use reth_primitives_traits::InMemorySize; use seismic_alloy_consensus::SeismicTxType; /// Typed ethereum transaction receipt. /// Receipt containing result of transaction execution. #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] pub enum SeismicReceipt { /// Legacy receipt Legacy(Receipt), /// EIP-2930 receipt Eip2930(Receipt), /// EIP-1559 receipt Eip1559(Receipt), /// EIP-4844 receipt Eip4844(Receipt), /// EIP-7702 receipt Eip7702(Receipt), /// Seismic receipt Seismic(Receipt), } impl Default for SeismicReceipt { fn default() -> Self { Self::Legacy(Default::default()) } } impl SeismicReceipt { /// Returns [`SeismicTxType`] of the receipt. pub const fn tx_type(&self) -> SeismicTxType { match self { Self::Legacy(_) => SeismicTxType::Legacy, Self::Eip2930(_) => SeismicTxType::Eip2930, Self::Eip1559(_) => SeismicTxType::Eip1559, Self::Eip4844(_) => SeismicTxType::Eip4844, Self::Eip7702(_) => SeismicTxType::Eip7702, Self::Seismic(_) => SeismicTxType::Seismic, } } /// Returns inner [`Receipt`], pub const fn as_receipt(&self) -> &Receipt { match self { Self::Legacy(receipt) | Self::Eip2930(receipt) | Self::Eip1559(receipt) | Self::Eip4844(receipt) | Self::Eip7702(receipt) | Self::Seismic(receipt) => receipt, } } /// Returns a mutable reference to the inner [`Receipt`], pub const fn as_receipt_mut(&mut self) -> &mut Receipt { match self { Self::Legacy(receipt) | Self::Eip2930(receipt) | Self::Eip1559(receipt) | Self::Eip4844(receipt) | Self::Eip7702(receipt) | Self::Seismic(receipt) => receipt, } } /// Consumes this and returns the inner [`Receipt`]. pub fn into_receipt(self) -> Receipt { match self { Self::Legacy(receipt) | Self::Eip2930(receipt) | Self::Eip1559(receipt) | Self::Eip4844(receipt) | Self::Eip7702(receipt) | Self::Seismic(receipt) => receipt, } } /// Returns length of RLP-encoded receipt fields with the given [`Bloom`] without an RLP header. pub fn rlp_encoded_fields_length(&self, bloom: &Bloom) -> usize { match self { Self::Legacy(receipt) | Self::Eip2930(receipt) | Self::Eip1559(receipt) | Self::Eip4844(receipt) | Self::Eip7702(receipt) | Self::Seismic(receipt) => receipt.rlp_encoded_fields_length_with_bloom(bloom), } } /// RLP-encodes receipt fields with the given [`Bloom`] without an RLP header. pub fn rlp_encode_fields(&self, bloom: &Bloom, out: &mut dyn BufMut) { match self { Self::Legacy(receipt) | Self::Eip2930(receipt) | Self::Eip1559(receipt) | Self::Eip4844(receipt) | Self::Eip7702(receipt) | Self::Seismic(receipt) => receipt.rlp_encode_fields_with_bloom(bloom, out), } } /// Returns RLP header for inner encoding. pub fn rlp_header_inner(&self, bloom: &Bloom) -> Header { Header { list: true, payload_length: self.rlp_encoded_fields_length(bloom) } } /// Returns RLP header for inner encoding without bloom. pub fn rlp_header_inner_without_bloom(&self) -> Header { Header { list: true, payload_length: self.rlp_encoded_fields_length_without_bloom() } } /// RLP-decodes the receipt from the provided buffer. This does not expect a type byte or /// network header. pub fn rlp_decode_inner( buf: &mut &[u8], tx_type: SeismicTxType, ) -> alloy_rlp::Result<ReceiptWithBloom<Self>> { match tx_type { SeismicTxType::Legacy => { let ReceiptWithBloom { receipt, logs_bloom } = RlpDecodableReceipt::rlp_decode_with_bloom(buf)?; Ok(ReceiptWithBloom { receipt: Self::Legacy(receipt), logs_bloom }) } SeismicTxType::Eip2930 => { let ReceiptWithBloom { receipt, logs_bloom } = RlpDecodableReceipt::rlp_decode_with_bloom(buf)?; Ok(ReceiptWithBloom { receipt: Self::Eip2930(receipt), logs_bloom }) } SeismicTxType::Eip1559 => { let ReceiptWithBloom { receipt, logs_bloom } = RlpDecodableReceipt::rlp_decode_with_bloom(buf)?; Ok(ReceiptWithBloom { receipt: Self::Eip1559(receipt), logs_bloom }) } SeismicTxType::Eip4844 => { let ReceiptWithBloom { receipt, logs_bloom } = RlpDecodableReceipt::rlp_decode_with_bloom(buf)?; Ok(ReceiptWithBloom { receipt: Self::Eip4844(receipt), logs_bloom }) } SeismicTxType::Eip7702 => { let ReceiptWithBloom { receipt, logs_bloom } = RlpDecodableReceipt::rlp_decode_with_bloom(buf)?; Ok(ReceiptWithBloom { receipt: Self::Eip7702(receipt), logs_bloom }) } SeismicTxType::Seismic => { let ReceiptWithBloom { receipt, logs_bloom } = RlpDecodableReceipt::rlp_decode_with_bloom(buf)?; Ok(ReceiptWithBloom { receipt: Self::Seismic(receipt), logs_bloom }) } } } /// RLP-encodes receipt fields without an RLP header. pub fn rlp_encode_fields_without_bloom(&self, out: &mut dyn BufMut) { match self { Self::Legacy(receipt) | Self::Eip2930(receipt) | Self::Eip1559(receipt) | Self::Eip4844(receipt) | Self::Eip7702(receipt) | Self::Seismic(receipt) => { receipt.status.encode(out); receipt.cumulative_gas_used.encode(out); receipt.logs.encode(out); } } } /// Returns length of RLP-encoded receipt fields without an RLP header. pub fn rlp_encoded_fields_length_without_bloom(&self) -> usize { match self { Self::Legacy(receipt) | Self::Eip2930(receipt) | Self::Eip1559(receipt) | Self::Eip4844(receipt) | Self::Eip7702(receipt) | Self::Seismic(receipt) => { receipt.status.length() + receipt.cumulative_gas_used.length() + receipt.logs.length() } } } /// RLP-decodes the receipt from the provided buffer without bloom. pub fn rlp_decode_inner_without_bloom( buf: &mut &[u8], tx_type: SeismicTxType, ) -> alloy_rlp::Result<Self> { let header = Header::decode(buf)?; if !header.list { return Err(alloy_rlp::Error::UnexpectedString); } let remaining = buf.len(); let status = Decodable::decode(buf)?; let cumulative_gas_used = Decodable::decode(buf)?; let logs = Decodable::decode(buf)?; if buf.len() + header.payload_length != remaining { return Err(alloy_rlp::Error::UnexpectedLength); } match tx_type { SeismicTxType::Legacy => { Ok(Self::Legacy(Receipt { status, cumulative_gas_used, logs })) } SeismicTxType::Eip2930 => { Ok(Self::Eip2930(Receipt { status, cumulative_gas_used, logs })) } SeismicTxType::Eip1559 => { Ok(Self::Eip1559(Receipt { status, cumulative_gas_used, logs })) } SeismicTxType::Eip4844 => { Ok(Self::Eip4844(Receipt { status, cumulative_gas_used, logs })) } SeismicTxType::Eip7702 => { Ok(Self::Eip7702(Receipt { status, cumulative_gas_used, logs })) } SeismicTxType::Seismic => { Ok(Self::Seismic(Receipt { status, cumulative_gas_used, logs })) } } } /// Calculates the receipt root for a header for the reference type of [Receipt]. /// /// NOTE: Prefer `proofs::calculate_receipt_root` if you have log blooms memoized. pub fn calculate_receipt_root_no_memo(receipts: &[Self]) -> B256 { ordered_trie_root_with_encoder(receipts, |r, buf| r.with_bloom_ref().encode_2718(buf)) } } impl Eip2718EncodableReceipt for SeismicReceipt { fn eip2718_encoded_length_with_bloom(&self, bloom: &Bloom) -> usize { !self.tx_type().is_legacy() as usize + self.rlp_header_inner(bloom).length_with_payload() } fn eip2718_encode_with_bloom(&self, bloom: &Bloom, out: &mut dyn BufMut) { if !self.tx_type().is_legacy() { out.put_u8(self.tx_type() as u8); } self.rlp_header_inner(bloom).encode(out); self.rlp_encode_fields(bloom, out); } } impl RlpEncodableReceipt for SeismicReceipt { fn rlp_encoded_length_with_bloom(&self, bloom: &Bloom) -> usize { let mut len = self.eip2718_encoded_length_with_bloom(bloom); if !self.tx_type().is_legacy() { len += Header { list: false, payload_length: self.eip2718_encoded_length_with_bloom(bloom), } .length(); } len } fn rlp_encode_with_bloom(&self, bloom: &Bloom, out: &mut dyn BufMut) { if !self.tx_type().is_legacy() { Header { list: false, payload_length: self.eip2718_encoded_length_with_bloom(bloom) } .encode(out); } self.eip2718_encode_with_bloom(bloom, out); } } impl RlpDecodableReceipt for SeismicReceipt { fn rlp_decode_with_bloom(buf: &mut &[u8]) -> alloy_rlp::Result<ReceiptWithBloom<Self>> { let header_buf = &mut &**buf; let header = Header::decode(header_buf)?; // Legacy receipt, reuse initial buffer without advancing if header.list { return Self::rlp_decode_inner(buf, SeismicTxType::Legacy) } // Otherwise, advance the buffer and try decoding type flag followed by receipt *buf = *header_buf; let remaining = buf.len(); let tx_type = SeismicTxType::decode(buf)?; let this = Self::rlp_decode_inner(buf, tx_type)?; if buf.len() + header.payload_length != remaining { return Err(alloy_rlp::Error::UnexpectedLength); } Ok(this) } } impl Encodable2718 for SeismicReceipt { fn encode_2718_len(&self) -> usize { !self.tx_type().is_legacy() as usize + self.rlp_header_inner_without_bloom().length_with_payload() } fn encode_2718(&self, out: &mut dyn BufMut) { if !self.tx_type().is_legacy() { out.put_u8(self.tx_type() as u8); } self.rlp_header_inner_without_bloom().encode(out); self.rlp_encode_fields_without_bloom(out); } } impl Decodable2718 for SeismicReceipt { fn typed_decode(ty: u8, buf: &mut &[u8]) -> Eip2718Result<Self> { Ok(Self::rlp_decode_inner_without_bloom(buf, SeismicTxType::try_from(ty)?)?) } fn fallback_decode(buf: &mut &[u8]) -> Eip2718Result<Self> { Ok(Self::rlp_decode_inner_without_bloom(buf, SeismicTxType::Legacy)?) } } impl Encodable for SeismicReceipt { fn encode(&self, out: &mut dyn BufMut) { self.network_encode(out); } fn length(&self) -> usize { self.network_len() } } impl Decodable for SeismicReceipt { fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> { Ok(Self::network_decode(buf)?) } } impl TxReceipt for SeismicReceipt { type Log = Log; fn status_or_post_state(&self) -> Eip658Value { self.as_receipt().status_or_post_state() } fn status(&self) -> bool { self.as_receipt().status() } fn bloom(&self) -> Bloom { self.as_receipt().bloom() } fn cumulative_gas_used(&self) -> u64 { self.as_receipt().cumulative_gas_used() } fn logs(&self) -> &[Log] { self.as_receipt().logs() } } impl Typed2718 for SeismicReceipt { fn ty(&self) -> u8 { self.tx_type().into() } } impl InMemorySize for SeismicReceipt { fn size(&self) -> usize { self.as_receipt().size() } } #[cfg(feature = "reth-codec")] mod compact { use super::*; use alloc::borrow::Cow; use reth_codecs::Compact; #[derive(reth_codecs::CompactZstd)] #[reth_zstd( compressor = reth_zstd_compressors::RECEIPT_COMPRESSOR, decompressor = reth_zstd_compressors::RECEIPT_DECOMPRESSOR )] struct CompactSeismicReceipt<'a> { tx_type: SeismicTxType, success: bool, cumulative_gas_used: u64, #[expect(clippy::owned_cow)] logs: Cow<'a, Vec<Log>>, } impl<'a> From<&'a SeismicReceipt> for CompactSeismicReceipt<'a> { fn from(receipt: &'a SeismicReceipt) -> Self { Self { tx_type: receipt.tx_type(), success: receipt.status(), cumulative_gas_used: receipt.cumulative_gas_used(), logs: Cow::Borrowed(&receipt.as_receipt().logs), } } } impl From<CompactSeismicReceipt<'_>> for SeismicReceipt { fn from(receipt: CompactSeismicReceipt<'_>) -> Self { let CompactSeismicReceipt { tx_type, success, cumulative_gas_used, logs } = receipt; let inner = Receipt { status: success.into(), cumulative_gas_used, logs: logs.into_owned() }; match tx_type { SeismicTxType::Legacy => Self::Legacy(inner), SeismicTxType::Eip2930 => Self::Eip2930(inner), SeismicTxType::Eip1559 => Self::Eip1559(inner), SeismicTxType::Eip4844 => Self::Eip4844(inner), SeismicTxType::Eip7702 => Self::Eip7702(inner), SeismicTxType::Seismic => Self::Seismic(inner), } } } impl Compact for SeismicReceipt { fn to_compact<B>(&self, buf: &mut B) -> usize where B: bytes::BufMut + AsMut<[u8]>, { CompactSeismicReceipt::from(self).to_compact(buf) } fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) { let (receipt, buf) = CompactSeismicReceipt::from_compact(buf, len); (receipt.into(), buf) } } } #[cfg(all(feature = "serde", feature = "serde-bincode-compat"))] pub(super) mod serde_bincode_compat { use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_with::{DeserializeAs, SerializeAs}; /// Bincode-compatible [`super::SeismicReceipt`] serde implementation. /// /// Intended to use with the [`serde_with::serde_as`] macro in the following way: /// ```rust /// use reth_seismic_primitives::{serde_bincode_compat, SeismicReceipt}; /// use serde::{de::DeserializeOwned, Deserialize, Serialize}; /// use serde_with::serde_as; /// /// #[serde_as] /// #[derive(Serialize, Deserialize)] /// struct Data { /// #[serde_as(as = "serde_bincode_compat::SeismicReceipt<'_>")] /// receipt: SeismicReceipt, /// } /// ``` #[derive(Debug, Serialize, Deserialize)] pub enum SeismicReceipt<'a> { /// Legacy receipt Legacy(alloy_consensus::serde_bincode_compat::Receipt<'a, alloy_primitives::Log>), /// EIP-2930 receipt Eip2930(alloy_consensus::serde_bincode_compat::Receipt<'a, alloy_primitives::Log>), /// EIP-1559 receipt Eip1559(alloy_consensus::serde_bincode_compat::Receipt<'a, alloy_primitives::Log>), /// EIP-4844 receipt Eip4844(alloy_consensus::serde_bincode_compat::Receipt<'a, alloy_primitives::Log>), /// EIP-7702 receipt Eip7702(alloy_consensus::serde_bincode_compat::Receipt<'a, alloy_primitives::Log>), /// Seismic receipt Seismic(alloy_consensus::serde_bincode_compat::Receipt<'a, alloy_primitives::Log>), } impl<'a> From<&'a super::SeismicReceipt> for SeismicReceipt<'a> { fn from(value: &'a super::SeismicReceipt) -> Self { match value { super::SeismicReceipt::Legacy(receipt) => Self::Legacy(receipt.into()), super::SeismicReceipt::Eip2930(receipt) => Self::Eip2930(receipt.into()), super::SeismicReceipt::Eip1559(receipt) => Self::Eip1559(receipt.into()), super::SeismicReceipt::Eip4844(receipt) => Self::Eip4844(receipt.into()), super::SeismicReceipt::Eip7702(receipt) => Self::Eip7702(receipt.into()), super::SeismicReceipt::Seismic(receipt) => Self::Seismic(receipt.into()), } } } impl<'a> From<SeismicReceipt<'a>> for super::SeismicReceipt { fn from(value: SeismicReceipt<'a>) -> Self { match value { SeismicReceipt::Legacy(receipt) => Self::Legacy(receipt.into()), SeismicReceipt::Eip2930(receipt) => Self::Eip2930(receipt.into()), SeismicReceipt::Eip1559(receipt) => Self::Eip1559(receipt.into()), SeismicReceipt::Eip4844(receipt) => Self::Eip4844(receipt.into()), SeismicReceipt::Eip7702(receipt) => Self::Eip7702(receipt.into()), SeismicReceipt::Seismic(receipt) => Self::Seismic(receipt.into()), } } } impl SerializeAs<super::SeismicReceipt> for SeismicReceipt<'_> { fn serialize_as<S>(source: &super::SeismicReceipt, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { SeismicReceipt::<'_>::from(source).serialize(serializer) } } impl<'de> DeserializeAs<'de, super::SeismicReceipt> for SeismicReceipt<'de> { fn deserialize_as<D>(deserializer: D) -> Result<super::SeismicReceipt, D::Error> where D: Deserializer<'de>, { SeismicReceipt::<'_>::deserialize(deserializer).map(Into::into) } } impl reth_primitives_traits::serde_bincode_compat::SerdeBincodeCompat for super::SeismicReceipt { type BincodeRepr<'a> = SeismicReceipt<'a>; fn as_repr(&self) -> Self::BincodeRepr<'_> { self.into() } fn from_repr(repr: Self::BincodeRepr<'_>) -> Self { repr.into() } } #[cfg(test)] mod tests { use crate::{receipt::serde_bincode_compat, SeismicReceipt}; use arbitrary::Arbitrary; use rand::Rng; use serde::{Deserialize, Serialize}; use serde_with::serde_as; #[test] fn test_tx_bincode_roundtrip() { #[serde_as] #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] struct Data { #[serde_as(as = "serde_bincode_compat::SeismicReceipt<'_>")] receipt: SeismicReceipt, } let mut bytes = [0u8; 1024]; rand::rng().fill(bytes.as_mut_slice()); let mut data = Data { receipt: SeismicReceipt::arbitrary(&mut arbitrary::Unstructured::new(&bytes)) .unwrap(), }; let success = data.receipt.as_receipt_mut().status.coerce_status(); // // ensure we don't have an invalid poststate variant data.receipt.as_receipt_mut().status = success.into(); let encoded = bincode::serialize(&data).unwrap(); let decoded: Data = bincode::deserialize(&encoded).unwrap(); assert_eq!(decoded, data); } } } #[cfg(test)] mod tests { use super::*; use alloy_eips::eip2718::Encodable2718; use alloy_primitives::{address, b256, bytes, hex_literal::hex}; use alloy_rlp::Encodable; #[test] #[cfg(feature = "reth-codec")] // checks compact encoding, test decode performs a roundtrip check fn test_decode_receipt() { reth_codecs::test_utils::test_decode::<SeismicReceipt>(&hex!( "c428b52ffd23fc42696156b10200f034792b6a94c3850215c2fef7aea361a0c31b79d9a32652eefc0d4e2e730036061cff7344b6fc6132b50cda0ed810a991ae58ef013150c12b2522533cb3b3a8b19b7786a8b5ff1d3cdc84225e22b02def168c8858df" )); } // Test vector from: https://eips.ethereum.org/EIPS/eip-2481 // checks rlp encoding #[test] fn encode_legacy_receipt() { let expected = hex!("f901668001b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f85ff85d940000000000000000000000000000000000000011f842a0000000000000000000000000000000000000000000000000000000000000deada0000000000000000000000000000000000000000000000000000000000000beef830100ff"); let mut data = Vec::with_capacity(expected.length()); let receipt = ReceiptWithBloom { receipt: SeismicReceipt::Legacy(Receipt { status: Eip658Value::Eip658(false), cumulative_gas_used: 0x1, logs: vec![Log::new_unchecked( address!("0x0000000000000000000000000000000000000011"), vec![ b256!("0x000000000000000000000000000000000000000000000000000000000000dead"), b256!("0x000000000000000000000000000000000000000000000000000000000000beef"), ], bytes!("0100ff"), )], }), logs_bloom: [0; 256].into(), }; receipt.encode(&mut data); // check that the rlp length equals the length of the expected rlp assert_eq!(receipt.length(), expected.len()); assert_eq!(data, expected); } // Test vector from: https://eips.ethereum.org/EIPS/eip-2481 // checks rlp decoding #[test] fn decode_legacy_receipt() { let data = hex!("f901668001b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f85ff85d940000000000000000000000000000000000000011f842a0000000000000000000000000000000000000000000000000000000000000deada0000000000000000000000000000000000000000000000000000000000000beef830100ff"); // EIP658Receipt let expected = ReceiptWithBloom { receipt: SeismicReceipt::Legacy(Receipt { status: Eip658Value::Eip658(false), cumulative_gas_used: 0x1, logs: vec![Log::new_unchecked( address!("0x0000000000000000000000000000000000000011"), vec![ b256!("0x000000000000000000000000000000000000000000000000000000000000dead"), b256!("0x000000000000000000000000000000000000000000000000000000000000beef"), ], bytes!("0100ff"), )], }), logs_bloom: [0; 256].into(), }; let receipt = ReceiptWithBloom::decode(&mut &data[..]).unwrap(); assert_eq!(receipt, expected); } #[test] fn test_encode_2718_length() { let receipt = ReceiptWithBloom { receipt: SeismicReceipt::Eip1559(Receipt { status: Eip658Value::Eip658(true), cumulative_gas_used: 21000, logs: vec![], }), logs_bloom: Bloom::default(), }; let encoded = receipt.encoded_2718(); assert_eq!( encoded.len(), receipt.encode_2718_len(), "Encoded length should match the actual encoded data length" ); // Test for legacy receipt as well let legacy_receipt = ReceiptWithBloom { receipt: SeismicReceipt::Legacy(Receipt { status: Eip658Value::Eip658(true), cumulative_gas_used: 21000, logs: vec![], }), logs_bloom: Bloom::default(), }; let legacy_encoded = legacy_receipt.encoded_2718(); assert_eq!( legacy_encoded.len(), legacy_receipt.encode_2718_len(), "Encoded length for legacy receipt should match the actual encoded data length" ); } #[test] // checks rlp encoding for SeismicReceipt::Seismic fn seismic_seismic_receipt_roundtrip() { let receipt: ReceiptWithBloom<SeismicReceipt> = ReceiptWithBloom { receipt: SeismicReceipt::Legacy(Receipt { status: Eip658Value::Eip658(false), cumulative_gas_used: 0x1, logs: vec![Log::new_unchecked( address!("0x0000000000000000000000000000000000000011"), vec![ b256!("0x000000000000000000000000000000000000000000000000000000000000dead"), b256!("0x000000000000000000000000000000000000000000000000000000000000beef"), ], bytes!("0100ff"), )], }), logs_bloom: [0; 256].into(), }; let mut data = Vec::with_capacity(receipt.encode_2718_len()); receipt.encode(&mut data); let decoded: ReceiptWithBloom<SeismicReceipt> = ReceiptWithBloom::decode(&mut &data[..]).unwrap(); assert_eq!(receipt, decoded); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/seismic/primitives/src/transaction/mod.rs
crates/seismic/primitives/src/transaction/mod.rs
//! Optimism transaction types pub mod signed; pub mod tx_type;
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/seismic/primitives/src/transaction/signed.rs
crates/seismic/primitives/src/transaction/signed.rs
//! A signed Seismic transaction. use alloc::vec::Vec; use alloy_consensus::{ transaction::{RlpEcdsaDecodableTx, RlpEcdsaEncodableTx}, SignableTransaction, Signed, Transaction, TxEip1559, TxEip2930, TxEip4844, TxEip7702, TxLegacy, Typed2718, }; use alloy_eips::{ eip2718::{Decodable2718, Eip2718Error, Eip2718Result, Encodable2718}, eip2930::AccessList, eip7702::SignedAuthorization, }; use alloy_evm::FromRecoveredTx; use alloy_primitives::{keccak256, Address, Bytes, Signature, TxHash, TxKind, Uint, B256}; use alloy_rlp::Header; use core::{ hash::{Hash, Hasher}, mem, ops::Deref, }; use derive_more::{AsRef, Deref}; #[cfg(any(test, feature = "reth-codec"))] use proptest as _; use reth_primitives_traits::{ crypto::secp256k1::{recover_signer, recover_signer_unchecked}, sync::OnceLock, transaction::signed::RecoveryError, InMemorySize, SignedTransaction, SignerRecoverable, }; use revm_context::{either::Either, TxEnv}; use seismic_alloy_consensus::{ InputDecryptionElements, InputDecryptionElementsError, SeismicTxEnvelope, SeismicTypedTransaction, TxSeismic, TxSeismicElements, }; use seismic_revm::{transaction::abstraction::RngMode, SeismicTransaction}; // Seismic imports, not used by upstream use alloy_consensus::TxEip4844Variant; use alloy_evm::FromTxWithEncoded; /// Signed transaction. /// /// [`SeismicTransactionSigned`] is a wrapper around a [`SeismicTypedTransaction`] enum, /// which can be Seismic(TxSeismic) with additional fields, or Ethereum compatible transactions. #[cfg_attr(any(test, feature = "reth-codec"), reth_codecs::add_arbitrary_tests(rlp))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Debug, Clone, Eq, AsRef, Deref)] pub struct SeismicTransactionSigned { /// Transaction hash #[cfg_attr(feature = "serde", serde(skip))] hash: OnceLock<TxHash>, /// The transaction signature values signature: Signature, /// Raw transaction info #[deref] #[as_ref] transaction: SeismicTypedTransaction, } impl SeismicTransactionSigned { /// Creates a new signed transaction from the given transaction, signature and hash. pub fn new(transaction: SeismicTypedTransaction, signature: Signature, hash: B256) -> Self { Self { hash: hash.into(), signature, transaction } } /// Consumes the type and returns the transaction. #[inline] pub fn into_transaction(self) -> SeismicTypedTransaction { self.transaction } /// Returns the transaction. #[inline] pub const fn transaction(&self) -> &SeismicTypedTransaction { &self.transaction } /// Splits the `SeismicTransactionSigned` into its transaction and signature. pub fn split(self) -> (SeismicTypedTransaction, Signature) { (self.transaction, self.signature) } /// Creates a new signed transaction from the given transaction and signature without the hash. /// /// Note: this only calculates the hash on the first [`SeismicTransactionSigned::hash`] call. pub fn new_unhashed(transaction: SeismicTypedTransaction, signature: Signature) -> Self { Self { hash: Default::default(), signature, transaction } } /// Splits the transaction into parts. pub fn into_parts(self) -> (SeismicTypedTransaction, Signature, B256) { let hash = *self.hash.get_or_init(|| self.recalculate_hash()); (self.transaction, self.signature, hash) } } impl SignerRecoverable for SeismicTransactionSigned { fn recover_signer(&self) -> Result<Address, RecoveryError> { let Self { transaction, signature, .. } = self; let signature_hash = signature_hash(transaction); recover_signer(signature, signature_hash) } fn recover_signer_unchecked(&self) -> Result<Address, RecoveryError> { let Self { transaction, signature, .. } = self; let signature_hash = signature_hash(transaction); recover_signer_unchecked(signature, signature_hash) } } impl SignedTransaction for SeismicTransactionSigned { fn tx_hash(&self) -> &TxHash { self.hash.get_or_init(|| self.recalculate_hash()) } fn recalculate_hash(&self) -> B256 { keccak256(self.encoded_2718()) } } macro_rules! impl_from_signed { ($($tx:ident),*) => { $( impl From<Signed<$tx>> for SeismicTransactionSigned { fn from(value: Signed<$tx>) -> Self { let(tx,sig,hash) = value.into_parts(); Self::new(tx.into(), sig, hash) } } )* }; } impl_from_signed!( TxLegacy, TxEip2930, TxEip1559, TxEip4844Variant, TxEip7702, TxSeismic, SeismicTypedTransaction ); impl From<SeismicTxEnvelope> for SeismicTransactionSigned { fn from(value: SeismicTxEnvelope) -> Self { match value { SeismicTxEnvelope::Legacy(tx) => tx.into(), SeismicTxEnvelope::Eip2930(tx) => tx.into(), SeismicTxEnvelope::Eip1559(tx) => tx.into(), SeismicTxEnvelope::Eip4844(tx) => tx.into(), SeismicTxEnvelope::Eip7702(tx) => tx.into(), SeismicTxEnvelope::Seismic(tx) => tx.into(), } } } impl From<SeismicTransactionSigned> for SeismicTxEnvelope { fn from(value: SeismicTransactionSigned) -> Self { let (tx, signature, hash) = value.into_parts(); match tx { SeismicTypedTransaction::Legacy(tx) => { Signed::new_unchecked(tx, signature, hash).into() } SeismicTypedTransaction::Eip2930(tx) => { Signed::new_unchecked(tx, signature, hash).into() } SeismicTypedTransaction::Eip1559(tx) => { Signed::new_unchecked(tx, signature, hash).into() } SeismicTypedTransaction::Eip4844(tx) => { Signed::new_unchecked(tx, signature, hash).into() } SeismicTypedTransaction::Seismic(tx) => { Signed::new_unchecked(tx, signature, hash).into() } SeismicTypedTransaction::Eip7702(tx) => { Signed::new_unchecked(tx, signature, hash).into() } } } } impl From<SeismicTransactionSigned> for Signed<SeismicTypedTransaction> { fn from(value: SeismicTransactionSigned) -> Self { let (tx, sig, hash) = value.into_parts(); Self::new_unchecked(tx, sig, hash) } } // This function converts reth types (SeismicTransactionSigned) to revm types // (SeismicTransaction<TxEnv>) impl FromRecoveredTx<SeismicTransactionSigned> for SeismicTransaction<TxEnv> { fn from_recovered_tx(tx: &SeismicTransactionSigned, sender: Address) -> Self { let tx_hash = tx.tx_hash().clone(); let rng_mode = RngMode::Execution; // TODO WARNING: chose a default value let tx = match &tx.transaction { SeismicTypedTransaction::Legacy(tx) => SeismicTransaction::<TxEnv> { base: TxEnv { gas_limit: tx.gas_limit, gas_price: tx.gas_price, gas_priority_fee: None, kind: tx.to, value: tx.value, data: tx.input.clone(), chain_id: tx.chain_id, nonce: tx.nonce, access_list: Default::default(), blob_hashes: Default::default(), max_fee_per_blob_gas: Default::default(), authorization_list: Default::default(), tx_type: 0, caller: sender, }, tx_hash, rng_mode, }, SeismicTypedTransaction::Eip2930(tx) => SeismicTransaction::<TxEnv> { base: TxEnv { gas_limit: tx.gas_limit, gas_price: tx.gas_price, gas_priority_fee: None, kind: tx.to, value: tx.value, data: tx.input.clone(), chain_id: Some(tx.chain_id), nonce: tx.nonce, access_list: tx.access_list.clone(), blob_hashes: Default::default(), max_fee_per_blob_gas: Default::default(), authorization_list: Default::default(), tx_type: 1, caller: sender, }, tx_hash, rng_mode, }, SeismicTypedTransaction::Eip1559(tx) => SeismicTransaction::<TxEnv> { base: TxEnv { gas_limit: tx.gas_limit, gas_price: tx.max_fee_per_gas, gas_priority_fee: Some(tx.max_priority_fee_per_gas), kind: tx.to, value: tx.value, data: tx.input.clone(), chain_id: Some(tx.chain_id), nonce: tx.nonce, access_list: tx.access_list.clone(), blob_hashes: Default::default(), max_fee_per_blob_gas: Default::default(), authorization_list: Default::default(), tx_type: 2, caller: sender, }, tx_hash, rng_mode, }, SeismicTypedTransaction::Eip4844(tx) => match tx { TxEip4844Variant::TxEip4844(tx) => SeismicTransaction::<TxEnv> { base: TxEnv { gas_limit: tx.gas_limit, gas_price: tx.max_fee_per_gas, gas_priority_fee: Some(tx.max_priority_fee_per_gas), kind: TxKind::Call(tx.to), value: tx.value, data: tx.input.clone(), chain_id: Some(tx.chain_id), nonce: tx.nonce, access_list: tx.access_list.clone(), blob_hashes: Default::default(), max_fee_per_blob_gas: Default::default(), authorization_list: Default::default(), tx_type: 4, caller: sender, }, tx_hash, rng_mode, }, TxEip4844Variant::TxEip4844WithSidecar(tx) => SeismicTransaction::<TxEnv> { base: TxEnv { gas_limit: tx.tx.gas_limit, gas_price: tx.tx.max_fee_per_gas, gas_priority_fee: Some(tx.tx.max_priority_fee_per_gas), kind: TxKind::Call(tx.tx.to), value: tx.tx.value, data: tx.tx.input.clone(), chain_id: Some(tx.tx.chain_id), nonce: tx.tx.nonce, access_list: tx.tx.access_list.clone(), blob_hashes: Default::default(), max_fee_per_blob_gas: Default::default(), authorization_list: Default::default(), tx_type: 4, caller: sender, }, tx_hash, rng_mode, }, }, SeismicTypedTransaction::Eip7702(tx) => SeismicTransaction::<TxEnv> { base: TxEnv { gas_limit: tx.gas_limit, gas_price: tx.max_fee_per_gas, gas_priority_fee: Some(tx.max_priority_fee_per_gas), kind: TxKind::Call(tx.to), value: tx.value, data: tx.input.clone(), chain_id: Some(tx.chain_id), nonce: tx.nonce, access_list: tx.access_list.clone(), blob_hashes: Default::default(), max_fee_per_blob_gas: Default::default(), authorization_list: tx .authorization_list .iter() .map(|auth| Either::Left(auth.clone())) .collect(), tx_type: 4, caller: sender, }, tx_hash, rng_mode, }, SeismicTypedTransaction::Seismic(tx) => SeismicTransaction::<TxEnv> { base: TxEnv { gas_limit: tx.gas_limit, gas_price: tx.gas_price, gas_priority_fee: None, kind: tx.to, value: tx.value, data: tx.input.clone(), chain_id: Some(tx.chain_id), nonce: tx.nonce, access_list: Default::default(), blob_hashes: Default::default(), max_fee_per_blob_gas: Default::default(), authorization_list: Default::default(), tx_type: TxSeismic::TX_TYPE, caller: sender, }, tx_hash, rng_mode, }, }; tracing::debug!("from_recovered_tx: tx: {:?}", tx); tx } } impl FromTxWithEncoded<SeismicTransactionSigned> for SeismicTransaction<TxEnv> { fn from_encoded_tx(tx: &SeismicTransactionSigned, sender: Address, _encoded: Bytes) -> Self { let tx_env = SeismicTransaction::<TxEnv>::from_recovered_tx(tx, sender); Self { base: tx_env.base, tx_hash: tx_env.tx_hash, rng_mode: RngMode::Execution } } } impl InMemorySize for SeismicTransactionSigned { #[inline] fn size(&self) -> usize { mem::size_of::<TxHash>() + self.transaction.size() + mem::size_of::<Signature>() } } impl alloy_rlp::Encodable for SeismicTransactionSigned { fn encode(&self, out: &mut dyn alloy_rlp::bytes::BufMut) { self.network_encode(out); } fn length(&self) -> usize { let mut payload_length = self.encode_2718_len(); if !self.is_legacy() { payload_length += Header { list: false, payload_length }.length(); } payload_length } } impl alloy_rlp::Decodable for SeismicTransactionSigned { fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> { Self::network_decode(buf).map_err(Into::into) } } impl Encodable2718 for SeismicTransactionSigned { fn type_flag(&self) -> Option<u8> { if Typed2718::is_legacy(self) { None } else { Some(self.ty()) } } fn encode_2718_len(&self) -> usize { match &self.transaction { SeismicTypedTransaction::Legacy(legacy_tx) => { legacy_tx.eip2718_encoded_length(&self.signature) } SeismicTypedTransaction::Eip2930(access_list_tx) => { access_list_tx.eip2718_encoded_length(&self.signature) } SeismicTypedTransaction::Eip1559(dynamic_fee_tx) => { dynamic_fee_tx.eip2718_encoded_length(&self.signature) } SeismicTypedTransaction::Eip4844(blob_tx) => { blob_tx.eip2718_encoded_length(&self.signature) } SeismicTypedTransaction::Eip7702(set_code_tx) => { set_code_tx.eip2718_encoded_length(&self.signature) } SeismicTypedTransaction::Seismic(seismic_tx) => { seismic_tx.eip2718_encoded_length(&self.signature) } } } fn encode_2718(&self, out: &mut dyn alloy_rlp::BufMut) { let Self { transaction, signature, .. } = self; match &transaction { SeismicTypedTransaction::Legacy(legacy_tx) => { // do nothing w/ with_header legacy_tx.eip2718_encode(signature, out) } SeismicTypedTransaction::Eip2930(access_list_tx) => { access_list_tx.eip2718_encode(signature, out) } SeismicTypedTransaction::Eip1559(dynamic_fee_tx) => { dynamic_fee_tx.eip2718_encode(signature, out) } SeismicTypedTransaction::Eip4844(blob_tx) => blob_tx.eip2718_encode(signature, out), SeismicTypedTransaction::Eip7702(set_code_tx) => { set_code_tx.eip2718_encode(signature, out) } SeismicTypedTransaction::Seismic(seismic_tx) => { seismic_tx.eip2718_encode(signature, out) } } } } impl Decodable2718 for SeismicTransactionSigned { fn typed_decode(ty: u8, buf: &mut &[u8]) -> Eip2718Result<Self> { match ty.try_into().map_err(|_| Eip2718Error::UnexpectedType(ty))? { seismic_alloy_consensus::SeismicTxType::Legacy => Err(Eip2718Error::UnexpectedType(0)), seismic_alloy_consensus::SeismicTxType::Eip2930 => { let (tx, signature, hash) = TxEip2930::rlp_decode_signed(buf)?.into_parts(); let signed_tx = Self::new_unhashed(SeismicTypedTransaction::Eip2930(tx), signature); signed_tx.hash.get_or_init(|| hash); Ok(signed_tx) } seismic_alloy_consensus::SeismicTxType::Eip1559 => { let (tx, signature, hash) = TxEip1559::rlp_decode_signed(buf)?.into_parts(); let signed_tx = Self::new_unhashed(SeismicTypedTransaction::Eip1559(tx), signature); signed_tx.hash.get_or_init(|| hash); Ok(signed_tx) } seismic_alloy_consensus::SeismicTxType::Eip4844 => { let (tx, signature, hash) = TxEip4844::rlp_decode_signed(buf)?.into_parts(); let signed_tx = Self::new_unhashed( SeismicTypedTransaction::Eip4844(TxEip4844Variant::TxEip4844(tx)), signature, ); signed_tx.hash.get_or_init(|| hash); Ok(signed_tx) } seismic_alloy_consensus::SeismicTxType::Eip7702 => { let (tx, signature, hash) = TxEip7702::rlp_decode_signed(buf)?.into_parts(); let signed_tx = Self::new_unhashed(SeismicTypedTransaction::Eip7702(tx), signature); signed_tx.hash.get_or_init(|| hash); Ok(signed_tx) } seismic_alloy_consensus::SeismicTxType::Seismic => { let (tx, signature, hash) = TxSeismic::rlp_decode_signed(buf)?.into_parts(); let signed_tx = Self::new_unhashed(SeismicTypedTransaction::Seismic(tx), signature); signed_tx.hash.get_or_init(|| hash); Ok(signed_tx) } } } fn fallback_decode(buf: &mut &[u8]) -> Eip2718Result<Self> { let (transaction, signature) = TxLegacy::rlp_decode_with_signature(buf)?; let signed_tx = Self::new_unhashed(SeismicTypedTransaction::Legacy(transaction), signature); Ok(signed_tx) } } impl Transaction for SeismicTransactionSigned { fn chain_id(&self) -> Option<u64> { self.deref().chain_id() } fn nonce(&self) -> u64 { self.deref().nonce() } fn gas_limit(&self) -> u64 { self.deref().gas_limit() } fn gas_price(&self) -> Option<u128> { self.deref().gas_price() } fn max_fee_per_gas(&self) -> u128 { self.deref().max_fee_per_gas() } fn max_priority_fee_per_gas(&self) -> Option<u128> { self.deref().max_priority_fee_per_gas() } fn max_fee_per_blob_gas(&self) -> Option<u128> { self.deref().max_fee_per_blob_gas() } fn priority_fee_or_price(&self) -> u128 { self.deref().priority_fee_or_price() } fn effective_gas_price(&self, base_fee: Option<u64>) -> u128 { self.deref().effective_gas_price(base_fee) } fn effective_tip_per_gas(&self, base_fee: u64) -> Option<u128> { self.deref().effective_tip_per_gas(base_fee) } fn is_dynamic_fee(&self) -> bool { self.deref().is_dynamic_fee() } fn kind(&self) -> TxKind { self.deref().kind() } fn is_create(&self) -> bool { self.deref().is_create() } fn value(&self) -> Uint<256, 4> { self.deref().value() } fn input(&self) -> &Bytes { self.deref().input() } fn access_list(&self) -> Option<&AccessList> { self.deref().access_list() } fn blob_versioned_hashes(&self) -> Option<&[B256]> { self.deref().blob_versioned_hashes() } fn authorization_list(&self) -> Option<&[SignedAuthorization]> { self.deref().authorization_list() } } impl InputDecryptionElements for SeismicTransactionSigned { fn get_decryption_elements(&self) -> Result<TxSeismicElements, InputDecryptionElementsError> { self.transaction.get_decryption_elements() } fn get_input(&self) -> Bytes { self.transaction.get_input() } fn set_input(&mut self, input: Bytes) -> Result<(), InputDecryptionElementsError> { self.transaction.set_input(input) } } impl Typed2718 for SeismicTransactionSigned { fn ty(&self) -> u8 { self.deref().ty() } } impl PartialEq for SeismicTransactionSigned { fn eq(&self, other: &Self) -> bool { self.signature == other.signature && self.transaction == other.transaction && self.tx_hash() == other.tx_hash() } } impl Hash for SeismicTransactionSigned { fn hash<H: Hasher>(&self, state: &mut H) { self.signature.hash(state); self.transaction.hash(state); } } #[cfg(feature = "reth-codec")] impl reth_codecs::Compact for SeismicTransactionSigned { fn to_compact<B>(&self, buf: &mut B) -> usize where B: bytes::BufMut + AsMut<[u8]>, { let start = buf.as_mut().len(); // Placeholder for bitflags. // The first byte uses 4 bits as flags: IsCompressed[1bit], TxType[2bits], Signature[1bit] buf.put_u8(0); let sig_bit = self.signature.to_compact(buf) as u8; let zstd_bit = self.transaction.input().len() >= 32; let tx_bits = if zstd_bit { let mut tmp = Vec::with_capacity(256); if cfg!(feature = "std") { reth_zstd_compressors::TRANSACTION_COMPRESSOR.with(|compressor| { let mut compressor = compressor.borrow_mut(); let tx_bits = self.transaction.to_compact(&mut tmp); buf.put_slice(&compressor.compress(&tmp).expect("Failed to compress")); tx_bits as u8 }) } else { let mut compressor = reth_zstd_compressors::create_tx_compressor(); let tx_bits = self.transaction.to_compact(&mut tmp); buf.put_slice(&compressor.compress(&tmp).expect("Failed to compress")); tx_bits as u8 } } else { self.transaction.to_compact(buf) as u8 }; // Replace bitflags with the actual values buf.as_mut()[start] = sig_bit | (tx_bits << 1) | ((zstd_bit as u8) << 3); buf.as_mut().len() - start } fn from_compact(mut buf: &[u8], _len: usize) -> (Self, &[u8]) { use bytes::Buf; // The first byte uses 4 bits as flags: IsCompressed[1], TxType[2], Signature[1] let bitflags = buf.get_u8() as usize; let sig_bit = bitflags & 1; let (signature, buf) = Signature::from_compact(buf, sig_bit); let zstd_bit = bitflags >> 3; let (transaction, buf) = if zstd_bit != 0 { if cfg!(feature = "std") { reth_zstd_compressors::TRANSACTION_DECOMPRESSOR.with(|decompressor| { let mut decompressor = decompressor.borrow_mut(); // TODO: enforce that zstd is only present at a "top" level type let transaction_type = (bitflags & 0b110) >> 1; let (transaction, _) = SeismicTypedTransaction::from_compact( decompressor.decompress(buf), transaction_type, ); (transaction, buf) }) } else { let mut decompressor = reth_zstd_compressors::create_tx_decompressor(); let transaction_type = (bitflags & 0b110) >> 1; let (transaction, _) = SeismicTypedTransaction::from_compact( decompressor.decompress(buf), transaction_type, ); (transaction, buf) } } else { let transaction_type = bitflags >> 1; SeismicTypedTransaction::from_compact(buf, transaction_type) }; (Self { signature, transaction, hash: Default::default() }, buf) } } #[cfg(any(test, feature = "arbitrary"))] impl<'a> arbitrary::Arbitrary<'a> for SeismicTransactionSigned { fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> { #[allow(unused_mut)] let mut transaction = SeismicTypedTransaction::arbitrary(u)?; let secp = secp256k1::Secp256k1::new(); let key_pair = secp256k1::Keypair::new(&secp, &mut rand_08::thread_rng()); let signature = reth_primitives_traits::crypto::secp256k1::sign_message( B256::from_slice(&key_pair.secret_bytes()[..]), signature_hash(&transaction), ) .unwrap(); Ok(Self::new_unhashed(transaction, signature)) } } /// Calculates the signing hash for the transaction. fn signature_hash(tx: &SeismicTypedTransaction) -> B256 { match tx { SeismicTypedTransaction::Legacy(tx) => tx.signature_hash(), SeismicTypedTransaction::Eip2930(tx) => tx.signature_hash(), SeismicTypedTransaction::Eip1559(tx) => tx.signature_hash(), SeismicTypedTransaction::Eip4844(tx) => match tx { TxEip4844Variant::TxEip4844(tx) => tx.signature_hash(), TxEip4844Variant::TxEip4844WithSidecar(tx) => tx.tx.signature_hash(), }, SeismicTypedTransaction::Eip7702(tx) => tx.signature_hash(), SeismicTypedTransaction::Seismic(tx) => tx.signature_hash(), } } /// Bincode-compatible transaction type serde implementations. #[cfg(feature = "serde-bincode-compat")] pub mod serde_bincode_compat { use alloy_consensus::transaction::serde_bincode_compat::{ TxEip1559, TxEip2930, TxEip7702, TxLegacy, }; use alloy_primitives::{Signature, TxHash}; use reth_primitives_traits::{serde_bincode_compat::SerdeBincodeCompat, SignedTransaction}; use seismic_alloy_consensus::serde_bincode_compat::TxSeismic; use serde::{Deserialize, Serialize}; /// Bincode-compatible [`super::SeismicTypedTransaction`] serde implementation. #[derive(Debug, Serialize, Deserialize)] #[allow(missing_docs)] enum SeismicTypedTransaction<'a> { Legacy(TxLegacy<'a>), Eip2930(TxEip2930<'a>), Eip1559(TxEip1559<'a>), Eip7702(TxEip7702<'a>), Seismic(seismic_alloy_consensus::serde_bincode_compat::TxSeismic<'a>), } impl<'a> From<&'a super::SeismicTypedTransaction> for SeismicTypedTransaction<'a> { fn from(value: &'a super::SeismicTypedTransaction) -> Self { match value { super::SeismicTypedTransaction::Legacy(tx) => Self::Legacy(TxLegacy::from(tx)), super::SeismicTypedTransaction::Eip2930(tx) => Self::Eip2930(TxEip2930::from(tx)), super::SeismicTypedTransaction::Eip1559(tx) => Self::Eip1559(TxEip1559::from(tx)), super::SeismicTypedTransaction::Eip4844(_tx) => { todo!("seismic upstream merge:Eip4844 not supported") } super::SeismicTypedTransaction::Eip7702(tx) => Self::Eip7702(TxEip7702::from(tx)), super::SeismicTypedTransaction::Seismic(tx) => Self::Seismic(TxSeismic::from(tx)), } } } impl<'a> From<SeismicTypedTransaction<'a>> for super::SeismicTypedTransaction { fn from(value: SeismicTypedTransaction<'a>) -> Self { match value { SeismicTypedTransaction::Legacy(tx) => Self::Legacy(tx.into()), SeismicTypedTransaction::Eip2930(tx) => Self::Eip2930(tx.into()), SeismicTypedTransaction::Eip1559(tx) => Self::Eip1559(tx.into()), SeismicTypedTransaction::Eip7702(tx) => Self::Eip7702(tx.into()), SeismicTypedTransaction::Seismic(tx) => Self::Seismic(tx.into()), } } } /// Bincode-compatible [`super::SeismicTransactionSigned`] serde implementation. #[derive(Debug, Serialize, Deserialize)] pub struct SeismicTransactionSigned<'a> { hash: TxHash, signature: Signature, transaction: SeismicTypedTransaction<'a>, } impl<'a> From<&'a super::SeismicTransactionSigned> for SeismicTransactionSigned<'a> { fn from(value: &'a super::SeismicTransactionSigned) -> Self { Self { hash: *value.tx_hash(), signature: value.signature, transaction: SeismicTypedTransaction::from(&value.transaction), } } } impl<'a> From<SeismicTransactionSigned<'a>> for super::SeismicTransactionSigned { fn from(value: SeismicTransactionSigned<'a>) -> Self { Self { hash: value.hash.into(), signature: value.signature, transaction: value.transaction.into(), } } } impl SerdeBincodeCompat for super::SeismicTransactionSigned { type BincodeRepr<'a> = SeismicTransactionSigned<'a>; fn as_repr(&self) -> Self::BincodeRepr<'_> { self.into() } fn from_repr(repr: Self::BincodeRepr<'_>) -> Self { repr.into() } } } #[cfg(test)] mod tests { use core::str::FromStr; use crate::test_utils::{get_signed_seismic_tx, get_signing_private_key}; use super::*; use alloy_primitives::{aliases::U96, U256}; use proptest::proptest; use proptest_arbitrary_interop::arb; use reth_codecs::Compact; use secp256k1::PublicKey; use seismic_alloy_consensus::SeismicTxType; use seismic_revm::transaction::abstraction::SeismicTxTr; #[test] fn recover_signer_test() { let signed_tx = get_signed_seismic_tx(); let recovered_signer = signed_tx.recover_signer().expect("Failed to recover signer"); let expected_signer = Address::from_private_key(&get_signing_private_key()); assert_eq!(recovered_signer, expected_signer); } proptest! { #[test] fn test_roundtrip_2718(reth_tx in arb::<SeismicTransactionSigned>()) { println!("{}", reth_tx.transaction().tx_type()); if reth_tx.transaction().tx_type() == SeismicTxType::Eip4844 { // TODO: make this work for eip4844 in seismic-alloy return Ok(()) } let mut signed_tx_bytes = Vec::<u8>::new(); reth_tx.encode_2718(&mut signed_tx_bytes); let recovered_tx = SeismicTransactionSigned::decode_2718(&mut &signed_tx_bytes[..]) .expect("Failed to decode transaction"); assert_eq!(recovered_tx, reth_tx); } #[test] fn test_roundtrip_compact_encode_envelope(reth_tx in arb::<SeismicTransactionSigned>()) { println!("{}", reth_tx.transaction().tx_type()); if reth_tx.transaction().tx_type() == SeismicTxType::Eip4844 { // TODO: make this work for eip4844 in seismic-alloy return Ok(()) } let mut expected_buf = Vec::<u8>::new(); let expected_len = reth_tx.to_compact(&mut expected_buf); let mut actual_but = Vec::<u8>::new(); let alloy_tx = SeismicTxEnvelope::from(reth_tx); let actual_len = alloy_tx.to_compact(&mut actual_but); assert_eq!(actual_but, expected_buf); assert_eq!(actual_len, expected_len); } #[test] fn test_roundtrip_compact_decode_envelope(reth_tx in arb::<SeismicTransactionSigned>()) { println!("{}", reth_tx.transaction().tx_type()); if reth_tx.transaction().tx_type() == SeismicTxType::Eip4844 { // TODO: make this work for eip4844 in seismic-alloy
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
true
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/seismic/primitives/src/transaction/tx_type.rs
crates/seismic/primitives/src/transaction/tx_type.rs
//! Seismic transaction type. pub use seismic_alloy_consensus::SeismicTxType; #[cfg(test)] mod tests { use super::*; use alloy_consensus::constants::EIP7702_TX_TYPE_ID; use reth_codecs::{txtype::*, Compact}; use rstest::rstest; #[rstest] #[case(SeismicTxType::Legacy, COMPACT_IDENTIFIER_LEGACY, vec![])] #[case(SeismicTxType::Eip2930, COMPACT_IDENTIFIER_EIP2930, vec![])] #[case(SeismicTxType::Eip1559, COMPACT_IDENTIFIER_EIP1559, vec![])] #[case(SeismicTxType::Eip7702, COMPACT_EXTENDED_IDENTIFIER_FLAG, vec![EIP7702_TX_TYPE_ID])] #[case(SeismicTxType::Seismic, COMPACT_EXTENDED_IDENTIFIER_FLAG, vec![74 as u8])] fn test_txtype_to_compact( #[case] tx_type: SeismicTxType, #[case] expected_identifier: usize, #[case] expected_buf: Vec<u8>, ) { let mut buf = vec![]; let identifier = tx_type.to_compact(&mut buf); assert_eq!( identifier, expected_identifier, "Unexpected identifier for SeismicTxType {tx_type:?}", ); assert_eq!(buf, expected_buf, "Unexpected buffer for SeismicTxType {tx_type:?}",); } #[rstest] #[case(SeismicTxType::Legacy, COMPACT_IDENTIFIER_LEGACY, vec![])] #[case(SeismicTxType::Eip2930, COMPACT_IDENTIFIER_EIP2930, vec![])] #[case(SeismicTxType::Eip1559, COMPACT_IDENTIFIER_EIP1559, vec![])] #[case(SeismicTxType::Eip7702, COMPACT_EXTENDED_IDENTIFIER_FLAG, vec![EIP7702_TX_TYPE_ID])] #[case(SeismicTxType::Seismic, COMPACT_EXTENDED_IDENTIFIER_FLAG, vec![74 as u8])] fn test_txtype_from_compact( #[case] expected_type: SeismicTxType, #[case] identifier: usize, #[case] buf: Vec<u8>, ) { let (actual_type, remaining_buf) = SeismicTxType::from_compact(&buf, identifier); assert_eq!(actual_type, expected_type, "Unexpected TxType for identifier {identifier}"); assert!(remaining_buf.is_empty(), "Buffer not fully consumed for identifier {identifier}"); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/seismic/cli/src/lib.rs
crates/seismic/cli/src/lib.rs
//! Seismic-Reth CLI implementation. #![doc( html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png", html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256", issue_tracker_base_url = "https://github.com/SeismicSystems/seismic-reth/issues/" )] #![cfg_attr(not(test), warn(unused_crate_dependencies))] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] /// Seismic chain specification parser. pub mod chainspec; use reth_chainspec::ChainSpec; use reth_cli_commands::{launcher::FnLauncher, node}; use reth_seismic_node::args::EnclaveArgs; use std::{ffi::OsString, fmt, sync::Arc}; use chainspec::SeismicChainSpecParser; use clap::{value_parser, Parser, Subcommand}; use futures_util::Future; use reth_chainspec::EthChainSpec; use reth_cli::chainspec::ChainSpecParser; use reth_cli_runner::CliRunner; use reth_db::DatabaseEnv; use reth_node_builder::{NodeBuilder, WithLaunchContext}; use reth_node_core::{args::LogArgs, version::version_metadata}; use reth_tracing::FileWorkerGuard; use tracing::info; // This allows us to manually enable node metrics features, required for proper jemalloc metric // reporting use reth_node_metrics as _; use reth_node_metrics::recorder::install_prometheus_recorder; /// The main seismic-reth cli interface. /// /// This is the entrypoint to the executable. #[derive(Debug, Parser)] #[command(author, version =version_metadata().short_version.as_ref(), long_version = version_metadata().long_version.as_ref(), about = "Reth", long_about = None)] pub struct Cli< Spec: ChainSpecParser = SeismicChainSpecParser, Ext: clap::Args + fmt::Debug = EnclaveArgs, > { /// The command to run #[command(subcommand)] pub command: Commands<Spec, Ext>, /// The chain this node is running. /// /// Possible values are either a built-in chain or the path to a chain specification file. #[arg( long, value_name = "CHAIN_OR_PATH", long_help = Spec::help_message(), default_value = Spec::SUPPORTED_CHAINS[0], value_parser = Spec::parser(), global = true, )] pub chain: Arc<Spec::ChainSpec>, /// Add a new instance of a node. /// /// Configures the ports of the node to avoid conflicts with the defaults. /// This is useful for running multiple nodes on the same machine. /// /// Max number of instances is 200. It is chosen in a way so that it's not possible to have /// port numbers that conflict with each other. /// /// Changes to the following port numbers: /// - `DISCOVERY_PORT`: default + `instance` - 1 /// - `AUTH_PORT`: default + `instance` * 100 - 100 /// - `HTTP_RPC_PORT`: default - `instance` + 1 /// - `WS_RPC_PORT`: default + `instance` * 2 - 2 #[arg(long, value_name = "INSTANCE", global = true, default_value_t = 1, value_parser = value_parser!(u16).range(..=200))] pub instance: u16, /// The logging configuration for the CLI. #[command(flatten)] pub logs: LogArgs, } impl Cli { /// Parsers only the default CLI arguments pub fn parse_args() -> Self { Self::parse() } /// Parsers only the default CLI arguments from the given iterator pub fn try_parse_args_from<I, T>(itr: I) -> Result<Self, clap::error::Error> where I: IntoIterator<Item = T>, T: Into<OsString> + Clone, { Self::try_parse_from(itr) } } impl<C, Ext> Cli<C, Ext> where C: ChainSpecParser<ChainSpec = ChainSpec>, Ext: clap::Args + fmt::Debug, { /// Execute the configured cli command. /// /// This accepts a closure that is used to launch the node via the /// [`NodeCommand`](reth_cli_commands::node::NodeCommand). pub fn run<L, Fut>(self, launcher: L) -> eyre::Result<()> where L: FnOnce(WithLaunchContext<NodeBuilder<Arc<DatabaseEnv>, C::ChainSpec>>, Ext) -> Fut, Fut: Future<Output = eyre::Result<()>>, { self.with_runner(CliRunner::try_default_runtime()?, launcher) } /// Execute the configured cli command with the provided [`CliRunner`]. pub fn with_runner<L, Fut>(mut self, runner: CliRunner, launcher: L) -> eyre::Result<()> where L: FnOnce(WithLaunchContext<NodeBuilder<Arc<DatabaseEnv>, C::ChainSpec>>, Ext) -> Fut, Fut: Future<Output = eyre::Result<()>>, { // add network name to logs dir self.logs.log_file_directory = self.logs.log_file_directory.join(self.chain.chain().to_string()); let _guard = self.init_tracing()?; info!(target: "reth::cli", "Initialized tracing, debug log directory: {}", self.logs.log_file_directory); // Install the prometheus recorder to be sure to record all metrics let _ = install_prometheus_recorder(); match self.command { Commands::Node(command) => runner.run_command_until_exit(|ctx| { command.execute( ctx, FnLauncher::new::<C, Ext>(async move |builder, ext| { launcher(builder, ext).await }), ) }), } } /// Initializes tracing with the configured options. /// /// If file logging is enabled, this function returns a guard that must be kept alive to ensure /// that all logs are flushed to disk. pub fn init_tracing(&self) -> eyre::Result<Option<FileWorkerGuard>> { let guard = self.logs.init_tracing()?; Ok(guard) } } /// Commands to be executed #[derive(Debug, Subcommand)] #[expect(clippy::large_enum_variant)] pub enum Commands<C: ChainSpecParser, Ext: clap::Args + fmt::Debug> { /// Start the node #[command(name = "node")] Node(Box<node::NodeCommand<C, Ext>>), } #[cfg(test)] mod test { use crate::chainspec::SeismicChainSpecParser; use clap::Parser; use reth_cli_commands::{node::NoArgs, NodeCommand}; use reth_seismic_chainspec::{SEISMIC_DEV, SEISMIC_DEV_OLD}; #[test] fn parse_dev() { let cmd = NodeCommand::<SeismicChainSpecParser, NoArgs>::parse_from(["seismic-reth", "--dev"]); let chain = SEISMIC_DEV.clone(); assert_eq!(cmd.chain.chain, chain.chain); assert_eq!(cmd.chain.genesis_hash(), chain.genesis_hash()); assert_eq!( cmd.chain.paris_block_and_final_difficulty, chain.paris_block_and_final_difficulty ); assert_eq!(cmd.chain.hardforks, chain.hardforks); assert!(cmd.rpc.http); assert!(cmd.network.discovery.disable_discovery); assert!(cmd.dev.dev); } #[test] fn parse_dev_old() { // TODO: remove this once we launch devnet with consensus let cmd = NodeCommand::<SeismicChainSpecParser, NoArgs>::parse_from([ "seismic-reth", "--chain", "dev-old", "--http", "-d", ]); let chain = SEISMIC_DEV_OLD.clone(); assert_eq!(cmd.chain.chain, chain.chain); assert_eq!(cmd.chain.genesis_hash(), chain.genesis_hash()); assert_eq!( cmd.chain.paris_block_and_final_difficulty, chain.paris_block_and_final_difficulty ); assert_eq!(cmd.chain.hardforks, chain.hardforks); assert!(cmd.rpc.http); assert!(cmd.network.discovery.disable_discovery); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/seismic/cli/src/chainspec.rs
crates/seismic/cli/src/chainspec.rs
use reth_chainspec::ChainSpec; use reth_cli::chainspec::{parse_genesis, ChainSpecParser}; use reth_seismic_chainspec::{SEISMIC_DEV, SEISMIC_DEV_OLD, SEISMIC_MAINNET}; use std::sync::Arc; /// Optimism chain specification parser. #[derive(Debug, Clone, Default)] #[non_exhaustive] pub struct SeismicChainSpecParser; impl ChainSpecParser for SeismicChainSpecParser { type ChainSpec = ChainSpec; const SUPPORTED_CHAINS: &'static [&'static str] = &["dev", "mainnet", "dev-old"]; fn parse(s: &str) -> eyre::Result<Arc<Self::ChainSpec>> { chain_value_parser(s) } } /// Clap value parser for [`ChainSpec`]s. /// /// The value parser matches either a known chain, the path /// to a json file, or a json formatted string in-memory. The json needs to be a Genesis struct. pub fn chain_value_parser(s: &str) -> eyre::Result<Arc<ChainSpec>, eyre::Error> { Ok(match s { "dev" => SEISMIC_DEV.clone(), "mainnet" => SEISMIC_MAINNET.clone(), "dev-old" => SEISMIC_DEV_OLD.clone(), _ => Arc::new(parse_genesis(s)?.into()), }) } #[cfg(test)] mod tests { use super::*; #[test] fn parse_known_chain_spec() { for &chain in SeismicChainSpecParser::SUPPORTED_CHAINS { assert!(<SeismicChainSpecParser as ChainSpecParser>::parse(chain).is_ok()); } } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/seismic/chainspec/src/lib.rs
crates/seismic/chainspec/src/lib.rs
//! Seismic-Reth chain specs. #![doc( html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png", html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256", issue_tracker_base_url = "https://github.com/SeismicSystems/seismic-reth/issues/" )] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #![cfg_attr(not(feature = "std"), no_std)] use std::sync::Arc; use alloy_chains::Chain; use alloy_consensus::constants::DEV_GENESIS_HASH; use alloy_primitives::{b256, B256, U256}; use reth_chainspec::{make_genesis_header, ChainSpec, DEV_HARDFORKS}; use reth_primitives_traits::{sync::LazyLock, SealedHeader}; use reth_seismic_forks::{SEISMIC_DEV_HARDFORKS, SEISMIC_MAINNET_HARDFORKS}; use seismic_alloy_genesis::Genesis; /// Genesis hash for the Seismic mainnet /// Calculated by rlp encoding the genesis header and hashing it pub const SEISMIC_MAINNET_GENESIS_HASH: B256 = b256!("0xd548d4a126d72e43d893b3826c07ad24bddbaeee267489baff2f73fff2ac0976"); /// Genesis hash for the Seismic devnet /// Calculated by rlp encoding the genesis header and hashing it /// Currently matches the mainnet genesis hash because they have matching hardforks pub const SEISMIC_DEV_GENESIS_HASH: B256 = b256!("0xdea362cf26069ee018e8a37b514c1e64d9e2d07f833728c86e19e88678c09b98"); /// Seismic devnet specification pub static SEISMIC_DEV: LazyLock<Arc<ChainSpec>> = LazyLock::new(|| { let mut genesis: Genesis = serde_json::from_str(include_str!("../res/genesis/dev.json")) .expect("Can't deserialize Dev testnet genesis json"); // Genesis JSON timestamps are in seconds, but when timestamp-in-seconds feature is disabled, // we store timestamps internally as milliseconds #[cfg(not(feature = "timestamp-in-seconds"))] { genesis.timestamp *= 1000; } let hardforks = SEISMIC_DEV_HARDFORKS.clone(); ChainSpec { chain: Chain::from_id(5124), genesis_header: SealedHeader::new( make_genesis_header(&genesis, &hardforks), SEISMIC_DEV_GENESIS_HASH, ), genesis, paris_block_and_final_difficulty: Some((0, U256::from(0))), hardforks: DEV_HARDFORKS.clone(), ..Default::default() } .into() }); // TODO: remove this once we launch devnet with consensus /// Seismic old devnet specification pub static SEISMIC_DEV_OLD: LazyLock<Arc<ChainSpec>> = LazyLock::new(|| { let mut genesis: Genesis = serde_json::from_str(include_str!("../res/genesis/dev.json")) .expect("Can't deserialize Dev testnet genesis json"); // Genesis JSON timestamps are in seconds, but when timestamp-in-seconds feature is disabled, // we store timestamps internally as milliseconds #[cfg(not(feature = "timestamp-in-seconds"))] { genesis.timestamp *= 1000; } let hardforks = SEISMIC_DEV_HARDFORKS.clone(); ChainSpec { chain: Chain::from_id(5124), genesis_header: SealedHeader::new( make_genesis_header(&genesis, &hardforks), DEV_GENESIS_HASH, ), genesis, paris_block_and_final_difficulty: Some((0, U256::from(0))), hardforks: DEV_HARDFORKS.clone(), ..Default::default() } .into() }); /// Seismic Mainnet pub static SEISMIC_MAINNET: LazyLock<Arc<ChainSpec>> = LazyLock::new(|| { let mut genesis: Genesis = serde_json::from_str(include_str!("../res/genesis/mainnet.json")) .expect("Can't deserialize Mainnet genesis json"); // Genesis JSON timestamps are in seconds, but when timestamp-in-seconds feature is disabled, // we store timestamps internally as milliseconds #[cfg(not(feature = "timestamp-in-seconds"))] { genesis.timestamp *= 1000; } let hardforks = SEISMIC_MAINNET_HARDFORKS.clone(); let mut spec = ChainSpec { chain: Chain::from_id(5123), genesis_header: SealedHeader::new( make_genesis_header(&genesis, &hardforks), SEISMIC_MAINNET_GENESIS_HASH, ), genesis, paris_block_and_final_difficulty: Some((0, U256::from(0))), hardforks, ..Default::default() }; spec.genesis.config.dao_fork_support = true; spec.into() }); /// Returns `true` if the given chain is a seismic chain. pub fn is_chain_seismic(chain: &Chain) -> bool { chain.id() == SEISMIC_MAINNET.chain.id() || chain.id() == SEISMIC_DEV.chain.id() } #[cfg(test)] mod tests { use crate::*; use alloy_consensus::constants::MAINNET_GENESIS_HASH; use reth_chainspec::MAINNET; use reth_ethereum_forks::EthereumHardfork; use reth_seismic_forks::SeismicHardfork; #[test] fn seismic_mainnet_genesis() { let genesis = SEISMIC_MAINNET.genesis_header(); let eth_genesis = MAINNET.genesis_header(); assert_ne!( genesis.hash_slow(), eth_genesis.hash_slow(), "Seismic spec should not match eth genesis" ); assert_eq!( genesis.hash_slow(), SEISMIC_MAINNET_GENESIS_HASH, "Seismic spec has correct genesis hash" ); } // Test that the latest fork id is the latest seismic fork (mercury) #[test] fn latest_seismic_mainnet_fork_id_with_builder() { let seismic_mainnet = &SEISMIC_MAINNET; assert_eq!( seismic_mainnet.hardfork_fork_id(SeismicHardfork::Mercury).unwrap(), seismic_mainnet.latest_fork_id() ) } // Check display contains all eth mainnet hardforks and the seismic mercury fork #[test] fn display_hardforks() { let content = SEISMIC_MAINNET.display_hardforks().to_string(); let eth_mainnet = EthereumHardfork::mainnet(); for (eth_hf, _) in eth_mainnet { assert!(content.contains(eth_hf.name()), "missing hardfork {eth_hf}"); } assert!(content.contains("Mercury")); } #[test] fn genesis_header_hash() { // Confirm how eth mainnet genesis header hash is calculated let expected = MAINNET_GENESIS_HASH; let genesis = serde_json::from_str(include_str!("../../../chainspec/res/genesis/mainnet.json")) .expect("Can't deserialize Mainnet genesis json"); let hardforks = EthereumHardfork::mainnet().into(); let genesis_header = make_genesis_header(&genesis, &hardforks); let actual_hash = genesis_header.hash_slow(); assert_eq!(actual_hash, expected); // Confirm seismic mainnet genesis header hash is calculated correctly let expected = SEISMIC_MAINNET_GENESIS_HASH; let genesis = serde_json::from_str(include_str!("../res/genesis/mainnet.json")) // note: same as Ethereum, needs to be updated before launch .expect("Can't deserialize Seismic Mainnet genesis json"); let hardforks = SEISMIC_MAINNET_HARDFORKS.clone(); let genesis_header = make_genesis_header(&genesis, &hardforks); let actual_hash = genesis_header.hash_slow(); assert_eq!(actual_hash, expected); // Confirm seismic devnet genesis header hash is calculated correctly let expected = SEISMIC_DEV_GENESIS_HASH; let genesis = serde_json::from_str(include_str!("../res/genesis/dev.json")) .expect("Can't deserialize Seismic devnet genesis json"); let hardforks = SEISMIC_DEV_HARDFORKS.clone(); let genesis_header = make_genesis_header(&genesis, &hardforks); let actual_hash = genesis_header.hash_slow(); assert_eq!(actual_hash, expected); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/seismic/payload/src/builder.rs
crates/seismic/payload/src/builder.rs
//! A basic Seismic payload builder implementation. use alloy_consensus::{Transaction, Typed2718}; use alloy_primitives::U256; use reth_basic_payload_builder::{ is_better_payload, BuildArguments, BuildOutcome, MissingPayloadBehaviour, PayloadBuilder, PayloadConfig, }; use reth_chainspec::{ChainSpec, ChainSpecProvider, EthereumHardforks}; use reth_errors::{BlockExecutionError, BlockValidationError}; use reth_evm::{ execute::{BlockBuilder, BlockBuilderOutcome}, ConfigureEvm, Evm, NextBlockEnvAttributes, }; use reth_payload_builder::{BlobSidecars, EthBuiltPayload, EthPayloadBuilderAttributes}; use reth_payload_builder_primitives::PayloadBuilderError; use reth_payload_primitives::PayloadBuilderAttributes; use reth_primitives_traits::SignedTransaction; use reth_revm::{database::StateProviderDatabase, db::State}; use reth_seismic_evm::SeismicEvmConfig; use reth_seismic_primitives::{SeismicPrimitives, SeismicTransactionSigned}; use reth_storage_api::StateProviderFactory; use reth_transaction_pool::{ error::InvalidPoolTransactionError, BestTransactions, BestTransactionsAttributes, PoolTransaction, TransactionPool, ValidPoolTransaction, }; use revm::context_interface::Block as _; use std::sync::Arc; use tracing::{debug, trace, warn}; use reth_evm::execute::InternalBlockExecutionError; use reth_primitives_traits::transaction::error::InvalidTransactionError; type BestTransactionsIter<Pool> = Box< dyn BestTransactions<Item = Arc<ValidPoolTransaction<<Pool as TransactionPool>::Transaction>>>, >; use super::SeismicBuilderConfig; /// Seismic payload builder #[derive(Debug, Clone, PartialEq, Eq)] pub struct SeismicPayloadBuilder<Pool, Client, EvmConfig = SeismicEvmConfig> { /// Client providing access to node state. client: Client, /// Transaction pool. pool: Pool, /// The type responsible for creating the evm. evm_config: EvmConfig, /// Payload builder configuration. builder_config: SeismicBuilderConfig, } impl<Pool, Client, EvmConfig> SeismicPayloadBuilder<Pool, Client, EvmConfig> { /// [`SeismicPayloadBuilder`] constructor. pub const fn new( client: Client, pool: Pool, evm_config: EvmConfig, builder_config: SeismicBuilderConfig, ) -> Self { Self { client, pool, evm_config, builder_config } } } // Default implementation of [`PayloadBuilder`] for unit type impl<Pool, Client, EvmConfig> PayloadBuilder for SeismicPayloadBuilder<Pool, Client, EvmConfig> where EvmConfig: ConfigureEvm<Primitives = SeismicPrimitives, NextBlockEnvCtx = NextBlockEnvAttributes>, Client: StateProviderFactory + ChainSpecProvider<ChainSpec = ChainSpec> + Clone, Pool: TransactionPool<Transaction: PoolTransaction<Consensus = SeismicTransactionSigned>>, { type Attributes = EthPayloadBuilderAttributes; type BuiltPayload = EthBuiltPayload<SeismicPrimitives>; fn try_build( &self, args: BuildArguments<EthPayloadBuilderAttributes, Self::BuiltPayload>, ) -> Result<BuildOutcome<EthBuiltPayload<SeismicPrimitives>>, PayloadBuilderError> { default_seismic_payload( self.evm_config.clone(), self.client.clone(), self.pool.clone(), self.builder_config.clone(), args, |attributes| self.pool.best_transactions_with_attributes(attributes), ) } fn on_missing_payload( &self, _args: BuildArguments<Self::Attributes, Self::BuiltPayload>, ) -> MissingPayloadBehaviour<Self::BuiltPayload> { if self.builder_config.await_payload_on_missing { MissingPayloadBehaviour::AwaitInProgress } else { MissingPayloadBehaviour::RaceEmptyPayload } } fn build_empty_payload( &self, config: PayloadConfig<Self::Attributes>, ) -> Result<Self::BuiltPayload, PayloadBuilderError> { let args = BuildArguments::new(Default::default(), config, Default::default(), None); default_seismic_payload( self.evm_config.clone(), self.client.clone(), self.pool.clone(), self.builder_config.clone(), args, |attributes| self.pool.best_transactions_with_attributes(attributes), )? .into_payload() .ok_or_else(|| PayloadBuilderError::MissingPayload) } } /// Constructs an Seismic transaction payload using the best transactions from the pool. /// /// Given build arguments including an Seismic client, transaction pool, /// and configuration, this function creates a transaction payload. Returns /// a result indicating success with the payload or an error in case of failure. #[inline] pub fn default_seismic_payload<EvmConfig, Client, Pool, F>( evm_config: EvmConfig, client: Client, pool: Pool, builder_config: SeismicBuilderConfig, args: BuildArguments<EthPayloadBuilderAttributes, EthBuiltPayload<SeismicPrimitives>>, best_txs: F, ) -> Result<BuildOutcome<EthBuiltPayload<SeismicPrimitives>>, PayloadBuilderError> where EvmConfig: ConfigureEvm<Primitives = SeismicPrimitives, NextBlockEnvCtx = NextBlockEnvAttributes>, Client: StateProviderFactory + ChainSpecProvider<ChainSpec = ChainSpec>, Pool: TransactionPool<Transaction: PoolTransaction<Consensus = SeismicTransactionSigned>>, F: FnOnce(BestTransactionsAttributes) -> BestTransactionsIter<Pool>, { let BuildArguments { mut cached_reads, config, cancel, best_payload } = args; let PayloadConfig { parent_header, attributes } = config; let state_provider = client.state_by_block_hash(parent_header.hash())?; let state = StateProviderDatabase::new(&state_provider); let mut db = State::builder().with_database(cached_reads.as_db_mut(state)).with_bundle_update().build(); let mut builder = evm_config .builder_for_next_block( &mut db, &parent_header, NextBlockEnvAttributes { timestamp: attributes.timestamp(), suggested_fee_recipient: attributes.suggested_fee_recipient(), prev_randao: attributes.prev_randao(), gas_limit: builder_config.gas_limit(parent_header.gas_limit), parent_beacon_block_root: attributes.parent_beacon_block_root(), withdrawals: Some(attributes.withdrawals().clone()), }, ) .map_err(PayloadBuilderError::other)?; let chain_spec = client.chain_spec(); debug!(target: "payload_builder", id=%attributes.id, parent_header = ?parent_header.hash(), parent_number = parent_header.number, "building new payload"); let mut cumulative_gas_used = 0; let block_gas_limit: u64 = builder.evm_mut().block().gas_limit; let base_fee = builder.evm_mut().block().basefee; let mut best_txs = best_txs(BestTransactionsAttributes::new( base_fee, builder.evm_mut().block().blob_gasprice().map(|gasprice| gasprice as u64), )); let mut total_fees = U256::ZERO; builder.apply_pre_execution_changes().map_err(|err| { warn!(target: "payload_builder", %err, "failed to apply pre-execution changes"); PayloadBuilderError::Internal(err.into()) })?; while let Some(pool_tx) = best_txs.next() { // ensure we still have capacity for this transaction if cumulative_gas_used + pool_tx.gas_limit() > block_gas_limit { // we can't fit this transaction into the block, so we need to mark it as invalid // which also removes all dependent transaction from the iterator before we can // continue best_txs.mark_invalid( &pool_tx, InvalidPoolTransactionError::ExceedsGasLimit(pool_tx.gas_limit(), block_gas_limit), ); continue } // check if the job was cancelled, if so we can exit early if cancel.is_cancelled() { return Ok(BuildOutcome::Cancelled) } // convert tx to a signed transaction let tx = pool_tx.to_consensus(); debug!("default_seismic_payload: tx: {:?}", tx); let gas_used = match builder.execute_transaction(tx.clone()) { Ok(gas_used) => gas_used, Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { error, .. })) => { if error.is_nonce_too_low() { // if the nonce is too low, we can skip this transaction trace!(target: "payload_builder", %error, ?tx, "skipping nonce too low transaction"); } else { // if the transaction is invalid, we can skip it and all of its // descendants trace!(target: "payload_builder", %error, ?tx, "skipping invalid transaction and its descendants"); best_txs.mark_invalid( &pool_tx, InvalidPoolTransactionError::Consensus( InvalidTransactionError::TxTypeNotSupported, ), ); } continue } Err(BlockExecutionError::Internal( InternalBlockExecutionError::FailedToDecryptSeismicTx(error), )) => { trace!(target: "payload_builder", %error, ?tx, "skipping seismic tx with wrong encryption"); best_txs.mark_invalid( &pool_tx, InvalidPoolTransactionError::Consensus( InvalidTransactionError::FailedToDecryptSeismicTx, ), ); continue } // this is an error that we should treat as fatal for this attempt Err(err) => return Err(PayloadBuilderError::evm(err)), }; // update add to total fees let miner_fee = tx.effective_tip_per_gas(base_fee).expect("fee is always valid; execution succeeded"); total_fees += U256::from(miner_fee) * U256::from(gas_used); cumulative_gas_used += gas_used; } // check if we have a better block if !is_better_payload(best_payload.as_ref(), total_fees) { // Release db drop(builder); // can skip building the block return Ok(BuildOutcome::Aborted { fees: total_fees, cached_reads }) } let BlockBuilderOutcome { execution_result, block, .. } = builder.finish(&state_provider)?; let requests = chain_spec .is_prague_active_at_timestamp(attributes.timestamp_seconds()) .then_some(execution_result.requests); // initialize empty blob sidecars at first. If cancun is active then this will let mut blob_sidecars = Vec::new(); // only determine cancun fields when active if chain_spec.is_cancun_active_at_timestamp(attributes.timestamp_seconds()) { // grab the blob sidecars from the executed txs blob_sidecars = pool .get_all_blobs_exact( block .body() .transactions() .filter(|tx| tx.is_eip4844()) .map(|tx| *tx.tx_hash()) .collect(), ) .map_err(PayloadBuilderError::other)?; } let mut sidecars = BlobSidecars::Empty; blob_sidecars .into_iter() .map(Arc::unwrap_or_clone) .for_each(|s| sidecars.push_sidecar_variant(s)); let sealed_block = Arc::new(block.sealed_block().clone()); debug!(target: "payload_builder", id=%attributes.id, sealed_block_header = ?sealed_block.sealed_header(), "sealed built block"); let payload = EthBuiltPayload::<SeismicPrimitives>::new_seismic_payload( attributes.id, sealed_block, total_fees, sidecars, requests, ); Ok(BuildOutcome::Better { payload, cached_reads }) }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/seismic/payload/src/lib.rs
crates/seismic/payload/src/lib.rs
//! Seismic's payload builder implementation. #![doc( html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png", html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256", issue_tracker_base_url = "https://github.com/SeismicSystems/seismic-reth/issues/" )] #![cfg_attr(not(test), warn(unused_crate_dependencies))] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #![allow(clippy::useless_let_if_seq)] pub mod builder; pub use builder::SeismicPayloadBuilder; pub use reth_ethereum_payload_builder::EthereumBuilderConfig as SeismicBuilderConfig; // Use reth_ethereum_primitives to suppress unused import warning // We import the crate ensure features such as serde and reth-codec are enabled // When it is pulled in by other dependencies use reth_ethereum_primitives as _;
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/era/src/era_file_ops.rs
crates/era/src/era_file_ops.rs
//! Represents reading and writing operations' era file use crate::{e2s_types::Version, E2sError}; use std::{ fs::File, io::{Read, Seek, Write}, path::Path, }; /// Represents era file with generic content and identifier types pub trait EraFileFormat: Sized { /// Content group type type EraGroup; /// The identifier type type Id: EraFileId; /// Get the version fn version(&self) -> &Version; /// Get the content group fn group(&self) -> &Self::EraGroup; /// Get the file identifier fn id(&self) -> &Self::Id; /// Create a new instance fn new(group: Self::EraGroup, id: Self::Id) -> Self; } /// Era file identifiers pub trait EraFileId: Clone { /// Convert to standardized file name fn to_file_name(&self) -> String; /// Get the network name fn network_name(&self) -> &str; /// Get the starting number (block or slot) fn start_number(&self) -> u64; /// Get the count of items fn count(&self) -> u32; } /// [`StreamReader`] for reading era-format files pub trait StreamReader<R: Read + Seek>: Sized { /// The file type the reader produces type File: EraFileFormat; /// The iterator type for streaming data type Iterator; /// Create a new reader fn new(reader: R) -> Self; /// Read and parse the complete file fn read(self, network_name: String) -> Result<Self::File, E2sError>; /// Get an iterator for streaming processing fn iter(self) -> Self::Iterator; } /// [`FileReader`] provides reading era file operations for era files pub trait FileReader: StreamReader<File> { /// Opens and reads an era file from the given path fn open<P: AsRef<Path>>( path: P, network_name: impl Into<String>, ) -> Result<Self::File, E2sError> { let file = File::open(path).map_err(E2sError::Io)?; let reader = Self::new(file); reader.read(network_name.into()) } } /// [`StreamWriter`] for writing era-format files pub trait StreamWriter<W: Write>: Sized { /// The file type this writer handles type File: EraFileFormat; /// Create a new writer fn new(writer: W) -> Self; /// Writer version fn write_version(&mut self) -> Result<(), E2sError>; /// Write a complete era file fn write_file(&mut self, file: &Self::File) -> Result<(), E2sError>; /// Flush any buffered data fn flush(&mut self) -> Result<(), E2sError>; } /// [`StreamWriter`] provides writing file operations for era files pub trait FileWriter { /// Era file type the writer handles type File: EraFileFormat<Id: EraFileId>; /// Creates a new file at the specified path and writes the era file to it fn create<P: AsRef<Path>>(path: P, file: &Self::File) -> Result<(), E2sError>; /// Creates a file in the directory using standardized era naming fn create_with_id<P: AsRef<Path>>(directory: P, file: &Self::File) -> Result<(), E2sError>; } impl<T: StreamWriter<File>> FileWriter for T { type File = T::File; /// Creates a new file at the specified path and writes the era file to it fn create<P: AsRef<Path>>(path: P, file: &Self::File) -> Result<(), E2sError> { let file_handle = File::create(path).map_err(E2sError::Io)?; let mut writer = Self::new(file_handle); writer.write_file(file)?; Ok(()) } /// Creates a file in the directory using standardized era naming fn create_with_id<P: AsRef<Path>>(directory: P, file: &Self::File) -> Result<(), E2sError> { let filename = file.id().to_file_name(); let path = directory.as_ref().join(filename); Self::create(path, file) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/era/src/era_types.rs
crates/era/src/era_types.rs
//! Era types for `.era` files //! //! See also <https://github.com/eth-clients/e2store-format-specs/blob/main/formats/era.md> use crate::{ consensus_types::{CompressedBeaconState, CompressedSignedBeaconBlock}, e2s_types::{Entry, IndexEntry, SLOT_INDEX}, }; /// Era file content group /// /// Format: `Version | block* | era-state | other-entries* | slot-index(block)? | slot-index(state)` /// See also <https://github.com/eth-clients/e2store-format-specs/blob/main/formats/era.md#structure> #[derive(Debug)] pub struct EraGroup { /// Group including all blocks leading up to the era transition in slot order pub blocks: Vec<CompressedSignedBeaconBlock>, /// State in the era transition slot pub era_state: CompressedBeaconState, /// Other entries that don't fit into standard categories pub other_entries: Vec<Entry>, /// Block slot index, omitted for genesis era pub slot_index: Option<SlotIndex>, /// State slot index pub state_slot_index: SlotIndex, } impl EraGroup { /// Create a new era group pub const fn new( blocks: Vec<CompressedSignedBeaconBlock>, era_state: CompressedBeaconState, state_slot_index: SlotIndex, ) -> Self { Self { blocks, era_state, other_entries: Vec::new(), slot_index: None, state_slot_index } } /// Create a new era group with block slot index pub const fn with_block_index( blocks: Vec<CompressedSignedBeaconBlock>, era_state: CompressedBeaconState, slot_index: SlotIndex, state_slot_index: SlotIndex, ) -> Self { Self { blocks, era_state, other_entries: Vec::new(), slot_index: Some(slot_index), state_slot_index, } } /// Check if this is a genesis era - no blocks yet pub const fn is_genesis(&self) -> bool { self.blocks.is_empty() && self.slot_index.is_none() } /// Add another entry to this group pub fn add_entry(&mut self, entry: Entry) { self.other_entries.push(entry); } } /// [`SlotIndex`] records store offsets to data at specific slots /// from the beginning of the index record to the beginning of the corresponding data. /// /// Format: `starting-slot | index | index | index ... | count` /// /// See also <https://github.com/status-im/nimbus-eth2/blob/stable/docs/e2store.md#slotindex>. #[derive(Debug, Clone, PartialEq, Eq)] pub struct SlotIndex { /// Starting slot number pub starting_slot: u64, /// Offsets to data at each slot /// 0 indicates no data for that slot pub offsets: Vec<i64>, } impl SlotIndex { /// Create a new slot index pub const fn new(starting_slot: u64, offsets: Vec<i64>) -> Self { Self { starting_slot, offsets } } /// Get the number of slots covered by this index pub const fn slot_count(&self) -> usize { self.offsets.len() } /// Get the offset for a specific slot pub fn get_offset(&self, slot_index: usize) -> Option<i64> { self.offsets.get(slot_index).copied() } /// Check if a slot has data - non-zero offset pub fn has_data_at_slot(&self, slot_index: usize) -> bool { self.get_offset(slot_index).is_some_and(|offset| offset != 0) } } impl IndexEntry for SlotIndex { fn new(starting_number: u64, offsets: Vec<i64>) -> Self { Self { starting_slot: starting_number, offsets } } fn entry_type() -> [u8; 2] { SLOT_INDEX } fn starting_number(&self) -> u64 { self.starting_slot } fn offsets(&self) -> &[i64] { &self.offsets } } #[cfg(test)] mod tests { use super::*; use crate::{ e2s_types::{Entry, IndexEntry}, test_utils::{create_beacon_block, create_beacon_state}, }; #[test] fn test_slot_index_roundtrip() { let starting_slot = 1000; let offsets = vec![100, 200, 300, 400, 500]; let slot_index = SlotIndex::new(starting_slot, offsets.clone()); let entry = slot_index.to_entry(); // Validate entry type assert_eq!(entry.entry_type, SLOT_INDEX); // Convert back to slot index let recovered = SlotIndex::from_entry(&entry).unwrap(); // Verify fields match assert_eq!(recovered.starting_slot, starting_slot); assert_eq!(recovered.offsets, offsets); } #[test] fn test_slot_index_basic_operations() { let starting_slot = 2000; let offsets = vec![100, 200, 300]; let slot_index = SlotIndex::new(starting_slot, offsets); assert_eq!(slot_index.slot_count(), 3); assert_eq!(slot_index.starting_slot, 2000); } #[test] fn test_slot_index_empty_slots() { let starting_slot = 1000; let offsets = vec![100, 0, 300, 0, 500]; let slot_index = SlotIndex::new(starting_slot, offsets); // Test that empty slots return false for has_data_at_slot // slot 1000: offset 100 assert!(slot_index.has_data_at_slot(0)); // slot 1001: offset 0 - empty assert!(!slot_index.has_data_at_slot(1)); // slot 1002: offset 300 assert!(slot_index.has_data_at_slot(2)); // slot 1003: offset 0 - empty assert!(!slot_index.has_data_at_slot(3)); // slot 1004: offset 500 assert!(slot_index.has_data_at_slot(4)); } #[test] fn test_era_group_basic_construction() { let blocks = vec![create_beacon_block(10), create_beacon_block(15), create_beacon_block(20)]; let era_state = create_beacon_state(50); let state_slot_index = SlotIndex::new(1000, vec![100, 200, 300]); let era_group = EraGroup::new(blocks, era_state, state_slot_index); // Verify initial state assert_eq!(era_group.blocks.len(), 3); assert_eq!(era_group.other_entries.len(), 0); assert_eq!(era_group.slot_index, None); assert_eq!(era_group.state_slot_index.starting_slot, 1000); assert_eq!(era_group.state_slot_index.offsets, vec![100, 200, 300]); } #[test] fn test_era_group_with_block_index() { let blocks = vec![create_beacon_block(10), create_beacon_block(15)]; let era_state = create_beacon_state(50); let block_slot_index = SlotIndex::new(500, vec![50, 100]); let state_slot_index = SlotIndex::new(1000, vec![200, 300]); let era_group = EraGroup::with_block_index(blocks, era_state, block_slot_index, state_slot_index); // Verify state with block index assert_eq!(era_group.blocks.len(), 2); assert_eq!(era_group.other_entries.len(), 0); assert!(era_group.slot_index.is_some()); let block_index = era_group.slot_index.as_ref().unwrap(); assert_eq!(block_index.starting_slot, 500); assert_eq!(block_index.offsets, vec![50, 100]); assert_eq!(era_group.state_slot_index.starting_slot, 1000); assert_eq!(era_group.state_slot_index.offsets, vec![200, 300]); } #[test] fn test_era_group_genesis_check() { // Genesis era - no blocks, no block slot index let era_state = create_beacon_state(50); let state_slot_index = SlotIndex::new(0, vec![100]); let genesis_era = EraGroup::new(vec![], era_state, state_slot_index); assert!(genesis_era.is_genesis()); // Non-genesis era - has blocks let blocks = vec![create_beacon_block(10)]; let era_state = create_beacon_state(50); let state_slot_index = SlotIndex::new(1000, vec![100]); let normal_era = EraGroup::new(blocks, era_state, state_slot_index); assert!(!normal_era.is_genesis()); // Non-genesis era - has block slot index let era_state = create_beacon_state(50); let block_slot_index = SlotIndex::new(500, vec![50]); let state_slot_index = SlotIndex::new(1000, vec![100]); let era_with_index = EraGroup::with_block_index(vec![], era_state, block_slot_index, state_slot_index); assert!(!era_with_index.is_genesis()); } #[test] fn test_era_group_add_entries() { let blocks = vec![create_beacon_block(10)]; let era_state = create_beacon_state(50); let state_slot_index = SlotIndex::new(1000, vec![100]); // Create and verify group let mut era_group = EraGroup::new(blocks, era_state, state_slot_index); assert_eq!(era_group.other_entries.len(), 0); // Create custom entries with different types let entry1 = Entry::new([0x01, 0x01], vec![1, 2, 3, 4]); let entry2 = Entry::new([0x02, 0x02], vec![5, 6, 7, 8]); // Add those entries era_group.add_entry(entry1); era_group.add_entry(entry2); // Verify entries were added correctly assert_eq!(era_group.other_entries.len(), 2); assert_eq!(era_group.other_entries[0].entry_type, [0x01, 0x01]); assert_eq!(era_group.other_entries[0].data, vec![1, 2, 3, 4]); assert_eq!(era_group.other_entries[1].entry_type, [0x02, 0x02]); assert_eq!(era_group.other_entries[1].data, vec![5, 6, 7, 8]); } #[test] fn test_index_with_negative_offset() { let mut data = Vec::new(); data.extend_from_slice(&0u64.to_le_bytes()); data.extend_from_slice(&(-1024i64).to_le_bytes()); data.extend_from_slice(&0i64.to_le_bytes()); data.extend_from_slice(&2i64.to_le_bytes()); let entry = Entry::new(SLOT_INDEX, data); let index = SlotIndex::from_entry(&entry).unwrap(); let parsed_offset = index.offsets[0]; assert_eq!(parsed_offset, -1024); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/era/src/lib.rs
crates/era/src/lib.rs
//! Era and Era1 files support for Ethereum history expiry. //! //! Era1 files use the same e2store foundation but are specialized for //! execution layer block history, following the format: //! Version | block-tuple* | other-entries* | Accumulator | `BlockIndex` //! //! Era files are special instances of `.e2s` files with a strict content format //! optimized for reading and long-term storage and distribution. //! //! See also: //! - E2store format: <https://github.com/status-im/nimbus-eth2/blob/stable/docs/e2store.md> //! - Era format: <https://github.com/eth-clients/e2store-format-specs/blob/main/formats/era.md> //! - Era1 format: <https://github.com/eth-clients/e2store-format-specs/blob/main/formats/era1.md> pub mod consensus_types; pub mod e2s_file; pub mod e2s_types; pub mod era1_file; pub mod era1_types; pub mod era_file_ops; pub mod era_types; pub mod execution_types; #[cfg(test)] pub(crate) mod test_utils; use crate::e2s_types::E2sError; use alloy_rlp::Decodable; use ssz::Decode; /// Extension trait for generic decoding from compressed data pub trait DecodeCompressed { /// Decompress and decode the data into the given type fn decode<T: Decodable>(&self) -> Result<T, E2sError>; } /// Extension trait for generic decoding from compressed ssz data pub trait DecodeCompressedSsz { /// Decompress and decode the SSZ data into the given type fn decode<T: Decode>(&self) -> Result<T, E2sError>; }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/era/src/e2s_types.rs
crates/era/src/e2s_types.rs
//! Types to build e2store files //! ie. with `.e2s` extension //! //! e2store file contains header and entry //! //! The [`Header`] is an 8-byte structure at the beginning of each record in the file //! //! An [`Entry`] is a complete record in the file, consisting of both a [`Header`] and its //! associated data use ssz_derive::{Decode, Encode}; use std::io::{self, Read, Write}; use thiserror::Error; /// [`Version`] record: ['e', '2'] pub const VERSION: [u8; 2] = [0x65, 0x32]; /// Empty record pub const EMPTY: [u8; 2] = [0x00, 0x00]; /// `SlotIndex` record: ['i', '2'] pub const SLOT_INDEX: [u8; 2] = [0x69, 0x32]; /// Error types for e2s file operations #[derive(Error, Debug)] pub enum E2sError { /// IO error during file operations #[error("IO error: {0}")] Io(#[from] io::Error), /// Error during SSZ encoding/decoding #[error("SSZ error: {0}")] Ssz(String), /// Reserved field in header not zero #[error("Reserved field in header not zero")] ReservedNotZero, /// Error during snappy compression #[error("Snappy compression error: {0}")] SnappyCompression(String), /// Error during snappy decompression #[error("Snappy decompression error: {0}")] SnappyDecompression(String), /// Error during RLP encoding/decoding #[error("RLP error: {0}")] Rlp(String), } /// Header for TLV records in e2store files #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct Header { /// Record type identifier pub header_type: [u8; 2], /// Length of data following the header pub length: u32, /// Reserved field, must be zero pub reserved: u16, } impl Header { /// Create a new header with the specified type and length pub const fn new(header_type: [u8; 2], length: u32) -> Self { Self { header_type, length, reserved: 0 } } /// Read header from a reader pub fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, E2sError> { let mut header_bytes = [0u8; 8]; match reader.read_exact(&mut header_bytes) { Ok(_) => {} Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None), Err(e) => return Err(e.into()), } let header: Self = match ssz::Decode::from_ssz_bytes(&header_bytes) { Ok(h) => h, Err(_) => return Err(E2sError::Ssz(String::from("Failed to decode SSZ header"))), }; if header.reserved != 0 { return Err(E2sError::ReservedNotZero); } Ok(Some(header)) } /// Writes the header to the given writer. pub fn write<W: Write>(&self, writer: &mut W) -> io::Result<()> { let encoded = ssz::Encode::as_ssz_bytes(self); writer.write_all(&encoded) } } /// The [`Version`] record must be the first record in an e2store file #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct Version; impl Version { /// Encode this record to the given writer pub fn encode<W: Write>(&self, writer: &mut W) -> io::Result<()> { let header = Header::new(VERSION, 0); header.write(writer) } } /// Complete record in an e2store file, consisting of a type, length, and associated data #[derive(Debug, Clone)] pub struct Entry { /// Record type identifier pub entry_type: [u8; 2], /// Data contained in the entry pub data: Vec<u8>, } impl Entry { /// Create a new entry pub const fn new(entry_type: [u8; 2], data: Vec<u8>) -> Self { Self { entry_type, data } } /// Read an entry from a reader pub fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, E2sError> { // Read the header first let header = match Header::read(reader)? { Some(h) => h, None => return Ok(None), }; // Read the data let mut data = vec![0u8; header.length as usize]; match reader.read_exact(&mut data) { Ok(_) => {} Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => { return Err(E2sError::Io(io::Error::new( io::ErrorKind::UnexpectedEof, "Unexpected EOF while reading entry data", ))); } Err(e) => return Err(e.into()), } Ok(Some(Self { entry_type: header.header_type, data })) } /// Write the entry to [`Entry`] writer pub fn write<W: Write>(&self, writer: &mut W) -> io::Result<()> { let header = Header::new(self.entry_type, self.data.len() as u32); header.write(writer)?; writer.write_all(&self.data) } /// Check if this is a [`Version`] entry pub fn is_version(&self) -> bool { self.entry_type == VERSION } /// Check if this is a `SlotIndex` entry pub fn is_slot_index(&self) -> bool { self.entry_type == SLOT_INDEX } } /// Serialize and deserialize index entries with format: /// `starting-number | offsets... | count` pub trait IndexEntry: Sized { /// Get the entry type identifier for this index fn entry_type() -> [u8; 2]; /// Create a new instance with starting number and offsets fn new(starting_number: u64, offsets: Vec<i64>) -> Self; /// Get the starting number - can be starting slot or block number for example fn starting_number(&self) -> u64; /// Get the offsets vector fn offsets(&self) -> &[i64]; /// Convert to an [`Entry`] for storage in an e2store file /// Format: starting-number | offset1 | offset2 | ... | count fn to_entry(&self) -> Entry { let mut data = Vec::with_capacity(8 + self.offsets().len() * 8 + 8); // Add starting number data.extend_from_slice(&self.starting_number().to_le_bytes()); // Add all offsets data.extend(self.offsets().iter().flat_map(|offset| offset.to_le_bytes())); // Encode count - 8 bytes again let count = self.offsets().len() as i64; data.extend_from_slice(&count.to_le_bytes()); Entry::new(Self::entry_type(), data) } /// Create from an [`Entry`] fn from_entry(entry: &Entry) -> Result<Self, E2sError> { let expected_type = Self::entry_type(); if entry.entry_type != expected_type { return Err(E2sError::Ssz(format!( "Invalid entry type: expected {:02x}{:02x}, got {:02x}{:02x}", expected_type[0], expected_type[1], entry.entry_type[0], entry.entry_type[1] ))); } if entry.data.len() < 16 { return Err(E2sError::Ssz( "Index entry too short: need at least 16 bytes for starting_number and count" .to_string(), )); } // Extract count from last 8 bytes let count_bytes = &entry.data[entry.data.len() - 8..]; let count = i64::from_le_bytes( count_bytes .try_into() .map_err(|_| E2sError::Ssz("Failed to read count bytes".to_string()))?, ) as usize; // Verify entry has correct size let expected_len = 8 + count * 8 + 8; if entry.data.len() != expected_len { return Err(E2sError::Ssz(format!( "Index entry has incorrect length: expected {expected_len}, got {}", entry.data.len() ))); } // Extract starting number from first 8 bytes let starting_number = u64::from_le_bytes( entry.data[0..8] .try_into() .map_err(|_| E2sError::Ssz("Failed to read starting_number bytes".to_string()))?, ); // Extract all offsets let mut offsets = Vec::with_capacity(count); for i in 0..count { let start = 8 + i * 8; let end = start + 8; let offset_bytes = &entry.data[start..end]; let offset = i64::from_le_bytes( offset_bytes .try_into() .map_err(|_| E2sError::Ssz(format!("Failed to read offset {i} bytes")))?, ); offsets.push(offset); } Ok(Self::new(starting_number, offsets)) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/era/src/e2s_file.rs
crates/era/src/e2s_file.rs
//! `E2Store` file reader //! //! See also <https://github.com/status-im/nimbus-eth2/blob/stable/docs/e2store.md> use crate::e2s_types::{E2sError, Entry, Version}; use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write}; /// A reader for `E2Store` files that wraps a [`BufReader`]. #[derive(Debug)] pub struct E2StoreReader<R: Read> { /// Buffered reader reader: BufReader<R>, } impl<R: Read + Seek> E2StoreReader<R> { /// Create a new [`E2StoreReader`] pub fn new(reader: R) -> Self { Self { reader: BufReader::new(reader) } } /// Read and validate the version record pub fn read_version(&mut self) -> Result<Option<Entry>, E2sError> { // Reset reader to beginning self.reader.seek(SeekFrom::Start(0))?; match Entry::read(&mut self.reader)? { Some(entry) if entry.is_version() => Ok(Some(entry)), Some(_) => Err(E2sError::Ssz("First entry must be a Version entry".to_string())), None => Ok(None), } } /// Read the next entry from the file pub fn read_next_entry(&mut self) -> Result<Option<Entry>, E2sError> { Entry::read(&mut self.reader) } /// Read all entries from the file, including the version entry pub fn entries(&mut self) -> Result<Vec<Entry>, E2sError> { // Reset reader to beginning self.reader.seek(SeekFrom::Start(0))?; let mut entries = Vec::new(); while let Some(entry) = self.read_next_entry()? { entries.push(entry); } Ok(entries) } } /// A writer for `E2Store` files that wraps a [`BufWriter`]. #[derive(Debug)] pub struct E2StoreWriter<W: Write> { /// Buffered writer writer: BufWriter<W>, /// Tracks whether this writer has written a version entry has_written_version: bool, } impl<W: Write> E2StoreWriter<W> { /// Create a new [`E2StoreWriter`] pub fn new(writer: W) -> Self { Self { writer: BufWriter::new(writer), has_written_version: false } } /// Create a new [`E2StoreWriter`] and write the version entry pub fn with_version(writer: W) -> Result<Self, E2sError> { let mut writer = Self::new(writer); writer.write_version()?; Ok(writer) } /// Write the version entry as the first entry in the file. /// If not called explicitly, it will be written automatically before the first non-version /// entry. pub fn write_version(&mut self) -> Result<(), E2sError> { if self.has_written_version { return Ok(()); } let version = Version; version.encode(&mut self.writer)?; self.has_written_version = true; Ok(()) } /// Write an entry to the file. /// If a version entry has not been written yet, it will be added. pub fn write_entry(&mut self, entry: &Entry) -> Result<(), E2sError> { if !self.has_written_version { self.write_version()?; } entry.write(&mut self.writer)?; Ok(()) } /// Flush any buffered data to the underlying writer pub fn flush(&mut self) -> Result<(), E2sError> { self.writer.flush().map_err(E2sError::Io) } } #[cfg(test)] mod tests { use super::*; use crate::e2s_types::{SLOT_INDEX, VERSION}; use std::io::Cursor; fn create_slot_index_data(starting_slot: u64, offsets: &[i64]) -> Vec<u8> { // Format: starting-slot | index | index | index ... | count let mut data = Vec::with_capacity(8 + offsets.len() * 8 + 8); // Add starting slot data.extend_from_slice(&starting_slot.to_le_bytes()); // Add all offsets for offset in offsets { data.extend_from_slice(&offset.to_le_bytes()); } // Add count data.extend_from_slice(&(offsets.len() as i64).to_le_bytes()); data } #[test] fn test_e2store_reader() -> Result<(), E2sError> { // Create a mock e2store file in memory let mut mock_file = Vec::new(); let version_entry = Entry::new(VERSION, Vec::new()); version_entry.write(&mut mock_file)?; let slot_index_entry1 = Entry::new(SLOT_INDEX, create_slot_index_data(1, &[1024])); slot_index_entry1.write(&mut mock_file)?; let slot_index_entry2 = Entry::new(SLOT_INDEX, create_slot_index_data(2, &[2048])); slot_index_entry2.write(&mut mock_file)?; let custom_type = [0x99, 0x99]; let custom_entry = Entry::new(custom_type, vec![10, 11, 12]); custom_entry.write(&mut mock_file)?; let cursor = Cursor::new(mock_file); let mut e2store_reader = E2StoreReader::new(cursor); let version = e2store_reader.read_version()?; assert!(version.is_some()); let entries = e2store_reader.entries()?; // Validate entries assert_eq!(entries.len(), 4); // First entry should be version assert!(entries[0].is_version()); // Second entry should be slot index assert!(entries[1].is_slot_index()); // Third entry is slot index assert!(entries[2].is_slot_index()); // Fourth entry is custom type assert!(entries[3].entry_type == [0x99, 0x99]); Ok(()) } #[test] fn test_slot_index_with_multiple_offsets() -> Result<(), E2sError> { let starting_slot = 100; let offsets = &[1024, 2048, 0, 0, 3072, 0, 4096]; let slot_index_data = create_slot_index_data(starting_slot, offsets); let slot_index_entry = Entry::new(SLOT_INDEX, slot_index_data.clone()); // Verify the slot index data format assert_eq!(slot_index_data.len(), 8 + offsets.len() * 8 + 8); // Check the starting slot let mut starting_slot_bytes = [0u8; 8]; starting_slot_bytes.copy_from_slice(&slot_index_data[0..8]); assert_eq!(u64::from_le_bytes(starting_slot_bytes), starting_slot); // Check the count at the end let mut count_bytes = [0u8; 8]; count_bytes.copy_from_slice(&slot_index_data[slot_index_data.len() - 8..]); assert_eq!(i64::from_le_bytes(count_bytes), offsets.len() as i64); // Verify we can write and read it back let mut buffer = Vec::new(); slot_index_entry.write(&mut buffer)?; let cursor = Cursor::new(buffer); let mut reader = E2StoreReader::new(cursor); let read_entry = reader.read_next_entry()?.unwrap(); assert!(read_entry.is_slot_index()); assert_eq!(read_entry.data.len(), slot_index_data.len()); Ok(()) } #[test] fn test_empty_file() -> Result<(), E2sError> { // Create an empty file let mock_file = Vec::new(); // Create reader let cursor = Cursor::new(mock_file); let mut e2store_reader = E2StoreReader::new(cursor); // Reading version should return None let version = e2store_reader.read_version()?; assert!(version.is_none()); // Entries should be empty let entries = e2store_reader.entries()?; assert!(entries.is_empty()); Ok(()) } #[test] fn test_read_next_entry() -> Result<(), E2sError> { let mut mock_file = Vec::new(); let version_entry = Entry::new(VERSION, Vec::new()); version_entry.write(&mut mock_file)?; let slot_entry = Entry::new(SLOT_INDEX, create_slot_index_data(1, &[1024])); slot_entry.write(&mut mock_file)?; let cursor = Cursor::new(mock_file); let mut reader = E2StoreReader::new(cursor); let first = reader.read_next_entry()?.unwrap(); assert!(first.is_version()); let second = reader.read_next_entry()?.unwrap(); assert!(second.is_slot_index()); let third = reader.read_next_entry()?; assert!(third.is_none()); Ok(()) } #[test] fn test_e2store_writer() -> Result<(), E2sError> { let mut buffer = Vec::new(); { let mut writer = E2StoreWriter::new(&mut buffer); // Write version entry writer.write_version()?; // Write a block index entry let block_entry = Entry::new(SLOT_INDEX, create_slot_index_data(1, &[1024])); writer.write_entry(&block_entry)?; // Write a custom entry let custom_type = [0x99, 0x99]; let custom_entry = Entry::new(custom_type, vec![10, 11, 12]); writer.write_entry(&custom_entry)?; writer.flush()?; } let cursor = Cursor::new(&buffer); let mut reader = E2StoreReader::new(cursor); let entries = reader.entries()?; assert_eq!(entries.len(), 3); assert!(entries[0].is_version()); assert!(entries[1].is_slot_index()); assert_eq!(entries[2].entry_type, [0x99, 0x99]); Ok(()) } #[test] fn test_writer_implicit_version_insertion() -> Result<(), E2sError> { let mut buffer = Vec::new(); { // Writer without explicitly writing the version let mut writer = E2StoreWriter::new(&mut buffer); // Write an entry, it should automatically add a version first let custom_type = [0x42, 0x42]; let custom_entry = Entry::new(custom_type, vec![1, 2, 3, 4]); writer.write_entry(&custom_entry)?; // Write another entry let another_custom = Entry::new([0x43, 0x43], vec![5, 6, 7, 8]); writer.write_entry(&another_custom)?; writer.flush()?; } let cursor = Cursor::new(&buffer); let mut reader = E2StoreReader::new(cursor); let version = reader.read_version()?; assert!(version.is_some(), "Version entry should have been auto-added"); let entries = reader.entries()?; assert_eq!(entries.len(), 3); assert!(entries[0].is_version()); assert_eq!(entries[1].entry_type, [0x42, 0x42]); assert_eq!(entries[1].data, vec![1, 2, 3, 4]); assert_eq!(entries[2].entry_type, [0x43, 0x43]); assert_eq!(entries[2].data, vec![5, 6, 7, 8]); Ok(()) } #[test] fn test_writer_prevents_duplicate_versions() -> Result<(), E2sError> { let mut buffer = Vec::new(); { let mut writer = E2StoreWriter::new(&mut buffer); // Call write_version multiple times, it should only write once writer.write_version()?; writer.write_version()?; writer.write_version()?; // Write an entry let block_entry = Entry::new(SLOT_INDEX, create_slot_index_data(42, &[8192])); writer.write_entry(&block_entry)?; writer.flush()?; } // Verify only one version entry was written let cursor = Cursor::new(&buffer); let mut reader = E2StoreReader::new(cursor); let entries = reader.entries()?; assert_eq!(entries.len(), 2); assert!(entries[0].is_version()); assert!(entries[1].is_slot_index()); Ok(()) } #[test] fn test_e2store_multiple_roundtrip_conversions() -> Result<(), E2sError> { // Initial set of entries to test with varied types and sizes let entry1 = Entry::new([0x01, 0x01], vec![1, 2, 3, 4, 5]); let entry2 = Entry::new([0x02, 0x02], vec![10, 20, 30, 40, 50]); let entry3 = Entry::new(SLOT_INDEX, create_slot_index_data(123, &[45678])); let entry4 = Entry::new([0xFF, 0xFF], Vec::new()); println!("Initial entries count: 4"); // First write cycle : create initial buffer let mut buffer1 = Vec::new(); { let mut writer = E2StoreWriter::new(&mut buffer1); writer.write_version()?; writer.write_entry(&entry1)?; writer.write_entry(&entry2)?; writer.write_entry(&entry3)?; writer.write_entry(&entry4)?; writer.flush()?; } // First read cycle : read from initial buffer let mut reader1 = E2StoreReader::new(Cursor::new(&buffer1)); let entries1 = reader1.entries()?; println!("First read entries:"); for (i, entry) in entries1.iter().enumerate() { println!("Entry {}: type {:?}, data len {}", i, entry.entry_type, entry.data.len()); } println!("First read entries count: {}", entries1.len()); // Verify first read content assert_eq!(entries1.len(), 5, "Should have 5 entries (version + 4 data)"); assert!(entries1[0].is_version()); assert_eq!(entries1[1].entry_type, [0x01, 0x01]); assert_eq!(entries1[1].data, vec![1, 2, 3, 4, 5]); assert_eq!(entries1[2].entry_type, [0x02, 0x02]); assert_eq!(entries1[2].data, vec![10, 20, 30, 40, 50]); assert!(entries1[3].is_slot_index()); assert_eq!(entries1[4].entry_type, [0xFF, 0xFF]); assert_eq!(entries1[4].data.len(), 0); // Second write cycle : write what we just read let mut buffer2 = Vec::new(); { let mut writer = E2StoreWriter::new(&mut buffer2); // Only write version once writer.write_version()?; // Skip the first entry ie the version since we already wrote it for entry in &entries1[1..] { writer.write_entry(entry)?; } writer.flush()?; } // Second read cycle - read the second buffer let mut reader2 = E2StoreReader::new(Cursor::new(&buffer2)); let entries2 = reader2.entries()?; // Verify second read matches first read assert_eq!(entries1.len(), entries2.len()); for i in 0..entries1.len() { assert_eq!(entries1[i].entry_type, entries2[i].entry_type); assert_eq!(entries1[i].data, entries2[i].data); } Ok(()) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/era/src/era1_types.rs
crates/era/src/era1_types.rs
//! Era1 types //! //! See also <https://github.com/eth-clients/e2store-format-specs/blob/main/formats/era1.md> use crate::{ e2s_types::{Entry, IndexEntry}, era_file_ops::EraFileId, execution_types::{Accumulator, BlockTuple, MAX_BLOCKS_PER_ERA1}, }; use alloy_primitives::BlockNumber; /// `BlockIndex` record: ['i', '2'] pub const BLOCK_INDEX: [u8; 2] = [0x66, 0x32]; /// File content in an Era1 file /// /// Format: `block-tuple* | other-entries* | Accumulator | BlockIndex` #[derive(Debug)] pub struct Era1Group { /// Blocks in this era1 group pub blocks: Vec<BlockTuple>, /// Other entries that don't fit into the standard categories pub other_entries: Vec<Entry>, /// Accumulator is hash tree root of block headers and difficulties pub accumulator: Accumulator, /// Block index, optional, omitted for genesis era pub block_index: BlockIndex, } impl Era1Group { /// Create a new [`Era1Group`] pub const fn new( blocks: Vec<BlockTuple>, accumulator: Accumulator, block_index: BlockIndex, ) -> Self { Self { blocks, accumulator, block_index, other_entries: Vec::new() } } /// Add another entry to this group pub fn add_entry(&mut self, entry: Entry) { self.other_entries.push(entry); } } /// [`BlockIndex`] records store offsets to data at specific block numbers /// from the beginning of the index record to the beginning of the corresponding data. /// /// Format: /// `starting-(block)-number | index | index | index ... | count` #[derive(Debug, Clone)] pub struct BlockIndex { /// Starting block number starting_number: BlockNumber, /// Offsets to data at each block number offsets: Vec<i64>, } impl BlockIndex { /// Get the offset for a specific block number pub fn offset_for_block(&self, block_number: BlockNumber) -> Option<i64> { if block_number < self.starting_number { return None; } let index = (block_number - self.starting_number) as usize; self.offsets.get(index).copied() } } impl IndexEntry for BlockIndex { fn new(starting_number: u64, offsets: Vec<i64>) -> Self { Self { starting_number, offsets } } fn entry_type() -> [u8; 2] { BLOCK_INDEX } fn starting_number(&self) -> u64 { self.starting_number } fn offsets(&self) -> &[i64] { &self.offsets } } /// Era1 file identifier #[derive(Debug, Clone, PartialEq, Eq)] pub struct Era1Id { /// Network configuration name pub network_name: String, /// First block number in file pub start_block: BlockNumber, /// Number of blocks in the file pub block_count: u32, /// Optional hash identifier for this file /// First 4 bytes of the last historical root in the last state in the era file pub hash: Option<[u8; 4]>, } impl Era1Id { /// Create a new [`Era1Id`] pub fn new( network_name: impl Into<String>, start_block: BlockNumber, block_count: u32, ) -> Self { Self { network_name: network_name.into(), start_block, block_count, hash: None } } /// Add a hash identifier to [`Era1Id`] pub const fn with_hash(mut self, hash: [u8; 4]) -> Self { self.hash = Some(hash); self } // Helper function to calculate the number of eras per era1 file, // If the user can decide how many blocks per era1 file there are, we need to calculate it. // Most of the time it should be 1, but it can never be more than 2 eras per file // as there is a maximum of 8192 blocks per era1 file. const fn calculate_era_count(&self, first_era: u64) -> u64 { // Calculate the actual last block number in the range let last_block = self.start_block + self.block_count as u64 - 1; // Find which era the last block belongs to let last_era = last_block / MAX_BLOCKS_PER_ERA1 as u64; // Count how many eras we span last_era - first_era + 1 } } impl EraFileId for Era1Id { fn network_name(&self) -> &str { &self.network_name } fn start_number(&self) -> u64 { self.start_block } fn count(&self) -> u32 { self.block_count } /// Convert to file name following the era file naming: /// `<config-name>-<era-number>-<era-count>-<short-historical-root>.era(1)` /// <https://github.com/eth-clients/e2store-format-specs/blob/main/formats/era.md#file-name> /// See also <https://github.com/eth-clients/e2store-format-specs/blob/main/formats/era1.md> fn to_file_name(&self) -> String { // Find which era the first block belongs to let era_number = self.start_block / MAX_BLOCKS_PER_ERA1 as u64; let era_count = self.calculate_era_count(era_number); if let Some(hash) = self.hash { format!( "{}-{:05}-{:05}-{:02x}{:02x}{:02x}{:02x}.era1", self.network_name, era_number, era_count, hash[0], hash[1], hash[2], hash[3] ) } else { // era spec format with placeholder hash when no hash available // Format: `<config-name>-<era-number>-<era-count>-00000000.era1` format!("{}-{:05}-{:05}-00000000.era1", self.network_name, era_number, era_count) } } } #[cfg(test)] mod tests { use super::*; use crate::{ test_utils::{create_sample_block, create_test_block_with_compressed_data}, DecodeCompressed, }; use alloy_consensus::ReceiptWithBloom; use alloy_primitives::{B256, U256}; #[test] fn test_alloy_components_decode_and_receipt_in_bloom() { // Create a block tuple from compressed data let block: BlockTuple = create_test_block_with_compressed_data(30); // Decode and decompress the block header let header: alloy_consensus::Header = block.header.decode().unwrap(); assert_eq!(header.number, 30, "Header block number should match"); assert_eq!(header.difficulty, U256::from(30 * 1000), "Header difficulty should match"); assert_eq!(header.gas_limit, 5000000, "Gas limit should match"); assert_eq!(header.gas_used, 21000, "Gas used should match"); assert_eq!(header.timestamp, 1609459200 + 30, "Timestamp should match"); assert_eq!(header.base_fee_per_gas, Some(10), "Base fee per gas should match"); assert!(header.withdrawals_root.is_some(), "Should have withdrawals root"); assert!(header.blob_gas_used.is_none(), "Should not have blob gas used"); assert!(header.excess_blob_gas.is_none(), "Should not have excess blob gas"); let body: alloy_consensus::BlockBody<alloy_primitives::Bytes> = block.body.decode().unwrap(); assert_eq!(body.ommers.len(), 0, "Should have no ommers"); assert!(body.withdrawals.is_some(), "Should have withdrawals field"); let receipts: Vec<ReceiptWithBloom> = block.receipts.decode().unwrap(); assert_eq!(receipts.len(), 1, "Should have exactly 1 receipt"); } #[test] fn test_block_index_roundtrip() { let starting_number = 1000; let offsets = vec![100, 200, 300, 400, 500]; let block_index = BlockIndex::new(starting_number, offsets.clone()); let entry = block_index.to_entry(); // Validate entry type assert_eq!(entry.entry_type, BLOCK_INDEX); // Convert back to block index let recovered = BlockIndex::from_entry(&entry).unwrap(); // Verify fields match assert_eq!(recovered.starting_number, starting_number); assert_eq!(recovered.offsets, offsets); } #[test] fn test_block_index_offset_lookup() { let starting_number = 1000; let offsets = vec![100, 200, 300, 400, 500]; let block_index = BlockIndex::new(starting_number, offsets); // Test valid lookups assert_eq!(block_index.offset_for_block(1000), Some(100)); assert_eq!(block_index.offset_for_block(1002), Some(300)); assert_eq!(block_index.offset_for_block(1004), Some(500)); // Test out of range lookups assert_eq!(block_index.offset_for_block(999), None); assert_eq!(block_index.offset_for_block(1005), None); } #[test] fn test_era1_group_basic_construction() { let blocks = vec![create_sample_block(10), create_sample_block(15), create_sample_block(20)]; let root_bytes = [0xDD; 32]; let accumulator = Accumulator::new(B256::from(root_bytes)); let block_index = BlockIndex::new(1000, vec![100, 200, 300]); let era1_group = Era1Group::new(blocks, accumulator.clone(), block_index); // Verify initial state assert_eq!(era1_group.blocks.len(), 3); assert_eq!(era1_group.other_entries.len(), 0); assert_eq!(era1_group.accumulator.root, accumulator.root); assert_eq!(era1_group.block_index.starting_number, 1000); assert_eq!(era1_group.block_index.offsets, vec![100, 200, 300]); } #[test] fn test_era1_group_add_entries() { let blocks = vec![create_sample_block(10)]; let root_bytes = [0xDD; 32]; let accumulator = Accumulator::new(B256::from(root_bytes)); let block_index = BlockIndex::new(1000, vec![100]); // Create and verify group let mut era1_group = Era1Group::new(blocks, accumulator, block_index); assert_eq!(era1_group.other_entries.len(), 0); // Create custom entries with different types let entry1 = Entry::new([0x01, 0x01], vec![1, 2, 3, 4]); let entry2 = Entry::new([0x02, 0x02], vec![5, 6, 7, 8]); // Add those entries era1_group.add_entry(entry1); era1_group.add_entry(entry2); // Verify entries were added correctly assert_eq!(era1_group.other_entries.len(), 2); assert_eq!(era1_group.other_entries[0].entry_type, [0x01, 0x01]); assert_eq!(era1_group.other_entries[0].data, vec![1, 2, 3, 4]); assert_eq!(era1_group.other_entries[1].entry_type, [0x02, 0x02]); assert_eq!(era1_group.other_entries[1].data, vec![5, 6, 7, 8]); } #[test] fn test_era1_group_with_mismatched_index() { let blocks = vec![create_sample_block(10), create_sample_block(15), create_sample_block(20)]; let root_bytes = [0xDD; 32]; let accumulator = Accumulator::new(B256::from(root_bytes)); // Create block index with different starting number let block_index = BlockIndex::new(2000, vec![100, 200, 300]); // This should create a valid Era1Group // even though the block numbers don't match the block index // validation not at the era1 group level let era1_group = Era1Group::new(blocks, accumulator, block_index); // Verify the mismatch exists but the group was created assert_eq!(era1_group.blocks.len(), 3); assert_eq!(era1_group.block_index.starting_number, 2000); } #[test_case::test_case( Era1Id::new("mainnet", 0, 8192).with_hash([0x5e, 0xc1, 0xff, 0xb8]), "mainnet-00000-00001-5ec1ffb8.era1"; "Mainnet era 0" )] #[test_case::test_case( Era1Id::new("mainnet", 8192, 8192).with_hash([0x5e, 0xcb, 0x9b, 0xf9]), "mainnet-00001-00001-5ecb9bf9.era1"; "Mainnet era 1" )] #[test_case::test_case( Era1Id::new("sepolia", 0, 8192).with_hash([0x90, 0x91, 0x84, 0x72]), "sepolia-00000-00001-90918472.era1"; "Sepolia era 0" )] #[test_case::test_case( Era1Id::new("sepolia", 155648, 8192).with_hash([0xfa, 0x77, 0x00, 0x19]), "sepolia-00019-00001-fa770019.era1"; "Sepolia era 19" )] #[test_case::test_case( Era1Id::new("mainnet", 1000, 100), "mainnet-00000-00001-00000000.era1"; "ID without hash" )] #[test_case::test_case( Era1Id::new("sepolia", 101130240, 8192).with_hash([0xab, 0xcd, 0xef, 0x12]), "sepolia-12345-00001-abcdef12.era1"; "Large block number era 12345" )] fn test_era1id_file_naming(id: Era1Id, expected_file_name: &str) { let actual_file_name = id.to_file_name(); assert_eq!(actual_file_name, expected_file_name); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/era/src/test_utils.rs
crates/era/src/test_utils.rs
//! Utilities helpers to create era data structures for testing purposes. use crate::{ consensus_types::{CompressedBeaconState, CompressedSignedBeaconBlock}, execution_types::{ BlockTuple, CompressedBody, CompressedHeader, CompressedReceipts, TotalDifficulty, }, }; use alloy_consensus::{Header, ReceiptWithBloom}; use alloy_primitives::{Address, BlockNumber, Bytes, Log, LogData, B256, B64, U256}; use reth_ethereum_primitives::{Receipt, TxType}; // Helper function to create a test header pub(crate) fn create_header() -> Header { Header { parent_hash: B256::default(), ommers_hash: B256::default(), beneficiary: Address::default(), state_root: B256::default(), transactions_root: B256::default(), receipts_root: B256::default(), logs_bloom: Default::default(), difficulty: U256::from(123456u64), number: 100, gas_limit: 5000000, gas_used: 21000, timestamp: 1609459200, extra_data: Bytes::default(), mix_hash: B256::default(), nonce: B64::default(), base_fee_per_gas: Some(10), withdrawals_root: Some(B256::default()), blob_gas_used: None, excess_blob_gas: None, parent_beacon_block_root: None, requests_hash: None, } } // Helper function to create a test receipt with customizable parameters pub(crate) fn create_test_receipt( tx_type: TxType, success: bool, cumulative_gas_used: u64, log_count: usize, ) -> Receipt { let mut logs = Vec::new(); for i in 0..log_count { let address_byte = (i + 1) as u8; let topic_byte = (i + 10) as u8; let data_byte = (i + 100) as u8; logs.push(Log { address: Address::from([address_byte; 20]), data: LogData::new_unchecked( vec![B256::from([topic_byte; 32]), B256::from([topic_byte + 1; 32])], alloy_primitives::Bytes::from(vec![data_byte, data_byte + 1, data_byte + 2]), ), }); } Receipt { tx_type, success, cumulative_gas_used, logs } } // Helper function to create a list of test receipts with different characteristics pub(crate) fn create_test_receipts() -> Vec<Receipt> { vec![ // Legacy transaction, successful, no logs create_test_receipt(TxType::Legacy, true, 21000, 0), // EIP-2930 transaction, failed, one log create_test_receipt(TxType::Eip2930, false, 42000, 1), // EIP-1559 transaction, successful, multiple logs create_test_receipt(TxType::Eip1559, true, 63000, 3), // EIP-4844 transaction, successful, two logs create_test_receipt(TxType::Eip4844, true, 84000, 2), // EIP-7702 transaction, failed, no logs create_test_receipt(TxType::Eip7702, false, 105000, 0), ] } pub(crate) fn create_test_receipt_with_bloom( tx_type: TxType, success: bool, cumulative_gas_used: u64, log_count: usize, ) -> ReceiptWithBloom { let receipt = create_test_receipt(tx_type, success, cumulative_gas_used, log_count); ReceiptWithBloom { receipt: receipt.into(), logs_bloom: Default::default() } } // Helper function to create a sample block tuple pub(crate) fn create_sample_block(data_size: usize) -> BlockTuple { // Create a compressed header with very sample data - not compressed for simplicity let header_data = vec![0xAA; data_size]; let header = CompressedHeader::new(header_data); // Create a compressed body with very sample data - not compressed for simplicity let body_data = vec![0xBB; data_size * 2]; let body = CompressedBody::new(body_data); // Create compressed receipts with very sample data - not compressed for simplicity let receipts_data = vec![0xCC; data_size]; let receipts = CompressedReceipts::new(receipts_data); let difficulty = TotalDifficulty::new(U256::from(data_size)); // Create and return the block tuple BlockTuple::new(header, body, receipts, difficulty) } // Helper function to create a test block with compressed data pub(crate) fn create_test_block_with_compressed_data(number: BlockNumber) -> BlockTuple { use alloy_consensus::{BlockBody, Header}; use alloy_eips::eip4895::Withdrawals; use alloy_primitives::{Address, Bytes, B256, B64, U256}; // Create test header let header = Header { parent_hash: B256::default(), ommers_hash: B256::default(), beneficiary: Address::default(), state_root: B256::default(), transactions_root: B256::default(), receipts_root: B256::default(), logs_bloom: Default::default(), difficulty: U256::from(number * 1000), number, gas_limit: 5000000, gas_used: 21000, timestamp: 1609459200 + number, extra_data: Bytes::default(), mix_hash: B256::default(), nonce: B64::default(), base_fee_per_gas: Some(10), withdrawals_root: Some(B256::default()), blob_gas_used: None, excess_blob_gas: None, parent_beacon_block_root: None, requests_hash: None, }; // Create test body let body: BlockBody<Bytes> = BlockBody { transactions: vec![Bytes::from(vec![(number % 256) as u8; 10])], ommers: vec![], withdrawals: Some(Withdrawals(vec![])), }; // Create test receipt list with bloom let receipts_list: Vec<ReceiptWithBloom> = vec![create_test_receipt_with_bloom( reth_ethereum_primitives::TxType::Legacy, true, 21000, 0, )]; // Compressed test compressed let compressed_header = CompressedHeader::from_header(&header).unwrap(); let compressed_body = CompressedBody::from_body(&body).unwrap(); let compressed_receipts = CompressedReceipts::from_encodable_list(&receipts_list).unwrap(); let total_difficulty = TotalDifficulty::new(U256::from(number * 1000)); BlockTuple::new(compressed_header, compressed_body, compressed_receipts, total_difficulty) } /// Helper function to create a simple beacon block pub(crate) fn create_beacon_block(data_size: usize) -> CompressedSignedBeaconBlock { let block_data = vec![0xAA; data_size]; CompressedSignedBeaconBlock::new(block_data) } /// Helper function to create a simple beacon state pub(crate) fn create_beacon_state(data_size: usize) -> CompressedBeaconState { let state_data = vec![0xBB; data_size]; CompressedBeaconState::new(state_data) }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/era/src/era1_file.rs
crates/era/src/era1_file.rs
//! Represents a complete Era1 file //! //! The structure of an Era1 file follows the specification: //! `Version | block-tuple* | other-entries* | Accumulator | BlockIndex` //! //! See also <https://github.com/eth-clients/e2store-format-specs/blob/main/formats/era1.md>. use crate::{ e2s_file::{E2StoreReader, E2StoreWriter}, e2s_types::{E2sError, Entry, IndexEntry, Version}, era1_types::{BlockIndex, Era1Group, Era1Id, BLOCK_INDEX}, era_file_ops::{EraFileFormat, FileReader, StreamReader, StreamWriter}, execution_types::{ self, Accumulator, BlockTuple, CompressedBody, CompressedHeader, CompressedReceipts, TotalDifficulty, MAX_BLOCKS_PER_ERA1, }, }; use alloy_primitives::BlockNumber; use std::{ collections::VecDeque, fs::File, io::{Read, Seek, Write}, }; /// Era1 file interface #[derive(Debug)] pub struct Era1File { /// Version record, must be the first record in the file pub version: Version, /// Main content group of the Era1 file pub group: Era1Group, /// File identifier pub id: Era1Id, } impl EraFileFormat for Era1File { type EraGroup = Era1Group; type Id = Era1Id; /// Create a new [`Era1File`] fn new(group: Era1Group, id: Era1Id) -> Self { Self { version: Version, group, id } } fn version(&self) -> &Version { &self.version } fn group(&self) -> &Self::EraGroup { &self.group } fn id(&self) -> &Self::Id { &self.id } } impl Era1File { /// Get a block by its number, if present in this file pub fn get_block_by_number(&self, number: BlockNumber) -> Option<&BlockTuple> { let index = (number - self.group.block_index.starting_number()) as usize; (index < self.group.blocks.len()).then(|| &self.group.blocks[index]) } /// Get the range of block numbers contained in this file pub fn block_range(&self) -> std::ops::RangeInclusive<BlockNumber> { let start = self.group.block_index.starting_number(); let end = start + (self.group.blocks.len() as u64) - 1; start..=end } /// Check if this file contains a specific block number pub fn contains_block(&self, number: BlockNumber) -> bool { self.block_range().contains(&number) } } /// Reader for Era1 files that builds on top of [`E2StoreReader`] #[derive(Debug)] pub struct Era1Reader<R: Read> { reader: E2StoreReader<R>, } /// An iterator of [`BlockTuple`] streaming from [`E2StoreReader`]. #[derive(Debug)] pub struct BlockTupleIterator<R: Read> { reader: E2StoreReader<R>, headers: VecDeque<CompressedHeader>, bodies: VecDeque<CompressedBody>, receipts: VecDeque<CompressedReceipts>, difficulties: VecDeque<TotalDifficulty>, other_entries: Vec<Entry>, accumulator: Option<Accumulator>, block_index: Option<BlockIndex>, } impl<R: Read> BlockTupleIterator<R> { fn new(reader: E2StoreReader<R>) -> Self { Self { reader, headers: Default::default(), bodies: Default::default(), receipts: Default::default(), difficulties: Default::default(), other_entries: Default::default(), accumulator: None, block_index: None, } } } impl<R: Read + Seek> Iterator for BlockTupleIterator<R> { type Item = Result<BlockTuple, E2sError>; fn next(&mut self) -> Option<Self::Item> { self.next_result().transpose() } } impl<R: Read + Seek> BlockTupleIterator<R> { fn next_result(&mut self) -> Result<Option<BlockTuple>, E2sError> { loop { let Some(entry) = self.reader.read_next_entry()? else { return Ok(None); }; match entry.entry_type { execution_types::COMPRESSED_HEADER => { self.headers.push_back(CompressedHeader::from_entry(&entry)?); } execution_types::COMPRESSED_BODY => { self.bodies.push_back(CompressedBody::from_entry(&entry)?); } execution_types::COMPRESSED_RECEIPTS => { self.receipts.push_back(CompressedReceipts::from_entry(&entry)?); } execution_types::TOTAL_DIFFICULTY => { self.difficulties.push_back(TotalDifficulty::from_entry(&entry)?); } execution_types::ACCUMULATOR => { if self.accumulator.is_some() { return Err(E2sError::Ssz("Multiple accumulator entries found".to_string())); } self.accumulator = Some(Accumulator::from_entry(&entry)?); } BLOCK_INDEX => { if self.block_index.is_some() { return Err(E2sError::Ssz("Multiple block index entries found".to_string())); } self.block_index = Some(BlockIndex::from_entry(&entry)?); } _ => { self.other_entries.push(entry); } } if !self.headers.is_empty() && !self.bodies.is_empty() && !self.receipts.is_empty() && !self.difficulties.is_empty() { let header = self.headers.pop_front().unwrap(); let body = self.bodies.pop_front().unwrap(); let receipt = self.receipts.pop_front().unwrap(); let difficulty = self.difficulties.pop_front().unwrap(); return Ok(Some(BlockTuple::new(header, body, receipt, difficulty))); } } } } impl<R: Read + Seek> StreamReader<R> for Era1Reader<R> { type File = Era1File; type Iterator = BlockTupleIterator<R>; /// Create a new [`Era1Reader`] fn new(reader: R) -> Self { Self { reader: E2StoreReader::new(reader) } } /// Returns an iterator of [`BlockTuple`] streaming from `reader`. fn iter(self) -> BlockTupleIterator<R> { BlockTupleIterator::new(self.reader) } fn read(self, network_name: String) -> Result<Self::File, E2sError> { self.read_and_assemble(network_name) } } impl<R: Read + Seek> Era1Reader<R> { /// Reads and parses an Era1 file from the underlying reader, assembling all components /// into a complete [`Era1File`] with an [`Era1Id`] that includes the provided network name. pub fn read_and_assemble(mut self, network_name: String) -> Result<Era1File, E2sError> { // Validate version entry let _version_entry = match self.reader.read_version()? { Some(entry) if entry.is_version() => entry, Some(_) => return Err(E2sError::Ssz("First entry is not a Version entry".to_string())), None => return Err(E2sError::Ssz("Empty Era1 file".to_string())), }; let mut iter = self.iter(); let blocks = (&mut iter).collect::<Result<Vec<_>, _>>()?; let BlockTupleIterator { headers, bodies, receipts, difficulties, other_entries, accumulator, block_index, .. } = iter; // Ensure we have matching counts for block components if headers.len() != bodies.len() || headers.len() != receipts.len() || headers.len() != difficulties.len() { return Err(E2sError::Ssz(format!( "Mismatched block component counts: headers={}, bodies={}, receipts={}, difficulties={}", headers.len(), bodies.len(), receipts.len(), difficulties.len() ))); } let accumulator = accumulator .ok_or_else(|| E2sError::Ssz("Era1 file missing accumulator entry".to_string()))?; let block_index = block_index .ok_or_else(|| E2sError::Ssz("Era1 file missing block index entry".to_string()))?; let mut group = Era1Group::new(blocks, accumulator, block_index.clone()); // Add other entries for entry in other_entries { group.add_entry(entry); } let id = Era1Id::new( network_name, block_index.starting_number(), block_index.offsets().len() as u32, ); Ok(Era1File::new(group, id)) } } impl FileReader for Era1Reader<File> {} /// Writer for Era1 files that builds on top of [`E2StoreWriter`] #[derive(Debug)] pub struct Era1Writer<W: Write> { writer: E2StoreWriter<W>, has_written_version: bool, has_written_blocks: bool, has_written_accumulator: bool, has_written_block_index: bool, } impl<W: Write> StreamWriter<W> for Era1Writer<W> { type File = Era1File; /// Create a new [`Era1Writer`] fn new(writer: W) -> Self { Self { writer: E2StoreWriter::new(writer), has_written_version: false, has_written_blocks: false, has_written_accumulator: false, has_written_block_index: false, } } /// Write the version entry fn write_version(&mut self) -> Result<(), E2sError> { if self.has_written_version { return Ok(()); } self.writer.write_version()?; self.has_written_version = true; Ok(()) } /// Write a complete [`Era1File`] to the underlying writer fn write_file(&mut self, era1_file: &Era1File) -> Result<(), E2sError> { // Write version self.write_version()?; // Ensure blocks are written before other entries if era1_file.group.blocks.len() > MAX_BLOCKS_PER_ERA1 { return Err(E2sError::Ssz("Era1 file cannot contain more than 8192 blocks".to_string())); } // Write all blocks for block in &era1_file.group.blocks { self.write_block(block)?; } // Write other entries for entry in &era1_file.group.other_entries { self.writer.write_entry(entry)?; } // Write accumulator self.write_accumulator(&era1_file.group.accumulator)?; // Write block index self.write_block_index(&era1_file.group.block_index)?; // Flush the writer self.writer.flush()?; Ok(()) } /// Flush any buffered data to the underlying writer fn flush(&mut self) -> Result<(), E2sError> { self.writer.flush() } } impl<W: Write> Era1Writer<W> { /// Write a single block tuple pub fn write_block( &mut self, block_tuple: &crate::execution_types::BlockTuple, ) -> Result<(), E2sError> { if !self.has_written_version { self.write_version()?; } if self.has_written_accumulator || self.has_written_block_index { return Err(E2sError::Ssz( "Cannot write blocks after accumulator or block index".to_string(), )); } // Write header let header_entry = block_tuple.header.to_entry(); self.writer.write_entry(&header_entry)?; // Write body let body_entry = block_tuple.body.to_entry(); self.writer.write_entry(&body_entry)?; // Write receipts let receipts_entry = block_tuple.receipts.to_entry(); self.writer.write_entry(&receipts_entry)?; // Write difficulty let difficulty_entry = block_tuple.total_difficulty.to_entry(); self.writer.write_entry(&difficulty_entry)?; self.has_written_blocks = true; Ok(()) } /// Write the block index pub fn write_block_index(&mut self, block_index: &BlockIndex) -> Result<(), E2sError> { if !self.has_written_version { self.write_version()?; } if self.has_written_block_index { return Err(E2sError::Ssz("Block index already written".to_string())); } let block_index_entry = block_index.to_entry(); self.writer.write_entry(&block_index_entry)?; self.has_written_block_index = true; Ok(()) } /// Write the accumulator pub fn write_accumulator(&mut self, accumulator: &Accumulator) -> Result<(), E2sError> { if !self.has_written_version { self.write_version()?; } if self.has_written_accumulator { return Err(E2sError::Ssz("Accumulator already written".to_string())); } if self.has_written_block_index { return Err(E2sError::Ssz("Cannot write accumulator after block index".to_string())); } let accumulator_entry = accumulator.to_entry(); self.writer.write_entry(&accumulator_entry)?; self.has_written_accumulator = true; Ok(()) } } #[cfg(test)] mod tests { use super::*; use crate::{ era_file_ops::FileWriter, execution_types::{ Accumulator, BlockTuple, CompressedBody, CompressedHeader, CompressedReceipts, TotalDifficulty, }, }; use alloy_primitives::{B256, U256}; use std::io::Cursor; use tempfile::tempdir; // Helper to create a sample block tuple for testing fn create_test_block(number: BlockNumber, data_size: usize) -> BlockTuple { let header_data = vec![(number % 256) as u8; data_size]; let header = CompressedHeader::new(header_data); let body_data = vec![((number + 1) % 256) as u8; data_size * 2]; let body = CompressedBody::new(body_data); let receipts_data = vec![((number + 2) % 256) as u8; data_size]; let receipts = CompressedReceipts::new(receipts_data); let difficulty = TotalDifficulty::new(U256::from(number * 1000)); BlockTuple::new(header, body, receipts, difficulty) } // Helper to create a sample Era1File for testing fn create_test_era1_file( start_block: BlockNumber, block_count: usize, network: &str, ) -> Era1File { // Create blocks let mut blocks = Vec::with_capacity(block_count); for i in 0..block_count { let block_num = start_block + i as u64; blocks.push(create_test_block(block_num, 32)); } let accumulator = Accumulator::new(B256::from([0xAA; 32])); let mut offsets = Vec::with_capacity(block_count); for i in 0..block_count { offsets.push(i as i64 * 100); } let block_index = BlockIndex::new(start_block, offsets); let group = Era1Group::new(blocks, accumulator, block_index); let id = Era1Id::new(network, start_block, block_count as u32); Era1File::new(group, id) } #[test] fn test_era1_roundtrip_memory() -> Result<(), E2sError> { // Create a test Era1File let start_block = 1000; let era1_file = create_test_era1_file(1000, 5, "testnet"); // Write to memory buffer let mut buffer = Vec::new(); { let mut writer = Era1Writer::new(&mut buffer); writer.write_file(&era1_file)?; } // Read back from memory buffer let reader = Era1Reader::new(Cursor::new(&buffer)); let read_era1 = reader.read("testnet".to_string())?; // Verify core properties assert_eq!(read_era1.id.network_name, "testnet"); assert_eq!(read_era1.id.start_block, 1000); assert_eq!(read_era1.id.block_count, 5); assert_eq!(read_era1.group.blocks.len(), 5); // Verify block properties assert_eq!(read_era1.group.blocks[0].total_difficulty.value, U256::from(1000 * 1000)); assert_eq!(read_era1.group.blocks[1].total_difficulty.value, U256::from(1001 * 1000)); // Verify block data assert_eq!(read_era1.group.blocks[0].header.data, vec![(start_block % 256) as u8; 32]); assert_eq!(read_era1.group.blocks[0].body.data, vec![((start_block + 1) % 256) as u8; 64]); assert_eq!( read_era1.group.blocks[0].receipts.data, vec![((start_block + 2) % 256) as u8; 32] ); // Verify block access methods assert!(read_era1.contains_block(1000)); assert!(read_era1.contains_block(1004)); assert!(!read_era1.contains_block(999)); assert!(!read_era1.contains_block(1005)); let block_1002 = read_era1.get_block_by_number(1002); assert!(block_1002.is_some()); assert_eq!(block_1002.unwrap().header.data, vec![((start_block + 2) % 256) as u8; 32]); Ok(()) } #[test] fn test_era1_roundtrip_file() -> Result<(), E2sError> { // Create a temporary directory let temp_dir = tempdir().expect("Failed to create temp directory"); let file_path = temp_dir.path().join("test_roundtrip.era1"); // Create and write `Era1File` to disk let era1_file = create_test_era1_file(2000, 3, "mainnet"); Era1Writer::create(&file_path, &era1_file)?; // Read it back let read_era1 = Era1Reader::open(&file_path, "mainnet")?; // Verify core properties assert_eq!(read_era1.id.network_name, "mainnet"); assert_eq!(read_era1.id.start_block, 2000); assert_eq!(read_era1.id.block_count, 3); assert_eq!(read_era1.group.blocks.len(), 3); // Verify blocks for i in 0..3 { let block_num = 2000 + i as u64; let block = read_era1.get_block_by_number(block_num); assert!(block.is_some()); assert_eq!(block.unwrap().header.data, vec![block_num as u8; 32]); } Ok(()) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/era/src/execution_types.rs
crates/era/src/execution_types.rs
//! Execution layer specific types for `.era1` files //! //! Contains implementations for compressed execution layer data structures: //! - [`CompressedHeader`] - Block header //! - [`CompressedBody`] - Block body //! - [`CompressedReceipts`] - Block receipts //! - [`TotalDifficulty`] - Block total difficulty //! //! These types use Snappy compression to match the specification. //! //! See also <https://github.com/eth-clients/e2store-format-specs/blob/main/formats/era1.md> //! //! # Examples //! //! ## [`CompressedHeader`] //! //! ```rust //! use alloy_consensus::Header; //! use reth_era::{execution_types::CompressedHeader, DecodeCompressed}; //! //! let header = Header { number: 100, ..Default::default() }; //! // Compress the header: rlp encoding and Snappy compression //! let compressed = CompressedHeader::from_header(&header)?; //! // Decompressed and decode typed compressed header //! let decoded_header: Header = compressed.decode_header()?; //! assert_eq!(decoded_header.number, 100); //! # Ok::<(), reth_era::e2s_types::E2sError>(()) //! ``` //! //! ## [`CompressedBody`] //! //! ```rust //! use alloy_consensus::{BlockBody, Header}; //! use alloy_primitives::Bytes; //! use reth_era::{execution_types::CompressedBody, DecodeCompressed}; //! use reth_ethereum_primitives::TransactionSigned; //! //! let body: BlockBody<Bytes> = BlockBody { //! transactions: vec![Bytes::from(vec![1, 2, 3])], //! ommers: vec![], //! withdrawals: None, //! }; //! // Compress the body: rlp encoding and snappy compression //! let compressed_body = CompressedBody::from_body(&body)?; //! // Decode back to typed body by decompressing and decoding //! let decoded_body: alloy_consensus::BlockBody<alloy_primitives::Bytes> = //! compressed_body.decode()?; //! assert_eq!(decoded_body.transactions.len(), 1); //! # Ok::<(), reth_era::e2s_types::E2sError>(()) //! ``` //! //! ## [`CompressedReceipts`] //! //! ```rust //! use alloy_consensus::ReceiptWithBloom; //! use reth_era::{execution_types::CompressedReceipts, DecodeCompressed}; //! use reth_ethereum_primitives::{Receipt, TxType}; //! //! let receipt = Receipt { //! tx_type: TxType::Legacy, //! success: true, //! cumulative_gas_used: 21000, //! logs: vec![], //! }; //! let receipt_with_bloom = ReceiptWithBloom { receipt, logs_bloom: Default::default() }; //! // Compress the receipt: rlp encoding and snappy compression //! let compressed_receipt_data = CompressedReceipts::from_encodable(&receipt_with_bloom)?; //! // Get raw receipt by decoding and decompressing compressed and encoded receipt //! let decompressed_receipt = compressed_receipt_data.decode::<ReceiptWithBloom>()?; //! assert_eq!(decompressed_receipt.receipt.cumulative_gas_used, 21000); //! # Ok::<(), reth_era::e2s_types::E2sError>(()) //! `````` use crate::{ e2s_types::{E2sError, Entry}, DecodeCompressed, }; use alloy_consensus::{Block, BlockBody, Header}; use alloy_primitives::{B256, U256}; use alloy_rlp::{Decodable, Encodable}; use snap::{read::FrameDecoder, write::FrameEncoder}; use std::{ io::{Read, Write}, marker::PhantomData, }; // Era1-specific constants /// `CompressedHeader` record type pub const COMPRESSED_HEADER: [u8; 2] = [0x03, 0x00]; /// `CompressedBody` record type pub const COMPRESSED_BODY: [u8; 2] = [0x04, 0x00]; /// `CompressedReceipts` record type pub const COMPRESSED_RECEIPTS: [u8; 2] = [0x05, 0x00]; /// `TotalDifficulty` record type pub const TOTAL_DIFFICULTY: [u8; 2] = [0x06, 0x00]; /// `Accumulator` record type pub const ACCUMULATOR: [u8; 2] = [0x07, 0x00]; /// Maximum number of blocks in an Era1 file, limited by accumulator size pub const MAX_BLOCKS_PER_ERA1: usize = 8192; /// Generic codec for Snappy-compressed RLP data #[derive(Debug, Clone, Default)] pub struct SnappyRlpCodec<T> { _phantom: PhantomData<T>, } impl<T> SnappyRlpCodec<T> { /// Create a new codec for the given type pub const fn new() -> Self { Self { _phantom: PhantomData } } } impl<T: Decodable> SnappyRlpCodec<T> { /// Decode compressed data into the target type pub fn decode(&self, compressed_data: &[u8]) -> Result<T, E2sError> { let mut decoder = FrameDecoder::new(compressed_data); let mut decompressed = Vec::new(); Read::read_to_end(&mut decoder, &mut decompressed).map_err(|e| { E2sError::SnappyDecompression(format!("Failed to decompress data: {e}")) })?; let mut slice = decompressed.as_slice(); T::decode(&mut slice).map_err(|e| E2sError::Rlp(format!("Failed to decode RLP data: {e}"))) } } impl<T: Encodable> SnappyRlpCodec<T> { /// Encode data into compressed format pub fn encode(&self, data: &T) -> Result<Vec<u8>, E2sError> { let mut rlp_data = Vec::new(); data.encode(&mut rlp_data); let mut compressed = Vec::new(); { let mut encoder = FrameEncoder::new(&mut compressed); Write::write_all(&mut encoder, &rlp_data).map_err(|e| { E2sError::SnappyCompression(format!("Failed to compress data: {e}")) })?; encoder.flush().map_err(|e| { E2sError::SnappyCompression(format!("Failed to flush encoder: {e}")) })?; } Ok(compressed) } } /// Compressed block header using `snappyFramed(rlp(header))` #[derive(Debug, Clone)] pub struct CompressedHeader { /// The compressed data pub data: Vec<u8>, } impl CompressedHeader { /// Create a new [`CompressedHeader`] from compressed data pub const fn new(data: Vec<u8>) -> Self { Self { data } } /// Create from RLP-encoded header by compressing it with Snappy pub fn from_rlp(rlp_data: &[u8]) -> Result<Self, E2sError> { let mut compressed = Vec::new(); { let mut encoder = FrameEncoder::new(&mut compressed); Write::write_all(&mut encoder, rlp_data).map_err(|e| { E2sError::SnappyCompression(format!("Failed to compress header: {e}")) })?; encoder.flush().map_err(|e| { E2sError::SnappyCompression(format!("Failed to flush encoder: {e}")) })?; } Ok(Self { data: compressed }) } /// Decompress to get the original RLP-encoded header pub fn decompress(&self) -> Result<Vec<u8>, E2sError> { let mut decoder = FrameDecoder::new(self.data.as_slice()); let mut decompressed = Vec::new(); Read::read_to_end(&mut decoder, &mut decompressed).map_err(|e| { E2sError::SnappyDecompression(format!("Failed to decompress header: {e}")) })?; Ok(decompressed) } /// Convert to an [`Entry`] pub fn to_entry(&self) -> Entry { Entry::new(COMPRESSED_HEADER, self.data.clone()) } /// Create from an [`Entry`] pub fn from_entry(entry: &Entry) -> Result<Self, E2sError> { if entry.entry_type != COMPRESSED_HEADER { return Err(E2sError::Ssz(format!( "Invalid entry type for CompressedHeader: expected {:02x}{:02x}, got {:02x}{:02x}", COMPRESSED_HEADER[0], COMPRESSED_HEADER[1], entry.entry_type[0], entry.entry_type[1] ))); } Ok(Self { data: entry.data.clone() }) } /// Decode this compressed header into an `alloy_consensus::Header` pub fn decode_header(&self) -> Result<Header, E2sError> { self.decode() } /// Create a [`CompressedHeader`] from a header pub fn from_header<H: Encodable>(header: &H) -> Result<Self, E2sError> { let encoder = SnappyRlpCodec::new(); let compressed = encoder.encode(header)?; Ok(Self::new(compressed)) } } impl DecodeCompressed for CompressedHeader { fn decode<T: Decodable>(&self) -> Result<T, E2sError> { let decoder = SnappyRlpCodec::<T>::new(); decoder.decode(&self.data) } } /// Compressed block body using `snappyFramed(rlp(body))` #[derive(Debug, Clone)] pub struct CompressedBody { /// The compressed data pub data: Vec<u8>, } impl CompressedBody { /// Create a new [`CompressedBody`] from compressed data pub const fn new(data: Vec<u8>) -> Self { Self { data } } /// Create from RLP-encoded body by compressing it with Snappy pub fn from_rlp(rlp_data: &[u8]) -> Result<Self, E2sError> { let mut compressed = Vec::new(); { let mut encoder = FrameEncoder::new(&mut compressed); Write::write_all(&mut encoder, rlp_data).map_err(|e| { E2sError::SnappyCompression(format!("Failed to compress header: {e}")) })?; encoder.flush().map_err(|e| { E2sError::SnappyCompression(format!("Failed to flush encoder: {e}")) })?; } Ok(Self { data: compressed }) } /// Decompress to get the original RLP-encoded body pub fn decompress(&self) -> Result<Vec<u8>, E2sError> { let mut decoder = FrameDecoder::new(self.data.as_slice()); let mut decompressed = Vec::new(); Read::read_to_end(&mut decoder, &mut decompressed).map_err(|e| { E2sError::SnappyDecompression(format!("Failed to decompress body: {e}")) })?; Ok(decompressed) } /// Convert to an [`Entry`] pub fn to_entry(&self) -> Entry { Entry::new(COMPRESSED_BODY, self.data.clone()) } /// Create from an [`Entry`] pub fn from_entry(entry: &Entry) -> Result<Self, E2sError> { if entry.entry_type != COMPRESSED_BODY { return Err(E2sError::Ssz(format!( "Invalid entry type for CompressedBody: expected {:02x}{:02x}, got {:02x}{:02x}", COMPRESSED_BODY[0], COMPRESSED_BODY[1], entry.entry_type[0], entry.entry_type[1] ))); } Ok(Self { data: entry.data.clone() }) } /// Decode this [`CompressedBody`] into an `alloy_consensus::BlockBody` pub fn decode_body<T: Decodable, H: Decodable>(&self) -> Result<BlockBody<T, H>, E2sError> { let decompressed = self.decompress()?; Self::decode_body_from_decompressed(&decompressed) } /// Decode decompressed body data into an `alloy_consensus::BlockBody` pub fn decode_body_from_decompressed<T: Decodable, H: Decodable>( data: &[u8], ) -> Result<BlockBody<T, H>, E2sError> { alloy_rlp::decode_exact::<BlockBody<T, H>>(data) .map_err(|e| E2sError::Rlp(format!("Failed to decode RLP data: {e}"))) } /// Create a [`CompressedBody`] from a block body (e.g. `alloy_consensus::BlockBody`) pub fn from_body<B: Encodable>(body: &B) -> Result<Self, E2sError> { let encoder = SnappyRlpCodec::new(); let compressed = encoder.encode(body)?; Ok(Self::new(compressed)) } } impl DecodeCompressed for CompressedBody { fn decode<T: Decodable>(&self) -> Result<T, E2sError> { let decoder = SnappyRlpCodec::<T>::new(); decoder.decode(&self.data) } } /// Compressed receipts using snappyFramed(rlp(receipts)) #[derive(Debug, Clone)] pub struct CompressedReceipts { /// The compressed data pub data: Vec<u8>, } impl CompressedReceipts { /// Create a new [`CompressedReceipts`] from compressed data pub const fn new(data: Vec<u8>) -> Self { Self { data } } /// Create from RLP-encoded receipts by compressing it with Snappy pub fn from_rlp(rlp_data: &[u8]) -> Result<Self, E2sError> { let mut compressed = Vec::new(); { let mut encoder = FrameEncoder::new(&mut compressed); Write::write_all(&mut encoder, rlp_data).map_err(|e| { E2sError::SnappyCompression(format!("Failed to compress header: {e}")) })?; encoder.flush().map_err(|e| { E2sError::SnappyCompression(format!("Failed to flush encoder: {e}")) })?; } Ok(Self { data: compressed }) } /// Decompress to get the original RLP-encoded receipts pub fn decompress(&self) -> Result<Vec<u8>, E2sError> { let mut decoder = FrameDecoder::new(self.data.as_slice()); let mut decompressed = Vec::new(); Read::read_to_end(&mut decoder, &mut decompressed).map_err(|e| { E2sError::SnappyDecompression(format!("Failed to decompress receipts: {e}")) })?; Ok(decompressed) } /// Convert to an [`Entry`] pub fn to_entry(&self) -> Entry { Entry::new(COMPRESSED_RECEIPTS, self.data.clone()) } /// Create from an [`Entry`] pub fn from_entry(entry: &Entry) -> Result<Self, E2sError> { if entry.entry_type != COMPRESSED_RECEIPTS { return Err(E2sError::Ssz(format!( "Invalid entry type for CompressedReceipts: expected {:02x}{:02x}, got {:02x}{:02x}", COMPRESSED_RECEIPTS[0], COMPRESSED_RECEIPTS[1], entry.entry_type[0], entry.entry_type[1] ))); } Ok(Self { data: entry.data.clone() }) } /// Decode this [`CompressedReceipts`] into the given type pub fn decode<T: Decodable>(&self) -> Result<T, E2sError> { let decoder = SnappyRlpCodec::<T>::new(); decoder.decode(&self.data) } /// Create [`CompressedReceipts`] from an encodable type pub fn from_encodable<T: Encodable>(data: &T) -> Result<Self, E2sError> { let encoder = SnappyRlpCodec::<T>::new(); let compressed = encoder.encode(data)?; Ok(Self::new(compressed)) } /// Encode a list of receipts to RLP format pub fn encode_receipts_to_rlp<T: Encodable>(receipts: &[T]) -> Result<Vec<u8>, E2sError> { let mut rlp_data = Vec::new(); alloy_rlp::encode_list(receipts, &mut rlp_data); Ok(rlp_data) } /// Encode and compress a list of receipts pub fn from_encodable_list<T: Encodable>(receipts: &[T]) -> Result<Self, E2sError> { let rlp_data = Self::encode_receipts_to_rlp(receipts)?; Self::from_rlp(&rlp_data) } } impl DecodeCompressed for CompressedReceipts { fn decode<T: Decodable>(&self) -> Result<T, E2sError> { let decoder = SnappyRlpCodec::<T>::new(); decoder.decode(&self.data) } } /// Total difficulty for a block #[derive(Debug, Clone)] pub struct TotalDifficulty { /// The total difficulty as U256 pub value: U256, } impl TotalDifficulty { /// Create a new [`TotalDifficulty`] from a U256 value pub const fn new(value: U256) -> Self { Self { value } } /// Convert to an [`Entry`] pub fn to_entry(&self) -> Entry { let mut data = [0u8; 32]; let be_bytes = self.value.to_be_bytes_vec(); if be_bytes.len() <= 32 { data[32 - be_bytes.len()..].copy_from_slice(&be_bytes); } else { data.copy_from_slice(&be_bytes[be_bytes.len() - 32..]); } Entry::new(TOTAL_DIFFICULTY, data.to_vec()) } /// Create from an [`Entry`] pub fn from_entry(entry: &Entry) -> Result<Self, E2sError> { if entry.entry_type != TOTAL_DIFFICULTY { return Err(E2sError::Ssz(format!( "Invalid entry type for TotalDifficulty: expected {:02x}{:02x}, got {:02x}{:02x}", TOTAL_DIFFICULTY[0], TOTAL_DIFFICULTY[1], entry.entry_type[0], entry.entry_type[1] ))); } if entry.data.len() != 32 { return Err(E2sError::Ssz(format!( "Invalid data length for TotalDifficulty: expected 32, got {}", entry.data.len() ))); } // Convert 32-byte array to U256 let value = U256::from_be_slice(&entry.data); Ok(Self { value }) } } /// Accumulator is computed by constructing an SSZ list of header-records /// and calculating the `hash_tree_root` #[derive(Debug, Clone)] pub struct Accumulator { /// The accumulator root hash pub root: B256, } impl Accumulator { /// Create a new [`Accumulator`] from a root hash pub const fn new(root: B256) -> Self { Self { root } } /// Convert to an [`Entry`] pub fn to_entry(&self) -> Entry { Entry::new(ACCUMULATOR, self.root.to_vec()) } /// Create from an [`Entry`] pub fn from_entry(entry: &Entry) -> Result<Self, E2sError> { if entry.entry_type != ACCUMULATOR { return Err(E2sError::Ssz(format!( "Invalid entry type for Accumulator: expected {:02x}{:02x}, got {:02x}{:02x}", ACCUMULATOR[0], ACCUMULATOR[1], entry.entry_type[0], entry.entry_type[1] ))); } if entry.data.len() != 32 { return Err(E2sError::Ssz(format!( "Invalid data length for Accumulator: expected 32, got {}", entry.data.len() ))); } let mut root = [0u8; 32]; root.copy_from_slice(&entry.data); Ok(Self { root: B256::from(root) }) } } /// A block tuple in an Era1 file, containing all components for a single block #[derive(Debug, Clone)] pub struct BlockTuple { /// Compressed block header pub header: CompressedHeader, /// Compressed block body pub body: CompressedBody, /// Compressed receipts pub receipts: CompressedReceipts, /// Total difficulty pub total_difficulty: TotalDifficulty, } impl BlockTuple { /// Create a new [`BlockTuple`] pub const fn new( header: CompressedHeader, body: CompressedBody, receipts: CompressedReceipts, total_difficulty: TotalDifficulty, ) -> Self { Self { header, body, receipts, total_difficulty } } /// Convert to an `alloy_consensus::Block` pub fn to_alloy_block<T: Decodable>(&self) -> Result<Block<T>, E2sError> { let header: Header = self.header.decode()?; let body: BlockBody<T> = self.body.decode()?; Ok(Block::new(header, body)) } /// Create from an `alloy_consensus::Block` pub fn from_alloy_block<T: Encodable, R: Encodable>( block: &Block<T>, receipts: &R, total_difficulty: U256, ) -> Result<Self, E2sError> { let header = CompressedHeader::from_header(&block.header)?; let body = CompressedBody::from_body(&block.body)?; let compressed_receipts = CompressedReceipts::from_encodable(receipts)?; let difficulty = TotalDifficulty::new(total_difficulty); Ok(Self::new(header, body, compressed_receipts, difficulty)) } } #[cfg(test)] mod tests { use super::*; use crate::test_utils::{create_header, create_test_receipt, create_test_receipts}; use alloy_eips::eip4895::Withdrawals; use alloy_primitives::{Bytes, U256}; use reth_ethereum_primitives::{Receipt, TxType}; #[test] fn test_header_conversion_roundtrip() { let header = create_header(); let compressed_header = CompressedHeader::from_header(&header).unwrap(); let decoded_header = compressed_header.decode_header().unwrap(); assert_eq!(header.number, decoded_header.number); assert_eq!(header.difficulty, decoded_header.difficulty); assert_eq!(header.timestamp, decoded_header.timestamp); assert_eq!(header.gas_used, decoded_header.gas_used); assert_eq!(header.parent_hash, decoded_header.parent_hash); assert_eq!(header.base_fee_per_gas, decoded_header.base_fee_per_gas); } #[test] fn test_block_body_conversion() { let block_body: BlockBody<Bytes> = BlockBody { transactions: vec![], ommers: vec![], withdrawals: None }; let compressed_body = CompressedBody::from_body(&block_body).unwrap(); let decoded_body: BlockBody<Bytes> = compressed_body.decode_body().unwrap(); assert_eq!(decoded_body.transactions.len(), 0); assert_eq!(decoded_body.ommers.len(), 0); assert_eq!(decoded_body.withdrawals, None); } #[test] fn test_total_difficulty_roundtrip() { let value = U256::from(123456789u64); let total_difficulty = TotalDifficulty::new(value); let entry = total_difficulty.to_entry(); assert_eq!(entry.entry_type, TOTAL_DIFFICULTY); let recovered = TotalDifficulty::from_entry(&entry).unwrap(); assert_eq!(recovered.value, value); } #[test] fn test_compression_roundtrip() { let rlp_data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Test header compression/decompression let compressed_header = CompressedHeader::from_rlp(&rlp_data).unwrap(); let decompressed = compressed_header.decompress().unwrap(); assert_eq!(decompressed, rlp_data); // Test body compression/decompression let compressed_body = CompressedBody::from_rlp(&rlp_data).unwrap(); let decompressed = compressed_body.decompress().unwrap(); assert_eq!(decompressed, rlp_data); // Test receipts compression/decompression let compressed_receipts = CompressedReceipts::from_rlp(&rlp_data).unwrap(); let decompressed = compressed_receipts.decompress().unwrap(); assert_eq!(decompressed, rlp_data); } #[test] fn test_block_tuple_with_data() { // Create block with transactions and withdrawals let header = create_header(); let transactions = vec![Bytes::from(vec![1, 2, 3, 4]), Bytes::from(vec![5, 6, 7, 8])]; let withdrawals = Some(Withdrawals(vec![])); let block_body = BlockBody { transactions, ommers: vec![], withdrawals }; let block = Block::new(header, block_body); let receipts: Vec<u8> = Vec::new(); let block_tuple = BlockTuple::from_alloy_block(&block, &receipts, U256::from(123456u64)).unwrap(); // Convert back to Block let decoded_block: Block<Bytes> = block_tuple.to_alloy_block().unwrap(); // Verify block components assert_eq!(decoded_block.header.number, 100); assert_eq!(decoded_block.body.transactions.len(), 2); assert_eq!(decoded_block.body.transactions[0], Bytes::from(vec![1, 2, 3, 4])); assert_eq!(decoded_block.body.transactions[1], Bytes::from(vec![5, 6, 7, 8])); assert!(decoded_block.body.withdrawals.is_some()); } #[test] fn test_single_receipt_compression_roundtrip() { let test_receipt = create_test_receipt(TxType::Eip1559, true, 21000, 2); // Compress the receipt let compressed_receipts = CompressedReceipts::from_encodable(&test_receipt).expect("Failed to compress receipt"); // Verify compression assert!(!compressed_receipts.data.is_empty()); // Decode the compressed receipt back let decoded_receipt: Receipt = compressed_receipts.decode().expect("Failed to decode compressed receipt"); // Verify that the decoded receipt matches the original assert_eq!(decoded_receipt.tx_type, test_receipt.tx_type); assert_eq!(decoded_receipt.success, test_receipt.success); assert_eq!(decoded_receipt.cumulative_gas_used, test_receipt.cumulative_gas_used); assert_eq!(decoded_receipt.logs.len(), test_receipt.logs.len()); // Verify each log for (original_log, decoded_log) in test_receipt.logs.iter().zip(decoded_receipt.logs.iter()) { assert_eq!(decoded_log.address, original_log.address); assert_eq!(decoded_log.data.topics(), original_log.data.topics()); } } #[test] fn test_receipt_list_compression() { let receipts = create_test_receipts(); // Compress the list of receipts let compressed_receipts = CompressedReceipts::from_encodable_list(&receipts) .expect("Failed to compress receipt list"); // Decode the compressed receipts back // Note: most likely the decoding for real era files will be done to reach // `Vec<ReceiptWithBloom>`` let decoded_receipts: Vec<Receipt> = compressed_receipts.decode().expect("Failed to decode compressed receipt list"); // Verify that the decoded receipts match the original assert_eq!(decoded_receipts.len(), receipts.len()); for (original, decoded) in receipts.iter().zip(decoded_receipts.iter()) { assert_eq!(decoded.tx_type, original.tx_type); assert_eq!(decoded.success, original.success); assert_eq!(decoded.cumulative_gas_used, original.cumulative_gas_used); assert_eq!(decoded.logs.len(), original.logs.len()); for (original_log, decoded_log) in original.logs.iter().zip(decoded.logs.iter()) { assert_eq!(decoded_log.address, original_log.address); assert_eq!(decoded_log.data.topics(), original_log.data.topics()); } } } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/era/src/consensus_types.rs
crates/era/src/consensus_types.rs
//! Consensus types for Era post-merge history files use crate::{ e2s_types::{E2sError, Entry}, DecodeCompressedSsz, }; use snap::{read::FrameDecoder, write::FrameEncoder}; use ssz::Decode; use std::io::{Read, Write}; /// `CompressedSignedBeaconBlock` record type: [0x01, 0x00] pub const COMPRESSED_SIGNED_BEACON_BLOCK: [u8; 2] = [0x01, 0x00]; /// `CompressedBeaconState` record type: [0x02, 0x00] pub const COMPRESSED_BEACON_STATE: [u8; 2] = [0x02, 0x00]; /// Compressed signed beacon block /// /// See also <https://github.com/status-im/nimbus-eth2/blob/stable/docs/e2store.md#compressedsignedbeaconblock>. #[derive(Debug, Clone)] pub struct CompressedSignedBeaconBlock { /// Snappy-compressed ssz-encoded `SignedBeaconBlock` pub data: Vec<u8>, } impl CompressedSignedBeaconBlock { /// Create a new [`CompressedSignedBeaconBlock`] from compressed data pub const fn new(data: Vec<u8>) -> Self { Self { data } } /// Create from ssz-encoded block by compressing it with snappy pub fn from_ssz(ssz_data: &[u8]) -> Result<Self, E2sError> { let mut compressed = Vec::new(); { let mut encoder = FrameEncoder::new(&mut compressed); Write::write_all(&mut encoder, ssz_data).map_err(|e| { E2sError::SnappyCompression(format!("Failed to compress signed beacon block: {e}")) })?; encoder.flush().map_err(|e| { E2sError::SnappyCompression(format!("Failed to flush encoder: {e}")) })?; } Ok(Self { data: compressed }) } /// Decompress to get the original ssz-encoded signed beacon block pub fn decompress(&self) -> Result<Vec<u8>, E2sError> { let mut decoder = FrameDecoder::new(self.data.as_slice()); let mut decompressed = Vec::new(); Read::read_to_end(&mut decoder, &mut decompressed).map_err(|e| { E2sError::SnappyDecompression(format!("Failed to decompress signed beacon block: {e}")) })?; Ok(decompressed) } /// Convert to an [`Entry`] pub fn to_entry(&self) -> Entry { Entry::new(COMPRESSED_SIGNED_BEACON_BLOCK, self.data.clone()) } /// Create from an [`Entry`] pub fn from_entry(entry: &Entry) -> Result<Self, E2sError> { if entry.entry_type != COMPRESSED_SIGNED_BEACON_BLOCK { return Err(E2sError::Ssz(format!( "Invalid entry type for CompressedSignedBeaconBlock: expected {:02x}{:02x}, got {:02x}{:02x}", COMPRESSED_SIGNED_BEACON_BLOCK[0], COMPRESSED_SIGNED_BEACON_BLOCK[1], entry.entry_type[0], entry.entry_type[1] ))); } Ok(Self { data: entry.data.clone() }) } /// Decode the compressed signed beacon block into ssz bytes pub fn decode_to_ssz(&self) -> Result<Vec<u8>, E2sError> { self.decompress() } } impl DecodeCompressedSsz for CompressedSignedBeaconBlock { fn decode<T: Decode>(&self) -> Result<T, E2sError> { let ssz_bytes = self.decompress()?; T::from_ssz_bytes(&ssz_bytes).map_err(|e| { E2sError::Ssz(format!("Failed to decode SSZ data into target type: {e:?}")) }) } } /// Compressed beacon state /// /// See also <https://github.com/status-im/nimbus-eth2/blob/stable/docs/e2store.md#compressedbeaconstate>. #[derive(Debug, Clone)] pub struct CompressedBeaconState { /// Snappy-compressed ssz-encoded `BeaconState` pub data: Vec<u8>, } impl CompressedBeaconState { /// Create a new [`CompressedBeaconState`] from compressed data pub const fn new(data: Vec<u8>) -> Self { Self { data } } /// Compress with snappy from ssz-encoded state pub fn from_ssz(ssz_data: &[u8]) -> Result<Self, E2sError> { let mut compressed = Vec::new(); { let mut encoder = FrameEncoder::new(&mut compressed); Write::write_all(&mut encoder, ssz_data).map_err(|e| { E2sError::SnappyCompression(format!("Failed to compress beacon state: {e}")) })?; encoder.flush().map_err(|e| { E2sError::SnappyCompression(format!("Failed to flush encoder: {e}")) })?; } Ok(Self { data: compressed }) } /// Decompress to get the original ssz-encoded beacon state pub fn decompress(&self) -> Result<Vec<u8>, E2sError> { let mut decoder = FrameDecoder::new(self.data.as_slice()); let mut decompressed = Vec::new(); Read::read_to_end(&mut decoder, &mut decompressed).map_err(|e| { E2sError::SnappyDecompression(format!("Failed to decompress beacon state: {e}")) })?; Ok(decompressed) } /// Convert to an [`Entry`] pub fn to_entry(&self) -> Entry { Entry::new(COMPRESSED_BEACON_STATE, self.data.clone()) } /// Create from an [`Entry`] pub fn from_entry(entry: &Entry) -> Result<Self, E2sError> { if entry.entry_type != COMPRESSED_BEACON_STATE { return Err(E2sError::Ssz(format!( "Invalid entry type for CompressedBeaconState: expected {:02x}{:02x}, got {:02x}{:02x}", COMPRESSED_BEACON_STATE[0], COMPRESSED_BEACON_STATE[1], entry.entry_type[0], entry.entry_type[1] ))); } Ok(Self { data: entry.data.clone() }) } /// Decode the compressed beacon state into ssz bytes pub fn decode_to_ssz(&self) -> Result<Vec<u8>, E2sError> { self.decompress() } } impl DecodeCompressedSsz for CompressedBeaconState { fn decode<T: Decode>(&self) -> Result<T, E2sError> { let ssz_bytes = self.decompress()?; T::from_ssz_bytes(&ssz_bytes).map_err(|e| { E2sError::Ssz(format!("Failed to decode SSZ data into target type: {e:?}")) }) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_signed_beacon_block_compression_roundtrip() { let ssz_data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let compressed_block = CompressedSignedBeaconBlock::from_ssz(&ssz_data).unwrap(); let decompressed = compressed_block.decompress().unwrap(); assert_eq!(decompressed, ssz_data); } #[test] fn test_beacon_state_compression_roundtrip() { let ssz_data = vec![10, 9, 8, 7, 6, 5, 4, 3, 2, 1]; let compressed_state = CompressedBeaconState::from_ssz(&ssz_data).unwrap(); let decompressed = compressed_state.decompress().unwrap(); assert_eq!(decompressed, ssz_data); } #[test] fn test_entry_conversion_signed_beacon_block() { let ssz_data = vec![1, 2, 3, 4, 5]; let compressed_block = CompressedSignedBeaconBlock::from_ssz(&ssz_data).unwrap(); let entry = compressed_block.to_entry(); assert_eq!(entry.entry_type, COMPRESSED_SIGNED_BEACON_BLOCK); let recovered = CompressedSignedBeaconBlock::from_entry(&entry).unwrap(); let recovered_ssz = recovered.decode_to_ssz().unwrap(); assert_eq!(recovered_ssz, ssz_data); } #[test] fn test_entry_conversion_beacon_state() { let ssz_data = vec![5, 4, 3, 2, 1]; let compressed_state = CompressedBeaconState::from_ssz(&ssz_data).unwrap(); let entry = compressed_state.to_entry(); assert_eq!(entry.entry_type, COMPRESSED_BEACON_STATE); let recovered = CompressedBeaconState::from_entry(&entry).unwrap(); let recovered_ssz = recovered.decode_to_ssz().unwrap(); assert_eq!(recovered_ssz, ssz_data); } #[test] fn test_invalid_entry_type() { let invalid_entry = Entry::new([0xFF, 0xFF], vec![1, 2, 3]); let result = CompressedSignedBeaconBlock::from_entry(&invalid_entry); assert!(result.is_err()); let result = CompressedBeaconState::from_entry(&invalid_entry); assert!(result.is_err()); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/era/tests/it/genesis.rs
crates/era/tests/it/genesis.rs
//! Genesis block tests for `.era1` files. //! //! These tests verify proper decompression and decoding of genesis blocks //! from different networks. use crate::{ Era1TestDownloader, ERA1_MAINNET_FILES_NAMES, ERA1_SEPOLIA_FILES_NAMES, MAINNET, SEPOLIA, }; use alloy_consensus::{BlockBody, Header}; use reth_era::{e2s_types::IndexEntry, execution_types::CompressedBody}; use reth_ethereum_primitives::TransactionSigned; #[tokio::test(flavor = "multi_thread")] #[ignore = "download intensive"] async fn test_mainnet_genesis_block_decompression() -> eyre::Result<()> { let downloader = Era1TestDownloader::new().await?; let file = downloader.open_era1_file(ERA1_MAINNET_FILES_NAMES[0], MAINNET).await?; // Genesis and a few early blocks let test_blocks = [0, 1, 10, 100]; for &block_idx in &test_blocks { let block = &file.group.blocks[block_idx]; let block_number = file.group.block_index.starting_number() + block_idx as u64; println!( "Testing block {}, compressed body size: {} bytes", block_number, block.body.data.len() ); // Test decompression let body_data = block.body.decompress()?; assert!(!body_data.is_empty(), "Decompressed body should not be empty"); println!("Successfully decompressed body: {} bytes", body_data.len()); let decoded_body: BlockBody<TransactionSigned> = CompressedBody::decode_body_from_decompressed::<TransactionSigned, Header>(&body_data) .expect("Failed to decode body"); // For genesis era blocks, there should be no transactions or ommers assert_eq!( decoded_body.transactions.len(), 0, "Genesis era block should have no transactions" ); assert_eq!(decoded_body.ommers.len(), 0, "Genesis era block should have no ommers"); // Check for withdrawals, should be `None` for genesis era blocks assert!(decoded_body.withdrawals.is_none(), "Genesis era block should have no withdrawals"); let header = block.header.decode_header()?; assert_eq!(header.number, block_number, "Header should have correct block number"); println!("Successfully decoded header for block {block_number}"); // Test total difficulty value let td = block.total_difficulty.value; println!("Block {block_number} total difficulty: {td}"); } Ok(()) } #[tokio::test(flavor = "multi_thread")] #[ignore = "download intensive"] async fn test_sepolia_genesis_block_decompression() -> eyre::Result<()> { let downloader = Era1TestDownloader::new().await?; let file = downloader.open_era1_file(ERA1_SEPOLIA_FILES_NAMES[0], SEPOLIA).await?; // Genesis and a few early blocks let test_blocks = [0, 1, 10, 100]; for &block_idx in &test_blocks { let block = &file.group.blocks[block_idx]; let block_number = file.group.block_index.starting_number() + block_idx as u64; println!( "Testing block {}, compressed body size: {} bytes", block_number, block.body.data.len() ); // Test decompression let body_data = block.body.decompress()?; assert!(!body_data.is_empty(), "Decompressed body should not be empty"); println!("Successfully decompressed body: {} bytes", body_data.len()); let decoded_body: BlockBody<TransactionSigned> = CompressedBody::decode_body_from_decompressed::<TransactionSigned, Header>(&body_data) .expect("Failed to decode body"); // For genesis era blocks, there should be no transactions or ommers assert_eq!( decoded_body.transactions.len(), 0, "Genesis era block should have no transactions" ); assert_eq!(decoded_body.ommers.len(), 0, "Genesis era block should have no ommers"); // Check for withdrawals, should be `None` for genesis era blocks assert!(decoded_body.withdrawals.is_none(), "Genesis era block should have no withdrawals"); let header = block.header.decode_header()?; assert_eq!(header.number, block_number, "Header should have correct block number"); println!("Successfully decoded header for block {block_number}"); // Test total difficulty value let td = block.total_difficulty.value; println!("Block {block_number} total difficulty: {td}"); } Ok(()) }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/era/tests/it/roundtrip.rs
crates/era/tests/it/roundtrip.rs
//! Roundtrip tests for `.era1` files. //! //! These tests verify the full lifecycle of era files by: //! - Reading files from their original source //! - Decompressing and decoding their contents //! - Re-encoding and recompressing the data //! - Writing the data back to a new file //! - Confirming that all original data is preserved throughout the process use alloy_consensus::{BlockBody, BlockHeader, Header, ReceiptWithBloom}; use rand::{prelude::IndexedRandom, rng}; use reth_era::{ e2s_types::IndexEntry, era1_file::{Era1File, Era1Reader, Era1Writer}, era1_types::{Era1Group, Era1Id}, era_file_ops::{EraFileFormat, StreamReader, StreamWriter}, execution_types::{ BlockTuple, CompressedBody, CompressedHeader, CompressedReceipts, TotalDifficulty, }, }; use reth_ethereum_primitives::TransactionSigned; use std::io::Cursor; use crate::{ Era1TestDownloader, ERA1_MAINNET_FILES_NAMES, ERA1_SEPOLIA_FILES_NAMES, MAINNET, SEPOLIA, }; // Helper function to test roundtrip compression/encoding for a specific file async fn test_file_roundtrip( downloader: &Era1TestDownloader, filename: &str, network: &str, ) -> eyre::Result<()> { println!("\nTesting roundtrip for file: {filename}"); let original_file = downloader.open_era1_file(filename, network).await?; // Select a few blocks to test let test_block_indices = [ 0, // First block original_file.group.blocks.len() / 2, // Middle block original_file.group.blocks.len() - 1, // Last block ]; // Write the entire file to a buffer let mut buffer = Vec::new(); { let mut writer = Era1Writer::new(&mut buffer); writer.write_file(&original_file)?; } // Read back from buffer let reader = Era1Reader::new(Cursor::new(&buffer)); let roundtrip_file = reader.read(network.to_string())?; assert_eq!( original_file.id.network_name, roundtrip_file.id.network_name, "Network name should match after roundtrip" ); assert_eq!( original_file.id.start_block, roundtrip_file.id.start_block, "Start block should match after roundtrip" ); assert_eq!( original_file.group.blocks.len(), roundtrip_file.group.blocks.len(), "Block count should match after roundtrip" ); assert_eq!( original_file.group.accumulator.root, roundtrip_file.group.accumulator.root, "Accumulator root should match after roundtrip" ); // Test individual blocks for &block_id in &test_block_indices { let original_block = &original_file.group.blocks[block_id]; let roundtrip_block = &roundtrip_file.group.blocks[block_id]; let block_number = original_file.group.block_index.starting_number() + block_id as u64; println!("Testing roundtrip for block {block_number}"); // Test header decompression let original_header_data = original_block.header.decompress()?; let roundtrip_header_data = roundtrip_block.header.decompress()?; assert_eq!( original_header_data, roundtrip_header_data, "Block {block_number} header data should be identical after roundtrip" ); // Test body decompression let original_body_data = original_block.body.decompress()?; let roundtrip_body_data = roundtrip_block.body.decompress()?; assert_eq!( original_body_data, roundtrip_body_data, "Block {block_number} body data should be identical after roundtrip" ); // Test receipts decompression let original_receipts_data = original_block.receipts.decompress()?; let roundtrip_receipts_data = roundtrip_block.receipts.decompress()?; assert_eq!( original_receipts_data, roundtrip_receipts_data, "Block {block_number} receipts data should be identical after roundtrip" ); // Test total difficulty preservation assert_eq!( original_block.total_difficulty.value, roundtrip_block.total_difficulty.value, "Block {block_number} total difficulty should be identical after roundtrip", ); // Test decoding of header and body to ensure structural integrity let original_header = original_block.header.decode_header()?; let roundtrip_header = roundtrip_block.header.decode_header()?; assert_eq!( original_header.number, roundtrip_header.number, "Block number should match after roundtrip decoding" ); assert_eq!( original_header.mix_hash(), roundtrip_header.mix_hash(), "Block hash should match after roundtrip decoding" ); // Decode and verify body contents let original_decoded_body: BlockBody<TransactionSigned> = CompressedBody::decode_body_from_decompressed::<TransactionSigned, Header>( &original_body_data, ) .expect("Failed to decode original body"); let roundtrip_decoded_body: BlockBody<TransactionSigned> = CompressedBody::decode_body_from_decompressed::<TransactionSigned, Header>( &roundtrip_body_data, ) .expect("Failed to original decode body"); assert_eq!( original_decoded_body.transactions.len(), roundtrip_decoded_body.transactions.len(), "Transaction count should match after roundtrip between original and roundtrip" ); assert_eq!( original_decoded_body.ommers.len(), roundtrip_decoded_body.ommers.len(), "Ommers count should match after roundtrip" ); // Decode receipts let original_receipts_decoded = original_block.receipts.decode::<Vec<ReceiptWithBloom>>()?; let roundtrip_receipts_decoded = roundtrip_block.receipts.decode::<Vec<ReceiptWithBloom>>()?; assert_eq!( original_receipts_decoded, roundtrip_receipts_decoded, "Block {block_number} decoded receipts should be identical after roundtrip" ); assert_eq!( original_receipts_data, roundtrip_receipts_data, "Block {block_number} receipts data should be identical after roundtrip" ); // Check withdrawals presence/absence matches assert_eq!( original_decoded_body.withdrawals.is_some(), roundtrip_decoded_body.withdrawals.is_some(), "Withdrawals presence should match after roundtrip" ); println!("Block {block_number} roundtrip verified successfully"); println!("Testing full re-encoding/re-compression cycle for block {block_number}"); // Re-encode and re-compress the header let recompressed_header = CompressedHeader::from_header(&original_header)?; let recompressed_header_data = recompressed_header.decompress()?; assert_eq!( original_header_data, recompressed_header_data, "Re-compressed header data should match original after full cycle" ); // Re-encode and re-compress the body let recompressed_body = CompressedBody::from_body(&original_decoded_body)?; let recompressed_body_data = recompressed_body.decompress()?; let recompressed_decoded_body: BlockBody<TransactionSigned> = CompressedBody::decode_body_from_decompressed::<TransactionSigned, Header>( &recompressed_body_data, ) .expect("Failed to decode re-compressed body"); assert_eq!( original_decoded_body.transactions.len(), recompressed_decoded_body.transactions.len(), "Transaction count should match after re-compression" ); // Re-encore and re-compress the receipts let recompressed_receipts = CompressedReceipts::from_encodable(&roundtrip_receipts_decoded)?; let recompressed_receipts_data = recompressed_receipts.decompress()?; assert_eq!( original_receipts_data.len(), recompressed_receipts_data.len(), "Receipts length should match after re-compression" ); let recompressed_block = BlockTuple::new( recompressed_header, recompressed_body, recompressed_receipts, TotalDifficulty::new(original_block.total_difficulty.value), ); let mut recompressed_buffer = Vec::new(); { let blocks = vec![recompressed_block]; let new_group = Era1Group::new( blocks, original_file.group.accumulator.clone(), original_file.group.block_index.clone(), ); let new_file = Era1File::new(new_group, Era1Id::new(network, original_file.id.start_block, 1)); let mut writer = Era1Writer::new(&mut recompressed_buffer); writer.write_file(&new_file)?; } let reader = Era1Reader::new(Cursor::new(&recompressed_buffer)); let recompressed_file = reader.read(network.to_string())?; let recompressed_first_block = &recompressed_file.group.blocks[0]; let recompressed_header = recompressed_first_block.header.decode_header()?; assert_eq!( original_header.number, recompressed_header.number, "Block number should match after complete re-encoding cycle" ); println!( "Block {block_number} full re-encoding/re-compression cycle verified successfully 🫡" ); } println!("File {filename} roundtrip successful"); Ok(()) } #[tokio::test(flavor = "multi_thread")] #[ignore = "download intensive"] async fn test_roundtrip_compression_encoding_mainnet() -> eyre::Result<()> { let downloader = Era1TestDownloader::new().await?; let mut rng = rng(); // pick 4 random files from the mainnet list let sample_files: Vec<&str> = ERA1_MAINNET_FILES_NAMES.choose_multiple(&mut rng, 4).copied().collect(); println!("Testing {} randomly selected mainnet files", sample_files.len()); for &filename in &sample_files { test_file_roundtrip(&downloader, filename, MAINNET).await?; } Ok(()) } #[tokio::test(flavor = "multi_thread")] #[ignore = "download intensive"] async fn test_roundtrip_compression_encoding_sepolia() -> eyre::Result<()> { let downloader = Era1TestDownloader::new().await?; // Test all Sepolia files for &filename in &ERA1_SEPOLIA_FILES_NAMES { test_file_roundtrip(&downloader, filename, SEPOLIA).await?; } Ok(()) }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/era/tests/it/main.rs
crates/era/tests/it/main.rs
//! Root //! Includes common helpers for integration tests //! //! These tests use the `reth-era-downloader` client to download `.era1` files temporarily //! and verify that we can correctly read and decompress their data. //! //! Files are downloaded from [`MAINNET_URL`] and [`SEPOLIA_URL`]. use reqwest::{Client, Url}; use reth_era::{ e2s_types::E2sError, era1_file::{Era1File, Era1Reader}, era_file_ops::FileReader, }; use reth_era_downloader::EraClient; use std::{ collections::HashMap, path::{Path, PathBuf}, str::FromStr, sync::{Arc, Mutex}, }; use eyre::{eyre, Result}; use tempfile::TempDir; mod dd; mod genesis; mod roundtrip; const fn main() {} /// Mainnet network name const MAINNET: &str = "mainnet"; /// Default mainnet url /// for downloading mainnet `.era1` files const MAINNET_URL: &str = "https://era.ithaca.xyz/era1/"; /// Succinct list of mainnet files we want to download /// from <https://era.ithaca.xyz/era1/> /// for testing purposes const ERA1_MAINNET_FILES_NAMES: [&str; 8] = [ "mainnet-00000-5ec1ffb8.era1", "mainnet-00003-d8b8a40b.era1", "mainnet-00151-e322efe1.era1", "mainnet-00293-0d6c5812.era1", "mainnet-00443-ea71b6f9.era1", "mainnet-01367-d7efc68f.era1", "mainnet-01610-99fdde4b.era1", "mainnet-01895-3f81607c.era1", ]; /// Sepolia network name const SEPOLIA: &str = "sepolia"; /// Default sepolia url /// for downloading sepolia `.era1` files const SEPOLIA_URL: &str = "https://era.ithaca.xyz/sepolia-era1/"; /// Succinct list of sepolia files we want to download /// from <https://era.ithaca.xyz/sepolia-era1/> /// for testing purposes const ERA1_SEPOLIA_FILES_NAMES: [&str; 4] = [ "sepolia-00000-643a00f7.era1", "sepolia-00074-0e81003c.era1", "sepolia-00173-b6924da5.era1", "sepolia-00182-a4f0a8a1.era1 ", ]; /// Utility for downloading `.era1` files for tests /// in a temporary directory /// and caching them in memory #[derive(Debug)] struct Era1TestDownloader { /// Temporary directory for storing downloaded files temp_dir: TempDir, /// Cache mapping file names to their paths file_cache: Arc<Mutex<HashMap<String, PathBuf>>>, } impl Era1TestDownloader { /// Create a new downloader instance with a temporary directory async fn new() -> Result<Self> { let temp_dir = TempDir::new().map_err(|e| eyre!("Failed to create temp directory: {}", e))?; Ok(Self { temp_dir, file_cache: Arc::new(Mutex::new(HashMap::new())) }) } /// Download a specific .era1 file by name pub(crate) async fn download_file(&self, filename: &str, network: &str) -> Result<PathBuf> { // check cache first { let cache = self.file_cache.lock().unwrap(); if let Some(path) = cache.get(filename) { return Ok(path.clone()); } } // check if the filename is supported if !ERA1_MAINNET_FILES_NAMES.contains(&filename) && !ERA1_SEPOLIA_FILES_NAMES.contains(&filename) { return Err(eyre!( "Unknown file: {}. Only the following files are supported: {:?} or {:?}", filename, ERA1_MAINNET_FILES_NAMES, ERA1_SEPOLIA_FILES_NAMES )); } // initialize the client and build url config let url = match network { MAINNET => MAINNET_URL, SEPOLIA => SEPOLIA_URL, _ => { return Err(eyre!( "Unknown network: {}. Only mainnet and sepolia are supported.", network )); } }; let final_url = Url::from_str(url).map_err(|e| eyre!("Failed to parse URL: {}", e))?; let folder = self.temp_dir.path(); // set up the client let client = EraClient::new(Client::new(), final_url, folder); // set up the file list, required before we can download files client.fetch_file_list().await.map_err(|e| { E2sError::Io(std::io::Error::other(format!("Failed to fetch file list: {e}"))) })?; // create an url for the file let file_url = Url::parse(&format!("{url}{filename}")) .map_err(|e| eyre!("Failed to parse file URL: {}", e))?; // download the file let mut client = client; let downloaded_path = client .download_to_file(file_url) .await .map_err(|e| eyre!("Failed to download file: {}", e))?; // update the cache { let mut cache = self.file_cache.lock().unwrap(); cache.insert(filename.to_string(), downloaded_path.to_path_buf()); } Ok(downloaded_path.to_path_buf()) } /// open .era1 file, downloading it if necessary async fn open_era1_file(&self, filename: &str, network: &str) -> Result<Era1File> { let path = self.download_file(filename, network).await?; Era1Reader::open(&path, network).map_err(|e| eyre!("Failed to open Era1 file: {e}")) } } /// Open a test file by name, /// downloading only if it is necessary async fn open_test_file( file_path: &str, downloader: &Era1TestDownloader, network: &str, ) -> Result<Era1File> { let filename = Path::new(file_path) .file_name() .and_then(|os_str| os_str.to_str()) .ok_or_else(|| eyre!("Invalid file path: {}", file_path))?; downloader.open_era1_file(filename, network).await }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/era/tests/it/dd.rs
crates/era/tests/it/dd.rs
//! Simple decoding and decompressing tests //! for mainnet era1 files use alloy_consensus::{BlockBody, Header}; use alloy_primitives::U256; use reth_era::{ e2s_types::IndexEntry, era1_file::{Era1Reader, Era1Writer}, era_file_ops::{StreamReader, StreamWriter}, execution_types::CompressedBody, }; use reth_ethereum_primitives::TransactionSigned; use std::io::Cursor; use crate::{open_test_file, Era1TestDownloader, ERA1_MAINNET_FILES_NAMES, MAINNET}; #[tokio::test(flavor = "multi_thread")] #[ignore = "download intensive"] async fn test_mainnet_era1_only_file_decompression_and_decoding() -> eyre::Result<()> { let downloader = Era1TestDownloader::new().await.expect("Failed to create downloader"); for &filename in &ERA1_MAINNET_FILES_NAMES { println!("\nTesting file: {filename}"); let file = open_test_file(filename, &downloader, MAINNET).await?; // Test block decompression across different positions in the file let test_block_indices = [ 0, // First block file.group.blocks.len() / 2, // Middle block file.group.blocks.len() - 1, // Last block ]; for &block_idx in &test_block_indices { let block = &file.group.blocks[block_idx]; let block_number = file.group.block_index.starting_number() + block_idx as u64; println!( "\n Testing block {}, compressed body size: {} bytes", block_number, block.body.data.len() ); // Test header decompression and decoding let header_data = block.header.decompress()?; assert!( !header_data.is_empty(), "Block {block_number} header decompression should produce non-empty data" ); let header = block.header.decode_header()?; assert_eq!( header.number, block_number, "Decoded header should have correct block number" ); println!("Header decompression and decoding successful"); // Test body decompression let body_data = block.body.decompress()?; assert!( !body_data.is_empty(), "Block {block_number} body decompression should produce non-empty data" ); println!("Body decompression successful ({} bytes)", body_data.len()); let decoded_body: BlockBody<TransactionSigned> = CompressedBody::decode_body_from_decompressed::<TransactionSigned, Header>( &body_data, ) .expect("Failed to decode body"); println!( "Body decoding successful: {} transactions, {} ommers, withdrawals: {}", decoded_body.transactions.len(), decoded_body.ommers.len(), decoded_body.withdrawals.is_some() ); // Test receipts decompression let receipts_data = block.receipts.decompress()?; assert!( !receipts_data.is_empty(), "Block {block_number} receipts decompression should produce non-empty data" ); println!("Receipts decompression successful ({} bytes)", receipts_data.len()); assert!( block.total_difficulty.value > U256::ZERO, "Block {block_number} should have non-zero difficulty" ); println!("Total difficulty verified: {}", block.total_difficulty.value); } // Test round-trip serialization println!("\n Testing data preservation roundtrip..."); let mut buffer = Vec::new(); { let mut writer = Era1Writer::new(&mut buffer); writer.write_file(&file)?; } // Read back from buffer let reader = Era1Reader::new(Cursor::new(&buffer)); let read_back_file = reader.read(file.id.network_name.clone())?; // Verify basic properties are preserved assert_eq!(file.id.network_name, read_back_file.id.network_name); assert_eq!(file.id.start_block, read_back_file.id.start_block); assert_eq!(file.group.blocks.len(), read_back_file.group.blocks.len()); assert_eq!(file.group.accumulator.root, read_back_file.group.accumulator.root); // Test data preservation for some blocks for &idx in &test_block_indices { let original_block = &file.group.blocks[idx]; let read_back_block = &read_back_file.group.blocks[idx]; let block_number = file.group.block_index.starting_number() + idx as u64; println!("Block {block_number} details:"); println!(" Header size: {} bytes", original_block.header.data.len()); println!(" Body size: {} bytes", original_block.body.data.len()); println!(" Receipts size: {} bytes", original_block.receipts.data.len()); // Test that decompressed data is identical assert_eq!( original_block.header.decompress()?, read_back_block.header.decompress()?, "Header data should be identical for block {block_number}" ); assert_eq!( original_block.body.decompress()?, read_back_block.body.decompress()?, "Body data should be identical for block {block_number}" ); assert_eq!( original_block.receipts.decompress()?, read_back_block.receipts.decompress()?, "Receipts data should be identical for block {block_number}" ); assert_eq!( original_block.total_difficulty.value, read_back_block.total_difficulty.value, "Total difficulty should be identical for block {block_number}" ); } } Ok(()) }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/stats.rs
crates/trie/trie/src/stats.rs
use std::time::{Duration, Instant}; /// Trie stats. #[derive(Clone, Copy, Debug)] pub struct TrieStats { duration: Duration, branches_added: u64, leaves_added: u64, } impl TrieStats { /// Duration for root calculation. pub const fn duration(&self) -> Duration { self.duration } /// Number of leaves added to the hash builder during the calculation. pub const fn leaves_added(&self) -> u64 { self.leaves_added } /// Number of branches added to the hash builder during the calculation. pub const fn branches_added(&self) -> u64 { self.branches_added } } /// Trie metrics tracker. #[derive(Debug)] pub struct TrieTracker { started_at: Instant, branches_added: u64, leaves_added: u64, } impl Default for TrieTracker { fn default() -> Self { Self { started_at: Instant::now(), branches_added: 0, leaves_added: 0 } } } impl TrieTracker { /// Increment the number of branches added to the hash builder during the calculation. pub const fn inc_branch(&mut self) { self.branches_added += 1; } /// Increment the number of leaves added to the hash builder during the calculation. pub const fn inc_leaf(&mut self) { self.leaves_added += 1; } /// Called when root calculation is finished to return trie statistics. pub fn finish(self) -> TrieStats { TrieStats { duration: self.started_at.elapsed(), branches_added: self.branches_added, leaves_added: self.leaves_added, } } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/lib.rs
crates/trie/trie/src/lib.rs
//! The implementation of Merkle Patricia Trie, a cryptographically //! authenticated radix trie that is used to store key-value bindings. //! <https://ethereum.org/en/developers/docs/data-structures-and-encoding/patricia-merkle-trie/> //! //! ## Feature Flags //! //! - `rayon`: uses rayon for parallel [`HashedPostState`] creation. //! - `test-utils`: Export utilities for testing #![doc( html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png", html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256", issue_tracker_base_url = "https://github.com/SeismicSystems/seismic-reth/issues/" )] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] /// The implementation of forward-only in-memory cursor. pub mod forward_cursor; /// The cursor implementations for navigating account and storage tries. pub mod trie_cursor; /// The cursor implementations for navigating hashed state. pub mod hashed_cursor; /// The trie walker for iterating over the trie nodes. pub mod walker; /// The iterators for traversing existing intermediate hashes and updated trie leaves. pub mod node_iter; /// Merkle proof generation. pub mod proof; /// Trie witness generation. pub mod witness; /// The implementation of the Merkle Patricia Trie. mod trie; pub use trie::{StateRoot, StorageRoot, TrieType}; /// Utilities for state root checkpoint progress. mod progress; pub use progress::{ IntermediateStateRootState, IntermediateStorageRootState, StateRootProgress, StorageRootProgress, }; /// Trie calculation stats. pub mod stats; // re-export for convenience pub use reth_trie_common::*; /// Trie calculation metrics. #[cfg(feature = "metrics")] pub mod metrics; /// Collection of trie-related test utilities. #[cfg(any(test, feature = "test-utils"))] pub mod test_utils; /// Collection of mock types for testing. #[cfg(test)] pub mod mock; /// Verification of existing stored trie nodes against state data. pub mod verify;
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/walker.rs
crates/trie/trie/src/walker.rs
use crate::{ prefix_set::PrefixSet, trie_cursor::{subnode::SubNodePosition, CursorSubNode, TrieCursor}, BranchNodeCompact, Nibbles, }; use alloy_primitives::{map::HashSet, B256}; use alloy_trie::proof::AddedRemovedKeys; use reth_storage_errors::db::DatabaseError; use tracing::{instrument, trace}; #[cfg(feature = "metrics")] use crate::metrics::WalkerMetrics; /// Traverses the trie in lexicographic order. /// /// This iterator depends on the ordering guarantees of [`TrieCursor`]. #[derive(Debug)] pub struct TrieWalker<C, K = AddedRemovedKeys> { /// A mutable reference to a trie cursor instance used for navigating the trie. pub cursor: C, /// A vector containing the trie nodes that have been visited. pub stack: Vec<CursorSubNode>, /// A flag indicating whether the current node can be skipped when traversing the trie. This /// is determined by whether the current key's prefix is included in the prefix set and if the /// hash flag is set. pub can_skip_current_node: bool, /// A `PrefixSet` representing the changes to be applied to the trie. pub changes: PrefixSet, /// The retained trie node keys that need to be removed. removed_keys: Option<HashSet<Nibbles>>, /// Provided when it's necessary to not skip certain nodes during proof generation. /// Specifically we don't skip certain branch nodes even when they are not in the `PrefixSet`, /// when they might be required to support leaf removal. added_removed_keys: Option<K>, #[cfg(feature = "metrics")] /// Walker metrics. metrics: WalkerMetrics, } impl<C: TrieCursor, K: AsRef<AddedRemovedKeys>> TrieWalker<C, K> { /// Constructs a new `TrieWalker` for the state trie from existing stack and a cursor. pub fn state_trie_from_stack(cursor: C, stack: Vec<CursorSubNode>, changes: PrefixSet) -> Self { Self::from_stack( cursor, stack, changes, #[cfg(feature = "metrics")] crate::TrieType::State, ) } /// Constructs a new `TrieWalker` for the storage trie from existing stack and a cursor. pub fn storage_trie_from_stack( cursor: C, stack: Vec<CursorSubNode>, changes: PrefixSet, ) -> Self { Self::from_stack( cursor, stack, changes, #[cfg(feature = "metrics")] crate::TrieType::Storage, ) } /// Constructs a new `TrieWalker` from existing stack and a cursor. fn from_stack( cursor: C, stack: Vec<CursorSubNode>, changes: PrefixSet, #[cfg(feature = "metrics")] trie_type: crate::TrieType, ) -> Self { let mut this = Self { cursor, changes, stack, can_skip_current_node: false, removed_keys: None, added_removed_keys: None, #[cfg(feature = "metrics")] metrics: WalkerMetrics::new(trie_type), }; this.update_skip_node(); this } /// Sets the flag whether the trie updates should be stored. pub fn with_deletions_retained(mut self, retained: bool) -> Self { if retained { self.removed_keys = Some(HashSet::default()); } self } /// Configures the walker to not skip certain branch nodes, even when they are not in the /// `PrefixSet`, when they might be needed to support leaf removal. pub fn with_added_removed_keys<K2>(self, added_removed_keys: Option<K2>) -> TrieWalker<C, K2> { TrieWalker { cursor: self.cursor, stack: self.stack, can_skip_current_node: self.can_skip_current_node, changes: self.changes, removed_keys: self.removed_keys, added_removed_keys, #[cfg(feature = "metrics")] metrics: self.metrics, } } /// Split the walker into stack and trie updates. pub fn split(mut self) -> (Vec<CursorSubNode>, HashSet<Nibbles>) { let keys = self.take_removed_keys(); (self.stack, keys) } /// Take removed keys from the walker. pub fn take_removed_keys(&mut self) -> HashSet<Nibbles> { self.removed_keys.take().unwrap_or_default() } /// Prints the current stack of trie nodes. pub fn print_stack(&self) { println!("====================== STACK ======================"); for node in &self.stack { println!("{node:?}"); } println!("====================== END STACK ======================\n"); } /// The current length of the removed keys. pub fn removed_keys_len(&self) -> usize { self.removed_keys.as_ref().map_or(0, |u| u.len()) } /// Returns the current key in the trie. pub fn key(&self) -> Option<&Nibbles> { self.stack.last().map(|n| n.full_key()) } /// Returns the current hash in the trie, if any. pub fn hash(&self) -> Option<B256> { self.stack.last().and_then(|n| n.hash()) } /// Returns the current hash in the trie, if any. /// /// Differs from [`Self::hash`] in that it returns `None` if the subnode is positioned at the /// child without a hash mask bit set. [`Self::hash`] panics in that case. pub fn maybe_hash(&self) -> Option<B256> { self.stack.last().and_then(|n| n.maybe_hash()) } /// Indicates whether the children of the current node are present in the trie. pub fn children_are_in_trie(&self) -> bool { self.stack.last().is_some_and(|n| n.tree_flag()) } /// Returns the next unprocessed key in the trie along with its raw [`Nibbles`] representation. #[instrument(level = "trace", skip(self), ret)] pub fn next_unprocessed_key(&self) -> Option<(B256, Nibbles)> { self.key() .and_then(|key| if self.can_skip_current_node { key.increment() } else { Some(*key) }) .map(|key| { let mut packed = key.pack(); packed.resize(32, 0); (B256::from_slice(packed.as_slice()), key) }) } /// Updates the skip node flag based on the walker's current state. fn update_skip_node(&mut self) { let old = self.can_skip_current_node; self.can_skip_current_node = self.stack.last().is_some_and(|node| { // If the current key is not removed according to the [`AddedRemovedKeys`], and all of // its siblings are removed, then we don't want to skip it. This allows the // `ProofRetainer` to include this node in the returned proofs. Required to support // leaf removal. let key_is_only_nonremoved_child = self.added_removed_keys.as_ref().is_some_and(|added_removed_keys| { node.full_key_is_only_nonremoved_child(added_removed_keys.as_ref()) }); trace!( target: "trie::walker", ?key_is_only_nonremoved_child, full_key=?node.full_key(), "Checked for only nonremoved child", ); !self.changes.contains(node.full_key()) && node.hash_flag() && !key_is_only_nonremoved_child }); trace!( target: "trie::walker", old, new = self.can_skip_current_node, last = ?self.stack.last(), "updated skip node flag" ); } /// Constructs a new [`TrieWalker`] for the state trie. pub fn state_trie(cursor: C, changes: PrefixSet) -> Self { Self::new( cursor, changes, #[cfg(feature = "metrics")] crate::TrieType::State, ) } /// Constructs a new [`TrieWalker`] for the storage trie. pub fn storage_trie(cursor: C, changes: PrefixSet) -> Self { Self::new( cursor, changes, #[cfg(feature = "metrics")] crate::TrieType::Storage, ) } /// Constructs a new `TrieWalker`, setting up the initial state of the stack and cursor. fn new( cursor: C, changes: PrefixSet, #[cfg(feature = "metrics")] trie_type: crate::TrieType, ) -> Self { // Initialize the walker with a single empty stack element. let mut this = Self { cursor, changes, stack: vec![CursorSubNode::default()], can_skip_current_node: false, removed_keys: None, added_removed_keys: Default::default(), #[cfg(feature = "metrics")] metrics: WalkerMetrics::new(trie_type), }; // Set up the root node of the trie in the stack, if it exists. if let Some((key, value)) = this.node(true).unwrap() { this.stack[0] = CursorSubNode::new(key, Some(value)); } // Update the skip state for the root node. this.update_skip_node(); this } /// Advances the walker to the next trie node and updates the skip node flag. /// The new key can then be obtained via `key()`. /// /// # Returns /// /// * `Result<(), Error>` - Unit on success or an error. pub fn advance(&mut self) -> Result<(), DatabaseError> { if let Some(last) = self.stack.last() { if !self.can_skip_current_node && self.children_are_in_trie() { trace!( target: "trie::walker", position = ?last.position(), "cannot skip current node and children are in the trie" ); // If we can't skip the current node and the children are in the trie, // either consume the next node or move to the next sibling. match last.position() { SubNodePosition::ParentBranch => self.move_to_next_sibling(true)?, SubNodePosition::Child(_) => self.consume_node()?, } } else { trace!(target: "trie::walker", "can skip current node"); // If we can skip the current node, move to the next sibling. self.move_to_next_sibling(false)?; } // Update the skip node flag based on the new position in the trie. self.update_skip_node(); } Ok(()) } /// Retrieves the current root node from the DB, seeking either the exact node or the next one. fn node(&mut self, exact: bool) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { let key = self.key().expect("key must exist"); let entry = if exact { self.cursor.seek_exact(*key)? } else { self.cursor.seek(*key)? }; #[cfg(feature = "metrics")] self.metrics.inc_branch_nodes_seeked(); if let Some((_, node)) = &entry { assert!(!node.state_mask.is_empty()); } Ok(entry) } /// Consumes the next node in the trie, updating the stack. #[instrument(level = "trace", skip(self), ret)] fn consume_node(&mut self) -> Result<(), DatabaseError> { let Some((key, node)) = self.node(false)? else { // If no next node is found, clear the stack. self.stack.clear(); return Ok(()) }; // Overwrite the root node's first nibble // We need to sync the stack with the trie structure when consuming a new node. This is // necessary for proper traversal and accurately representing the trie in the stack. if !key.is_empty() && !self.stack.is_empty() { self.stack[0].set_nibble(key.get_unchecked(0)); } // The current tree mask might have been set incorrectly. // Sanity check that the newly retrieved trie node key is the child of the last item // on the stack. If not, advance to the next sibling instead of adding the node to the // stack. if let Some(subnode) = self.stack.last() { if !key.starts_with(subnode.full_key()) { #[cfg(feature = "metrics")] self.metrics.inc_out_of_order_subnode(1); self.move_to_next_sibling(false)?; return Ok(()) } } // Create a new CursorSubNode and push it to the stack. let subnode = CursorSubNode::new(key, Some(node)); let position = subnode.position(); self.stack.push(subnode); self.update_skip_node(); // Delete the current node if it's included in the prefix set or it doesn't contain the root // hash. if !self.can_skip_current_node || position.is_child() { if let Some((keys, key)) = self.removed_keys.as_mut().zip(self.cursor.current()?) { keys.insert(key); } } Ok(()) } /// Moves to the next sibling node in the trie, updating the stack. #[instrument(level = "trace", skip(self), ret)] fn move_to_next_sibling( &mut self, allow_root_to_child_nibble: bool, ) -> Result<(), DatabaseError> { let Some(subnode) = self.stack.last_mut() else { return Ok(()) }; // Check if the walker needs to backtrack to the previous level in the trie during its // traversal. if subnode.position().is_last_child() || (subnode.position().is_parent() && !allow_root_to_child_nibble) { self.stack.pop(); self.move_to_next_sibling(false)?; return Ok(()) } subnode.inc_nibble(); if subnode.node.is_none() { return self.consume_node() } // Find the next sibling with state. loop { let position = subnode.position(); if subnode.state_flag() { trace!(target: "trie::walker", ?position, "found next sibling with state"); return Ok(()) } if position.is_last_child() { trace!(target: "trie::walker", ?position, "checked all siblings"); break } subnode.inc_nibble(); } // Pop the current node and move to the next sibling. self.stack.pop(); self.move_to_next_sibling(false)?; Ok(()) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/witness.rs
crates/trie/trie/src/witness.rs
use crate::{ hashed_cursor::{HashedCursor, HashedCursorFactory}, prefix_set::TriePrefixSetsMut, proof::{Proof, ProofTrieNodeProviderFactory}, trie_cursor::TrieCursorFactory, }; use alloy_rlp::EMPTY_STRING_CODE; use alloy_trie::EMPTY_ROOT_HASH; use reth_trie_common::HashedPostState; use reth_trie_sparse::SparseTrieInterface; use alloy_primitives::{ keccak256, map::{B256Map, B256Set, Entry, HashMap}, Bytes, B256, }; use itertools::Itertools; use reth_execution_errors::{ SparseStateTrieErrorKind, SparseTrieError, SparseTrieErrorKind, StateProofError, TrieWitnessError, }; use reth_trie_common::{MultiProofTargets, Nibbles}; use reth_trie_sparse::{ provider::{RevealedNode, TrieNodeProvider, TrieNodeProviderFactory}, SerialSparseTrie, SparseStateTrie, }; use std::sync::{mpsc, Arc}; /// State transition witness for the trie. #[derive(Debug)] pub struct TrieWitness<T, H> { /// The cursor factory for traversing trie nodes. trie_cursor_factory: T, /// The factory for hashed cursors. hashed_cursor_factory: H, /// A set of prefix sets that have changes. prefix_sets: TriePrefixSetsMut, /// Flag indicating whether the root node should always be included (even if the target state /// is empty). This setting is useful if the caller wants to verify the witness against the /// parent state root. /// Set to `false` by default. always_include_root_node: bool, /// Recorded witness. witness: B256Map<Bytes>, } impl<T, H> TrieWitness<T, H> { /// Creates a new witness generator. pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self { Self { trie_cursor_factory, hashed_cursor_factory, prefix_sets: TriePrefixSetsMut::default(), always_include_root_node: false, witness: HashMap::default(), } } /// Set the trie cursor factory. pub fn with_trie_cursor_factory<TF>(self, trie_cursor_factory: TF) -> TrieWitness<TF, H> { TrieWitness { trie_cursor_factory, hashed_cursor_factory: self.hashed_cursor_factory, prefix_sets: self.prefix_sets, always_include_root_node: self.always_include_root_node, witness: self.witness, } } /// Set the hashed cursor factory. pub fn with_hashed_cursor_factory<HF>(self, hashed_cursor_factory: HF) -> TrieWitness<T, HF> { TrieWitness { trie_cursor_factory: self.trie_cursor_factory, hashed_cursor_factory, prefix_sets: self.prefix_sets, always_include_root_node: self.always_include_root_node, witness: self.witness, } } /// Set the prefix sets. They have to be mutable in order to allow extension with proof target. pub fn with_prefix_sets_mut(mut self, prefix_sets: TriePrefixSetsMut) -> Self { self.prefix_sets = prefix_sets; self } /// Set `always_include_root_node` to true. Root node will be included even on empty state. /// This setting is useful if the caller wants to verify the witness against the /// parent state root. pub const fn always_include_root_node(mut self) -> Self { self.always_include_root_node = true; self } } impl<T, H> TrieWitness<T, H> where T: TrieCursorFactory + Clone + Send + Sync, H: HashedCursorFactory + Clone + Send + Sync, { /// Compute the state transition witness for the trie. Gather all required nodes /// to apply `state` on top of the current trie state. /// /// # Arguments /// /// `state` - state transition containing both modified and touched accounts and storage slots. pub fn compute(mut self, state: HashedPostState) -> Result<B256Map<Bytes>, TrieWitnessError> { let is_state_empty = state.is_empty(); if is_state_empty && !self.always_include_root_node { return Ok(Default::default()) } let proof_targets = if is_state_empty { MultiProofTargets::account(B256::ZERO) } else { self.get_proof_targets(&state)? }; let multiproof = Proof::new(self.trie_cursor_factory.clone(), self.hashed_cursor_factory.clone()) .with_prefix_sets_mut(self.prefix_sets.clone()) .multiproof(proof_targets.clone())?; // No need to reconstruct the rest of the trie, we just need to include // the root node and return. if is_state_empty { let (root_hash, root_node) = if let Some(root_node) = multiproof.account_subtree.into_inner().remove(&Nibbles::default()) { (keccak256(&root_node), root_node) } else { (EMPTY_ROOT_HASH, Bytes::from([EMPTY_STRING_CODE])) }; return Ok(B256Map::from_iter([(root_hash, root_node)])) } // 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())) { 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())) { entry.insert(storage_node.clone()); } } let (tx, rx) = mpsc::channel(); let blinded_provider_factory = WitnessTrieNodeProviderFactory::new( ProofTrieNodeProviderFactory::new( self.trie_cursor_factory, self.hashed_cursor_factory, Arc::new(self.prefix_sets), ), tx, ); let mut sparse_trie = SparseStateTrie::<SerialSparseTrie>::new(); sparse_trie.reveal_multiproof(multiproof)?; // Attempt to update state trie to gather additional information for the witness. for (hashed_address, hashed_slots) in proof_targets.into_iter().sorted_unstable_by_key(|(ha, _)| *ha) { // Update storage trie first. let provider = blinded_provider_factory.storage_node_provider(hashed_address); let storage = state.storages.get(&hashed_address); let storage_trie = sparse_trie.storage_trie_mut(&hashed_address).ok_or( SparseStateTrieErrorKind::SparseStorageTrie( hashed_address, SparseTrieErrorKind::Blind, ), )?; for hashed_slot in hashed_slots.into_iter().sorted_unstable() { let storage_nibbles = Nibbles::unpack(hashed_slot); let maybe_leaf_value = storage.and_then(|s| s.storage.get(&hashed_slot)).filter(|v| !v.is_zero()); if let Some(value) = maybe_leaf_value { let is_private = value.is_private; let value = alloy_rlp::encode_fixed_size(value).to_vec(); storage_trie .update_leaf(storage_nibbles, value, is_private, &provider) .map_err(|err| { SparseStateTrieErrorKind::SparseStorageTrie( hashed_address, err.into_kind(), ) })?; } else { storage_trie.remove_leaf(&storage_nibbles, &provider).map_err(|err| { SparseStateTrieErrorKind::SparseStorageTrie(hashed_address, err.into_kind()) })?; } } // Calculate storage root after updates. storage_trie.root(); let account = state .accounts .get(&hashed_address) .ok_or(TrieWitnessError::MissingAccount(hashed_address))? .unwrap_or_default(); if !sparse_trie.update_account(hashed_address, account, &blinded_provider_factory)? { let nibbles = Nibbles::unpack(hashed_address); sparse_trie.remove_account_leaf(&nibbles, &blinded_provider_factory)?; } while let Ok(node) = rx.try_recv() { self.witness.insert(keccak256(&node), node); } } Ok(self.witness) } /// Retrieve proof targets for incoming hashed state. /// This method will aggregate all accounts and slots present in the hash state as well as /// select all existing slots from the database for the accounts that have been destroyed. fn get_proof_targets( &self, state: &HashedPostState, ) -> Result<MultiProofTargets, StateProofError> { let mut proof_targets = MultiProofTargets::default(); for hashed_address in state.accounts.keys() { proof_targets.insert(*hashed_address, B256Set::default()); } for (hashed_address, storage) in &state.storages { let mut storage_keys = storage.storage.keys().copied().collect::<B256Set>(); if storage.wiped { // storage for this account was destroyed, gather all slots from the current state let mut storage_cursor = self.hashed_cursor_factory.hashed_storage_cursor(*hashed_address)?; // position cursor at the start let mut current_entry = storage_cursor.seek(B256::ZERO)?; while let Some((hashed_slot, _)) = current_entry { storage_keys.insert(hashed_slot); current_entry = storage_cursor.next()?; } } proof_targets.insert(*hashed_address, storage_keys); } Ok(proof_targets) } } #[derive(Debug, Clone)] struct WitnessTrieNodeProviderFactory<F> { /// Trie node provider factory. provider_factory: F, /// Sender for forwarding fetched trie node. tx: mpsc::Sender<Bytes>, } impl<F> WitnessTrieNodeProviderFactory<F> { const fn new(provider_factory: F, tx: mpsc::Sender<Bytes>) -> Self { Self { provider_factory, tx } } } impl<F> TrieNodeProviderFactory for WitnessTrieNodeProviderFactory<F> where F: TrieNodeProviderFactory, F::AccountNodeProvider: TrieNodeProvider, F::StorageNodeProvider: TrieNodeProvider, { type AccountNodeProvider = WitnessTrieNodeProvider<F::AccountNodeProvider>; type StorageNodeProvider = WitnessTrieNodeProvider<F::StorageNodeProvider>; fn account_node_provider(&self) -> Self::AccountNodeProvider { let provider = self.provider_factory.account_node_provider(); WitnessTrieNodeProvider::new(provider, self.tx.clone()) } fn storage_node_provider(&self, account: B256) -> Self::StorageNodeProvider { let provider = self.provider_factory.storage_node_provider(account); WitnessTrieNodeProvider::new(provider, self.tx.clone()) } } #[derive(Debug)] struct WitnessTrieNodeProvider<P> { /// Proof-based blinded. provider: P, /// Sender for forwarding fetched blinded node. tx: mpsc::Sender<Bytes>, } impl<P> WitnessTrieNodeProvider<P> { const fn new(provider: P, tx: mpsc::Sender<Bytes>) -> Self { Self { provider, tx } } } impl<P: TrieNodeProvider> TrieNodeProvider for WitnessTrieNodeProvider<P> { fn trie_node(&self, path: &Nibbles) -> Result<Option<RevealedNode>, SparseTrieError> { let maybe_node = self.provider.trie_node(path)?; if let Some(node) = &maybe_node { self.tx .send(node.node.clone()) .map_err(|error| SparseTrieErrorKind::Other(Box::new(error)))?; } Ok(maybe_node) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/forward_cursor.rs
crates/trie/trie/src/forward_cursor.rs
/// The implementation of forward-only in memory cursor over the entries. /// /// The cursor operates under the assumption that the supplied collection is pre-sorted. #[derive(Debug)] pub struct ForwardInMemoryCursor<'a, K, V> { /// The reference to the pre-sorted collection of entries. entries: std::slice::Iter<'a, (K, V)>, is_empty: bool, } impl<'a, K, V> ForwardInMemoryCursor<'a, K, V> { /// Create new forward cursor positioned at the beginning of the collection. /// /// The cursor expects all of the entries have been sorted in advance. #[inline] pub fn new(entries: &'a [(K, V)]) -> Self { Self { entries: entries.iter(), is_empty: entries.is_empty() } } /// Returns `true` if the cursor is empty, regardless of its position. #[inline] pub const fn is_empty(&self) -> bool { self.is_empty } #[inline] fn peek(&self) -> Option<&(K, V)> { self.entries.clone().next() } #[inline] fn next(&mut self) -> Option<&(K, V)> { self.entries.next() } } impl<K, V> ForwardInMemoryCursor<'_, K, V> where K: PartialOrd + Clone, V: Clone, { /// Returns the first entry from the current cursor position that's greater or equal to the /// provided key. This method advances the cursor forward. pub fn seek(&mut self, key: &K) -> Option<(K, V)> { self.advance_while(|k| k < key) } /// Returns the first entry from the current cursor position that's greater than the provided /// key. This method advances the cursor forward. pub fn first_after(&mut self, key: &K) -> Option<(K, V)> { self.advance_while(|k| k <= key) } /// Advances the cursor forward while `predicate` returns `true` or until the collection is /// exhausted. /// /// Returns the first entry for which `predicate` returns `false` or `None`. The cursor will /// point to the returned entry. fn advance_while(&mut self, predicate: impl Fn(&K) -> bool) -> Option<(K, V)> { let mut entry; loop { entry = self.peek(); if entry.is_some_and(|(k, _)| predicate(k)) { self.next(); } else { break; } } entry.cloned() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_cursor() { let mut cursor = ForwardInMemoryCursor::new(&[(1, ()), (2, ()), (3, ()), (4, ()), (5, ())]); assert_eq!(cursor.seek(&0), Some((1, ()))); assert_eq!(cursor.peek(), Some(&(1, ()))); assert_eq!(cursor.seek(&3), Some((3, ()))); assert_eq!(cursor.peek(), Some(&(3, ()))); assert_eq!(cursor.seek(&3), Some((3, ()))); assert_eq!(cursor.peek(), Some(&(3, ()))); assert_eq!(cursor.seek(&4), Some((4, ()))); assert_eq!(cursor.peek(), Some(&(4, ()))); assert_eq!(cursor.seek(&6), None); assert_eq!(cursor.peek(), None); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/test_utils.rs
crates/trie/trie/src/test_utils.rs
use crate::{HashBuilder, Nibbles}; use alloy_primitives::{Address, B256}; use alloy_rlp::encode_fixed_size; use reth_primitives_traits::Account; use reth_trie_common::triehash::KeccakHasher; /// Re-export of [triehash]. pub use triehash; /// Compute the state root of a given set of accounts using [`triehash::sec_trie_root`]. pub fn state_root<I, S>(accounts: I) -> B256 where I: IntoIterator<Item = (Address, (Account, S))>, S: IntoIterator<Item = (B256, alloy_primitives::FlaggedStorage)>, { let encoded_accounts = accounts.into_iter().map(|(address, (account, storage))| { let storage_root = storage_root(storage); let account = account.into_trie_account(storage_root); (address, alloy_rlp::encode(account)) }); triehash::sec_trie_root::<KeccakHasher, _, _, _>(encoded_accounts) } /// Compute the storage root for a given account using [`triehash::sec_trie_root`]. pub fn storage_root<I: IntoIterator<Item = (B256, alloy_primitives::FlaggedStorage)>>( storage: I, ) -> B256 { let encoded_storage = storage.into_iter().map(|(k, v)| (k, encode_fixed_size(&v))); triehash::sec_trie_root::<KeccakHasher, _, _, _>(encoded_storage) } /// Compute the state root of a given set of accounts with prehashed keys using /// [`triehash::trie_root`]. pub fn state_root_prehashed<I, S>(accounts: I) -> B256 where I: IntoIterator<Item = (B256, (Account, S))>, S: IntoIterator<Item = (B256, alloy_primitives::FlaggedStorage)>, { let encoded_accounts = accounts.into_iter().map(|(address, (account, storage))| { let storage_root = storage_root_prehashed(storage); let account = account.into_trie_account(storage_root); (address, alloy_rlp::encode(account)) }); triehash::trie_root::<KeccakHasher, _, _, _>(encoded_accounts) } /// Compute the storage root for a given account with prehashed slots using [`triehash::trie_root`]. pub fn storage_root_prehashed<I: IntoIterator<Item = (B256, alloy_primitives::FlaggedStorage)>>( storage: I, ) -> B256 { let encoded_storage = storage.into_iter().map(|(k, v)| (k, encode_fixed_size(&v))); triehash::trie_root::<KeccakHasher, _, _, _>(encoded_storage) } /// Compute the state root of a given set of accounts using privacy-aware HashBuilder. /// This function respects the privacy flags in FlaggedStorage values and hashes the keys. pub fn state_root_privacy_aware<I, S>(accounts: I) -> B256 where I: IntoIterator<Item = (Address, (Account, S))>, S: IntoIterator<Item = (B256, alloy_primitives::FlaggedStorage)>, { let mut hash_builder = HashBuilder::default(); // Collect and sort account entries by hashed address for consistent ordering let mut account_entries: Vec<_> = accounts .into_iter() .map(|(address, (account, storage))| { let storage_root = storage_root_privacy_aware(storage); let account = account.into_trie_account(storage_root); (alloy_primitives::keccak256(address), account) }) .collect(); account_entries.sort_by(|a, b| a.0.cmp(&b.0)); // Add each account entry to the hash builder // Note: Account privacy is determined by whether it has private storage for (hashed_address, account) in account_entries { let nibbles = Nibbles::unpack(hashed_address); let encoded_account = alloy_rlp::encode(account); hash_builder.add_leaf(nibbles, &encoded_account, false); } hash_builder.root() } /// Compute the storage root for a given account using privacy-aware HashBuilder. /// This function respects the privacy flags in FlaggedStorage values and hashes the keys. pub fn storage_root_privacy_aware< I: IntoIterator<Item = (B256, alloy_primitives::FlaggedStorage)>, >( storage: I, ) -> B256 { let mut hash_builder = HashBuilder::default(); // Collect and sort storage entries by hashed key for consistent ordering let mut storage_entries: Vec<_> = storage.into_iter().map(|(k, v)| (alloy_primitives::keccak256(k), v)).collect(); storage_entries.sort_by(|a, b| a.0.cmp(&b.0)); // Add each storage entry to the hash builder with privacy awareness for (hashed_key, flagged_storage) in storage_entries { let nibbles = Nibbles::unpack(hashed_key); let encoded_value = encode_fixed_size(&flagged_storage); hash_builder.add_leaf(nibbles, &encoded_value, flagged_storage.is_private()); } hash_builder.root() } /// Compute the storage root for a given account with prehashed slots using privacy-aware /// HashBuilder. This function respects the privacy flags in FlaggedStorage values, unlike the /// standard version above. pub fn storage_root_prehashed_privacy_aware< I: IntoIterator<Item = (B256, alloy_primitives::FlaggedStorage)>, >( storage: I, ) -> B256 { let mut hash_builder = HashBuilder::default(); // Collect and sort storage entries by key for consistent ordering let mut storage_entries: Vec<_> = storage.into_iter().collect(); storage_entries.sort_by(|a, b| a.0.cmp(&b.0)); // Add each storage entry to the hash builder with privacy awareness for (key, flagged_storage) in storage_entries { let nibbles = Nibbles::unpack(key); let encoded_value = encode_fixed_size(&flagged_storage); hash_builder.add_leaf(nibbles, &encoded_value, flagged_storage.is_private()); } hash_builder.root() }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/node_iter.rs
crates/trie/trie/src/node_iter.rs
use crate::{ hashed_cursor::HashedCursor, trie_cursor::TrieCursor, walker::TrieWalker, Nibbles, TrieType, }; use alloy_primitives::B256; use alloy_trie::proof::AddedRemovedKeys; use reth_storage_errors::db::DatabaseError; use tracing::{instrument, trace}; /// Represents a branch node in the trie. #[derive(Debug)] pub struct TrieBranchNode { /// The key associated with the node. pub key: Nibbles, /// The value associated with the node. pub value: B256, /// Indicates whether children are in the trie. pub children_are_in_trie: bool, } impl TrieBranchNode { /// Creates a new `TrieBranchNode`. pub const fn new(key: Nibbles, value: B256, children_are_in_trie: bool) -> Self { Self { key, value, children_are_in_trie } } } /// Represents variants of trie nodes returned by the iteration. #[derive(Debug)] pub enum TrieElement<Value> { /// Branch node. Branch(TrieBranchNode), /// Leaf node. Leaf(B256, Value), } /// Result of calling [`HashedCursor::seek`]. #[derive(Debug)] struct SeekedHashedEntry<V> { /// The key that was seeked. seeked_key: B256, /// The result of the seek. /// If no entry was found for the provided key, this will be [`None`]. result: Option<(B256, V)>, } /// Iterates over trie nodes for hash building. /// /// This iterator depends on the ordering guarantees of [`TrieCursor`], /// and additionally uses hashed cursor lookups when operating on storage tries. #[derive(Debug)] pub struct TrieNodeIter<C, H: HashedCursor, K> { /// The walker over intermediate nodes. pub walker: TrieWalker<C, K>, /// The cursor for the hashed entries. pub hashed_cursor: H, /// The type of the trie. trie_type: TrieType, /// The previous hashed key. If the iteration was previously interrupted, this value can be /// used to resume iterating from the last returned leaf node. previous_hashed_key: Option<B256>, /// Current hashed entry. current_hashed_entry: Option<(B256, H::Value)>, /// Flag indicating whether we should check the current walker key. should_check_walker_key: bool, /// The last seeked hashed entry. /// /// We use it to not seek the same hashed entry twice, and instead reuse it. last_seeked_hashed_entry: Option<SeekedHashedEntry<H::Value>>, #[cfg(feature = "metrics")] metrics: crate::metrics::TrieNodeIterMetrics, /// Stores the result of the last successful [`Self::next_hashed_entry`], used to avoid a /// redundant [`Self::seek_hashed_entry`] call if the walker points to the same key that /// was just returned by `next()`. last_next_result: Option<(B256, H::Value)>, } impl<C, H: HashedCursor, K> TrieNodeIter<C, H, K> where H::Value: Copy, K: AsRef<AddedRemovedKeys>, { /// Creates a new [`TrieNodeIter`] for the state trie. pub fn state_trie(walker: TrieWalker<C, K>, hashed_cursor: H) -> Self { Self::new(walker, hashed_cursor, TrieType::State) } /// Creates a new [`TrieNodeIter`] for the storage trie. pub fn storage_trie(walker: TrieWalker<C, K>, hashed_cursor: H) -> Self { Self::new(walker, hashed_cursor, TrieType::Storage) } /// Creates a new [`TrieNodeIter`]. fn new(walker: TrieWalker<C, K>, hashed_cursor: H, trie_type: TrieType) -> Self { Self { walker, hashed_cursor, trie_type, previous_hashed_key: None, current_hashed_entry: None, should_check_walker_key: false, last_seeked_hashed_entry: None, #[cfg(feature = "metrics")] metrics: crate::metrics::TrieNodeIterMetrics::new(trie_type), last_next_result: None, } } /// Sets the last iterated hashed key and returns the modified [`TrieNodeIter`]. /// This is used to resume iteration from the last checkpoint. pub const fn with_last_hashed_key(mut self, previous_hashed_key: B256) -> Self { self.previous_hashed_key = Some(previous_hashed_key); self } /// Seeks the hashed cursor to the given key. /// /// If the key is the same as the last seeked key, the result of the last seek is returned. /// /// If `metrics` feature is enabled, also updates the metrics. fn seek_hashed_entry(&mut self, key: B256) -> Result<Option<(B256, H::Value)>, DatabaseError> { if let Some((last_key, last_value)) = self.last_next_result { if last_key == key { trace!(target: "trie::node_iter", seek_key = ?key, "reusing result from last next() call instead of seeking"); self.last_next_result = None; // Consume the cached value let result = Some((last_key, last_value)); self.last_seeked_hashed_entry = Some(SeekedHashedEntry { seeked_key: key, result }); return Ok(result); } } if let Some(entry) = self .last_seeked_hashed_entry .as_ref() .filter(|entry| entry.seeked_key == key) .map(|entry| entry.result) { #[cfg(feature = "metrics")] self.metrics.inc_leaf_nodes_same_seeked(); return Ok(entry); } trace!(target: "trie::node_iter", ?key, "performing hashed cursor seek"); let result = self.hashed_cursor.seek(key)?; self.last_seeked_hashed_entry = Some(SeekedHashedEntry { seeked_key: key, result }); #[cfg(feature = "metrics")] { self.metrics.inc_leaf_nodes_seeked(); } Ok(result) } /// Advances the hashed cursor to the next entry. /// /// If `metrics` feature is enabled, also updates the metrics. fn next_hashed_entry(&mut self) -> Result<Option<(B256, H::Value)>, DatabaseError> { let result = self.hashed_cursor.next(); self.last_next_result = result.clone()?; #[cfg(feature = "metrics")] { self.metrics.inc_leaf_nodes_advanced(); } result } } impl<C, H, K> TrieNodeIter<C, H, K> where C: TrieCursor, H: HashedCursor, H::Value: Copy, K: AsRef<AddedRemovedKeys>, { /// Return the next trie node to be added to the hash builder. /// /// Returns the nodes using this algorithm: /// 1. Return the current intermediate branch node if it hasn't been updated. /// 2. Advance the trie walker to the next intermediate branch node and retrieve next /// unprocessed key. /// 3. Reposition the hashed cursor on the next unprocessed key. /// 4. Return every hashed entry up to the key of the current intermediate branch node. /// 5. Repeat. /// /// NOTE: The iteration will start from the key of the previous hashed entry if it was supplied. #[instrument( level = "trace", target = "trie::node_iter", skip_all, fields(trie_type = ?self.trie_type), ret )] pub fn try_next( &mut self, ) -> Result<Option<TrieElement<<H as HashedCursor>::Value>>, DatabaseError> { loop { // If the walker has a key... if let Some(key) = self.walker.key() { // Ensure that the current walker key shouldn't be checked and there's no previous // hashed key if !self.should_check_walker_key && self.previous_hashed_key.is_none() { // Make sure we check the next walker key, because we only know we can skip the // current one. self.should_check_walker_key = true; // If it's possible to skip the current node in the walker, return a branch node if self.walker.can_skip_current_node { #[cfg(feature = "metrics")] self.metrics.inc_branch_nodes_returned(); return Ok(Some(TrieElement::Branch(TrieBranchNode::new( *key, self.walker.hash().unwrap(), self.walker.children_are_in_trie(), )))); } } } // If there's a hashed entry... if let Some((hashed_key, value)) = self.current_hashed_entry.take() { // Check if the walker's key is less than the key of the current hashed entry if self.walker.key().is_some_and(|key| key < &Nibbles::unpack(hashed_key)) { self.should_check_walker_key = false; continue } // Set the next hashed entry as a leaf node and return trace!(target: "trie::node_iter", ?hashed_key, "next hashed entry"); self.current_hashed_entry = self.next_hashed_entry()?; #[cfg(feature = "metrics")] self.metrics.inc_leaf_nodes_returned(); return Ok(Some(TrieElement::Leaf(hashed_key, value))) } // Handle seeking and advancing based on the previous hashed key match self.previous_hashed_key.take() { Some(hashed_key) => { trace!(target: "trie::node_iter", ?hashed_key, "seeking to the previous hashed entry"); // Seek to the previous hashed key and get the next hashed entry self.seek_hashed_entry(hashed_key)?; self.current_hashed_entry = self.next_hashed_entry()?; } None => { // Get the seek key and set the current hashed entry based on walker's next // unprocessed key let (seek_key, seek_prefix) = match self.walker.next_unprocessed_key() { Some(key) => key, None => break, // no more keys }; trace!( target: "trie::node_iter", ?seek_key, can_skip_current_node = self.walker.can_skip_current_node, last = ?self.walker.stack.last(), "seeking to the next unprocessed hashed entry" ); let can_skip_node = self.walker.can_skip_current_node; self.walker.advance()?; trace!( target: "trie::node_iter", last = ?self.walker.stack.last(), "advanced walker" ); // We should get the iterator to return a branch node if we can skip the // current node and the tree flag for the current node is set. // // `can_skip_node` is already set when the hash flag is set, so we don't need // to check for the hash flag explicitly. // // It is possible that the branch node at the key `seek_key` is not stored in // the database, so the walker will advance to the branch node after it. Because // of this, we need to check that the current walker key has a prefix of the key // that we seeked to. if can_skip_node && self.walker.key().is_some_and(|key| key.starts_with(&seek_prefix)) && self.walker.children_are_in_trie() { trace!( target: "trie::node_iter", ?seek_key, walker_hash = ?self.walker.maybe_hash(), "skipping hashed seek" ); self.should_check_walker_key = false; continue } self.current_hashed_entry = self.seek_hashed_entry(seek_key)?; } } } Ok(None) } } #[cfg(test)] mod tests { use crate::{ hashed_cursor::{ mock::MockHashedCursorFactory, noop::NoopHashedAccountCursor, HashedCursorFactory, HashedPostStateAccountCursor, }, mock::{KeyVisit, KeyVisitType}, trie_cursor::{ mock::MockTrieCursorFactory, noop::NoopAccountTrieCursor, TrieCursorFactory, }, walker::TrieWalker, }; use alloy_primitives::{ b256, map::{B256Map, HashMap}, }; use alloy_trie::{ BranchNodeCompact, HashBuilder, Nibbles, TrieAccount, TrieMask, EMPTY_ROOT_HASH, }; use itertools::Itertools; use reth_primitives_traits::Account; use reth_trie_common::{ prefix_set::PrefixSetMut, updates::TrieUpdates, BranchNode, HashedPostState, LeafNode, RlpNode, }; use std::collections::BTreeMap; use super::{TrieElement, TrieNodeIter}; /// Calculate the branch node stored in the database by feeding the provided state to the hash /// builder and taking the trie updates. fn get_hash_builder_branch_nodes( state: impl IntoIterator<Item = (Nibbles, Account)> + Clone, ) -> HashMap<Nibbles, BranchNodeCompact> { let mut hash_builder = HashBuilder::default().with_updates(true); let mut prefix_set = PrefixSetMut::default(); prefix_set.extend_keys(state.clone().into_iter().map(|(nibbles, _)| nibbles)); let walker = TrieWalker::<_>::state_trie(NoopAccountTrieCursor, prefix_set.freeze()); let hashed_post_state = HashedPostState::default() .with_accounts(state.into_iter().map(|(nibbles, account)| { (nibbles.pack().into_inner().unwrap().into(), Some(account)) })) .into_sorted(); let mut node_iter = TrieNodeIter::state_trie( walker, HashedPostStateAccountCursor::new( NoopHashedAccountCursor::default(), hashed_post_state.accounts(), ), ); while let Some(node) = node_iter.try_next().unwrap() { match node { TrieElement::Branch(branch) => { hash_builder.add_branch(branch.key, branch.value, branch.children_are_in_trie); } TrieElement::Leaf(key, account) => { hash_builder.add_leaf( Nibbles::unpack(key), &alloy_rlp::encode(account.into_trie_account(EMPTY_ROOT_HASH)), false, // account nodes are always public ); } } } hash_builder.root(); let mut trie_updates = TrieUpdates::default(); trie_updates.finalize(hash_builder, Default::default(), Default::default()); trie_updates.account_nodes } #[test] fn test_trie_node_iter() { fn empty_leaf_rlp_for_key(key: Nibbles) -> RlpNode { RlpNode::from_rlp(&alloy_rlp::encode(LeafNode::new( key, alloy_rlp::encode(TrieAccount::default()), false, // account nodes are always public ))) } reth_tracing::init_test_tracing(); // Extension (Key = 0x0000000000000000000000000000000000000000000000000000000000000) // └── Branch (`branch_node_0`) // ├── 0 -> Branch (`branch_node_1`) // │ ├── 0 -> Leaf (`account_1`, Key = 0x0) // │ └── 1 -> Leaf (`account_2`, Key = 0x0) // ├── 1 -> Branch (`branch_node_2`) // │ ├── 0 -> Branch (`branch_node_3`) // │ │ ├── 0 -> Leaf (`account_3`, marked as changed) // │ │ └── 1 -> Leaf (`account_4`) // │ └── 1 -> Leaf (`account_5`, Key = 0x0) let account_1 = b256!("0x0000000000000000000000000000000000000000000000000000000000000000"); let account_2 = b256!("0x0000000000000000000000000000000000000000000000000000000000000010"); let account_3 = b256!("0x0000000000000000000000000000000000000000000000000000000000000100"); let account_4 = b256!("0x0000000000000000000000000000000000000000000000000000000000000101"); let account_5 = b256!("0x0000000000000000000000000000000000000000000000000000000000000110"); let empty_account = Account::default(); let hash_builder_branch_nodes = get_hash_builder_branch_nodes(vec![ (Nibbles::unpack(account_1), empty_account), (Nibbles::unpack(account_2), empty_account), (Nibbles::unpack(account_3), empty_account), (Nibbles::unpack(account_4), empty_account), (Nibbles::unpack(account_5), empty_account), ]); let branch_node_1_rlp = RlpNode::from_rlp(&alloy_rlp::encode(BranchNode::new( vec![ empty_leaf_rlp_for_key(Nibbles::from_nibbles([0])), empty_leaf_rlp_for_key(Nibbles::from_nibbles([0])), ], TrieMask::new(0b11), ))); let branch_node_3_rlp = RlpNode::from_rlp(&alloy_rlp::encode(BranchNode::new( vec![ empty_leaf_rlp_for_key(Nibbles::default()), empty_leaf_rlp_for_key(Nibbles::default()), ], TrieMask::new(0b11), ))); let branch_node_2 = ( Nibbles::from_nibbles([vec![0; 61], vec![1]].concat()), BranchNodeCompact::new( TrieMask::new(0b11), TrieMask::new(0b00), TrieMask::new(0b01), vec![branch_node_3_rlp.as_hash().unwrap()], None, ), ); let branch_node_2_rlp = RlpNode::from_rlp(&alloy_rlp::encode(BranchNode::new( vec![branch_node_3_rlp, empty_leaf_rlp_for_key(Nibbles::from_nibbles([0]))], TrieMask::new(0b11), ))); let branch_node_0 = ( Nibbles::from_nibbles([0; 61]), BranchNodeCompact::new( TrieMask::new(0b11), TrieMask::new(0b10), TrieMask::new(0b11), vec![branch_node_1_rlp.as_hash().unwrap(), branch_node_2_rlp.as_hash().unwrap()], None, ), ); let mock_trie_nodes = vec![branch_node_0.clone(), branch_node_2.clone()]; pretty_assertions::assert_eq!( hash_builder_branch_nodes.into_iter().sorted().collect::<Vec<_>>(), mock_trie_nodes, ); let trie_cursor_factory = MockTrieCursorFactory::new(mock_trie_nodes.into_iter().collect(), B256Map::default()); // Mark the account 3 as changed. let mut prefix_set = PrefixSetMut::default(); prefix_set.insert(Nibbles::unpack(account_3)); let prefix_set = prefix_set.freeze(); let walker = TrieWalker::<_>::state_trie( trie_cursor_factory.account_trie_cursor().unwrap(), prefix_set, ); let hashed_cursor_factory = MockHashedCursorFactory::new( BTreeMap::from([ (account_1, empty_account), (account_2, empty_account), (account_3, empty_account), (account_4, empty_account), (account_5, empty_account), ]), B256Map::default(), ); let mut iter = TrieNodeIter::state_trie( walker, hashed_cursor_factory.hashed_account_cursor().unwrap(), ); // Walk the iterator until it's exhausted. while iter.try_next().unwrap().is_some() {} pretty_assertions::assert_eq!( *trie_cursor_factory.visited_account_keys(), vec![ KeyVisit { visit_type: KeyVisitType::SeekExact(Nibbles::default()), visited_key: None }, KeyVisit { visit_type: KeyVisitType::SeekNonExact(Nibbles::from_nibbles([0x0])), visited_key: Some(branch_node_0.0) }, KeyVisit { visit_type: KeyVisitType::SeekNonExact(branch_node_2.0), visited_key: Some(branch_node_2.0) }, KeyVisit { visit_type: KeyVisitType::SeekNonExact(Nibbles::from_nibbles([0x1])), visited_key: None } ] ); pretty_assertions::assert_eq!( *hashed_cursor_factory.visited_account_keys(), vec![ // Why do we always seek this key first? KeyVisit { visit_type: KeyVisitType::SeekNonExact(account_1), visited_key: Some(account_1) }, // Seek to the modified account. KeyVisit { visit_type: KeyVisitType::SeekNonExact(account_3), visited_key: Some(account_3) }, // Collect the siblings of the modified account KeyVisit { visit_type: KeyVisitType::Next, visited_key: Some(account_4) }, KeyVisit { visit_type: KeyVisitType::Next, visited_key: Some(account_5) }, KeyVisit { visit_type: KeyVisitType::Next, visited_key: None }, ], ); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/verify.rs
crates/trie/trie/src/verify.rs
use crate::{ hashed_cursor::{HashedCursor, HashedCursorFactory}, progress::{IntermediateStateRootState, StateRootProgress}, trie::StateRoot, trie_cursor::{ depth_first::{self, DepthFirstTrieIterator}, noop::NoopTrieCursorFactory, TrieCursor, TrieCursorFactory, }, Nibbles, }; use alloy_primitives::B256; use alloy_trie::BranchNodeCompact; use reth_execution_errors::StateRootError; use reth_storage_errors::db::DatabaseError; use std::cmp::Ordering; use tracing::trace; /// Used by [`StateRootBranchNodesIter`] to iterate over branch nodes in a state root. #[derive(Debug)] enum BranchNode { Account(Nibbles, BranchNodeCompact), Storage(B256, Nibbles, BranchNodeCompact), } /// Iterates over branch nodes produced by a [`StateRoot`]. The `StateRoot` will only used the /// hashed accounts/storages tables, meaning it is recomputing the trie from scratch without the use /// of the trie tables. /// /// [`BranchNode`]s are iterated over such that: /// * Account nodes and storage nodes may be interspersed. /// * Storage nodes for the same account will be ordered by ascending path relative to each other. /// * Account nodes will be ordered by ascending path relative to each other. /// * All storage nodes for one account will finish before storage nodes for another account are /// started. In other words, if the current storage account is not equal to the previous, the /// previous has no more nodes. #[derive(Debug)] struct StateRootBranchNodesIter<H> { hashed_cursor_factory: H, account_nodes: Vec<(Nibbles, BranchNodeCompact)>, storage_tries: Vec<(B256, Vec<(Nibbles, BranchNodeCompact)>)>, curr_storage: Option<(B256, Vec<(Nibbles, BranchNodeCompact)>)>, intermediate_state: Option<Box<IntermediateStateRootState>>, complete: bool, } impl<H> StateRootBranchNodesIter<H> { fn new(hashed_cursor_factory: H) -> Self { Self { hashed_cursor_factory, account_nodes: Default::default(), storage_tries: Default::default(), curr_storage: None, intermediate_state: None, complete: false, } } /// Sorts a Vec of updates such that it is ready to be yielded from the `next` method. We yield /// by popping off of the account/storage vecs, so we sort them in reverse order. /// /// Depth-first sorting is used because this is the order that the `HashBuilder` computes /// branch nodes internally, even if it produces them as `B256Map`s. fn sort_updates(updates: &mut [(Nibbles, BranchNodeCompact)]) { updates.sort_unstable_by(|a, b| depth_first::cmp(&b.0, &a.0)); } } impl<H: HashedCursorFactory + Clone> Iterator for StateRootBranchNodesIter<H> { type Item = Result<BranchNode, StateRootError>; fn next(&mut self) -> Option<Self::Item> { loop { // If we already started iterating through a storage trie's updates, continue doing // so. if let Some((account, storage_updates)) = self.curr_storage.as_mut() { if let Some((path, node)) = storage_updates.pop() { let node = BranchNode::Storage(*account, path, node); return Some(Ok(node)) } } // If there's not a storage trie already being iterated over than check if there's a // storage trie we could start iterating over. if let Some((account, storage_updates)) = self.storage_tries.pop() { debug_assert!(!storage_updates.is_empty()); self.curr_storage = Some((account, storage_updates)); continue; } // `storage_updates` is empty, check if there are account updates. if let Some((path, node)) = self.account_nodes.pop() { return Some(Ok(BranchNode::Account(path, node))) } // All data from any previous runs of the `StateRoot` has been produced, run the next // partial computation, unless `StateRootProgress::Complete` has been returned in which // case iteration is over. if self.complete { return None } let state_root = StateRoot::new(NoopTrieCursorFactory, self.hashed_cursor_factory.clone()) .with_intermediate_state(self.intermediate_state.take().map(|s| *s)); let updates = match state_root.root_with_progress() { Err(err) => return Some(Err(err)), Ok(StateRootProgress::Complete(_, _, updates)) => { self.complete = true; updates } Ok(StateRootProgress::Progress(intermediate_state, _, updates)) => { self.intermediate_state = Some(intermediate_state); updates } }; // collect account updates and sort them in descending order, so that when we pop them // off the Vec they are popped in ascending order. self.account_nodes.extend(updates.account_nodes); Self::sort_updates(&mut self.account_nodes); self.storage_tries = updates .storage_tries .into_iter() .filter_map(|(account, t)| { (!t.storage_nodes.is_empty()).then(|| { let mut storage_nodes = t.storage_nodes.into_iter().collect::<Vec<_>>(); Self::sort_updates(&mut storage_nodes); (account, storage_nodes) }) }) .collect::<Vec<_>>(); // `root_with_progress` will output storage updates ordered by their account hash. If // `root_with_progress` only returns a partial result then it will pick up with where // it left off in the storage trie on the next run. // // By sorting by the account we ensure that we continue with the partially processed // trie (the last of the previous run) first. We sort in reverse order because we pop // off of this Vec. self.storage_tries.sort_unstable_by(|a, b| b.0.cmp(&a.0)); // loop back to the top. } } } /// Output describes an inconsistency found when comparing the hashed state tables /// ([`HashedCursorFactory`]) with that of the trie tables ([`TrieCursorFactory`]). The hashed /// tables are considered the source of truth; outputs are on the part of the trie tables. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Output { /// An extra account node was found. AccountExtra(Nibbles, BranchNodeCompact), /// A extra storage node was found. StorageExtra(B256, Nibbles, BranchNodeCompact), /// An account node had the wrong value. AccountWrong { /// Path of the node path: Nibbles, /// The node's expected value. expected: BranchNodeCompact, /// The node's found value. found: BranchNodeCompact, }, /// A storage node had the wrong value. StorageWrong { /// The account the storage trie belongs to. account: B256, /// Path of the node path: Nibbles, /// The node's expected value. expected: BranchNodeCompact, /// The node's found value. found: BranchNodeCompact, }, /// An account node was missing. AccountMissing(Nibbles, BranchNodeCompact), /// A storage node was missing. StorageMissing(B256, Nibbles, BranchNodeCompact), /// Progress indicator with the last seen account path. Progress(Nibbles), } /// Verifies the contents of a trie table against some other data source which is able to produce /// stored trie nodes. #[derive(Debug)] struct SingleVerifier<I> { account: Option<B256>, // None for accounts trie trie_iter: I, curr: Option<(Nibbles, BranchNodeCompact)>, } impl<C: TrieCursor> SingleVerifier<DepthFirstTrieIterator<C>> { fn new(account: Option<B256>, trie_cursor: C) -> Result<Self, DatabaseError> { let mut trie_iter = DepthFirstTrieIterator::new(trie_cursor); let curr = trie_iter.next().transpose()?; Ok(Self { account, trie_iter, curr }) } const fn output_extra(&self, path: Nibbles, node: BranchNodeCompact) -> Output { if let Some(account) = self.account { Output::StorageExtra(account, path, node) } else { Output::AccountExtra(path, node) } } const fn output_wrong( &self, path: Nibbles, expected: BranchNodeCompact, found: BranchNodeCompact, ) -> Output { if let Some(account) = self.account { Output::StorageWrong { account, path, expected, found } } else { Output::AccountWrong { path, expected, found } } } const fn output_missing(&self, path: Nibbles, node: BranchNodeCompact) -> Output { if let Some(account) = self.account { Output::StorageMissing(account, path, node) } else { Output::AccountMissing(path, node) } } /// Called with the next path and node in the canonical sequence of stored trie nodes. Will /// append to the given `outputs` Vec if walking the trie cursor produces data /// inconsistent with that given. /// /// `next` must be called with paths in depth-first order. fn next( &mut self, outputs: &mut Vec<Output>, path: Nibbles, node: BranchNodeCompact, ) -> Result<(), DatabaseError> { loop { // `curr` is None only if the end of the iterator has been reached. Any further nodes // found must be considered missing. if self.curr.is_none() { outputs.push(self.output_missing(path, node)); return Ok(()) } let (curr_path, curr_node) = self.curr.as_ref().expect("not None"); trace!(target: "trie::verify", account=?self.account, ?curr_path, ?path, "Current cursor node"); // Use depth-first ordering for comparison match depth_first::cmp(&path, curr_path) { Ordering::Less => { // If the given path comes before the cursor's current path in depth-first // order, then the given path was not produced by the cursor. outputs.push(self.output_missing(path, node)); return Ok(()) } Ordering::Equal => { // If the the current path matches the given one (happy path) but the nodes // aren't equal then we produce a wrong node. Either way we want to move the // iterator forward. if *curr_node != node { outputs.push(self.output_wrong(path, node, curr_node.clone())) } self.curr = self.trie_iter.next().transpose()?; return Ok(()) } Ordering::Greater => { // If the given path comes after the current path in depth-first order, // it means the cursor's path was not found by the caller (otherwise it would // have hit the equal case) and so is extraneous. outputs.push(self.output_extra(*curr_path, curr_node.clone())); self.curr = self.trie_iter.next().transpose()?; // back to the top of the loop to check the latest `self.curr` value against the // given path/node. } } } } /// Must be called once there are no more calls to `next` to made. All further nodes produced /// by the iterator will be considered extraneous. fn finalize(&mut self, outputs: &mut Vec<Output>) -> Result<(), DatabaseError> { loop { if let Some((curr_path, curr_node)) = self.curr.take() { outputs.push(self.output_extra(curr_path, curr_node)); self.curr = self.trie_iter.next().transpose()?; } else { return Ok(()) } } } } /// Checks that data stored in the trie database is consistent, using hashed accounts/storages /// database tables as the source of truth. This will iteratively re-compute the entire trie based /// on the hashed state, and produce any discovered [`Output`]s via the `next` method. #[derive(Debug)] pub struct Verifier<T: TrieCursorFactory, H> { trie_cursor_factory: T, hashed_cursor_factory: H, branch_node_iter: StateRootBranchNodesIter<H>, outputs: Vec<Output>, account: SingleVerifier<DepthFirstTrieIterator<T::AccountTrieCursor>>, storage: Option<(B256, SingleVerifier<DepthFirstTrieIterator<T::StorageTrieCursor>>)>, complete: bool, } impl<T: TrieCursorFactory + Clone, H: HashedCursorFactory + Clone> Verifier<T, H> { /// Creates a new verifier instance. pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Result<Self, DatabaseError> { Ok(Self { trie_cursor_factory: trie_cursor_factory.clone(), hashed_cursor_factory: hashed_cursor_factory.clone(), branch_node_iter: StateRootBranchNodesIter::new(hashed_cursor_factory), outputs: Default::default(), account: SingleVerifier::new(None, trie_cursor_factory.account_trie_cursor()?)?, storage: None, complete: false, }) } } impl<T: TrieCursorFactory, H: HashedCursorFactory + Clone> Verifier<T, H> { fn new_storage( &mut self, account: B256, path: Nibbles, node: BranchNodeCompact, ) -> Result<(), DatabaseError> { let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(account)?; let mut storage = SingleVerifier::new(Some(account), trie_cursor)?; storage.next(&mut self.outputs, path, node)?; self.storage = Some((account, storage)); Ok(()) } /// This method is called using the account hashes at the boundary of [`BranchNode::Storage`] /// sequences, ie once the [`StateRootBranchNodesIter`] has begun yielding storage nodes for a /// different account than it was yielding previously. All accounts between the two should have /// empty storages. fn verify_empty_storages( &mut self, last_account: B256, next_account: B256, start_inclusive: bool, end_inclusive: bool, ) -> Result<(), DatabaseError> { let mut account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?; let mut account_seeked = false; if !start_inclusive { account_seeked = true; account_cursor.seek(last_account)?; } loop { let Some((curr_account, _)) = (if account_seeked { account_cursor.next()? } else { account_seeked = true; account_cursor.seek(last_account)? }) else { return Ok(()) }; if curr_account < next_account || (end_inclusive && curr_account == next_account) { trace!(target: "trie::verify", account = ?curr_account, "Verying account has empty storage"); let mut storage_cursor = self.trie_cursor_factory.storage_trie_cursor(curr_account)?; let mut seeked = false; while let Some((path, node)) = if seeked { storage_cursor.next()? } else { seeked = true; storage_cursor.seek(Nibbles::new())? } { self.outputs.push(Output::StorageExtra(curr_account, path, node)); } } else { return Ok(()) } } } fn try_next(&mut self) -> Result<(), StateRootError> { match self.branch_node_iter.next().transpose()? { None => { self.account.finalize(&mut self.outputs)?; if let Some((prev_account, storage)) = self.storage.as_mut() { storage.finalize(&mut self.outputs)?; // If there was a previous storage account, and it is the final one, then we // need to validate that all accounts coming after it have empty storages. let prev_account = *prev_account; // Calculate the max possible account address. let mut max_account = B256::ZERO; max_account.reverse(); self.verify_empty_storages(prev_account, max_account, false, true)?; } self.complete = true; } Some(BranchNode::Account(path, node)) => { trace!(target: "trie::verify", ?path, "Account node from state root"); self.account.next(&mut self.outputs, path, node)?; // Push progress indicator if !path.is_empty() { self.outputs.push(Output::Progress(path)); } } Some(BranchNode::Storage(account, path, node)) => { trace!(target: "trie::verify", ?account, ?path, "Storage node from state root"); match self.storage.as_mut() { None => { // First storage account - check for any empty storages before it self.verify_empty_storages(B256::ZERO, account, true, false)?; self.new_storage(account, path, node)?; } Some((prev_account, storage)) if *prev_account == account => { storage.next(&mut self.outputs, path, node)?; } Some((prev_account, storage)) => { storage.finalize(&mut self.outputs)?; // Clear any storage entries between the previous account and the new one let prev_account = *prev_account; self.verify_empty_storages(prev_account, account, false, false)?; self.new_storage(account, path, node)?; } } } } // If any outputs were appended we want to reverse them, so they are popped off // in the same order they were appended. self.outputs.reverse(); Ok(()) } } impl<T: TrieCursorFactory, H: HashedCursorFactory + Clone> Iterator for Verifier<T, H> { type Item = Result<Output, StateRootError>; fn next(&mut self) -> Option<Self::Item> { loop { if let Some(output) = self.outputs.pop() { return Some(Ok(output)) } if self.complete { return None } if let Err(err) = self.try_next() { return Some(Err(err)) } } } } #[cfg(test)] mod tests { use super::*; use crate::{ hashed_cursor::mock::MockHashedCursorFactory, trie_cursor::mock::{MockTrieCursor, MockTrieCursorFactory}, }; use alloy_primitives::{address, keccak256, map::B256Map, U256}; use alloy_trie::TrieMask; use assert_matches::assert_matches; use reth_primitives_traits::Account; use std::collections::BTreeMap; /// Helper function to create a simple test `BranchNodeCompact` fn test_branch_node( state_mask: u16, tree_mask: u16, hash_mask: u16, hashes: Vec<B256>, ) -> BranchNodeCompact { // Ensure the number of hashes matches the number of bits set in hash_mask let expected_hashes = hash_mask.count_ones() as usize; let mut final_hashes = hashes; let mut counter = 100u8; while final_hashes.len() < expected_hashes { final_hashes.push(B256::from([counter; 32])); counter += 1; } final_hashes.truncate(expected_hashes); BranchNodeCompact::new( TrieMask::new(state_mask), TrieMask::new(tree_mask), TrieMask::new(hash_mask), final_hashes, None, ) } /// Helper function to create a simple test `MockTrieCursor` fn create_mock_cursor(trie_nodes: BTreeMap<Nibbles, BranchNodeCompact>) -> MockTrieCursor { let factory = MockTrieCursorFactory::new(trie_nodes, B256Map::default()); factory.account_trie_cursor().unwrap() } #[test] fn test_state_root_branch_nodes_iter_empty() { // Test with completely empty state let factory = MockHashedCursorFactory::new(BTreeMap::new(), B256Map::default()); let mut iter = StateRootBranchNodesIter::new(factory); // Collect all results - with empty state, should complete without producing nodes let mut count = 0; for result in iter.by_ref() { assert!(result.is_ok(), "Unexpected error: {:?}", result.unwrap_err()); count += 1; // Prevent infinite loop in test assert!(count <= 1000, "Too many iterations"); } assert!(iter.complete); } #[test] fn test_state_root_branch_nodes_iter_basic() { // Simple test with a few accounts and storage let mut accounts = BTreeMap::new(); let mut storage_tries = B256Map::default(); // Create test accounts let addr1 = keccak256(address!("0000000000000000000000000000000000000001")); accounts.insert( addr1, Account { nonce: 1, balance: U256::from(1000), bytecode_hash: Some(keccak256(b"code1")), }, ); // Add storage for the account let mut storage1 = BTreeMap::new(); storage1.insert(keccak256(B256::from(U256::from(1))), U256::from(100).into()); storage1.insert(keccak256(B256::from(U256::from(2))), U256::from(200).into()); storage_tries.insert(addr1, storage1); let factory = MockHashedCursorFactory::new(accounts, storage_tries); let mut iter = StateRootBranchNodesIter::new(factory); // Collect nodes and verify basic properties let mut account_paths = Vec::new(); let mut storage_paths_by_account: B256Map<Vec<Nibbles>> = B256Map::default(); let mut iterations = 0; for result in iter.by_ref() { iterations += 1; assert!(iterations <= 10000, "Too many iterations - possible infinite loop"); match result { Ok(BranchNode::Account(path, _)) => { account_paths.push(path); } Ok(BranchNode::Storage(account, path, _)) => { storage_paths_by_account.entry(account).or_default().push(path); } Err(e) => panic!("Unexpected error: {:?}", e), } } // Verify account paths are in ascending order for i in 1..account_paths.len() { assert!( account_paths[i - 1] < account_paths[i], "Account paths should be in ascending order" ); } // Verify storage paths for each account are in ascending order for (account, paths) in storage_paths_by_account { for i in 1..paths.len() { assert!( paths[i - 1] < paths[i], "Storage paths for account {:?} should be in ascending order", account ); } } assert!(iter.complete); } #[test] fn test_state_root_branch_nodes_iter_multiple_accounts() { // Test with multiple accounts to verify ordering let mut accounts = BTreeMap::new(); let mut storage_tries = B256Map::default(); // Create multiple test addresses for i in 1u8..=3 { let addr = keccak256([i; 20]); accounts.insert( addr, Account { nonce: i as u64, balance: U256::from(i as u64 * 1000), bytecode_hash: (i == 2).then(|| keccak256([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).into()); } if !storage.is_empty() { storage_tries.insert(addr, storage); } } let factory = MockHashedCursorFactory::new(accounts, storage_tries); let mut iter = StateRootBranchNodesIter::new(factory); // Track what we see let mut seen_storage_accounts = Vec::new(); let mut current_storage_account = None; let mut iterations = 0; for result in iter.by_ref() { iterations += 1; assert!(iterations <= 10000, "Too many iterations"); match result { Ok(BranchNode::Storage(account, _, _)) => { if current_storage_account != Some(account) { // Verify we don't revisit a storage account assert!( !seen_storage_accounts.contains(&account), "Should not revisit storage account {:?}", account ); seen_storage_accounts.push(account); current_storage_account = Some(account); } } Ok(BranchNode::Account(_, _)) => { // Account nodes are fine } Err(e) => panic!("Unexpected error: {:?}", e), } } assert!(iter.complete); } #[test] fn test_single_verifier_new() { // Test creating a new SingleVerifier for account trie let trie_nodes = BTreeMap::from([( Nibbles::from_nibbles([0x1]), test_branch_node(0b1111, 0, 0, vec![]), )]); let cursor = create_mock_cursor(trie_nodes); let verifier = SingleVerifier::new(None, cursor).unwrap(); // Should have seeked to the beginning and found the first node assert!(verifier.curr.is_some()); } #[test] fn test_single_verifier_next_exact_match() { // Test when the expected node matches exactly let node1 = test_branch_node(0b1111, 0, 0b1111, vec![B256::from([1u8; 32])]); let node2 = test_branch_node(0b0101, 0b0001, 0b0100, vec![B256::from([2u8; 32])]); let trie_nodes = BTreeMap::from([ (Nibbles::from_nibbles([0x1]), node1.clone()), (Nibbles::from_nibbles([0x2]), node2), ]); let cursor = create_mock_cursor(trie_nodes); let mut verifier = SingleVerifier::new(None, cursor).unwrap(); let mut outputs = Vec::new(); // Call next with the exact node that exists verifier.next(&mut outputs, Nibbles::from_nibbles([0x1]), node1).unwrap(); // Should have no outputs assert!(outputs.is_empty()); } #[test] fn test_single_verifier_next_wrong_value() { // Test when the path matches but value is different let node_in_trie = test_branch_node(0b1111, 0, 0b1111, vec![B256::from([1u8; 32])]); let node_expected = test_branch_node(0b0101, 0b0001, 0b0100, vec![B256::from([2u8; 32])]); let trie_nodes = BTreeMap::from([(Nibbles::from_nibbles([0x1]), node_in_trie.clone())]); let cursor = create_mock_cursor(trie_nodes); let mut verifier = SingleVerifier::new(None, cursor).unwrap(); let mut outputs = Vec::new(); // Call next with different node value verifier.next(&mut outputs, Nibbles::from_nibbles([0x1]), node_expected.clone()).unwrap(); // Should have one "wrong" output assert_eq!(outputs.len(), 1); assert_matches!( &outputs[0], Output::AccountWrong { path, expected, found } if *path == Nibbles::from_nibbles([0x1]) && *expected == node_expected && *found == node_in_trie ); } #[test] fn test_single_verifier_next_missing() { // Test when expected node doesn't exist in trie let node1 = test_branch_node(0b1111, 0, 0b1111, vec![B256::from([1u8; 32])]); let node_missing = test_branch_node(0b0101, 0b0001, 0b0100, vec![B256::from([2u8; 32])]); let trie_nodes = BTreeMap::from([(Nibbles::from_nibbles([0x3]), node1)]); let cursor = create_mock_cursor(trie_nodes); let mut verifier = SingleVerifier::new(None, cursor).unwrap(); let mut outputs = Vec::new(); // Call next with a node that comes before any in the trie verifier.next(&mut outputs, Nibbles::from_nibbles([0x1]), node_missing.clone()).unwrap(); // Should have one "missing" output assert_eq!(outputs.len(), 1); assert_matches!( &outputs[0], Output::AccountMissing(path, node) if *path == Nibbles::from_nibbles([0x1]) && *node == node_missing ); } #[test] fn test_single_verifier_next_extra() { // Test when trie has extra nodes not in expected // Create a proper trie structure with root let node_root = test_branch_node(0b1110, 0, 0b1110, vec![]); // root has children at 1, 2, 3 let node1 = test_branch_node(0b0001, 0, 0b0001, vec![]); let node2 = test_branch_node(0b0010, 0, 0b0010, vec![]); let node3 = test_branch_node(0b0100, 0, 0b0100, vec![]); let trie_nodes = BTreeMap::from([ (Nibbles::new(), node_root.clone()), (Nibbles::from_nibbles([0x1]), node1.clone()), (Nibbles::from_nibbles([0x2]), node2.clone()), (Nibbles::from_nibbles([0x3]), node3.clone()), ]); let cursor = create_mock_cursor(trie_nodes); let mut verifier = SingleVerifier::new(None, cursor).unwrap(); let mut outputs = Vec::new(); // The depth-first iterator produces in post-order: 0x1, 0x2, 0x3, root // We only provide 0x1 and 0x3, skipping 0x2 and root verifier.next(&mut outputs, Nibbles::from_nibbles([0x1]), node1).unwrap(); verifier.next(&mut outputs, Nibbles::from_nibbles([0x3]), node3).unwrap(); verifier.finalize(&mut outputs).unwrap(); // Should have two "extra" outputs for nodes in the trie that we skipped if outputs.len() != 2 { eprintln!("Expected 2 outputs, got {}:", outputs.len()); for inc in &outputs { eprintln!(" {:?}", inc); } } assert_eq!(outputs.len(), 2); assert_matches!( &outputs[0], Output::AccountExtra(path, node) if *path == Nibbles::from_nibbles([0x2]) && *node == node2 ); assert_matches!( &outputs[1], Output::AccountExtra(path, node) if *path == Nibbles::new() && *node == node_root ); } #[test] fn test_single_verifier_finalize() { // Test finalize marks all remaining nodes as extra let node_root = test_branch_node(0b1110, 0, 0b1110, vec![]); // root has children at 1, 2, 3 let node1 = test_branch_node(0b0001, 0, 0b0001, vec![]); let node2 = test_branch_node(0b0010, 0, 0b0010, vec![]); let node3 = test_branch_node(0b0100, 0, 0b0100, vec![]); let trie_nodes = BTreeMap::from([ (Nibbles::new(), node_root.clone()), (Nibbles::from_nibbles([0x1]), node1.clone()), (Nibbles::from_nibbles([0x2]), node2.clone()), (Nibbles::from_nibbles([0x3]), node3.clone()), ]); let cursor = create_mock_cursor(trie_nodes); let mut verifier = SingleVerifier::new(None, cursor).unwrap(); let mut outputs = Vec::new(); // The depth-first iterator produces in post-order: 0x1, 0x2, 0x3, root // Process first two nodes correctly verifier.next(&mut outputs, Nibbles::from_nibbles([0x1]), node1).unwrap(); verifier.next(&mut outputs, Nibbles::from_nibbles([0x2]), node2).unwrap(); assert!(outputs.is_empty());
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
true
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/progress.rs
crates/trie/trie/src/progress.rs
use crate::{ hash_builder::HashBuilder, trie_cursor::CursorSubNode, updates::{StorageTrieUpdates, TrieUpdates}, }; use alloy_primitives::B256; use reth_primitives_traits::Account; use reth_stages_types::MerkleCheckpoint; /// The progress of the state root computation. #[derive(Debug)] pub enum StateRootProgress { /// The complete state root computation with updates, the total number of entries walked, and /// the computed root. Complete(B256, usize, TrieUpdates), /// The intermediate progress of state root computation. /// Contains the walker stack, the hash builder, and the trie updates. /// /// Also contains any progress in an inner storage root computation. Progress(Box<IntermediateStateRootState>, usize, TrieUpdates), } /// The intermediate state of the state root computation. #[derive(Debug)] pub struct IntermediateStateRootState { /// The intermediate account root state. pub account_root_state: IntermediateRootState, /// The intermediate storage root state with account data. pub storage_root_state: Option<IntermediateStorageRootState>, } /// The intermediate state of a storage root computation along with the account. #[derive(Debug)] pub struct IntermediateStorageRootState { /// The intermediate storage trie state. pub state: IntermediateRootState, /// The account for which the storage root is being computed. pub account: Account, } impl From<MerkleCheckpoint> for IntermediateStateRootState { fn from(value: MerkleCheckpoint) -> Self { Self { account_root_state: IntermediateRootState { hash_builder: HashBuilder::from(value.state), walker_stack: value.walker_stack.into_iter().map(CursorSubNode::from).collect(), last_hashed_key: value.last_account_key, }, storage_root_state: value.storage_root_checkpoint.map(|checkpoint| { IntermediateStorageRootState { state: IntermediateRootState { hash_builder: HashBuilder::from(checkpoint.state), walker_stack: checkpoint .walker_stack .into_iter() .map(CursorSubNode::from) .collect(), last_hashed_key: checkpoint.last_storage_key, }, account: Account { nonce: checkpoint.account_nonce, balance: checkpoint.account_balance, bytecode_hash: Some(checkpoint.account_bytecode_hash), }, } }), } } } /// The intermediate state of a state root computation, whether account or storage root. #[derive(Debug)] pub struct IntermediateRootState { /// Previously constructed hash builder. pub hash_builder: HashBuilder, /// Previously recorded walker stack. pub walker_stack: Vec<CursorSubNode>, /// The last hashed key processed. pub last_hashed_key: B256, } /// The progress of a storage root calculation. #[derive(Debug)] pub enum StorageRootProgress { /// The complete storage root computation with updates and computed root. Complete(B256, usize, StorageTrieUpdates), /// The intermediate progress of state root computation. /// Contains the walker stack, the hash builder, and the trie updates. Progress(Box<IntermediateRootState>, usize, StorageTrieUpdates), }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/mock.rs
crates/trie/trie/src/mock.rs
/// The key visit. #[derive(Debug, Clone, PartialEq, Eq)] pub struct KeyVisit<T> { /// The type of key visit. pub visit_type: KeyVisitType<T>, /// The key that was visited, if found. pub visited_key: Option<T>, } /// The type of key visit. #[derive(Debug, Clone, PartialEq, Eq)] pub enum KeyVisitType<T> { /// Seeked exact key. SeekExact(T), /// Seeked non-exact key, returning the next key if no exact match found. SeekNonExact(T), /// Next key. Next, }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/metrics.rs
crates/trie/trie/src/metrics.rs
use crate::{stats::TrieStats, trie::TrieType}; use metrics::{Counter, Histogram}; use reth_metrics::Metrics; /// Wrapper for state root metrics. #[derive(Debug)] pub struct StateRootMetrics { /// State trie metrics. pub state_trie: TrieRootMetrics, /// Storage trie metrics. pub storage_trie: TrieRootMetrics, } impl Default for StateRootMetrics { fn default() -> Self { Self { state_trie: TrieRootMetrics::new(TrieType::State), storage_trie: TrieRootMetrics::new(TrieType::Storage), } } } /// Metrics for trie root calculation. #[derive(Clone, Metrics)] #[metrics(scope = "trie")] pub struct TrieRootMetrics { /// The number of seconds trie root calculation lasted. duration_seconds: Histogram, /// The number of branches added during trie root calculation. branches_added: Histogram, /// The number of leaves added during trie root calculation. leaves_added: Histogram, } impl TrieRootMetrics { /// Create new metrics for the given trie type. pub fn new(ty: TrieType) -> Self { Self::new_with_labels(&[("type", ty.as_str())]) } /// Record trie stats as metrics. pub fn record(&self, stats: TrieStats) { self.duration_seconds.record(stats.duration().as_secs_f64()); self.branches_added.record(stats.branches_added() as f64); self.leaves_added.record(stats.leaves_added() as f64); } } /// Metrics for [`crate::walker::TrieWalker`]. #[derive(Clone, Metrics)] #[metrics(scope = "trie.walker")] pub struct WalkerMetrics { /// The number of branch nodes seeked by the walker. branch_nodes_seeked_total: Counter, /// The number of subnodes out of order due to wrong tree mask. out_of_order_subnode: Counter, } impl WalkerMetrics { /// Create new metrics for the given trie type. pub fn new(ty: TrieType) -> Self { Self::new_with_labels(&[("type", ty.as_str())]) } /// Increment `branch_nodes_seeked_total`. pub fn inc_branch_nodes_seeked(&self) { self.branch_nodes_seeked_total.increment(1); } /// Increment `out_of_order_subnode`. pub fn inc_out_of_order_subnode(&self, amount: u64) { self.out_of_order_subnode.increment(amount); } } /// Metrics for [`crate::node_iter::TrieNodeIter`]. #[derive(Clone, Metrics)] #[metrics(scope = "trie.node_iter")] pub struct TrieNodeIterMetrics { /// The number of branch nodes returned by the iterator. branch_nodes_returned_total: Counter, /// The number of times the same hashed cursor key was seeked multiple times in a row by the /// iterator. It does not mean the database seek was actually done, as the trie node /// iterator caches the last hashed cursor seek. leaf_nodes_same_seeked_total: Counter, /// The number of leaf nodes seeked by the iterator. leaf_nodes_seeked_total: Counter, /// The number of leaf nodes advanced by the iterator. leaf_nodes_advanced_total: Counter, /// The number of leaf nodes returned by the iterator. leaf_nodes_returned_total: Counter, } impl TrieNodeIterMetrics { /// Create new metrics for the given trie type. pub fn new(ty: TrieType) -> Self { Self::new_with_labels(&[("type", ty.as_str())]) } /// Increment `branch_nodes_returned_total`. pub fn inc_branch_nodes_returned(&self) { self.branch_nodes_returned_total.increment(1); } /// Increment `leaf_nodes_same_seeked_total`. pub fn inc_leaf_nodes_same_seeked(&self) { self.leaf_nodes_same_seeked_total.increment(1); } /// Increment `leaf_nodes_seeked_total`. pub fn inc_leaf_nodes_seeked(&self) { self.leaf_nodes_seeked_total.increment(1); } /// Increment `leaf_nodes_advanced_total`. pub fn inc_leaf_nodes_advanced(&self) { self.leaf_nodes_advanced_total.increment(1); } /// Increment `leaf_nodes_returned_total`. pub fn inc_leaf_nodes_returned(&self) { self.leaf_nodes_returned_total.increment(1); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/trie.rs
crates/trie/trie/src/trie.rs
use crate::{ hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor}, node_iter::{TrieElement, TrieNodeIter}, prefix_set::{PrefixSet, TriePrefixSets}, progress::{ IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState, StateRootProgress, StorageRootProgress, }, stats::TrieTracker, trie_cursor::{TrieCursor, TrieCursorFactory}, updates::{StorageTrieUpdates, TrieUpdates}, walker::TrieWalker, HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE, }; use alloy_consensus::EMPTY_ROOT_HASH; use alloy_primitives::{keccak256, Address, B256}; use alloy_rlp::{BufMut, Encodable}; use alloy_trie::proof::AddedRemovedKeys; use reth_execution_errors::{StateRootError, StorageRootError}; use reth_primitives_traits::Account; use tracing::{debug, instrument, trace}; /// The default updates after which root algorithms should return intermediate progress rather than /// finishing the computation. const DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000; #[cfg(feature = "metrics")] use crate::metrics::{StateRootMetrics, TrieRootMetrics}; /// `StateRoot` is used to compute the root node of a state trie. #[derive(Debug)] pub struct StateRoot<T, H> { /// The factory for trie cursors. pub trie_cursor_factory: T, /// The factory for hashed cursors. pub hashed_cursor_factory: H, /// A set of prefix sets that have changed. pub prefix_sets: TriePrefixSets, /// Previous intermediate state. previous_state: Option<IntermediateStateRootState>, /// The number of updates after which the intermediate progress should be returned. threshold: u64, #[cfg(feature = "metrics")] /// State root metrics. metrics: StateRootMetrics, } impl<T, H> StateRoot<T, H> { /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other /// parameters are set to reasonable defaults. /// /// The cursors created by given factories are then used to walk through the accounts and /// calculate the state root value with. pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self { Self { trie_cursor_factory, hashed_cursor_factory, prefix_sets: TriePrefixSets::default(), previous_state: None, threshold: DEFAULT_INTERMEDIATE_THRESHOLD, #[cfg(feature = "metrics")] metrics: StateRootMetrics::default(), } } /// Set the prefix sets. pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self { self.prefix_sets = prefix_sets; self } /// Set the threshold. pub const fn with_threshold(mut self, threshold: u64) -> Self { self.threshold = threshold; self } /// Set the threshold to maximum value so that intermediate progress is not returned. pub const fn with_no_threshold(mut self) -> Self { self.threshold = u64::MAX; self } /// Set the previously recorded intermediate state. pub fn with_intermediate_state(mut self, state: Option<IntermediateStateRootState>) -> Self { self.previous_state = state; self } /// Set the hashed cursor factory. pub fn with_hashed_cursor_factory<HF>(self, hashed_cursor_factory: HF) -> StateRoot<T, HF> { StateRoot { trie_cursor_factory: self.trie_cursor_factory, hashed_cursor_factory, prefix_sets: self.prefix_sets, threshold: self.threshold, previous_state: self.previous_state, #[cfg(feature = "metrics")] metrics: self.metrics, } } /// Set the trie cursor factory. pub fn with_trie_cursor_factory<TF>(self, trie_cursor_factory: TF) -> StateRoot<TF, H> { StateRoot { trie_cursor_factory, hashed_cursor_factory: self.hashed_cursor_factory, prefix_sets: self.prefix_sets, threshold: self.threshold, previous_state: self.previous_state, #[cfg(feature = "metrics")] metrics: self.metrics, } } } impl<T, H> StateRoot<T, H> where T: TrieCursorFactory + Clone, H: HashedCursorFactory + Clone, { /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the /// nodes into the hash builder. Collects the updates in the process. /// /// Ignores the threshold. /// /// # Returns /// /// The state root and the trie updates. pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> { match self.with_no_threshold().calculate(true)? { StateRootProgress::Complete(root, _, updates) => Ok((root, updates)), StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold } } /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the /// nodes into the hash builder. /// /// # Returns /// /// The state root hash. pub fn root(self) -> Result<B256, StateRootError> { match self.calculate(false)? { StateRootProgress::Complete(root, _, _) => Ok(root), StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled } } /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the /// nodes into the hash builder. Collects the updates in the process. /// /// # Returns /// /// The intermediate progress of state root computation. pub fn root_with_progress(self) -> Result<StateRootProgress, StateRootError> { self.calculate(true) } fn calculate(self, retain_updates: bool) -> Result<StateRootProgress, StateRootError> { trace!(target: "trie::state_root", "calculating state root"); let mut tracker = TrieTracker::default(); let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?; let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?; // create state root context once for reuse let mut storage_ctx = StateRootContext::new(); // first handle any in-progress storage root calculation let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state { let IntermediateStateRootState { account_root_state, storage_root_state } = state; // resume account trie iteration let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates); let walker = TrieWalker::<_>::state_trie_from_stack( trie_cursor, account_root_state.walker_stack, self.prefix_sets.account_prefix_set, ) .with_deletions_retained(retain_updates); let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor) .with_last_hashed_key(account_root_state.last_hashed_key); // if we have an in-progress storage root, complete it first if let Some(storage_state) = storage_root_state { let hashed_address = account_root_state.last_hashed_key; let account = storage_state.account; debug!( target: "trie::state_root", account_nonce = account.nonce, account_balance = ?account.balance, last_hashed_key = ?account_root_state.last_hashed_key, "Resuming storage root calculation" ); // resume the storage root calculation let remaining_threshold = self.threshold.saturating_sub( storage_ctx.total_updates_len(&account_node_iter, &hash_builder), ); let storage_root_calculator = StorageRoot::new_hashed( self.trie_cursor_factory.clone(), self.hashed_cursor_factory.clone(), hashed_address, self.prefix_sets .storage_prefix_sets .get(&hashed_address) .cloned() .unwrap_or_default(), #[cfg(feature = "metrics")] self.metrics.storage_trie.clone(), ) .with_intermediate_state(Some(storage_state.state)) .with_threshold(remaining_threshold); let storage_result = storage_root_calculator.calculate(retain_updates)?; if let Some(storage_state) = storage_ctx.process_storage_root_result( storage_result, hashed_address, account, &mut hash_builder, // TODO(audit) false, retain_updates, )? { // still in progress, need to pause again return Ok(storage_ctx.create_progress_state( account_node_iter, hash_builder, account_root_state.last_hashed_key, Some(storage_state), )) } } (hash_builder, account_node_iter) } else { // no intermediate state, create new hash builder and node iter for state root // calculation let hash_builder = HashBuilder::default().with_updates(retain_updates); let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set) .with_deletions_retained(retain_updates); let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor); (hash_builder, node_iter) }; while let Some(node) = account_node_iter.try_next()? { match node { TrieElement::Branch(node) => { tracker.inc_branch(); hash_builder.add_branch(node.key, node.value, node.children_are_in_trie); } TrieElement::Leaf(hashed_address, account) => { tracker.inc_leaf(); let is_private = false; // account leaves are always public. Their storage leaves can be private. storage_ctx.hashed_entries_walked += 1; // calculate storage root, calculating the remaining threshold so we have // bounded memory usage even while in the middle of storage root calculation let remaining_threshold = self.threshold.saturating_sub( storage_ctx.total_updates_len(&account_node_iter, &hash_builder), ); let storage_root_calculator = StorageRoot::new_hashed( self.trie_cursor_factory.clone(), self.hashed_cursor_factory.clone(), hashed_address, self.prefix_sets .storage_prefix_sets .get(&hashed_address) .cloned() .unwrap_or_default(), #[cfg(feature = "metrics")] self.metrics.storage_trie.clone(), ) .with_threshold(remaining_threshold); let storage_result = storage_root_calculator.calculate(retain_updates)?; if let Some(storage_state) = storage_ctx.process_storage_root_result( storage_result, hashed_address, account, &mut hash_builder, is_private, retain_updates, )? { // storage root hit threshold, need to pause return Ok(storage_ctx.create_progress_state( account_node_iter, hash_builder, hashed_address, Some(storage_state), )) } // decide if we need to return intermediate progress let total_updates_len = storage_ctx.total_updates_len(&account_node_iter, &hash_builder); if retain_updates && total_updates_len >= self.threshold { return Ok(storage_ctx.create_progress_state( account_node_iter, hash_builder, hashed_address, None, )) } } } } let root = hash_builder.root(); let removed_keys = account_node_iter.walker.take_removed_keys(); let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx; trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts); let stats = tracker.finish(); #[cfg(feature = "metrics")] self.metrics.state_trie.record(stats); trace!( target: "trie::state_root", %root, duration = ?stats.duration(), branches_added = stats.branches_added(), leaves_added = stats.leaves_added(), "calculated state root" ); Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates)) } } /// Contains state mutated during state root calculation and storage root result handling. #[derive(Debug)] pub(crate) struct StateRootContext { /// Reusable buffer for encoding account data. account_rlp: Vec<u8>, /// Accumulates updates from account and storage root calculation. trie_updates: TrieUpdates, /// Tracks total hashed entries walked. hashed_entries_walked: usize, /// Counts storage trie nodes updated. updated_storage_nodes: usize, } impl StateRootContext { /// Creates a new state root context. fn new() -> Self { Self { account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE), trie_updates: TrieUpdates::default(), hashed_entries_walked: 0, updated_storage_nodes: 0, } } /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state. fn create_progress_state<C, H, K>( mut self, account_node_iter: TrieNodeIter<C, H, K>, hash_builder: HashBuilder, last_hashed_key: B256, storage_state: Option<IntermediateStorageRootState>, ) -> StateRootProgress where C: TrieCursor, H: HashedCursor, K: AsRef<AddedRemovedKeys>, { let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split(); self.trie_updates.removed_nodes.extend(walker_deleted_keys); let (hash_builder, hash_builder_updates) = hash_builder.split(); self.trie_updates.account_nodes.extend(hash_builder_updates); let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key }; let state = IntermediateStateRootState { account_root_state: account_state, storage_root_state: storage_state, }; StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates) } /// Calculates the total number of updated nodes. fn total_updates_len<C, H, K>( &self, account_node_iter: &TrieNodeIter<C, H, K>, hash_builder: &HashBuilder, ) -> u64 where C: TrieCursor, H: HashedCursor, K: AsRef<AddedRemovedKeys>, { (self.updated_storage_nodes + account_node_iter.walker.removed_keys_len() + hash_builder.updates_len()) as u64 } /// Processes the result of a storage root calculation. /// /// Handles both completed and in-progress storage root calculations: /// - For completed roots: encodes the account with the storage root, updates the hash builder /// with the new account, and updates metrics. /// - For in-progress roots: returns the intermediate state for later resumption /// /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or /// `None` if the storage root was successfully computed and added to the trie. fn process_storage_root_result( &mut self, storage_result: StorageRootProgress, hashed_address: B256, account: Account, hash_builder: &mut HashBuilder, is_private: bool, retain_updates: bool, ) -> Result<Option<IntermediateStorageRootState>, StateRootError> { match storage_result { StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => { // Storage root completed self.hashed_entries_walked += storage_slots_walked; if retain_updates { self.updated_storage_nodes += updates.len(); self.trie_updates.insert_storage_updates(hashed_address, updates); } // Encode the account with the computed storage root self.account_rlp.clear(); let trie_account = account.into_trie_account(storage_root); trie_account.encode(&mut self.account_rlp as &mut dyn BufMut); hash_builder.add_leaf( Nibbles::unpack(hashed_address), &self.account_rlp, is_private, ); Ok(None) } StorageRootProgress::Progress(state, storage_slots_walked, updates) => { // Storage root hit threshold or resumed calculation hit threshold debug!( target: "trie::state_root", ?hashed_address, storage_slots_walked, last_storage_key = ?state.last_hashed_key, ?account, "Pausing storage root calculation" ); self.hashed_entries_walked += storage_slots_walked; if retain_updates { self.trie_updates.insert_storage_updates(hashed_address, updates); } Ok(Some(IntermediateStorageRootState { state: *state, account })) } } } } /// `StorageRoot` is used to compute the root node of an account storage trie. #[derive(Debug)] pub struct StorageRoot<T, H> { /// A reference to the database transaction. pub trie_cursor_factory: T, /// The factory for hashed cursors. pub hashed_cursor_factory: H, /// The hashed address of an account. pub hashed_address: B256, /// The set of storage slot prefixes that have changed. pub prefix_set: PrefixSet, /// Previous intermediate state. previous_state: Option<IntermediateRootState>, /// The number of updates after which the intermediate progress should be returned. threshold: u64, /// Storage root metrics. #[cfg(feature = "metrics")] metrics: TrieRootMetrics, } impl<T, H> StorageRoot<T, H> { /// Creates a new storage root calculator given a raw address. pub fn new( trie_cursor_factory: T, hashed_cursor_factory: H, address: Address, prefix_set: PrefixSet, #[cfg(feature = "metrics")] metrics: TrieRootMetrics, ) -> Self { Self::new_hashed( trie_cursor_factory, hashed_cursor_factory, keccak256(address), prefix_set, #[cfg(feature = "metrics")] metrics, ) } /// Creates a new storage root calculator given a hashed address. pub const fn new_hashed( trie_cursor_factory: T, hashed_cursor_factory: H, hashed_address: B256, prefix_set: PrefixSet, #[cfg(feature = "metrics")] metrics: TrieRootMetrics, ) -> Self { Self { trie_cursor_factory, hashed_cursor_factory, hashed_address, prefix_set, previous_state: None, threshold: DEFAULT_INTERMEDIATE_THRESHOLD, #[cfg(feature = "metrics")] metrics, } } /// Set the changed prefixes. pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self { self.prefix_set = prefix_set; self } /// Set the threshold. pub const fn with_threshold(mut self, threshold: u64) -> Self { self.threshold = threshold; self } /// Set the threshold to maximum value so that intermediate progress is not returned. pub const fn with_no_threshold(mut self) -> Self { self.threshold = u64::MAX; self } /// Set the previously recorded intermediate state. pub fn with_intermediate_state(mut self, state: Option<IntermediateRootState>) -> Self { self.previous_state = state; self } /// Set the hashed cursor factory. pub fn with_hashed_cursor_factory<HF>(self, hashed_cursor_factory: HF) -> StorageRoot<T, HF> { StorageRoot { trie_cursor_factory: self.trie_cursor_factory, hashed_cursor_factory, hashed_address: self.hashed_address, prefix_set: self.prefix_set, previous_state: self.previous_state, threshold: self.threshold, #[cfg(feature = "metrics")] metrics: self.metrics, } } /// Set the trie cursor factory. pub fn with_trie_cursor_factory<TF>(self, trie_cursor_factory: TF) -> StorageRoot<TF, H> { StorageRoot { trie_cursor_factory, hashed_cursor_factory: self.hashed_cursor_factory, hashed_address: self.hashed_address, prefix_set: self.prefix_set, previous_state: self.previous_state, threshold: self.threshold, #[cfg(feature = "metrics")] metrics: self.metrics, } } } impl<T, H> StorageRoot<T, H> where T: TrieCursorFactory, H: HashedCursorFactory, { /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the /// nodes into the hash builder. Collects the updates in the process. /// /// # Returns /// /// The intermediate progress of state root computation. pub fn root_with_progress(self) -> Result<StorageRootProgress, StorageRootError> { self.calculate(true) } /// Walks the hashed storage table entries for a given address and calculates the storage root. /// /// # Returns /// /// The storage root and storage trie updates for a given address. pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> { match self.with_no_threshold().calculate(true)? { StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)), StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold } } /// Walks the hashed storage table entries for a given address and calculates the storage root. /// /// # Returns /// /// The storage root. pub fn root(self) -> Result<B256, StorageRootError> { match self.calculate(false)? { StorageRootProgress::Complete(root, _, _) => Ok(root), StorageRootProgress::Progress(..) => unreachable!(), // update retenion is disabled } } /// Walks the hashed storage table entries for a given address and calculates the storage root. /// /// # Returns /// /// The storage root, number of walked entries and trie updates /// for a given address if requested. #[instrument(skip_all, target = "trie::storage_root", name = "Storage trie", fields(hashed_address = ?self.hashed_address))] pub fn calculate(self, retain_updates: bool) -> Result<StorageRootProgress, StorageRootError> { trace!(target: "trie::storage_root", "calculating storage root"); let mut hashed_storage_cursor = self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?; // short circuit on empty storage if hashed_storage_cursor.is_storage_empty()? { return Ok(StorageRootProgress::Complete( EMPTY_ROOT_HASH, 0, StorageTrieUpdates::deleted(), )) } let mut tracker = TrieTracker::default(); let mut trie_updates = StorageTrieUpdates::default(); let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?; let (mut hash_builder, mut storage_node_iter) = match self.previous_state { Some(state) => { let hash_builder = state.hash_builder.with_updates(retain_updates); let walker = TrieWalker::<_>::storage_trie_from_stack( trie_cursor, state.walker_stack, self.prefix_set, ) .with_deletions_retained(retain_updates); let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor) .with_last_hashed_key(state.last_hashed_key); (hash_builder, node_iter) } None => { let hash_builder = HashBuilder::default().with_updates(retain_updates); let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set) .with_deletions_retained(retain_updates); let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor); (hash_builder, node_iter) } }; let mut hashed_entries_walked = 0; while let Some(node) = storage_node_iter.try_next()? { match node { TrieElement::Branch(node) => { tracker.inc_branch(); hash_builder.add_branch(node.key, node.value, node.children_are_in_trie); } TrieElement::Leaf(hashed_slot, value) => { tracker.inc_leaf(); hashed_entries_walked += 1; hash_builder.add_leaf( Nibbles::unpack(hashed_slot), alloy_rlp::encode_fixed_size(&value).as_ref(), value.is_private, ); // Check if we need to return intermediate progress let total_updates_len = storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len(); if retain_updates && total_updates_len as u64 >= self.threshold { let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split(); trie_updates.removed_nodes.extend(walker_deleted_keys); let (hash_builder, hash_builder_updates) = hash_builder.split(); trie_updates.storage_nodes.extend(hash_builder_updates); let state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key: hashed_slot, }; return Ok(StorageRootProgress::Progress( Box::new(state), hashed_entries_walked, trie_updates, )) } } } } let root = hash_builder.root(); let removed_keys = storage_node_iter.walker.take_removed_keys(); trie_updates.finalize(hash_builder, removed_keys); let stats = tracker.finish(); #[cfg(feature = "metrics")] self.metrics.record(stats); trace!( target: "trie::storage_root", %root, hashed_address = %self.hashed_address, duration = ?stats.duration(), branches_added = stats.branches_added(), leaves_added = stats.leaves_added(), "calculated storage root" ); let storage_slots_walked = stats.leaves_added() as usize; Ok(StorageRootProgress::Complete(root, storage_slots_walked, trie_updates)) } } /// Trie type for differentiating between various trie calculations. #[derive(Clone, Copy, Debug)] pub enum TrieType { /// State trie type. State, /// Storage trie type. Storage, } impl TrieType { #[cfg(feature = "metrics")] pub(crate) const fn as_str(&self) -> &'static str { match self { Self::State => "state", Self::Storage => "storage", } } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/trie_cursor/subnode.rs
crates/trie/trie/src/trie_cursor/subnode.rs
use crate::{BranchNodeCompact, Nibbles, StoredSubNode, CHILD_INDEX_RANGE}; use alloy_primitives::B256; use alloy_trie::proof::AddedRemovedKeys; /// Cursor for iterating over a subtrie. #[derive(Clone)] pub struct CursorSubNode { /// The key of the current node. pub key: Nibbles, /// The position of the current subnode. position: SubNodePosition, /// The node itself. pub node: Option<BranchNodeCompact>, /// Full key full_key: Nibbles, } impl Default for CursorSubNode { fn default() -> Self { Self::new(Nibbles::default(), None) } } impl std::fmt::Debug for CursorSubNode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("CursorSubNode") .field("key", &self.key) .field("position", &self.position) .field("state_flag", &self.state_flag()) .field("tree_flag", &self.tree_flag()) .field("hash_flag", &self.hash_flag()) .field("hash", &self.maybe_hash()) .finish() } } /// Implements conversion from `StoredSubNode` to `CursorSubNode`. impl From<StoredSubNode> for CursorSubNode { /// Converts a `StoredSubNode` into a `CursorSubNode`. /// /// Extracts necessary values from the `StoredSubNode` and constructs /// a corresponding `CursorSubNode`. fn from(value: StoredSubNode) -> Self { let position = value.nibble.map_or(SubNodePosition::ParentBranch, SubNodePosition::Child); let key = Nibbles::from_nibbles_unchecked(value.key); Self::new_with_full_key(key, value.node, position) } } impl From<CursorSubNode> for StoredSubNode { fn from(value: CursorSubNode) -> Self { Self { key: value.key.to_vec(), nibble: value.position.as_child(), node: value.node } } } impl CursorSubNode { /// Creates a new [`CursorSubNode`] from a key and an optional node. pub fn new(key: Nibbles, node: Option<BranchNodeCompact>) -> Self { // Find the first nibble that is set in the state mask of the node. let position = node.as_ref().filter(|n| n.root_hash.is_none()).map_or( SubNodePosition::ParentBranch, |n| { SubNodePosition::Child( CHILD_INDEX_RANGE.clone().find(|i| n.state_mask.is_bit_set(*i)).unwrap(), ) }, ); Self::new_with_full_key(key, node, position) } /// Creates a new [`CursorSubNode`] and sets the full key according to the provided key and /// position. fn new_with_full_key( key: Nibbles, node: Option<BranchNodeCompact>, position: SubNodePosition, ) -> Self { let mut full_key = key; if let Some(nibble) = position.as_child() { full_key.push(nibble); } Self { key, node, position, full_key } } /// Returns the full key of the current node. #[inline] pub const fn full_key(&self) -> &Nibbles { &self.full_key } /// Returns true if all of: /// - Position is a child /// - There is a branch node /// - All children except the current are removed according to the [`AddedRemovedKeys`]. pub fn full_key_is_only_nonremoved_child(&self, added_removed_keys: &AddedRemovedKeys) -> bool { self.position.as_child().zip(self.node.as_ref()).is_some_and(|(nibble, node)| { let removed_mask = added_removed_keys.get_removed_mask(&self.key); let nonremoved_mask = !removed_mask & node.state_mask; tracing::trace!( target: "trie::walker", key = ?self.key, ?removed_mask, ?nonremoved_mask, ?nibble, "Checking full_key_is_only_nonremoved_node", ); nonremoved_mask.count_ones() == 1 && nonremoved_mask.is_bit_set(nibble) }) } /// Updates the full key by replacing or appending a child nibble based on the old subnode /// position. #[inline] fn update_full_key(&mut self, old_position: SubNodePosition) { if let Some(new_nibble) = self.position.as_child() { if old_position.is_child() { let last_index = self.full_key.len() - 1; self.full_key.set_at(last_index, new_nibble); } else { self.full_key.push(new_nibble); } } else if old_position.is_child() { self.full_key.pop(); } } /// Returns `true` if either of these: /// - No current node is set. /// - The current node is a parent branch node. /// - The current node is a child with state mask bit set in the parent branch node. #[inline] pub fn state_flag(&self) -> bool { self.node.as_ref().is_none_or(|node| { self.position.as_child().is_none_or(|nibble| node.state_mask.is_bit_set(nibble)) }) } /// Returns `true` if either of these: /// - No current node is set. /// - The current node is a parent branch node. /// - The current node is a child with tree mask bit set in the parent branch node. #[inline] pub fn tree_flag(&self) -> bool { self.node.as_ref().is_none_or(|node| { self.position.as_child().is_none_or(|nibble| node.tree_mask.is_bit_set(nibble)) }) } /// Returns `true` if the hash for the current node is set. /// /// It means either of two: /// - Current node is a parent branch node, and it has a root hash. /// - Current node is a child node, and it has a hash mask bit set in the parent branch node. pub fn hash_flag(&self) -> bool { self.node.as_ref().is_some_and(|node| match self.position { // Check if the parent branch node has a root hash SubNodePosition::ParentBranch => node.root_hash.is_some(), // Or get it from the children SubNodePosition::Child(nibble) => node.hash_mask.is_bit_set(nibble), }) } /// Returns the hash of the current node. /// /// It means either of two: /// - Root hash of the parent branch node. /// - Hash of the child node at the current nibble, if it has a hash mask bit set in the parent /// branch node. pub fn hash(&self) -> Option<B256> { self.node.as_ref().and_then(|node| match self.position { // Get the root hash for the parent branch node SubNodePosition::ParentBranch => node.root_hash, // Or get it from the children SubNodePosition::Child(nibble) => Some(node.hash_for_nibble(nibble)), }) } /// Returns the hash of the current node, if any. /// /// Differs from [`Self::hash`] in that it returns `None` if the subnode is positioned at the /// child without a hash mask bit set. [`Self::hash`] panics in that case. pub fn maybe_hash(&self) -> Option<B256> { self.node.as_ref().and_then(|node| match self.position { // Get the root hash for the parent branch node SubNodePosition::ParentBranch => node.root_hash, // Or get it from the children SubNodePosition::Child(nibble) => { node.hash_mask.is_bit_set(nibble).then(|| node.hash_for_nibble(nibble)) } }) } /// Returns the position to the current node. #[inline] pub const fn position(&self) -> SubNodePosition { self.position } /// Increments the nibble index. #[inline] pub fn inc_nibble(&mut self) { let old_position = self.position; self.position.increment(); self.update_full_key(old_position); } /// Sets the nibble index. #[inline] pub fn set_nibble(&mut self, nibble: u8) { let old_position = self.position; self.position = SubNodePosition::Child(nibble); self.update_full_key(old_position); } } /// Represents a subnode position. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum SubNodePosition { /// Positioned at the parent branch node. ParentBranch, /// Positioned at a child node at the given nibble. Child(u8), } impl SubNodePosition { /// Returns `true` if the position is set to the parent branch node. pub const fn is_parent(&self) -> bool { matches!(self, Self::ParentBranch) } /// Returns `true` if the position is set to a child node. pub const fn is_child(&self) -> bool { matches!(self, Self::Child(_)) } /// Returns the nibble of the child node if the position is set to a child node. pub const fn as_child(&self) -> Option<u8> { match self { Self::Child(nibble) => Some(*nibble), _ => None, } } /// Returns `true` if the position is set to a last child nibble (i.e. greater than or equal to /// 0xf). pub const fn is_last_child(&self) -> bool { match self { Self::ParentBranch => false, Self::Child(nibble) => *nibble >= 0xf, } } const fn increment(&mut self) { match self { Self::ParentBranch => *self = Self::Child(0), Self::Child(nibble) => *nibble += 1, } } } #[cfg(test)] mod tests { use super::*; #[test] fn subnode_position_ord() { assert!([ SubNodePosition::ParentBranch, SubNodePosition::Child(0), SubNodePosition::Child(1), SubNodePosition::Child(2), SubNodePosition::Child(3), SubNodePosition::Child(4), SubNodePosition::Child(5), SubNodePosition::Child(6), SubNodePosition::Child(7), SubNodePosition::Child(8), SubNodePosition::Child(9), SubNodePosition::Child(10), SubNodePosition::Child(11), SubNodePosition::Child(12), SubNodePosition::Child(13), SubNodePosition::Child(14), SubNodePosition::Child(15), ] .is_sorted()); } #[test] fn subnode_position_is_last_child() { assert!([ SubNodePosition::ParentBranch, SubNodePosition::Child(0), SubNodePosition::Child(1), SubNodePosition::Child(2), SubNodePosition::Child(3), SubNodePosition::Child(4), SubNodePosition::Child(5), SubNodePosition::Child(6), SubNodePosition::Child(7), SubNodePosition::Child(8), SubNodePosition::Child(9), SubNodePosition::Child(10), SubNodePosition::Child(11), SubNodePosition::Child(12), SubNodePosition::Child(13), SubNodePosition::Child(14), ] .iter() .all(|position| !position.is_last_child())); assert!(SubNodePosition::Child(15).is_last_child()); assert!(SubNodePosition::Child(16).is_last_child()); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/trie_cursor/noop.rs
crates/trie/trie/src/trie_cursor/noop.rs
use super::{TrieCursor, TrieCursorFactory}; use crate::{BranchNodeCompact, Nibbles}; use alloy_primitives::B256; use reth_storage_errors::db::DatabaseError; /// Noop trie cursor factory. #[derive(Clone, Default, Debug)] #[non_exhaustive] pub struct NoopTrieCursorFactory; impl TrieCursorFactory for NoopTrieCursorFactory { type AccountTrieCursor = NoopAccountTrieCursor; type StorageTrieCursor = NoopStorageTrieCursor; /// Generates a noop account trie cursor. fn account_trie_cursor(&self) -> Result<Self::AccountTrieCursor, DatabaseError> { Ok(NoopAccountTrieCursor::default()) } /// Generates a noop storage trie cursor. fn storage_trie_cursor( &self, _hashed_address: B256, ) -> Result<Self::StorageTrieCursor, DatabaseError> { Ok(NoopStorageTrieCursor::default()) } } /// Noop account trie cursor. #[derive(Default, Debug)] #[non_exhaustive] pub struct NoopAccountTrieCursor; impl TrieCursor for NoopAccountTrieCursor { fn seek_exact( &mut self, _key: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { Ok(None) } fn seek( &mut self, _key: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { Ok(None) } fn next(&mut self) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { Ok(None) } fn current(&mut self) -> Result<Option<Nibbles>, DatabaseError> { Ok(None) } } /// Noop storage trie cursor. #[derive(Default, Debug)] #[non_exhaustive] pub struct NoopStorageTrieCursor; impl TrieCursor for NoopStorageTrieCursor { fn seek_exact( &mut self, _key: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { Ok(None) } fn seek( &mut self, _key: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { Ok(None) } fn next(&mut self) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { Ok(None) } fn current(&mut self) -> Result<Option<Nibbles>, DatabaseError> { Ok(None) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/trie_cursor/mod.rs
crates/trie/trie/src/trie_cursor/mod.rs
use crate::{BranchNodeCompact, Nibbles}; use alloy_primitives::B256; use reth_storage_errors::db::DatabaseError; /// In-memory implementations of trie cursors. mod in_memory; /// Cursor for iterating over a subtrie. pub mod subnode; /// Noop trie cursor implementations. pub mod noop; /// Depth-first trie iterator. pub mod depth_first; /// Mock trie cursor implementations. #[cfg(test)] pub mod mock; pub use self::{depth_first::DepthFirstTrieIterator, in_memory::*, subnode::CursorSubNode}; /// Factory for creating trie cursors. #[auto_impl::auto_impl(&)] pub trait TrieCursorFactory { /// The account trie cursor type. type AccountTrieCursor: TrieCursor; /// The storage trie cursor type. type StorageTrieCursor: TrieCursor; /// Create an account trie cursor. fn account_trie_cursor(&self) -> Result<Self::AccountTrieCursor, DatabaseError>; /// Create a storage tries cursor. fn storage_trie_cursor( &self, hashed_address: B256, ) -> Result<Self::StorageTrieCursor, DatabaseError>; } /// A cursor for traversing stored trie nodes. The cursor must iterate over keys in /// lexicographical order. #[auto_impl::auto_impl(&mut, Box)] pub trait TrieCursor: Send + Sync { /// Move the cursor to the key and return if it is an exact match. fn seek_exact( &mut self, key: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError>; /// Move the cursor to the key and return a value matching of greater than the key. fn seek(&mut self, key: Nibbles) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError>; /// Move the cursor to the next key. fn next(&mut self) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError>; /// Get the current entry. fn current(&mut self) -> Result<Option<Nibbles>, DatabaseError>; }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/trie_cursor/mock.rs
crates/trie/trie/src/trie_cursor/mock.rs
use parking_lot::{Mutex, MutexGuard}; use std::{collections::BTreeMap, sync::Arc}; use tracing::instrument; use super::{TrieCursor, TrieCursorFactory}; use crate::{ mock::{KeyVisit, KeyVisitType}, BranchNodeCompact, Nibbles, }; use alloy_primitives::{map::B256Map, B256}; use reth_storage_errors::db::DatabaseError; /// Mock trie cursor factory. #[derive(Clone, Default, Debug)] pub struct MockTrieCursorFactory { account_trie_nodes: Arc<BTreeMap<Nibbles, BranchNodeCompact>>, storage_tries: B256Map<Arc<BTreeMap<Nibbles, BranchNodeCompact>>>, /// List of keys that the account trie cursor has visited. visited_account_keys: Arc<Mutex<Vec<KeyVisit<Nibbles>>>>, /// List of keys that the storage trie cursor has visited, per storage trie. visited_storage_keys: B256Map<Arc<Mutex<Vec<KeyVisit<Nibbles>>>>>, } impl MockTrieCursorFactory { /// Creates a new mock trie cursor factory. pub fn new( account_trie_nodes: BTreeMap<Nibbles, BranchNodeCompact>, storage_tries: B256Map<BTreeMap<Nibbles, BranchNodeCompact>>, ) -> Self { let visited_storage_keys = storage_tries.keys().map(|k| (*k, Default::default())).collect(); Self { account_trie_nodes: Arc::new(account_trie_nodes), storage_tries: storage_tries.into_iter().map(|(k, v)| (k, Arc::new(v))).collect(), visited_account_keys: Default::default(), visited_storage_keys, } } /// Returns a reference to the list of visited account keys. pub fn visited_account_keys(&self) -> MutexGuard<'_, Vec<KeyVisit<Nibbles>>> { self.visited_account_keys.lock() } /// Returns a reference to the list of visited storage keys for the given hashed address. pub fn visited_storage_keys( &self, hashed_address: B256, ) -> MutexGuard<'_, Vec<KeyVisit<Nibbles>>> { self.visited_storage_keys.get(&hashed_address).expect("storage trie should exist").lock() } } impl TrieCursorFactory for MockTrieCursorFactory { type AccountTrieCursor = MockTrieCursor; type StorageTrieCursor = MockTrieCursor; /// Generates a mock account trie cursor. fn account_trie_cursor(&self) -> Result<Self::AccountTrieCursor, DatabaseError> { Ok(MockTrieCursor::new(self.account_trie_nodes.clone(), self.visited_account_keys.clone())) } /// Generates a mock storage trie cursor. fn storage_trie_cursor( &self, hashed_address: B256, ) -> Result<Self::StorageTrieCursor, DatabaseError> { Ok(MockTrieCursor::new( self.storage_tries .get(&hashed_address) .ok_or_else(|| { DatabaseError::Other(format!("storage trie for {hashed_address:?} not found")) })? .clone(), self.visited_storage_keys .get(&hashed_address) .ok_or_else(|| { DatabaseError::Other(format!("storage trie for {hashed_address:?} not found")) })? .clone(), )) } } /// Mock trie cursor. #[derive(Default, Debug)] #[non_exhaustive] pub struct MockTrieCursor { /// The current key. If set, it is guaranteed to exist in `trie_nodes`. current_key: Option<Nibbles>, trie_nodes: Arc<BTreeMap<Nibbles, BranchNodeCompact>>, visited_keys: Arc<Mutex<Vec<KeyVisit<Nibbles>>>>, } impl MockTrieCursor { fn new( trie_nodes: Arc<BTreeMap<Nibbles, BranchNodeCompact>>, visited_keys: Arc<Mutex<Vec<KeyVisit<Nibbles>>>>, ) -> Self { Self { current_key: None, trie_nodes, visited_keys } } } impl TrieCursor for MockTrieCursor { #[instrument(level = "trace", skip(self), ret)] fn seek_exact( &mut self, key: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { let entry = self.trie_nodes.get(&key).cloned().map(|value| (key, value)); if let Some((key, _)) = &entry { self.current_key = Some(*key); } self.visited_keys.lock().push(KeyVisit { visit_type: KeyVisitType::SeekExact(key), visited_key: entry.as_ref().map(|(k, _)| *k), }); Ok(entry) } #[instrument(level = "trace", skip(self), ret)] fn seek( &mut self, key: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { // Find the first key that is greater than or equal to the given key. let entry = self.trie_nodes.iter().find_map(|(k, v)| (k >= &key).then(|| (*k, v.clone()))); if let Some((key, _)) = &entry { self.current_key = Some(*key); } self.visited_keys.lock().push(KeyVisit { visit_type: KeyVisitType::SeekNonExact(key), visited_key: entry.as_ref().map(|(k, _)| *k), }); Ok(entry) } #[instrument(level = "trace", skip(self), ret)] fn next(&mut self) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { let mut iter = self.trie_nodes.iter(); // Jump to the first key that has a prefix of the current key if it's set, or to the first // key otherwise. iter.find(|(k, _)| self.current_key.as_ref().is_none_or(|current| k.starts_with(current))) .expect("current key should exist in trie nodes"); // Get the next key-value pair. let entry = iter.next().map(|(k, v)| (*k, v.clone())); if let Some((key, _)) = &entry { self.current_key = Some(*key); } self.visited_keys.lock().push(KeyVisit { visit_type: KeyVisitType::Next, visited_key: entry.as_ref().map(|(k, _)| *k), }); Ok(entry) } #[instrument(level = "trace", skip(self), ret)] fn current(&mut self) -> Result<Option<Nibbles>, DatabaseError> { Ok(self.current_key) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/trie_cursor/in_memory.rs
crates/trie/trie/src/trie_cursor/in_memory.rs
use super::{TrieCursor, TrieCursorFactory}; use crate::{ forward_cursor::ForwardInMemoryCursor, updates::{StorageTrieUpdatesSorted, TrieUpdatesSorted}, }; use alloy_primitives::{map::HashSet, B256}; use reth_storage_errors::db::DatabaseError; use reth_trie_common::{BranchNodeCompact, Nibbles}; /// The trie cursor factory for the trie updates. #[derive(Debug, Clone)] pub struct InMemoryTrieCursorFactory<'a, CF> { /// Underlying trie cursor factory. cursor_factory: CF, /// Reference to sorted trie updates. trie_updates: &'a TrieUpdatesSorted, } impl<'a, CF> InMemoryTrieCursorFactory<'a, CF> { /// Create a new trie cursor factory. pub const fn new(cursor_factory: CF, trie_updates: &'a TrieUpdatesSorted) -> Self { Self { cursor_factory, trie_updates } } } impl<'a, CF: TrieCursorFactory> TrieCursorFactory for InMemoryTrieCursorFactory<'a, CF> { type AccountTrieCursor = InMemoryAccountTrieCursor<'a, CF::AccountTrieCursor>; type StorageTrieCursor = InMemoryStorageTrieCursor<'a, CF::StorageTrieCursor>; fn account_trie_cursor(&self) -> Result<Self::AccountTrieCursor, DatabaseError> { let cursor = self.cursor_factory.account_trie_cursor()?; Ok(InMemoryAccountTrieCursor::new(cursor, self.trie_updates)) } fn storage_trie_cursor( &self, hashed_address: B256, ) -> Result<Self::StorageTrieCursor, DatabaseError> { let cursor = self.cursor_factory.storage_trie_cursor(hashed_address)?; Ok(InMemoryStorageTrieCursor::new( hashed_address, cursor, self.trie_updates.storage_tries.get(&hashed_address), )) } } /// The cursor to iterate over account trie updates and corresponding database entries. /// It will always give precedence to the data from the trie updates. #[derive(Debug)] pub struct InMemoryAccountTrieCursor<'a, C> { /// The underlying cursor. cursor: C, /// Forward-only in-memory cursor over storage trie nodes. in_memory_cursor: ForwardInMemoryCursor<'a, Nibbles, BranchNodeCompact>, /// Collection of removed trie nodes. removed_nodes: &'a HashSet<Nibbles>, /// Last key returned by the cursor. last_key: Option<Nibbles>, } impl<'a, C: TrieCursor> InMemoryAccountTrieCursor<'a, C> { /// Create new account trie cursor from underlying cursor and reference to /// [`TrieUpdatesSorted`]. pub fn new(cursor: C, trie_updates: &'a TrieUpdatesSorted) -> Self { let in_memory_cursor = ForwardInMemoryCursor::new(&trie_updates.account_nodes); Self { cursor, in_memory_cursor, removed_nodes: &trie_updates.removed_nodes, last_key: None, } } fn seek_inner( &mut self, key: Nibbles, exact: bool, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { let in_memory = self.in_memory_cursor.seek(&key); if in_memory.as_ref().is_some_and(|entry| entry.0 == key) { return Ok(in_memory) } // Reposition the cursor to the first greater or equal node that wasn't removed. let mut db_entry = self.cursor.seek(key)?; while db_entry.as_ref().is_some_and(|entry| self.removed_nodes.contains(&entry.0)) { db_entry = self.cursor.next()?; } // Compare two entries and return the lowest. // If seek is exact, filter the entry for exact key match. Ok(compare_trie_node_entries(in_memory, db_entry) .filter(|(nibbles, _)| !exact || nibbles == &key)) } fn next_inner( &mut self, last: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { let in_memory = self.in_memory_cursor.first_after(&last); // Reposition the cursor to the first greater or equal node that wasn't removed. let mut db_entry = self.cursor.seek(last)?; while db_entry .as_ref() .is_some_and(|entry| entry.0 < last || self.removed_nodes.contains(&entry.0)) { db_entry = self.cursor.next()?; } // Compare two entries and return the lowest. Ok(compare_trie_node_entries(in_memory, db_entry)) } } impl<C: TrieCursor> TrieCursor for InMemoryAccountTrieCursor<'_, C> { fn seek_exact( &mut self, key: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { let entry = self.seek_inner(key, true)?; self.last_key = entry.as_ref().map(|(nibbles, _)| *nibbles); Ok(entry) } fn seek( &mut self, key: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { let entry = self.seek_inner(key, false)?; self.last_key = entry.as_ref().map(|(nibbles, _)| *nibbles); Ok(entry) } fn next(&mut self) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { let next = match &self.last_key { Some(last) => { let entry = self.next_inner(*last)?; self.last_key = entry.as_ref().map(|entry| entry.0); entry } // no previous entry was found None => None, }; Ok(next) } fn current(&mut self) -> Result<Option<Nibbles>, DatabaseError> { match &self.last_key { Some(key) => Ok(Some(*key)), None => self.cursor.current(), } } } /// The cursor to iterate over storage trie updates and corresponding database entries. /// It will always give precedence to the data from the trie updates. #[derive(Debug)] #[expect(dead_code)] pub struct InMemoryStorageTrieCursor<'a, C> { /// The hashed address of the account that trie belongs to. hashed_address: B256, /// The underlying cursor. cursor: C, /// Forward-only in-memory cursor over storage trie nodes. in_memory_cursor: Option<ForwardInMemoryCursor<'a, Nibbles, BranchNodeCompact>>, /// Reference to the set of removed storage node keys. removed_nodes: Option<&'a HashSet<Nibbles>>, /// The flag indicating whether the storage trie was cleared. storage_trie_cleared: bool, /// Last key returned by the cursor. last_key: Option<Nibbles>, } impl<'a, C> InMemoryStorageTrieCursor<'a, C> { /// Create new storage trie cursor from underlying cursor and reference to /// [`StorageTrieUpdatesSorted`]. pub fn new( hashed_address: B256, cursor: C, updates: Option<&'a StorageTrieUpdatesSorted>, ) -> Self { let in_memory_cursor = updates.map(|u| ForwardInMemoryCursor::new(&u.storage_nodes)); let removed_nodes = updates.map(|u| &u.removed_nodes); let storage_trie_cleared = updates.is_some_and(|u| u.is_deleted); Self { hashed_address, cursor, in_memory_cursor, removed_nodes, storage_trie_cleared, last_key: None, } } } impl<C: TrieCursor> InMemoryStorageTrieCursor<'_, C> { fn seek_inner( &mut self, key: Nibbles, exact: bool, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { let in_memory = self.in_memory_cursor.as_mut().and_then(|c| c.seek(&key)); if self.storage_trie_cleared || in_memory.as_ref().is_some_and(|entry| entry.0 == key) { return Ok(in_memory.filter(|(nibbles, _)| !exact || nibbles == &key)) } // Reposition the cursor to the first greater or equal node that wasn't removed. let mut db_entry = self.cursor.seek(key)?; while db_entry .as_ref() .is_some_and(|entry| self.removed_nodes.as_ref().is_some_and(|r| r.contains(&entry.0))) { db_entry = self.cursor.next()?; } // Compare two entries and return the lowest. // If seek is exact, filter the entry for exact key match. Ok(compare_trie_node_entries(in_memory, db_entry) .filter(|(nibbles, _)| !exact || nibbles == &key)) } fn next_inner( &mut self, last: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { let in_memory = self.in_memory_cursor.as_mut().and_then(|c| c.first_after(&last)); if self.storage_trie_cleared { return Ok(in_memory) } // Reposition the cursor to the first greater or equal node that wasn't removed. let mut db_entry = self.cursor.seek(last)?; while db_entry.as_ref().is_some_and(|entry| { entry.0 < last || self.removed_nodes.as_ref().is_some_and(|r| r.contains(&entry.0)) }) { db_entry = self.cursor.next()?; } // Compare two entries and return the lowest. Ok(compare_trie_node_entries(in_memory, db_entry)) } } impl<C: TrieCursor> TrieCursor for InMemoryStorageTrieCursor<'_, C> { fn seek_exact( &mut self, key: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { let entry = self.seek_inner(key, true)?; self.last_key = entry.as_ref().map(|(nibbles, _)| *nibbles); Ok(entry) } fn seek( &mut self, key: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { let entry = self.seek_inner(key, false)?; self.last_key = entry.as_ref().map(|(nibbles, _)| *nibbles); Ok(entry) } fn next(&mut self) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { let next = match &self.last_key { Some(last) => { let entry = self.next_inner(*last)?; self.last_key = entry.as_ref().map(|entry| entry.0); entry } // no previous entry was found None => None, }; Ok(next) } fn current(&mut self) -> Result<Option<Nibbles>, DatabaseError> { match &self.last_key { Some(key) => Ok(Some(*key)), None => self.cursor.current(), } } } /// Return the node with the lowest nibbles. /// /// Given the next in-memory and database entries, return the smallest of the two. /// If the node keys are the same, the in-memory entry is given precedence. fn compare_trie_node_entries( mut in_memory_item: Option<(Nibbles, BranchNodeCompact)>, mut db_item: Option<(Nibbles, BranchNodeCompact)>, ) -> Option<(Nibbles, BranchNodeCompact)> { if let Some((in_memory_entry, db_entry)) = in_memory_item.as_ref().zip(db_item.as_ref()) { // If both are not empty, return the smallest of the two // In-memory is given precedence if keys are equal if in_memory_entry.0 <= db_entry.0 { in_memory_item.take() } else { db_item.take() } } else { // Return either non-empty entry db_item.or(in_memory_item) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/trie_cursor/depth_first.rs
crates/trie/trie/src/trie_cursor/depth_first.rs
use super::TrieCursor; use crate::{BranchNodeCompact, Nibbles}; use reth_storage_errors::db::DatabaseError; use std::cmp::Ordering; use tracing::trace; /// Compares two Nibbles in depth-first order. /// /// In depth-first ordering: /// - Descendants come before their ancestors (children before parents) /// - Siblings are ordered lexicographically /// /// # Example /// /// ```text /// 0x11 comes before 0x1 (child before parent) /// 0x12 comes before 0x1 (child before parent) /// 0x11 comes before 0x12 (lexicographical among siblings) /// 0x1 comes before 0x21 (lexicographical among siblings) /// Result: 0x11, 0x12, 0x1, 0x21 /// ``` pub fn cmp(a: &Nibbles, b: &Nibbles) -> Ordering { // If the two are equal length then compare them lexicographically if a.len() == b.len() { return a.cmp(b) } // If one is a prefix of the other, then the other comes first let common_prefix_len = a.common_prefix_length(b); if a.len() == common_prefix_len { return Ordering::Greater } else if b.len() == common_prefix_len { return Ordering::Less } // Otherwise the nibble after the prefix determines the ordering. We know that neither is empty // at this point, otherwise the previous if/else block would have caught it. a.get_unchecked(common_prefix_len).cmp(&b.get_unchecked(common_prefix_len)) } /// An iterator that traverses trie nodes in depth-first post-order. /// /// This iterator yields nodes in post-order traversal (children before parents), /// which matches the `cmp` comparison function where descendants /// come before their ancestors. #[derive(Debug)] pub struct DepthFirstTrieIterator<C: TrieCursor> { /// The underlying trie cursor. cursor: C, /// Set to true once the trie cursor has done its initial seek to the root node. initialized: bool, /// Stack of nodes which have been fetched. Each node's path is a prefix of the next's. stack: Vec<(Nibbles, BranchNodeCompact)>, /// Nodes which are ready to be yielded from `next`. next: Vec<(Nibbles, BranchNodeCompact)>, /// Set to true once the cursor has been exhausted. complete: bool, } impl<C: TrieCursor> DepthFirstTrieIterator<C> { /// Create a new depth-first iterator from a trie cursor. pub fn new(cursor: C) -> Self { Self { cursor, initialized: false, stack: Default::default(), next: Default::default(), complete: false, } } fn push(&mut self, path: Nibbles, node: BranchNodeCompact) { loop { match self.stack.last() { None => { // If the stack is empty then we push this node onto it, as it may have child // nodes which need to be yielded first. self.stack.push((path, node)); break } Some((top_path, _)) if path.starts_with(top_path) => { // If the top of the stack is a prefix of this node, it means this node is a // child of the top of the stack (and all other nodes on the stack). Push this // node onto the stack, as future nodes may be children of it. self.stack.push((path, node)); break } Some((_, _)) => { // The top of the stack is not a prefix of this node, therefore it is not a // parent of this node. Yield the top of the stack, and loop back to see if this // node is a child of the new top-of-stack. self.next.push(self.stack.pop().expect("stack is not empty")); } } } // We will have popped off the top of the stack in the order we want to yield nodes, but // `next` is itself popped off so it needs to be reversed. self.next.reverse(); } fn fill_next(&mut self) -> Result<(), DatabaseError> { debug_assert!(self.next.is_empty()); loop { let Some((path, node)) = (if self.initialized { self.cursor.next()? } else { self.initialized = true; self.cursor.seek(Nibbles::new())? }) else { // Record that the cursor is empty and yield the stack. The stack is in reverse // order of what we want to yield, but `next` is popped from, so we don't have to // reverse it. self.complete = true; self.next = core::mem::take(&mut self.stack); return Ok(()) }; trace!( target: "trie::trie_cursor::depth_first", ?path, "Iterated from cursor", ); self.push(path, node); if !self.next.is_empty() { return Ok(()) } } } } impl<C: TrieCursor> Iterator for DepthFirstTrieIterator<C> { type Item = Result<(Nibbles, BranchNodeCompact), DatabaseError>; fn next(&mut self) -> Option<Self::Item> { loop { if let Some(next) = self.next.pop() { return Some(Ok(next)) } if self.complete { return None } if let Err(err) = self.fill_next() { return Some(Err(err)) } } } } #[cfg(test)] mod tests { use super::*; use crate::trie_cursor::{mock::MockTrieCursorFactory, TrieCursorFactory}; use alloy_trie::TrieMask; use std::{collections::BTreeMap, sync::Arc}; fn create_test_node(state_nibbles: &[u8], tree_nibbles: &[u8]) -> BranchNodeCompact { let mut state_mask = TrieMask::default(); for &nibble in state_nibbles { state_mask.set_bit(nibble); } let mut tree_mask = TrieMask::default(); for &nibble in tree_nibbles { tree_mask.set_bit(nibble); } BranchNodeCompact { state_mask, tree_mask, hash_mask: TrieMask::default(), hashes: Arc::new(vec![]), root_hash: None, } } #[test] fn test_depth_first_cmp() { // Test case 1: Child comes before parent let child = Nibbles::from_nibbles([0x1, 0x1]); let parent = Nibbles::from_nibbles([0x1]); assert_eq!(cmp(&child, &parent), Ordering::Less); assert_eq!(cmp(&parent, &child), Ordering::Greater); // Test case 2: Deeper descendant comes before ancestor let deep = Nibbles::from_nibbles([0x1, 0x2, 0x3, 0x4]); let ancestor = Nibbles::from_nibbles([0x1, 0x2]); assert_eq!(cmp(&deep, &ancestor), Ordering::Less); assert_eq!(cmp(&ancestor, &deep), Ordering::Greater); // Test case 3: Siblings use lexicographical ordering let sibling1 = Nibbles::from_nibbles([0x1, 0x2]); let sibling2 = Nibbles::from_nibbles([0x1, 0x3]); assert_eq!(cmp(&sibling1, &sibling2), Ordering::Less); assert_eq!(cmp(&sibling2, &sibling1), Ordering::Greater); // Test case 4: Different branches use lexicographical ordering let branch1 = Nibbles::from_nibbles([0x1]); let branch2 = Nibbles::from_nibbles([0x2]); assert_eq!(cmp(&branch1, &branch2), Ordering::Less); assert_eq!(cmp(&branch2, &branch1), Ordering::Greater); // Test case 5: Empty path comes after everything let empty = Nibbles::new(); let non_empty = Nibbles::from_nibbles([0x0]); assert_eq!(cmp(&non_empty, &empty), Ordering::Less); assert_eq!(cmp(&empty, &non_empty), Ordering::Greater); // Test case 6: Same paths are equal let same1 = Nibbles::from_nibbles([0x1, 0x2, 0x3]); let same2 = Nibbles::from_nibbles([0x1, 0x2, 0x3]); assert_eq!(cmp(&same1, &same2), Ordering::Equal); } #[test] fn test_depth_first_ordering_complex() { // Test the example from the conversation: 0x11, 0x12, 0x1, 0x2 let mut paths = [ Nibbles::from_nibbles([0x1]), // 0x1 Nibbles::from_nibbles([0x2]), // 0x2 Nibbles::from_nibbles([0x1, 0x1]), // 0x11 Nibbles::from_nibbles([0x1, 0x2]), // 0x12 ]; // Shuffle to ensure sorting works regardless of input order paths.reverse(); // Sort using depth-first ordering paths.sort_by(cmp); // Expected order: 0x11, 0x12, 0x1, 0x2 assert_eq!(paths[0], Nibbles::from_nibbles([0x1, 0x1])); // 0x11 assert_eq!(paths[1], Nibbles::from_nibbles([0x1, 0x2])); // 0x12 assert_eq!(paths[2], Nibbles::from_nibbles([0x1])); // 0x1 assert_eq!(paths[3], Nibbles::from_nibbles([0x2])); // 0x2 } #[test] fn test_depth_first_ordering_tree() { // Test a more complex tree structure let mut paths = vec![ Nibbles::new(), // root (empty) Nibbles::from_nibbles([0x1]), // 0x1 Nibbles::from_nibbles([0x1, 0x1]), // 0x11 Nibbles::from_nibbles([0x1, 0x1, 0x1]), // 0x111 Nibbles::from_nibbles([0x1, 0x1, 0x2]), // 0x112 Nibbles::from_nibbles([0x1, 0x2]), // 0x12 Nibbles::from_nibbles([0x2]), // 0x2 Nibbles::from_nibbles([0x2, 0x1]), // 0x21 ]; // Shuffle paths.reverse(); // Sort using depth-first ordering paths.sort_by(cmp); // Expected depth-first order: // All descendants come before ancestors // Within same level, lexicographical order assert_eq!(paths[0], Nibbles::from_nibbles([0x1, 0x1, 0x1])); // 0x111 (deepest in 0x1 branch) assert_eq!(paths[1], Nibbles::from_nibbles([0x1, 0x1, 0x2])); // 0x112 (sibling of 0x111) assert_eq!(paths[2], Nibbles::from_nibbles([0x1, 0x1])); // 0x11 (parent of 0x111, 0x112) assert_eq!(paths[3], Nibbles::from_nibbles([0x1, 0x2])); // 0x12 (sibling of 0x11) assert_eq!(paths[4], Nibbles::from_nibbles([0x1])); // 0x1 (parent of 0x11, 0x12) assert_eq!(paths[5], Nibbles::from_nibbles([0x2, 0x1])); // 0x21 (child of 0x2) assert_eq!(paths[6], Nibbles::from_nibbles([0x2])); // 0x2 (parent of 0x21) assert_eq!(paths[7], Nibbles::new()); // root (empty, parent of all) } #[test] fn test_empty_trie() { let factory = MockTrieCursorFactory::new(BTreeMap::new(), Default::default()); let cursor = factory.account_trie_cursor().unwrap(); let mut iter = DepthFirstTrieIterator::new(cursor); assert!(iter.next().is_none()); } #[test] fn test_single_node() { let path = Nibbles::from_nibbles([0x1, 0x2, 0x3]); let node = create_test_node(&[0x4], &[0x5]); let mut nodes = BTreeMap::new(); nodes.insert(path, node.clone()); let factory = MockTrieCursorFactory::new(nodes, Default::default()); let cursor = factory.account_trie_cursor().unwrap(); let mut iter = DepthFirstTrieIterator::new(cursor); let result = iter.next().unwrap().unwrap(); assert_eq!(result.0, path); assert_eq!(result.1, node); assert!(iter.next().is_none()); } #[test] fn test_depth_first_order() { // Create a simple trie structure: // root // ├── 0x1 (has children 0x2 and 0x3) // │ ├── 0x12 // │ └── 0x13 // └── 0x2 (has child 0x4) // └── 0x24 let nodes = vec![ // Root node with children at nibbles 1 and 2 (Nibbles::default(), create_test_node(&[], &[0x1, 0x2])), // Node at path 0x1 with children at nibbles 2 and 3 (Nibbles::from_nibbles([0x1]), create_test_node(&[], &[0x2, 0x3])), // Leaf nodes (Nibbles::from_nibbles([0x1, 0x2]), create_test_node(&[0xF], &[])), (Nibbles::from_nibbles([0x1, 0x3]), create_test_node(&[0xF], &[])), // Node at path 0x2 with child at nibble 4 (Nibbles::from_nibbles([0x2]), create_test_node(&[], &[0x4])), // Leaf node (Nibbles::from_nibbles([0x2, 0x4]), create_test_node(&[0xF], &[])), ]; let nodes_map: BTreeMap<_, _> = nodes.into_iter().collect(); let factory = MockTrieCursorFactory::new(nodes_map, Default::default()); let cursor = factory.account_trie_cursor().unwrap(); let iter = DepthFirstTrieIterator::new(cursor); // Expected post-order (depth-first with children before parents): // 1. 0x12 (leaf, child of 0x1) // 2. 0x13 (leaf, child of 0x1) // 3. 0x1 (parent of 0x12 and 0x13) // 4. 0x24 (leaf, child of 0x2) // 5. 0x2 (parent of 0x24) // 6. Root (parent of 0x1 and 0x2) let expected_order = vec![ Nibbles::from_nibbles([0x1, 0x2]), Nibbles::from_nibbles([0x1, 0x3]), Nibbles::from_nibbles([0x1]), Nibbles::from_nibbles([0x2, 0x4]), Nibbles::from_nibbles([0x2]), Nibbles::default(), ]; let mut actual_order = Vec::new(); for result in iter { let (path, _) = result.unwrap(); actual_order.push(path); } assert_eq!(actual_order, expected_order); } #[test] fn test_complex_tree() { // Create a more complex tree structure with multiple levels let nodes = vec![ // Root with multiple children (Nibbles::default(), create_test_node(&[], &[0x0, 0x5, 0xA, 0xF])), // Branch at 0x0 with children (Nibbles::from_nibbles([0x0]), create_test_node(&[], &[0x1, 0x2])), (Nibbles::from_nibbles([0x0, 0x1]), create_test_node(&[0x3], &[])), (Nibbles::from_nibbles([0x0, 0x2]), create_test_node(&[0x4], &[])), // Branch at 0x5 with no children (leaf) (Nibbles::from_nibbles([0x5]), create_test_node(&[0xB], &[])), // Branch at 0xA with deep nesting (Nibbles::from_nibbles([0xA]), create_test_node(&[], &[0xB])), (Nibbles::from_nibbles([0xA, 0xB]), create_test_node(&[], &[0xC])), (Nibbles::from_nibbles([0xA, 0xB, 0xC]), create_test_node(&[0xD], &[])), // Branch at 0xF (leaf) (Nibbles::from_nibbles([0xF]), create_test_node(&[0xE], &[])), ]; let nodes_map: BTreeMap<_, _> = nodes.into_iter().collect(); let factory = MockTrieCursorFactory::new(nodes_map, Default::default()); let cursor = factory.account_trie_cursor().unwrap(); let iter = DepthFirstTrieIterator::new(cursor); // Verify post-order traversal (children before parents) let expected_order = vec![ Nibbles::from_nibbles([0x0, 0x1]), // leaf child of 0x0 Nibbles::from_nibbles([0x0, 0x2]), // leaf child of 0x0 Nibbles::from_nibbles([0x0]), // parent of 0x01 and 0x02 Nibbles::from_nibbles([0x5]), // leaf Nibbles::from_nibbles([0xA, 0xB, 0xC]), // deepest leaf Nibbles::from_nibbles([0xA, 0xB]), // parent of 0xABC Nibbles::from_nibbles([0xA]), // parent of 0xAB Nibbles::from_nibbles([0xF]), // leaf Nibbles::default(), // root (last) ]; let mut actual_order = Vec::new(); for result in iter { let (path, _node) = result.unwrap(); actual_order.push(path); } assert_eq!(actual_order, expected_order); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/proof/trie_node.rs
crates/trie/trie/src/proof/trie_node.rs
use super::{Proof, StorageProof}; use crate::{hashed_cursor::HashedCursorFactory, trie_cursor::TrieCursorFactory}; use alloy_primitives::{map::HashSet, B256}; use reth_execution_errors::{SparseTrieError, SparseTrieErrorKind}; use reth_trie_common::{prefix_set::TriePrefixSetsMut, MultiProofTargets, Nibbles}; use reth_trie_sparse::provider::{ pad_path_to_key, RevealedNode, TrieNodeProvider, TrieNodeProviderFactory, }; use std::{sync::Arc, time::Instant}; use tracing::{enabled, trace, Level}; /// Factory for instantiating providers capable of retrieving blinded trie nodes via proofs. #[derive(Debug, Clone)] pub struct ProofTrieNodeProviderFactory<T, H> { /// The cursor factory for traversing trie nodes. trie_cursor_factory: T, /// The factory for hashed cursors. hashed_cursor_factory: H, /// A set of prefix sets that have changes. prefix_sets: Arc<TriePrefixSetsMut>, } impl<T, H> ProofTrieNodeProviderFactory<T, H> { /// Create new proof-based blinded provider factory. pub const fn new( trie_cursor_factory: T, hashed_cursor_factory: H, prefix_sets: Arc<TriePrefixSetsMut>, ) -> Self { Self { trie_cursor_factory, hashed_cursor_factory, prefix_sets } } } impl<T, H> TrieNodeProviderFactory for ProofTrieNodeProviderFactory<T, H> where T: TrieCursorFactory + Clone + Send + Sync, H: HashedCursorFactory + Clone + Send + Sync, { type AccountNodeProvider = ProofBlindedAccountProvider<T, H>; type StorageNodeProvider = ProofBlindedStorageProvider<T, H>; fn account_node_provider(&self) -> Self::AccountNodeProvider { ProofBlindedAccountProvider { trie_cursor_factory: self.trie_cursor_factory.clone(), hashed_cursor_factory: self.hashed_cursor_factory.clone(), prefix_sets: self.prefix_sets.clone(), } } fn storage_node_provider(&self, account: B256) -> Self::StorageNodeProvider { ProofBlindedStorageProvider { trie_cursor_factory: self.trie_cursor_factory.clone(), hashed_cursor_factory: self.hashed_cursor_factory.clone(), prefix_sets: self.prefix_sets.clone(), account, } } } /// Blinded provider for retrieving account trie nodes by path. #[derive(Debug)] pub struct ProofBlindedAccountProvider<T, H> { /// The cursor factory for traversing trie nodes. trie_cursor_factory: T, /// The factory for hashed cursors. hashed_cursor_factory: H, /// A set of prefix sets that have changes. prefix_sets: Arc<TriePrefixSetsMut>, } impl<T, H> ProofBlindedAccountProvider<T, H> { /// Create new proof-based blinded account node provider. pub const fn new( trie_cursor_factory: T, hashed_cursor_factory: H, prefix_sets: Arc<TriePrefixSetsMut>, ) -> Self { Self { trie_cursor_factory, hashed_cursor_factory, prefix_sets } } } impl<T, H> TrieNodeProvider for ProofBlindedAccountProvider<T, H> where T: TrieCursorFactory + Clone + Send + Sync, H: HashedCursorFactory + Clone + Send + Sync, { fn trie_node(&self, path: &Nibbles) -> Result<Option<RevealedNode>, SparseTrieError> { let start = enabled!(target: "trie::proof::blinded", Level::TRACE).then(Instant::now); let targets = MultiProofTargets::from_iter([(pad_path_to_key(path), HashSet::default())]); let mut proof = Proof::new(self.trie_cursor_factory.clone(), self.hashed_cursor_factory.clone()) .with_prefix_sets_mut(self.prefix_sets.as_ref().clone()) .with_branch_node_masks(true) .multiproof(targets) .map_err(|error| SparseTrieErrorKind::Other(Box::new(error)))?; let node = proof.account_subtree.into_inner().remove(path); let tree_mask = proof.branch_node_tree_masks.remove(path); let hash_mask = proof.branch_node_hash_masks.remove(path); trace!( target: "trie::proof::blinded", elapsed = ?start.unwrap().elapsed(), ?path, ?node, ?tree_mask, ?hash_mask, "Blinded node for account trie" ); Ok(node.map(|node| RevealedNode { node, tree_mask, hash_mask })) } } /// Blinded provider for retrieving storage trie nodes by path. #[derive(Debug)] pub struct ProofBlindedStorageProvider<T, H> { /// The cursor factory for traversing trie nodes. trie_cursor_factory: T, /// The factory for hashed cursors. hashed_cursor_factory: H, /// A set of prefix sets that have changes. prefix_sets: Arc<TriePrefixSetsMut>, /// Target account. account: B256, } impl<T, H> ProofBlindedStorageProvider<T, H> { /// Create new proof-based blinded storage node provider. pub const fn new( trie_cursor_factory: T, hashed_cursor_factory: H, prefix_sets: Arc<TriePrefixSetsMut>, account: B256, ) -> Self { Self { trie_cursor_factory, hashed_cursor_factory, prefix_sets, account } } } impl<T, H> TrieNodeProvider for ProofBlindedStorageProvider<T, H> where T: TrieCursorFactory + Clone + Send + Sync, H: HashedCursorFactory + Clone + Send + Sync, { fn trie_node(&self, path: &Nibbles) -> Result<Option<RevealedNode>, SparseTrieError> { let start = enabled!(target: "trie::proof::blinded", Level::TRACE).then(Instant::now); let targets = HashSet::from_iter([pad_path_to_key(path)]); let storage_prefix_set = self.prefix_sets.storage_prefix_sets.get(&self.account).cloned().unwrap_or_default(); let mut proof = StorageProof::new_hashed( self.trie_cursor_factory.clone(), self.hashed_cursor_factory.clone(), self.account, ) .with_prefix_set_mut(storage_prefix_set) .with_branch_node_masks(true) .storage_multiproof(targets) .map_err(|error| SparseTrieErrorKind::Other(Box::new(error)))?; let node = proof.subtree.into_inner().remove(path); let tree_mask = proof.branch_node_tree_masks.remove(path); let hash_mask = proof.branch_node_hash_masks.remove(path); trace!( target: "trie::proof::blinded", account = ?self.account, elapsed = ?start.unwrap().elapsed(), ?path, ?node, ?tree_mask, ?hash_mask, "Blinded node for storage trie" ); Ok(node.map(|node| RevealedNode { node, tree_mask, hash_mask })) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/proof/mod.rs
crates/trie/trie/src/proof/mod.rs
use crate::{ hashed_cursor::{HashedCursorFactory, HashedStorageCursor}, node_iter::{TrieElement, TrieNodeIter}, prefix_set::{PrefixSetMut, TriePrefixSetsMut}, trie_cursor::TrieCursorFactory, walker::TrieWalker, HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE, }; use alloy_primitives::{ keccak256, map::{B256Map, B256Set, HashMap, HashSet}, Address, B256, }; use alloy_rlp::{BufMut, Encodable}; use alloy_trie::proof::AddedRemovedKeys; use reth_execution_errors::trie::StateProofError; use reth_trie_common::{ proof::ProofRetainer, AccountProof, MultiProof, MultiProofTargets, StorageMultiProof, }; mod trie_node; pub use trie_node::*; /// A struct for generating merkle proofs. /// /// Proof generator adds the target address and slots to the prefix set, enables the proof retainer /// on the hash builder and follows the same algorithm as the state root calculator. /// See `StateRoot::root` for more info. #[derive(Debug)] pub struct Proof<T, H> { /// The factory for traversing trie nodes. trie_cursor_factory: T, /// The factory for hashed cursors. hashed_cursor_factory: H, /// A set of prefix sets that have changes. prefix_sets: TriePrefixSetsMut, /// Flag indicating whether to include branch node masks in the proof. collect_branch_node_masks: bool, } impl<T, H> Proof<T, H> { /// Create a new [`Proof`] instance. pub fn new(t: T, h: H) -> Self { Self { trie_cursor_factory: t, hashed_cursor_factory: h, prefix_sets: TriePrefixSetsMut::default(), collect_branch_node_masks: false, } } /// Set the trie cursor factory. pub fn with_trie_cursor_factory<TF>(self, trie_cursor_factory: TF) -> Proof<TF, H> { Proof { trie_cursor_factory, hashed_cursor_factory: self.hashed_cursor_factory, prefix_sets: self.prefix_sets, collect_branch_node_masks: self.collect_branch_node_masks, } } /// Set the hashed cursor factory. pub fn with_hashed_cursor_factory<HF>(self, hashed_cursor_factory: HF) -> Proof<T, HF> { Proof { trie_cursor_factory: self.trie_cursor_factory, hashed_cursor_factory, prefix_sets: self.prefix_sets, collect_branch_node_masks: self.collect_branch_node_masks, } } /// Set the prefix sets. They have to be mutable in order to allow extension with proof target. pub fn with_prefix_sets_mut(mut self, prefix_sets: TriePrefixSetsMut) -> Self { self.prefix_sets = prefix_sets; self } /// Set the flag indicating whether to include branch node masks in the proof. pub const fn with_branch_node_masks(mut self, branch_node_masks: bool) -> Self { self.collect_branch_node_masks = branch_node_masks; self } } impl<T, H> Proof<T, H> where T: TrieCursorFactory + Clone, H: HashedCursorFactory + Clone, { /// Generate an account proof from intermediate nodes. pub fn account_proof( self, address: Address, slots: &[B256], ) -> Result<AccountProof, StateProofError> { Ok(self .multiproof(MultiProofTargets::from_iter([( keccak256(address), slots.iter().map(keccak256).collect(), )]))? .account_proof(address, slots)?) } /// Generate a state multiproof according to specified targets. pub fn multiproof( mut self, mut targets: MultiProofTargets, ) -> Result<MultiProof, StateProofError> { let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?; let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?; // Create the walker. let mut prefix_set = self.prefix_sets.account_prefix_set.clone(); prefix_set.extend_keys(targets.keys().map(Nibbles::unpack)); let walker = TrieWalker::<_>::state_trie(trie_cursor, prefix_set.freeze()); // Create a hash builder to rebuild the root node since it is not available in the database. let retainer = targets.keys().map(Nibbles::unpack).collect(); let mut hash_builder = HashBuilder::default() .with_proof_retainer(retainer) .with_updates(self.collect_branch_node_masks); // Initialize all storage multiproofs as empty. // Storage multiproofs for non empty tries will be overwritten if necessary. let mut storages: B256Map<_> = targets.keys().map(|key| (*key, StorageMultiProof::empty())).collect(); let mut account_rlp = Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE); let mut account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor); while let Some(account_node) = account_node_iter.try_next()? { match account_node { TrieElement::Branch(node) => { hash_builder.add_branch(node.key, node.value, node.children_are_in_trie); } TrieElement::Leaf(hashed_address, account) => { let proof_targets = targets.remove(&hashed_address); let leaf_is_proof_target = proof_targets.is_some(); let storage_prefix_set = self .prefix_sets .storage_prefix_sets .remove(&hashed_address) .unwrap_or_default(); let storage_multiproof = StorageProof::new_hashed( self.trie_cursor_factory.clone(), self.hashed_cursor_factory.clone(), hashed_address, ) .with_prefix_set_mut(storage_prefix_set) .with_branch_node_masks(self.collect_branch_node_masks) .storage_multiproof(proof_targets.unwrap_or_default())?; // Encode account account_rlp.clear(); let account = account.into_trie_account(storage_multiproof.root); account.encode(&mut account_rlp as &mut dyn BufMut); let is_private = false; // account leaves are always public. Their storage leaves can be private. hash_builder.add_leaf( Nibbles::unpack(hashed_address), &account_rlp, is_private, ); // We might be adding leaves that are not necessarily our proof targets. if leaf_is_proof_target { // Overwrite storage multiproof. storages.insert(hashed_address, storage_multiproof); } } } } let _ = hash_builder.root(); let account_subtree = hash_builder.take_proof_nodes(); let (branch_node_hash_masks, branch_node_tree_masks) = if self.collect_branch_node_masks { let updated_branch_nodes = hash_builder.updated_branch_nodes.unwrap_or_default(); ( updated_branch_nodes.iter().map(|(path, node)| (*path, node.hash_mask)).collect(), updated_branch_nodes .into_iter() .map(|(path, node)| (path, node.tree_mask)) .collect(), ) } else { (HashMap::default(), HashMap::default()) }; Ok(MultiProof { account_subtree, branch_node_hash_masks, branch_node_tree_masks, storages }) } } /// Generates storage merkle proofs. #[derive(Debug)] pub struct StorageProof<T, H, K = AddedRemovedKeys> { /// The factory for traversing trie nodes. trie_cursor_factory: T, /// The factory for hashed cursors. hashed_cursor_factory: H, /// The hashed address of an account. hashed_address: B256, /// The set of storage slot prefixes that have changed. prefix_set: PrefixSetMut, /// Flag indicating whether to include branch node masks in the proof. collect_branch_node_masks: bool, /// Provided by the user to give the necessary context to retain extra proofs. added_removed_keys: Option<K>, } impl<T, H> StorageProof<T, H> { /// Create a new [`StorageProof`] instance. pub fn new(t: T, h: H, address: Address) -> Self { Self::new_hashed(t, h, keccak256(address)) } /// Create a new [`StorageProof`] instance with hashed address. pub fn new_hashed(t: T, h: H, hashed_address: B256) -> Self { Self { trie_cursor_factory: t, hashed_cursor_factory: h, hashed_address, prefix_set: PrefixSetMut::default(), collect_branch_node_masks: false, added_removed_keys: None, } } } impl<T, H, K> StorageProof<T, H, K> { /// Set the trie cursor factory. pub fn with_trie_cursor_factory<TF>(self, trie_cursor_factory: TF) -> StorageProof<TF, H, K> { StorageProof { trie_cursor_factory, hashed_cursor_factory: self.hashed_cursor_factory, hashed_address: self.hashed_address, prefix_set: self.prefix_set, collect_branch_node_masks: self.collect_branch_node_masks, added_removed_keys: self.added_removed_keys, } } /// Set the hashed cursor factory. pub fn with_hashed_cursor_factory<HF>( self, hashed_cursor_factory: HF, ) -> StorageProof<T, HF, K> { StorageProof { trie_cursor_factory: self.trie_cursor_factory, hashed_cursor_factory, hashed_address: self.hashed_address, prefix_set: self.prefix_set, collect_branch_node_masks: self.collect_branch_node_masks, added_removed_keys: self.added_removed_keys, } } /// Set the changed prefixes. pub fn with_prefix_set_mut(mut self, prefix_set: PrefixSetMut) -> Self { self.prefix_set = prefix_set; self } /// Set the flag indicating whether to include branch node masks in the proof. pub const fn with_branch_node_masks(mut self, branch_node_masks: bool) -> Self { self.collect_branch_node_masks = branch_node_masks; self } /// Configures the retainer to retain proofs for certain nodes which would otherwise fall /// outside the target set, when those nodes might be required to calculate the state root when /// keys have been added or removed to the trie. /// /// If None is given then retention of extra proofs is disabled. pub fn with_added_removed_keys<K2>( self, added_removed_keys: Option<K2>, ) -> StorageProof<T, H, K2> { StorageProof { trie_cursor_factory: self.trie_cursor_factory, hashed_cursor_factory: self.hashed_cursor_factory, hashed_address: self.hashed_address, prefix_set: self.prefix_set, collect_branch_node_masks: self.collect_branch_node_masks, added_removed_keys, } } } impl<T, H, K> StorageProof<T, H, K> where T: TrieCursorFactory, H: HashedCursorFactory, K: AsRef<AddedRemovedKeys>, { /// Generate an account proof from intermediate nodes. pub fn storage_proof( self, slot: B256, ) -> Result<reth_trie_common::StorageProof, StateProofError> { let targets = HashSet::from_iter([keccak256(slot)]); Ok(self.storage_multiproof(targets)?.storage_proof(slot)?) } /// Generate storage proof. pub fn storage_multiproof( mut self, targets: B256Set, ) -> Result<StorageMultiProof, StateProofError> { let mut hashed_storage_cursor = self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?; // short circuit on empty storage if hashed_storage_cursor.is_storage_empty()? { return Ok(StorageMultiProof::empty()); } let target_nibbles = targets.into_iter().map(Nibbles::unpack).collect::<Vec<_>>(); self.prefix_set.extend_keys(target_nibbles.clone()); let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?; let walker = TrieWalker::<_>::storage_trie(trie_cursor, self.prefix_set.freeze()) .with_added_removed_keys(self.added_removed_keys.as_ref()); let retainer = ProofRetainer::from_iter(target_nibbles) .with_added_removed_keys(self.added_removed_keys.as_ref()); let mut hash_builder = HashBuilder::default() .with_proof_retainer(retainer) .with_updates(self.collect_branch_node_masks); let mut storage_node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor); while let Some(node) = storage_node_iter.try_next()? { match node { TrieElement::Branch(node) => { hash_builder.add_branch(node.key, node.value, node.children_are_in_trie); } TrieElement::Leaf(hashed_slot, value) => { hash_builder.add_leaf( Nibbles::unpack(hashed_slot), alloy_rlp::encode_fixed_size(&value).as_ref(), value.is_private, ); } } } let root = hash_builder.root(); let subtree = hash_builder.take_proof_nodes(); let (branch_node_hash_masks, branch_node_tree_masks) = if self.collect_branch_node_masks { let updated_branch_nodes = hash_builder.updated_branch_nodes.unwrap_or_default(); ( updated_branch_nodes.iter().map(|(path, node)| (*path, node.hash_mask)).collect(), updated_branch_nodes .into_iter() .map(|(path, node)| (path, node.tree_mask)) .collect(), ) } else { (HashMap::default(), HashMap::default()) }; Ok(StorageMultiProof { root, subtree, branch_node_hash_masks, branch_node_tree_masks }) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/hashed_cursor/noop.rs
crates/trie/trie/src/hashed_cursor/noop.rs
use super::{HashedCursor, HashedCursorFactory, HashedStorageCursor}; use alloy_primitives::B256; use reth_primitives_traits::Account; use reth_storage_errors::db::DatabaseError; use revm_state::FlaggedStorage; /// Noop hashed cursor factory. #[derive(Clone, Default, Debug)] #[non_exhaustive] pub struct NoopHashedCursorFactory; impl HashedCursorFactory for NoopHashedCursorFactory { type AccountCursor = NoopHashedAccountCursor; type StorageCursor = NoopHashedStorageCursor; fn hashed_account_cursor(&self) -> Result<Self::AccountCursor, DatabaseError> { Ok(NoopHashedAccountCursor::default()) } fn hashed_storage_cursor( &self, _hashed_address: B256, ) -> Result<Self::StorageCursor, DatabaseError> { Ok(NoopHashedStorageCursor::default()) } } /// Noop account hashed cursor. #[derive(Default, Debug)] #[non_exhaustive] pub struct NoopHashedAccountCursor; impl HashedCursor for NoopHashedAccountCursor { type Value = Account; fn seek(&mut self, _key: B256) -> Result<Option<(B256, Self::Value)>, DatabaseError> { Ok(None) } fn next(&mut self) -> Result<Option<(B256, Self::Value)>, DatabaseError> { Ok(None) } } /// Noop account hashed cursor. #[derive(Default, Debug)] #[non_exhaustive] pub struct NoopHashedStorageCursor; impl HashedCursor for NoopHashedStorageCursor { type Value = FlaggedStorage; fn seek(&mut self, _key: B256) -> Result<Option<(B256, Self::Value)>, DatabaseError> { Ok(None) } fn next(&mut self) -> Result<Option<(B256, Self::Value)>, DatabaseError> { Ok(None) } } impl HashedStorageCursor for NoopHashedStorageCursor { fn is_storage_empty(&mut self) -> Result<bool, DatabaseError> { Ok(true) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/hashed_cursor/mod.rs
crates/trie/trie/src/hashed_cursor/mod.rs
use alloy_primitives::B256; use reth_primitives_traits::Account; use reth_storage_errors::db::DatabaseError; use revm_state::FlaggedStorage; /// Implementation of hashed state cursor traits for the post state. mod post_state; pub use post_state::*; /// Implementation of noop hashed state cursor. pub mod noop; /// Mock trie cursor implementations. #[cfg(test)] pub mod mock; /// The factory trait for creating cursors over the hashed state. pub trait HashedCursorFactory { /// The hashed account cursor type. type AccountCursor: HashedCursor<Value = Account>; /// The hashed storage cursor type. type StorageCursor: HashedStorageCursor<Value = FlaggedStorage>; /// Returns a cursor for iterating over all hashed accounts in the state. fn hashed_account_cursor(&self) -> Result<Self::AccountCursor, DatabaseError>; /// Returns a cursor for iterating over all hashed storage entries in the state. fn hashed_storage_cursor( &self, hashed_address: B256, ) -> Result<Self::StorageCursor, DatabaseError>; } /// The cursor for iterating over hashed entries. pub trait HashedCursor { /// Value returned by the cursor. type Value: std::fmt::Debug; /// Seek an entry greater or equal to the given key and position the cursor there. /// Returns the first entry with the key greater or equal to the sought key. fn seek(&mut self, key: B256) -> Result<Option<(B256, Self::Value)>, DatabaseError>; /// Move the cursor to the next entry and return it. fn next(&mut self) -> Result<Option<(B256, Self::Value)>, DatabaseError>; } /// The cursor for iterating over hashed storage entries. pub trait HashedStorageCursor: HashedCursor { /// Returns `true` if there are no entries for a given key. fn is_storage_empty(&mut self) -> Result<bool, DatabaseError>; }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/hashed_cursor/mock.rs
crates/trie/trie/src/hashed_cursor/mock.rs
use std::{collections::BTreeMap, fmt::Debug, sync::Arc}; use crate::mock::{KeyVisit, KeyVisitType}; use super::{HashedCursor, HashedCursorFactory, HashedStorageCursor}; use alloy_primitives::{map::B256Map, B256}; use parking_lot::{Mutex, MutexGuard}; use reth_primitives_traits::Account; use reth_storage_errors::db::DatabaseError; use revm_state::FlaggedStorage; use tracing::instrument; /// Mock hashed cursor factory. #[derive(Clone, Default, Debug)] pub struct MockHashedCursorFactory { hashed_accounts: Arc<BTreeMap<B256, Account>>, hashed_storage_tries: B256Map<Arc<BTreeMap<B256, FlaggedStorage>>>, /// List of keys that the hashed accounts cursor has visited. visited_account_keys: Arc<Mutex<Vec<KeyVisit<B256>>>>, /// List of keys that the hashed storages cursor has visited, per storage trie. visited_storage_keys: B256Map<Arc<Mutex<Vec<KeyVisit<B256>>>>>, } impl MockHashedCursorFactory { /// Creates a new mock hashed cursor factory. pub fn new( hashed_accounts: BTreeMap<B256, Account>, hashed_storage_tries: B256Map<BTreeMap<B256, FlaggedStorage>>, ) -> Self { let visited_storage_keys = hashed_storage_tries.keys().map(|k| (*k, Default::default())).collect(); Self { hashed_accounts: Arc::new(hashed_accounts), hashed_storage_tries: hashed_storage_tries .into_iter() .map(|(k, v)| (k, Arc::new(v))) .collect(), visited_account_keys: Default::default(), visited_storage_keys, } } /// Returns a reference to the list of visited hashed account keys. pub fn visited_account_keys(&self) -> MutexGuard<'_, Vec<KeyVisit<B256>>> { self.visited_account_keys.lock() } /// Returns a reference to the list of visited hashed storage keys for the given hashed address. pub fn visited_storage_keys( &self, hashed_address: B256, ) -> MutexGuard<'_, Vec<KeyVisit<B256>>> { self.visited_storage_keys.get(&hashed_address).expect("storage trie should exist").lock() } } impl HashedCursorFactory for MockHashedCursorFactory { type AccountCursor = MockHashedCursor<Account>; type StorageCursor = MockHashedCursor<FlaggedStorage>; fn hashed_account_cursor(&self) -> Result<Self::AccountCursor, DatabaseError> { Ok(MockHashedCursor::new(self.hashed_accounts.clone(), self.visited_account_keys.clone())) } fn hashed_storage_cursor( &self, hashed_address: B256, ) -> Result<Self::StorageCursor, DatabaseError> { Ok(MockHashedCursor::new( self.hashed_storage_tries .get(&hashed_address) .ok_or_else(|| { DatabaseError::Other(format!("storage trie for {hashed_address:?} not found")) })? .clone(), self.visited_storage_keys .get(&hashed_address) .ok_or_else(|| { DatabaseError::Other(format!("storage trie for {hashed_address:?} not found")) })? .clone(), )) } } /// Mock hashed cursor. #[derive(Default, Debug)] pub struct MockHashedCursor<T> { /// The current key. If set, it is guaranteed to exist in `values`. current_key: Option<B256>, values: Arc<BTreeMap<B256, T>>, visited_keys: Arc<Mutex<Vec<KeyVisit<B256>>>>, } impl<T> MockHashedCursor<T> { fn new(values: Arc<BTreeMap<B256, T>>, visited_keys: Arc<Mutex<Vec<KeyVisit<B256>>>>) -> Self { Self { current_key: None, values, visited_keys } } } impl<T: Debug + Clone> HashedCursor for MockHashedCursor<T> { type Value = T; #[instrument(level = "trace", skip(self), ret)] fn seek(&mut self, key: B256) -> Result<Option<(B256, Self::Value)>, DatabaseError> { // Find the first key that is greater than or equal to the given key. let entry = self.values.iter().find_map(|(k, v)| (k >= &key).then(|| (*k, v.clone()))); if let Some((key, _)) = &entry { self.current_key = Some(*key); } self.visited_keys.lock().push(KeyVisit { visit_type: KeyVisitType::SeekNonExact(key), visited_key: entry.as_ref().map(|(k, _)| *k), }); Ok(entry) } #[instrument(level = "trace", skip(self), ret)] fn next(&mut self) -> Result<Option<(B256, Self::Value)>, DatabaseError> { let mut iter = self.values.iter(); // Jump to the first key that has a prefix of the current key if it's set, or to the first // key otherwise. iter.find(|(k, _)| { self.current_key.as_ref().is_none_or(|current| k.starts_with(current.as_slice())) }) .expect("current key should exist in values"); // Get the next key-value pair. let entry = iter.next().map(|(k, v)| (*k, v.clone())); if let Some((key, _)) = &entry { self.current_key = Some(*key); } self.visited_keys.lock().push(KeyVisit { visit_type: KeyVisitType::Next, visited_key: entry.as_ref().map(|(k, _)| *k), }); Ok(entry) } } impl<T: Debug + Clone> HashedStorageCursor for MockHashedCursor<T> { #[instrument(level = "trace", skip(self), ret)] fn is_storage_empty(&mut self) -> Result<bool, DatabaseError> { Ok(self.values.is_empty()) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/src/hashed_cursor/post_state.rs
crates/trie/trie/src/hashed_cursor/post_state.rs
use super::{HashedCursor, HashedCursorFactory, HashedStorageCursor}; use crate::forward_cursor::ForwardInMemoryCursor; use alloy_primitives::{map::B256Set, B256}; use reth_primitives_traits::Account; use reth_storage_errors::db::DatabaseError; use reth_trie_common::{HashedAccountsSorted, HashedPostStateSorted, HashedStorageSorted}; use revm_state::FlaggedStorage; /// The hashed cursor factory for the post state. #[derive(Clone, Debug)] pub struct HashedPostStateCursorFactory<'a, CF> { cursor_factory: CF, post_state: &'a HashedPostStateSorted, } impl<'a, CF> HashedPostStateCursorFactory<'a, CF> { /// Create a new factory. pub const fn new(cursor_factory: CF, post_state: &'a HashedPostStateSorted) -> Self { Self { cursor_factory, post_state } } } impl<'a, CF: HashedCursorFactory> HashedCursorFactory for HashedPostStateCursorFactory<'a, CF> { type AccountCursor = HashedPostStateAccountCursor<'a, CF::AccountCursor>; type StorageCursor = HashedPostStateStorageCursor<'a, CF::StorageCursor>; fn hashed_account_cursor(&self) -> Result<Self::AccountCursor, DatabaseError> { let cursor = self.cursor_factory.hashed_account_cursor()?; Ok(HashedPostStateAccountCursor::new(cursor, &self.post_state.accounts)) } fn hashed_storage_cursor( &self, hashed_address: B256, ) -> Result<Self::StorageCursor, DatabaseError> { let cursor = self.cursor_factory.hashed_storage_cursor(hashed_address)?; Ok(HashedPostStateStorageCursor::new(cursor, self.post_state.storages.get(&hashed_address))) } } /// The cursor to iterate over post state hashed accounts and corresponding database entries. /// It will always give precedence to the data from the hashed post state. #[derive(Debug)] pub struct HashedPostStateAccountCursor<'a, C> { /// The database cursor. cursor: C, /// Forward-only in-memory cursor over accounts. post_state_cursor: ForwardInMemoryCursor<'a, B256, Account>, /// Reference to the collection of account keys that were destroyed. destroyed_accounts: &'a B256Set, /// The last hashed account that was returned by the cursor. /// De facto, this is a current cursor position. last_account: Option<B256>, } impl<'a, C> HashedPostStateAccountCursor<'a, C> where C: HashedCursor<Value = Account>, { /// Create new instance of [`HashedPostStateAccountCursor`]. pub fn new(cursor: C, post_state_accounts: &'a HashedAccountsSorted) -> Self { let post_state_cursor = ForwardInMemoryCursor::new(&post_state_accounts.accounts); let destroyed_accounts = &post_state_accounts.destroyed_accounts; Self { cursor, post_state_cursor, destroyed_accounts, last_account: None } } /// Returns `true` if the account has been destroyed. /// This check is used for evicting account keys from the state trie. /// /// This function only checks the post state, not the database, because the latter does not /// store destroyed accounts. fn is_account_cleared(&self, account: &B256) -> bool { self.destroyed_accounts.contains(account) } fn seek_inner(&mut self, key: B256) -> Result<Option<(B256, Account)>, DatabaseError> { // Take the next account from the post state with the key greater than or equal to the // sought key. let post_state_entry = self.post_state_cursor.seek(&key); // It's an exact match, return the account from post state without looking up in the // database. if post_state_entry.is_some_and(|entry| entry.0 == key) { return Ok(post_state_entry); } // It's not an exact match, reposition to the first greater or equal account that wasn't // cleared. let mut db_entry = self.cursor.seek(key)?; while db_entry.as_ref().is_some_and(|(address, _)| self.is_account_cleared(address)) { db_entry = self.cursor.next()?; } // Compare two entries and return the lowest. Ok(Self::compare_entries(post_state_entry, db_entry)) } fn next_inner(&mut self, last_account: B256) -> Result<Option<(B256, Account)>, DatabaseError> { // Take the next account from the post state with the key greater than the last sought key. let post_state_entry = self.post_state_cursor.first_after(&last_account); // If post state was given precedence or account was cleared, move the cursor forward. let mut db_entry = self.cursor.seek(last_account)?; while db_entry.as_ref().is_some_and(|(address, _)| { address <= &last_account || self.is_account_cleared(address) }) { db_entry = self.cursor.next()?; } // Compare two entries and return the lowest. Ok(Self::compare_entries(post_state_entry, db_entry)) } /// Return the account with the lowest hashed account key. /// /// Given the next post state and database entries, return the smallest of the two. /// If the account keys are the same, the post state entry is given precedence. fn compare_entries( post_state_item: Option<(B256, Account)>, db_item: Option<(B256, Account)>, ) -> Option<(B256, Account)> { if let Some((post_state_entry, db_entry)) = post_state_item.zip(db_item) { // If both are not empty, return the smallest of the two // Post state is given precedence if keys are equal Some(if post_state_entry.0 <= db_entry.0 { post_state_entry } else { db_entry }) } else { // Return either non-empty entry db_item.or(post_state_item) } } } impl<C> HashedCursor for HashedPostStateAccountCursor<'_, C> where C: HashedCursor<Value = Account>, { type Value = Account; /// Seek the next entry for a given hashed account key. /// /// If the post state contains the exact match for the key, return it. /// Otherwise, retrieve the next entries that are greater than or equal to the key from the /// database and the post state. The two entries are compared and the lowest is returned. /// /// The returned account key is memoized and the cursor remains positioned at that key until /// [`HashedCursor::seek`] or [`HashedCursor::next`] are called. fn seek(&mut self, key: B256) -> Result<Option<(B256, Self::Value)>, DatabaseError> { // Find the closes account. let entry = self.seek_inner(key)?; self.last_account = entry.as_ref().map(|entry| entry.0); Ok(entry) } /// Retrieve the next entry from the cursor. /// /// If the cursor is positioned at the entry, return the entry with next greater key. /// Returns [None] if the previous memoized or the next greater entries are missing. /// /// NOTE: This function will not return any entry unless [`HashedCursor::seek`] has been /// called. fn next(&mut self) -> Result<Option<(B256, Self::Value)>, DatabaseError> { let next = match self.last_account { Some(account) => { let entry = self.next_inner(account)?; self.last_account = entry.as_ref().map(|entry| entry.0); entry } // no previous entry was found None => None, }; Ok(next) } } /// The cursor to iterate over post state hashed storages and corresponding database entries. /// It will always give precedence to the data from the post state. #[derive(Debug)] pub struct HashedPostStateStorageCursor<'a, C> { /// The database cursor. cursor: C, /// Forward-only in-memory cursor over non zero-valued account storage slots. post_state_cursor: Option<ForwardInMemoryCursor<'a, B256, FlaggedStorage>>, /// Reference to the collection of storage slot keys that were cleared. cleared_slots: Option<&'a B256Set>, /// Flag indicating whether database storage was wiped. storage_wiped: bool, /// The last slot that has been returned by the cursor. /// De facto, this is the cursor's position for the given account key. last_slot: Option<B256>, } impl<'a, C> HashedPostStateStorageCursor<'a, C> where C: HashedStorageCursor<Value = FlaggedStorage>, { /// Create new instance of [`HashedPostStateStorageCursor`] for the given hashed address. pub fn new(cursor: C, post_state_storage: Option<&'a HashedStorageSorted>) -> Self { let post_state_cursor = post_state_storage.map(|s| ForwardInMemoryCursor::new(&s.non_zero_valued_slots)); let cleared_slots = post_state_storage.map(|s| &s.zero_valued_slots); let storage_wiped = post_state_storage.is_some_and(|s| s.wiped); Self { cursor, post_state_cursor, cleared_slots, storage_wiped, last_slot: None } } /// Check if the slot was zeroed out in the post state. /// The database is not checked since it already has no zero-valued slots. fn is_slot_zero_valued(&self, slot: &B256) -> bool { self.cleared_slots.is_some_and(|s| s.contains(slot)) } /// Find the storage entry in post state or database that's greater or equal to provided subkey. fn seek_inner( &mut self, subkey: B256, ) -> Result<Option<(B256, FlaggedStorage)>, DatabaseError> { // Attempt to find the account's storage in post state. let post_state_entry = self.post_state_cursor.as_mut().and_then(|c| c.seek(&subkey)); // If database storage was wiped or it's an exact match, // return the storage slot from post state without looking up in the database. if self.storage_wiped || post_state_entry.is_some_and(|entry| entry.0 == subkey) { return Ok(post_state_entry); } // It's not an exact match and storage was not wiped, // reposition to the first greater or equal account. let mut db_entry = self.cursor.seek(subkey)?; while db_entry.as_ref().is_some_and(|entry| self.is_slot_zero_valued(&entry.0)) { db_entry = self.cursor.next()?; } // Compare two entries and return the lowest. Ok(Self::compare_entries(post_state_entry, db_entry)) } /// Find the storage entry that is right after current cursor position. fn next_inner( &mut self, last_slot: B256, ) -> Result<Option<(B256, FlaggedStorage)>, DatabaseError> { // Attempt to find the account's storage in post state. let post_state_entry = self.post_state_cursor.as_mut().and_then(|c| c.first_after(&last_slot)); // Return post state entry immediately if database was wiped. if self.storage_wiped { return Ok(post_state_entry); } // If post state was given precedence, move the cursor forward. // If the entry was already returned or is zero-valued, move to the next. let mut db_entry = self.cursor.seek(last_slot)?; while db_entry .as_ref() .is_some_and(|entry| entry.0 == last_slot || self.is_slot_zero_valued(&entry.0)) { db_entry = self.cursor.next()?; } // Compare two entries and return the lowest. Ok(Self::compare_entries(post_state_entry, db_entry)) } /// Return the storage entry with the lowest hashed storage key (hashed slot). /// /// Given the next post state and database entries, return the smallest of the two. /// If the storage keys are the same, the post state entry is given precedence. fn compare_entries( post_state_item: Option<(B256, FlaggedStorage)>, db_item: Option<(B256, FlaggedStorage)>, ) -> Option<(B256, FlaggedStorage)> { if let Some((post_state_entry, db_entry)) = post_state_item.zip(db_item) { // If both are not empty, return the smallest of the two // Post state is given precedence if keys are equal Some(if post_state_entry.0 <= db_entry.0 { post_state_entry } else { db_entry }) } else { // Return either non-empty entry db_item.or(post_state_item) } } } impl<C> HashedCursor for HashedPostStateStorageCursor<'_, C> where C: HashedStorageCursor<Value = FlaggedStorage>, { type Value = FlaggedStorage; /// Seek the next account storage entry for a given hashed key pair. fn seek(&mut self, subkey: B256) -> Result<Option<(B256, Self::Value)>, DatabaseError> { let entry = self.seek_inner(subkey)?; self.last_slot = entry.as_ref().map(|entry| entry.0); Ok(entry) } /// Return the next account storage entry for the current account key. fn next(&mut self) -> Result<Option<(B256, Self::Value)>, DatabaseError> { let next = match self.last_slot { Some(last_slot) => { let entry = self.next_inner(last_slot)?; self.last_slot = entry.as_ref().map(|entry| entry.0); entry } // no previous entry was found None => None, }; Ok(next) } } impl<C> HashedStorageCursor for HashedPostStateStorageCursor<'_, C> where C: HashedStorageCursor<Value = FlaggedStorage>, { /// Returns `true` if the account has no storage entries. /// /// This function should be called before attempting to call [`HashedCursor::seek`] or /// [`HashedCursor::next`]. fn is_storage_empty(&mut self) -> Result<bool, DatabaseError> { let is_empty = match &self.post_state_cursor { Some(cursor) => { // If the storage has been wiped at any point self.storage_wiped && // and the current storage does not contain any non-zero values cursor.is_empty() } None => self.cursor.is_storage_empty()?, }; Ok(is_empty) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/benches/trie_root.rs
crates/trie/trie/benches/trie_root.rs
#![allow(missing_docs, unreachable_pub)] use alloy_consensus::ReceiptWithBloom; use alloy_primitives::B256; use criterion::{criterion_group, criterion_main, Criterion}; use proptest::{prelude::*, strategy::ValueTree, test_runner::TestRunner}; use proptest_arbitrary_interop::arb; use reth_ethereum_primitives::Receipt; use reth_trie::triehash::KeccakHasher; use std::hint::black_box; /// Benchmarks different implementations of the root calculation. pub fn trie_root_benchmark(c: &mut Criterion) { let mut group = c.benchmark_group("Receipts root calculation"); for size in [10, 100, 1_000] { let group_name = |description: &str| format!("receipts root | size: {size} | {description}"); let receipts = &generate_test_data(size)[..]; assert_eq!(trie_hash_ordered_trie_root(receipts), hash_builder_root(receipts)); group.bench_function(group_name("triehash::ordered_trie_root"), |b| { b.iter(|| trie_hash_ordered_trie_root(black_box(receipts))); }); group.bench_function(group_name("HashBuilder"), |b| { b.iter(|| hash_builder_root(black_box(receipts))); }); } } fn generate_test_data(size: usize) -> Vec<ReceiptWithBloom<Receipt>> { prop::collection::vec(arb::<ReceiptWithBloom<Receipt>>(), size) .new_tree(&mut TestRunner::deterministic()) .unwrap() .current() } criterion_group! { name = benches; config = Criterion::default(); targets = trie_root_benchmark } criterion_main!(benches); mod implementations { use super::*; use alloy_eips::eip2718::Encodable2718; use alloy_rlp::Encodable; use alloy_trie::root::adjust_index_for_rlp; use reth_trie_common::{HashBuilder, Nibbles}; pub fn trie_hash_ordered_trie_root(receipts: &[ReceiptWithBloom<Receipt>]) -> B256 { triehash::ordered_trie_root::<KeccakHasher, _>( receipts.iter().map(|receipt_with_bloom| receipt_with_bloom.encoded_2718()), ) } pub fn hash_builder_root(receipts: &[ReceiptWithBloom<Receipt>]) -> B256 { let mut index_buffer = Vec::new(); let mut value_buffer = Vec::new(); let mut hb = HashBuilder::default(); let receipts_len = receipts.len(); for i in 0..receipts_len { let index = adjust_index_for_rlp(i, receipts_len); index_buffer.clear(); index.encode(&mut index_buffer); value_buffer.clear(); receipts[index].encode_2718(&mut value_buffer); let is_private = false; // hardcode to false for legacy bench hb.add_leaf(Nibbles::unpack(&index_buffer), &value_buffer, is_private); } hb.root() } } use implementations::*;
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/trie/benches/hash_post_state.rs
crates/trie/trie/benches/hash_post_state.rs
#![allow(missing_docs, unreachable_pub)] use alloy_primitives::{keccak256, 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}; use revm_database::{states::BundleBuilder, BundleAccount}; use revm_state::FlaggedStorage; pub fn hash_post_state(c: &mut Criterion) { let mut group = c.benchmark_group("Hash Post State"); group.sample_size(20); for size in [100, 1_000, 3_000, 5_000, 10_000] { // Too slow. #[expect(unexpected_cfgs)] if cfg!(codspeed) && size > 1_000 { continue; } let state = generate_test_data(size); // sequence group.bench_function(BenchmarkId::new("sequence hashing", size), |b| { b.iter(|| from_bundle_state_seq(&state)) }); // parallel group.bench_function(BenchmarkId::new("parallel hashing", size), |b| { b.iter(|| HashedPostState::from_bundle_state::<KeccakKeyHasher>(&state)) }); } } fn from_bundle_state_seq(state: &HashMap<Address, BundleAccount>) -> HashedPostState { let mut this = HashedPostState::default(); for (address, account) in state { let hashed_address = keccak256(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)), ); this.storages.insert(hashed_address, hashed_storage); } this } fn generate_test_data(size: usize) -> HashMap<Address, BundleAccount> { let storage_size = 1_000; let mut runner = TestRunner::deterministic(); use proptest::collection::hash_map; let state = hash_map( any::<Address>(), hash_map( any::<U256>(), // slot ( any::<FlaggedStorage>(), // old value any::<FlaggedStorage>(), // new value ), storage_size, ), size, ) .new_tree(&mut runner) .unwrap() .current(); let mut bundle_builder = BundleBuilder::default(); for (address, storage) in state { bundle_builder = bundle_builder.state_storage(address, storage.into_iter().collect()); } let bundle_state = bundle_builder.build(); bundle_state.state } criterion_group!(post_state, hash_post_state); criterion_main!(post_state);
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/db/src/proof.rs
crates/trie/db/src/proof.rs
use crate::{DatabaseHashedCursorFactory, DatabaseTrieCursorFactory}; use alloy_primitives::{keccak256, map::HashMap, Address, B256}; use reth_db_api::transaction::DbTx; use reth_execution_errors::StateProofError; use reth_trie::{ hashed_cursor::HashedPostStateCursorFactory, proof::{Proof, StorageProof}, trie_cursor::InMemoryTrieCursorFactory, AccountProof, HashedPostStateSorted, HashedStorage, MultiProof, MultiProofTargets, StorageMultiProof, TrieInput, }; /// Extends [`Proof`] with operations specific for working with a database transaction. pub trait DatabaseProof<'a, TX> { /// Create a new [Proof] from database transaction. fn from_tx(tx: &'a TX) -> Self; /// Generates the state proof for target account based on [`TrieInput`]. fn overlay_account_proof( tx: &'a TX, input: TrieInput, address: Address, slots: &[B256], ) -> Result<AccountProof, StateProofError>; /// Generates the state [`MultiProof`] for target hashed account and storage keys. fn overlay_multiproof( tx: &'a TX, input: TrieInput, targets: MultiProofTargets, ) -> Result<MultiProof, StateProofError>; } impl<'a, TX: DbTx> DatabaseProof<'a, TX> for Proof<DatabaseTrieCursorFactory<'a, TX>, DatabaseHashedCursorFactory<'a, TX>> { /// Create a new [Proof] instance from database transaction. fn from_tx(tx: &'a TX) -> Self { Self::new(DatabaseTrieCursorFactory::new(tx), DatabaseHashedCursorFactory::new(tx)) } fn overlay_account_proof( tx: &'a TX, input: TrieInput, address: Address, slots: &[B256], ) -> Result<AccountProof, StateProofError> { let nodes_sorted = input.nodes.into_sorted(); let state_sorted = input.state.into_sorted(); Self::from_tx(tx) .with_trie_cursor_factory(InMemoryTrieCursorFactory::new( DatabaseTrieCursorFactory::new(tx), &nodes_sorted, )) .with_hashed_cursor_factory(HashedPostStateCursorFactory::new( DatabaseHashedCursorFactory::new(tx), &state_sorted, )) .with_prefix_sets_mut(input.prefix_sets) .account_proof(address, slots) } fn overlay_multiproof( tx: &'a TX, input: TrieInput, targets: MultiProofTargets, ) -> Result<MultiProof, StateProofError> { let nodes_sorted = input.nodes.into_sorted(); let state_sorted = input.state.into_sorted(); Self::from_tx(tx) .with_trie_cursor_factory(InMemoryTrieCursorFactory::new( DatabaseTrieCursorFactory::new(tx), &nodes_sorted, )) .with_hashed_cursor_factory(HashedPostStateCursorFactory::new( DatabaseHashedCursorFactory::new(tx), &state_sorted, )) .with_prefix_sets_mut(input.prefix_sets) .multiproof(targets) } } /// Extends [`StorageProof`] with operations specific for working with a database transaction. pub trait DatabaseStorageProof<'a, TX> { /// Create a new [`StorageProof`] from database transaction and account address. fn from_tx(tx: &'a TX, address: Address) -> Self; /// Generates the storage proof for target slot based on [`TrieInput`]. fn overlay_storage_proof( tx: &'a TX, address: Address, slot: B256, storage: HashedStorage, ) -> Result<reth_trie::StorageProof, StateProofError>; /// Generates the storage multiproof for target slots based on [`TrieInput`]. fn overlay_storage_multiproof( tx: &'a TX, address: Address, slots: &[B256], storage: HashedStorage, ) -> Result<StorageMultiProof, StateProofError>; } impl<'a, TX: DbTx> DatabaseStorageProof<'a, TX> for StorageProof<DatabaseTrieCursorFactory<'a, TX>, DatabaseHashedCursorFactory<'a, TX>> { fn from_tx(tx: &'a TX, address: Address) -> Self { Self::new(DatabaseTrieCursorFactory::new(tx), DatabaseHashedCursorFactory::new(tx), address) } fn overlay_storage_proof( tx: &'a TX, address: Address, slot: B256, storage: HashedStorage, ) -> Result<reth_trie::StorageProof, StateProofError> { let hashed_address = keccak256(address); let prefix_set = storage.construct_prefix_set(); let state_sorted = HashedPostStateSorted::new( Default::default(), HashMap::from_iter([(hashed_address, storage.into_sorted())]), ); Self::from_tx(tx, address) .with_hashed_cursor_factory(HashedPostStateCursorFactory::new( DatabaseHashedCursorFactory::new(tx), &state_sorted, )) .with_prefix_set_mut(prefix_set) .storage_proof(slot) } fn overlay_storage_multiproof( tx: &'a TX, address: Address, slots: &[B256], storage: HashedStorage, ) -> Result<StorageMultiProof, StateProofError> { let hashed_address = keccak256(address); let targets = slots.iter().map(keccak256).collect(); let prefix_set = storage.construct_prefix_set(); let state_sorted = HashedPostStateSorted::new( Default::default(), HashMap::from_iter([(hashed_address, storage.into_sorted())]), ); Self::from_tx(tx, address) .with_hashed_cursor_factory(HashedPostStateCursorFactory::new( DatabaseHashedCursorFactory::new(tx), &state_sorted, )) .with_prefix_set_mut(prefix_set) .storage_multiproof(targets) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/db/src/lib.rs
crates/trie/db/src/lib.rs
//! An integration of `reth-trie` with `reth-db`. #![cfg_attr(not(test), warn(unused_crate_dependencies))] mod hashed_cursor; mod prefix_set; mod proof; mod state; mod storage; mod trie_cursor; mod witness; pub use hashed_cursor::{ DatabaseHashedAccountCursor, DatabaseHashedCursorFactory, DatabaseHashedStorageCursor, }; pub use prefix_set::PrefixSetLoader; pub use proof::{DatabaseProof, DatabaseStorageProof}; pub use state::{DatabaseHashedPostState, DatabaseStateRoot}; pub use storage::{DatabaseHashedStorage, DatabaseStorageRoot}; pub use trie_cursor::{ DatabaseAccountTrieCursor, DatabaseStorageTrieCursor, DatabaseTrieCursorFactory, }; pub use witness::DatabaseTrieWitness;
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/db/src/hashed_cursor.rs
crates/trie/db/src/hashed_cursor.rs
use alloy_primitives::B256; use reth_db_api::{ cursor::{DbCursorRO, DbDupCursorRO}, tables, transaction::DbTx, DatabaseError, }; use reth_primitives_traits::Account; use reth_trie::hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor}; use revm_state::FlaggedStorage; /// A struct wrapping database transaction that implements [`HashedCursorFactory`]. #[derive(Debug)] pub struct DatabaseHashedCursorFactory<'a, TX>(&'a TX); impl<TX> Clone for DatabaseHashedCursorFactory<'_, TX> { fn clone(&self) -> Self { Self(self.0) } } impl<'a, TX> DatabaseHashedCursorFactory<'a, TX> { /// Create new database hashed cursor factory. pub const fn new(tx: &'a TX) -> Self { Self(tx) } } impl<TX: DbTx> HashedCursorFactory for DatabaseHashedCursorFactory<'_, TX> { type AccountCursor = DatabaseHashedAccountCursor<<TX as DbTx>::Cursor<tables::HashedAccounts>>; type StorageCursor = DatabaseHashedStorageCursor<<TX as DbTx>::DupCursor<tables::HashedStorages>>; fn hashed_account_cursor(&self) -> Result<Self::AccountCursor, DatabaseError> { Ok(DatabaseHashedAccountCursor(self.0.cursor_read::<tables::HashedAccounts>()?)) } fn hashed_storage_cursor( &self, hashed_address: B256, ) -> Result<Self::StorageCursor, DatabaseError> { Ok(DatabaseHashedStorageCursor::new( self.0.cursor_dup_read::<tables::HashedStorages>()?, hashed_address, )) } } /// A struct wrapping database cursor over hashed accounts implementing [`HashedCursor`] for /// iterating over accounts. #[derive(Debug)] pub struct DatabaseHashedAccountCursor<C>(C); impl<C> DatabaseHashedAccountCursor<C> { /// Create new database hashed account cursor. pub const fn new(cursor: C) -> Self { Self(cursor) } } impl<C> HashedCursor for DatabaseHashedAccountCursor<C> where C: DbCursorRO<tables::HashedAccounts>, { type Value = Account; fn seek(&mut self, key: B256) -> Result<Option<(B256, Self::Value)>, DatabaseError> { self.0.seek(key) } fn next(&mut self) -> Result<Option<(B256, Self::Value)>, DatabaseError> { self.0.next() } } /// The structure wrapping a database cursor for hashed storage and /// a target hashed address. Implements [`HashedCursor`] and [`HashedStorageCursor`] /// for iterating over hashed storage. #[derive(Debug)] pub struct DatabaseHashedStorageCursor<C> { /// Database hashed storage cursor. cursor: C, /// Target hashed address of the account that the storage belongs to. hashed_address: B256, } impl<C> DatabaseHashedStorageCursor<C> { /// Create new [`DatabaseHashedStorageCursor`]. pub const fn new(cursor: C, hashed_address: B256) -> Self { Self { cursor, hashed_address } } } impl<C> HashedCursor for DatabaseHashedStorageCursor<C> where C: DbCursorRO<tables::HashedStorages> + DbDupCursorRO<tables::HashedStorages>, { type Value = FlaggedStorage; fn seek(&mut self, subkey: B256) -> Result<Option<(B256, Self::Value)>, DatabaseError> { Ok(self.cursor.seek_by_key_subkey(self.hashed_address, subkey)?.map(|e| (e.key, e.into()))) } fn next(&mut self) -> Result<Option<(B256, Self::Value)>, DatabaseError> { Ok(self.cursor.next_dup_val()?.map(|e| (e.key, e.into()))) } } impl<C> HashedStorageCursor for DatabaseHashedStorageCursor<C> where C: DbCursorRO<tables::HashedStorages> + DbDupCursorRO<tables::HashedStorages>, { fn is_storage_empty(&mut self) -> Result<bool, DatabaseError> { Ok(self.cursor.seek_exact(self.hashed_address)?.is_none()) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/db/src/witness.rs
crates/trie/db/src/witness.rs
use crate::{DatabaseHashedCursorFactory, DatabaseTrieCursorFactory}; use alloy_primitives::{map::B256Map, Bytes}; use reth_db_api::transaction::DbTx; use reth_execution_errors::TrieWitnessError; use reth_trie::{ hashed_cursor::HashedPostStateCursorFactory, trie_cursor::InMemoryTrieCursorFactory, witness::TrieWitness, HashedPostState, TrieInput, }; /// Extends [`TrieWitness`] with operations specific for working with a database transaction. pub trait DatabaseTrieWitness<'a, TX> { /// Create a new [`TrieWitness`] from database transaction. fn from_tx(tx: &'a TX) -> Self; /// Generates trie witness for target state based on [`TrieInput`]. fn overlay_witness( tx: &'a TX, input: TrieInput, target: HashedPostState, ) -> Result<B256Map<Bytes>, TrieWitnessError>; } impl<'a, TX: DbTx> DatabaseTrieWitness<'a, TX> for TrieWitness<DatabaseTrieCursorFactory<'a, TX>, DatabaseHashedCursorFactory<'a, TX>> { fn from_tx(tx: &'a TX) -> Self { Self::new(DatabaseTrieCursorFactory::new(tx), DatabaseHashedCursorFactory::new(tx)) } fn overlay_witness( tx: &'a TX, input: TrieInput, target: HashedPostState, ) -> Result<B256Map<Bytes>, TrieWitnessError> { let nodes_sorted = input.nodes.into_sorted(); let state_sorted = input.state.into_sorted(); Self::from_tx(tx) .with_trie_cursor_factory(InMemoryTrieCursorFactory::new( DatabaseTrieCursorFactory::new(tx), &nodes_sorted, )) .with_hashed_cursor_factory(HashedPostStateCursorFactory::new( DatabaseHashedCursorFactory::new(tx), &state_sorted, )) .with_prefix_sets_mut(input.prefix_sets) .always_include_root_node() .compute(target) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/db/src/state.rs
crates/trie/db/src/state.rs
use crate::{DatabaseHashedCursorFactory, DatabaseTrieCursorFactory, PrefixSetLoader}; use alloy_primitives::{ map::{AddressMap, B256Map}, Address, BlockNumber, B256, }; use reth_db_api::{ cursor::DbCursorRO, models::{AccountBeforeTx, BlockNumberAddress}, tables, transaction::DbTx, DatabaseError, }; use reth_execution_errors::StateRootError; use reth_trie::{ hashed_cursor::HashedPostStateCursorFactory, trie_cursor::InMemoryTrieCursorFactory, updates::TrieUpdates, HashedPostState, HashedStorage, KeccakKeyHasher, KeyHasher, StateRoot, StateRootProgress, TrieInput, }; use revm::state::FlaggedStorage; use std::{collections::HashMap, ops::RangeInclusive}; use tracing::debug; /// Extends [`StateRoot`] with operations specific for working with a database transaction. pub trait DatabaseStateRoot<'a, TX>: Sized { /// Create a new [`StateRoot`] instance. fn from_tx(tx: &'a TX) -> Self; /// Given a block number range, identifies all the accounts and storage keys that /// have changed. /// /// # Returns /// /// An instance of state root calculator with account and storage prefixes loaded. fn incremental_root_calculator( tx: &'a TX, range: RangeInclusive<BlockNumber>, ) -> Result<Self, StateRootError>; /// Computes the state root of the trie with the changed account and storage prefixes and /// existing trie nodes. /// /// # Returns /// /// The updated state root. fn incremental_root( tx: &'a TX, range: RangeInclusive<BlockNumber>, ) -> Result<B256, StateRootError>; /// Computes the state root of the trie with the changed account and storage prefixes and /// existing trie nodes collecting updates in the process. /// /// Ignores the threshold. /// /// # Returns /// /// The updated state root and the trie updates. fn incremental_root_with_updates( tx: &'a TX, range: RangeInclusive<BlockNumber>, ) -> Result<(B256, TrieUpdates), StateRootError>; /// Computes the state root of the trie with the changed account and storage prefixes and /// existing trie nodes collecting updates in the process. /// /// # Returns /// /// The intermediate progress of state root computation. fn incremental_root_with_progress( tx: &'a TX, range: RangeInclusive<BlockNumber>, ) -> Result<StateRootProgress, StateRootError>; /// Calculate the state root for this [`HashedPostState`]. /// Internally, this method retrieves prefixsets and uses them /// to calculate incremental state root. /// /// # Example /// /// ``` /// use alloy_primitives::U256; /// use reth_db::test_utils::create_test_rw_db; /// use reth_db_api::database::Database; /// use reth_primitives_traits::Account; /// use reth_trie::{updates::TrieUpdates, HashedPostState, StateRoot}; /// use reth_trie_db::DatabaseStateRoot; /// /// // Initialize the database /// let db = create_test_rw_db(); /// /// // Initialize hashed post state /// let mut hashed_state = HashedPostState::default(); /// hashed_state.accounts.insert( /// [0x11; 32].into(), /// Some(Account { nonce: 1, balance: U256::from(10), bytecode_hash: None }), /// ); /// /// // Calculate the state root /// let tx = db.tx().expect("failed to create transaction"); /// let state_root = StateRoot::overlay_root(&tx, hashed_state); /// ``` /// /// # Returns /// /// The state root for this [`HashedPostState`]. fn overlay_root(tx: &'a TX, post_state: HashedPostState) -> Result<B256, StateRootError>; /// Calculates the state root for this [`HashedPostState`] and returns it alongside trie /// updates. See [`Self::overlay_root`] for more info. fn overlay_root_with_updates( tx: &'a TX, post_state: HashedPostState, ) -> Result<(B256, TrieUpdates), StateRootError>; /// Calculates the state root for provided [`HashedPostState`] using cached intermediate nodes. fn overlay_root_from_nodes(tx: &'a TX, input: TrieInput) -> Result<B256, StateRootError>; /// Calculates the state root and trie updates for provided [`HashedPostState`] using /// cached intermediate nodes. fn overlay_root_from_nodes_with_updates( tx: &'a TX, input: TrieInput, ) -> Result<(B256, TrieUpdates), StateRootError>; } /// Extends [`HashedPostState`] with operations specific for working with a database transaction. pub trait DatabaseHashedPostState<TX>: Sized { /// Initializes [`HashedPostState`] from reverts. Iterates over state reverts from the specified /// block up to the current tip and aggregates them into hashed state in reverse. fn from_reverts<KH: KeyHasher>(tx: &TX, from: BlockNumber) -> Result<Self, DatabaseError>; } impl<'a, TX: DbTx> DatabaseStateRoot<'a, TX> for StateRoot<DatabaseTrieCursorFactory<'a, TX>, DatabaseHashedCursorFactory<'a, TX>> { fn from_tx(tx: &'a TX) -> Self { Self::new(DatabaseTrieCursorFactory::new(tx), DatabaseHashedCursorFactory::new(tx)) } fn incremental_root_calculator( tx: &'a TX, range: RangeInclusive<BlockNumber>, ) -> Result<Self, StateRootError> { let loaded_prefix_sets = PrefixSetLoader::<_, KeccakKeyHasher>::new(tx).load(range)?; Ok(Self::from_tx(tx).with_prefix_sets(loaded_prefix_sets)) } fn incremental_root( tx: &'a TX, range: RangeInclusive<BlockNumber>, ) -> Result<B256, StateRootError> { debug!(target: "trie::loader", ?range, "incremental state root"); Self::incremental_root_calculator(tx, range)?.root() } fn incremental_root_with_updates( tx: &'a TX, range: RangeInclusive<BlockNumber>, ) -> Result<(B256, TrieUpdates), StateRootError> { debug!(target: "trie::loader", ?range, "incremental state root"); Self::incremental_root_calculator(tx, range)?.root_with_updates() } fn incremental_root_with_progress( tx: &'a TX, range: RangeInclusive<BlockNumber>, ) -> Result<StateRootProgress, StateRootError> { debug!(target: "trie::loader", ?range, "incremental state root with progress"); Self::incremental_root_calculator(tx, range)?.root_with_progress() } fn overlay_root(tx: &'a TX, post_state: HashedPostState) -> Result<B256, StateRootError> { let prefix_sets = post_state.construct_prefix_sets().freeze(); let state_sorted = post_state.into_sorted(); StateRoot::new( DatabaseTrieCursorFactory::new(tx), HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(tx), &state_sorted), ) .with_prefix_sets(prefix_sets) .root() } fn overlay_root_with_updates( tx: &'a TX, post_state: HashedPostState, ) -> Result<(B256, TrieUpdates), StateRootError> { let prefix_sets = post_state.construct_prefix_sets().freeze(); let state_sorted = post_state.into_sorted(); StateRoot::new( DatabaseTrieCursorFactory::new(tx), HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(tx), &state_sorted), ) .with_prefix_sets(prefix_sets) .root_with_updates() } fn overlay_root_from_nodes(tx: &'a TX, input: TrieInput) -> Result<B256, StateRootError> { let state_sorted = input.state.into_sorted(); let nodes_sorted = input.nodes.into_sorted(); StateRoot::new( InMemoryTrieCursorFactory::new(DatabaseTrieCursorFactory::new(tx), &nodes_sorted), HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(tx), &state_sorted), ) .with_prefix_sets(input.prefix_sets.freeze()) .root() } fn overlay_root_from_nodes_with_updates( tx: &'a TX, input: TrieInput, ) -> Result<(B256, TrieUpdates), StateRootError> { let state_sorted = input.state.into_sorted(); let nodes_sorted = input.nodes.into_sorted(); StateRoot::new( InMemoryTrieCursorFactory::new(DatabaseTrieCursorFactory::new(tx), &nodes_sorted), HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(tx), &state_sorted), ) .with_prefix_sets(input.prefix_sets.freeze()) .root_with_updates() } } impl<TX: DbTx> DatabaseHashedPostState<TX> for HashedPostState { fn from_reverts<KH: KeyHasher>(tx: &TX, from: BlockNumber) -> Result<Self, DatabaseError> { // Iterate over account changesets and record value before first occurring account change. let mut accounts = HashMap::new(); let mut account_changesets_cursor = tx.cursor_read::<tables::AccountChangeSets>()?; for entry in account_changesets_cursor.walk_range(from..)? { let (_, AccountBeforeTx { address, info }) = entry?; accounts.entry(address).or_insert(info); } // Iterate over storage changesets and record value before first occurring storage change. let mut storages = AddressMap::<B256Map<FlaggedStorage>>::default(); let mut storage_changesets_cursor = tx.cursor_read::<tables::StorageChangeSets>()?; for entry in storage_changesets_cursor.walk_range(BlockNumberAddress((from, Address::ZERO))..)? { let (BlockNumberAddress((_, address)), storage) = entry?; let account_storage = storages.entry(address).or_default(); account_storage.entry(storage.key).or_insert(storage.into()); } let hashed_accounts = accounts.into_iter().map(|(address, info)| (KH::hash_key(address), info)).collect(); let hashed_storages = storages .into_iter() .map(|(address, storage)| { ( KH::hash_key(address), HashedStorage::from_iter( // The `wiped` flag indicates only whether previous storage entries // should be looked up in db or not. For reverts it's a noop since all // wiped changes had been written as storage reverts. false, storage.into_iter().map(|(slot, value)| (KH::hash_key(slot), value)), ), ) }) .collect(); Ok(Self { accounts: hashed_accounts, storages: hashed_storages }) } } #[cfg(test)] mod tests { use super::*; use alloy_primitives::{hex, map::HashMap, Address, U256}; use reth_db::test_utils::create_test_rw_db; use reth_db_api::database::Database; use reth_trie::KeccakKeyHasher; use revm::state::AccountInfo; use revm_database::BundleState; #[test] fn from_bundle_state_with_rayon() { let address1 = Address::with_last_byte(1); let address2 = Address::with_last_byte(2); let slot1 = U256::from(1015); let slot2 = U256::from(2015); let account1 = AccountInfo { nonce: 1, ..Default::default() }; let account2 = AccountInfo { nonce: 2, ..Default::default() }; let bundle_state = BundleState::builder(2..=2) .state_present_account_info(address1, account1) .state_present_account_info(address2, account2) .state_storage( address1, HashMap::from_iter([( slot1, (FlaggedStorage::ZERO, FlaggedStorage::new_from_value(10)), )]), ) .state_storage( address2, HashMap::from_iter([( slot2, (FlaggedStorage::ZERO, FlaggedStorage::new_from_value(20)), )]), ) .build(); assert_eq!(bundle_state.reverts.len(), 1); let post_state = HashedPostState::from_bundle_state::<KeccakKeyHasher>(&bundle_state.state); assert_eq!(post_state.accounts.len(), 2); assert_eq!(post_state.storages.len(), 2); let db = create_test_rw_db(); let tx = db.tx().expect("failed to create transaction"); assert_eq!( StateRoot::overlay_root(&tx, post_state).unwrap(), // If we had the same state root calculation as ethereum when all values are public: /* hex!("b464525710cafcf5d4044ac85b72c08b1e76231b8d91f288fe438cc41d8eaafd") */ hex!("64f7822621afd8a66d71e233b48e945c101ab97334e19398422f22c3fae72223") ); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/db/src/storage.rs
crates/trie/db/src/storage.rs
use crate::{DatabaseHashedCursorFactory, DatabaseTrieCursorFactory}; use alloy_primitives::{keccak256, map::hash_map, Address, BlockNumber, B256}; use reth_db_api::{ cursor::DbCursorRO, models::BlockNumberAddress, tables, transaction::DbTx, DatabaseError, }; use reth_execution_errors::StorageRootError; use reth_trie::{ hashed_cursor::HashedPostStateCursorFactory, HashedPostState, HashedStorage, StorageRoot, }; #[cfg(feature = "metrics")] use reth_trie::metrics::TrieRootMetrics; /// Extends [`StorageRoot`] with operations specific for working with a database transaction. pub trait DatabaseStorageRoot<'a, TX> { /// Create a new storage root calculator from database transaction and raw address. fn from_tx(tx: &'a TX, address: Address) -> Self; /// Create a new storage root calculator from database transaction and hashed address. fn from_tx_hashed(tx: &'a TX, hashed_address: B256) -> Self; /// Calculates the storage root for this [`HashedStorage`] and returns it. fn overlay_root( tx: &'a TX, address: Address, hashed_storage: HashedStorage, ) -> Result<B256, StorageRootError>; } /// Extends [`HashedStorage`] with operations specific for working with a database transaction. pub trait DatabaseHashedStorage<TX>: Sized { /// Initializes [`HashedStorage`] from reverts. Iterates over storage reverts from the specified /// block up to the current tip and aggregates them into hashed storage in reverse. fn from_reverts(tx: &TX, address: Address, from: BlockNumber) -> Result<Self, DatabaseError>; } impl<'a, TX: DbTx> DatabaseStorageRoot<'a, TX> for StorageRoot<DatabaseTrieCursorFactory<'a, TX>, DatabaseHashedCursorFactory<'a, TX>> { fn from_tx(tx: &'a TX, address: Address) -> Self { Self::new( DatabaseTrieCursorFactory::new(tx), DatabaseHashedCursorFactory::new(tx), address, Default::default(), #[cfg(feature = "metrics")] TrieRootMetrics::new(reth_trie::TrieType::Storage), ) } fn from_tx_hashed(tx: &'a TX, hashed_address: B256) -> Self { Self::new_hashed( DatabaseTrieCursorFactory::new(tx), DatabaseHashedCursorFactory::new(tx), hashed_address, Default::default(), #[cfg(feature = "metrics")] TrieRootMetrics::new(reth_trie::TrieType::Storage), ) } fn overlay_root( tx: &'a TX, address: Address, hashed_storage: HashedStorage, ) -> Result<B256, StorageRootError> { let prefix_set = hashed_storage.construct_prefix_set().freeze(); let state_sorted = HashedPostState::from_hashed_storage(keccak256(address), hashed_storage).into_sorted(); StorageRoot::new( DatabaseTrieCursorFactory::new(tx), HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(tx), &state_sorted), address, prefix_set, #[cfg(feature = "metrics")] TrieRootMetrics::new(reth_trie::TrieType::Storage), ) .root() } } impl<TX: DbTx> DatabaseHashedStorage<TX> for HashedStorage { fn from_reverts(tx: &TX, address: Address, from: BlockNumber) -> Result<Self, DatabaseError> { let mut storage = Self::new(false); let mut storage_changesets_cursor = tx.cursor_read::<tables::StorageChangeSets>()?; 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); if let hash_map::Entry::Vacant(entry) = storage.storage.entry(hashed_slot) { entry.insert(storage_change.into()); } } } Ok(storage) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/db/src/prefix_set.rs
crates/trie/db/src/prefix_set.rs
use alloy_primitives::{ map::{HashMap, HashSet}, BlockNumber, B256, }; use core::{ marker::PhantomData, ops::{Deref, RangeInclusive}, }; use reth_db_api::{ cursor::DbCursorRO, models::{AccountBeforeTx, BlockNumberAddress}, tables, transaction::DbTx, DatabaseError, }; use reth_primitives_traits::StorageEntry; use reth_trie::{ prefix_set::{PrefixSetMut, TriePrefixSets}, KeyHasher, Nibbles, }; /// A wrapper around a database transaction that loads prefix sets within a given block range. #[derive(Debug)] pub struct PrefixSetLoader<'a, TX, KH>(&'a TX, PhantomData<KH>); impl<'a, TX, KH> PrefixSetLoader<'a, TX, KH> { /// Create a new loader. pub const fn new(tx: &'a TX) -> Self { Self(tx, PhantomData) } } impl<TX, KH> Deref for PrefixSetLoader<'_, TX, KH> { type Target = TX; fn deref(&self) -> &Self::Target { self.0 } } impl<TX: DbTx, KH: KeyHasher> PrefixSetLoader<'_, TX, KH> { /// Load all account and storage changes for the given block range. pub fn load(self, range: RangeInclusive<BlockNumber>) -> Result<TriePrefixSets, DatabaseError> { // Initialize prefix sets. let mut account_prefix_set = PrefixSetMut::default(); let mut storage_prefix_sets = HashMap::<B256, PrefixSetMut>::default(); let mut destroyed_accounts = HashSet::default(); // Walk account changeset and insert account prefixes. let mut account_changeset_cursor = self.cursor_read::<tables::AccountChangeSets>()?; let mut account_hashed_state_cursor = self.cursor_read::<tables::HashedAccounts>()?; for account_entry in account_changeset_cursor.walk_range(range.clone())? { let (_, AccountBeforeTx { address, .. }) = account_entry?; let hashed_address = KH::hash_key(address); account_prefix_set.insert(Nibbles::unpack(hashed_address)); if account_hashed_state_cursor.seek_exact(hashed_address)?.is_none() { destroyed_accounts.insert(hashed_address); } } // Walk storage changeset and insert storage prefixes as well as account prefixes if missing // from the account prefix set. let mut storage_cursor = self.cursor_dup_read::<tables::StorageChangeSets>()?; let storage_range = BlockNumberAddress::range(range); for storage_entry in storage_cursor.walk_range(storage_range)? { let (BlockNumberAddress((_, address)), StorageEntry { key, .. }) = storage_entry?; let hashed_address = KH::hash_key(address); account_prefix_set.insert(Nibbles::unpack(hashed_address)); storage_prefix_sets .entry(hashed_address) .or_default() .insert(Nibbles::unpack(KH::hash_key(key))); } Ok(TriePrefixSets { account_prefix_set: account_prefix_set.freeze(), storage_prefix_sets: storage_prefix_sets .into_iter() .map(|(k, v)| (k, v.freeze())) .collect(), destroyed_accounts, }) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/db/src/trie_cursor.rs
crates/trie/db/src/trie_cursor.rs
use alloy_primitives::B256; use reth_db_api::{ cursor::{DbCursorRO, DbCursorRW, DbDupCursorRO, DbDupCursorRW}, tables, transaction::DbTx, DatabaseError, }; use reth_trie::{ trie_cursor::{TrieCursor, TrieCursorFactory}, updates::StorageTrieUpdates, BranchNodeCompact, Nibbles, StorageTrieEntry, StoredNibbles, StoredNibblesSubKey, }; /// Wrapper struct for database transaction implementing trie cursor factory trait. #[derive(Debug)] pub struct DatabaseTrieCursorFactory<'a, TX>(&'a TX); impl<TX> Clone for DatabaseTrieCursorFactory<'_, TX> { fn clone(&self) -> Self { Self(self.0) } } impl<'a, TX> DatabaseTrieCursorFactory<'a, TX> { /// Create new [`DatabaseTrieCursorFactory`]. pub const fn new(tx: &'a TX) -> Self { Self(tx) } } /// Implementation of the trie cursor factory for a database transaction. impl<TX: DbTx> TrieCursorFactory for DatabaseTrieCursorFactory<'_, TX> { type AccountTrieCursor = DatabaseAccountTrieCursor<<TX as DbTx>::Cursor<tables::AccountsTrie>>; type StorageTrieCursor = DatabaseStorageTrieCursor<<TX as DbTx>::DupCursor<tables::StoragesTrie>>; fn account_trie_cursor(&self) -> Result<Self::AccountTrieCursor, DatabaseError> { Ok(DatabaseAccountTrieCursor::new(self.0.cursor_read::<tables::AccountsTrie>()?)) } fn storage_trie_cursor( &self, hashed_address: B256, ) -> Result<Self::StorageTrieCursor, DatabaseError> { Ok(DatabaseStorageTrieCursor::new( self.0.cursor_dup_read::<tables::StoragesTrie>()?, hashed_address, )) } } /// A cursor over the account trie. #[derive(Debug)] pub struct DatabaseAccountTrieCursor<C>(pub(crate) C); impl<C> DatabaseAccountTrieCursor<C> { /// Create a new account trie cursor. pub const fn new(cursor: C) -> Self { Self(cursor) } } impl<C> TrieCursor for DatabaseAccountTrieCursor<C> where C: DbCursorRO<tables::AccountsTrie> + Send + Sync, { /// Seeks an exact match for the provided key in the account trie. fn seek_exact( &mut self, key: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { Ok(self.0.seek_exact(StoredNibbles(key))?.map(|value| (value.0 .0, value.1))) } /// Seeks a key in the account trie that matches or is greater than the provided key. fn seek( &mut self, key: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { Ok(self.0.seek(StoredNibbles(key))?.map(|value| (value.0 .0, value.1))) } /// Move the cursor to the next entry and return it. fn next(&mut self) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { Ok(self.0.next()?.map(|value| (value.0 .0, value.1))) } /// Retrieves the current key in the cursor. fn current(&mut self) -> Result<Option<Nibbles>, DatabaseError> { Ok(self.0.current()?.map(|(k, _)| k.0)) } } /// A cursor over the storage tries stored in the database. #[derive(Debug)] pub struct DatabaseStorageTrieCursor<C> { /// The underlying cursor. pub cursor: C, /// Hashed address used for cursor positioning. hashed_address: B256, } impl<C> DatabaseStorageTrieCursor<C> { /// Create a new storage trie cursor. pub const fn new(cursor: C, hashed_address: B256) -> Self { Self { cursor, hashed_address } } } impl<C> DatabaseStorageTrieCursor<C> where C: DbCursorRO<tables::StoragesTrie> + DbCursorRW<tables::StoragesTrie> + DbDupCursorRO<tables::StoragesTrie> + DbDupCursorRW<tables::StoragesTrie>, { /// Writes storage updates pub fn write_storage_trie_updates( &mut self, updates: &StorageTrieUpdates, ) -> Result<usize, DatabaseError> { // The storage trie for this account has to be deleted. if updates.is_deleted() && self.cursor.seek_exact(self.hashed_address)?.is_some() { self.cursor.delete_current_duplicates()?; } // Merge updated and removed nodes. Updated nodes must take precedence. let mut storage_updates = updates .removed_nodes_ref() .iter() .filter_map(|n| (!updates.storage_nodes_ref().contains_key(n)).then_some((n, None))) .collect::<Vec<_>>(); storage_updates.extend( updates.storage_nodes_ref().iter().map(|(nibbles, node)| (nibbles, Some(node))), ); // Sort trie node updates. storage_updates.sort_unstable_by(|a, b| a.0.cmp(b.0)); let mut num_entries = 0; for (nibbles, maybe_updated) in storage_updates.into_iter().filter(|(n, _)| !n.is_empty()) { num_entries += 1; let nibbles = StoredNibblesSubKey(*nibbles); // Delete the old entry if it exists. if self .cursor .seek_by_key_subkey(self.hashed_address, nibbles.clone())? .filter(|e| e.nibbles == nibbles) .is_some() { self.cursor.delete_current()?; } // There is an updated version of this node, insert new entry. if let Some(node) = maybe_updated { self.cursor.upsert( self.hashed_address, &StorageTrieEntry { nibbles, node: node.clone() }, )?; } } Ok(num_entries) } } impl<C> TrieCursor for DatabaseStorageTrieCursor<C> where C: DbCursorRO<tables::StoragesTrie> + DbDupCursorRO<tables::StoragesTrie> + Send + Sync, { /// Seeks an exact match for the given key in the storage trie. fn seek_exact( &mut self, key: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { Ok(self .cursor .seek_by_key_subkey(self.hashed_address, StoredNibblesSubKey(key))? .filter(|e| e.nibbles == StoredNibblesSubKey(key)) .map(|value| (value.nibbles.0, value.node))) } /// Seeks the given key in the storage trie. fn seek( &mut self, key: Nibbles, ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { Ok(self .cursor .seek_by_key_subkey(self.hashed_address, StoredNibblesSubKey(key))? .map(|value| (value.nibbles.0, value.node))) } /// Move the cursor to the next entry and return it. fn next(&mut self) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> { Ok(self.cursor.next_dup()?.map(|(_, v)| (v.nibbles.0, v.node))) } /// Retrieves the current value in the storage trie cursor. fn current(&mut self) -> Result<Option<Nibbles>, DatabaseError> { Ok(self.cursor.current()?.map(|(_, v)| v.nibbles.0)) } } #[cfg(test)] mod tests { use super::*; use alloy_primitives::hex_literal::hex; use reth_db_api::{cursor::DbCursorRW, transaction::DbTxMut}; use reth_provider::test_utils::create_test_provider_factory; #[test] fn test_account_trie_order() { let factory = create_test_provider_factory(); let provider = factory.provider_rw().unwrap(); let mut cursor = provider.tx_ref().cursor_write::<tables::AccountsTrie>().unwrap(); let data = vec![ hex!("0303040e").to_vec(), hex!("030305").to_vec(), hex!("03030500").to_vec(), hex!("0303050a").to_vec(), ]; for key in data.clone() { cursor .upsert( key.into(), &BranchNodeCompact::new( 0b0000_0010_0000_0001, 0b0000_0010_0000_0001, 0, Vec::default(), None, ), ) .unwrap(); } let db_data = cursor.walk_range(..).unwrap().collect::<Result<Vec<_>, _>>().unwrap(); assert_eq!(db_data[0].0 .0.to_vec(), data[0]); assert_eq!(db_data[1].0 .0.to_vec(), data[1]); assert_eq!(db_data[2].0 .0.to_vec(), data[2]); assert_eq!(db_data[3].0 .0.to_vec(), data[3]); assert_eq!( cursor.seek(hex!("0303040f").to_vec().into()).unwrap().map(|(k, _)| k.0.to_vec()), Some(data[1].clone()) ); } // tests that upsert and seek match on the storage trie cursor #[test] fn test_storage_cursor_abstraction() { let factory = create_test_provider_factory(); let provider = factory.provider_rw().unwrap(); let mut cursor = provider.tx_ref().cursor_dup_write::<tables::StoragesTrie>().unwrap(); let hashed_address = B256::random(); let key = StoredNibblesSubKey::from(vec![0x2, 0x3]); let value = BranchNodeCompact::new(1, 1, 1, vec![B256::random()], None); cursor .upsert(hashed_address, &StorageTrieEntry { nibbles: key.clone(), node: value.clone() }) .unwrap(); let mut cursor = DatabaseStorageTrieCursor::new(cursor, hashed_address); assert_eq!(cursor.seek(key.into()).unwrap().unwrap().1, value); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/db/tests/proof.rs
crates/trie/db/tests/proof.rs
#![allow(missing_docs)] use alloy_consensus::EMPTY_ROOT_HASH; use alloy_primitives::{address, b256, keccak256, Address, Bytes, B256, U256}; use alloy_rlp::EMPTY_STRING_CODE; use reth_chainspec::{Chain, ChainSpec, HOLESKY, MAINNET}; use reth_primitives_traits::Account; use reth_provider::test_utils::{create_test_provider_factory, insert_genesis}; use reth_trie::{proof::Proof, AccountProof, Nibbles, StorageProof}; use reth_trie_db::DatabaseProof; use std::{ str::FromStr, sync::{Arc, LazyLock}, }; /* World State (sampled from <https://ethereum.stackexchange.com/questions/268/ethereum-block-architecture/6413#6413>) | address | prefix | hash | balance |--------------------------------------------|-----------|--------------------------------------------------------------------|-------- | 0x2031f89b3ea8014eb51a78c316e42af3e0d7695f | 0xa711355 | 0xa711355ec1c8f7e26bb3ccbcb0b75d870d15846c0b98e5cc452db46c37faea40 | 45 eth | 0x33f0fc440b8477fcfbe9d0bf8649e7dea9baedb2 | 0xa77d337 | 0xa77d337781e762f3577784bab7491fcc43e291ce5a356b9bc517ac52eed3a37a | 1 wei | 0x62b0dd4aab2b1a0a04e279e2b828791a10755528 | 0xa7f9365 | 0xa7f936599f93b769acf90c7178fd2ddcac1b5b4bc9949ee5a04b7e0823c2446e | 1.1 eth | 0x1ed9b1dd266b607ee278726d324b855a093394a6 | 0xa77d397 | 0xa77d397a32b8ab5eb4b043c65b1f00c93f517bc8883c5cd31baf8e8a279475e3 | .12 eth All expected testspec results were obtained from querying proof RPC on the running geth instance `geth init crates/trie/testdata/proof-genesis.json && geth --http`. */ static TEST_SPEC: LazyLock<Arc<ChainSpec>> = LazyLock::new(|| { ChainSpec { chain: Chain::from_id(12345), genesis: serde_json::from_str(include_str!("../../trie/testdata/proof-genesis.json")) .expect("Can't deserialize test genesis json"), ..Default::default() } .into() }); fn convert_to_proof<'a>(path: impl IntoIterator<Item = &'a str>) -> Vec<Bytes> { path.into_iter().map(Bytes::from_str).collect::<Result<Vec<_>, _>>().unwrap() } #[test] fn testspec_proofs() { // Create test database and insert genesis accounts. let factory = create_test_provider_factory(); let root = insert_genesis(&factory, TEST_SPEC.clone()).unwrap(); let data = Vec::from([ ( "0x2031f89b3ea8014eb51a78c316e42af3e0d7695f", convert_to_proof([ "0xe48200a7a040f916999be583c572cc4dd369ec53b0a99f7de95f13880cf203d98f935ed1b3", "0xf87180a04fb9bab4bb88c062f32452b7c94c8f64d07b5851d44a39f1e32ba4b1829fdbfb8080808080a0b61eeb2eb82808b73c4ad14140a2836689f4ab8445d69dd40554eaf1fce34bc080808080808080a0dea230ff2026e65de419288183a340125b04b8405cc61627b3b4137e2260a1e880", "0xf8719f31355ec1c8f7e26bb3ccbcb0b75d870d15846c0b98e5cc452db46c37faea40b84ff84d80890270801d946c940000a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", ]), ), ( "0x33f0fc440b8477fcfbe9d0bf8649e7dea9baedb2", convert_to_proof([ "0xe48200a7a040f916999be583c572cc4dd369ec53b0a99f7de95f13880cf203d98f935ed1b3", "0xf87180a04fb9bab4bb88c062f32452b7c94c8f64d07b5851d44a39f1e32ba4b1829fdbfb8080808080a0b61eeb2eb82808b73c4ad14140a2836689f4ab8445d69dd40554eaf1fce34bc080808080808080a0dea230ff2026e65de419288183a340125b04b8405cc61627b3b4137e2260a1e880", "0xe48200d3a0ef957210bca5b9b402d614eb8408c88cfbf4913eb6ab83ca233c8b8f0e626b54", "0xf851808080a02743a5addaf4cf9b8c0c073e1eaa555deaaf8c41cb2b41958e88624fa45c2d908080808080a0bfbf6937911dfb88113fecdaa6bde822e4e99dae62489fcf61a91cb2f36793d680808080808080", "0xf8679e207781e762f3577784bab7491fcc43e291ce5a356b9bc517ac52eed3a37ab846f8448001a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", ]), ), ( "0x62b0dd4aab2b1a0a04e279e2b828791a10755528", convert_to_proof([ "0xe48200a7a040f916999be583c572cc4dd369ec53b0a99f7de95f13880cf203d98f935ed1b3", "0xf87180a04fb9bab4bb88c062f32452b7c94c8f64d07b5851d44a39f1e32ba4b1829fdbfb8080808080a0b61eeb2eb82808b73c4ad14140a2836689f4ab8445d69dd40554eaf1fce34bc080808080808080a0dea230ff2026e65de419288183a340125b04b8405cc61627b3b4137e2260a1e880", "0xf8709f3936599f93b769acf90c7178fd2ddcac1b5b4bc9949ee5a04b7e0823c2446eb84ef84c80880f43fc2c04ee0000a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", ]), ), ( "0x1ed9b1dd266b607ee278726d324b855a093394a6", convert_to_proof([ "0xe48200a7a040f916999be583c572cc4dd369ec53b0a99f7de95f13880cf203d98f935ed1b3", "0xf87180a04fb9bab4bb88c062f32452b7c94c8f64d07b5851d44a39f1e32ba4b1829fdbfb8080808080a0b61eeb2eb82808b73c4ad14140a2836689f4ab8445d69dd40554eaf1fce34bc080808080808080a0dea230ff2026e65de419288183a340125b04b8405cc61627b3b4137e2260a1e880", "0xe48200d3a0ef957210bca5b9b402d614eb8408c88cfbf4913eb6ab83ca233c8b8f0e626b54", "0xf851808080a02743a5addaf4cf9b8c0c073e1eaa555deaaf8c41cb2b41958e88624fa45c2d908080808080a0bfbf6937911dfb88113fecdaa6bde822e4e99dae62489fcf61a91cb2f36793d680808080808080", "0xf86f9e207a32b8ab5eb4b043c65b1f00c93f517bc8883c5cd31baf8e8a279475e3b84ef84c808801aa535d3d0c0000a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", ]), ), ]); let provider = factory.provider().unwrap(); for (target, expected_proof) in data { let target = Address::from_str(target).unwrap(); let account_proof = Proof::from_tx(provider.tx_ref()).account_proof(target, &[]).unwrap(); similar_asserts::assert_eq!( account_proof.proof, expected_proof, "proof for {target:?} does not match" ); assert_eq!(account_proof.verify(root), Ok(())); } } #[test] fn testspec_empty_storage_proof() { // Create test database and insert genesis accounts. let factory = create_test_provider_factory(); let root = insert_genesis(&factory, TEST_SPEC.clone()).unwrap(); let target = address!("0x1ed9b1dd266b607ee278726d324b855a093394a6"); let slots = Vec::from([B256::with_last_byte(1), B256::with_last_byte(3)]); let provider = factory.provider().unwrap(); let account_proof = Proof::from_tx(provider.tx_ref()).account_proof(target, &slots).unwrap(); assert_eq!(account_proof.storage_root, EMPTY_ROOT_HASH, "expected empty storage root"); assert_eq!(slots.len(), account_proof.storage_proofs.len()); for (idx, slot) in slots.into_iter().enumerate() { let proof = account_proof.storage_proofs.get(idx).unwrap(); assert_eq!( proof, &StorageProof::new(slot).with_proof(vec![Bytes::from([EMPTY_STRING_CODE])]) ); assert_eq!(proof.verify(account_proof.storage_root), Ok(())); } assert_eq!(account_proof.verify(root), Ok(())); } #[test] fn mainnet_genesis_account_proof() { // Create test database and insert genesis accounts. let factory = create_test_provider_factory(); let root = insert_genesis(&factory, MAINNET.clone()).unwrap(); // Address from mainnet genesis allocation. // keccak256 - `0xcf67b71c90b0d523dd5004cf206f325748da347685071b34812e21801f5270c4` let target = address!("0x000d836201318ec6899a67540690382780743280"); // `cast proof 0x000d836201318ec6899a67540690382780743280 --block 0` let expected_account_proof = convert_to_proof([ "0xf90211a090dcaf88c40c7bbc95a912cbdde67c175767b31173df9ee4b0d733bfdd511c43a0babe369f6b12092f49181ae04ca173fb68d1a5456f18d20fa32cba73954052bda0473ecf8a7e36a829e75039a3b055e51b8332cbf03324ab4af2066bbd6fbf0021a0bbda34753d7aa6c38e603f360244e8f59611921d9e1f128372fec0d586d4f9e0a04e44caecff45c9891f74f6a2156735886eedf6f1a733628ebc802ec79d844648a0a5f3f2f7542148c973977c8a1e154c4300fec92f755f7846f1b734d3ab1d90e7a0e823850f50bf72baae9d1733a36a444ab65d0a6faaba404f0583ce0ca4dad92da0f7a00cbe7d4b30b11faea3ae61b7f1f2b315b61d9f6bd68bfe587ad0eeceb721a07117ef9fc932f1a88e908eaead8565c19b5645dc9e5b1b6e841c5edbdfd71681a069eb2de283f32c11f859d7bcf93da23990d3e662935ed4d6b39ce3673ec84472a0203d26456312bbc4da5cd293b75b840fc5045e493d6f904d180823ec22bfed8ea09287b5c21f2254af4e64fca76acc5cd87399c7f1ede818db4326c98ce2dc2208a06fc2d754e304c48ce6a517753c62b1a9c1d5925b89707486d7fc08919e0a94eca07b1c54f15e299bd58bdfef9741538c7828b5d7d11a489f9c20d052b3471df475a051f9dd3739a927c89e357580a4c97b40234aa01ed3d5e0390dc982a7975880a0a089d613f26159af43616fd9455bb461f4869bfede26f2130835ed067a8b967bfb80", "0xf90211a0dae48f5b47930c28bb116fbd55e52cd47242c71bf55373b55eb2805ee2e4a929a00f1f37f337ec800e2e5974e2e7355f10f1a4832b39b846d916c3597a460e0676a0da8f627bb8fbeead17b318e0a8e4f528db310f591bb6ab2deda4a9f7ca902ab5a0971c662648d58295d0d0aa4b8055588da0037619951217c22052802549d94a2fa0ccc701efe4b3413fd6a61a6c9f40e955af774649a8d9fd212d046a5a39ddbb67a0d607cdb32e2bd635ee7f2f9e07bc94ddbd09b10ec0901b66628e15667aec570ba05b89203dc940e6fa70ec19ad4e01d01849d3a5baa0a8f9c0525256ed490b159fa0b84227d48df68aecc772939a59afa9e1a4ab578f7b698bdb1289e29b6044668ea0fd1c992070b94ace57e48cbf6511a16aa770c645f9f5efba87bbe59d0a042913a0e16a7ccea6748ae90de92f8aef3b3dc248a557b9ac4e296934313f24f7fced5fa042373cf4a00630d94de90d0a23b8f38ced6b0f7cb818b8925fee8f0c2a28a25aa05f89d2161c1741ff428864f7889866484cef622de5023a46e795dfdec336319fa07597a017664526c8c795ce1da27b8b72455c49657113e0455552dbc068c5ba31a0d5be9089012fda2c585a1b961e988ea5efcd3a06988e150a8682091f694b37c5a0f7b0352e38c315b2d9a14d51baea4ddee1770974c806e209355233c3c89dce6ea049bf6e8df0acafd0eff86defeeb305568e44d52d2235cf340ae15c6034e2b24180", "0xf901f1a0cf67e0f5d5f8d70e53a6278056a14ddca46846f5ef69c7bde6810d058d4a9eda80a06732ada65afd192197fe7ce57792a7f25d26978e64e954b7b84a1f7857ac279da05439f8d011683a6fc07efb90afca198fd7270c795c835c7c85d91402cda992eaa0449b93033b6152d289045fdb0bf3f44926f831566faa0e616b7be1abaad2cb2da031be6c3752bcd7afb99b1bb102baf200f8567c394d464315323a363697646616a0a40e3ed11d906749aa501279392ffde868bd35102db41364d9c601fd651f974aa0044bfa4fe8dd1a58e6c7144da79326e94d1331c0b00373f6ae7f3662f45534b7a098005e3e48db68cb1dc9b9f034ff74d2392028ddf718b0f2084133017da2c2e7a02a62bc40414ee95b02e202a9e89babbabd24bef0abc3fc6dcd3e9144ceb0b725a0239facd895bbf092830390a8676f34b35b29792ae561f196f86614e0448a5792a0a4080f88925daff6b4ce26d188428841bd65655d8e93509f2106020e76d41eefa04918987904be42a6894256ca60203283d1b89139cf21f09f5719c44b8cdbb8f7a06201fc3ef0827e594d953b5e3165520af4fceb719e11cc95fd8d3481519bfd8ca05d0e353d596bd725b09de49c01ede0f29023f0153d7b6d401556aeb525b2959ba0cd367d0679950e9c5f2aa4298fd4b081ade2ea429d71ff390c50f8520e16e30880", "0xf87180808080808080a0dbee8b33c73b86df839f309f7ac92eee19836e08b39302ffa33921b3c6a09f66a06068b283d51aeeee682b8fb5458354315d0b91737441ede5e137c18b4775174a8080808080a0fe7779c7d58c2fda43eba0a6644043c86ebb9ceb4836f89e30831f23eb059ece8080", "0xf8719f20b71c90b0d523dd5004cf206f325748da347685071b34812e21801f5270c4b84ff84d80890ad78ebc5ac6200000a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", ]); let provider = factory.provider().unwrap(); let account_proof = Proof::from_tx(provider.tx_ref()).account_proof(target, &[]).unwrap(); similar_asserts::assert_eq!(account_proof.proof, expected_account_proof); assert_eq!(account_proof.verify(root), Ok(())); } #[test] fn mainnet_genesis_account_proof_nonexistent() { // Create test database and insert genesis accounts. let factory = create_test_provider_factory(); let root = insert_genesis(&factory, MAINNET.clone()).unwrap(); // Address that does not exist in mainnet genesis allocation. // keccak256 - `0x18f415ffd7f66bb1924d90f0e82fb79ca8c6d8a3473cd9a95446a443b9db1761` let target = address!("0x000d836201318ec6899a67540690382780743281"); // `cast proof 0x000d836201318ec6899a67540690382780743281 --block 0` let expected_account_proof = convert_to_proof([ "0xf90211a090dcaf88c40c7bbc95a912cbdde67c175767b31173df9ee4b0d733bfdd511c43a0babe369f6b12092f49181ae04ca173fb68d1a5456f18d20fa32cba73954052bda0473ecf8a7e36a829e75039a3b055e51b8332cbf03324ab4af2066bbd6fbf0021a0bbda34753d7aa6c38e603f360244e8f59611921d9e1f128372fec0d586d4f9e0a04e44caecff45c9891f74f6a2156735886eedf6f1a733628ebc802ec79d844648a0a5f3f2f7542148c973977c8a1e154c4300fec92f755f7846f1b734d3ab1d90e7a0e823850f50bf72baae9d1733a36a444ab65d0a6faaba404f0583ce0ca4dad92da0f7a00cbe7d4b30b11faea3ae61b7f1f2b315b61d9f6bd68bfe587ad0eeceb721a07117ef9fc932f1a88e908eaead8565c19b5645dc9e5b1b6e841c5edbdfd71681a069eb2de283f32c11f859d7bcf93da23990d3e662935ed4d6b39ce3673ec84472a0203d26456312bbc4da5cd293b75b840fc5045e493d6f904d180823ec22bfed8ea09287b5c21f2254af4e64fca76acc5cd87399c7f1ede818db4326c98ce2dc2208a06fc2d754e304c48ce6a517753c62b1a9c1d5925b89707486d7fc08919e0a94eca07b1c54f15e299bd58bdfef9741538c7828b5d7d11a489f9c20d052b3471df475a051f9dd3739a927c89e357580a4c97b40234aa01ed3d5e0390dc982a7975880a0a089d613f26159af43616fd9455bb461f4869bfede26f2130835ed067a8b967bfb80", "0xf90211a0586b1ddec8db4824154209d355a1989b6c43aa69aba36e9d70c9faa53e7452baa0f86db47d628c73764d74b9ccaed73b8486d97a7731d57008fc9efaf417411860a0d9faed7b9ea107b5d98524246c977e782377f976e34f70717e8b1207f2f9b981a00218f59ccedf797c95e27c56405b9bf16845050fb43e773b66b26bc6992744f5a0dbf396f480c4e024156644adea7c331688d03742369e9d87ab8913bc439ff975a0aced524f39b22c62a5be512ddbca89f0b89b47c311065ccf423dee7013c7ea83a0c06b05f80b237b403adc019c0bc95b5de935021b14a75cbc18509eec60dfd83aa085339d45c4a52b7d523c301701f1ab339964e9c907440cff0a871c98dcf8811ea03ae9f6b8e227ec9be9461f0947b01696f78524c4519a6dee9fba14d209952cf9a0af17f551f9fa1ba4be41d0b342b160e2e8468d7e98a65a2dbf9d5fe5d6928024a0b850ac3bc03e9a309cc59ce5f1ab8db264870a7a22786081753d1db91897b8e6a09e796a4904bd78cb2655b5f346c94350e2d5f0dbf2bc00ac00871cd7ba46b241a0f6f0377427b900529caf32abf32ba1eb93f5f70153aa50b90bf55319a434c252a0725eaf27c8ee07e9b2511a6d6a0d71c649d855e8a9ed26e667903e2e94ae47cba0e4139fb48aa1a524d47f6e0df80314b88b52202d7e853da33c276aa8572283a8a05e9003d54a45935fdebae3513dc7cd16626dc05e1d903ae7f47f1a35aa6e234580", "0xf901d1a0b7c55b381eb205712a2f5d1b7d6309ac725da79ab159cb77dc2783af36e6596da0b3b48aa390e0f3718b486ccc32b01682f92819e652315c1629058cd4d9bb1545a0e3c0cc68af371009f14416c27e17f05f4f696566d2ba45362ce5711d4a01d0e4a0bad1e085e431b510508e2a9e3712633a414b3fe6fd358635ab206021254c1e10a0f8407fe8d5f557b9e012d52e688139bd932fec40d48630d7ff4204d27f8cc68da08c6ca46eff14ad4950e65469c394ca9d6b8690513b1c1a6f91523af00082474c80a0630c034178cb1290d4d906edf28688804d79d5e37a3122c909adab19ac7dc8c5a059f6d047c5d1cc75228c4517a537763cb410c38554f273e5448a53bc3c7166e7a0d842f53ce70c3aad1e616fa6485d3880d15c936fcc306ec14ae35236e5a60549a0218ee2ee673c69b4e1b953194b2568157a69085b86e4f01644fa06ab472c6cf9a016a35a660ea496df7c0da646378bfaa9562f401e42a5c2fe770b7bbe22433585a0dd0fbbe227a4d50868cdbb3107573910fd97131ea8d835bef81d91a2fc30b175a06aafa3d78cf179bf055bd5ec629be0ff8352ce0aec9125a4d75be3ee7eb71f10a01d6817ef9f64fcbb776ff6df0c83138dcd2001bd752727af3e60f4afc123d8d58080", ]); let provider = factory.provider().unwrap(); let account_proof = Proof::from_tx(provider.tx_ref()).account_proof(target, &[]).unwrap(); similar_asserts::assert_eq!(account_proof.proof, expected_account_proof); assert_eq!(account_proof.verify(root), Ok(())); } #[test] #[ignore = "State roots use non-flagged storage"] fn holesky_deposit_contract_proof() { // legacy test adapter let is_private = false; // Create test database and insert genesis accounts. let factory = create_test_provider_factory(); let root = insert_genesis(&factory, HOLESKY.clone()).unwrap(); let target = address!("0x4242424242424242424242424242424242424242"); // existent let slot_22 = B256::from_str("0x0000000000000000000000000000000000000000000000000000000000000022") .unwrap(); let slot_23 = B256::from_str("0x0000000000000000000000000000000000000000000000000000000000000023") .unwrap(); let slot_24 = B256::from_str("0x0000000000000000000000000000000000000000000000000000000000000024") .unwrap(); // non-existent let slot_100 = B256::from_str("0x0000000000000000000000000000000000000000000000000000000000000100") .unwrap(); let slots = Vec::from([slot_22, slot_23, slot_24, slot_100]); // `cast proof 0x4242424242424242424242424242424242424242 0x22 0x23 0x24 0x100 --block 0` let expected = AccountProof { address: target, info: Some(Account { balance: U256::ZERO, nonce: 0, bytecode_hash: Some(b256!("0x2034f79e0e33b0ae6bef948532021baceb116adf2616478703bec6b17329f1cc")) }), storage_root: b256!("0x556a482068355939c95a3412bdb21213a301483edb1b64402fb66ac9f3583599"), proof: convert_to_proof([ "0xf90211a0ea92fb71507739d5afe328d607b2c5e98322b7aa7cdfeccf817543058b54af70a0bd0c2525b5bee47abf7120c9e01ec3249699d687f80ebb96ed9ad9de913dbab0a0ab4b14b89416eb23c6b64204fa45cfcb39d4220016a9cd0815ebb751fe45eb71a0986ae29c2148b9e61f9a7543f44a1f8d029f1c5095b359652e9ec94e64b5d393a0555d54aa23ed990b0488153418637df7b2c878b604eb761aa2673b609937b0eba0140afb6a3909cc6047b3d44af13fc83f161a7e4c4ddba430a2841862912eb222a031b1185c1f455022d9e42ce04a71f174eb9441b1ada67449510500f4d85b3b22a051ecd01e18113b23cc65e62f67d69b33ee15d20bf81a6b524f7df90ded00ca15a0703769d6a7befad000bc2b4faae3e41b809b1b1241fe2964262554e7e3603488a0e5de7f600e4e6c3c3e5630e0c66f50506a17c9715642fccb63667e81397bbf93a095f783cd1d464a60e3c8adcadc28c6eb9fec7306664df39553be41dccc909606a04225fda3b89f0c59bf40129d1d5e5c3bf67a2129f0c55e53ffdd2cebf185d644a078e0f7fd3ae5a9bc90f66169614211b48fe235eb64818b3935d3e69c53523b9aa0a870e00e53ebaa1e9ec16e5f36606fd7d21d3a3c96894c0a2a23550949d4fdf7a0809226b69cee1f4f22ced1974e7805230da1909036a49a7652428999431afac2a0f11593b2407e86e11997325d8df2d22d937bbe0aef8302ba40c6be0601b04fc380", "0xf901f1a09da7d9755fe0c558b3c3de9fdcdf9f28ae641f38c9787b05b73ab22ae53af3e2a0d9990bf0b810d1145ecb2b011fd68c63cc85564e6724166fd4a9520180706e5fa05f5f09855df46330aa310e8d6be5fb82d1a4b975782d9b29acf06ac8d3e72b1ca0ca976997ddaf06f18992f6207e4f6a05979d07acead96568058789017cc6d06ba04d78166b48044fdc28ed22d2fd39c8df6f8aaa04cb71d3a17286856f6893ff83a004f8c7cc4f1335182a1709fb28fc67d52e59878480210abcba864d5d1fd4a066a0fc3b71c33e2e6b77c5e494c1db7fdbb447473f003daf378c7a63ba9bf3f0049d80a07b8e7a21c1178d28074f157b50fca85ee25c12568ff8e9706dcbcdacb77bf854a0973274526811393ea0bf4811ca9077531db00d06b86237a2ecd683f55ba4bcb0a03a93d726d7487874e51b52d8d534c63aa2a689df18e3b307c0d6cb0a388b00f3a06aa67101d011d1c22fe739ef83b04b5214a3e2f8e1a2625d8bfdb116b447e86fa02dd545b33c62d33a183e127a08a4767fba891d9f3b94fc20a2ca02600d6d1fffa0f3b039a4f32349e85c782d1164c1890e5bf16badc9ee4cf827db6afd2229dde6a0d9240a9d2d5851d05a97ff3305334dfdb0101e1e321fc279d2bb3cad6afa8fc8a01b69c6ab5173de8a8ec53a6ebba965713a4cc7feb86cb3e230def37c230ca2b280", "0xf869a0202a47fc6863b89a6b51890ef3c1550d560886c027141d2058ba1e2d4c66d99ab846f8448080a0556a482068355939c95a3412bdb21213a301483edb1b64402fb66ac9f3583599a02034f79e0e33b0ae6bef948532021baceb116adf2616478703bec6b17329f1cc", ]), storage_proofs: Vec::from([ StorageProof { key: slot_22, nibbles: Nibbles::unpack(keccak256(slot_22)), value: U256::from_str( "0xf5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b", ) .unwrap(), is_private, proof: convert_to_proof([ "0xf9019180a0aafd5b14a6edacd149e110ba6776a654f2dbffca340902be933d011113f2750380a0a502c93b1918c4c6534d4593ae03a5a23fa10ebc30ffb7080b297bff2446e42da02eb2bf45fd443bd1df8b6f9c09726a4c6252a0f7896a131a081e39a7f644b38980a0a9cf7f673a0bce76fd40332afe8601542910b48dea44e93933a3e5e930da5d19a0ddf79db0a36d0c8134ba143bcb541cd4795a9a2bae8aca0ba24b8d8963c2a77da0b973ec0f48f710bf79f63688485755cbe87f9d4c68326bb83c26af620802a80ea0f0855349af6bf84afc8bca2eda31c8ef8c5139be1929eeb3da4ba6b68a818cb0a0c271e189aeeb1db5d59d7fe87d7d6327bbe7cfa389619016459196497de3ccdea0e7503ba5799e77aa31bbe1310c312ca17b2c5bcc8fa38f266675e8f154c2516ba09278b846696d37213ab9d20a5eb42b03db3173ce490a2ef3b2f3b3600579fc63a0e9041059114f9c910adeca12dbba1fef79b2e2c8899f2d7213cd22dfe4310561a047c59da56bb2bf348c9dd2a2e8f5538a92b904b661cfe54a4298b85868bbe4858080", "0xf85180a0776aa456ba9c5008e03b82b841a9cf2fc1e8578cfacd5c9015804eae315f17fb80808080808080808080808080a072e3e284d47badbb0a5ca1421e1179d3ea90cc10785b26b74fb8a81f0f9e841880", "0xf843a020035b26e3e9eee00e0d72fd1ee8ddca6894550dca6916ea2ac6baa90d11e510a1a0f5a5fd42d16a20302798ef6ed309979b43003d2320d9f0e8ea9831a92759fb4b", ]), }, StorageProof { key: slot_23, nibbles: Nibbles::unpack(keccak256(slot_23)), value: U256::from_str( "0xdb56114e00fdd4c1f85c892bf35ac9a89289aaecb1ebd0a96cde606a748b5d71", ) .unwrap(), is_private, proof: convert_to_proof([ "0xf9019180a0aafd5b14a6edacd149e110ba6776a654f2dbffca340902be933d011113f2750380a0a502c93b1918c4c6534d4593ae03a5a23fa10ebc30ffb7080b297bff2446e42da02eb2bf45fd443bd1df8b6f9c09726a4c6252a0f7896a131a081e39a7f644b38980a0a9cf7f673a0bce76fd40332afe8601542910b48dea44e93933a3e5e930da5d19a0ddf79db0a36d0c8134ba143bcb541cd4795a9a2bae8aca0ba24b8d8963c2a77da0b973ec0f48f710bf79f63688485755cbe87f9d4c68326bb83c26af620802a80ea0f0855349af6bf84afc8bca2eda31c8ef8c5139be1929eeb3da4ba6b68a818cb0a0c271e189aeeb1db5d59d7fe87d7d6327bbe7cfa389619016459196497de3ccdea0e7503ba5799e77aa31bbe1310c312ca17b2c5bcc8fa38f266675e8f154c2516ba09278b846696d37213ab9d20a5eb42b03db3173ce490a2ef3b2f3b3600579fc63a0e9041059114f9c910adeca12dbba1fef79b2e2c8899f2d7213cd22dfe4310561a047c59da56bb2bf348c9dd2a2e8f5538a92b904b661cfe54a4298b85868bbe4858080", "0xf8518080808080a0d546c4ca227a267d29796643032422374624ed109b3d94848c5dc06baceaee76808080808080a027c48e210ccc6e01686be2d4a199d35f0e1e8df624a8d3a17c163be8861acd6680808080", "0xf843a0207b2b5166478fd4318d2acc6cc2c704584312bdd8781b32d5d06abda57f4230a1a0db56114e00fdd4c1f85c892bf35ac9a89289aaecb1ebd0a96cde606a748b5d71", ]), }, StorageProof { key: slot_24, nibbles: Nibbles::unpack(keccak256(slot_24)), value: U256::from_str( "0xc78009fdf07fc56a11f122370658a353aaa542ed63e44c4bc15ff4cd105ab33c", ) .unwrap(), is_private, proof: convert_to_proof([ "0xf9019180a0aafd5b14a6edacd149e110ba6776a654f2dbffca340902be933d011113f2750380a0a502c93b1918c4c6534d4593ae03a5a23fa10ebc30ffb7080b297bff2446e42da02eb2bf45fd443bd1df8b6f9c09726a4c6252a0f7896a131a081e39a7f644b38980a0a9cf7f673a0bce76fd40332afe8601542910b48dea44e93933a3e5e930da5d19a0ddf79db0a36d0c8134ba143bcb541cd4795a9a2bae8aca0ba24b8d8963c2a77da0b973ec0f48f710bf79f63688485755cbe87f9d4c68326bb83c26af620802a80ea0f0855349af6bf84afc8bca2eda31c8ef8c5139be1929eeb3da4ba6b68a818cb0a0c271e189aeeb1db5d59d7fe87d7d6327bbe7cfa389619016459196497de3ccdea0e7503ba5799e77aa31bbe1310c312ca17b2c5bcc8fa38f266675e8f154c2516ba09278b846696d37213ab9d20a5eb42b03db3173ce490a2ef3b2f3b3600579fc63a0e9041059114f9c910adeca12dbba1fef79b2e2c8899f2d7213cd22dfe4310561a047c59da56bb2bf348c9dd2a2e8f5538a92b904b661cfe54a4298b85868bbe4858080", "0xf85180808080a030263404acfee103d0b1019053ff3240fce433c69b709831673285fa5887ce4c80808080808080a0f8f1fbb1f7b482d9860480feebb83ff54a8b6ec1ead61cc7d2f25d7c01659f9c80808080", "0xf843a020d332d19b93bcabe3cce7ca0c18a052f57e5fd03b4758a09f30f5ddc4b22ec4a1a0c78009fdf07fc56a11f122370658a353aaa542ed63e44c4bc15ff4cd105ab33c", ]), }, StorageProof { key: slot_100, nibbles: Nibbles::unpack(keccak256(slot_100)), value: U256::ZERO, is_private, proof: convert_to_proof([ "0xf9019180a0aafd5b14a6edacd149e110ba6776a654f2dbffca340902be933d011113f2750380a0a502c93b1918c4c6534d4593ae03a5a23fa10ebc30ffb7080b297bff2446e42da02eb2bf45fd443bd1df8b6f9c09726a4c6252a0f7896a131a081e39a7f644b38980a0a9cf7f673a0bce76fd40332afe8601542910b48dea44e93933a3e5e930da5d19a0ddf79db0a36d0c8134ba143bcb541cd4795a9a2bae8aca0ba24b8d8963c2a77da0b973ec0f48f710bf79f63688485755cbe87f9d4c68326bb83c26af620802a80ea0f0855349af6bf84afc8bca2eda31c8ef8c5139be1929eeb3da4ba6b68a818cb0a0c271e189aeeb1db5d59d7fe87d7d6327bbe7cfa389619016459196497de3ccdea0e7503ba5799e77aa31bbe1310c312ca17b2c5bcc8fa38f266675e8f154c2516ba09278b846696d37213ab9d20a5eb42b03db3173ce490a2ef3b2f3b3600579fc63a0e9041059114f9c910adeca12dbba1fef79b2e2c8899f2d7213cd22dfe4310561a047c59da56bb2bf348c9dd2a2e8f5538a92b904b661cfe54a4298b85868bbe4858080", "0xf891a090bacef44b189ddffdc5f22edc70fe298c58e5e523e6e1dfdf7dbc6d657f7d1b80a026eed68746028bc369eb456b7d3ee475aa16f34e5eaa0c98fdedb9c59ebc53b0808080a09ce86197173e14e0633db84ce8eea32c5454eebe954779255644b45b717e8841808080a0328c7afb2c58ef3f8c4117a8ebd336f1a61d24591067ed9c5aae94796cac987d808080808080", ]), }, ]), }; let provider = factory.provider().unwrap(); let account_proof = Proof::from_tx(provider.tx_ref()).account_proof(target, &slots).unwrap(); similar_asserts::assert_eq!(account_proof, expected); assert_eq!(account_proof.verify(root), Ok(())); }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/db/tests/walker.rs
crates/trie/db/tests/walker.rs
#![allow(missing_docs)] use alloy_primitives::B256; use reth_db_api::{cursor::DbCursorRW, tables, transaction::DbTxMut}; use reth_provider::test_utils::create_test_provider_factory; use reth_trie::{ prefix_set::PrefixSetMut, trie_cursor::TrieCursor, walker::TrieWalker, BranchNodeCompact, Nibbles, StorageTrieEntry, }; use reth_trie_db::{DatabaseAccountTrieCursor, DatabaseStorageTrieCursor}; #[test] fn walk_nodes_with_common_prefix() { let inputs = vec![ (vec![0x5u8], BranchNodeCompact::new(0b1_0000_0101, 0b1_0000_0100, 0, vec![], None)), (vec![0x5u8, 0x2, 0xC], BranchNodeCompact::new(0b1000_0111, 0, 0, vec![], None)), (vec![0x5u8, 0x8], BranchNodeCompact::new(0b0110, 0b0100, 0, vec![], None)), ]; let expected = vec![ vec![0x5, 0x0], // The [0x5, 0x2] prefix is shared by the first 2 nodes, however: // 1. 0x2 for the first node points to the child node path // 2. 0x2 for the second node is a key. // So to proceed to add 1 and 3, we need to push the sibling first (0xC). vec![0x5, 0x2], vec![0x5, 0x2, 0xC, 0x0], vec![0x5, 0x2, 0xC, 0x1], vec![0x5, 0x2, 0xC, 0x2], vec![0x5, 0x2, 0xC, 0x7], vec![0x5, 0x8], vec![0x5, 0x8, 0x1], vec![0x5, 0x8, 0x2], ]; let factory = create_test_provider_factory(); let tx = factory.provider_rw().unwrap(); let mut account_cursor = tx.tx_ref().cursor_write::<tables::AccountsTrie>().unwrap(); for (k, v) in &inputs { account_cursor.upsert(k.clone().into(), &v.clone()).unwrap(); } let account_trie = DatabaseAccountTrieCursor::new(account_cursor); test_cursor(account_trie, &expected); let hashed_address = B256::random(); let mut storage_cursor = tx.tx_ref().cursor_dup_write::<tables::StoragesTrie>().unwrap(); for (k, v) in &inputs { storage_cursor .upsert( hashed_address, &StorageTrieEntry { nibbles: k.clone().into(), node: v.clone() }, ) .unwrap(); } let storage_trie = DatabaseStorageTrieCursor::new(storage_cursor, hashed_address); test_cursor(storage_trie, &expected); } fn test_cursor<T>(mut trie: T, expected: &[Vec<u8>]) where T: TrieCursor, { let mut walker = TrieWalker::<_>::state_trie(&mut trie, Default::default()); assert!(walker.key().unwrap().is_empty()); // We're traversing the path in lexicographical order. for expected in expected { walker.advance().unwrap(); let got = walker.key().copied(); assert_eq!(got.unwrap(), Nibbles::from_nibbles_unchecked(expected.clone())); } // There should be 8 paths traversed in total from 3 branches. walker.advance().unwrap(); assert!(walker.key().is_none()); } #[test] fn cursor_rootnode_with_changesets() { let factory = create_test_provider_factory(); let tx = factory.provider_rw().unwrap(); let mut cursor = tx.tx_ref().cursor_dup_write::<tables::StoragesTrie>().unwrap(); let nodes = vec![ ( vec![], BranchNodeCompact::new( // 2 and 4 are set 0b10100, 0b00100, 0, vec![], Some(B256::random()), ), ), ( vec![0x2], BranchNodeCompact::new( // 1 is set 0b00010, 0, 0b00010, vec![B256::random()], None, ), ), ]; let hashed_address = B256::random(); for (k, v) in nodes { cursor.upsert(hashed_address, &StorageTrieEntry { nibbles: k.into(), node: v }).unwrap(); } let mut trie = DatabaseStorageTrieCursor::new(cursor, hashed_address); // No changes let mut cursor = TrieWalker::<_>::state_trie(&mut trie, Default::default()); assert_eq!(cursor.key().copied(), Some(Nibbles::new())); // root assert!(cursor.can_skip_current_node); // due to root_hash cursor.advance().unwrap(); // skips to the end of trie assert_eq!(cursor.key().copied(), None); // We insert something that's not part of the existing trie/prefix. let mut changed = PrefixSetMut::default(); changed.insert(Nibbles::from_nibbles([0xF, 0x1])); let mut cursor = TrieWalker::<_>::state_trie(&mut trie, changed.freeze()); // Root node assert_eq!(cursor.key().copied(), Some(Nibbles::new())); // Should not be able to skip state due to the changed values assert!(!cursor.can_skip_current_node); cursor.advance().unwrap(); assert_eq!(cursor.key().copied(), Some(Nibbles::from_nibbles([0x2]))); cursor.advance().unwrap(); assert_eq!(cursor.key().copied(), Some(Nibbles::from_nibbles([0x2, 0x1]))); cursor.advance().unwrap(); assert_eq!(cursor.key().copied(), Some(Nibbles::from_nibbles([0x4]))); cursor.advance().unwrap(); assert_eq!(cursor.key().copied(), None); // the end of trie }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/db/tests/witness.rs
crates/trie/db/tests/witness.rs
#![allow(missing_docs)] use alloy_consensus::EMPTY_ROOT_HASH; use alloy_primitives::{ keccak256, map::{HashMap, HashSet}, Address, Bytes, B256, }; use alloy_rlp::EMPTY_STRING_CODE; use reth_db::{cursor::DbCursorRW, tables}; use reth_db_api::transaction::DbTxMut; use reth_primitives_traits::{Account, StorageEntry}; use reth_provider::{test_utils::create_test_provider_factory, HashingWriter}; use reth_trie::{ proof::Proof, witness::TrieWitness, HashedPostState, HashedStorage, MultiProofTargets, StateRoot, }; use reth_trie_db::{DatabaseProof, DatabaseStateRoot, DatabaseTrieWitness}; use revm_state::FlaggedStorage; #[test] fn includes_empty_node_preimage() { let factory = create_test_provider_factory(); let provider = factory.provider_rw().unwrap(); let address = Address::random(); let hashed_address = keccak256(address); let hashed_slot = B256::random(); // witness includes empty state trie root node assert_eq!( TrieWitness::from_tx(provider.tx_ref()) .compute(HashedPostState { accounts: HashMap::from_iter([(hashed_address, Some(Account::default()))]), storages: HashMap::default(), }) .unwrap(), HashMap::from_iter([(EMPTY_ROOT_HASH, Bytes::from([EMPTY_STRING_CODE]))]) ); // Insert account into database provider.insert_account_for_hashing([(address, Some(Account::default()))]).unwrap(); let state_root = StateRoot::from_tx(provider.tx_ref()).root().unwrap(); let multiproof = Proof::from_tx(provider.tx_ref()) .multiproof(MultiProofTargets::from_iter([( hashed_address, HashSet::from_iter([hashed_slot]), )])) .unwrap(); let witness = TrieWitness::from_tx(provider.tx_ref()) .compute(HashedPostState { accounts: HashMap::from_iter([(hashed_address, Some(Account::default()))]), storages: HashMap::from_iter([( hashed_address, HashedStorage::from_iter(false, [(hashed_slot, FlaggedStorage::public(1))]), )]), }) .unwrap(); assert!(witness.contains_key(&state_root)); for node in multiproof.account_subtree.values() { assert_eq!(witness.get(&keccak256(node)), Some(node)); } // witness includes empty state trie root node assert_eq!(witness.get(&EMPTY_ROOT_HASH), Some(&Bytes::from([EMPTY_STRING_CODE]))); } #[test] fn includes_nodes_for_destroyed_storage_nodes() { let factory = create_test_provider_factory(); let provider = factory.provider_rw().unwrap(); let address = Address::random(); let hashed_address = keccak256(address); let slot = B256::random(); let hashed_slot = keccak256(slot); // Insert account and slot into database provider.insert_account_for_hashing([(address, Some(Account::default()))]).unwrap(); provider .insert_storage_for_hashing([( address, [StorageEntry { key: slot, value: alloy_primitives::FlaggedStorage::public(1) }], )]) .unwrap(); let state_root = StateRoot::from_tx(provider.tx_ref()).root().unwrap(); let multiproof = Proof::from_tx(provider.tx_ref()) .multiproof(MultiProofTargets::from_iter([( hashed_address, HashSet::from_iter([hashed_slot]), )])) .unwrap(); let witness = TrieWitness::from_tx(provider.tx_ref()) .compute(HashedPostState { accounts: HashMap::from_iter([(hashed_address, Some(Account::default()))]), storages: HashMap::from_iter([( hashed_address, HashedStorage::from_iter(true, []), )]), // destroyed }) .unwrap(); assert!(witness.contains_key(&state_root)); for node in multiproof.account_subtree.values() { assert_eq!(witness.get(&keccak256(node)), Some(node)); } for node in multiproof.storages.iter().flat_map(|(_, storage)| storage.subtree.values()) { assert_eq!(witness.get(&keccak256(node)), Some(node)); } } #[test] fn correctly_decodes_branch_node_values() { let factory = create_test_provider_factory(); let provider = factory.provider_rw().unwrap(); let address = Address::random(); let hashed_address = keccak256(address); let hashed_slot1 = B256::with_last_byte(1); let hashed_slot2 = B256::with_last_byte(2); // Insert account and slots into database provider.insert_account_for_hashing([(address, Some(Account::default()))]).unwrap(); let mut hashed_storage_cursor = provider.tx_ref().cursor_dup_write::<tables::HashedStorages>().unwrap(); hashed_storage_cursor .upsert( hashed_address, &StorageEntry { key: hashed_slot1, value: alloy_primitives::FlaggedStorage::public(1) }, ) .unwrap(); hashed_storage_cursor .upsert( hashed_address, &StorageEntry { key: hashed_slot2, value: alloy_primitives::FlaggedStorage::public(1) }, ) .unwrap(); let state_root = StateRoot::from_tx(provider.tx_ref()).root().unwrap(); let multiproof = Proof::from_tx(provider.tx_ref()) .multiproof(MultiProofTargets::from_iter([( hashed_address, HashSet::from_iter([hashed_slot1, hashed_slot2]), )])) .unwrap(); let witness = TrieWitness::from_tx(provider.tx_ref()) .compute(HashedPostState { accounts: HashMap::from_iter([(hashed_address, Some(Account::default()))]), storages: HashMap::from_iter([( hashed_address, HashedStorage::from_iter( false, [hashed_slot1, hashed_slot2] .map(|hashed_slot| (hashed_slot, FlaggedStorage::public(2))), ), )]), }) .unwrap(); assert!(witness.contains_key(&state_root)); for node in multiproof.account_subtree.values() { assert_eq!(witness.get(&keccak256(node)), Some(node)); } for node in multiproof.storages.iter().flat_map(|(_, storage)| storage.subtree.values()) { assert_eq!(witness.get(&keccak256(node)), Some(node)); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/db/tests/fuzz_in_memory_nodes.rs
crates/trie/db/tests/fuzz_in_memory_nodes.rs
#![allow(missing_docs)] use alloy_primitives::{B256, U256}; use proptest::prelude::*; use reth_db::{ cursor::{DbCursorRO, DbCursorRW, DbDupCursorRW}, tables, transaction::DbTxMut, }; use reth_primitives_traits::{Account, StorageEntry}; use reth_provider::test_utils::create_test_provider_factory; use reth_trie::{ test_utils::{state_root_prehashed, storage_root_prehashed_privacy_aware}, trie_cursor::InMemoryTrieCursorFactory, updates::TrieUpdates, HashedPostState, HashedStorage, StateRoot, StorageRoot, }; use reth_trie_db::{DatabaseStateRoot, DatabaseStorageRoot, DatabaseTrieCursorFactory}; use std::collections::BTreeMap; proptest! { #![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })] #[test] fn fuzz_in_memory_account_nodes(mut init_state: BTreeMap<B256, U256>, state_updates: [BTreeMap<B256, Option<U256>>; 10]) { let factory = create_test_provider_factory(); let provider = factory.provider_rw().unwrap(); let mut hashed_account_cursor = provider.tx_ref().cursor_write::<tables::HashedAccounts>().unwrap(); // Insert init state into database for (hashed_address, balance) in init_state.clone() { hashed_account_cursor.upsert(hashed_address, &Account { balance, ..Default::default() }).unwrap(); } // Compute initial root and updates let (_, mut trie_nodes) = StateRoot::from_tx(provider.tx_ref()) .root_with_updates() .unwrap(); let mut state = init_state; for state_update in state_updates { // Insert state updates into database let mut hashed_state = HashedPostState::default(); for (hashed_address, balance) in state_update { if let Some(balance) = balance { let account = Account { balance, ..Default::default() }; hashed_account_cursor.upsert(hashed_address, &account).unwrap(); hashed_state.accounts.insert(hashed_address, Some(account)); state.insert(hashed_address, balance); } else { hashed_state.accounts.insert(hashed_address, None); state.remove(&hashed_address); } } // Compute root with in-memory trie nodes overlay let (state_root, trie_updates) = StateRoot::from_tx(provider.tx_ref()) .with_prefix_sets(hashed_state.construct_prefix_sets().freeze()) .with_trie_cursor_factory(InMemoryTrieCursorFactory::new( DatabaseTrieCursorFactory::new(provider.tx_ref()), &trie_nodes.clone().into_sorted()) ) .root_with_updates() .unwrap(); trie_nodes.extend(trie_updates); // Verify the result let expected_root = state_root_prehashed( state.iter().map(|(&key, &balance)| (key, (Account { balance, ..Default::default() }, std::iter::empty()))) ); assert_eq!(expected_root, state_root); } } #[test] fn fuzz_in_memory_storage_nodes(mut init_storage: BTreeMap<B256, alloy_primitives::FlaggedStorage>, storage_updates: [(bool, BTreeMap<B256, alloy_primitives::FlaggedStorage>); 10]) { let hashed_address = B256::random(); let factory = create_test_provider_factory(); let provider = factory.provider_rw().unwrap(); let mut hashed_storage_cursor = provider.tx_ref().cursor_write::<tables::HashedStorages>().unwrap(); // Insert init state into database for (hashed_slot, value) in init_storage.clone() { hashed_storage_cursor .upsert(hashed_address, &StorageEntry { key: hashed_slot, value }) .unwrap(); } // Compute initial storage root and updates let (_, _, mut storage_trie_nodes) = StorageRoot::from_tx_hashed(provider.tx_ref(), hashed_address).root_with_updates().unwrap(); let mut storage = init_storage; for (is_deleted, mut storage_update) in storage_updates { // Insert state updates into database if is_deleted && hashed_storage_cursor.seek_exact(hashed_address).unwrap().is_some() { hashed_storage_cursor.delete_current_duplicates().unwrap(); } let mut hashed_storage = HashedStorage::new(is_deleted); for (hashed_slot, value) in storage_update.clone() { hashed_storage_cursor .upsert(hashed_address, &StorageEntry { key: hashed_slot, value }) .unwrap(); hashed_storage.storage.insert(hashed_slot, value); } // Compute root with in-memory trie nodes overlay let mut trie_nodes = TrieUpdates::default(); trie_nodes.insert_storage_updates(hashed_address, storage_trie_nodes.clone()); let (storage_root, _, trie_updates) = StorageRoot::from_tx_hashed(provider.tx_ref(), hashed_address) .with_prefix_set(hashed_storage.construct_prefix_set().freeze()) .with_trie_cursor_factory(InMemoryTrieCursorFactory::new( DatabaseTrieCursorFactory::new(provider.tx_ref()), &trie_nodes.into_sorted(), )) .root_with_updates() .unwrap(); storage_trie_nodes.extend(trie_updates); // Verify the result if is_deleted { storage.clear(); } storage.append(&mut storage_update); let expected_root = storage_root_prehashed_privacy_aware(storage.clone()); assert_eq!(expected_root, storage_root); } } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/db/tests/post_state.rs
crates/trie/db/tests/post_state.rs
#![allow(missing_docs)] use alloy_primitives::{B256, U256}; use proptest::prelude::*; use proptest_arbitrary_interop::arb; use reth_db::{tables, test_utils::create_test_rw_db}; use reth_db_api::{database::Database, transaction::DbTxMut}; use reth_primitives_traits::{Account, StorageEntry}; use reth_trie::{ hashed_cursor::{ HashedCursor, HashedCursorFactory, HashedPostStateCursorFactory, HashedStorageCursor, }, HashedPostState, HashedStorage, }; use reth_trie_db::DatabaseHashedCursorFactory; use revm::state::FlaggedStorage; use std::collections::BTreeMap; fn assert_account_cursor_order( factory: &impl HashedCursorFactory, mut expected: impl Iterator<Item = (B256, Account)>, ) { let mut cursor = factory.hashed_account_cursor().unwrap(); let first_account = cursor.seek(B256::default()).unwrap(); assert_eq!(first_account, expected.next()); for expected in expected { let next_cursor_account = cursor.next().unwrap(); assert_eq!(next_cursor_account, Some(expected)); } assert!(cursor.next().unwrap().is_none()); } fn assert_storage_cursor_order( factory: &impl HashedCursorFactory, expected: impl Iterator<Item = (B256, BTreeMap<B256, FlaggedStorage>)>, ) { for (account, storage) in expected { let mut cursor = factory.hashed_storage_cursor(account).unwrap(); let mut expected_storage = storage.into_iter(); let first_storage = cursor.seek(B256::default()).unwrap(); assert_eq!(first_storage, expected_storage.next()); for expected_entry in expected_storage { let next_cursor_storage = cursor.next().unwrap(); assert_eq!(next_cursor_storage, Some(expected_entry)); } assert!(cursor.next().unwrap().is_none()); } } #[test] fn post_state_only_accounts() { let accounts = (1..11).map(|key| (B256::with_last_byte(key), Account::default())).collect::<Vec<_>>(); let mut hashed_post_state = HashedPostState::default(); for (hashed_address, account) in &accounts { hashed_post_state.accounts.insert(*hashed_address, Some(*account)); } let db = create_test_rw_db(); let sorted = hashed_post_state.into_sorted(); let tx = db.tx().unwrap(); let factory = HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(&tx), &sorted); assert_account_cursor_order(&factory, accounts.into_iter()); } #[test] fn db_only_accounts() { let accounts = (1..11).map(|key| (B256::with_last_byte(key), Account::default())).collect::<Vec<_>>(); let db = create_test_rw_db(); db.update(|tx| { for (key, account) in &accounts { tx.put::<tables::HashedAccounts>(*key, *account).unwrap(); } }) .unwrap(); let sorted_post_state = HashedPostState::default().into_sorted(); let tx = db.tx().unwrap(); let factory = HashedPostStateCursorFactory::new( DatabaseHashedCursorFactory::new(&tx), &sorted_post_state, ); assert_account_cursor_order(&factory, accounts.into_iter()); } #[test] fn account_cursor_correct_order() { // odd keys are in post state, even keys are in db let accounts = (1..111).map(|key| (B256::with_last_byte(key), Account::default())).collect::<Vec<_>>(); let db = create_test_rw_db(); db.update(|tx| { for (key, account) in accounts.iter().filter(|x| x.0[31].is_multiple_of(2)) { tx.put::<tables::HashedAccounts>(*key, *account).unwrap(); } }) .unwrap(); let mut hashed_post_state = HashedPostState::default(); for (hashed_address, account) in accounts.iter().filter(|x| !x.0[31].is_multiple_of(2)) { hashed_post_state.accounts.insert(*hashed_address, Some(*account)); } let sorted = hashed_post_state.into_sorted(); let tx = db.tx().unwrap(); let factory = HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(&tx), &sorted); assert_account_cursor_order(&factory, accounts.into_iter()); } #[test] fn removed_accounts_are_discarded() { // odd keys are in post state, even keys are in db let accounts = (1..111).map(|key| (B256::with_last_byte(key), Account::default())).collect::<Vec<_>>(); // accounts 5, 9, 11 should be considered removed from post state let removed_keys = [5, 9, 11].into_iter().map(B256::with_last_byte).collect::<Vec<_>>(); let db = create_test_rw_db(); db.update(|tx| { for (key, account) in accounts.iter().filter(|x| x.0[31].is_multiple_of(2)) { tx.put::<tables::HashedAccounts>(*key, *account).unwrap(); } }) .unwrap(); let mut hashed_post_state = HashedPostState::default(); for (hashed_address, account) in accounts.iter().filter(|x| !x.0[31].is_multiple_of(2)) { hashed_post_state.accounts.insert( *hashed_address, if removed_keys.contains(hashed_address) { None } else { Some(*account) }, ); } let sorted = hashed_post_state.into_sorted(); let tx = db.tx().unwrap(); let factory = HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(&tx), &sorted); let expected = accounts.into_iter().filter(|x| !removed_keys.contains(&x.0)); assert_account_cursor_order(&factory, expected); } #[test] fn post_state_accounts_take_precedence() { let accounts = (1..10) .map(|key| (B256::with_last_byte(key), Account { nonce: key as u64, ..Default::default() })) .collect::<Vec<_>>(); let db = create_test_rw_db(); db.update(|tx| { for (key, _) in &accounts { // insert zero value accounts to the database tx.put::<tables::HashedAccounts>(*key, Account::default()).unwrap(); } }) .unwrap(); let mut hashed_post_state = HashedPostState::default(); for (hashed_address, account) in &accounts { hashed_post_state.accounts.insert(*hashed_address, Some(*account)); } let sorted = hashed_post_state.into_sorted(); let tx = db.tx().unwrap(); let factory = HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(&tx), &sorted); assert_account_cursor_order(&factory, accounts.into_iter()); } #[test] fn fuzz_hashed_account_cursor() { proptest!(ProptestConfig::with_cases(10), |(db_accounts in arb::<BTreeMap<B256, Account>>(), post_state_accounts in arb::<BTreeMap<B256, Option<Account>>>())| { let db = create_test_rw_db(); db.update(|tx| { for (key, account) in &db_accounts { tx.put::<tables::HashedAccounts>(*key, *account).unwrap(); } }) .unwrap(); let mut hashed_post_state = HashedPostState::default(); for (hashed_address, account) in &post_state_accounts { hashed_post_state.accounts.insert(*hashed_address, *account); } let mut expected = db_accounts; // overwrite or remove accounts from the expected result for (key, account) in &post_state_accounts { if let Some(account) = account { expected.insert(*key, *account); } else { expected.remove(key); } } let sorted = hashed_post_state.into_sorted(); let tx = db.tx().unwrap(); let factory = HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(&tx), &sorted); assert_account_cursor_order(&factory, expected.into_iter()); } ); } #[test] fn storage_is_empty() { let address = B256::random(); let db = create_test_rw_db(); // empty from the get go { let sorted = HashedPostState::default().into_sorted(); let tx = db.tx().unwrap(); let factory = HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(&tx), &sorted); let mut cursor = factory.hashed_storage_cursor(address).unwrap(); assert!(cursor.is_storage_empty().unwrap()); } let db_storage = (0..10).map(|key| (B256::with_last_byte(key), U256::from(key))).collect::<BTreeMap<_, _>>(); db.update(|tx| { for (slot, value) in &db_storage { // insert zero value accounts to the database tx.put::<tables::HashedStorages>( address, StorageEntry { key: *slot, value: FlaggedStorage::public(*value) }, ) .unwrap(); } }) .unwrap(); // not empty { let sorted = HashedPostState::default().into_sorted(); let tx = db.tx().unwrap(); let factory = HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(&tx), &sorted); let mut cursor = factory.hashed_storage_cursor(address).unwrap(); assert!(!cursor.is_storage_empty().unwrap()); } // wiped storage, must be empty { let wiped = true; let hashed_storage = HashedStorage::new(wiped); let mut hashed_post_state = HashedPostState::default(); hashed_post_state.storages.insert(address, hashed_storage); let sorted = hashed_post_state.into_sorted(); let tx = db.tx().unwrap(); let factory = HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(&tx), &sorted); let mut cursor = factory.hashed_storage_cursor(address).unwrap(); assert!(cursor.is_storage_empty().unwrap()); } // wiped storage, but post state has zero-value entries { let wiped = true; let mut hashed_storage = HashedStorage::new(wiped); hashed_storage.storage.insert(B256::random(), FlaggedStorage::ZERO); let mut hashed_post_state = HashedPostState::default(); hashed_post_state.storages.insert(address, hashed_storage); let sorted = hashed_post_state.into_sorted(); let tx = db.tx().unwrap(); let factory = HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(&tx), &sorted); let mut cursor = factory.hashed_storage_cursor(address).unwrap(); assert!(cursor.is_storage_empty().unwrap()); } // wiped storage, but post state has non-zero entries { let wiped = true; let mut hashed_storage = HashedStorage::new(wiped); hashed_storage.storage.insert(B256::random(), FlaggedStorage::new_from_value(1)); let mut hashed_post_state = HashedPostState::default(); hashed_post_state.storages.insert(address, hashed_storage); let sorted = hashed_post_state.into_sorted(); let tx = db.tx().unwrap(); let factory = HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(&tx), &sorted); let mut cursor = factory.hashed_storage_cursor(address).unwrap(); assert!(!cursor.is_storage_empty().unwrap()); } } #[test] fn storage_cursor_correct_order() { let address = B256::random(); let db_storage = (1..11) .map(|key| (B256::with_last_byte(key), FlaggedStorage::new_from_value(key))) .collect::<BTreeMap<_, _>>(); let post_state_storage = (11..21) .map(|key| (B256::with_last_byte(key), FlaggedStorage::new_from_value(key))) .collect::<BTreeMap<_, _>>(); let db = create_test_rw_db(); db.update(|tx| { for (slot, &value) in &db_storage { // insert zero value accounts to the database tx.put::<tables::HashedStorages>(address, StorageEntry { key: *slot, value }).unwrap(); } }) .unwrap(); let wiped = false; let mut hashed_storage = HashedStorage::new(wiped); for (slot, value) in &post_state_storage { hashed_storage.storage.insert(*slot, *value); } let mut hashed_post_state = HashedPostState::default(); hashed_post_state.storages.insert(address, hashed_storage); let sorted = hashed_post_state.into_sorted(); let tx = db.tx().unwrap(); let factory = HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(&tx), &sorted); let expected = std::iter::once((address, db_storage.into_iter().chain(post_state_storage).collect())); assert_storage_cursor_order(&factory, expected); } #[test] fn zero_value_storage_entries_are_discarded() { let address = B256::random(); let db_storage = (0..10) .map(|key| (B256::with_last_byte(key), FlaggedStorage::new_from_value(key))) .collect::<BTreeMap<_, _>>(); // every even number is changed to zero value let post_state_storage = (0..10) .map(|key| { ( B256::with_last_byte(key), if key.is_multiple_of(2) { FlaggedStorage::ZERO } else { FlaggedStorage::new_from_value(key) }, ) }) .collect::<BTreeMap<_, _>>(); let db = create_test_rw_db(); db.update(|tx| { for (slot, value) in db_storage { // insert zero value accounts to the database tx.put::<tables::HashedStorages>(address, StorageEntry { key: slot, value }).unwrap(); } }) .unwrap(); let wiped = false; let mut hashed_storage = HashedStorage::new(wiped); for (slot, value) in &post_state_storage { hashed_storage.storage.insert(*slot, *value); } let mut hashed_post_state = HashedPostState::default(); hashed_post_state.storages.insert(address, hashed_storage); let sorted = hashed_post_state.into_sorted(); let tx = db.tx().unwrap(); let factory = HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(&tx), &sorted); let expected = std::iter::once(( address, post_state_storage.into_iter().filter(|(_, value)| value.value > U256::ZERO).collect(), )); assert_storage_cursor_order(&factory, expected); } #[test] fn wiped_storage_is_discarded() { let address = B256::random(); let db_storage = (1..11) .map(|key| (B256::with_last_byte(key), FlaggedStorage::new_from_value(key))) .collect::<BTreeMap<_, _>>(); let post_state_storage = (11..21) .map(|key| (B256::with_last_byte(key), FlaggedStorage::new_from_value(key))) .collect::<BTreeMap<_, _>>(); let db = create_test_rw_db(); db.update(|tx| { for (slot, value) in db_storage { // insert zero value accounts to the database tx.put::<tables::HashedStorages>(address, StorageEntry { key: slot, value }).unwrap(); } }) .unwrap(); let wiped = true; let mut hashed_storage = HashedStorage::new(wiped); for (slot, value) in &post_state_storage { hashed_storage.storage.insert(*slot, *value); } let mut hashed_post_state = HashedPostState::default(); hashed_post_state.storages.insert(address, hashed_storage); let sorted = hashed_post_state.into_sorted(); let tx = db.tx().unwrap(); let factory = HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(&tx), &sorted); let expected = std::iter::once((address, post_state_storage)); assert_storage_cursor_order(&factory, expected); } #[test] fn post_state_storages_take_precedence() { let address = B256::random(); let storage = (1..10) .map(|key| (B256::with_last_byte(key), FlaggedStorage::new_from_value(key))) .collect::<BTreeMap<_, _>>(); let db = create_test_rw_db(); db.update(|tx| { for slot in storage.keys() { // insert zero value accounts to the database tx.put::<tables::HashedStorages>( address, StorageEntry { key: *slot, value: FlaggedStorage::ZERO }, ) .unwrap(); } }) .unwrap(); let wiped = false; let mut hashed_storage = HashedStorage::new(wiped); for (slot, value) in &storage { hashed_storage.storage.insert(*slot, *value); } let mut hashed_post_state = HashedPostState::default(); hashed_post_state.storages.insert(address, hashed_storage); let sorted = hashed_post_state.into_sorted(); let tx = db.tx().unwrap(); let factory = HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(&tx), &sorted); let expected = std::iter::once((address, storage)); assert_storage_cursor_order(&factory, expected); } #[test] fn fuzz_hashed_storage_cursor() { proptest!(ProptestConfig::with_cases(10), |( db_storages: BTreeMap<B256, BTreeMap<B256, FlaggedStorage>>, post_state_storages: BTreeMap<B256, (bool, BTreeMap<B256, FlaggedStorage>)>, )| { let db = create_test_rw_db(); db.update(|tx| { for (address, storage) in &db_storages { for (slot, &value) in storage { let entry = StorageEntry { key: *slot, value }; tx.put::<tables::HashedStorages>(*address, entry).unwrap(); } } }) .unwrap(); let mut hashed_post_state = HashedPostState::default(); for (address, (wiped, storage)) in &post_state_storages { let mut hashed_storage = HashedStorage::new(*wiped); for (slot, value) in storage { hashed_storage.storage.insert(*slot, *value); } hashed_post_state.storages.insert(*address, hashed_storage); } let mut expected = db_storages; // overwrite or remove accounts from the expected result for (key, (wiped, storage)) in post_state_storages { let entry = expected.entry(key).or_default(); if wiped { entry.clear(); } entry.extend(storage); } let sorted = hashed_post_state.into_sorted(); let tx = db.tx().unwrap(); let factory = HashedPostStateCursorFactory::new(DatabaseHashedCursorFactory::new(&tx), &sorted); assert_storage_cursor_order(&factory, expected.into_iter()); }); }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/db/tests/trie.rs
crates/trie/db/tests/trie.rs
#![allow(missing_docs)] use alloy_consensus::EMPTY_ROOT_HASH; use alloy_primitives::{ address, b256, hex_literal::hex, keccak256, map::HashMap, Address, B256, U256, }; use alloy_rlp::Encodable; use proptest::{prelude::ProptestConfig, proptest}; use proptest_arbitrary_interop::arb; use reth_db::{tables, test_utils::TempDatabase, DatabaseEnv}; use reth_db_api::{ cursor::{DbCursorRO, DbCursorRW, DbDupCursorRO}, transaction::{DbTx, DbTxMut}, }; use reth_primitives_traits::{Account, StorageEntry}; use reth_provider::{ providers::ProviderNodeTypes, test_utils::create_test_provider_factory, DatabaseProviderRW, StorageTrieWriter, TrieWriter, }; use reth_trie::{ prefix_set::{PrefixSetMut, TriePrefixSets}, test_utils::{ state_root_prehashed, state_root_privacy_aware, storage_root, storage_root_prehashed, storage_root_privacy_aware, }, triehash::KeccakHasher, updates::StorageTrieUpdates, BranchNodeCompact, HashBuilder, IntermediateStateRootState, Nibbles, StateRoot, StateRootProgress, StorageRoot, TrieMask, }; use reth_trie_db::{DatabaseStateRoot, DatabaseStorageRoot}; use std::{collections::BTreeMap, ops::Mul, str::FromStr, sync::Arc}; fn insert_account( tx: &impl DbTxMut, address: Address, account: Account, storage: &BTreeMap<B256, alloy_primitives::FlaggedStorage>, ) { let hashed_address = keccak256(address); tx.put::<tables::HashedAccounts>(hashed_address, account).unwrap(); insert_storage(tx, hashed_address, storage); } fn insert_storage( tx: &impl DbTxMut, hashed_address: B256, storage: &BTreeMap<B256, alloy_primitives::FlaggedStorage>, ) { for (k, v) in storage { tx.put::<tables::HashedStorages>( hashed_address, StorageEntry { key: keccak256(k), value: *v }, ) .unwrap(); } } fn incremental_vs_full_root(inputs: &[&str], modified: &str) { let factory = create_test_provider_factory(); let tx = factory.provider_rw().unwrap(); let hashed_address = B256::with_last_byte(1); let mut hashed_storage_cursor = tx.tx_ref().cursor_dup_write::<tables::HashedStorages>().unwrap(); let data = inputs.iter().map(|x| B256::from_str(x).unwrap()); let value = U256::from(0); for key in data { hashed_storage_cursor .upsert( hashed_address, &StorageEntry { key, value: alloy_primitives::FlaggedStorage::public(value) }, ) .unwrap(); } // Generate the intermediate nodes on the receiving end of the channel let (_, _, trie_updates) = StorageRoot::from_tx_hashed(tx.tx_ref(), hashed_address).root_with_updates().unwrap(); // 1. Some state transition happens, update the hashed storage to the new value let modified_key = B256::from_str(modified).unwrap(); let value = U256::from(1); if hashed_storage_cursor.seek_by_key_subkey(hashed_address, modified_key).unwrap().is_some() { hashed_storage_cursor.delete_current().unwrap(); } hashed_storage_cursor .upsert( hashed_address, &StorageEntry { key: modified_key, value: alloy_primitives::FlaggedStorage::public(value), }, ) .unwrap(); // 2. Calculate full merkle root let loader = StorageRoot::from_tx_hashed(tx.tx_ref(), hashed_address); let modified_root = loader.root().unwrap(); // Update the intermediate roots table so that we can run the incremental verification tx.write_individual_storage_trie_updates(hashed_address, &trie_updates).unwrap(); // 3. Calculate the incremental root let mut storage_changes = PrefixSetMut::default(); storage_changes.insert(Nibbles::unpack(modified_key)); let loader = StorageRoot::from_tx_hashed(tx.tx_ref(), hashed_address) .with_prefix_set(storage_changes.freeze()); let incremental_root = loader.root().unwrap(); assert_eq!(modified_root, incremental_root); } #[test] fn branch_node_child_changes() { incremental_vs_full_root( &[ "1000000000000000000000000000000000000000000000000000000000000000", "1100000000000000000000000000000000000000000000000000000000000000", "1110000000000000000000000000000000000000000000000000000000000000", "1200000000000000000000000000000000000000000000000000000000000000", "1220000000000000000000000000000000000000000000000000000000000000", "1320000000000000000000000000000000000000000000000000000000000000", ], "1200000000000000000000000000000000000000000000000000000000000000", ); } #[test] fn arbitrary_storage_root() { proptest!(ProptestConfig::with_cases(10), |(item in arb::<(Address, std::collections::BTreeMap<B256, alloy_primitives::FlaggedStorage>)>())| { let (address, storage) = item; let hashed_address = keccak256(address); let factory = create_test_provider_factory(); let tx = factory.provider_rw().unwrap(); for (key, value) in &storage { tx.tx_ref().put::<tables::HashedStorages>( hashed_address, StorageEntry { key: keccak256(key), value: *value }, ) .unwrap(); } tx.commit().unwrap(); let tx = factory.provider_rw().unwrap(); let got = StorageRoot::from_tx(tx.tx_ref(), address).root().unwrap(); let expected = storage_root_privacy_aware(storage.into_iter()); assert_eq!(expected, got); }); } #[test] // This ensures we don't add empty accounts to the trie fn test_empty_account() { let state: State = BTreeMap::from([ ( Address::random(), ( Account { nonce: 0, balance: U256::from(0), bytecode_hash: None }, BTreeMap::from([(B256::with_last_byte(0x4), U256::from(12).into())]), ), ), ( Address::random(), ( Account { nonce: 0, balance: U256::from(0), bytecode_hash: None }, BTreeMap::default(), ), ), ( Address::random(), ( Account { nonce: 155, balance: U256::from(414241124u32), bytecode_hash: Some(keccak256("test")), }, BTreeMap::from([ (B256::ZERO, U256::from(3).into()), (B256::with_last_byte(2), U256::from(1).into()), ]), ), ), ]); test_state_root_with_state(state); } #[test] // This ensures we return an empty root when there are no storage entries fn test_empty_storage_root() { let factory = create_test_provider_factory(); let tx = factory.provider_rw().unwrap(); let address = Address::random(); let code = "el buen fla"; let account = Account { nonce: 155, balance: U256::from(414241124u32), bytecode_hash: Some(keccak256(code)), }; insert_account(tx.tx_ref(), address, account, &Default::default()); tx.commit().unwrap(); let tx = factory.provider_rw().unwrap(); let got = StorageRoot::from_tx(tx.tx_ref(), address).root().unwrap(); assert_eq!(got, EMPTY_ROOT_HASH); } #[test] // This ensures that the walker goes over all the storage slots fn test_storage_root() { let factory = create_test_provider_factory(); let tx = factory.provider_rw().unwrap(); let address = Address::random(); let storage = BTreeMap::from([ (B256::ZERO, alloy_primitives::FlaggedStorage::public(U256::from(3))), (B256::with_last_byte(2), alloy_primitives::FlaggedStorage::public(U256::from(1))), ]); let code = "el buen fla"; let account = Account { nonce: 155, balance: U256::from(414241124u32), bytecode_hash: Some(keccak256(code)), }; insert_account(tx.tx_ref(), address, account, &storage); tx.commit().unwrap(); let tx = factory.provider_rw().unwrap(); let got = StorageRoot::from_tx(tx.tx_ref(), address).root().unwrap(); assert_eq!(storage_root(storage.into_iter()), got); } type State = BTreeMap<Address, (Account, BTreeMap<B256, alloy_primitives::FlaggedStorage>)>; #[test] fn arbitrary_state_root() { proptest!( ProptestConfig::with_cases(10), | (state in arb::<State>()) | { test_state_root_with_state(state); } ); } #[test] fn arbitrary_state_root_with_progress() { proptest!( ProptestConfig::with_cases(10), | (state in arb::<State>()) | { let hashed_entries_total = state.len() + state.values().map(|(_, slots)| slots.len()).sum::<usize>(); let factory = create_test_provider_factory(); let tx = factory.provider_rw().unwrap(); for (address, (account, storage)) in &state { insert_account(tx.tx_ref(), *address, *account, storage) } tx.commit().unwrap(); let tx = factory.provider_rw().unwrap(); let expected = state_root_privacy_aware(state); let threshold = 10; let mut got = None; let mut hashed_entries_walked = 0; let mut intermediate_state: Option<Box<IntermediateStateRootState>> = None; while got.is_none() { let calculator = StateRoot::from_tx(tx.tx_ref()) .with_threshold(threshold) .with_intermediate_state(intermediate_state.take().map(|state| *state)); match calculator.root_with_progress().unwrap() { StateRootProgress::Progress(state, walked, _) => { intermediate_state = Some(state); hashed_entries_walked += walked; }, StateRootProgress::Complete(root, walked, _) => { got = Some(root); hashed_entries_walked += walked; }, }; } assert_eq!(expected, got.unwrap()); assert_eq!(hashed_entries_total, hashed_entries_walked) } ); } fn test_state_root_with_state(state: State) { let factory = create_test_provider_factory(); let tx = factory.provider_rw().unwrap(); for (address, (account, storage)) in &state { insert_account(tx.tx_ref(), *address, *account, storage) } tx.commit().unwrap(); let expected = state_root_privacy_aware(state); let tx = factory.provider_rw().unwrap(); let got = StateRoot::from_tx(tx.tx_ref()).root().unwrap(); assert_eq!(expected, got); } fn encode_account(account: Account, storage_root: Option<B256>) -> Vec<u8> { let account = account.into_trie_account(storage_root.unwrap_or(EMPTY_ROOT_HASH)); let mut account_rlp = Vec::with_capacity(account.length()); account.encode(&mut account_rlp); account_rlp } #[test] fn storage_root_regression() { let factory = create_test_provider_factory(); let tx = factory.provider_rw().unwrap(); // Some address whose hash starts with 0xB041 let address3 = address!("0x16b07afd1c635f77172e842a000ead9a2a222459"); let key3 = keccak256(address3); assert_eq!(key3[0], 0xB0); assert_eq!(key3[1], 0x41); let storage = BTreeMap::from( [ ("1200000000000000000000000000000000000000000000000000000000000000", 0x42), ("1400000000000000000000000000000000000000000000000000000000000000", 0x01), ("3000000000000000000000000000000000000000000000000000000000E00000", 0x127a89), ("3000000000000000000000000000000000000000000000000000000000E00001", 0x05), ] .map(|(slot, val)| { (B256::from_str(slot).unwrap(), revm_primitives::FlaggedStorage::public(val)) }), ); let mut hashed_storage_cursor = tx.tx_ref().cursor_dup_write::<tables::HashedStorages>().unwrap(); for (hashed_slot, value) in storage.clone() { hashed_storage_cursor.upsert(key3, &StorageEntry { key: hashed_slot, value }).unwrap(); } tx.commit().unwrap(); let tx = factory.provider_rw().unwrap(); let account3_storage_root = StorageRoot::from_tx(tx.tx_ref(), address3).root().unwrap(); let expected_root = storage_root_prehashed(storage); assert_eq!(expected_root, account3_storage_root); } #[test] fn account_and_storage_trie() { let account_is_private = false; // accounts are always public let ether = U256::from(1e18); let storage = BTreeMap::from( [ ("1200000000000000000000000000000000000000000000000000000000000000", 0x42), ("1400000000000000000000000000000000000000000000000000000000000000", 0x01), ("3000000000000000000000000000000000000000000000000000000000E00000", 0x127a89), ("3000000000000000000000000000000000000000000000000000000000E00001", 0x05), ] .map(|(slot, val)| (B256::from_str(slot).unwrap(), U256::from(val))), ); let factory = create_test_provider_factory(); let tx = factory.provider_rw().unwrap(); let mut hashed_account_cursor = tx.tx_ref().cursor_write::<tables::HashedAccounts>().unwrap(); let mut hashed_storage_cursor = tx.tx_ref().cursor_dup_write::<tables::HashedStorages>().unwrap(); let mut hash_builder = HashBuilder::default(); // Insert first account let key1 = b256!("0xb000000000000000000000000000000000000000000000000000000000000000"); let account1 = Account { nonce: 0, balance: U256::from(3).mul(ether), bytecode_hash: None }; hashed_account_cursor.upsert(key1, &account1).unwrap(); hash_builder.add_leaf( Nibbles::unpack(key1), &encode_account(account1, None), account_is_private, ); // Some address whose hash starts with 0xB040 let address2 = address!("0x7db3e81b72d2695e19764583f6d219dbee0f35ca"); let key2 = keccak256(address2); assert_eq!(key2[0], 0xB0); assert_eq!(key2[1], 0x40); let account2 = Account { nonce: 0, balance: ether, ..Default::default() }; hashed_account_cursor.upsert(key2, &account2).unwrap(); hash_builder.add_leaf( Nibbles::unpack(key2), &encode_account(account2, None), account_is_private, ); // Some address whose hash starts with 0xB041 let address3 = address!("0x16b07afd1c635f77172e842a000ead9a2a222459"); let key3 = keccak256(address3); assert_eq!(key3[0], 0xB0); assert_eq!(key3[1], 0x41); let code_hash = b256!("0x5be74cad16203c4905c068b012a2e9fb6d19d036c410f16fd177f337541440dd"); let account3 = Account { nonce: 0, balance: U256::from(2).mul(ether), bytecode_hash: Some(code_hash) }; hashed_account_cursor.upsert(key3, &account3).unwrap(); for (hashed_slot, value) in storage { if hashed_storage_cursor .seek_by_key_subkey(key3, hashed_slot) .unwrap() .filter(|e| e.key == hashed_slot) .is_some() { hashed_storage_cursor.delete_current().unwrap(); } hashed_storage_cursor .upsert( key3, &StorageEntry { key: hashed_slot, value: alloy_primitives::FlaggedStorage::public(value), }, ) .unwrap(); } let account3_storage_root = StorageRoot::from_tx(tx.tx_ref(), address3).root().unwrap(); hash_builder.add_leaf( Nibbles::unpack(key3), &encode_account(account3, Some(account3_storage_root)), account_is_private, ); let key4a = b256!("0xB1A0000000000000000000000000000000000000000000000000000000000000"); let account4a = Account { nonce: 0, balance: U256::from(4).mul(ether), ..Default::default() }; hashed_account_cursor.upsert(key4a, &account4a).unwrap(); hash_builder.add_leaf( Nibbles::unpack(key4a), &encode_account(account4a, None), account_is_private, ); let key5 = b256!("0xB310000000000000000000000000000000000000000000000000000000000000"); let account5 = Account { nonce: 0, balance: U256::from(8).mul(ether), ..Default::default() }; hashed_account_cursor.upsert(key5, &account5).unwrap(); hash_builder.add_leaf( Nibbles::unpack(key5), &encode_account(account5, None), account_is_private, ); let key6 = b256!("0xB340000000000000000000000000000000000000000000000000000000000000"); let account6 = Account { nonce: 0, balance: U256::from(1).mul(ether), ..Default::default() }; hashed_account_cursor.upsert(key6, &account6).unwrap(); hash_builder.add_leaf( Nibbles::unpack(key6), &encode_account(account6, None), account_is_private, ); // Populate account & storage trie DB tables /* let expected_root = b256!("0x72861041bc90cd2f93777956f058a545412b56de79af5eb6b8075fe2eabbe015"); */ let expected_root = b256!("0xf7eac2e1715b2cf20e7d731df7a6cadf6602bac6f66de747c7eb929930c3e976"); let computed_expected_root: B256 = triehash::trie_root::<KeccakHasher, _, _, _>([ (key1, encode_account(account1, None)), (key2, encode_account(account2, None)), (key3, encode_account(account3, Some(account3_storage_root))), (key4a, encode_account(account4a, None)), (key5, encode_account(account5, None)), (key6, encode_account(account6, None)), ]); // Check computed trie root to ensure correctness assert_eq!(computed_expected_root, expected_root); // Check hash builder root assert_eq!(hash_builder.root(), computed_expected_root); // Check state root calculation from scratch let (root, trie_updates) = StateRoot::from_tx(tx.tx_ref()).root_with_updates().unwrap(); assert_eq!(root, computed_expected_root); // Check account trie let account_updates = trie_updates.into_sorted(); let account_updates = account_updates.account_nodes_ref(); assert_eq!(account_updates.len(), 2); let (nibbles1a, node1a) = account_updates.first().unwrap(); assert_eq!(nibbles1a.to_vec(), vec![0xB]); assert_eq!(node1a.state_mask, TrieMask::new(0b1011)); assert_eq!(node1a.tree_mask, TrieMask::new(0b0001)); assert_eq!(node1a.hash_mask, TrieMask::new(0b1001)); assert_eq!(node1a.root_hash, None); assert_eq!(node1a.hashes.len(), 2); let (nibbles2a, node2a) = account_updates.last().unwrap(); assert_eq!(nibbles2a.to_vec(), vec![0xB, 0x0]); assert_eq!(node2a.state_mask, TrieMask::new(0b10001)); assert_eq!(node2a.tree_mask, TrieMask::new(0b00000)); assert_eq!(node2a.hash_mask, TrieMask::new(0b10000)); assert_eq!(node2a.root_hash, None); assert_eq!(node2a.hashes.len(), 1); // Add an account // Some address whose hash starts with 0xB1 let address4b = address!("0x4f61f2d5ebd991b85aa1677db97307caf5215c91"); let key4b = keccak256(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(); let mut prefix_set = PrefixSetMut::default(); prefix_set.insert(Nibbles::unpack(key4b)); /* let expected_state_root = b256!("0x8e263cd4eefb0c3cbbb14e5541a66a755cad25bcfab1e10dd9d706263e811b28"); */ let expected_state_root = b256!("0x96372312afd49741fe2e31097b80e1f5f7f9dbb23ad662099c797cb44bf88a12"); let (root, trie_updates) = StateRoot::from_tx(tx.tx_ref()) .with_prefix_sets(TriePrefixSets { account_prefix_set: prefix_set.freeze(), ..Default::default() }) .root_with_updates() .unwrap(); assert_eq!(root, expected_state_root); let account_updates = trie_updates.into_sorted(); let account_updates = account_updates.account_nodes_ref(); assert_eq!(account_updates.len(), 2); let (nibbles1b, node1b) = account_updates.first().unwrap(); assert_eq!(nibbles1b.to_vec(), vec![0xB]); assert_eq!(node1b.state_mask, TrieMask::new(0b1011)); assert_eq!(node1b.tree_mask, TrieMask::new(0b0001)); assert_eq!(node1b.hash_mask, TrieMask::new(0b1011)); assert_eq!(node1b.root_hash, None); assert_eq!(node1b.hashes.len(), 3); assert_eq!(node1a.hashes[0], node1b.hashes[0]); assert_eq!(node1a.hashes[1], node1b.hashes[2]); let (nibbles2b, node2b) = account_updates.last().unwrap(); assert_eq!(nibbles2b.to_vec(), vec![0xB, 0x0]); assert_eq!(node2a, node2b); tx.commit().unwrap(); { let tx = factory.provider_rw().unwrap(); let mut hashed_account_cursor = tx.tx_ref().cursor_write::<tables::HashedAccounts>().unwrap(); let account = hashed_account_cursor.seek_exact(key2).unwrap().unwrap(); hashed_account_cursor.delete_current().unwrap(); let mut account_prefix_set = PrefixSetMut::default(); account_prefix_set.insert(Nibbles::unpack(account.0)); let computed_expected_root: B256 = triehash::trie_root::<KeccakHasher, _, _, _>([ (key1, encode_account(account1, None)), // DELETED: (key2, encode_account(account2, None)), (key3, encode_account(account3, Some(account3_storage_root))), (key4a, encode_account(account4a, None)), (key4b, encode_account(account4b, None)), (key5, encode_account(account5, None)), (key6, encode_account(account6, None)), ]); let (root, trie_updates) = StateRoot::from_tx(tx.tx_ref()) .with_prefix_sets(TriePrefixSets { account_prefix_set: account_prefix_set.freeze(), ..Default::default() }) .root_with_updates() .unwrap(); assert_eq!(root, computed_expected_root); assert_eq!( trie_updates.account_nodes_ref().len() + trie_updates.removed_nodes_ref().len(), 1 ); assert_eq!(trie_updates.account_nodes_ref().len(), 1); let (nibbles1c, node1c) = trie_updates.account_nodes_ref().iter().next().unwrap(); assert_eq!(nibbles1c.to_vec(), vec![0xB]); assert_eq!(node1c.state_mask, TrieMask::new(0b1011)); assert_eq!(node1c.tree_mask, TrieMask::new(0b0000)); assert_eq!(node1c.hash_mask, TrieMask::new(0b1011)); assert_eq!(node1c.root_hash, None); assert_eq!(node1c.hashes.len(), 3); assert_ne!(node1c.hashes[0], node1b.hashes[0]); assert_eq!(node1c.hashes[1], node1b.hashes[1]); assert_eq!(node1c.hashes[2], node1b.hashes[2]); } { let tx = factory.provider_rw().unwrap(); let mut hashed_account_cursor = tx.tx_ref().cursor_write::<tables::HashedAccounts>().unwrap(); let account2 = hashed_account_cursor.seek_exact(key2).unwrap().unwrap(); hashed_account_cursor.delete_current().unwrap(); let account3 = hashed_account_cursor.seek_exact(key3).unwrap().unwrap(); hashed_account_cursor.delete_current().unwrap(); let mut account_prefix_set = PrefixSetMut::default(); account_prefix_set.insert(Nibbles::unpack(account2.0)); account_prefix_set.insert(Nibbles::unpack(account3.0)); let computed_expected_root: B256 = triehash::trie_root::<KeccakHasher, _, _, _>([ (key1, encode_account(account1, None)), // DELETED: (key2, encode_account(account2, None)), // DELETED: (key3, encode_account(account3, Some(account3_storage_root))), (key4a, encode_account(account4a, None)), (key4b, encode_account(account4b, None)), (key5, encode_account(account5, None)), (key6, encode_account(account6, None)), ]); let (root, trie_updates) = StateRoot::from_tx(tx.tx_ref()) .with_prefix_sets(TriePrefixSets { account_prefix_set: account_prefix_set.freeze(), ..Default::default() }) .root_with_updates() .unwrap(); assert_eq!(root, computed_expected_root); assert_eq!( trie_updates.account_nodes_ref().len() + trie_updates.removed_nodes_ref().len(), 1 ); assert!(!trie_updates .storage_tries_ref() .iter() .any(|(_, u)| !u.storage_nodes_ref().is_empty() || !u.removed_nodes_ref().is_empty())); // no storage root update assert_eq!(trie_updates.account_nodes_ref().len(), 1); let (nibbles1d, node1d) = trie_updates.account_nodes_ref().iter().next().unwrap(); assert_eq!(nibbles1d.to_vec(), vec![0xB]); assert_eq!(node1d.state_mask, TrieMask::new(0b1011)); assert_eq!(node1d.tree_mask, TrieMask::new(0b0000)); assert_eq!(node1d.hash_mask, TrieMask::new(0b1010)); assert_eq!(node1d.root_hash, None); assert_eq!(node1d.hashes.len(), 2); assert_eq!(node1d.hashes[0], node1b.hashes[1]); assert_eq!(node1d.hashes[1], node1b.hashes[2]); } } #[test] fn account_trie_around_extension_node() { let factory = create_test_provider_factory(); let tx = factory.provider_rw().unwrap(); let expected = extension_node_trie(&tx); let (got, updates) = StateRoot::from_tx(tx.tx_ref()).root_with_updates().unwrap(); assert_eq!(expected, got); assert_trie_updates(updates.account_nodes_ref()); } #[test] fn account_trie_around_extension_node_with_dbtrie() { let factory = create_test_provider_factory(); let tx = factory.provider_rw().unwrap(); let expected = extension_node_trie(&tx); let (got, updates) = StateRoot::from_tx(tx.tx_ref()).root_with_updates().unwrap(); assert_eq!(expected, got); tx.write_trie_updates(&updates).unwrap(); // read the account updates from the db let mut accounts_trie = tx.tx_ref().cursor_read::<tables::AccountsTrie>().unwrap(); let walker = accounts_trie.walk(None).unwrap(); let account_updates = walker .into_iter() .map(|item| { let (key, node) = item.unwrap(); (key.0, node) }) .collect(); assert_trie_updates(&account_updates); } proptest! { #![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })] #[test] fn fuzz_state_root_incremental(account_changes: [BTreeMap<B256, U256>; 5]) { let factory = create_test_provider_factory(); let tx = factory.provider_rw().unwrap(); let mut hashed_account_cursor = tx.tx_ref().cursor_write::<tables::HashedAccounts>().unwrap(); let mut state = BTreeMap::default(); for accounts in account_changes { let should_generate_changeset = !state.is_empty(); let mut changes = PrefixSetMut::default(); for (hashed_address, balance) in accounts.clone() { hashed_account_cursor.upsert(hashed_address, &Account { balance, ..Default::default() }).unwrap(); if should_generate_changeset { changes.insert(Nibbles::unpack(hashed_address)); } } let (state_root, trie_updates) = StateRoot::from_tx(tx.tx_ref()) .with_prefix_sets(TriePrefixSets { account_prefix_set: changes.freeze(), ..Default::default() }) .root_with_updates() .unwrap(); state.append(&mut accounts.clone()); let expected_root = state_root_prehashed( state.iter().map(|(&key, &balance)| (key, (Account { balance, ..Default::default() }, std::iter::empty()))) ); assert_eq!(expected_root, state_root); tx.write_trie_updates(&trie_updates).unwrap(); } } } #[test] fn storage_trie_around_extension_node() { let factory = create_test_provider_factory(); let tx = factory.provider_rw().unwrap(); let hashed_address = B256::random(); let (expected_root, expected_updates) = extension_node_storage_trie(&tx, hashed_address); let (got, _, updates) = StorageRoot::from_tx_hashed(tx.tx_ref(), hashed_address).root_with_updates().unwrap(); assert_eq!(expected_root, got); assert_eq!(expected_updates, updates); assert_trie_updates(updates.storage_nodes_ref()); } fn extension_node_storage_trie<N: ProviderNodeTypes>( tx: &DatabaseProviderRW<Arc<TempDatabase<DatabaseEnv>>, N>, hashed_address: B256, ) -> (B256, StorageTrieUpdates) { let value = U256::from(1).into(); let mut hashed_storage = tx.tx_ref().cursor_write::<tables::HashedStorages>().unwrap(); let mut hb = HashBuilder::default().with_updates(true); for key in [ hex!("30af561000000000000000000000000000000000000000000000000000000000"), hex!("30af569000000000000000000000000000000000000000000000000000000000"), hex!("30af650000000000000000000000000000000000000000000000000000000000"), hex!("30af6f0000000000000000000000000000000000000000000000000000000000"), hex!("30af8f0000000000000000000000000000000000000000000000000000000000"), hex!("3100000000000000000000000000000000000000000000000000000000000000"), ] { hashed_storage .upsert(hashed_address, &StorageEntry { key: B256::new(key), value }) .unwrap(); hb.add_leaf(Nibbles::unpack(key), &alloy_rlp::encode_fixed_size(&value), value.is_private); } let root = hb.root(); let (_, updates) = hb.split(); let trie_updates = StorageTrieUpdates::new(updates); (root, trie_updates) } fn extension_node_trie<N: ProviderNodeTypes>( tx: &DatabaseProviderRW<Arc<TempDatabase<DatabaseEnv>>, N>, ) -> B256 { let a = Account { nonce: 0, balance: U256::from(1u64), bytecode_hash: Some(B256::random()) }; let val = encode_account(a, None); let mut hashed_accounts = tx.tx_ref().cursor_write::<tables::HashedAccounts>().unwrap(); let mut hb = HashBuilder::default(); for key in [ hex!("30af561000000000000000000000000000000000000000000000000000000000"), hex!("30af569000000000000000000000000000000000000000000000000000000000"), hex!("30af650000000000000000000000000000000000000000000000000000000000"), hex!("30af6f0000000000000000000000000000000000000000000000000000000000"), hex!("30af8f0000000000000000000000000000000000000000000000000000000000"), hex!("3100000000000000000000000000000000000000000000000000000000000000"), ] { hashed_accounts.upsert(B256::new(key), &a).unwrap(); hb.add_leaf(Nibbles::unpack(key), &val, false); // account leaves are always public } hb.root() } fn assert_trie_updates(account_updates: &HashMap<Nibbles, BranchNodeCompact>) { assert_eq!(account_updates.len(), 2); let node = account_updates.get(&Nibbles::from_nibbles_unchecked([0x3])).unwrap(); let expected = BranchNodeCompact::new(0b0011, 0b0001, 0b0000, vec![], None); assert_eq!(node, &expected); let node = account_updates.get(&Nibbles::from_nibbles_unchecked([0x3, 0x0, 0xA, 0xF])).unwrap(); assert_eq!(node.state_mask, TrieMask::new(0b101100000)); assert_eq!(node.tree_mask, TrieMask::new(0b000000000)); assert_eq!(node.hash_mask, TrieMask::new(0b001000000)); assert_eq!(node.root_hash, None); assert_eq!(node.hashes.len(), 1); }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/sparse/src/lib.rs
crates/trie/sparse/src/lib.rs
//! The implementation of sparse MPT. #![cfg_attr(not(test), warn(unused_crate_dependencies))] #![cfg_attr(not(feature = "std"), no_std)] extern crate alloc; mod state; pub use state::*; mod trie; pub use trie::*; mod traits; pub use traits::*; pub mod provider; #[cfg(feature = "metrics")] mod metrics; /// Re-export sparse trie error types. pub mod errors { pub use reth_execution_errors::{ SparseStateTrieError, SparseStateTrieErrorKind, SparseStateTrieResult, SparseTrieError, SparseTrieErrorKind, SparseTrieResult, }; }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/sparse/src/state.rs
crates/trie/sparse/src/state.rs
use crate::{ provider::{TrieNodeProvider, TrieNodeProviderFactory}, traits::SparseTrieInterface, RevealedSparseNode, SerialSparseTrie, SparseTrie, TrieMasks, }; use alloc::{collections::VecDeque, vec::Vec}; use alloy_primitives::{ map::{B256Map, HashMap, HashSet}, Bytes, B256, }; use alloy_rlp::{Decodable, Encodable}; use alloy_trie::proof::DecodedProofNodes; use reth_execution_errors::{SparseStateTrieErrorKind, SparseStateTrieResult, SparseTrieErrorKind}; use reth_primitives_traits::Account; use reth_trie_common::{ proof::ProofNodes, updates::{StorageTrieUpdates, TrieUpdates}, DecodedMultiProof, DecodedStorageMultiProof, MultiProof, Nibbles, RlpNode, StorageMultiProof, TrieAccount, TrieMask, TrieNode, EMPTY_ROOT_HASH, TRIE_ACCOUNT_RLP_MAX_SIZE, }; use tracing::trace; /// Provides type-safe re-use of cleared [`SparseStateTrie`]s, which helps to save allocations /// across payload runs. #[derive(Debug)] pub struct ClearedSparseStateTrie< A = SerialSparseTrie, // Account trie implementation S = SerialSparseTrie, // Storage trie implementation >(SparseStateTrie<A, S>); impl<A, S> ClearedSparseStateTrie<A, S> where A: SparseTrieInterface + Default, S: SparseTrieInterface + Default, { /// Creates a [`ClearedSparseStateTrie`] by clearing all the existing internal state of a /// [`SparseStateTrie`] and then storing that instance for later re-use. pub fn from_state_trie(mut trie: SparseStateTrie<A, S>) -> Self { trie.state = trie.state.clear(); trie.revealed_account_paths.clear(); trie.storage.clear(); trie.account_rlp_buf.clear(); Self(trie) } /// Returns the cleared [`SparseStateTrie`], consuming this instance. pub fn into_inner(self) -> SparseStateTrie<A, S> { self.0 } } #[derive(Debug)] /// Sparse state trie representing lazy-loaded Ethereum state trie. pub struct SparseStateTrie< A = SerialSparseTrie, // Account trie implementation S = SerialSparseTrie, // Storage trie implementation > { /// Sparse account trie. state: SparseTrie<A>, /// Collection of revealed account trie paths. revealed_account_paths: HashSet<Nibbles>, /// State related to storage tries. storage: StorageTries<S>, /// Flag indicating whether trie updates should be retained. retain_updates: bool, /// Reusable buffer for RLP encoding of trie accounts. account_rlp_buf: Vec<u8>, /// Metrics for the sparse state trie. #[cfg(feature = "metrics")] metrics: crate::metrics::SparseStateTrieMetrics, } impl<A, S> Default for SparseStateTrie<A, S> where A: Default, S: Default, { fn default() -> Self { Self { state: Default::default(), revealed_account_paths: Default::default(), storage: Default::default(), retain_updates: false, account_rlp_buf: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE), #[cfg(feature = "metrics")] metrics: Default::default(), } } } #[cfg(test)] impl SparseStateTrie { /// Create state trie from state trie. pub fn from_state(state: SparseTrie) -> Self { Self { state, ..Default::default() } } } impl<A, S> SparseStateTrie<A, S> { /// Set the retention of branch node updates and deletions. pub const fn with_updates(mut self, retain_updates: bool) -> Self { self.retain_updates = retain_updates; self } /// Set the accounts trie to the given `SparseTrie`. pub fn with_accounts_trie(mut self, trie: SparseTrie<A>) -> Self { self.state = trie; self } } impl<A, S> SparseStateTrie<A, S> where A: SparseTrieInterface + Default, S: SparseTrieInterface + Default, { /// Create new [`SparseStateTrie`] pub fn new() -> Self { Self::default() } /// Returns `true` if account was already revealed. pub fn is_account_revealed(&self, account: B256) -> bool { self.revealed_account_paths.contains(&Nibbles::unpack(account)) } /// Was the account witness for `address` complete? pub fn check_valid_account_witness(&self, address: B256) -> bool { let path = Nibbles::unpack(address); let trie = match self.state_trie_ref() { Some(t) => t, None => return false, }; trie.find_leaf(&path, None).is_ok() } /// Was the storage-slot witness for (`address`,`slot`) complete? pub fn check_valid_storage_witness(&self, address: B256, slot: B256) -> bool { let path = Nibbles::unpack(slot); let trie = match self.storage_trie_ref(&address) { Some(t) => t, None => return false, }; trie.find_leaf(&path, None).is_ok() } /// Returns `true` if storage slot for account was already revealed. pub fn is_storage_slot_revealed(&self, account: B256, slot: B256) -> bool { self.storage .revealed_paths .get(&account) .is_some_and(|slots| slots.contains(&Nibbles::unpack(slot))) } /// Returns reference to bytes representing leaf value for the target account. pub fn get_account_value(&self, account: &B256) -> Option<&Vec<u8>> { self.state.as_revealed_ref()?.get_leaf_value(&Nibbles::unpack(account)) } /// Returns reference to bytes representing leaf value for the target account and storage slot. pub fn get_storage_slot_value(&self, account: &B256, slot: &B256) -> Option<&Vec<u8>> { self.storage.tries.get(account)?.as_revealed_ref()?.get_leaf_value(&Nibbles::unpack(slot)) } /// Returns reference to state trie if it was revealed. pub const fn state_trie_ref(&self) -> Option<&A> { self.state.as_revealed_ref() } /// Returns reference to storage trie if it was revealed. pub fn storage_trie_ref(&self, address: &B256) -> Option<&S> { self.storage.tries.get(address).and_then(|e| e.as_revealed_ref()) } /// Returns mutable reference to storage sparse trie if it was revealed. pub fn storage_trie_mut(&mut self, address: &B256) -> Option<&mut S> { self.storage.tries.get_mut(address).and_then(|e| e.as_revealed_mut()) } /// Takes the storage trie for the provided address. pub fn take_storage_trie(&mut self, address: &B256) -> Option<SparseTrie<S>> { self.storage.tries.remove(address) } /// Inserts storage trie for the provided address. pub fn insert_storage_trie(&mut self, address: B256, storage_trie: SparseTrie<S>) { self.storage.tries.insert(address, storage_trie); } /// Reveal unknown trie paths from multiproof. /// NOTE: This method does not extensively validate the proof. pub fn reveal_multiproof(&mut self, multiproof: MultiProof) -> SparseStateTrieResult<()> { // first decode the multiproof let decoded_multiproof = multiproof.try_into()?; // then reveal the decoded multiproof self.reveal_decoded_multiproof(decoded_multiproof) } /// Reveal unknown trie paths from decoded multiproof. /// NOTE: This method does not extensively validate the proof. pub fn reveal_decoded_multiproof( &mut self, multiproof: DecodedMultiProof, ) -> SparseStateTrieResult<()> { let DecodedMultiProof { account_subtree, storages, branch_node_hash_masks, branch_node_tree_masks, } = multiproof; // first reveal the account proof nodes self.reveal_decoded_account_multiproof( account_subtree, branch_node_hash_masks, branch_node_tree_masks, )?; #[cfg(not(feature = "std"))] // If nostd then serially reveal storage proof nodes for each storage trie { for (account, storage_subtree) in storages { self.reveal_decoded_storage_multiproof(account, storage_subtree)?; } Ok(()) } #[cfg(feature = "std")] // If std then reveal storage proofs in parallel { use rayon::iter::{ParallelBridge, ParallelIterator}; let (tx, rx) = std::sync::mpsc::channel(); let retain_updates = self.retain_updates; // Process all storage trie revealings in parallel, having first removed the // `reveal_nodes` tracking and `SparseTrie`s for each account from their HashMaps. // These will be returned after processing. storages .into_iter() .map(|(account, storage_subtree)| { let revealed_nodes = self.storage.take_or_create_revealed_paths(&account); let trie = self.storage.take_or_create_trie(&account); (account, storage_subtree, revealed_nodes, trie) }) .par_bridge() .map(|(account, storage_subtree, mut revealed_nodes, mut trie)| { let result = Self::reveal_decoded_storage_multiproof_inner( account, storage_subtree, &mut revealed_nodes, &mut trie, retain_updates, ); (account, revealed_nodes, trie, result) }) .for_each_init(|| tx.clone(), |tx, result| tx.send(result).unwrap()); drop(tx); // Return `revealed_nodes` and `SparseTrie` for each account, incrementing metrics and // returning the last error seen if any. let mut any_err = Ok(()); for (account, revealed_nodes, trie, result) in rx { self.storage.revealed_paths.insert(account, revealed_nodes); self.storage.tries.insert(account, trie); if let Ok(_metric_values) = result { #[cfg(feature = "metrics")] { self.metrics .increment_total_storage_nodes(_metric_values.total_nodes as u64); self.metrics .increment_skipped_storage_nodes(_metric_values.skipped_nodes as u64); } } else { any_err = result.map(|_| ()); } } any_err } } /// Reveals an account multiproof. pub fn reveal_account_multiproof( &mut self, account_subtree: ProofNodes, branch_node_hash_masks: HashMap<Nibbles, TrieMask>, branch_node_tree_masks: HashMap<Nibbles, TrieMask>, ) -> SparseStateTrieResult<()> { // decode the multiproof first let decoded_multiproof = account_subtree.try_into()?; self.reveal_decoded_account_multiproof( decoded_multiproof, branch_node_hash_masks, branch_node_tree_masks, ) } /// Reveals a decoded account multiproof. pub fn reveal_decoded_account_multiproof( &mut self, account_subtree: DecodedProofNodes, branch_node_hash_masks: HashMap<Nibbles, TrieMask>, branch_node_tree_masks: HashMap<Nibbles, TrieMask>, ) -> SparseStateTrieResult<()> { let FilterMappedProofNodes { root_node, nodes, new_nodes, metric_values: _metric_values } = filter_map_revealed_nodes( account_subtree, &mut self.revealed_account_paths, &branch_node_hash_masks, &branch_node_tree_masks, )?; #[cfg(feature = "metrics")] { self.metrics.increment_total_account_nodes(_metric_values.total_nodes as u64); self.metrics.increment_skipped_account_nodes(_metric_values.skipped_nodes as u64); } if let Some(root_node) = root_node { // Reveal root node if it wasn't already. trace!(target: "trie::sparse", ?root_node, "Revealing root account node"); let trie = self.state.reveal_root(root_node.node, root_node.masks, self.retain_updates)?; // Reserve the capacity for new nodes ahead of time, if the trie implementation // supports doing so. trie.reserve_nodes(new_nodes); trace!(target: "trie::sparse", total_nodes = ?nodes.len(), "Revealing account nodes"); trie.reveal_nodes(nodes)?; } Ok(()) } /// Reveals a storage multiproof for the given address. pub fn reveal_storage_multiproof( &mut self, account: B256, storage_subtree: StorageMultiProof, ) -> SparseStateTrieResult<()> { // decode the multiproof first let decoded_multiproof = storage_subtree.try_into()?; self.reveal_decoded_storage_multiproof(account, decoded_multiproof) } /// Reveals a decoded storage multiproof for the given address. pub fn reveal_decoded_storage_multiproof( &mut self, account: B256, storage_subtree: DecodedStorageMultiProof, ) -> SparseStateTrieResult<()> { let (trie, revealed_paths) = self.storage.get_trie_and_revealed_paths_mut(account); let _metric_values = Self::reveal_decoded_storage_multiproof_inner( account, storage_subtree, revealed_paths, trie, self.retain_updates, )?; #[cfg(feature = "metrics")] { self.metrics.increment_total_storage_nodes(_metric_values.total_nodes as u64); self.metrics.increment_skipped_storage_nodes(_metric_values.skipped_nodes as u64); } Ok(()) } /// Reveals a decoded storage multiproof for the given address. This is internal static function /// is designed to handle a variety of associated public functions. fn reveal_decoded_storage_multiproof_inner( account: B256, storage_subtree: DecodedStorageMultiProof, revealed_nodes: &mut HashSet<Nibbles>, trie: &mut SparseTrie<S>, retain_updates: bool, ) -> SparseStateTrieResult<ProofNodesMetricValues> { let FilterMappedProofNodes { root_node, nodes, new_nodes, metric_values } = filter_map_revealed_nodes( storage_subtree.subtree, revealed_nodes, &storage_subtree.branch_node_hash_masks, &storage_subtree.branch_node_tree_masks, )?; if let Some(root_node) = root_node { // Reveal root node if it wasn't already. trace!(target: "trie::sparse", ?account, ?root_node, "Revealing root storage node"); let trie = trie.reveal_root(root_node.node, root_node.masks, retain_updates)?; // Reserve the capacity for new nodes ahead of time, if the trie implementation // supports doing so. trie.reserve_nodes(new_nodes); trace!(target: "trie::sparse", ?account, total_nodes = ?nodes.len(), "Revealing storage nodes"); trie.reveal_nodes(nodes)?; } Ok(metric_values) } /// Reveal state witness with the given state root. /// The state witness is expected to be a map of `keccak(rlp(node)): rlp(node).` /// NOTE: This method does not extensively validate the witness. pub fn reveal_witness( &mut self, state_root: B256, witness: &B256Map<Bytes>, ) -> SparseStateTrieResult<()> { // Create a `(hash, path, maybe_account)` queue for traversing witness trie nodes // starting from the root node. let mut queue = VecDeque::from([(state_root, Nibbles::default(), None)]); while let Some((hash, path, maybe_account)) = queue.pop_front() { // Retrieve the trie node and decode it. let Some(trie_node_bytes) = witness.get(&hash) else { continue }; let trie_node = TrieNode::decode(&mut &trie_node_bytes[..])?; // Push children nodes into the queue. match &trie_node { TrieNode::Branch(branch) => { for (idx, maybe_child) in branch.as_ref().children() { if let Some(child_hash) = maybe_child.and_then(RlpNode::as_hash) { let mut child_path = path; child_path.push_unchecked(idx); queue.push_back((child_hash, child_path, maybe_account)); } } } TrieNode::Extension(ext) => { if let Some(child_hash) = ext.child.as_hash() { let mut child_path = path; child_path.extend(&ext.key); queue.push_back((child_hash, child_path, maybe_account)); } } TrieNode::Leaf(leaf) => { let mut full_path = path; full_path.extend(&leaf.key); if maybe_account.is_none() { let hashed_address = B256::from_slice(&full_path.pack()); let account = TrieAccount::decode(&mut &leaf.value[..])?; if account.storage_root != EMPTY_ROOT_HASH { queue.push_back(( account.storage_root, Nibbles::default(), Some(hashed_address), )); } } } TrieNode::EmptyRoot => {} // nothing to do here }; // Reveal the node itself. if let Some(account) = maybe_account { // Check that the path was not already revealed. if self .storage .revealed_paths .get(&account) .is_none_or(|paths| !paths.contains(&path)) { let retain_updates = self.retain_updates; let (storage_trie_entry, revealed_storage_paths) = self.storage.get_trie_and_revealed_paths_mut(account); if path.is_empty() { // Handle special storage state root node case. storage_trie_entry.reveal_root( trie_node, TrieMasks::none(), retain_updates, )?; } else { // Reveal non-root storage trie node. storage_trie_entry .as_revealed_mut() .ok_or(SparseTrieErrorKind::Blind)? .reveal_node(path, trie_node, TrieMasks::none())?; } // Track the revealed path. revealed_storage_paths.insert(path); } } // Check that the path was not already revealed. else if !self.revealed_account_paths.contains(&path) { if path.is_empty() { // Handle special state root node case. self.state.reveal_root(trie_node, TrieMasks::none(), self.retain_updates)?; } else { // Reveal non-root state trie node. self.state.as_revealed_mut().ok_or(SparseTrieErrorKind::Blind)?.reveal_node( path, trie_node, TrieMasks::none(), )?; } // Track the revealed path. self.revealed_account_paths.insert(path); } } Ok(()) } /// Wipe the storage trie at the provided address. pub fn wipe_storage(&mut self, address: B256) -> SparseStateTrieResult<()> { if let Some(trie) = self.storage.tries.get_mut(&address) { trie.wipe()?; } Ok(()) } /// Calculates the hashes of subtries. /// /// If the trie has not been revealed, this function does nothing. pub fn calculate_subtries(&mut self) { if let SparseTrie::Revealed(trie) = &mut self.state { trie.update_subtrie_hashes(); } } /// Returns storage sparse trie root if the trie has been revealed. pub fn storage_root(&mut self, account: B256) -> Option<B256> { self.storage.tries.get_mut(&account).and_then(|trie| trie.root()) } /// Returns mutable reference to the revealed account sparse trie. /// /// If the trie is not revealed yet, its root will be revealed using the trie node provider. fn revealed_trie_mut( &mut self, provider_factory: impl TrieNodeProviderFactory, ) -> SparseStateTrieResult<&mut A> { match self.state { SparseTrie::Blind(_) => { let (root_node, hash_mask, tree_mask) = provider_factory .account_node_provider() .trie_node(&Nibbles::default())? .map(|node| { TrieNode::decode(&mut &node.node[..]) .map(|decoded| (decoded, node.hash_mask, node.tree_mask)) }) .transpose()? .unwrap_or((TrieNode::EmptyRoot, None, None)); self.state .reveal_root(root_node, TrieMasks { hash_mask, tree_mask }, self.retain_updates) .map_err(Into::into) } SparseTrie::Revealed(ref mut trie) => Ok(trie), } } /// Returns sparse trie root. /// /// If the trie has not been revealed, this function reveals the root node and returns its hash. pub fn root( &mut self, provider_factory: impl TrieNodeProviderFactory, ) -> SparseStateTrieResult<B256> { // record revealed node metrics #[cfg(feature = "metrics")] self.metrics.record(); Ok(self.revealed_trie_mut(provider_factory)?.root()) } /// Returns sparse trie root and trie updates if the trie has been revealed. pub fn root_with_updates( &mut self, provider_factory: impl TrieNodeProviderFactory, ) -> SparseStateTrieResult<(B256, TrieUpdates)> { // record revealed node metrics #[cfg(feature = "metrics")] self.metrics.record(); let storage_tries = self.storage_trie_updates(); let revealed = self.revealed_trie_mut(provider_factory)?; let (root, updates) = (revealed.root(), revealed.take_updates()); let updates = TrieUpdates { account_nodes: updates.updated_nodes, removed_nodes: updates.removed_nodes, storage_tries, }; Ok((root, updates)) } /// Returns storage trie updates for tries that have been revealed. /// /// Panics if any of the storage tries are not revealed. pub fn storage_trie_updates(&mut self) -> B256Map<StorageTrieUpdates> { self.storage .tries .iter_mut() .map(|(address, trie)| { let trie = trie.as_revealed_mut().unwrap(); let updates = trie.take_updates(); let updates = StorageTrieUpdates { is_deleted: updates.wiped, storage_nodes: updates.updated_nodes, removed_nodes: updates.removed_nodes, }; (*address, updates) }) .filter(|(_, updates)| !updates.is_empty()) .collect() } /// Returns [`TrieUpdates`] by taking the updates from the revealed sparse tries. /// /// Returns `None` if the accounts trie is not revealed. pub fn take_trie_updates(&mut self) -> Option<TrieUpdates> { let storage_tries = self.storage_trie_updates(); self.state.as_revealed_mut().map(|state| { let updates = state.take_updates(); TrieUpdates { account_nodes: updates.updated_nodes, removed_nodes: updates.removed_nodes, storage_tries, } }) } /// Update the account leaf node. pub fn update_account_leaf( &mut self, path: Nibbles, value: Vec<u8>, provider_factory: impl TrieNodeProviderFactory, ) -> SparseStateTrieResult<()> { if !self.revealed_account_paths.contains(&path) { self.revealed_account_paths.insert(path); } let is_private = false; // account leaves are always public. Their storage leaves can be private. let provider = provider_factory.account_node_provider(); self.state.update_leaf(path, value, is_private, provider)?; Ok(()) } /// Update the leaf node of a revealed storage trie at the provided address. pub fn update_storage_leaf( &mut self, address: B256, slot: Nibbles, value: Vec<u8>, is_private: bool, provider_factory: impl TrieNodeProviderFactory, ) -> SparseStateTrieResult<()> { let provider = provider_factory.storage_node_provider(address); self.storage .tries .get_mut(&address) .ok_or(SparseTrieErrorKind::Blind)? .update_leaf(slot, value, is_private, provider)?; self.storage.get_revealed_paths_mut(address).insert(slot); Ok(()) } /// Update or remove trie account based on new account info. This method will either recompute /// the storage root based on update storage trie or look it up from existing leaf value. /// /// Returns false if the new account info and storage trie are empty, indicating the account /// leaf should be removed. pub fn update_account( &mut self, address: B256, account: Account, provider_factory: impl TrieNodeProviderFactory, ) -> SparseStateTrieResult<bool> { let storage_root = if let Some(storage_trie) = self.storage.tries.get_mut(&address) { trace!(target: "trie::sparse", ?address, "Calculating storage root to update account"); storage_trie.root().ok_or(SparseTrieErrorKind::Blind)? } else if self.is_account_revealed(address) { trace!(target: "trie::sparse", ?address, "Retrieving storage root from account leaf to update account"); // The account was revealed, either... if let Some(value) = self.get_account_value(&address) { // ..it exists and we should take its current storage root or... TrieAccount::decode(&mut &value[..])?.storage_root } else { // ...the account is newly created and the storage trie is empty. EMPTY_ROOT_HASH } } else { return Err(SparseTrieErrorKind::Blind.into()); }; if account.is_empty() && storage_root == EMPTY_ROOT_HASH { return Ok(false); } trace!(target: "trie::sparse", ?address, "Updating account"); let nibbles = Nibbles::unpack(address); self.account_rlp_buf.clear(); account.into_trie_account(storage_root).encode(&mut self.account_rlp_buf); self.update_account_leaf(nibbles, self.account_rlp_buf.clone(), provider_factory)?; Ok(true) } /// Update the storage root of a revealed account. /// /// If the account doesn't exist in the trie, the function is a no-op. /// /// Returns false if the new storage root is empty, and the account info was already empty, /// indicating the account leaf should be removed. pub fn update_account_storage_root( &mut self, address: B256, provider_factory: impl TrieNodeProviderFactory, ) -> SparseStateTrieResult<bool> { if !self.is_account_revealed(address) { return Err(SparseTrieErrorKind::Blind.into()); } // Nothing to update if the account doesn't exist in the trie. let Some(mut trie_account) = self .get_account_value(&address) .map(|v| TrieAccount::decode(&mut &v[..])) .transpose()? else { trace!(target: "trie::sparse", ?address, "Account not found in trie, skipping storage root update"); return Ok(true) }; // Calculate the new storage root. If the storage trie doesn't exist, the storage root will // be empty. let storage_root = if let Some(storage_trie) = self.storage.tries.get_mut(&address) { trace!(target: "trie::sparse", ?address, "Calculating storage root to update account"); storage_trie.root().ok_or(SparseTrieErrorKind::Blind)? } else { EMPTY_ROOT_HASH }; // Update the account with the new storage root. trie_account.storage_root = storage_root; // If the account is empty, indicate that it should be removed. if trie_account == TrieAccount::default() { return Ok(false) } // Otherwise, update the account leaf. trace!(target: "trie::sparse", ?address, "Updating account with the new storage root"); let nibbles = Nibbles::unpack(address); self.account_rlp_buf.clear(); trie_account.encode(&mut self.account_rlp_buf); self.update_account_leaf(nibbles, self.account_rlp_buf.clone(), provider_factory)?; Ok(true) } /// Remove the account leaf node. pub fn remove_account_leaf( &mut self, path: &Nibbles, provider_factory: impl TrieNodeProviderFactory, ) -> SparseStateTrieResult<()> { let provider = provider_factory.account_node_provider(); self.state.remove_leaf(path, provider)?; Ok(()) } /// Update the leaf node of a storage trie at the provided address. pub fn remove_storage_leaf( &mut self, address: B256, slot: &Nibbles, provider_factory: impl TrieNodeProviderFactory, ) -> SparseStateTrieResult<()> { let storage_trie = self.storage.tries.get_mut(&address).ok_or(SparseTrieErrorKind::Blind)?; let provider = provider_factory.storage_node_provider(address); storage_trie.remove_leaf(slot, provider)?; Ok(()) } } /// The fields of [`SparseStateTrie`] related to storage tries. This is kept separate from the rest /// of [`SparseStateTrie`] both to help enforce allocation re-use and to allow us to implement /// methods like `get_trie_and_revealed_paths` which return multiple mutable borrows. #[derive(Debug, Default)] struct StorageTries<S = SerialSparseTrie> { /// Sparse storage tries. tries: B256Map<SparseTrie<S>>, /// Cleared storage tries, kept for re-use. cleared_tries: Vec<SparseTrie<S>>, /// Collection of revealed storage trie paths, per account. revealed_paths: B256Map<HashSet<Nibbles>>, /// Cleared revealed storage trie path collections, kept for re-use. cleared_revealed_paths: Vec<HashSet<Nibbles>>, } impl<S: SparseTrieInterface + Default> StorageTries<S> { /// Returns all fields to a cleared state, equivalent to the default state, keeping cleared /// collections for re-use later when possible. fn clear(&mut self) { self.cleared_tries.extend(self.tries.drain().map(|(_, trie)| trie.clear())); self.cleared_revealed_paths.extend(self.revealed_paths.drain().map(|(_, mut set)| { set.clear(); set })); } /// Returns the set of already revealed trie node paths for an account's storage, creating the /// set if it didn't previously exist. fn get_revealed_paths_mut(&mut self, account: B256) -> &mut HashSet<Nibbles> { self.revealed_paths .entry(account) .or_insert_with(|| self.cleared_revealed_paths.pop().unwrap_or_default()) } /// Returns the `SparseTrie` and the set of already revealed trie node paths for an account's /// storage, creating them if they didn't previously exist. fn get_trie_and_revealed_paths_mut( &mut self, account: B256, ) -> (&mut SparseTrie<S>, &mut HashSet<Nibbles>) { let trie = self .tries .entry(account) .or_insert_with(|| self.cleared_tries.pop().unwrap_or_default()); let revealed_paths = self .revealed_paths .entry(account)
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
true
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/sparse/src/metrics.rs
crates/trie/sparse/src/metrics.rs
//! Metrics for the sparse state trie use reth_metrics::{metrics::Histogram, Metrics}; /// Metrics for the sparse state trie #[derive(Default, Debug)] pub(crate) struct SparseStateTrieMetrics { /// Number of account nodes that were skipped during a multiproof reveal due to being redundant /// (i.e. they were already revealed) pub(crate) multiproof_skipped_account_nodes: u64, /// Number of total account nodes, including those that were skipped. pub(crate) multiproof_total_account_nodes: u64, /// Number of storage nodes that were skipped during a multiproof reveal due to being redundant /// (i.e. they were already revealed) pub(crate) multiproof_skipped_storage_nodes: u64, /// Number of total storage nodes, including those that were skipped. pub(crate) multiproof_total_storage_nodes: u64, /// The actual metrics we will record into the histogram pub(crate) histograms: SparseStateTrieHistograms, } impl SparseStateTrieMetrics { /// Record the metrics into the histograms pub(crate) fn record(&mut self) { use core::mem::take; self.histograms .multiproof_skipped_account_nodes .record(take(&mut self.multiproof_skipped_account_nodes) as f64); self.histograms .multiproof_total_account_nodes .record(take(&mut self.multiproof_total_account_nodes) as f64); self.histograms .multiproof_skipped_storage_nodes .record(take(&mut self.multiproof_skipped_storage_nodes) as f64); self.histograms .multiproof_total_storage_nodes .record(take(&mut self.multiproof_total_storage_nodes) as f64); } /// Increment the skipped account nodes counter by the given count pub(crate) const fn increment_skipped_account_nodes(&mut self, count: u64) { self.multiproof_skipped_account_nodes += count; } /// Increment the total account nodes counter by the given count pub(crate) const fn increment_total_account_nodes(&mut self, count: u64) { self.multiproof_total_account_nodes += count; } /// Increment the skipped storage nodes counter by the given count pub(crate) const fn increment_skipped_storage_nodes(&mut self, count: u64) { self.multiproof_skipped_storage_nodes += count; } /// Increment the total storage nodes counter by the given count pub(crate) const fn increment_total_storage_nodes(&mut self, count: u64) { self.multiproof_total_storage_nodes += count; } } /// Metrics for the sparse state trie #[derive(Metrics)] #[metrics(scope = "sparse_state_trie")] pub(crate) struct SparseStateTrieHistograms { /// Histogram of account nodes that were skipped during a multiproof reveal due to being /// redundant (i.e. they were already revealed) pub(crate) multiproof_skipped_account_nodes: Histogram, /// Histogram of total account nodes, including those that were skipped. pub(crate) multiproof_total_account_nodes: Histogram, /// Histogram of storage nodes that were skipped during a multiproof reveal due to being /// redundant (i.e. they were already revealed) pub(crate) multiproof_skipped_storage_nodes: Histogram, /// Histogram of total storage nodes, including those that were skipped. pub(crate) multiproof_total_storage_nodes: Histogram, }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/sparse/src/traits.rs
crates/trie/sparse/src/traits.rs
//! Traits for sparse trie implementations. use core::fmt::Debug; use alloc::{borrow::Cow, vec, vec::Vec}; use alloy_primitives::{ map::{HashMap, HashSet}, B256, }; use alloy_trie::{BranchNodeCompact, TrieMask}; use reth_execution_errors::SparseTrieResult; use reth_trie_common::{Nibbles, TrieNode}; use crate::provider::TrieNodeProvider; /// Trait defining common operations for revealed sparse trie implementations. /// /// This trait abstracts over different sparse trie implementations (serial vs parallel) /// while providing a unified interface for the core trie operations needed by the /// [`crate::SparseTrie`] enum. pub trait SparseTrieInterface: Sized + Debug + Send + Sync { /// Configures the trie to have the given root node revealed. /// /// # Arguments /// /// * `root` - The root node to reveal /// * `masks` - Trie masks for root branch node /// * `retain_updates` - Whether to track updates /// /// # Returns /// /// Self if successful, or an error if revealing fails. /// /// # Panics /// /// May panic if the trie is not new/cleared, and has already revealed nodes. fn with_root( self, root: TrieNode, masks: TrieMasks, retain_updates: bool, ) -> SparseTrieResult<Self>; /// Configures the trie to retain information about updates. /// /// If `retain_updates` is true, the trie will record branch node updates /// and deletions. This information can be used to efficiently update /// an external database. /// /// # Arguments /// /// * `retain_updates` - Whether to track updates /// /// # Returns /// /// Self for method chaining. fn with_updates(self, retain_updates: bool) -> Self; /// Reserves capacity for additional trie nodes. /// /// # Arguments /// /// * `additional` - The number of additional trie nodes to reserve capacity for. fn reserve_nodes(&mut self, _additional: usize) {} /// The single-node version of `reveal_nodes`. /// /// # Returns /// /// `Ok(())` if successful, or an error if the node was not revealed. fn reveal_node( &mut self, path: Nibbles, node: TrieNode, masks: TrieMasks, ) -> SparseTrieResult<()> { self.reveal_nodes(vec![RevealedSparseNode { path, node, masks }]) } /// Reveals one or more trie nodes if they have not been revealed before. /// /// This function decodes trie nodes and inserts them into the trie structure. It handles /// different node types (leaf, extension, branch) by appropriately adding them to the trie and /// recursively revealing their children. /// /// # Arguments /// /// * `nodes` - The nodes to be revealed, each having a path and optional set of branch node /// masks. The nodes will be unsorted. /// /// # Returns /// /// `Ok(())` if successful, or an error if any of the nodes was not revealed. fn reveal_nodes(&mut self, nodes: Vec<RevealedSparseNode>) -> SparseTrieResult<()>; /// Updates the value of a leaf node at the specified path. /// /// If the leaf doesn't exist, it will be created. /// If it does exist, its value will be updated. /// /// # Arguments /// /// * `full_path` - The full path to the leaf /// * `value` - The new value for the leaf /// * `provider` - The trie provider for resolving missing nodes /// /// # Returns /// /// `Ok(())` if successful, or an error if the update failed. fn update_leaf<P: TrieNodeProvider>( &mut self, full_path: Nibbles, value: Vec<u8>, is_private: bool, provider: P, ) -> SparseTrieResult<()>; /// Removes a leaf node at the specified path. /// /// This will also handle collapsing the trie structure as needed /// (e.g., removing branch nodes that become unnecessary). /// /// # Arguments /// /// * `full_path` - The full path to the leaf to remove /// * `provider` - The trie node provider for resolving missing nodes /// /// # Returns /// /// `Ok(())` if successful, or an error if the removal failed. fn remove_leaf<P: TrieNodeProvider>( &mut self, full_path: &Nibbles, provider: P, ) -> SparseTrieResult<()>; /// Calculates and returns the root hash of the trie. /// /// This processes any dirty nodes by updating their RLP encodings /// and returns the root hash. /// /// # Returns /// /// The root hash of the trie. fn root(&mut self) -> B256; /// Recalculates and updates the RLP hashes of subtries deeper than a certain level. The level /// is defined in the implementation. /// /// The root node is considered to be at level 0. This method is useful for optimizing /// hash recalculations after localized changes to the trie structure. fn update_subtrie_hashes(&mut self); /// Retrieves a reference to the leaf value at the specified path. /// /// # Arguments /// /// * `full_path` - The full path to the leaf value /// /// # Returns /// /// A reference to the leaf value stored at the given full path, if it is revealed. /// /// Note: a value can exist in the full trie and this function still returns `None` /// because the value has not been revealed. /// /// Hence a `None` indicates two possibilities: /// - The value does not exists in the trie, so it cannot be revealed /// - The value has not yet been revealed. In order to determine which is true, one would need /// an exclusion proof. fn get_leaf_value(&self, full_path: &Nibbles) -> Option<&Vec<u8>>; /// Attempts to find a leaf node at the specified path. /// /// This method traverses the trie from the root down to the given path, checking /// if a leaf exists at that path. It can be used to verify the existence of a leaf /// or to generate an exclusion proof (proof that a leaf does not exist). /// /// # Parameters /// /// - `full_path`: The path to search for. /// - `expected_value`: Optional expected value. If provided, will verify the leaf value /// matches. /// /// # Returns /// /// - `Ok(LeafLookup::Exists)` if the leaf exists with the expected value. /// - `Ok(LeafLookup::NonExistent)` if the leaf definitely does not exist (exclusion proof). /// - `Err(LeafLookupError)` if the search encountered a blinded node or found a different /// value. fn find_leaf( &self, full_path: &Nibbles, expected_value: Option<&Vec<u8>>, ) -> Result<LeafLookup, LeafLookupError>; /// Returns a reference to the current sparse trie updates. /// /// If no updates have been made/recorded, returns an empty update set. fn updates_ref(&self) -> Cow<'_, SparseTrieUpdates>; /// Consumes and returns the currently accumulated trie updates. /// /// This is useful when you want to apply the updates to an external database /// and then start tracking a new set of updates. /// /// # Returns /// /// The accumulated updates, or an empty set if updates weren't being tracked. fn take_updates(&mut self) -> SparseTrieUpdates; /// Removes all nodes and values from the trie, resetting it to a blank state /// with only an empty root node. This is used when a storage root is deleted. /// /// This should not be used when intending to reuse the trie for a fresh account/storage root; /// use `clear` for that. /// /// Note: All previously tracked changes to the trie are also removed. fn wipe(&mut self); /// This clears all data structures in the sparse trie, keeping the backing data structures /// allocated. A [`crate::SparseNode::Empty`] is inserted at the root. /// /// This is useful for reusing the trie without needing to reallocate memory. fn clear(&mut self); } /// Struct for passing around branch node mask information. /// /// Branch nodes can have up to 16 children (one for each nibble). /// The masks represent which children are stored in different ways: /// - `hash_mask`: Indicates which children are stored as hashes in the database /// - `tree_mask`: Indicates which children are complete subtrees stored in the database /// /// These masks are essential for efficient trie traversal and serialization, as they /// determine how nodes should be encoded and stored on disk. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub struct TrieMasks { /// Branch node hash mask, if any. /// /// When a bit is set, the corresponding child node's hash is stored in the trie. /// /// This mask enables selective hashing of child nodes. pub hash_mask: Option<TrieMask>, /// Branch node tree mask, if any. /// /// When a bit is set, the corresponding child subtree is stored in the database. pub tree_mask: Option<TrieMask>, } impl TrieMasks { /// Helper function, returns both fields `hash_mask` and `tree_mask` as [`None`] pub const fn none() -> Self { Self { hash_mask: None, tree_mask: None } } } /// Tracks modifications to the sparse trie structure. /// /// Maintains references to both modified and pruned/removed branches, enabling /// one to make batch updates to a persistent database. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct SparseTrieUpdates { /// Collection of updated intermediate nodes indexed by full path. pub updated_nodes: HashMap<Nibbles, BranchNodeCompact>, /// Collection of removed intermediate nodes indexed by full path. pub removed_nodes: HashSet<Nibbles>, /// Flag indicating whether the trie was wiped. pub wiped: bool, } /// Error type for a leaf lookup operation #[derive(Debug, Clone, PartialEq, Eq)] pub enum LeafLookupError { /// The path leads to a blinded node, cannot determine if leaf exists. /// This means the witness is not complete. BlindedNode { /// Path to the blinded node. path: Nibbles, /// Hash of the blinded node. hash: B256, }, /// The path leads to a leaf with a different value than expected. /// This means the witness is malformed. ValueMismatch { /// Path to the leaf. path: Nibbles, /// Expected value. expected: Option<Vec<u8>>, /// Actual value found. actual: Vec<u8>, }, } /// Success value for a leaf lookup operation #[derive(Debug, Clone, PartialEq, Eq)] pub enum LeafLookup { /// Leaf exists with expected value. Exists, /// Leaf does not exist (exclusion proof found). NonExistent, } /// Carries all information needed by a sparse trie to reveal a particular node. #[derive(Debug, PartialEq, Eq)] pub struct RevealedSparseNode { /// Path of the node. pub path: Nibbles, /// The node itself. pub node: TrieNode, /// Tree and hash masks for the node, if known. pub masks: TrieMasks, }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/sparse/src/provider.rs
crates/trie/sparse/src/provider.rs
//! Traits and default implementations related to retrieval of blinded trie nodes. use alloy_primitives::{Bytes, B256}; use reth_execution_errors::SparseTrieError; use reth_trie_common::{Nibbles, TrieMask}; /// Factory for instantiating trie node providers. #[auto_impl::auto_impl(&)] pub trait TrieNodeProviderFactory { /// Type capable of fetching blinded account nodes. type AccountNodeProvider: TrieNodeProvider; /// Type capable of fetching blinded storage nodes. type StorageNodeProvider: TrieNodeProvider; /// Returns blinded account node provider. fn account_node_provider(&self) -> Self::AccountNodeProvider; /// Returns blinded storage node provider. fn storage_node_provider(&self, account: B256) -> Self::StorageNodeProvider; } /// Revealed blinded trie node. #[derive(PartialEq, Eq, Clone, Debug)] pub struct RevealedNode { /// Raw trie node. pub node: Bytes, /// Branch node tree mask, if any. pub tree_mask: Option<TrieMask>, /// Branch node hash mask, if any. pub hash_mask: Option<TrieMask>, } /// Trie node provider for retrieving trie nodes. #[auto_impl::auto_impl(&)] pub trait TrieNodeProvider { /// Retrieve trie node by path. fn trie_node(&self, path: &Nibbles) -> Result<Option<RevealedNode>, SparseTrieError>; } /// Default trie node provider factory that creates [`DefaultTrieNodeProviderFactory`]. #[derive(PartialEq, Eq, Clone, Default, Debug)] pub struct DefaultTrieNodeProviderFactory; impl TrieNodeProviderFactory for DefaultTrieNodeProviderFactory { type AccountNodeProvider = DefaultTrieNodeProvider; type StorageNodeProvider = DefaultTrieNodeProvider; fn account_node_provider(&self) -> Self::AccountNodeProvider { DefaultTrieNodeProvider } fn storage_node_provider(&self, _account: B256) -> Self::StorageNodeProvider { DefaultTrieNodeProvider } } /// Default trie node provider that always returns `Ok(None)`. #[derive(PartialEq, Eq, Clone, Default, Debug)] pub struct DefaultTrieNodeProvider; impl TrieNodeProvider for DefaultTrieNodeProvider { fn trie_node(&self, _path: &Nibbles) -> Result<Option<RevealedNode>, SparseTrieError> { Ok(None) } } /// Right pad the path with 0s and return as [`B256`]. #[inline] pub fn pad_path_to_key(path: &Nibbles) -> B256 { let mut padded = path.pack(); padded.resize(32, 0); B256::from_slice(&padded) }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/sparse/src/trie.rs
crates/trie/sparse/src/trie.rs
use crate::{ provider::{RevealedNode, TrieNodeProvider}, LeafLookup, LeafLookupError, RevealedSparseNode, SparseTrieInterface, SparseTrieUpdates, TrieMasks, }; use alloc::{ borrow::Cow, boxed::Box, fmt, string::{String, ToString}, vec, vec::Vec, }; use alloy_primitives::{ hex, keccak256, map::{Entry, HashMap, HashSet}, B256, }; use alloy_rlp::Decodable; use reth_execution_errors::{SparseTrieErrorKind, SparseTrieResult}; use reth_trie_common::{ prefix_set::{PrefixSet, PrefixSetMut}, BranchNodeCompact, BranchNodeRef, ExtensionNodeRef, LeafNodeRef, Nibbles, RlpNode, TrieMask, TrieNode, CHILD_INDEX_RANGE, EMPTY_ROOT_HASH, }; use smallvec::SmallVec; use tracing::{debug, trace}; /// The level below which the sparse trie hashes are calculated in /// [`SerialSparseTrie::update_subtrie_hashes`]. const SPARSE_TRIE_SUBTRIE_HASHES_LEVEL: usize = 2; /// A sparse trie that is either in a "blind" state (no nodes are revealed, root node hash is /// unknown) or in a "revealed" state (root node has been revealed and the trie can be updated). /// /// In blind mode the trie does not contain any decoded node data, which saves memory but /// prevents direct access to node contents. The revealed mode stores decoded nodes along /// with additional information such as values, allowing direct manipulation. /// /// The sparse trie design is optimised for: /// 1. Memory efficiency - only revealed nodes are loaded into memory /// 2. Update tracking - changes to the trie structure can be tracked and selectively persisted /// 3. Incremental operations - nodes can be revealed as needed without loading the entire trie. /// This is what gives rise to the notion of a "sparse" trie. #[derive(PartialEq, Eq, Debug)] pub enum SparseTrie<T = SerialSparseTrie> { /// The trie is blind -- no nodes have been revealed /// /// This is the default state. In this state, the trie cannot be directly queried or modified /// until nodes are revealed. /// /// In this state the `SparseTrie` can optionally carry with it a cleared `SerialSparseTrie`. /// This allows for reusing the trie's allocations between payload executions. Blind(Option<Box<T>>), /// Some nodes in the Trie have been revealed. /// /// In this state, the trie can be queried and modified for the parts /// that have been revealed. Other parts remain blind and require revealing /// before they can be accessed. Revealed(Box<T>), } impl<T: Default> Default for SparseTrie<T> { fn default() -> Self { Self::Blind(None) } } impl<T: SparseTrieInterface + Default> SparseTrie<T> { /// Creates a new revealed but empty sparse trie with `SparseNode::Empty` as root node. /// /// # Examples /// /// ``` /// use reth_trie_sparse::{provider::DefaultTrieNodeProvider, SerialSparseTrie, SparseTrie}; /// /// let trie = SparseTrie::<SerialSparseTrie>::revealed_empty(); /// assert!(!trie.is_blind()); /// ``` pub fn revealed_empty() -> Self { Self::Revealed(Box::default()) } /// Reveals the root node, converting a blind trie into a revealed one. /// /// If the trie is blinded, its root node is replaced with `root`. /// /// The `masks` are used to determine how the node's children are stored. /// The `retain_updates` flag controls whether changes to the trie structure /// should be tracked. /// /// # Returns /// /// A mutable reference to the underlying [`SparseTrieInterface`]. pub fn reveal_root( &mut self, root: TrieNode, masks: TrieMasks, retain_updates: bool, ) -> SparseTrieResult<&mut T> { // if `Blind`, we initialize the revealed trie with the given root node, using a // pre-allocated trie if available. if self.is_blind() { let mut revealed_trie = if let Self::Blind(Some(cleared_trie)) = core::mem::take(self) { cleared_trie } else { Box::default() }; *revealed_trie = revealed_trie.with_root(root, masks, retain_updates)?; *self = Self::Revealed(revealed_trie); } Ok(self.as_revealed_mut().unwrap()) } } impl<T: SparseTrieInterface> SparseTrie<T> { /// Creates a new blind sparse trie. /// /// # Examples /// /// ``` /// use reth_trie_sparse::{provider::DefaultTrieNodeProvider, SerialSparseTrie, SparseTrie}; /// /// let trie = SparseTrie::<SerialSparseTrie>::blind(); /// assert!(trie.is_blind()); /// let trie = SparseTrie::<SerialSparseTrie>::default(); /// assert!(trie.is_blind()); /// ``` pub const fn blind() -> Self { Self::Blind(None) } /// Returns `true` if the sparse trie has no revealed nodes. pub const fn is_blind(&self) -> bool { matches!(self, Self::Blind(_)) } /// Returns `true` if the sparse trie is revealed. pub const fn is_revealed(&self) -> bool { matches!(self, Self::Revealed(_)) } /// Returns an immutable reference to the underlying revealed sparse trie. /// /// Returns `None` if the trie is blinded. pub const fn as_revealed_ref(&self) -> Option<&T> { if let Self::Revealed(revealed) = self { Some(revealed) } else { None } } /// Returns a mutable reference to the underlying revealed sparse trie. /// /// Returns `None` if the trie is blinded. pub fn as_revealed_mut(&mut self) -> Option<&mut T> { if let Self::Revealed(revealed) = self { Some(revealed) } else { None } } /// Wipes the trie by removing all nodes and values, /// and resetting the trie to only contain an empty root node. /// /// Note: This method will error if the trie is blinded. pub fn wipe(&mut self) -> SparseTrieResult<()> { let revealed = self.as_revealed_mut().ok_or(SparseTrieErrorKind::Blind)?; revealed.wipe(); Ok(()) } /// Calculates the root hash of the trie. /// /// This will update any remaining dirty nodes before computing the root hash. /// "dirty" nodes are nodes that need their hashes to be recomputed because one or more of their /// children's hashes have changed. /// /// # Returns /// /// - `Some(B256)` with the calculated root hash if the trie is revealed. /// - `None` if the trie is still blind. pub fn root(&mut self) -> Option<B256> { Some(self.as_revealed_mut()?.root()) } /// Returns the root hash along with any accumulated update information. /// /// This is useful for when you need both the root hash and information about /// what nodes were modified, which can be used to efficiently update /// an external database. /// /// # Returns /// /// An `Option` tuple consisting of: /// - The trie root hash (`B256`). /// - A [`SparseTrieUpdates`] structure containing information about updated nodes. /// - `None` if the trie is still blind. pub fn root_with_updates(&mut self) -> Option<(B256, SparseTrieUpdates)> { let revealed = self.as_revealed_mut()?; Some((revealed.root(), revealed.take_updates())) } /// Returns a [`SparseTrie::Blind`] based on this one. If this instance was revealed, or was /// itself a `Blind` with a pre-allocated [`SparseTrieInterface`], this will return /// a `Blind` carrying a cleared pre-allocated [`SparseTrieInterface`]. pub fn clear(self) -> Self { match self { Self::Blind(_) => self, Self::Revealed(mut trie) => { trie.clear(); Self::Blind(Some(trie)) } } } /// Updates (or inserts) a leaf at the given key path with the specified RLP-encoded value. /// /// # Errors /// /// Returns an error if the trie is still blind, or if the update fails. pub fn update_leaf( &mut self, path: Nibbles, value: Vec<u8>, is_private: bool, provider: impl TrieNodeProvider, ) -> SparseTrieResult<()> { let revealed = self.as_revealed_mut().ok_or(SparseTrieErrorKind::Blind)?; revealed.update_leaf(path, value, is_private, provider)?; Ok(()) } /// Removes a leaf node at the specified key path. /// /// # Errors /// /// Returns an error if the trie is still blind, or if the leaf cannot be removed pub fn remove_leaf( &mut self, path: &Nibbles, provider: impl TrieNodeProvider, ) -> SparseTrieResult<()> { let revealed = self.as_revealed_mut().ok_or(SparseTrieErrorKind::Blind)?; revealed.remove_leaf(path, provider)?; Ok(()) } } /// The representation of revealed sparse trie. /// /// The revealed sparse trie contains the actual trie structure with nodes, values, and /// tracking for changes. It supports operations like inserting, updating, and removing /// nodes. /// /// /// ## Invariants /// /// - The root node is always present in `nodes` collection. /// - Each leaf entry in `nodes` collection must have a corresponding entry in `values` collection. /// The opposite is also true. /// - All keys in `values` collection are full leaf paths. #[derive(Clone, PartialEq, Eq)] pub struct SerialSparseTrie { /// Map from a path (nibbles) to its corresponding sparse trie node. /// This contains all of the revealed nodes in trie. nodes: HashMap<Nibbles, SparseNode>, /// When a branch is set, the corresponding child subtree is stored in the database. branch_node_tree_masks: HashMap<Nibbles, TrieMask>, /// When a bit is set, the corresponding child is stored as a hash in the database. branch_node_hash_masks: HashMap<Nibbles, TrieMask>, /// Map from leaf key paths to their values. /// All values are stored here instead of directly in leaf nodes. values: HashMap<Nibbles, Vec<u8>>, /// Set of prefixes (key paths) that have been marked as updated. /// This is used to track which parts of the trie need to be recalculated. prefix_set: PrefixSetMut, /// Optional tracking of trie updates for later use. updates: Option<SparseTrieUpdates>, /// Reusable buffer for RLP encoding of nodes. rlp_buf: Vec<u8>, } impl fmt::Debug for SerialSparseTrie { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("SerialSparseTrie") .field("nodes", &self.nodes) .field("branch_tree_masks", &self.branch_node_tree_masks) .field("branch_hash_masks", &self.branch_node_hash_masks) .field("values", &self.values) .field("prefix_set", &self.prefix_set) .field("updates", &self.updates) .field("rlp_buf", &hex::encode(&self.rlp_buf)) .finish_non_exhaustive() } } /// Turns a [`Nibbles`] into a [`String`] by concatenating each nibbles' hex character. fn encode_nibbles(nibbles: &Nibbles) -> String { let encoded = hex::encode(nibbles.pack()); encoded[..nibbles.len()].to_string() } impl fmt::Display for SerialSparseTrie { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // This prints the trie in preorder traversal, using a stack let mut stack = Vec::new(); let mut visited = HashSet::new(); // 4 spaces as indent per level const INDENT: &str = " "; // Track both path and depth stack.push((Nibbles::default(), self.nodes_ref().get(&Nibbles::default()).unwrap(), 0)); while let Some((path, node, depth)) = stack.pop() { if !visited.insert(path) { continue; } // Add indentation if alternate flag (#) is set if f.alternate() { write!(f, "{}", INDENT.repeat(depth))?; } let packed_path = if depth == 0 { String::from("Root") } else { encode_nibbles(&path) }; match node { SparseNode::Empty | SparseNode::Hash(_) => { writeln!(f, "{packed_path} -> {node:?}")?; } SparseNode::Leaf { key, .. } => { // we want to append the key to the path let mut full_path = path; full_path.extend(key); let packed_path = encode_nibbles(&full_path); writeln!(f, "{packed_path} -> {node:?}")?; } SparseNode::Extension { key, .. } => { writeln!(f, "{packed_path} -> {node:?}")?; // push the child node onto the stack with increased depth let mut child_path = path; child_path.extend(key); if let Some(child_node) = self.nodes_ref().get(&child_path) { stack.push((child_path, child_node, depth + 1)); } } SparseNode::Branch { state_mask, .. } => { writeln!(f, "{packed_path} -> {node:?}")?; for i in CHILD_INDEX_RANGE.rev() { if state_mask.is_bit_set(i) { let mut child_path = path; child_path.push_unchecked(i); if let Some(child_node) = self.nodes_ref().get(&child_path) { stack.push((child_path, child_node, depth + 1)); } } } } } } Ok(()) } } impl Default for SerialSparseTrie { fn default() -> Self { Self { nodes: HashMap::from_iter([(Nibbles::default(), SparseNode::Empty)]), branch_node_tree_masks: HashMap::default(), branch_node_hash_masks: HashMap::default(), values: HashMap::default(), prefix_set: PrefixSetMut::default(), updates: None, rlp_buf: Vec::new(), } } } impl SparseTrieInterface for SerialSparseTrie { fn with_root( mut self, root: TrieNode, masks: TrieMasks, retain_updates: bool, ) -> SparseTrieResult<Self> { self = self.with_updates(retain_updates); // A fresh/cleared `SerialSparseTrie` has a `SparseNode::Empty` at its root. Delete that // so we can reveal the new root node. let path = Nibbles::default(); let _removed_root = self.nodes.remove(&path).expect("root node should exist"); debug_assert_eq!(_removed_root, SparseNode::Empty); self.reveal_node(path, root, masks)?; Ok(self) } fn with_updates(mut self, retain_updates: bool) -> Self { if retain_updates { self.updates = Some(SparseTrieUpdates::default()); } self } fn reserve_nodes(&mut self, additional: usize) { self.nodes.reserve(additional); } fn reveal_node( &mut self, path: Nibbles, node: TrieNode, masks: TrieMasks, ) -> SparseTrieResult<()> { trace!(target: "trie::sparse", ?path, ?node, ?masks, "reveal_node called"); // If the node is already revealed and it's not a hash node, do nothing. if self.nodes.get(&path).is_some_and(|node| !node.is_hash()) { return Ok(()); } if let Some(tree_mask) = masks.tree_mask { self.branch_node_tree_masks.insert(path, tree_mask); } if let Some(hash_mask) = masks.hash_mask { self.branch_node_hash_masks.insert(path, hash_mask); } match node { TrieNode::EmptyRoot => { // For an empty root, ensure that we are at the root path. debug_assert!(path.is_empty()); self.nodes.insert(path, SparseNode::Empty); } TrieNode::Branch(branch) => { // For a branch node, iterate over all potential children let mut stack_ptr = branch.as_ref().first_child_index(); for idx in CHILD_INDEX_RANGE { if branch.state_mask.is_bit_set(idx) { let mut child_path = path; child_path.push_unchecked(idx); // Reveal each child node or hash it has self.reveal_node_or_hash(child_path, &branch.stack[stack_ptr])?; stack_ptr += 1; } } // Update the branch node entry in the nodes map, handling cases where a blinded // node is now replaced with a revealed node. match self.nodes.entry(path) { Entry::Occupied(mut entry) => match entry.get() { // Replace a hash node with a fully revealed branch node. SparseNode::Hash(hash) => { entry.insert(SparseNode::Branch { state_mask: branch.state_mask, // Memoize the hash of a previously blinded node in a new branch // node. hash: Some(*hash), store_in_db_trie: Some( masks.hash_mask.is_some_and(|mask| !mask.is_empty()) || masks.tree_mask.is_some_and(|mask| !mask.is_empty()), ), }); } // Branch node already exists, or an extension node was placed where a // branch node was before. SparseNode::Branch { .. } | SparseNode::Extension { .. } => {} // All other node types can't be handled. node @ (SparseNode::Empty | SparseNode::Leaf { .. }) => { return Err(SparseTrieErrorKind::Reveal { path: *entry.key(), node: Box::new(node.clone()), } .into()) } }, Entry::Vacant(entry) => { entry.insert(SparseNode::new_branch(branch.state_mask)); } } } TrieNode::Extension(ext) => match self.nodes.entry(path) { Entry::Occupied(mut entry) => match entry.get() { // Replace a hash node with a revealed extension node. SparseNode::Hash(hash) => { let mut child_path = *entry.key(); child_path.extend(&ext.key); entry.insert(SparseNode::Extension { key: ext.key, // Memoize the hash of a previously blinded node in a new extension // node. hash: Some(*hash), store_in_db_trie: None, }); self.reveal_node_or_hash(child_path, &ext.child)?; } // Extension node already exists, or an extension node was placed where a branch // node was before. SparseNode::Extension { .. } | SparseNode::Branch { .. } => {} // All other node types can't be handled. node @ (SparseNode::Empty | SparseNode::Leaf { .. }) => { return Err(SparseTrieErrorKind::Reveal { path: *entry.key(), node: Box::new(node.clone()), } .into()) } }, Entry::Vacant(entry) => { let mut child_path = *entry.key(); child_path.extend(&ext.key); entry.insert(SparseNode::new_ext(ext.key)); self.reveal_node_or_hash(child_path, &ext.child)?; } }, TrieNode::Leaf(leaf) => match self.nodes.entry(path) { Entry::Occupied(mut entry) => match entry.get() { // Replace a hash node with a revealed leaf node and store leaf node value. SparseNode::Hash(hash) => { let mut full = *entry.key(); full.extend(&leaf.key); self.values.insert(full, leaf.value.clone()); entry.insert(SparseNode::Leaf { key: leaf.key, // Memoize the hash of a previously blinded node in a new leaf // node. hash: Some(*hash), is_private: leaf.is_private, }); } // Left node already exists. SparseNode::Leaf { .. } => {} // All other node types can't be handled. node @ (SparseNode::Empty | SparseNode::Extension { .. } | SparseNode::Branch { .. }) => { return Err(SparseTrieErrorKind::Reveal { path: *entry.key(), node: Box::new(node.clone()), } .into()) } }, Entry::Vacant(entry) => { let mut full = *entry.key(); full.extend(&leaf.key); entry.insert(SparseNode::new_leaf(leaf.key, leaf.is_private)); self.values.insert(full, leaf.value); } }, } Ok(()) } fn reveal_nodes(&mut self, mut nodes: Vec<RevealedSparseNode>) -> SparseTrieResult<()> { nodes.sort_unstable_by_key(|node| node.path); for node in nodes { self.reveal_node(node.path, node.node, node.masks)?; } Ok(()) } fn update_leaf<P: TrieNodeProvider>( &mut self, full_path: Nibbles, value: Vec<u8>, is_private: bool, provider: P, ) -> SparseTrieResult<()> { trace!(target: "trie::sparse", ?full_path, ?value, "update_leaf called"); self.prefix_set.insert(full_path); let existing = self.values.insert(full_path, value); if existing.is_some() { // trie structure unchanged, return immediately return Ok(()) } let mut current = Nibbles::default(); while let Some(node) = self.nodes.get_mut(&current) { match node { SparseNode::Empty => { *node = SparseNode::new_leaf(full_path, is_private); break } &mut SparseNode::Hash(hash) => { return Err(SparseTrieErrorKind::BlindedNode { path: current, hash }.into()) } SparseNode::Leaf { key: current_key, is_private: existing_is_private, .. } => { // Store the existing is_private value before modifying the node let existing_is_private = *existing_is_private; current.extend(current_key); // this leaf is being updated if current == full_path { unreachable!("we already checked leaf presence in the beginning"); } // find the common prefix let common = current.common_prefix_length(&full_path); // update existing node let new_ext_key = current.slice(current.len() - current_key.len()..common); *node = SparseNode::new_ext(new_ext_key); // create a branch node and corresponding leaves self.nodes.reserve(3); self.nodes.insert( current.slice(..common), SparseNode::new_split_branch( current.get_unchecked(common), full_path.get_unchecked(common), ), ); self.nodes.insert( full_path.slice(..=common), SparseNode::new_leaf(full_path.slice(common + 1..), is_private), ); self.nodes.insert( current.slice(..=common), SparseNode::new_leaf(current.slice(common + 1..), existing_is_private), ); break; } SparseNode::Extension { key, .. } => { current.extend(key); if !full_path.starts_with(&current) { // find the common prefix let common = current.common_prefix_length(&full_path); *key = current.slice(current.len() - key.len()..common); // If branch node updates retention is enabled, we need to query the // extension node child to later set the hash mask for a parent branch node // correctly. if self.updates.is_some() { // Check if the extension node child is a hash that needs to be revealed if self.nodes.get(&current).unwrap().is_hash() { debug!( target: "trie::sparse", leaf_full_path = ?full_path, child_path = ?current, "Extension node child not revealed in update_leaf, falling back to db", ); if let Some(RevealedNode { node, tree_mask, hash_mask }) = provider.trie_node(&current)? { let decoded = TrieNode::decode(&mut &node[..])?; trace!( target: "trie::sparse", ?current, ?decoded, ?tree_mask, ?hash_mask, "Revealing extension node child", ); self.reveal_node( current, decoded, TrieMasks { hash_mask, tree_mask }, )?; } } } // create state mask for new branch node // NOTE: this might overwrite the current extension node self.nodes.reserve(3); let branch = SparseNode::new_split_branch( current.get_unchecked(common), full_path.get_unchecked(common), ); self.nodes.insert(current.slice(..common), branch); // create new leaf let new_leaf = SparseNode::new_leaf(full_path.slice(common + 1..), is_private); self.nodes.insert(full_path.slice(..=common), new_leaf); // recreate extension to previous child if needed let key = current.slice(common + 1..); if !key.is_empty() { self.nodes.insert(current.slice(..=common), SparseNode::new_ext(key)); } break; } } SparseNode::Branch { state_mask, .. } => { let nibble = full_path.get_unchecked(current.len()); current.push_unchecked(nibble); if !state_mask.is_bit_set(nibble) { state_mask.set_bit(nibble); let new_leaf = SparseNode::new_leaf(full_path.slice(current.len()..), is_private); self.nodes.insert(current, new_leaf); break; } } }; } Ok(()) } fn remove_leaf<P: TrieNodeProvider>( &mut self, full_path: &Nibbles, provider: P, ) -> SparseTrieResult<()> { trace!(target: "trie::sparse", ?full_path, "remove_leaf called"); if self.values.remove(full_path).is_none() { if let Some(&SparseNode::Hash(hash)) = self.nodes.get(full_path) { // Leaf is present in the trie, but it's blinded. return Err(SparseTrieErrorKind::BlindedNode { path: *full_path, hash }.into()) } trace!(target: "trie::sparse", ?full_path, "Leaf node is not present in the trie"); // Leaf is not present in the trie. return Ok(()) } self.prefix_set.insert(*full_path); // If the path wasn't present in `values`, we still need to walk the trie and ensure that // there is no node at the path. When a leaf node is a blinded `Hash`, it will have an entry // in `nodes`, but not in the `values`. let mut removed_nodes = self.take_nodes_for_path(full_path)?; // Pop the first node from the stack which is the leaf node we want to remove. let mut child = removed_nodes.pop().expect("leaf exists"); #[cfg(debug_assertions)] { let mut child_path = child.path; let SparseNode::Leaf { key, .. } = &child.node else { panic!("expected leaf node") }; child_path.extend(key); assert_eq!(&child_path, full_path); } // If we don't have any other removed nodes, insert an empty node at the root. if removed_nodes.is_empty() { debug_assert!(self.nodes.is_empty()); self.nodes.insert(Nibbles::default(), SparseNode::Empty); return Ok(()) } // Walk the stack of removed nodes from the back and re-insert them back into the trie, // adjusting the node type as needed. while let Some(removed_node) = removed_nodes.pop() { let removed_path = removed_node.path; let new_node = match &removed_node.node { SparseNode::Empty => return Err(SparseTrieErrorKind::Blind.into()), &SparseNode::Hash(hash) => { return Err(SparseTrieErrorKind::BlindedNode { path: removed_path, hash }.into()) } SparseNode::Leaf { .. } => { unreachable!("we already popped the leaf node") } SparseNode::Extension { key, .. } => { // If the node is an extension node, we need to look at its child to see if we // need to merge them. match &child.node { SparseNode::Empty => return Err(SparseTrieErrorKind::Blind.into()), &SparseNode::Hash(hash) => { return Err( SparseTrieErrorKind::BlindedNode { path: child.path, hash }.into() ) } // For a leaf node, we collapse the extension node into a leaf node, // extending the key. While it's impossible to encounter an extension node // followed by a leaf node in a complete trie, it's possible here because we // could have downgraded the extension node's child into a leaf node from // another node type. SparseNode::Leaf { key: leaf_key, is_private, .. } => { self.nodes.remove(&child.path); let mut new_key = *key;
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
true
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/sparse/benches/update.rs
crates/trie/sparse/benches/update.rs
#![allow(missing_docs)] use alloy_primitives::{B256, U256}; use criterion::{criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion}; use proptest::{prelude::*, strategy::ValueTree}; use rand::seq::IteratorRandom; use reth_trie_common::Nibbles; use reth_trie_sparse::{provider::DefaultTrieNodeProvider, SerialSparseTrie, SparseTrie}; const LEAF_COUNTS: [usize; 2] = [1_000, 5_000]; fn update_leaf(c: &mut Criterion) { let mut group = c.benchmark_group("update_leaf"); for leaf_count in LEAF_COUNTS { group.bench_function(BenchmarkId::from_parameter(leaf_count), |b| { let leaves = generate_leaves(leaf_count); // Start with an empty trie let provider = DefaultTrieNodeProvider; b.iter_batched( || { let mut trie = SparseTrie::<SerialSparseTrie>::revealed_empty(); // Pre-populate with data for (path, value) in leaves.iter().cloned() { trie.update_leaf(path, value, false, &provider).unwrap(); } let new_leaves = leaves .iter() // Update 10% of existing leaves with new values .choose_multiple(&mut rand::rng(), leaf_count / 10) .into_iter() .map(|(path, _)| { ( path, alloy_rlp::encode_fixed_size(&U256::from(path.len() * 2)).to_vec(), ) }) .collect::<Vec<_>>(); (trie, new_leaves) }, |(mut trie, new_leaves)| { for (path, new_value) in new_leaves { trie.update_leaf(*path, new_value, false, &provider).unwrap(); } trie }, BatchSize::LargeInput, ); }); } } fn remove_leaf(c: &mut Criterion) { let mut group = c.benchmark_group("remove_leaf"); for leaf_count in LEAF_COUNTS { group.bench_function(BenchmarkId::from_parameter(leaf_count), |b| { let leaves = generate_leaves(leaf_count); // Start with an empty trie let provider = DefaultTrieNodeProvider; b.iter_batched( || { let mut trie = SparseTrie::<SerialSparseTrie>::revealed_empty(); // Pre-populate with data for (path, value) in leaves.iter().cloned() { trie.update_leaf(path, value, false, &provider).unwrap(); } let delete_leaves = leaves .iter() .map(|(path, _)| path) // Remove 10% leaves .choose_multiple(&mut rand::rng(), leaf_count / 10); (trie, delete_leaves) }, |(mut trie, delete_leaves)| { for path in delete_leaves { trie.remove_leaf(path, &provider).unwrap(); } trie }, BatchSize::LargeInput, ); }); } } fn generate_leaves(size: usize) -> Vec<(Nibbles, Vec<u8>)> { proptest::collection::hash_map(any::<B256>(), any::<U256>(), size) .new_tree(&mut Default::default()) .unwrap() .current() .iter() .map(|(key, value)| (Nibbles::unpack(key), alloy_rlp::encode_fixed_size(value).to_vec())) .collect() } criterion_group!(benches, update_leaf, remove_leaf); criterion_main!(benches);
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/sparse/benches/root.rs
crates/trie/sparse/benches/root.rs
#![allow(missing_docs)] use alloy_primitives::{map::B256Map, B256, U256}; use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; use itertools::Itertools; use proptest::{prelude::*, strategy::ValueTree, test_runner::TestRunner}; use reth_trie::{ hashed_cursor::{noop::NoopHashedStorageCursor, HashedPostStateStorageCursor}, node_iter::{TrieElement, TrieNodeIter}, trie_cursor::{noop::NoopStorageTrieCursor, InMemoryStorageTrieCursor}, updates::StorageTrieUpdates, walker::TrieWalker, HashedStorage, }; use reth_trie_common::{HashBuilder, Nibbles}; use reth_trie_sparse::{provider::DefaultTrieNodeProvider, SerialSparseTrie, SparseTrie}; // seismic-only dependencies use alloy_primitives::FlaggedStorage; fn calculate_root_from_leaves(c: &mut Criterion) { let is_private = false; // hardcode to false for legacy test let mut group = c.benchmark_group("calculate root from leaves"); group.sample_size(20); for size in [1_000, 5_000, 10_000, 100_000] { // Too slow. #[expect(unexpected_cfgs)] if cfg!(codspeed) && size > 5_000 { continue; } let state = generate_test_data(size); // hash builder group.bench_function(BenchmarkId::new("hash builder", size), |b| { b.iter_with_setup(HashBuilder::default, |mut hb| { for (key, value) in state.iter().sorted_by_key(|(key, _)| *key) { hb.add_leaf( Nibbles::unpack(key), &alloy_rlp::encode_fixed_size(value), is_private, ); } hb.root(); hb }) }); // sparse trie let provider = DefaultTrieNodeProvider; group.bench_function(BenchmarkId::new("sparse trie", size), |b| { b.iter_with_setup(SparseTrie::<SerialSparseTrie>::revealed_empty, |mut sparse| { for (key, value) in &state { sparse .update_leaf( Nibbles::unpack(key), alloy_rlp::encode_fixed_size(value).to_vec(), is_private, &provider, ) .unwrap(); } sparse.root().unwrap(); sparse }) }); } } fn calculate_root_from_leaves_repeated(c: &mut Criterion) { let is_private = false; // hardcode to false for legacy test let mut group = c.benchmark_group("calculate root from leaves repeated"); group.sample_size(20); for init_size in [1_000, 10_000, 100_000] { // Too slow. #[expect(unexpected_cfgs)] if cfg!(codspeed) && init_size > 10_000 { continue; } let init_state = generate_test_data(init_size); for update_size in [100, 1_000, 5_000, 10_000] { // Too slow. #[expect(unexpected_cfgs)] if cfg!(codspeed) && update_size > 1_000 { continue; } for num_updates in [1, 3, 5, 10] { let updates = (0..num_updates).map(|_| generate_test_data(update_size)).collect::<Vec<_>>(); // hash builder let benchmark_id = BenchmarkId::new( "hash builder", format!( "init size {init_size} | update size {update_size} | num updates {num_updates}" ), ); group.bench_function(benchmark_id, |b| { b.iter_with_setup( || { let init_storage = HashedStorage::from_iter(false, init_state.clone()); let storage_updates = updates .clone() .into_iter() .map(|update| HashedStorage::from_iter(false, update)) .collect::<Vec<_>>(); let mut hb = HashBuilder::default().with_updates(true); for (key, value) in init_state.iter().sorted_by_key(|(key, _)| *key) { hb.add_leaf( Nibbles::unpack(key), &alloy_rlp::encode_fixed_size(value), is_private, ); } hb.root(); let (_, updates) = hb.split(); let trie_updates = StorageTrieUpdates::new(updates); (init_storage, storage_updates, trie_updates) }, |(init_storage, storage_updates, mut trie_updates)| { let mut storage = init_storage; let mut storage_updates = storage_updates.into_iter().peekable(); while let Some(update) = storage_updates.next() { storage.extend(&update); let prefix_set = update.construct_prefix_set().freeze(); let (storage_sorted, trie_updates_sorted) = if storage_updates.peek().is_some() { ( storage.clone().into_sorted(), trie_updates.clone().into_sorted(), ) } else { ( std::mem::take(&mut storage).into_sorted(), std::mem::take(&mut trie_updates).into_sorted(), ) }; let walker = TrieWalker::<_>::storage_trie( InMemoryStorageTrieCursor::new( B256::ZERO, NoopStorageTrieCursor::default(), Some(&trie_updates_sorted), ), prefix_set, ); let mut node_iter = TrieNodeIter::storage_trie( walker, HashedPostStateStorageCursor::new( NoopHashedStorageCursor::default(), Some(&storage_sorted), ), ); let mut hb = HashBuilder::default().with_updates(true); while let Some(node) = node_iter.try_next().unwrap() { match node { TrieElement::Branch(node) => { hb.add_branch( node.key, node.value, node.children_are_in_trie, ); } TrieElement::Leaf(hashed_slot, value) => { hb.add_leaf( Nibbles::unpack(hashed_slot), alloy_rlp::encode_fixed_size(&value).as_ref(), is_private, ); } } } hb.root(); if storage_updates.peek().is_some() { trie_updates.finalize(hb, node_iter.walker.take_removed_keys()); } } (storage, storage_updates, trie_updates) }, ) }); // sparse trie let provider = DefaultTrieNodeProvider; let benchmark_id = BenchmarkId::new( "sparse trie", format!( "init size {init_size} | update size {update_size} | num updates {num_updates}" ), ); group.bench_function(benchmark_id, |b| { b.iter_with_setup( || { let mut sparse = SparseTrie::<SerialSparseTrie>::revealed_empty(); for (key, value) in &init_state { sparse .update_leaf( Nibbles::unpack(key), alloy_rlp::encode_fixed_size(value).to_vec(), is_private, &provider, ) .unwrap(); } sparse.root().unwrap(); sparse }, |mut sparse| { for update in &updates { for (key, value) in update { sparse .update_leaf( Nibbles::unpack(key), alloy_rlp::encode_fixed_size(value).to_vec(), is_private, &provider, ) .unwrap(); } sparse.root().unwrap(); } sparse }, ) }); } } } } fn generate_test_data(size: usize) -> B256Map<FlaggedStorage> { let mut runner = TestRunner::deterministic(); proptest::collection::hash_map(any::<B256>(), any::<U256>(), size) .new_tree(&mut runner) .unwrap() .current() .into_iter() .map(|(key, value)| (key, FlaggedStorage::new(value, false))) .collect() } criterion_group!(root, calculate_root_from_leaves, calculate_root_from_leaves_repeated); criterion_main!(root);
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/sparse/benches/rlp_node.rs
crates/trie/sparse/benches/rlp_node.rs
#![allow(missing_docs)] use alloy_primitives::{B256, U256}; use criterion::{criterion_group, criterion_main, Criterion}; use prop::strategy::ValueTree; use proptest::{prelude::*, test_runner::TestRunner}; use rand::{seq::IteratorRandom, Rng}; use reth_testing_utils::generators; use reth_trie::Nibbles; use reth_trie_sparse::{provider::DefaultTrieNodeProvider, SerialSparseTrie, SparseTrieInterface}; fn update_rlp_node_level(c: &mut Criterion) { let mut rng = generators::rng(); let mut group = c.benchmark_group("update rlp node level"); group.sample_size(20); for size in [100_000] { let mut runner = TestRunner::deterministic(); let state = proptest::collection::hash_map(any::<B256>(), any::<U256>(), size) .new_tree(&mut runner) .unwrap() .current(); let is_private = false; // hardcoded to false for legacy benchmark // Create a sparse trie with `size` leaves let provider = DefaultTrieNodeProvider; let mut sparse = SerialSparseTrie::default(); for (key, value) in &state { sparse .update_leaf( Nibbles::unpack(key), alloy_rlp::encode_fixed_size(value).to_vec(), false, &provider, ) .unwrap(); } sparse.root(); for updated_leaves in [0.1, 1.0] { for key in state .keys() .choose_multiple(&mut rng, (size as f64 * (updated_leaves / 100.0)) as usize) { sparse .update_leaf( Nibbles::unpack(key), alloy_rlp::encode_fixed_size(&rng.random::<U256>()).to_vec(), is_private, &provider, ) .unwrap(); } // Calculate the maximum depth of the trie for the given number of leaves let max_depth = (size as f64).log(16.0).ceil() as usize; for depth in 0..=max_depth { group.bench_function( format!("size {size} | updated {updated_leaves}% | depth {depth}"), |b| { b.iter_batched_ref( || sparse.clone(), |cloned| cloned.update_rlp_node_level(depth), criterion::BatchSize::PerIteration, ) }, ); } } } } criterion_group!(rlp_node, update_rlp_node_level); criterion_main!(rlp_node);
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/src/hashed_state.rs
crates/trie/common/src/hashed_state.rs
use core::ops::Not; use crate::{ added_removed_keys::MultiAddedRemovedKeys, prefix_set::{PrefixSetMut, TriePrefixSetsMut}, KeyHasher, MultiProofTargets, Nibbles, }; use alloc::{borrow::Cow, vec::Vec}; use alloy_primitives::{ keccak256, map::{hash_map, B256Map, B256Set, HashMap, HashSet}, Address, B256, U256, }; use itertools::Itertools; #[cfg(feature = "rayon")] pub use rayon::*; use reth_primitives_traits::Account; #[cfg(feature = "rayon")] use rayon::prelude::{IntoParallelIterator, ParallelIterator}; use revm_database::{AccountStatus, BundleAccount}; use revm_state::FlaggedStorage; /// Representation of in-memory hashed state. #[derive(PartialEq, Eq, Clone, Default, Debug)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct HashedPostState { /// Mapping of hashed address to account info, `None` if destroyed. pub accounts: B256Map<Option<Account>>, /// Mapping of hashed address to hashed storage. pub storages: B256Map<HashedStorage>, } impl HashedPostState { /// Create new instance of [`HashedPostState`]. pub fn with_capacity(capacity: usize) -> Self { Self { accounts: B256Map::with_capacity_and_hasher(capacity, Default::default()), storages: B256Map::with_capacity_and_hasher(capacity, Default::default()), } } /// Initialize [`HashedPostState`] from bundle state. /// Hashes all changed accounts and storage entries that are currently stored in the bundle /// state. #[inline] #[cfg(feature = "rayon")] pub fn from_bundle_state<'a, KH: KeyHasher>( state: impl IntoParallelIterator<Item = (&'a Address, &'a BundleAccount)>, ) -> Self { let hashed = state .into_par_iter() .map(|(address, account)| { let hashed_address = KH::hash_key(address); let hashed_account = account.info.as_ref().map(Into::into); let hashed_storage = HashedStorage::from_plain_storage( account.status, account.storage.iter().map(|(slot, value)| (slot, &value.present_value)), ); (hashed_address, (hashed_account, hashed_storage)) }) .collect::<Vec<(B256, (Option<Account>, HashedStorage))>>(); let mut accounts = HashMap::with_capacity_and_hasher(hashed.len(), Default::default()); let mut storages = HashMap::with_capacity_and_hasher(hashed.len(), Default::default()); for (address, (account, storage)) in hashed { accounts.insert(address, account); if !storage.is_empty() { storages.insert(address, storage); } } Self { accounts, storages } } /// Initialize [`HashedPostState`] from bundle state. /// Hashes all changed accounts and storage entries that are currently stored in the bundle /// state. #[cfg(not(feature = "rayon"))] pub fn from_bundle_state<'a, KH: KeyHasher>( state: impl IntoIterator<Item = (&'a Address, &'a BundleAccount)>, ) -> Self { let hashed = state .into_iter() .map(|(address, account)| { let hashed_address = KH::hash_key(address); let hashed_account = account.info.as_ref().map(Into::into); let hashed_storage = HashedStorage::from_plain_storage( account.status, account.storage.iter().map(|(slot, value)| (slot, &value.present_value)), ); (hashed_address, (hashed_account, hashed_storage)) }) .collect::<Vec<(B256, (Option<Account>, HashedStorage))>>(); let mut accounts = HashMap::with_capacity_and_hasher(hashed.len(), Default::default()); let mut storages = HashMap::with_capacity_and_hasher(hashed.len(), Default::default()); for (address, (account, storage)) in hashed { accounts.insert(address, account); if !storage.is_empty() { storages.insert(address, storage); } } Self { accounts, storages } } /// Construct [`HashedPostState`] from a single [`HashedStorage`]. pub fn from_hashed_storage(hashed_address: B256, storage: HashedStorage) -> Self { Self { accounts: HashMap::default(), storages: HashMap::from_iter([(hashed_address, storage)]), } } /// Set account entries on hashed state. pub fn with_accounts( mut self, accounts: impl IntoIterator<Item = (B256, Option<Account>)>, ) -> Self { self.accounts = HashMap::from_iter(accounts); self } /// Set storage entries on hashed state. pub fn with_storages( mut self, storages: impl IntoIterator<Item = (B256, HashedStorage)>, ) -> Self { self.storages = HashMap::from_iter(storages); self } /// Returns `true` if the hashed state is empty. pub fn is_empty(&self) -> bool { self.accounts.is_empty() && self.storages.is_empty() } /// Construct [`TriePrefixSetsMut`] from hashed post state. /// The prefix sets contain the hashed account and storage keys that have been changed in the /// post state. pub fn construct_prefix_sets(&self) -> TriePrefixSetsMut { // Populate account prefix set. let mut account_prefix_set = PrefixSetMut::with_capacity(self.accounts.len()); let mut destroyed_accounts = HashSet::default(); for (hashed_address, account) in &self.accounts { account_prefix_set.insert(Nibbles::unpack(hashed_address)); if account.is_none() { destroyed_accounts.insert(*hashed_address); } } // Populate storage prefix sets. let mut storage_prefix_sets = HashMap::with_capacity_and_hasher(self.storages.len(), Default::default()); for (hashed_address, hashed_storage) in &self.storages { account_prefix_set.insert(Nibbles::unpack(hashed_address)); storage_prefix_sets.insert(*hashed_address, hashed_storage.construct_prefix_set()); } TriePrefixSetsMut { account_prefix_set, storage_prefix_sets, destroyed_accounts } } /// Create multiproof targets for this state. pub fn multi_proof_targets(&self) -> MultiProofTargets { // Pre-allocate minimum capacity for the targets. let mut targets = MultiProofTargets::with_capacity(self.accounts.len()); for hashed_address in self.accounts.keys() { targets.insert(*hashed_address, Default::default()); } for (hashed_address, storage) in &self.storages { targets.entry(*hashed_address).or_default().extend(storage.storage.keys().copied()); } targets } /// Create multiproof targets difference for this state, /// i.e., the targets that are in targets create from `self` but not in `excluded`. /// /// This method is preferred to first calling `Self::multi_proof_targets` and the calling /// `MultiProofTargets::retain_difference`, because it does not over allocate the targets map. pub fn multi_proof_targets_difference( &self, excluded: &MultiProofTargets, ) -> MultiProofTargets { let mut targets = MultiProofTargets::default(); for hashed_address in self.accounts.keys() { if !excluded.contains_key(hashed_address) { targets.insert(*hashed_address, Default::default()); } } for (hashed_address, storage) in &self.storages { let maybe_excluded_storage = excluded.get(hashed_address); let mut hashed_slots_targets = storage .storage .keys() .filter(|slot| !maybe_excluded_storage.is_some_and(|f| f.contains(*slot))) .peekable(); if hashed_slots_targets.peek().is_some() { targets.entry(*hashed_address).or_default().extend(hashed_slots_targets); } } targets } /// Partition the state update into two state updates: /// - First with accounts and storages slots that are present in the provided targets. /// - Second with all other. /// /// CAUTION: The state updates are expected to be applied in order, so that the storage wipes /// are done correctly. pub fn partition_by_targets( mut self, targets: &MultiProofTargets, added_removed_keys: &MultiAddedRemovedKeys, ) -> (Self, Self) { let mut state_updates_not_in_targets = Self::default(); self.storages.retain(|&address, storage| { let storage_added_removed_keys = added_removed_keys.get_storage(&address); let (retain, storage_not_in_targets) = match targets.get(&address) { Some(storage_in_targets) => { let mut storage_not_in_targets = HashedStorage::default(); storage.storage.retain(|&slot, value| { if storage_in_targets.contains(&slot) && !storage_added_removed_keys.is_some_and(|k| k.is_removed(&slot)) { return true } storage_not_in_targets.storage.insert(slot, *value); false }); // We do not check the wiped flag here, because targets only contain addresses // and storage slots. So if there are no storage slots left, the storage update // can be fully removed. let retain = !storage.storage.is_empty(); // Since state updates are expected to be applied in order, we can only set the // wiped flag in the second storage update if the first storage update is empty // and will not be retained. if !retain { storage_not_in_targets.wiped = storage.wiped; } ( retain, storage_not_in_targets.is_empty().not().then_some(storage_not_in_targets), ) } None => (false, Some(core::mem::take(storage))), }; if let Some(storage_not_in_targets) = storage_not_in_targets { state_updates_not_in_targets.storages.insert(address, storage_not_in_targets); } retain }); self.accounts.retain(|&address, account| { if targets.contains_key(&address) { return true } state_updates_not_in_targets.accounts.insert(address, *account); false }); (self, state_updates_not_in_targets) } /// Returns an iterator that yields chunks of the specified size. /// /// See [`ChunkedHashedPostState`] for more information. pub fn chunks(self, size: usize) -> ChunkedHashedPostState { ChunkedHashedPostState::new(self, size) } /// Extend this hashed post state with contents of another. /// Entries in the second hashed post state take precedence. pub fn extend(&mut self, other: Self) { self.extend_inner(Cow::Owned(other)); } /// Extend this hashed post state with contents of another. /// Entries in the second hashed post state take precedence. /// /// Slightly less efficient than [`Self::extend`], but preferred to `extend(other.clone())`. pub fn extend_ref(&mut self, other: &Self) { self.extend_inner(Cow::Borrowed(other)); } fn extend_inner(&mut self, other: Cow<'_, Self>) { self.accounts.extend(other.accounts.iter().map(|(&k, &v)| (k, v))); self.storages.reserve(other.storages.len()); match other { Cow::Borrowed(other) => { self.extend_storages(other.storages.iter().map(|(k, v)| (*k, Cow::Borrowed(v)))) } Cow::Owned(other) => { self.extend_storages(other.storages.into_iter().map(|(k, v)| (k, Cow::Owned(v)))) } } } fn extend_storages<'a>( &mut self, storages: impl IntoIterator<Item = (B256, Cow<'a, HashedStorage>)>, ) { for (hashed_address, storage) in storages { match self.storages.entry(hashed_address) { hash_map::Entry::Vacant(entry) => { entry.insert(storage.into_owned()); } hash_map::Entry::Occupied(mut entry) => { entry.get_mut().extend(&storage); } } } } /// Converts hashed post state into [`HashedPostStateSorted`]. pub fn into_sorted(self) -> HashedPostStateSorted { let mut updated_accounts = Vec::new(); let mut destroyed_accounts = HashSet::default(); for (hashed_address, info) in self.accounts { if let Some(info) = info { updated_accounts.push((hashed_address, info)); } else { destroyed_accounts.insert(hashed_address); } } updated_accounts.sort_unstable_by_key(|(address, _)| *address); let accounts = HashedAccountsSorted { accounts: updated_accounts, destroyed_accounts }; let storages = self .storages .into_iter() .map(|(hashed_address, storage)| (hashed_address, storage.into_sorted())) .collect(); HashedPostStateSorted { accounts, storages } } /// Converts hashed post state into [`HashedPostStateSorted`], but keeping the maps allocated by /// draining. /// /// This effectively clears all the fields in the [`HashedPostStateSorted`]. /// /// This allows us to reuse the allocated space. This allocates new space for the sorted hashed /// post state, like `into_sorted`. pub fn drain_into_sorted(&mut self) -> HashedPostStateSorted { let mut updated_accounts = Vec::new(); let mut destroyed_accounts = HashSet::default(); for (hashed_address, info) in self.accounts.drain() { if let Some(info) = info { updated_accounts.push((hashed_address, info)); } else { destroyed_accounts.insert(hashed_address); } } updated_accounts.sort_unstable_by_key(|(address, _)| *address); let accounts = HashedAccountsSorted { accounts: updated_accounts, destroyed_accounts }; let storages = self .storages .drain() .map(|(hashed_address, storage)| (hashed_address, storage.into_sorted())) .collect(); HashedPostStateSorted { accounts, storages } } /// Clears the account and storage maps of this `HashedPostState`. pub fn clear(&mut self) { self.accounts.clear(); self.storages.clear(); } } /// Representation of in-memory hashed storage. #[derive(PartialEq, Eq, Clone, Debug, Default)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct HashedStorage { /// Flag indicating whether the storage was wiped or not. pub wiped: bool, /// Mapping of hashed storage slot to storage value. pub storage: B256Map<FlaggedStorage>, } impl HashedStorage { /// Create new instance of [`HashedStorage`]. pub fn new(wiped: bool) -> Self { Self { wiped, storage: HashMap::default() } } /// Check if self is empty. pub fn is_empty(&self) -> bool { !self.wiped && self.storage.is_empty() } /// Create new hashed storage from iterator. pub fn from_iter(wiped: bool, iter: impl IntoIterator<Item = (B256, FlaggedStorage)>) -> Self { Self { wiped, storage: HashMap::from_iter(iter) } } /// Create new hashed storage from account status and plain storage. pub fn from_plain_storage<'a>( status: AccountStatus, storage: impl IntoIterator<Item = (&'a U256, &'a FlaggedStorage)>, ) -> Self { Self::from_iter( status.was_destroyed(), storage.into_iter().map(|(key, value)| (keccak256(B256::from(*key)), *value)), ) } /// Construct [`PrefixSetMut`] from hashed storage. pub fn construct_prefix_set(&self) -> PrefixSetMut { if self.wiped { PrefixSetMut::all() } else { let mut prefix_set = PrefixSetMut::with_capacity(self.storage.len()); for hashed_slot in self.storage.keys() { prefix_set.insert(Nibbles::unpack(hashed_slot)); } prefix_set } } /// Extend hashed storage with contents of other. /// The entries in second hashed storage take precedence. pub fn extend(&mut self, other: &Self) { if other.wiped { self.wiped = true; self.storage.clear(); } self.storage.extend(other.storage.iter().map(|(&k, &v)| (k, v))); } /// Converts hashed storage into [`HashedStorageSorted`]. pub fn into_sorted(self) -> HashedStorageSorted { let mut non_zero_valued_slots = Vec::new(); let mut zero_valued_slots = HashSet::default(); for (hashed_slot, value) in self.storage { if value.is_zero() { zero_valued_slots.insert(hashed_slot); } else { non_zero_valued_slots.push((hashed_slot, value)); } } non_zero_valued_slots.sort_unstable_by_key(|(key, _)| *key); HashedStorageSorted { non_zero_valued_slots, zero_valued_slots, wiped: self.wiped } } } /// Sorted hashed post state optimized for iterating during state trie calculation. #[derive(PartialEq, Eq, Clone, Default, Debug)] pub struct HashedPostStateSorted { /// Updated state of accounts. pub accounts: HashedAccountsSorted, /// Map of hashed addresses to hashed storage. pub storages: B256Map<HashedStorageSorted>, } impl HashedPostStateSorted { /// Create new instance of [`HashedPostStateSorted`] pub const fn new( accounts: HashedAccountsSorted, storages: B256Map<HashedStorageSorted>, ) -> Self { Self { accounts, storages } } /// Returns reference to hashed accounts. pub const fn accounts(&self) -> &HashedAccountsSorted { &self.accounts } /// Returns reference to hashed account storages. pub const fn account_storages(&self) -> &B256Map<HashedStorageSorted> { &self.storages } } /// Sorted account state optimized for iterating during state trie calculation. #[derive(Clone, Eq, PartialEq, Default, Debug)] pub struct HashedAccountsSorted { /// Sorted collection of hashed addresses and their account info. pub accounts: Vec<(B256, Account)>, /// Set of destroyed account keys. pub destroyed_accounts: B256Set, } impl HashedAccountsSorted { /// Returns a sorted iterator over updated accounts. pub fn accounts_sorted(&self) -> impl Iterator<Item = (B256, Option<Account>)> { self.accounts .iter() .map(|(address, account)| (*address, Some(*account))) .chain(self.destroyed_accounts.iter().map(|address| (*address, None))) .sorted_by_key(|entry| *entry.0) } } /// Sorted hashed storage optimized for iterating during state trie calculation. #[derive(Clone, Eq, PartialEq, Debug)] pub struct HashedStorageSorted { /// Sorted hashed storage slots with non-zero value. pub non_zero_valued_slots: Vec<(B256, FlaggedStorage)>, /// Slots that have been zero valued. pub zero_valued_slots: B256Set, /// Flag indicating whether the storage was wiped or not. pub wiped: bool, } impl HashedStorageSorted { /// Returns `true` if the account was wiped. pub const fn is_wiped(&self) -> bool { self.wiped } /// Returns a sorted iterator over updated storage slots. pub fn storage_slots_sorted(&self) -> impl Iterator<Item = (B256, FlaggedStorage)> { self.non_zero_valued_slots .iter() .map(|(hashed_slot, value)| (*hashed_slot, *value)) .chain( self.zero_valued_slots .iter() .map(|hashed_slot| (*hashed_slot, FlaggedStorage::ZERO)), ) .sorted_by_key(|entry| *entry.0) } } /// An iterator that yields chunks of the state updates of at most `size` account and storage /// targets. /// /// # Notes /// 1. Chunks are expected to be applied in order, because of storage wipes. If applied out of /// order, it's possible to wipe more storage than in the original state update. /// 2. For each account, chunks with storage updates come first, followed by account updates. #[derive(Debug)] pub struct ChunkedHashedPostState { flattened: alloc::vec::IntoIter<(B256, FlattenedHashedPostStateItem)>, size: usize, } #[derive(Debug)] enum FlattenedHashedPostStateItem { Account(Option<Account>), StorageWipe, StorageUpdate { slot: B256, value: FlaggedStorage }, } impl ChunkedHashedPostState { fn new(hashed_post_state: HashedPostState, size: usize) -> Self { let flattened = hashed_post_state .storages .into_iter() .flat_map(|(address, storage)| { // Storage wipes should go first Some((address, FlattenedHashedPostStateItem::StorageWipe)) .filter(|_| storage.wiped) .into_iter() .chain( storage.storage.into_iter().sorted_unstable_by_key(|(slot, _)| *slot).map( move |(slot, value)| { ( address, FlattenedHashedPostStateItem::StorageUpdate { slot, value }, ) }, ), ) }) .chain(hashed_post_state.accounts.into_iter().map(|(address, account)| { (address, FlattenedHashedPostStateItem::Account(account)) })) // We need stable sort here to preserve the order for each address: // 1. Storage wipes // 2. Storage updates // 3. Account update .sorted_by_key(|(address, _)| *address); Self { flattened, size } } } impl Iterator for ChunkedHashedPostState { type Item = HashedPostState; fn next(&mut self) -> Option<Self::Item> { let mut chunk = HashedPostState::default(); let mut current_size = 0; while current_size < self.size { let Some((address, item)) = self.flattened.next() else { break }; match item { FlattenedHashedPostStateItem::Account(account) => { chunk.accounts.insert(address, account); } FlattenedHashedPostStateItem::StorageWipe => { chunk.storages.entry(address).or_default().wiped = true; } FlattenedHashedPostStateItem::StorageUpdate { slot, value } => { chunk.storages.entry(address).or_default().storage.insert(slot, value); } } current_size += 1; } if chunk.is_empty() { None } else { Some(chunk) } } } #[cfg(test)] mod tests { use super::*; use crate::KeccakKeyHasher; use alloy_primitives::Bytes; use revm_database::{states::StorageSlot, StorageWithOriginalValues}; use revm_state::{AccountInfo, Bytecode}; #[test] fn hashed_state_wiped_extension() { let hashed_address = B256::default(); let hashed_slot = B256::with_last_byte(64); let hashed_slot2 = B256::with_last_byte(65); // Initialize post state storage let original_slot_value = FlaggedStorage::new(123, true); let mut hashed_state = HashedPostState::default().with_storages([( hashed_address, HashedStorage::from_iter( false, [(hashed_slot, original_slot_value), (hashed_slot2, original_slot_value)], ), )]); // Update single slot value let updated_slot_value = FlaggedStorage::new_from_tuple((321, false)); let extension = HashedPostState::default().with_storages([( hashed_address, HashedStorage::from_iter(false, [(hashed_slot, updated_slot_value)]), )]); hashed_state.extend(extension); let account_storage = hashed_state.storages.get(&hashed_address); assert_eq!( account_storage.and_then(|st| st.storage.get(&hashed_slot)), Some(&updated_slot_value) ); assert_eq!( account_storage.and_then(|st| st.storage.get(&hashed_slot2)), Some(&original_slot_value) ); assert_eq!(account_storage.map(|st| st.wiped), Some(false)); // Wipe account storage let wiped_extension = HashedPostState::default().with_storages([(hashed_address, HashedStorage::new(true))]); hashed_state.extend(wiped_extension); let account_storage = hashed_state.storages.get(&hashed_address); assert_eq!(account_storage.map(|st| st.storage.is_empty()), Some(true)); assert_eq!(account_storage.map(|st| st.wiped), Some(true)); // Reinitialize single slot value hashed_state.extend(HashedPostState::default().with_storages([( hashed_address, HashedStorage::from_iter(false, [(hashed_slot, original_slot_value)]), )])); let account_storage = hashed_state.storages.get(&hashed_address); assert_eq!( account_storage.and_then(|st| st.storage.get(&hashed_slot)), Some(&original_slot_value) ); assert_eq!(account_storage.and_then(|st| st.storage.get(&hashed_slot2)), None); assert_eq!(account_storage.map(|st| st.wiped), Some(true)); // Reinitialize single slot value hashed_state.extend(HashedPostState::default().with_storages([( hashed_address, HashedStorage::from_iter(false, [(hashed_slot2, updated_slot_value)]), )])); let account_storage = hashed_state.storages.get(&hashed_address); assert_eq!( account_storage.and_then(|st| st.storage.get(&hashed_slot)), Some(&original_slot_value) ); assert_eq!( account_storage.and_then(|st| st.storage.get(&hashed_slot2)), Some(&updated_slot_value) ); assert_eq!(account_storage.map(|st| st.wiped), Some(true)); } #[test] fn test_hashed_post_state_from_bundle_state() { // Prepare a random Ethereum address as a key for the account. let address = Address::random(); // Create a mock account info object. let account_info = AccountInfo { balance: U256::from(123), nonce: 42, code_hash: B256::random(), code: Some(Bytecode::new_raw(Bytes::from(vec![1, 2]))), }; let mut storage = StorageWithOriginalValues::default(); storage.insert( U256::from(1), StorageSlot { present_value: FlaggedStorage::new_from_value(4), ..Default::default() }, ); // Create a `BundleAccount` struct to represent the account and its storage. let account = BundleAccount { status: AccountStatus::Changed, info: Some(account_info.clone()), storage, original_info: None, }; // Create a vector of tuples representing the bundle state. let state = vec![(&address, &account)]; // Convert the bundle state into a hashed post state. let hashed_state = HashedPostState::from_bundle_state::<KeccakKeyHasher>(state); // Validate the hashed post state. assert_eq!(hashed_state.accounts.len(), 1); assert_eq!(hashed_state.storages.len(), 1); // Validate the account info. assert_eq!( *hashed_state.accounts.get(&keccak256(address)).unwrap(), Some(account_info.into()) ); } #[test] fn test_hashed_post_state_with_accounts() { // Prepare random addresses and mock account info. let address_1 = Address::random(); let address_2 = Address::random(); let account_info_1 = AccountInfo { balance: U256::from(1000), nonce: 1, code_hash: B256::random(), code: None, }; // Create hashed accounts with addresses. let account_1 = (keccak256(address_1), Some(account_info_1.into())); let account_2 = (keccak256(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))); } #[test] fn test_hashed_post_state_with_storages() { // Prepare random addresses and mock storage entries. 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)); // 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))); } #[test] fn test_hashed_post_state_is_empty() { // Create an empty hashed post state and validate it's empty. let empty_state = HashedPostState::default(); assert!(empty_state.is_empty()); // 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()))]); assert!(!non_empty_state.is_empty()); } fn create_state_for_multi_proof_targets() -> HashedPostState { let mut state = HashedPostState::default(); let addr1 = B256::random(); let addr2 = B256::random(); state.accounts.insert(addr1, Some(Default::default())); state.accounts.insert(addr2, Some(Default::default())); let mut storage = HashedStorage::default(); let slot1 = B256::random(); let slot2 = B256::random(); storage.storage.insert(slot1, FlaggedStorage::new(0, false)); storage.storage.insert(slot2, FlaggedStorage::new(1, false)); state.storages.insert(addr1, storage); state } #[test] fn test_multi_proof_targets_difference_empty_state() { let state = HashedPostState::default(); let excluded = MultiProofTargets::default(); let targets = state.multi_proof_targets_difference(&excluded); assert!(targets.is_empty()); } #[test] fn test_multi_proof_targets_difference_new_account_targets() { let state = create_state_for_multi_proof_targets(); let excluded = MultiProofTargets::default(); // should return all accounts as targets since excluded is empty let targets = state.multi_proof_targets_difference(&excluded); assert_eq!(targets.len(), state.accounts.len()); for addr in state.accounts.keys() { assert!(targets.contains_key(addr)); } } #[test] fn test_multi_proof_targets_difference_new_storage_targets() { let state = create_state_for_multi_proof_targets(); let excluded = MultiProofTargets::default(); let targets = state.multi_proof_targets_difference(&excluded); // verify storage slots are included for accounts with storage for (addr, storage) in &state.storages { assert!(targets.contains_key(addr)); let target_slots = &targets[addr]; assert_eq!(target_slots.len(), storage.storage.len());
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
true
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/src/key.rs
crates/trie/common/src/key.rs
use alloy_primitives::{keccak256, B256}; /// Trait for hashing keys in state. pub trait KeyHasher: Default + Clone + Send + Sync + 'static { /// Hashes the given bytes into a 256-bit hash. fn hash_key<T: AsRef<[u8]>>(bytes: T) -> B256; } /// A key hasher that uses the Keccak-256 hash function. #[derive(Clone, Debug, Default)] pub struct KeccakKeyHasher; impl KeyHasher for KeccakKeyHasher { #[inline] fn hash_key<T: AsRef<[u8]>>(bytes: T) -> B256 { keccak256(bytes) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/src/subnode.rs
crates/trie/common/src/subnode.rs
use super::BranchNodeCompact; use alloc::vec::Vec; /// Walker sub node for storing intermediate state root calculation state in the database. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct StoredSubNode { /// The key of the current node. pub key: Vec<u8>, /// The index of the next child to visit. pub nibble: Option<u8>, /// The node itself. pub node: Option<BranchNodeCompact>, } #[cfg(any(test, feature = "reth-codec"))] impl reth_codecs::Compact for StoredSubNode { fn to_compact<B>(&self, buf: &mut B) -> usize where B: bytes::BufMut + AsMut<[u8]>, { let mut len = 0; buf.put_u16(self.key.len() as u16); buf.put_slice(&self.key[..]); len += 2 + self.key.len(); if let Some(nibble) = self.nibble { buf.put_u8(1); buf.put_u8(nibble); len += 2; } else { buf.put_u8(0); len += 1; } if let Some(node) = &self.node { buf.put_u8(1); len += 1; len += node.to_compact(buf); } else { len += 1; buf.put_u8(0); } len } fn from_compact(mut buf: &[u8], _len: usize) -> (Self, &[u8]) { use bytes::Buf; let key_len = buf.get_u16() as usize; let key = Vec::from(&buf[..key_len]); buf.advance(key_len); let nibbles_exists = buf.get_u8() != 0; let nibble = nibbles_exists.then(|| buf.get_u8()); let node_exists = buf.get_u8() != 0; let node = node_exists.then(|| { let (node, rest) = BranchNodeCompact::from_compact(buf, 0); buf = rest; node }); (Self { key, nibble, node }, buf) } } #[cfg(test)] mod tests { use super::*; use crate::TrieMask; use alloy_primitives::B256; use reth_codecs::Compact; #[test] fn subnode_roundtrip() { let subnode = StoredSubNode { key: vec![], nibble: None, node: Some(BranchNodeCompact { state_mask: TrieMask::new(1), tree_mask: TrieMask::new(0), hash_mask: TrieMask::new(1), hashes: vec![B256::ZERO].into(), root_hash: None, }), }; let mut encoded = vec![]; subnode.to_compact(&mut encoded); let (decoded, _) = StoredSubNode::from_compact(&encoded[..], 0); assert_eq!(subnode, decoded); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/src/lib.rs
crates/trie/common/src/lib.rs
//! Commonly used types for trie usage. #![doc( html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png", html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256", issue_tracker_base_url = "https://github.com/SeismicSystems/seismic-reth/issues/" )] #![cfg_attr(not(test), warn(unused_crate_dependencies))] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #![cfg_attr(not(feature = "std"), no_std)] extern crate alloc; /// In-memory hashed state. mod hashed_state; pub use hashed_state::*; /// Input for trie computation. mod input; pub use input::TrieInput; /// The implementation of hash builder. pub mod hash_builder; /// Constants related to the trie computation. mod constants; pub use constants::*; mod account; pub use account::TrieAccount; mod key; pub use key::{KeccakKeyHasher, KeyHasher}; mod nibbles; pub use nibbles::{Nibbles, StoredNibbles, StoredNibblesSubKey}; mod storage; pub use storage::StorageTrieEntry; mod subnode; pub use subnode::StoredSubNode; /// The implementation of a container for storing intermediate changes to a trie. /// The container indicates when the trie has been modified. pub mod prefix_set; mod proofs; #[cfg(any(test, feature = "test-utils"))] pub use proofs::triehash; pub use proofs::*; pub mod root; /// Buffer for trie updates. pub mod updates; pub mod added_removed_keys; /// Bincode-compatible serde implementations for trie types. /// /// `bincode` crate allows for more efficient serialization of trie types, because it allows /// non-string map keys. /// /// Read more: <https://github.com/paradigmxyz/reth/issues/11370> #[cfg(all(feature = "serde", feature = "serde-bincode-compat"))] pub mod serde_bincode_compat { pub use super::updates::serde_bincode_compat as updates; } /// Re-export pub use alloy_trie::{nodes::*, proof, BranchNodeCompact, HashBuilder, TrieMask, EMPTY_ROOT_HASH};
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/src/proofs.rs
crates/trie/common/src/proofs.rs
//! Merkle trie proofs. 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}, Address, Bytes, B256, U256, }; use alloy_rlp::{encode_fixed_size, Decodable, EMPTY_STRING_CODE}; use alloy_trie::{ nodes::TrieNode, proof::{verify_proof, DecodedProofNodes, ProofNodes, ProofVerificationError}, TrieMask, EMPTY_ROOT_HASH, }; use derive_more::{Deref, DerefMut, IntoIterator}; use itertools::Itertools; use reth_primitives_traits::Account; /// Proof targets map. #[derive(Deref, DerefMut, IntoIterator, Clone, PartialEq, Eq, Default, Debug)] pub struct MultiProofTargets(B256Map<B256Set>); impl FromIterator<(B256, B256Set)> for MultiProofTargets { fn from_iter<T: IntoIterator<Item = (B256, B256Set)>>(iter: T) -> Self { Self(B256Map::from_iter(iter)) } } impl MultiProofTargets { /// Creates an empty `MultiProofTargets` with at least the specified capacity. pub fn with_capacity(capacity: usize) -> Self { Self(B256Map::with_capacity_and_hasher(capacity, Default::default())) } /// Create `MultiProofTargets` with a single account as a target. pub fn account(hashed_address: B256) -> Self { Self::accounts([hashed_address]) } /// Create `MultiProofTargets` with a single account and slots as targets. pub fn account_with_slots<I: IntoIterator<Item = B256>>( hashed_address: B256, slots_iter: I, ) -> Self { Self(B256Map::from_iter([(hashed_address, slots_iter.into_iter().collect())])) } /// Create `MultiProofTargets` only from accounts. pub fn accounts<I: IntoIterator<Item = B256>>(iter: I) -> Self { Self(iter.into_iter().map(|hashed_address| (hashed_address, Default::default())).collect()) } /// Retains the targets representing the difference, /// i.e., the values that are in `self` but not in `other`. pub fn retain_difference(&mut self, other: &Self) { self.0.retain(|hashed_address, hashed_slots| { if let Some(other_hashed_slots) = other.get(hashed_address) { hashed_slots.retain(|hashed_slot| !other_hashed_slots.contains(hashed_slot)); !hashed_slots.is_empty() } else { true } }); } /// Extend multi proof targets with contents of other. pub fn extend(&mut self, other: Self) { self.extend_inner(Cow::Owned(other)); } /// Extend multi proof targets with contents of other. /// /// Slightly less efficient than [`Self::extend`], but preferred to `extend(other.clone())`. pub fn extend_ref(&mut self, other: &Self) { self.extend_inner(Cow::Borrowed(other)); } fn extend_inner(&mut self, other: Cow<'_, Self>) { for (hashed_address, hashed_slots) in other.iter() { self.entry(*hashed_address).or_default().extend(hashed_slots); } } /// Returns an iterator that yields chunks of the specified size. /// /// See [`ChunkedMultiProofTargets`] for more information. pub fn chunks(self, size: usize) -> ChunkedMultiProofTargets { ChunkedMultiProofTargets::new(self, size) } } /// An iterator that yields chunks of the proof targets of at most `size` account and storage /// targets. /// /// For example, for the following proof targets: /// ```text /// - 0x1: [0x10, 0x20, 0x30] /// - 0x2: [0x40] /// - 0x3: [] /// ``` /// /// and `size = 2`, the iterator will yield the following chunks: /// ```text /// - { 0x1: [0x10, 0x20] } /// - { 0x1: [0x30], 0x2: [0x40] } /// - { 0x3: [] } /// ``` /// /// It follows two rules: /// - If account has associated storage slots, each storage slot is counted towards the chunk size. /// - If account has no associated storage slots, the account is counted towards the chunk size. #[derive(Debug)] pub struct ChunkedMultiProofTargets { flattened_targets: alloc::vec::IntoIter<(B256, Option<B256>)>, size: usize, } impl ChunkedMultiProofTargets { fn new(targets: MultiProofTargets, size: usize) -> Self { let flattened_targets = targets .into_iter() .flat_map(|(address, slots)| { if slots.is_empty() { // If the account has no storage slots, we still need to yield the account // address with empty storage slots. `None` here means that // there's no storage slot to fetch. itertools::Either::Left(core::iter::once((address, None))) } else { itertools::Either::Right( slots.into_iter().map(move |slot| (address, Some(slot))), ) } }) .sorted(); Self { flattened_targets, size } } } impl Iterator for ChunkedMultiProofTargets { type Item = MultiProofTargets; fn next(&mut self) -> Option<Self::Item> { let chunk = self.flattened_targets.by_ref().take(self.size).fold( MultiProofTargets::default(), |mut acc, (address, slot)| { let entry = acc.entry(address).or_default(); if let Some(slot) = slot { entry.insert(slot); } acc }, ); if chunk.is_empty() { None } else { Some(chunk) } } } /// The state multiproof of target accounts and multiproofs of their storage tries. /// Multiproof is effectively a state subtrie that only contains the nodes /// in the paths of target accounts. #[derive(Clone, Default, Debug, PartialEq, Eq)] pub struct MultiProof { /// State trie multiproof for requested accounts. pub account_subtree: ProofNodes, /// The hash masks of the branch nodes in the account proof. pub branch_node_hash_masks: HashMap<Nibbles, TrieMask>, /// The tree masks of the branch nodes in the account proof. pub branch_node_tree_masks: HashMap<Nibbles, TrieMask>, /// Storage trie multiproofs. pub storages: B256Map<StorageMultiProof>, } impl MultiProof { /// Returns true if the multiproof is empty. pub fn is_empty(&self) -> bool { self.account_subtree.is_empty() && self.branch_node_hash_masks.is_empty() && self.branch_node_tree_masks.is_empty() && self.storages.is_empty() } /// Return the account proof nodes for the given account path. pub fn account_proof_nodes(&self, path: &Nibbles) -> Vec<(Nibbles, Bytes)> { self.account_subtree.matching_nodes_sorted(path) } /// Return the storage proof nodes for the given storage slots of the account path. pub fn storage_proof_nodes( &self, hashed_address: B256, slots: impl IntoIterator<Item = B256>, ) -> Vec<(B256, Vec<(Nibbles, Bytes)>)> { self.storages .get(&hashed_address) .map(|storage_mp| { slots .into_iter() .map(|slot| { let nibbles = Nibbles::unpack(slot); (slot, storage_mp.subtree.matching_nodes_sorted(&nibbles)) }) .collect() }) .unwrap_or_default() } /// Construct the account proof from the multiproof. pub fn account_proof( &self, address: Address, slots: &[B256], ) -> Result<AccountProof, alloy_rlp::Error> { let hashed_address = keccak256(address); let nibbles = Nibbles::unpack(hashed_address); // Retrieve the account proof. let proof = self .account_proof_nodes(&nibbles) .into_iter() .map(|(_, node)| node) .collect::<Vec<_>>(); // Inspect the last node in the proof. If it's a leaf node with matching suffix, // then the node contains the encoded trie account. let info = 'info: { if let Some(last) = proof.last() { if let TrieNode::Leaf(leaf) = TrieNode::decode(&mut &last[..])? { if nibbles.ends_with(&leaf.key) { let account = TrieAccount::decode(&mut &leaf.value[..])?; break 'info Some(Account { balance: account.balance, nonce: account.nonce, bytecode_hash: (account.code_hash != KECCAK_EMPTY) .then_some(account.code_hash), }); } } } None }; // Retrieve proofs for requested storage slots. let storage_multiproof = self.storages.get(&hashed_address); let storage_root = storage_multiproof.map(|m| m.root).unwrap_or(EMPTY_ROOT_HASH); let mut storage_proofs = Vec::with_capacity(slots.len()); for slot in slots { let proof = if let Some(multiproof) = &storage_multiproof { multiproof.storage_proof(*slot)? } else { StorageProof::new(*slot) }; storage_proofs.push(proof); } Ok(AccountProof { address, info, proof, storage_root, storage_proofs }) } /// Extends this multiproof with another one, merging both account and storage /// proofs. pub fn extend(&mut self, other: Self) { self.account_subtree.extend_from(other.account_subtree); self.branch_node_hash_masks.extend(other.branch_node_hash_masks); self.branch_node_tree_masks.extend(other.branch_node_tree_masks); for (hashed_address, storage) in other.storages { match self.storages.entry(hashed_address) { hash_map::Entry::Occupied(mut entry) => { debug_assert_eq!(entry.get().root, storage.root); let entry = entry.get_mut(); entry.subtree.extend_from(storage.subtree); entry.branch_node_hash_masks.extend(storage.branch_node_hash_masks); entry.branch_node_tree_masks.extend(storage.branch_node_tree_masks); } hash_map::Entry::Vacant(entry) => { entry.insert(storage); } } } } /// Create a [`MultiProof`] from a [`StorageMultiProof`]. pub fn from_storage_proof(hashed_address: B256, storage_proof: StorageMultiProof) -> Self { Self { storages: B256Map::from_iter([(hashed_address, storage_proof)]), ..Default::default() } } } /// This is a type of [`MultiProof`] that uses decoded proofs, meaning these proofs are stored as a /// collection of [`TrieNode`]s instead of RLP-encoded bytes. #[derive(Clone, Default, Debug, PartialEq, Eq)] pub struct DecodedMultiProof { /// State trie multiproof for requested accounts. pub account_subtree: DecodedProofNodes, /// The hash masks of the branch nodes in the account proof. pub branch_node_hash_masks: HashMap<Nibbles, TrieMask>, /// The tree masks of the branch nodes in the account proof. pub branch_node_tree_masks: HashMap<Nibbles, TrieMask>, /// Storage trie multiproofs. pub storages: B256Map<DecodedStorageMultiProof>, } impl DecodedMultiProof { /// Returns true if the multiproof is empty. pub fn is_empty(&self) -> bool { self.account_subtree.is_empty() && self.branch_node_hash_masks.is_empty() && self.branch_node_tree_masks.is_empty() && self.storages.is_empty() } /// Return the account proof nodes for the given account path. pub fn account_proof_nodes(&self, path: &Nibbles) -> Vec<(Nibbles, TrieNode)> { self.account_subtree.matching_nodes_sorted(path) } /// Return the storage proof nodes for the given storage slots of the account path. pub fn storage_proof_nodes( &self, hashed_address: B256, slots: impl IntoIterator<Item = B256>, ) -> Vec<(B256, Vec<(Nibbles, TrieNode)>)> { self.storages .get(&hashed_address) .map(|storage_mp| { slots .into_iter() .map(|slot| { let nibbles = Nibbles::unpack(slot); (slot, storage_mp.subtree.matching_nodes_sorted(&nibbles)) }) .collect() }) .unwrap_or_default() } /// Construct the account proof from the multiproof. pub fn account_proof( &self, address: Address, slots: &[B256], ) -> Result<DecodedAccountProof, alloy_rlp::Error> { let hashed_address = keccak256(address); let nibbles = Nibbles::unpack(hashed_address); // Retrieve the account proof. let proof = self .account_proof_nodes(&nibbles) .into_iter() .map(|(_, node)| node) .collect::<Vec<_>>(); // Inspect the last node in the proof. If it's a leaf node with matching suffix, // then the node contains the encoded trie account. let info = 'info: { if let Some(TrieNode::Leaf(leaf)) = proof.last() { if nibbles.ends_with(&leaf.key) { let account = TrieAccount::decode(&mut &leaf.value[..])?; break 'info Some(Account { balance: account.balance, nonce: account.nonce, bytecode_hash: (account.code_hash != KECCAK_EMPTY) .then_some(account.code_hash), }); } } None }; // Retrieve proofs for requested storage slots. let storage_multiproof = self.storages.get(&hashed_address); let storage_root = storage_multiproof.map(|m| m.root).unwrap_or(EMPTY_ROOT_HASH); let mut storage_proofs = Vec::with_capacity(slots.len()); for slot in slots { let proof = if let Some(multiproof) = &storage_multiproof { multiproof.storage_proof(*slot)? } else { DecodedStorageProof::new(*slot) }; storage_proofs.push(proof); } Ok(DecodedAccountProof { address, info, proof, storage_root, storage_proofs }) } /// Extends this multiproof with another one, merging both account and storage /// proofs. pub fn extend(&mut self, other: Self) { self.account_subtree.extend_from(other.account_subtree); self.branch_node_hash_masks.extend(other.branch_node_hash_masks); self.branch_node_tree_masks.extend(other.branch_node_tree_masks); for (hashed_address, storage) in other.storages { match self.storages.entry(hashed_address) { hash_map::Entry::Occupied(mut entry) => { debug_assert_eq!(entry.get().root, storage.root); let entry = entry.get_mut(); entry.subtree.extend_from(storage.subtree); entry.branch_node_hash_masks.extend(storage.branch_node_hash_masks); entry.branch_node_tree_masks.extend(storage.branch_node_tree_masks); } hash_map::Entry::Vacant(entry) => { entry.insert(storage); } } } } /// Create a [`DecodedMultiProof`] from a [`DecodedStorageMultiProof`]. pub fn from_storage_proof( hashed_address: B256, storage_proof: DecodedStorageMultiProof, ) -> Self { Self { storages: B256Map::from_iter([(hashed_address, storage_proof)]), ..Default::default() } } } impl TryFrom<MultiProof> for DecodedMultiProof { type Error = alloy_rlp::Error; fn try_from(multi_proof: MultiProof) -> Result<Self, Self::Error> { let account_subtree = DecodedProofNodes::try_from(multi_proof.account_subtree)?; let storages = multi_proof .storages .into_iter() .map(|(address, storage)| Ok((address, storage.try_into()?))) .collect::<Result<B256Map<_>, alloy_rlp::Error>>()?; Ok(Self { account_subtree, branch_node_hash_masks: multi_proof.branch_node_hash_masks, branch_node_tree_masks: multi_proof.branch_node_tree_masks, storages, }) } } /// The merkle multiproof of storage trie. #[derive(Clone, Debug, PartialEq, Eq)] pub struct StorageMultiProof { /// Storage trie root. pub root: B256, /// Storage multiproof for requested slots. pub subtree: ProofNodes, /// The hash masks of the branch nodes in the storage proof. pub branch_node_hash_masks: HashMap<Nibbles, TrieMask>, /// The tree masks of the branch nodes in the storage proof. pub branch_node_tree_masks: HashMap<Nibbles, TrieMask>, } impl StorageMultiProof { /// Create new storage multiproof for empty trie. pub fn empty() -> Self { Self { root: EMPTY_ROOT_HASH, subtree: ProofNodes::from_iter([( Nibbles::default(), Bytes::from([EMPTY_STRING_CODE]), )]), branch_node_hash_masks: HashMap::default(), branch_node_tree_masks: HashMap::default(), } } /// Return storage proofs for the target storage slot (unhashed). pub fn storage_proof(&self, slot: B256) -> Result<StorageProof, alloy_rlp::Error> { let nibbles = Nibbles::unpack(keccak256(slot)); // Retrieve the storage proof. let proof = self .subtree .matching_nodes_iter(&nibbles) .sorted_by(|a, b| a.0.cmp(b.0)) .map(|(_, node)| node.clone()) .collect::<Vec<_>>(); // Inspect the last node in the proof. If it's a leaf node with matching suffix, // then the node contains the encoded slot value. let mut is_private = false; let value = 'value: { if let Some(last) = proof.last() { if let TrieNode::Leaf(leaf) = TrieNode::decode(&mut &last[..])? { if nibbles.ends_with(&leaf.key) { is_private = leaf.is_private; break 'value U256::decode(&mut &leaf.value[..])?; } } } U256::ZERO }; Ok(StorageProof { key: slot, nibbles, value, is_private, proof }) } } /// The decoded merkle multiproof for a storage trie. #[derive(Clone, Debug, PartialEq, Eq)] pub struct DecodedStorageMultiProof { /// Storage trie root. pub root: B256, /// Storage multiproof for requested slots. pub subtree: DecodedProofNodes, /// The hash masks of the branch nodes in the storage proof. pub branch_node_hash_masks: HashMap<Nibbles, TrieMask>, /// The tree masks of the branch nodes in the storage proof. pub branch_node_tree_masks: HashMap<Nibbles, TrieMask>, } impl DecodedStorageMultiProof { /// Create new storage multiproof for empty trie. pub fn empty() -> Self { Self { root: EMPTY_ROOT_HASH, subtree: DecodedProofNodes::from_iter([(Nibbles::default(), TrieNode::EmptyRoot)]), branch_node_hash_masks: HashMap::default(), branch_node_tree_masks: HashMap::default(), } } /// Return storage proofs for the target storage slot (unhashed). pub fn storage_proof(&self, slot: B256) -> Result<DecodedStorageProof, alloy_rlp::Error> { let nibbles = Nibbles::unpack(keccak256(slot)); // Retrieve the storage proof. let proof = self .subtree .matching_nodes_iter(&nibbles) .sorted_by(|a, b| a.0.cmp(b.0)) .map(|(_, node)| node.clone()) .collect::<Vec<_>>(); // Inspect the last node in the proof. If it's a leaf node with matching suffix, // then the node contains the encoded slot value. let value = 'value: { if let Some(TrieNode::Leaf(leaf)) = proof.last() { if nibbles.ends_with(&leaf.key) { break 'value U256::decode(&mut &leaf.value[..])?; } } U256::ZERO }; Ok(DecodedStorageProof { key: slot, nibbles, value, proof }) } } impl TryFrom<StorageMultiProof> for DecodedStorageMultiProof { type Error = alloy_rlp::Error; fn try_from(multi_proof: StorageMultiProof) -> Result<Self, Self::Error> { let subtree = DecodedProofNodes::try_from(multi_proof.subtree)?; Ok(Self { root: multi_proof.root, subtree, branch_node_hash_masks: multi_proof.branch_node_hash_masks, branch_node_tree_masks: multi_proof.branch_node_tree_masks, }) } } /// The merkle proof with the relevant account info. #[derive(Clone, PartialEq, Eq, Debug)] #[cfg_attr(any(test, feature = "serde"), derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(any(test, feature = "serde"), serde(rename_all = "camelCase"))] pub struct AccountProof { /// The address associated with the account. pub address: Address, /// Account info, if any. pub info: Option<Account>, /// Array of rlp-serialized merkle trie nodes which starting from the root node and /// following the path of the hashed address as key. pub proof: Vec<Bytes>, /// The storage trie root. pub storage_root: B256, /// Array of storage proofs as requested. pub storage_proofs: Vec<StorageProof>, } #[cfg(feature = "eip1186")] impl AccountProof { /// Convert into an EIP-1186 account proof response pub fn into_eip1186_response( self, slots: Vec<alloy_serde::JsonStorageKey>, ) -> alloy_rpc_types_eth::EIP1186AccountProofResponse { let info = self.info.unwrap_or_default(); alloy_rpc_types_eth::EIP1186AccountProofResponse { address: self.address, balance: info.balance, code_hash: info.get_bytecode_hash(), nonce: info.nonce, storage_hash: self.storage_root, account_proof: self.proof, storage_proof: self .storage_proofs .into_iter() .filter_map(|proof| { let input_slot = slots.iter().find(|s| s.as_b256() == proof.key)?; Some(proof.into_eip1186_proof(*input_slot)) }) .collect(), } } /// Converts an /// [`EIP1186AccountProofResponse`](alloy_rpc_types_eth::EIP1186AccountProofResponse) to an /// [`AccountProof`]. /// /// This is the inverse of [`Self::into_eip1186_response`] pub fn from_eip1186_proof(proof: alloy_rpc_types_eth::EIP1186AccountProofResponse) -> Self { let alloy_rpc_types_eth::EIP1186AccountProofResponse { nonce, address, balance, code_hash, storage_hash, account_proof, storage_proof, .. } = proof; let storage_proofs = storage_proof.into_iter().map(Into::into).collect(); let (storage_root, info) = if nonce == 0 && balance.is_zero() && storage_hash.is_zero() && code_hash == KECCAK_EMPTY { // Account does not exist in state. Return `None` here to prevent proof // verification. (EMPTY_ROOT_HASH, None) } else { (storage_hash, Some(Account { nonce, balance, bytecode_hash: code_hash.into() })) }; Self { address, info, proof: account_proof, storage_root, storage_proofs } } } #[cfg(feature = "eip1186")] impl From<alloy_rpc_types_eth::EIP1186AccountProofResponse> for AccountProof { fn from(proof: alloy_rpc_types_eth::EIP1186AccountProofResponse) -> Self { Self::from_eip1186_proof(proof) } } impl Default for AccountProof { fn default() -> Self { Self::new(Address::default()) } } impl AccountProof { /// Create new account proof entity. pub const fn new(address: Address) -> Self { Self { address, info: None, proof: Vec::new(), storage_root: EMPTY_ROOT_HASH, storage_proofs: Vec::new(), } } /// Verify the storage proofs and account proof against the provided state root. pub fn verify(&self, root: B256) -> Result<(), ProofVerificationError> { // Verify storage proofs. for storage_proof in &self.storage_proofs { storage_proof.verify(self.storage_root)?; } // Verify the account proof. let expected = if self.info.is_none() && self.storage_root == EMPTY_ROOT_HASH { None } else { Some(alloy_rlp::encode( self.info.unwrap_or_default().into_trie_account(self.storage_root), )) }; let nibbles = Nibbles::unpack(keccak256(self.address)); let account_node_is_private = false; // account nodes are always public verify_proof(root, nibbles, expected, account_node_is_private, &self.proof) } } /// The merkle proof with the relevant account info. #[derive(Clone, PartialEq, Eq, Debug)] pub struct DecodedAccountProof { /// The address associated with the account. pub address: Address, /// Account info. pub info: Option<Account>, /// Array of merkle trie nodes which starting from the root node and following the path of the /// hashed address as key. pub proof: Vec<TrieNode>, /// The storage trie root. pub storage_root: B256, /// Array of storage proofs as requested. pub storage_proofs: Vec<DecodedStorageProof>, } impl Default for DecodedAccountProof { fn default() -> Self { Self::new(Address::default()) } } impl DecodedAccountProof { /// Create new account proof entity. pub const fn new(address: Address) -> Self { Self { address, info: None, proof: Vec::new(), storage_root: EMPTY_ROOT_HASH, storage_proofs: Vec::new(), } } } /// The merkle proof of the storage entry. #[derive(Clone, PartialEq, Eq, Default, Debug)] #[cfg_attr(any(test, feature = "serde"), derive(serde::Serialize, serde::Deserialize))] pub struct StorageProof { /// The raw storage key. pub key: B256, /// The hashed storage key nibbles. pub nibbles: Nibbles, /// The storage value. pub value: U256, /// Whether the storge node is private. pub is_private: bool, /// Array of rlp-serialized merkle trie nodes which starting from the storage root node and /// following the path of the hashed storage slot as key. pub proof: Vec<Bytes>, } impl StorageProof { /// Create new storage proof from the storage slot. pub fn new(key: B256) -> Self { let nibbles = Nibbles::unpack(keccak256(key)); Self { key, nibbles, ..Default::default() } } /// Create new storage proof from the storage slot and its pre-hashed image. pub fn new_with_hashed(key: B256, hashed_key: B256) -> Self { Self { key, nibbles: Nibbles::unpack(hashed_key), ..Default::default() } } /// Create new storage proof from the storage slot and its pre-hashed image. pub fn new_with_nibbles(key: B256, nibbles: Nibbles) -> Self { Self { key, nibbles, ..Default::default() } } /// Set proof nodes on storage proof. pub fn with_proof(mut self, proof: Vec<Bytes>) -> Self { self.proof = proof; self } /// Verify the proof against the provided storage root. pub fn verify(&self, root: B256) -> Result<(), ProofVerificationError> { let expected = if self.value.is_zero() { None } else { Some(encode_fixed_size(&self.value).to_vec()) }; verify_proof(root, self.nibbles, expected, self.is_private, &self.proof) } } #[cfg(feature = "eip1186")] impl StorageProof { /// Convert into an EIP-1186 storage proof pub fn into_eip1186_proof( self, slot: alloy_serde::JsonStorageKey, ) -> alloy_rpc_types_eth::EIP1186StorageProof { alloy_rpc_types_eth::EIP1186StorageProof { key: slot, value: self.value, proof: self.proof } } /// Convert from an /// [`EIP1186StorageProof`](alloy_rpc_types_eth::EIP1186StorageProof) /// /// This is the inverse of [`Self::into_eip1186_proof`]. pub fn from_eip1186_proof(storage_proof: alloy_rpc_types_eth::EIP1186StorageProof) -> Self { Self { value: storage_proof.value, proof: storage_proof.proof, ..Self::new(storage_proof.key.as_b256()) } } } #[cfg(feature = "eip1186")] impl From<alloy_rpc_types_eth::EIP1186StorageProof> for StorageProof { fn from(proof: alloy_rpc_types_eth::EIP1186StorageProof) -> Self { Self::from_eip1186_proof(proof) } } /// The merkle proof of the storage entry, using decoded proofs. #[derive(Clone, PartialEq, Eq, Default, Debug)] pub struct DecodedStorageProof { /// The raw storage key. pub key: B256, /// The hashed storage key nibbles. pub nibbles: Nibbles, /// The storage value. pub value: U256, /// Array of merkle trie nodes which starting from the storage root node and following the path /// of the hashed storage slot as key. pub proof: Vec<TrieNode>, } impl DecodedStorageProof { /// Create new storage proof from the storage slot. pub fn new(key: B256) -> Self { let nibbles = Nibbles::unpack(keccak256(key)); Self { key, nibbles, ..Default::default() } } /// Create new storage proof from the storage slot and its pre-hashed image. pub fn new_with_hashed(key: B256, hashed_key: B256) -> Self { Self { key, nibbles: Nibbles::unpack(hashed_key), ..Default::default() } } /// Create new storage proof from the storage slot and its pre-hashed image. pub fn new_with_nibbles(key: B256, nibbles: Nibbles) -> Self { Self { key, nibbles, ..Default::default() } } /// Set proof nodes on storage proof. pub fn with_proof(mut self, proof: Vec<TrieNode>) -> Self { self.proof = proof; self } } /// Implementation of hasher using our keccak256 hashing function /// for compatibility with `triehash` crate. #[cfg(any(test, feature = "test-utils"))] pub mod triehash { use alloy_primitives::{keccak256, B256}; use alloy_rlp::RlpEncodable; use hash_db::Hasher; use plain_hasher::PlainHasher; /// A [Hasher] that calculates a keccak256 hash of the given data. #[derive(Default, Debug, Clone, PartialEq, Eq, RlpEncodable)] #[non_exhaustive] pub struct KeccakHasher; #[cfg(any(test, feature = "test-utils"))] impl Hasher for KeccakHasher { type Out = B256; type StdHasher = PlainHasher; const LENGTH: usize = 32; fn hash(x: &[u8]) -> Self::Out { keccak256(x) } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_multiproof_extend_account_proofs() { let mut proof1 = MultiProof::default(); let mut proof2 = MultiProof::default(); let addr1 = B256::random(); let addr2 = B256::random(); proof1.account_subtree.insert( Nibbles::unpack(addr1), alloy_rlp::encode_fixed_size(&U256::from(42)).to_vec().into(), ); proof2.account_subtree.insert( Nibbles::unpack(addr2), alloy_rlp::encode_fixed_size(&U256::from(43)).to_vec().into(), ); proof1.extend(proof2); assert!(proof1.account_subtree.contains_key(&Nibbles::unpack(addr1))); assert!(proof1.account_subtree.contains_key(&Nibbles::unpack(addr2))); } #[test] fn test_multiproof_extend_storage_proofs() { let mut proof1 = MultiProof::default(); let mut proof2 = MultiProof::default(); let addr = B256::random(); let root = B256::random(); let mut subtree1 = ProofNodes::default(); subtree1.insert( Nibbles::from_nibbles(vec![0]), alloy_rlp::encode_fixed_size(&U256::from(42)).to_vec().into(), ); proof1.storages.insert( addr, StorageMultiProof { root, subtree: subtree1,
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
true
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/src/added_removed_keys.rs
crates/trie/common/src/added_removed_keys.rs
//! Tracking of keys having been added and removed from the tries. use crate::HashedPostState; use alloy_primitives::{map::B256Map, B256}; use alloy_trie::proof::AddedRemovedKeys; /// Tracks added and removed keys across account and storage tries. #[derive(Debug, Clone)] pub struct MultiAddedRemovedKeys { account: AddedRemovedKeys, storages: B256Map<AddedRemovedKeys>, } /// Returns [`AddedRemovedKeys`] with default parameters. This is necessary while we are not yet /// tracking added keys. fn default_added_removed_keys() -> AddedRemovedKeys { AddedRemovedKeys::default().with_assume_added(true) } impl Default for MultiAddedRemovedKeys { fn default() -> Self { Self::new() } } impl MultiAddedRemovedKeys { /// Returns a new instance. pub fn new() -> Self { Self { account: default_added_removed_keys(), storages: Default::default() } } /// Updates the set of removed keys based on a [`HashedPostState`]. /// /// Storage keys set to [`alloy_primitives::U256::ZERO`] are added to the set for their /// respective account. Keys set to any other value are removed from their respective /// account. pub fn update_with_state(&mut self, update: &HashedPostState) { for (hashed_address, storage) in &update.storages { let account = update .accounts .get(hashed_address) .map(|entry| entry.unwrap_or_default()) .unwrap_or_default(); if storage.wiped { self.storages.remove(hashed_address); if account.is_empty() { self.account.insert_removed(*hashed_address); } continue } let storage_removed_keys = self.storages.entry(*hashed_address).or_insert_with(default_added_removed_keys); for (key, val) in &storage.storage { if val.is_zero() { storage_removed_keys.insert_removed(*key); } else { storage_removed_keys.remove_removed(key); } } if !account.is_empty() { self.account.remove_removed(hashed_address); } } } /// Returns a [`AddedRemovedKeys`] for the storage trie of a particular account, if any. pub fn get_storage(&self, hashed_address: &B256) -> Option<&AddedRemovedKeys> { self.storages.get(hashed_address) } /// Returns an [`AddedRemovedKeys`] for tracking account-level changes. pub const fn get_accounts(&self) -> &AddedRemovedKeys { &self.account } /// Marks an account as existing, and therefore having storage. pub fn touch_accounts(&mut self, addresses: impl Iterator<Item = B256>) { for address in addresses { self.storages.entry(address).or_insert_with(default_added_removed_keys); } } } #[cfg(test)] mod tests { use super::*; use crate::HashedStorage; use alloy_primitives::U256; use reth_primitives_traits::Account; #[test] fn test_update_with_state_storage_keys_non_zero() { let mut multi_keys = MultiAddedRemovedKeys::new(); let mut update = HashedPostState::default(); let addr = B256::random(); let slot1 = B256::random(); let slot2 = B256::random(); // First mark slots as removed let mut storage = HashedStorage::default(); storage.storage.insert(slot1, U256::ZERO.into()); storage.storage.insert(slot2, U256::ZERO.into()); update.storages.insert(addr, storage); multi_keys.update_with_state(&update); // Verify they are removed assert!(multi_keys.get_storage(&addr).unwrap().is_removed(&slot1)); assert!(multi_keys.get_storage(&addr).unwrap().is_removed(&slot2)); // Now update with non-zero values let mut update2 = HashedPostState::default(); let mut storage2 = HashedStorage::default(); storage2.storage.insert(slot1, U256::from(100).into()); storage2.storage.insert(slot2, U256::from(200).into()); update2.storages.insert(addr, storage2); multi_keys.update_with_state(&update2); // Slots should no longer be marked as removed let storage_keys = multi_keys.get_storage(&addr).unwrap(); assert!(!storage_keys.is_removed(&slot1)); assert!(!storage_keys.is_removed(&slot2)); } #[test] fn test_update_with_state_wiped_storage() { let mut multi_keys = MultiAddedRemovedKeys::new(); let mut update = HashedPostState::default(); let addr = B256::random(); let slot1 = B256::random(); // First add some removed keys let mut storage = HashedStorage::default(); storage.storage.insert(slot1, U256::ZERO.into()); update.storages.insert(addr, storage); multi_keys.update_with_state(&update); assert!(multi_keys.get_storage(&addr).is_some()); // Now wipe the storage let mut update2 = HashedPostState::default(); let wiped_storage = HashedStorage::new(true); update2.storages.insert(addr, wiped_storage); multi_keys.update_with_state(&update2); // Storage and account should be removed assert!(multi_keys.get_storage(&addr).is_none()); assert!(multi_keys.get_accounts().is_removed(&addr)); } #[test] fn test_update_with_state_account_tracking() { let mut multi_keys = MultiAddedRemovedKeys::new(); let mut update = HashedPostState::default(); let addr = B256::random(); let slot = B256::random(); // Add storage with zero value and empty account let mut storage = HashedStorage::default(); storage.storage.insert(slot, U256::ZERO.into()); update.storages.insert(addr, storage); // Account is implicitly empty (not in accounts map) multi_keys.update_with_state(&update); // Storage should have removed keys but account should not be removed assert!(multi_keys.get_storage(&addr).unwrap().is_removed(&slot)); assert!(!multi_keys.get_accounts().is_removed(&addr)); // Now clear all removed storage keys and keep account empty let mut update2 = HashedPostState::default(); let mut storage2 = HashedStorage::default(); storage2.storage.insert(slot, U256::from(100).into()); // Non-zero removes from removed set update2.storages.insert(addr, storage2); multi_keys.update_with_state(&update2); // Account should not be marked as removed still assert!(!multi_keys.get_accounts().is_removed(&addr)); } #[test] fn test_update_with_state_account_with_balance() { let mut multi_keys = MultiAddedRemovedKeys::new(); let mut update = HashedPostState::default(); let addr = B256::random(); // Add account with non-empty state (has balance) let account = Account { balance: U256::from(1000), nonce: 0, bytecode_hash: None }; update.accounts.insert(addr, Some(account)); // Add empty storage let storage = HashedStorage::default(); update.storages.insert(addr, storage); multi_keys.update_with_state(&update); // Account should not be marked as removed because it has balance assert!(!multi_keys.get_accounts().is_removed(&addr)); // Now wipe the storage let mut update2 = HashedPostState::default(); let wiped_storage = HashedStorage::new(true); update2.storages.insert(addr, wiped_storage); update2.accounts.insert(addr, Some(account)); multi_keys.update_with_state(&update2); // Storage should be None, but account should not be removed. assert!(multi_keys.get_storage(&addr).is_none()); assert!(!multi_keys.get_accounts().is_removed(&addr)); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/src/root.rs
crates/trie/common/src/root.rs
//! Common root computation functions. // Re-export for convenience. #[doc(inline)] pub use alloy_trie::root::{ state_root, state_root_ref_unhashed, state_root_unhashed, state_root_unsorted, storage_root, storage_root_unhashed, storage_root_unsorted, };
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/src/storage.rs
crates/trie/common/src/storage.rs
use super::{BranchNodeCompact, StoredNibblesSubKey}; /// Account storage trie node. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] #[cfg_attr(any(test, feature = "serde"), derive(serde::Serialize, serde::Deserialize))] pub struct StorageTrieEntry { /// The nibbles of the intermediate node pub nibbles: StoredNibblesSubKey, /// Encoded node. pub node: BranchNodeCompact, } // NOTE: Removing reth_codec and manually encode subkey // and compress second part of the value. If we have compression // over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey #[cfg(any(test, feature = "reth-codec"))] impl reth_codecs::Compact for StorageTrieEntry { fn to_compact<B>(&self, buf: &mut B) -> usize where B: bytes::BufMut + AsMut<[u8]>, { let nibbles_len = self.nibbles.to_compact(buf); let node_len = self.node.to_compact(buf); nibbles_len + node_len } fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) { let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65); let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65); let this = Self { nibbles, node }; (this, buf) } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/src/prefix_set.rs
crates/trie/common/src/prefix_set.rs
use crate::Nibbles; use alloc::{sync::Arc, vec::Vec}; use alloy_primitives::map::{B256Map, B256Set}; /// Collection of mutable prefix sets. #[derive(Clone, Default, Debug)] pub struct TriePrefixSetsMut { /// A set of account prefixes that have changed. pub account_prefix_set: PrefixSetMut, /// A map containing storage changes with the hashed address as key and a set of storage key /// prefixes as the value. pub storage_prefix_sets: B256Map<PrefixSetMut>, /// A set of hashed addresses of destroyed accounts. pub destroyed_accounts: B256Set, } impl TriePrefixSetsMut { /// Returns `true` if all prefix sets are empty. pub fn is_empty(&self) -> bool { self.account_prefix_set.is_empty() && self.storage_prefix_sets.is_empty() && self.destroyed_accounts.is_empty() } /// Extends prefix sets with contents of another prefix set. pub fn extend(&mut self, other: Self) { self.account_prefix_set.extend(other.account_prefix_set); for (hashed_address, prefix_set) in other.storage_prefix_sets { self.storage_prefix_sets.entry(hashed_address).or_default().extend(prefix_set); } self.destroyed_accounts.extend(other.destroyed_accounts); } /// Returns a `TriePrefixSets` with the same elements as these sets. /// /// If not yet sorted, the elements will be sorted and deduplicated. pub fn freeze(self) -> TriePrefixSets { TriePrefixSets { account_prefix_set: self.account_prefix_set.freeze(), storage_prefix_sets: self .storage_prefix_sets .into_iter() .map(|(hashed_address, prefix_set)| (hashed_address, prefix_set.freeze())) .collect(), destroyed_accounts: self.destroyed_accounts, } } /// Clears the prefix sets and destroyed accounts map. pub fn clear(&mut self) { self.destroyed_accounts.clear(); self.storage_prefix_sets.clear(); self.account_prefix_set.clear(); } } /// Collection of trie prefix sets. #[derive(Default, Debug, Clone)] pub struct TriePrefixSets { /// A set of account prefixes that have changed. pub account_prefix_set: PrefixSet, /// A map containing storage changes with the hashed address as key and a set of storage key /// prefixes as the value. pub storage_prefix_sets: B256Map<PrefixSet>, /// A set of hashed addresses of destroyed accounts. pub destroyed_accounts: B256Set, } /// A container for efficiently storing and checking for the presence of key prefixes. /// /// This data structure stores a set of `Nibbles` and provides methods to insert /// new elements and check whether any existing element has a given prefix. /// /// Internally, this implementation uses a `Vec` and aims to act like a `BTreeSet` in being both /// sorted and deduplicated. It does this by keeping a `sorted` flag. The `sorted` flag represents /// whether or not the `Vec` is definitely sorted. When a new element is added, it is set to /// `false.`. The `Vec` is sorted and deduplicated when `sorted` is `true` and: /// * An element is being checked for inclusion (`contains`), or /// * The set is being converted into an immutable `PrefixSet` (`freeze`) /// /// This means that a `PrefixSet` will always be sorted and deduplicated when constructed from a /// `PrefixSetMut`. /// /// # Examples /// /// ``` /// use reth_trie_common::{prefix_set::PrefixSetMut, Nibbles}; /// /// let mut prefix_set_mut = PrefixSetMut::default(); /// prefix_set_mut.insert(Nibbles::from_nibbles_unchecked(&[0xa, 0xb])); /// prefix_set_mut.insert(Nibbles::from_nibbles_unchecked(&[0xa, 0xb, 0xc])); /// let mut prefix_set = prefix_set_mut.freeze(); /// assert!(prefix_set.contains(&Nibbles::from_nibbles_unchecked([0xa, 0xb]))); /// assert!(prefix_set.contains(&Nibbles::from_nibbles_unchecked([0xa, 0xb, 0xc]))); /// ``` #[derive(PartialEq, Eq, Clone, Default, Debug)] pub struct PrefixSetMut { /// Flag indicating that any entry should be considered changed. /// If set, the keys will be discarded. all: bool, keys: Vec<Nibbles>, } impl<I> From<I> for PrefixSetMut where I: IntoIterator<Item = Nibbles>, { fn from(value: I) -> Self { Self { all: false, keys: value.into_iter().collect() } } } impl PrefixSetMut { /// Create [`PrefixSetMut`] with pre-allocated capacity. pub fn with_capacity(capacity: usize) -> Self { Self { all: false, keys: Vec::with_capacity(capacity) } } /// Create [`PrefixSetMut`] that considers all key changed. pub const fn all() -> Self { Self { all: true, keys: Vec::new() } } /// Inserts the given `nibbles` into the set. pub fn insert(&mut self, nibbles: Nibbles) { self.keys.push(nibbles); } /// Extend prefix set with contents of another prefix set. pub fn extend(&mut self, other: Self) { self.all |= other.all; self.keys.extend(other.keys); } /// Extend prefix set keys with contents of provided iterator. pub fn extend_keys<I>(&mut self, keys: I) where I: IntoIterator<Item = Nibbles>, { self.keys.extend(keys); } /// Returns the number of elements in the set. pub const fn len(&self) -> usize { self.keys.len() } /// Returns `true` if the set is empty. pub const fn is_empty(&self) -> bool { self.keys.is_empty() } /// Clears the inner vec for reuse, setting `all` to `false`. pub fn clear(&mut self) { self.all = false; self.keys.clear(); } /// Returns a `PrefixSet` with the same elements as this set. /// /// If not yet sorted, the elements will be sorted and deduplicated. pub fn freeze(mut self) -> PrefixSet { if self.all { PrefixSet { index: 0, all: true, keys: Arc::new(Vec::new()) } } else { self.keys.sort_unstable(); self.keys.dedup(); // We need to shrink in both the sorted and non-sorted cases because deduping may have // occurred either on `freeze`, or during `contains`. self.keys.shrink_to_fit(); PrefixSet { index: 0, all: false, keys: Arc::new(self.keys) } } } } /// A sorted prefix set that has an immutable _sorted_ list of unique keys. /// /// See also [`PrefixSetMut::freeze`]. #[derive(Debug, Default, Clone)] pub struct PrefixSet { /// Flag indicating that any entry should be considered changed. all: bool, index: usize, keys: Arc<Vec<Nibbles>>, } impl PrefixSet { /// Returns `true` if any of the keys in the set has the given prefix /// /// # Note on Mutability /// /// This method requires `&mut self` (unlike typical `contains` methods) because it maintains an /// internal position tracker (`self.index`) between calls. This enables significant performance /// optimization for sequential lookups in sorted order, which is common during trie traversal. /// /// The `index` field allows subsequent searches to start where previous ones left off, /// avoiding repeated full scans of the prefix array when keys are accessed in nearby ranges. /// /// This optimization was inspired by Silkworm's implementation and significantly improves /// incremental state root calculation performance /// ([see PR #2417](https://github.com/paradigmxyz/reth/pull/2417)). #[inline] pub fn contains(&mut self, prefix: &Nibbles) -> bool { if self.all { return true } while self.index > 0 && &self.keys[self.index] > prefix { self.index -= 1; } for (idx, key) in self.keys[self.index..].iter().enumerate() { if key.starts_with(prefix) { self.index += idx; return true } if key > prefix { self.index += idx; return false } } false } /// Returns an iterator over reference to _all_ nibbles regardless of cursor position. pub fn iter(&self) -> core::slice::Iter<'_, Nibbles> { self.keys.iter() } /// Returns true if every entry should be considered changed. pub const fn all(&self) -> bool { self.all } /// Returns the number of elements in the set. pub fn len(&self) -> usize { self.keys.len() } /// Returns `true` if the set is empty. pub fn is_empty(&self) -> bool { self.keys.is_empty() } } impl<'a> IntoIterator for &'a PrefixSet { type Item = &'a Nibbles; type IntoIter = core::slice::Iter<'a, Nibbles>; fn into_iter(self) -> Self::IntoIter { self.iter() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_contains_with_multiple_inserts_and_duplicates() { let mut prefix_set_mut = PrefixSetMut::default(); prefix_set_mut.insert(Nibbles::from_nibbles([1, 2, 3])); prefix_set_mut.insert(Nibbles::from_nibbles([1, 2, 4])); prefix_set_mut.insert(Nibbles::from_nibbles([4, 5, 6])); prefix_set_mut.insert(Nibbles::from_nibbles([1, 2, 3])); // Duplicate let mut prefix_set = prefix_set_mut.freeze(); assert!(prefix_set.contains(&Nibbles::from_nibbles_unchecked([1, 2]))); assert!(prefix_set.contains(&Nibbles::from_nibbles_unchecked([4, 5]))); assert!(!prefix_set.contains(&Nibbles::from_nibbles_unchecked([7, 8]))); assert_eq!(prefix_set.len(), 3); // Length should be 3 (excluding duplicate) } #[test] fn test_freeze_shrinks_capacity() { let mut prefix_set_mut = PrefixSetMut::default(); prefix_set_mut.insert(Nibbles::from_nibbles([1, 2, 3])); prefix_set_mut.insert(Nibbles::from_nibbles([1, 2, 4])); prefix_set_mut.insert(Nibbles::from_nibbles([4, 5, 6])); prefix_set_mut.insert(Nibbles::from_nibbles([1, 2, 3])); // Duplicate assert_eq!(prefix_set_mut.keys.len(), 4); // Length should be 3 (including duplicate) assert_eq!(prefix_set_mut.keys.capacity(), 4); // Capacity should be 4 (including duplicate) let mut prefix_set = prefix_set_mut.freeze(); assert!(prefix_set.contains(&Nibbles::from_nibbles_unchecked([1, 2]))); assert!(prefix_set.contains(&Nibbles::from_nibbles_unchecked([4, 5]))); assert!(!prefix_set.contains(&Nibbles::from_nibbles_unchecked([7, 8]))); assert_eq!(prefix_set.keys.len(), 3); // Length should be 3 (excluding duplicate) assert_eq!(prefix_set.keys.capacity(), 3); // Capacity should be 3 after shrinking } #[test] fn test_freeze_shrinks_existing_capacity() { // do the above test but with preallocated capacity let mut prefix_set_mut = PrefixSetMut::with_capacity(101); prefix_set_mut.insert(Nibbles::from_nibbles([1, 2, 3])); prefix_set_mut.insert(Nibbles::from_nibbles([1, 2, 4])); prefix_set_mut.insert(Nibbles::from_nibbles([4, 5, 6])); prefix_set_mut.insert(Nibbles::from_nibbles([1, 2, 3])); // Duplicate assert_eq!(prefix_set_mut.keys.len(), 4); // Length should be 3 (including duplicate) assert_eq!(prefix_set_mut.keys.capacity(), 101); // Capacity should be 101 (including duplicate) let mut prefix_set = prefix_set_mut.freeze(); assert!(prefix_set.contains(&Nibbles::from_nibbles_unchecked([1, 2]))); assert!(prefix_set.contains(&Nibbles::from_nibbles_unchecked([4, 5]))); assert!(!prefix_set.contains(&Nibbles::from_nibbles_unchecked([7, 8]))); assert_eq!(prefix_set.keys.len(), 3); // Length should be 3 (excluding duplicate) assert_eq!(prefix_set.keys.capacity(), 3); // Capacity should be 3 after shrinking } #[test] fn test_prefix_set_all_extend() { let mut prefix_set_mut = PrefixSetMut::default(); prefix_set_mut.extend(PrefixSetMut::all()); assert!(prefix_set_mut.all); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/src/constants.rs
crates/trie/common/src/constants.rs
/// The maximum size of RLP encoded trie account in bytes. /// 2 (header) + 4 * 1 (field lens) + 8 (nonce) + 32 * 3 (balance, storage root, code hash) pub const TRIE_ACCOUNT_RLP_MAX_SIZE: usize = 110; #[cfg(test)] mod tests { use super::*; use crate::TrieAccount; use alloy_primitives::{B256, U256}; use alloy_rlp::Encodable; #[test] fn account_rlp_max_size() { let account = TrieAccount { nonce: u64::MAX, balance: U256::MAX, storage_root: B256::from_slice(&[u8::MAX; 32]), code_hash: B256::from_slice(&[u8::MAX; 32]), }; let mut encoded = Vec::new(); account.encode(&mut encoded); assert_eq!(encoded.len(), TRIE_ACCOUNT_RLP_MAX_SIZE); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/src/updates.rs
crates/trie/common/src/updates.rs
use crate::{BranchNodeCompact, HashBuilder, Nibbles}; use alloc::{ collections::{btree_map::BTreeMap, btree_set::BTreeSet}, vec::Vec, }; use alloy_primitives::{ map::{B256Map, B256Set, HashMap, HashSet}, FixedBytes, B256, }; /// The aggregation of trie updates. #[derive(PartialEq, Eq, Clone, Default, Debug)] #[cfg_attr(any(test, feature = "serde"), derive(serde::Serialize, serde::Deserialize))] pub struct TrieUpdates { /// Collection of updated intermediate account nodes indexed by full path. #[cfg_attr(any(test, feature = "serde"), serde(with = "serde_nibbles_map"))] pub account_nodes: HashMap<Nibbles, BranchNodeCompact>, /// Collection of removed intermediate account nodes indexed by full path. #[cfg_attr(any(test, feature = "serde"), serde(with = "serde_nibbles_set"))] pub removed_nodes: HashSet<Nibbles>, /// Collection of updated storage tries indexed by the hashed address. pub storage_tries: B256Map<StorageTrieUpdates>, } impl TrieUpdates { /// Returns `true` if the updates are empty. pub fn is_empty(&self) -> bool { self.account_nodes.is_empty() && self.removed_nodes.is_empty() && self.storage_tries.is_empty() } /// Returns reference to updated account nodes. pub const fn account_nodes_ref(&self) -> &HashMap<Nibbles, BranchNodeCompact> { &self.account_nodes } /// Returns a reference to removed account nodes. pub const fn removed_nodes_ref(&self) -> &HashSet<Nibbles> { &self.removed_nodes } /// Returns a reference to updated storage tries. pub const fn storage_tries_ref(&self) -> &B256Map<StorageTrieUpdates> { &self.storage_tries } /// Extends the trie updates. pub fn extend(&mut self, other: Self) { self.extend_common(&other); self.account_nodes.extend(exclude_empty_from_pair(other.account_nodes)); self.removed_nodes.extend(exclude_empty(other.removed_nodes)); for (hashed_address, storage_trie) in other.storage_tries { self.storage_tries.entry(hashed_address).or_default().extend(storage_trie); } } /// Extends the trie updates. /// /// Slightly less efficient than [`Self::extend`], but preferred to `extend(other.clone())`. pub fn extend_ref(&mut self, other: &Self) { self.extend_common(other); self.account_nodes.extend(exclude_empty_from_pair( other.account_nodes.iter().map(|(k, v)| (*k, v.clone())), )); self.removed_nodes.extend(exclude_empty(other.removed_nodes.iter().copied())); for (hashed_address, storage_trie) in &other.storage_tries { self.storage_tries.entry(*hashed_address).or_default().extend_ref(storage_trie); } } fn extend_common(&mut self, other: &Self) { self.account_nodes.retain(|nibbles, _| !other.removed_nodes.contains(nibbles)); } /// Insert storage updates for a given hashed address. pub fn insert_storage_updates( &mut self, hashed_address: B256, storage_updates: StorageTrieUpdates, ) { if storage_updates.is_empty() { return; } let existing = self.storage_tries.insert(hashed_address, storage_updates); debug_assert!(existing.is_none()); } /// Finalize state trie updates. pub fn finalize( &mut self, hash_builder: HashBuilder, removed_keys: HashSet<Nibbles>, destroyed_accounts: B256Set, ) { // Retrieve updated nodes from hash builder. let (_, updated_nodes) = hash_builder.split(); self.account_nodes.extend(exclude_empty_from_pair(updated_nodes)); // Add deleted node paths. self.removed_nodes.extend(exclude_empty(removed_keys)); // Add deleted storage tries for destroyed accounts. for destroyed in destroyed_accounts { self.storage_tries.entry(destroyed).or_default().set_deleted(true); } } /// Converts trie updates into [`TrieUpdatesSorted`]. pub fn into_sorted(self) -> TrieUpdatesSorted { let mut account_nodes = Vec::from_iter(self.account_nodes); account_nodes.sort_unstable_by(|a, b| a.0.cmp(&b.0)); let storage_tries = self .storage_tries .into_iter() .map(|(hashed_address, updates)| (hashed_address, updates.into_sorted())) .collect(); TrieUpdatesSorted { removed_nodes: self.removed_nodes, account_nodes, storage_tries } } /// Converts trie updates into [`TrieUpdatesSorted`], but keeping the maps allocated by /// draining. /// /// This effectively clears all the fields in the [`TrieUpdatesSorted`]. /// /// This allows us to reuse the allocated space. This allocates new space for the sorted /// updates, like `into_sorted`. pub fn drain_into_sorted(&mut self) -> TrieUpdatesSorted { let mut account_nodes = self.account_nodes.drain().collect::<Vec<_>>(); account_nodes.sort_unstable_by(|a, b| a.0.cmp(&b.0)); let storage_tries = self .storage_tries .drain() .map(|(hashed_address, updates)| (hashed_address, updates.into_sorted())) .collect(); TrieUpdatesSorted { removed_nodes: self.removed_nodes.clone(), account_nodes, storage_tries, } } /// Converts trie updates into [`TrieUpdatesSortedRef`]. pub fn into_sorted_ref<'a>(&'a self) -> TrieUpdatesSortedRef<'a> { let mut account_nodes = self.account_nodes.iter().collect::<Vec<_>>(); account_nodes.sort_unstable_by(|a, b| a.0.cmp(b.0)); TrieUpdatesSortedRef { removed_nodes: self.removed_nodes.iter().collect::<BTreeSet<_>>(), account_nodes, storage_tries: self .storage_tries .iter() .map(|m| (*m.0, m.1.into_sorted_ref().clone())) .collect(), } } /// Clears the nodes and storage trie maps in this `TrieUpdates`. pub fn clear(&mut self) { self.account_nodes.clear(); self.removed_nodes.clear(); self.storage_tries.clear(); } } /// Trie updates for storage trie of a single account. #[derive(PartialEq, Eq, Clone, Default, Debug)] #[cfg_attr(any(test, feature = "serde"), derive(serde::Serialize, serde::Deserialize))] pub struct StorageTrieUpdates { /// Flag indicating whether the trie was deleted. pub is_deleted: bool, /// Collection of updated storage trie nodes. #[cfg_attr(any(test, feature = "serde"), serde(with = "serde_nibbles_map"))] pub storage_nodes: HashMap<Nibbles, BranchNodeCompact>, /// Collection of removed storage trie nodes. #[cfg_attr(any(test, feature = "serde"), serde(with = "serde_nibbles_set"))] pub removed_nodes: HashSet<Nibbles>, } #[cfg(feature = "test-utils")] impl StorageTrieUpdates { /// Creates a new storage trie updates that are not marked as deleted. pub fn new(updates: impl IntoIterator<Item = (Nibbles, BranchNodeCompact)>) -> Self { Self { storage_nodes: exclude_empty_from_pair(updates).collect(), ..Default::default() } } } impl StorageTrieUpdates { /// Returns empty storage trie updates with `deleted` set to `true`. pub fn deleted() -> Self { Self { is_deleted: true, storage_nodes: HashMap::default(), removed_nodes: HashSet::default(), } } /// Returns the length of updated nodes. pub fn len(&self) -> usize { (self.is_deleted as usize) + self.storage_nodes.len() + self.removed_nodes.len() } /// Returns `true` if the trie was deleted. pub const fn is_deleted(&self) -> bool { self.is_deleted } /// Returns reference to updated storage nodes. pub const fn storage_nodes_ref(&self) -> &HashMap<Nibbles, BranchNodeCompact> { &self.storage_nodes } /// Returns reference to removed storage nodes. pub const fn removed_nodes_ref(&self) -> &HashSet<Nibbles> { &self.removed_nodes } /// Returns `true` if storage updates are empty. pub fn is_empty(&self) -> bool { !self.is_deleted && self.storage_nodes.is_empty() && self.removed_nodes.is_empty() } /// Sets `deleted` flag on the storage trie. pub const fn set_deleted(&mut self, deleted: bool) { self.is_deleted = deleted; } /// Extends storage trie updates. pub fn extend(&mut self, other: Self) { self.extend_common(&other); self.storage_nodes.extend(exclude_empty_from_pair(other.storage_nodes)); self.removed_nodes.extend(exclude_empty(other.removed_nodes)); } /// Extends storage trie updates. /// /// Slightly less efficient than [`Self::extend`], but preferred to `extend(other.clone())`. pub fn extend_ref(&mut self, other: &Self) { self.extend_common(other); self.storage_nodes.extend(exclude_empty_from_pair( other.storage_nodes.iter().map(|(k, v)| (*k, v.clone())), )); self.removed_nodes.extend(exclude_empty(other.removed_nodes.iter().copied())); } fn extend_common(&mut self, other: &Self) { if other.is_deleted { self.storage_nodes.clear(); self.removed_nodes.clear(); } self.is_deleted |= other.is_deleted; self.storage_nodes.retain(|nibbles, _| !other.removed_nodes.contains(nibbles)); } /// Finalize storage trie updates for by taking updates from walker and hash builder. pub fn finalize(&mut self, hash_builder: HashBuilder, removed_keys: HashSet<Nibbles>) { // Retrieve updated nodes from hash builder. let (_, updated_nodes) = hash_builder.split(); self.storage_nodes.extend(exclude_empty_from_pair(updated_nodes)); // Add deleted node paths. self.removed_nodes.extend(exclude_empty(removed_keys)); } /// Convert storage trie updates into [`StorageTrieUpdatesSorted`]. pub fn into_sorted(self) -> StorageTrieUpdatesSorted { let mut storage_nodes = Vec::from_iter(self.storage_nodes); storage_nodes.sort_unstable_by(|a, b| a.0.cmp(&b.0)); StorageTrieUpdatesSorted { is_deleted: self.is_deleted, removed_nodes: self.removed_nodes, storage_nodes, } } /// Convert storage trie updates into [`StorageTrieUpdatesSortedRef`]. pub fn into_sorted_ref(&self) -> StorageTrieUpdatesSortedRef<'_> { StorageTrieUpdatesSortedRef { is_deleted: self.is_deleted, removed_nodes: self.removed_nodes.iter().collect::<BTreeSet<_>>(), storage_nodes: self.storage_nodes.iter().collect::<BTreeMap<_, _>>(), } } } /// Serializes and deserializes any [`HashSet`] that includes [`Nibbles`] elements, by using the /// hex-encoded packed representation. /// /// This also sorts the set before serializing. #[cfg(any(test, feature = "serde"))] mod serde_nibbles_set { use crate::Nibbles; use alloc::{ string::{String, ToString}, vec::Vec, }; use alloy_primitives::map::HashSet; use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; pub(super) fn serialize<S>(map: &HashSet<Nibbles>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut storage_nodes = map.iter().map(|elem| alloy_primitives::hex::encode(elem.pack())).collect::<Vec<_>>(); storage_nodes.sort_unstable(); storage_nodes.serialize(serializer) } pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<HashSet<Nibbles>, D::Error> where D: Deserializer<'de>, { Vec::<String>::deserialize(deserializer)? .into_iter() .map(|node| { Ok(Nibbles::unpack( alloy_primitives::hex::decode(node) .map_err(|err| D::Error::custom(err.to_string()))?, )) }) .collect::<Result<HashSet<_>, _>>() } } /// Serializes and deserializes any [`HashMap`] that uses [`Nibbles`] as keys, by using the /// hex-encoded packed representation. /// /// This also sorts the map's keys before encoding and serializing. #[cfg(any(test, feature = "serde"))] mod serde_nibbles_map { use crate::Nibbles; use alloc::{ string::{String, ToString}, vec::Vec, }; use alloy_primitives::{hex, map::HashMap}; use core::marker::PhantomData; use serde::{ de::{Error, MapAccess, Visitor}, ser::SerializeMap, Deserialize, Deserializer, Serialize, Serializer, }; pub(super) fn serialize<S, T>( map: &HashMap<Nibbles, T>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, T: Serialize, { let mut map_serializer = serializer.serialize_map(Some(map.len()))?; let mut storage_nodes = Vec::from_iter(map); storage_nodes.sort_unstable_by_key(|node| node.0); for (k, v) in storage_nodes { // pack, then hex encode the Nibbles let packed = alloy_primitives::hex::encode(k.pack()); map_serializer.serialize_entry(&packed, &v)?; } map_serializer.end() } pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<HashMap<Nibbles, T>, D::Error> where D: Deserializer<'de>, T: Deserialize<'de>, { struct NibblesMapVisitor<T> { marker: PhantomData<T>, } impl<'de, T> Visitor<'de> for NibblesMapVisitor<T> where T: Deserialize<'de>, { type Value = HashMap<Nibbles, T>; fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { formatter.write_str("a map with hex-encoded Nibbles keys") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: MapAccess<'de>, { let mut result = HashMap::with_capacity_and_hasher( map.size_hint().unwrap_or(0), Default::default(), ); while let Some((key, value)) = map.next_entry::<String, T>()? { let decoded_key = hex::decode(&key).map_err(|err| Error::custom(err.to_string()))?; let nibbles = Nibbles::unpack(&decoded_key); result.insert(nibbles, value); } Ok(result) } } deserializer.deserialize_map(NibblesMapVisitor { marker: PhantomData }) } } /// Sorted trie updates reference used for serializing trie to file. #[derive(PartialEq, Eq, Clone, Default, Debug)] #[cfg_attr(any(test, feature = "serde"), derive(serde::Serialize))] pub struct TrieUpdatesSortedRef<'a> { /// Sorted collection of updated state nodes with corresponding paths. pub account_nodes: Vec<(&'a Nibbles, &'a BranchNodeCompact)>, /// The set of removed state node keys. pub removed_nodes: BTreeSet<&'a Nibbles>, /// Storage tries stored by hashed address of the account the trie belongs to. pub storage_tries: BTreeMap<FixedBytes<32>, StorageTrieUpdatesSortedRef<'a>>, } /// Sorted trie updates used for lookups and insertions. #[derive(PartialEq, Eq, Clone, Default, Debug)] #[cfg_attr(any(test, feature = "serde"), derive(serde::Serialize, serde::Deserialize))] pub struct TrieUpdatesSorted { /// Sorted collection of updated state nodes with corresponding paths. pub account_nodes: Vec<(Nibbles, BranchNodeCompact)>, /// The set of removed state node keys. pub removed_nodes: HashSet<Nibbles>, /// Storage tries stored by hashed address of the account the trie belongs to. pub storage_tries: B256Map<StorageTrieUpdatesSorted>, } impl TrieUpdatesSorted { /// Returns reference to updated account nodes. pub fn account_nodes_ref(&self) -> &[(Nibbles, BranchNodeCompact)] { &self.account_nodes } /// Returns reference to removed account nodes. pub const fn removed_nodes_ref(&self) -> &HashSet<Nibbles> { &self.removed_nodes } /// Returns reference to updated storage tries. pub const fn storage_tries_ref(&self) -> &B256Map<StorageTrieUpdatesSorted> { &self.storage_tries } } /// Sorted storage trie updates reference used for serializing to file. #[derive(PartialEq, Eq, Clone, Default, Debug)] #[cfg_attr(any(test, feature = "serde"), derive(serde::Serialize))] pub struct StorageTrieUpdatesSortedRef<'a> { /// Flag indicating whether the trie has been deleted/wiped. pub is_deleted: bool, /// Sorted collection of updated storage nodes with corresponding paths. pub storage_nodes: BTreeMap<&'a Nibbles, &'a BranchNodeCompact>, /// The set of removed storage node keys. pub removed_nodes: BTreeSet<&'a Nibbles>, } /// Sorted trie updates used for lookups and insertions. #[derive(PartialEq, Eq, Clone, Default, Debug)] #[cfg_attr(any(test, feature = "serde"), derive(serde::Serialize, serde::Deserialize))] pub struct StorageTrieUpdatesSorted { /// Flag indicating whether the trie has been deleted/wiped. pub is_deleted: bool, /// Sorted collection of updated storage nodes with corresponding paths. pub storage_nodes: Vec<(Nibbles, BranchNodeCompact)>, /// The set of removed storage node keys. pub removed_nodes: HashSet<Nibbles>, } impl StorageTrieUpdatesSorted { /// Returns `true` if the trie was deleted. pub const fn is_deleted(&self) -> bool { self.is_deleted } /// Returns reference to updated storage nodes. pub fn storage_nodes_ref(&self) -> &[(Nibbles, BranchNodeCompact)] { &self.storage_nodes } /// Returns reference to removed storage nodes. pub const fn removed_nodes_ref(&self) -> &HashSet<Nibbles> { &self.removed_nodes } } /// Excludes empty nibbles from the given iterator. fn exclude_empty(iter: impl IntoIterator<Item = Nibbles>) -> impl Iterator<Item = Nibbles> { iter.into_iter().filter(|n| !n.is_empty()) } /// Excludes empty nibbles from the given iterator of pairs where the nibbles are the key. fn exclude_empty_from_pair<V>( iter: impl IntoIterator<Item = (Nibbles, V)>, ) -> impl Iterator<Item = (Nibbles, V)> { iter.into_iter().filter(|(n, _)| !n.is_empty()) } /// Bincode-compatible trie updates type serde implementations. #[cfg(feature = "serde-bincode-compat")] pub mod serde_bincode_compat { use crate::{BranchNodeCompact, Nibbles}; use alloc::borrow::Cow; use alloy_primitives::map::{B256Map, HashMap, HashSet}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_with::{DeserializeAs, SerializeAs}; /// Bincode-compatible [`super::TrieUpdates`] serde implementation. /// /// Intended to use with the [`serde_with::serde_as`] macro in the following way: /// ```rust /// use reth_trie_common::{serde_bincode_compat, updates::TrieUpdates}; /// use serde::{Deserialize, Serialize}; /// use serde_with::serde_as; /// /// #[serde_as] /// #[derive(Serialize, Deserialize)] /// struct Data { /// #[serde_as(as = "serde_bincode_compat::updates::TrieUpdates")] /// trie_updates: TrieUpdates, /// } /// ``` #[derive(Debug, Serialize, Deserialize)] pub struct TrieUpdates<'a> { account_nodes: Cow<'a, HashMap<Nibbles, BranchNodeCompact>>, removed_nodes: Cow<'a, HashSet<Nibbles>>, storage_tries: B256Map<StorageTrieUpdates<'a>>, } impl<'a> From<&'a super::TrieUpdates> for TrieUpdates<'a> { fn from(value: &'a super::TrieUpdates) -> Self { Self { account_nodes: Cow::Borrowed(&value.account_nodes), removed_nodes: Cow::Borrowed(&value.removed_nodes), storage_tries: value.storage_tries.iter().map(|(k, v)| (*k, v.into())).collect(), } } } impl<'a> From<TrieUpdates<'a>> for super::TrieUpdates { fn from(value: TrieUpdates<'a>) -> Self { Self { account_nodes: value.account_nodes.into_owned(), removed_nodes: value.removed_nodes.into_owned(), storage_tries: value .storage_tries .into_iter() .map(|(k, v)| (k, v.into())) .collect(), } } } impl SerializeAs<super::TrieUpdates> for TrieUpdates<'_> { fn serialize_as<S>(source: &super::TrieUpdates, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { TrieUpdates::from(source).serialize(serializer) } } impl<'de> DeserializeAs<'de, super::TrieUpdates> for TrieUpdates<'de> { fn deserialize_as<D>(deserializer: D) -> Result<super::TrieUpdates, D::Error> where D: Deserializer<'de>, { TrieUpdates::deserialize(deserializer).map(Into::into) } } /// Bincode-compatible [`super::StorageTrieUpdates`] serde implementation. /// /// Intended to use with the [`serde_with::serde_as`] macro in the following way: /// ```rust /// use reth_trie_common::{serde_bincode_compat, updates::StorageTrieUpdates}; /// use serde::{Deserialize, Serialize}; /// use serde_with::serde_as; /// /// #[serde_as] /// #[derive(Serialize, Deserialize)] /// struct Data { /// #[serde_as(as = "serde_bincode_compat::updates::StorageTrieUpdates")] /// trie_updates: StorageTrieUpdates, /// } /// ``` #[derive(Debug, Serialize, Deserialize)] pub struct StorageTrieUpdates<'a> { is_deleted: bool, storage_nodes: Cow<'a, HashMap<Nibbles, BranchNodeCompact>>, removed_nodes: Cow<'a, HashSet<Nibbles>>, } impl<'a> From<&'a super::StorageTrieUpdates> for StorageTrieUpdates<'a> { fn from(value: &'a super::StorageTrieUpdates) -> Self { Self { is_deleted: value.is_deleted, storage_nodes: Cow::Borrowed(&value.storage_nodes), removed_nodes: Cow::Borrowed(&value.removed_nodes), } } } impl<'a> From<StorageTrieUpdates<'a>> for super::StorageTrieUpdates { fn from(value: StorageTrieUpdates<'a>) -> Self { Self { is_deleted: value.is_deleted, storage_nodes: value.storage_nodes.into_owned(), removed_nodes: value.removed_nodes.into_owned(), } } } impl SerializeAs<super::StorageTrieUpdates> for StorageTrieUpdates<'_> { fn serialize_as<S>( source: &super::StorageTrieUpdates, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { StorageTrieUpdates::from(source).serialize(serializer) } } impl<'de> DeserializeAs<'de, super::StorageTrieUpdates> for StorageTrieUpdates<'de> { fn deserialize_as<D>(deserializer: D) -> Result<super::StorageTrieUpdates, D::Error> where D: Deserializer<'de>, { StorageTrieUpdates::deserialize(deserializer).map(Into::into) } } #[cfg(test)] mod tests { use crate::{ serde_bincode_compat, updates::{StorageTrieUpdates, TrieUpdates}, BranchNodeCompact, Nibbles, }; use alloy_primitives::B256; use serde::{Deserialize, Serialize}; use serde_with::serde_as; #[test] fn test_trie_updates_bincode_roundtrip() { #[serde_as] #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] struct Data { #[serde_as(as = "serde_bincode_compat::updates::TrieUpdates")] trie_updates: TrieUpdates, } let mut data = Data { trie_updates: TrieUpdates::default() }; let encoded = bincode::serialize(&data).unwrap(); let decoded: Data = bincode::deserialize(&encoded).unwrap(); assert_eq!(decoded, data); data.trie_updates .removed_nodes .insert(Nibbles::from_nibbles_unchecked([0x0b, 0x0e, 0x0e, 0x0f])); let encoded = bincode::serialize(&data).unwrap(); let decoded: Data = bincode::deserialize(&encoded).unwrap(); assert_eq!(decoded, data); data.trie_updates.account_nodes.insert( Nibbles::from_nibbles_unchecked([0x0d, 0x0e, 0x0a, 0x0d]), BranchNodeCompact::default(), ); let encoded = bincode::serialize(&data).unwrap(); let decoded: Data = bincode::deserialize(&encoded).unwrap(); assert_eq!(decoded, data); data.trie_updates.storage_tries.insert(B256::default(), StorageTrieUpdates::default()); let encoded = bincode::serialize(&data).unwrap(); let decoded: Data = bincode::deserialize(&encoded).unwrap(); assert_eq!(decoded, data); } #[test] fn test_storage_trie_updates_bincode_roundtrip() { #[serde_as] #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] struct Data { #[serde_as(as = "serde_bincode_compat::updates::StorageTrieUpdates")] trie_updates: StorageTrieUpdates, } let mut data = Data { trie_updates: StorageTrieUpdates::default() }; let encoded = bincode::serialize(&data).unwrap(); let decoded: Data = bincode::deserialize(&encoded).unwrap(); assert_eq!(decoded, data); data.trie_updates .removed_nodes .insert(Nibbles::from_nibbles_unchecked([0x0b, 0x0e, 0x0e, 0x0f])); let encoded = bincode::serialize(&data).unwrap(); let decoded: Data = bincode::deserialize(&encoded).unwrap(); assert_eq!(decoded, data); data.trie_updates.storage_nodes.insert( Nibbles::from_nibbles_unchecked([0x0d, 0x0e, 0x0a, 0x0d]), BranchNodeCompact::default(), ); let encoded = bincode::serialize(&data).unwrap(); let decoded: Data = bincode::deserialize(&encoded).unwrap(); assert_eq!(decoded, data); } } } #[cfg(all(test, feature = "serde"))] mod tests { use super::*; #[test] fn test_trie_updates_serde_roundtrip() { let mut default_updates = TrieUpdates::default(); let updates_serialized = serde_json::to_string(&default_updates).unwrap(); let updates_deserialized: TrieUpdates = serde_json::from_str(&updates_serialized).unwrap(); assert_eq!(updates_deserialized, default_updates); default_updates .removed_nodes .insert(Nibbles::from_nibbles_unchecked([0x0b, 0x0e, 0x0e, 0x0f])); let updates_serialized = serde_json::to_string(&default_updates).unwrap(); let updates_deserialized: TrieUpdates = serde_json::from_str(&updates_serialized).unwrap(); assert_eq!(updates_deserialized, default_updates); default_updates.account_nodes.insert( Nibbles::from_nibbles_unchecked([0x0d, 0x0e, 0x0a, 0x0d]), BranchNodeCompact::default(), ); let updates_serialized = serde_json::to_string(&default_updates).unwrap(); let updates_deserialized: TrieUpdates = serde_json::from_str(&updates_serialized).unwrap(); assert_eq!(updates_deserialized, default_updates); default_updates.storage_tries.insert(B256::default(), StorageTrieUpdates::default()); let updates_serialized = serde_json::to_string(&default_updates).unwrap(); let updates_deserialized: TrieUpdates = serde_json::from_str(&updates_serialized).unwrap(); assert_eq!(updates_deserialized, default_updates); } #[test] fn test_storage_trie_updates_serde_roundtrip() { let mut default_updates = StorageTrieUpdates::default(); let updates_serialized = serde_json::to_string(&default_updates).unwrap(); let updates_deserialized: StorageTrieUpdates = serde_json::from_str(&updates_serialized).unwrap(); assert_eq!(updates_deserialized, default_updates); default_updates .removed_nodes .insert(Nibbles::from_nibbles_unchecked([0x0b, 0x0e, 0x0e, 0x0f])); let updates_serialized = serde_json::to_string(&default_updates).unwrap(); let updates_deserialized: StorageTrieUpdates = serde_json::from_str(&updates_serialized).unwrap(); assert_eq!(updates_deserialized, default_updates); default_updates.storage_nodes.insert( Nibbles::from_nibbles_unchecked([0x0d, 0x0e, 0x0a, 0x0d]), BranchNodeCompact::default(), ); let updates_serialized = serde_json::to_string(&default_updates).unwrap(); let updates_deserialized: StorageTrieUpdates = serde_json::from_str(&updates_serialized).unwrap(); assert_eq!(updates_deserialized, default_updates); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/src/input.rs
crates/trie/common/src/input.rs
use crate::{prefix_set::TriePrefixSetsMut, updates::TrieUpdates, HashedPostState}; /// Inputs for trie-related computations. #[derive(Default, Debug, Clone)] pub struct TrieInput { /// The collection of cached in-memory intermediate trie nodes that /// can be reused for computation. pub nodes: TrieUpdates, /// The in-memory overlay hashed state. pub state: HashedPostState, /// The collection of prefix sets for the computation. Since the prefix sets _always_ /// invalidate the in-memory nodes, not all keys from `self.state` might be present here, /// if we have cached nodes for them. pub prefix_sets: TriePrefixSetsMut, } impl TrieInput { /// Create new trie input. pub const fn new( nodes: TrieUpdates, state: HashedPostState, prefix_sets: TriePrefixSetsMut, ) -> Self { Self { nodes, state, prefix_sets } } /// Create new trie input from in-memory state. The prefix sets will be constructed and /// set automatically. pub fn from_state(state: HashedPostState) -> Self { let prefix_sets = state.construct_prefix_sets(); Self { nodes: TrieUpdates::default(), state, prefix_sets } } /// Create new trie input from the provided blocks, from oldest to newest. See the documentation /// for [`Self::extend_with_blocks`] for details. pub fn from_blocks<'a>( blocks: impl IntoIterator<Item = (&'a HashedPostState, Option<&'a TrieUpdates>)>, ) -> Self { let mut input = Self::default(); input.extend_with_blocks(blocks); input } /// Extend the trie input with the provided blocks, from oldest to newest. /// /// For blocks with missing trie updates, the trie input will be extended with prefix sets /// constructed from the state of this block and the state itself, **without** trie updates. pub fn extend_with_blocks<'a>( &mut self, blocks: impl IntoIterator<Item = (&'a HashedPostState, Option<&'a TrieUpdates>)>, ) { for (hashed_state, trie_updates) in blocks { if let Some(nodes) = trie_updates.as_ref() { self.append_cached_ref(nodes, hashed_state); } else { self.append_ref(hashed_state); } } } /// Prepend another trie input to the current one. pub fn prepend_self(&mut self, mut other: Self) { core::mem::swap(&mut self.nodes, &mut other.nodes); self.nodes.extend(other.nodes); core::mem::swap(&mut self.state, &mut other.state); self.state.extend(other.state); // No need to swap prefix sets, as they will be sorted and deduplicated. self.prefix_sets.extend(other.prefix_sets); } /// Prepend state to the input and extend the prefix sets. pub fn prepend(&mut self, mut state: HashedPostState) { self.prefix_sets.extend(state.construct_prefix_sets()); core::mem::swap(&mut self.state, &mut state); self.state.extend(state); } /// Prepend intermediate nodes and state to the input. /// Prefix sets for incoming state will be ignored. pub fn prepend_cached(&mut self, mut nodes: TrieUpdates, mut state: HashedPostState) { core::mem::swap(&mut self.nodes, &mut nodes); self.nodes.extend(nodes); core::mem::swap(&mut self.state, &mut state); self.state.extend(state); } /// Append state to the input and extend the prefix sets. pub fn append(&mut self, state: HashedPostState) { self.prefix_sets.extend(state.construct_prefix_sets()); self.state.extend(state); } /// Append state to the input by reference and extend the prefix sets. pub fn append_ref(&mut self, state: &HashedPostState) { self.prefix_sets.extend(state.construct_prefix_sets()); self.state.extend_ref(state); } /// Append intermediate nodes and state to the input. /// Prefix sets for incoming state will be ignored. pub fn append_cached(&mut self, nodes: TrieUpdates, state: HashedPostState) { self.nodes.extend(nodes); self.state.extend(state); } /// Append intermediate nodes and state to the input by reference. /// Prefix sets for incoming state will be ignored. pub fn append_cached_ref(&mut self, nodes: &TrieUpdates, state: &HashedPostState) { self.nodes.extend_ref(nodes); self.state.extend_ref(state); } /// This method clears the trie input nodes, state, and prefix sets. pub fn clear(&mut self) { self.nodes.clear(); self.state.clear(); self.prefix_sets.clear(); } /// This method returns a cleared version of this trie input. pub fn cleared(mut self) -> Self { self.clear(); self } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/src/nibbles.rs
crates/trie/common/src/nibbles.rs
use alloc::vec::Vec; use derive_more::Deref; pub use nybbles::Nibbles; /// The representation of nibbles of the merkle trie stored in the database. #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Index)] #[cfg_attr(any(test, feature = "serde"), derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "test-utils", derive(arbitrary::Arbitrary))] pub struct StoredNibbles(pub Nibbles); impl From<Nibbles> for StoredNibbles { #[inline] fn from(value: Nibbles) -> Self { Self(value) } } impl From<Vec<u8>> for StoredNibbles { #[inline] fn from(value: Vec<u8>) -> Self { Self(Nibbles::from_nibbles_unchecked(value)) } } #[cfg(any(test, feature = "reth-codec"))] impl reth_codecs::Compact for StoredNibbles { fn to_compact<B>(&self, buf: &mut B) -> usize where B: bytes::BufMut + AsMut<[u8]>, { for i in self.0.iter() { buf.put_u8(i); } self.0.len() } fn from_compact(mut buf: &[u8], len: usize) -> (Self, &[u8]) { use bytes::Buf; let nibbles = &buf[..len]; buf.advance(len); (Self(Nibbles::from_nibbles_unchecked(nibbles)), buf) } } /// The representation of nibbles of the merkle trie stored in the database. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deref)] #[cfg_attr(any(test, feature = "serde"), derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "test-utils", derive(arbitrary::Arbitrary))] pub struct StoredNibblesSubKey(pub Nibbles); impl From<Nibbles> for StoredNibblesSubKey { #[inline] fn from(value: Nibbles) -> Self { Self(value) } } impl From<Vec<u8>> for StoredNibblesSubKey { #[inline] fn from(value: Vec<u8>) -> Self { Self(Nibbles::from_nibbles_unchecked(value)) } } impl From<StoredNibblesSubKey> for Nibbles { #[inline] fn from(value: StoredNibblesSubKey) -> Self { value.0 } } #[cfg(any(test, feature = "reth-codec"))] impl reth_codecs::Compact for StoredNibblesSubKey { fn to_compact<B>(&self, buf: &mut B) -> usize where B: bytes::BufMut + AsMut<[u8]>, { assert!(self.0.len() <= 64); // right-pad with zeros for i in self.0.iter() { buf.put_u8(i); } static ZERO: &[u8; 64] = &[0; 64]; buf.put_slice(&ZERO[self.0.len()..]); buf.put_u8(self.0.len() as u8); 64 + 1 } fn from_compact(buf: &[u8], _len: usize) -> (Self, &[u8]) { let len = buf[64] as usize; (Self(Nibbles::from_nibbles_unchecked(&buf[..len])), &buf[65..]) } } #[cfg(test)] mod tests { use super::*; use bytes::BytesMut; use reth_codecs::Compact; #[test] fn test_stored_nibbles_from_nibbles() { let nibbles = Nibbles::from_nibbles_unchecked(vec![0x02, 0x04, 0x06]); let stored = StoredNibbles::from(nibbles); assert_eq!(stored.0, nibbles); } #[test] fn test_stored_nibbles_from_vec() { let bytes = vec![0x02, 0x04, 0x06]; let stored = StoredNibbles::from(bytes.clone()); assert_eq!(stored.0.to_vec(), bytes); } #[test] fn test_stored_nibbles_to_compact() { let stored = StoredNibbles::from(vec![0x02, 0x04]); let mut buf = BytesMut::with_capacity(10); let len = stored.to_compact(&mut buf); assert_eq!(len, 2); assert_eq!(buf, &vec![0x02, 0x04][..]); } #[test] fn test_stored_nibbles_from_compact() { let buf = vec![0x02, 0x04, 0x06]; let (stored, remaining) = StoredNibbles::from_compact(&buf, 2); assert_eq!(stored.0.to_vec(), vec![0x02, 0x04]); assert_eq!(remaining, &[0x06]); } #[test] fn test_stored_nibbles_subkey_to_compact() { let subkey = StoredNibblesSubKey::from(vec![0x02, 0x04]); let mut buf = BytesMut::with_capacity(65); let len = subkey.to_compact(&mut buf); assert_eq!(len, 65); assert_eq!(buf[..2], [0x02, 0x04]); assert_eq!(buf[64], 2); // Length byte } #[test] fn test_stored_nibbles_subkey_from_compact() { let mut buf = vec![0x02, 0x04]; buf.resize(65, 0); buf[64] = 2; let (subkey, remaining) = StoredNibblesSubKey::from_compact(&buf, 65); assert_eq!(subkey.0.to_vec(), vec![0x02, 0x04]); assert_eq!(remaining, &[] as &[u8]); } #[test] fn test_serialization_stored_nibbles() { let stored = StoredNibbles::from(vec![0x02, 0x04]); let serialized = serde_json::to_string(&stored).unwrap(); let deserialized: StoredNibbles = serde_json::from_str(&serialized).unwrap(); assert_eq!(stored, deserialized); } #[test] fn test_serialization_stored_nibbles_subkey() { let subkey = StoredNibblesSubKey::from(vec![0x02, 0x04]); let serialized = serde_json::to_string(&subkey).unwrap(); let deserialized: StoredNibblesSubKey = serde_json::from_str(&serialized).unwrap(); assert_eq!(subkey, deserialized); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/src/account.rs
crates/trie/common/src/account.rs
/// Re-export for convenience. pub use alloy_trie::TrieAccount; #[cfg(test)] mod tests { use super::*; use crate::root::storage_root_unhashed; use alloy_consensus::constants::KECCAK_EMPTY; use alloy_genesis::GenesisAccount; use alloy_primitives::{keccak256, Bytes, B256, U256}; use std::collections::BTreeMap; use alloy_trie::EMPTY_ROOT_HASH; use reth_primitives_traits::Account; #[test] fn test_from_genesis_account_with_default_values() { let genesis_account = GenesisAccount::default(); // Convert the GenesisAccount to a TrieAccount let trie_account: TrieAccount = genesis_account.into(); // Check the fields are properly set. assert_eq!(trie_account.nonce, 0); assert_eq!(trie_account.balance, U256::default()); assert_eq!(trie_account.storage_root, EMPTY_ROOT_HASH); assert_eq!(trie_account.code_hash, KECCAK_EMPTY); // Check that the default Account converts to the same TrieAccount assert_eq!(Account::default().into_trie_account(EMPTY_ROOT_HASH), trie_account); } #[test] fn test_from_genesis_account_with_values() { // Create a GenesisAccount with specific values let mut storage = BTreeMap::new(); storage.insert(B256::from([0x01; 32]), B256::from([0x02; 32])); let genesis_account = GenesisAccount { nonce: Some(10), balance: U256::from(1000), code: Some(Bytes::from(vec![0x60, 0x61])), storage: Some(storage), private_key: None, }; // Convert the GenesisAccount to a TrieAccount let trie_account: TrieAccount = genesis_account.into(); let is_private = false; // legacy test adapter value let u: U256 = B256::from([0x02; 32]).into(); let expected_storage_root = storage_root_unhashed(vec![( B256::from([0x01; 32]), alloy_primitives::FlaggedStorage::new(u, is_private), )]); // Check that the fields are properly set. 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])); // Check that the Account converts to the same TrieAccount assert_eq!( Account { nonce: 10, balance: U256::from(1000), bytecode_hash: Some(keccak256([0x60, 0x61])) } .into_trie_account(expected_storage_root), trie_account ); } #[test] fn test_from_genesis_account_with_zeroed_storage_values() { // Create a GenesisAccount with storage containing zero values let storage = BTreeMap::from([(B256::from([0x01; 32]), B256::from([0x00; 32]))]); let genesis_account = GenesisAccount { nonce: Some(3), balance: U256::from(300), code: None, storage: Some(storage), private_key: None, }; // Convert the GenesisAccount to a TrieAccount let trie_account: TrieAccount = genesis_account.into(); // Check the fields are properly set. assert_eq!(trie_account.nonce, 3); assert_eq!(trie_account.balance, U256::from(300)); // Zero values in storage should result in EMPTY_ROOT_HASH assert_eq!(trie_account.storage_root, EMPTY_ROOT_HASH); // No code provided, so code hash should be KECCAK_EMPTY assert_eq!(trie_account.code_hash, KECCAK_EMPTY); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/src/hash_builder/state.rs
crates/trie/common/src/hash_builder/state.rs
use crate::TrieMask; use alloc::vec::Vec; use alloy_trie::{hash_builder::HashBuilderValue, nodes::RlpNode, HashBuilder}; use nybbles::Nibbles; /// The hash builder state for storing in the database. /// Check the `reth-trie` crate for more info on hash builder. #[derive(Debug, Clone, PartialEq, Eq, Default)] #[cfg_attr(any(test, feature = "serde"), derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( feature = "arbitrary", derive(arbitrary::Arbitrary), reth_codecs::add_arbitrary_tests(compact) )] pub struct HashBuilderState { /// The current key. pub key: Vec<u8>, /// The current node value. pub value: HashBuilderValue, /// Whether the state value is private. pub is_private: Option<bool>, /// The builder stack. pub stack: Vec<RlpNode>, /// Group masks. pub groups: Vec<TrieMask>, /// Tree masks. pub tree_masks: Vec<TrieMask>, /// Hash masks. pub hash_masks: Vec<TrieMask>, /// Flag indicating if the current node is stored in the database. pub stored_in_database: bool, } impl From<HashBuilderState> for HashBuilder { fn from(state: HashBuilderState) -> Self { Self { key: Nibbles::from_nibbles_unchecked(state.key), stack: state.stack, value: state.value, is_private: state.is_private, state_masks: state.groups, tree_masks: state.tree_masks, hash_masks: state.hash_masks, stored_in_database: state.stored_in_database, updated_branch_nodes: None, proof_retainer: None, rlp_buf: Vec::with_capacity(32), } } } impl From<HashBuilder> for HashBuilderState { fn from(state: HashBuilder) -> Self { Self { key: state.key.to_vec(), stack: state.stack, value: state.value, is_private: state.is_private, groups: state.state_masks, tree_masks: state.tree_masks, hash_masks: state.hash_masks, stored_in_database: state.stored_in_database, } } } #[cfg(any(test, feature = "reth-codec"))] impl reth_codecs::Compact for HashBuilderState { fn to_compact<B>(&self, buf: &mut B) -> usize where B: bytes::BufMut + AsMut<[u8]>, { let mut len = 0; len += self.key.to_compact(buf); buf.put_u16(self.stack.len() as u16); len += 2; for item in &self.stack { buf.put_u16(item.len() as u16); buf.put_slice(&item[..]); len += 2 + item.len(); } len += self.value.to_compact(buf); buf.put_u16(self.groups.len() as u16); len += 2; for item in &self.groups { len += (*item).to_compact(buf); } buf.put_u16(self.tree_masks.len() as u16); len += 2; for item in &self.tree_masks { len += (*item).to_compact(buf); } buf.put_u16(self.hash_masks.len() as u16); len += 2; for item in &self.hash_masks { len += (*item).to_compact(buf); } // Serialize Seismic-specific `is_private: Option<bool>` let private_byte = match self.is_private { None => 0u8, Some(false) => 1u8, Some(true) => 2u8, }; buf.put_u8(private_byte); len += 1; buf.put_u8(self.stored_in_database as u8); len += 1; len } fn from_compact(buf: &[u8], _len: usize) -> (Self, &[u8]) { use bytes::Buf; let (key, mut buf) = Vec::from_compact(buf, 0); let stack_len = buf.get_u16() as usize; let mut stack = Vec::with_capacity(stack_len); for _ in 0..stack_len { let item_len = buf.get_u16() as usize; stack.push(RlpNode::from_raw(&buf[..item_len]).unwrap()); buf.advance(item_len); } let (value, mut buf) = HashBuilderValue::from_compact(buf, 0); let groups_len = buf.get_u16() as usize; let mut groups = Vec::with_capacity(groups_len); for _ in 0..groups_len { let (item, rest) = TrieMask::from_compact(buf, 0); groups.push(item); buf = rest; } let tree_masks_len = buf.get_u16() as usize; let mut tree_masks = Vec::with_capacity(tree_masks_len); for _ in 0..tree_masks_len { let (item, rest) = TrieMask::from_compact(buf, 0); tree_masks.push(item); buf = rest; } let hash_masks_len = buf.get_u16() as usize; let mut hash_masks = Vec::with_capacity(hash_masks_len); for _ in 0..hash_masks_len { let (item, rest) = TrieMask::from_compact(buf, 0); hash_masks.push(item); buf = rest; } // Deserialize Seismic-specific `is_private` let private_byte = buf.get_u8(); let is_private = match private_byte { 0 => None, 1 => Some(false), 2 => Some(true), _ => panic!("Invalid byte for Option<bool>: {}", private_byte), }; let stored_in_database = buf.get_u8() != 0; ( Self { key, stack, value, is_private, groups, tree_masks, hash_masks, stored_in_database, }, buf, ) } } #[cfg(test)] mod tests { use super::*; use reth_codecs::Compact; #[test] fn hash_builder_state_regression() { let mut state = HashBuilderState::default(); state.stack.push(Default::default()); let mut buf = vec![]; let len = state.clone().to_compact(&mut buf); let (decoded, _) = HashBuilderState::from_compact(&buf, len); assert_eq!(state, decoded); } #[test] fn hash_builder_state_regression_with_private() { let mut state = HashBuilderState::default(); state.is_private = Some(true); state.stack.push(Default::default()); let mut buf = vec![]; let len = state.clone().to_compact(&mut buf); let (decoded, _) = HashBuilderState::from_compact(&buf, len); assert_eq!(state, decoded); } #[cfg(feature = "arbitrary")] proptest::proptest! { #[test] fn hash_builder_state_roundtrip(state in proptest_arbitrary_interop::arb::<HashBuilderState>()) { let mut buf = vec![]; let len = state.to_compact(&mut buf); let (decoded, _) = HashBuilderState::from_compact(&buf, len); assert_eq!(state, decoded); } } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/src/hash_builder/mod.rs
crates/trie/common/src/hash_builder/mod.rs
//! MPT hash builder implementation. mod state; pub use state::HashBuilderState; pub use alloy_trie::hash_builder::*;
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/common/benches/prefix_set.rs
crates/trie/common/benches/prefix_set.rs
#![allow(missing_docs, unreachable_pub)] use criterion::{ criterion_group, criterion_main, measurement::WallTime, BenchmarkGroup, Criterion, }; use prop::test_runner::TestRng; use proptest::{ prelude::*, strategy::ValueTree, test_runner::{basic_result_cache, TestRunner}, }; use reth_trie_common::{ prefix_set::{PrefixSet, PrefixSetMut}, Nibbles, }; use std::{collections::BTreeSet, hint::black_box}; /// Abstraction for aggregating nibbles and freezing it to a type /// that can be later used for benching. pub trait PrefixSetMutAbstraction: Default { type Frozen; fn insert(&mut self, key: Nibbles); fn freeze(self) -> Self::Frozen; } /// Abstractions used for benching pub trait PrefixSetAbstraction: Default { fn contains(&mut self, key: Nibbles) -> bool; } impl PrefixSetMutAbstraction for PrefixSetMut { type Frozen = PrefixSet; fn insert(&mut self, key: Nibbles) { Self::insert(self, key) } fn freeze(self) -> Self::Frozen { Self::freeze(self) } } impl PrefixSetAbstraction for PrefixSet { fn contains(&mut self, key: Nibbles) -> bool { Self::contains(self, &key) } } pub fn prefix_set_lookups(c: &mut Criterion) { let mut group = c.benchmark_group("Prefix Set Lookups"); for size in [10, 100, 1_000, 10_000] { // Too slow. #[expect(unexpected_cfgs)] if cfg!(codspeed) && size > 1_000 { continue; } let test_data = generate_test_data(size); use implementations::*; prefix_set_bench::<BTreeAnyPrefixSet>( &mut group, "`BTreeSet` with `Iterator:any` lookup", test_data.clone(), size, ); prefix_set_bench::<BTreeRangeLastCheckedPrefixSet>( &mut group, "`BTreeSet` with `BTreeSet:range` lookup", test_data.clone(), size, ); prefix_set_bench::<VecCursorPrefixSet>( &mut group, "`Vec` with custom cursor lookup", test_data.clone(), size, ); prefix_set_bench::<VecBinarySearchPrefixSet>( &mut group, "`Vec` with binary search lookup", test_data.clone(), size, ); } } fn prefix_set_bench<T>( group: &mut BenchmarkGroup<'_, WallTime>, description: &str, (preload, input, expected): (Vec<Nibbles>, Vec<Nibbles>, Vec<bool>), size: usize, ) where T: PrefixSetMutAbstraction, T::Frozen: PrefixSetAbstraction, { let setup = || { let mut prefix_set = T::default(); for key in &preload { prefix_set.insert(*key); } (prefix_set.freeze(), input.clone(), expected.clone()) }; let group_id = format!("prefix set | size: {size} | {description}"); group.bench_function(group_id, |b| { b.iter_with_setup(setup, |(mut prefix_set, input, expected)| { for (idx, key) in input.into_iter().enumerate() { let result = black_box(prefix_set.contains(key)); assert_eq!(result, expected[idx]); } }); }); } fn generate_test_data(size: usize) -> (Vec<Nibbles>, Vec<Nibbles>, Vec<bool>) { use prop::collection::vec; let config = ProptestConfig { result_cache: basic_result_cache, ..Default::default() }; let rng = TestRng::deterministic_rng(config.rng_algorithm); let mut runner = TestRunner::new_with_rng(config, rng); let vec_of_nibbles = |range| vec(any_with::<Nibbles>(range), size); let mut preload = vec_of_nibbles(32usize.into()).new_tree(&mut runner).unwrap().current(); preload.sort(); preload.dedup(); let mut input = vec_of_nibbles((0..=32usize).into()).new_tree(&mut runner).unwrap().current(); input.sort(); input.dedup(); let expected = input .iter() .map(|prefix| preload.iter().any(|key| key.starts_with(prefix))) .collect::<Vec<_>>(); (preload, input, expected) } criterion_group!(prefix_set, prefix_set_lookups); criterion_main!(prefix_set); mod implementations { use super::*; use std::ops::Bound; #[derive(Default)] pub struct BTreeAnyPrefixSet { keys: BTreeSet<Nibbles>, } impl PrefixSetMutAbstraction for BTreeAnyPrefixSet { type Frozen = Self; fn insert(&mut self, key: Nibbles) { self.keys.insert(key); } fn freeze(self) -> Self::Frozen { self } } impl PrefixSetAbstraction for BTreeAnyPrefixSet { fn contains(&mut self, key: Nibbles) -> bool { self.keys.iter().any(|k| k.starts_with(&key)) } } #[derive(Default)] pub struct BTreeRangeLastCheckedPrefixSet { keys: BTreeSet<Nibbles>, last_checked: Option<Nibbles>, } impl PrefixSetMutAbstraction for BTreeRangeLastCheckedPrefixSet { type Frozen = Self; fn insert(&mut self, key: Nibbles) { self.keys.insert(key); } fn freeze(self) -> Self::Frozen { self } } impl PrefixSetAbstraction for BTreeRangeLastCheckedPrefixSet { fn contains(&mut self, prefix: Nibbles) -> bool { let range = match self.last_checked.as_ref() { // presumably never hit Some(last) if prefix < *last => (Bound::Unbounded, Bound::Excluded(last)), Some(last) => (Bound::Included(last), Bound::Unbounded), None => (Bound::Unbounded, Bound::Unbounded), }; for key in self.keys.range::<Nibbles, _>(range) { if key.starts_with(&prefix) { self.last_checked = Some(prefix); return true } if key > &prefix { self.last_checked = Some(prefix); return false } } false } } #[derive(Default)] pub struct VecBinarySearchPrefixSet { keys: Vec<Nibbles>, sorted: bool, } impl PrefixSetMutAbstraction for VecBinarySearchPrefixSet { type Frozen = Self; fn insert(&mut self, key: Nibbles) { self.sorted = false; self.keys.push(key); } fn freeze(self) -> Self::Frozen { self } } impl PrefixSetAbstraction for VecBinarySearchPrefixSet { fn contains(&mut self, prefix: Nibbles) -> bool { if !self.sorted { self.keys.sort(); self.sorted = true; } match self.keys.binary_search(&prefix) { Ok(_) => true, Err(idx) => match self.keys.get(idx) { Some(key) => key.starts_with(&prefix), None => false, // prefix > last key }, } } } #[derive(Default)] pub struct VecCursorPrefixSet { keys: Vec<Nibbles>, sorted: bool, index: usize, } impl PrefixSetMutAbstraction for VecCursorPrefixSet { type Frozen = Self; fn insert(&mut self, nibbles: Nibbles) { self.sorted = false; self.keys.push(nibbles); } fn freeze(self) -> Self::Frozen { self } } impl PrefixSetAbstraction for VecCursorPrefixSet { fn contains(&mut self, prefix: Nibbles) -> bool { if !self.sorted { self.keys.sort(); self.sorted = true; } while self.index > 0 && self.keys[self.index] > prefix { self.index -= 1; } for (idx, key) in self.keys[self.index..].iter().enumerate() { if key.starts_with(&prefix) { self.index += idx; return true } if key > &prefix { self.index += idx; return false } } false } } #[derive(Default)] #[allow(dead_code)] pub struct VecBinarySearchWithLastFoundPrefixSet { keys: Vec<Nibbles>, last_found_idx: usize, sorted: bool, } impl PrefixSetMutAbstraction for VecBinarySearchWithLastFoundPrefixSet { type Frozen = Self; fn insert(&mut self, key: Nibbles) { self.sorted = false; self.keys.push(key); } fn freeze(self) -> Self::Frozen { self } } impl PrefixSetAbstraction for VecBinarySearchWithLastFoundPrefixSet { fn contains(&mut self, prefix: Nibbles) -> bool { if !self.sorted { self.keys.sort(); self.sorted = true; } while self.last_found_idx > 0 && self.keys[self.last_found_idx] > prefix { self.last_found_idx -= 1; } match self.keys[self.last_found_idx..].binary_search(&prefix) { Ok(_) => true, Err(idx) => match self.keys.get(idx) { Some(key) => { self.last_found_idx = idx; key.starts_with(&prefix) } None => false, // prefix > last key }, } } } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/sparse-parallel/src/lib.rs
crates/trie/sparse-parallel/src/lib.rs
//! The implementation of parallel sparse MPT. #![cfg_attr(not(test), warn(unused_crate_dependencies))] extern crate alloc; mod trie; pub use trie::*; mod lower; use lower::*; #[cfg(feature = "metrics")] mod metrics;
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/sparse-parallel/src/lower.rs
crates/trie/sparse-parallel/src/lower.rs
use crate::SparseSubtrie; use reth_trie_common::Nibbles; /// Tracks the state of the lower subtries. /// /// When a [`crate::ParallelSparseTrie`] is initialized/cleared then its `LowerSparseSubtrie`s are /// all blinded, meaning they have no nodes. A blinded `LowerSparseSubtrie` may hold onto a cleared /// [`SparseSubtrie`] in order to reuse allocations. #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) enum LowerSparseSubtrie { Blind(Option<Box<SparseSubtrie>>), Revealed(Box<SparseSubtrie>), } impl Default for LowerSparseSubtrie { /// Creates a new blinded subtrie with no allocated storage. fn default() -> Self { Self::Blind(None) } } impl LowerSparseSubtrie { /// Returns a reference to the underlying [`SparseSubtrie`] if this subtrie is revealed. /// /// Returns `None` if the subtrie is blinded (has no nodes). pub(crate) fn as_revealed_ref(&self) -> Option<&SparseSubtrie> { match self { Self::Blind(_) => None, Self::Revealed(subtrie) => Some(subtrie.as_ref()), } } /// Returns a mutable reference to the underlying [`SparseSubtrie`] if this subtrie is revealed. /// /// Returns `None` if the subtrie is blinded (has no nodes). pub(crate) fn as_revealed_mut(&mut self) -> Option<&mut SparseSubtrie> { match self { Self::Blind(_) => None, Self::Revealed(subtrie) => Some(subtrie.as_mut()), } } /// Reveals the lower [`SparseSubtrie`], transitioning it from the Blinded to the Revealed /// variant, preserving allocations if possible. /// /// The given path is the path of a node which will be set into the [`SparseSubtrie`]'s `nodes` /// map immediately upon being revealed. If the subtrie is blinded, or if its current root path /// is longer than this one, than this one becomes the new root path of the subtrie. pub(crate) fn reveal(&mut self, path: &Nibbles) { match self { Self::Blind(allocated) => { debug_assert!(allocated.as_ref().is_none_or(|subtrie| subtrie.is_empty())); *self = if let Some(mut subtrie) = allocated.take() { subtrie.path = *path; Self::Revealed(subtrie) } else { Self::Revealed(Box::new(SparseSubtrie::new(*path))) } } Self::Revealed(subtrie) => { if path.len() < subtrie.path.len() { subtrie.path = *path; } } }; } /// Clears the subtrie and transitions it to the blinded state, preserving a cleared /// [`SparseSubtrie`] if possible. pub(crate) fn clear(&mut self) { *self = match core::mem::take(self) { Self::Blind(allocated) => { debug_assert!(allocated.as_ref().is_none_or(|subtrie| subtrie.is_empty())); Self::Blind(allocated) } Self::Revealed(mut subtrie) => { subtrie.clear(); Self::Blind(Some(subtrie)) } } } /// Takes ownership of the underlying [`SparseSubtrie`] if revealed, putting this /// `LowerSparseSubtrie` will be put into the blinded state. /// /// Otherwise returns None. pub(crate) fn take_revealed(&mut self) -> Option<Box<SparseSubtrie>> { self.take_revealed_if(|_| true) } /// Takes ownership of the underlying [`SparseSubtrie`] if revealed and the predicate returns /// true. /// /// If the subtrie is revealed, and the predicate function returns `true` when called with it, /// then this method will take ownership of the subtrie and transition this `LowerSparseSubtrie` /// to the blinded state. Otherwise, returns `None`. pub(crate) fn take_revealed_if<P>(&mut self, predicate: P) -> Option<Box<SparseSubtrie>> where P: FnOnce(&SparseSubtrie) -> bool, { match self { Self::Revealed(subtrie) if predicate(subtrie) => { let Self::Revealed(subtrie) = core::mem::take(self) else { unreachable!() }; Some(subtrie) } Self::Revealed(_) | Self::Blind(_) => None, } } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/sparse-parallel/src/metrics.rs
crates/trie/sparse-parallel/src/metrics.rs
//! Metrics for the parallel sparse trie use reth_metrics::{metrics::Histogram, Metrics}; /// Metrics for the parallel sparse trie #[derive(Metrics, Clone)] #[metrics(scope = "parallel_sparse_trie")] pub(crate) struct ParallelSparseTrieMetrics { /// A histogram for the number of subtries updated when calculating hashes. pub(crate) subtries_updated: Histogram, /// A histogram for the time it took to update lower subtrie hashes. pub(crate) subtrie_hash_update_latency: Histogram, /// A histogram for the time it took to update the upper subtrie hashes. pub(crate) subtrie_upper_hash_latency: Histogram, } impl PartialEq for ParallelSparseTrieMetrics { fn eq(&self, _other: &Self) -> bool { // It does not make sense to compare metrics, so return true, all are equal true } } impl Eq for ParallelSparseTrieMetrics {}
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/sparse-parallel/src/trie.rs
crates/trie/sparse-parallel/src/trie.rs
use crate::LowerSparseSubtrie; use alloc::borrow::Cow; use alloy_primitives::{ map::{Entry, HashMap}, B256, }; use alloy_rlp::Decodable; use alloy_trie::{BranchNodeCompact, TrieMask, EMPTY_ROOT_HASH}; use reth_execution_errors::{SparseTrieErrorKind, SparseTrieResult}; use reth_trie_common::{ prefix_set::{PrefixSet, PrefixSetMut}, BranchNodeRef, ExtensionNodeRef, LeafNodeRef, Nibbles, RlpNode, TrieNode, CHILD_INDEX_RANGE, }; use reth_trie_sparse::{ provider::{RevealedNode, TrieNodeProvider}, LeafLookup, LeafLookupError, RevealedSparseNode, RlpNodeStackItem, SparseNode, SparseNodeType, SparseTrieInterface, SparseTrieUpdates, TrieMasks, }; use smallvec::SmallVec; use std::{ cmp::{Ord, Ordering, PartialOrd}, sync::mpsc, }; use tracing::{debug, instrument, trace}; /// The maximum length of a path, in nibbles, which belongs to the upper subtrie of a /// [`ParallelSparseTrie`]. All longer paths belong to a lower subtrie. pub const UPPER_TRIE_MAX_DEPTH: usize = 2; /// Number of lower subtries which are managed by the [`ParallelSparseTrie`]. pub const NUM_LOWER_SUBTRIES: usize = 16usize.pow(UPPER_TRIE_MAX_DEPTH as u32); /// A revealed sparse trie with subtries that can be updated in parallel. /// /// ## Structure /// /// The trie is divided into two tiers for efficient parallel processing: /// - **Upper subtrie**: Contains nodes with paths shorter than [`UPPER_TRIE_MAX_DEPTH`] /// - **Lower subtries**: An array of [`NUM_LOWER_SUBTRIES`] subtries, each handling nodes with /// paths of at least [`UPPER_TRIE_MAX_DEPTH`] nibbles /// /// Node placement is determined by path depth: /// - Paths with < [`UPPER_TRIE_MAX_DEPTH`] nibbles go to the upper subtrie /// - Paths with >= [`UPPER_TRIE_MAX_DEPTH`] nibbles go to lower subtries, indexed by their first /// [`UPPER_TRIE_MAX_DEPTH`] nibbles. /// /// Each lower subtrie tracks its root via the `path` field, which represents the shortest path /// in that subtrie. This path will have at least [`UPPER_TRIE_MAX_DEPTH`] nibbles, but may be /// longer when an extension node in the upper trie "reaches into" the lower subtrie. For example, /// if the upper trie has an extension from `0x1` to `0x12345`, then the lower subtrie for prefix /// `0x12` will have its root at path `0x12345` rather than at `0x12`. /// /// ## Node Revealing /// /// The trie uses lazy loading to efficiently handle large state tries. Nodes can be: /// - **Blind nodes**: Stored as hashes ([`SparseNode::Hash`]), representing unloaded trie parts /// - **Revealed nodes**: Fully loaded nodes (Branch, Extension, Leaf) with complete structure /// /// Note: An empty trie contains an `EmptyRoot` node at the root path, rather than no nodes at all. /// A trie with no nodes is blinded, its root may be `EmptyRoot` or some other node type. /// /// Revealing is generally done using pre-loaded node data provided to via `reveal_nodes`. In /// certain cases, such as edge-cases when updating/removing leaves, nodes are revealed on-demand. /// /// ## Leaf Operations /// /// **Update**: When updating a leaf, the new value is stored in the appropriate subtrie's values /// map. If the leaf is new, the trie structure is updated by walking to the leaf from the root, /// creating necessary intermediate branch nodes. /// /// **Removal**: Leaf removal may require parent node modifications. The algorithm walks up the /// trie, removing nodes that become empty and converting single-child branches to extensions. /// /// During leaf operations the overall structure of the trie may change, causing nodes to be moved /// from the upper to lower trie or vice-versa. /// /// The `prefix_set` is modified during both leaf updates and removals to track changed leaf paths. /// /// ## Root Hash Calculation /// /// Root hash computation follows a bottom-up approach: /// 1. Update hashes for all modified lower subtries (can be done in parallel) /// 2. Update hashes for the upper subtrie (which may reference lower subtrie hashes) /// 3. Calculate the final root hash from the upper subtrie's root node /// /// The `prefix_set` tracks which paths have been modified, enabling incremental updates instead of /// recalculating the entire trie. /// /// ## Invariants /// /// - Each leaf entry in the `subtries` and `upper_trie` collection must have a corresponding entry /// in `values` collection. If the root node is a leaf, it must also have an entry in `values`. /// - All keys in `values` collection are full leaf paths. #[derive(Clone, PartialEq, Eq, Debug)] pub struct ParallelSparseTrie { /// This contains the trie nodes for the upper part of the trie. upper_subtrie: Box<SparseSubtrie>, /// An array containing the subtries at the second level of the trie. lower_subtries: [LowerSparseSubtrie; NUM_LOWER_SUBTRIES], /// Set of prefixes (key paths) that have been marked as updated. /// This is used to track which parts of the trie need to be recalculated. prefix_set: PrefixSetMut, /// Optional tracking of trie updates for later use. updates: Option<SparseTrieUpdates>, /// When a bit is set, the corresponding child subtree is stored in the database. branch_node_tree_masks: HashMap<Nibbles, TrieMask>, /// When a bit is set, the corresponding child is stored as a hash in the database. branch_node_hash_masks: HashMap<Nibbles, TrieMask>, /// Reusable buffer pool used for collecting [`SparseTrieUpdatesAction`]s during hash /// computations. update_actions_buffers: Vec<Vec<SparseTrieUpdatesAction>>, /// Metrics for the parallel sparse trie. #[cfg(feature = "metrics")] metrics: crate::metrics::ParallelSparseTrieMetrics, } impl Default for ParallelSparseTrie { fn default() -> Self { Self { upper_subtrie: Box::new(SparseSubtrie { nodes: HashMap::from_iter([(Nibbles::default(), SparseNode::Empty)]), ..Default::default() }), lower_subtries: [const { LowerSparseSubtrie::Blind(None) }; NUM_LOWER_SUBTRIES], prefix_set: PrefixSetMut::default(), updates: None, branch_node_tree_masks: HashMap::default(), branch_node_hash_masks: HashMap::default(), update_actions_buffers: Vec::default(), #[cfg(feature = "metrics")] metrics: Default::default(), } } } impl SparseTrieInterface for ParallelSparseTrie { fn with_root( mut self, root: TrieNode, masks: TrieMasks, retain_updates: bool, ) -> SparseTrieResult<Self> { // A fresh/cleared `ParallelSparseTrie` has a `SparseNode::Empty` at its root in the upper // subtrie. Delete that so we can reveal the new root node. let path = Nibbles::default(); let _removed_root = self.upper_subtrie.nodes.remove(&path).expect("root node should exist"); debug_assert_eq!(_removed_root, SparseNode::Empty); self = self.with_updates(retain_updates); self.reveal_upper_node(Nibbles::default(), &root, masks)?; Ok(self) } fn with_updates(mut self, retain_updates: bool) -> Self { self.updates = retain_updates.then(Default::default); self } fn reveal_nodes(&mut self, mut nodes: Vec<RevealedSparseNode>) -> SparseTrieResult<()> { if nodes.is_empty() { return Ok(()) } // Sort nodes first by their subtrie, and secondarily by their path. This allows for // grouping nodes by their subtrie using `chunk_by`. nodes.sort_unstable_by( |RevealedSparseNode { path: path_a, .. }, RevealedSparseNode { path: path_b, .. }| { let subtrie_type_a = SparseSubtrieType::from_path(path_a); let subtrie_type_b = SparseSubtrieType::from_path(path_b); subtrie_type_a.cmp(&subtrie_type_b).then(path_a.cmp(path_b)) }, ); // Update the top-level branch node masks. This is simple and can't be done in parallel. for RevealedSparseNode { path, masks, .. } in &nodes { if let Some(tree_mask) = masks.tree_mask { self.branch_node_tree_masks.insert(*path, tree_mask); } if let Some(hash_mask) = masks.hash_mask { self.branch_node_hash_masks.insert(*path, hash_mask); } } // Due to the sorting all upper subtrie nodes will be at the front of the slice. We split // them off from the rest to be handled specially by // `ParallelSparseTrie::reveal_upper_node`. let num_upper_nodes = nodes .iter() .position(|n| !SparseSubtrieType::path_len_is_upper(n.path.len())) .unwrap_or(nodes.len()); let upper_nodes = &nodes[..num_upper_nodes]; let lower_nodes = &nodes[num_upper_nodes..]; // Reserve the capacity of the upper subtrie's `nodes` HashMap before iterating, so we don't // end up making many small capacity changes as we loop. self.upper_subtrie.nodes.reserve(upper_nodes.len()); for node in upper_nodes { self.reveal_upper_node(node.path, &node.node, node.masks)?; } #[cfg(not(feature = "std"))] // Reveal lower subtrie nodes serially if nostd { for node in lower_nodes { if let Some(subtrie) = self.lower_subtrie_for_path_mut(&node.path) { subtrie.reveal_node(node.path, &node.node, &node.masks)?; } else { panic!("upper subtrie node {node:?} found amongst lower nodes"); } } Ok(()) } #[cfg(feature = "std")] // Reveal lower subtrie nodes in parallel { use rayon::iter::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator}; // Group the nodes by lower subtrie. This must be collected into a Vec in order for // rayon's `zip` to be happy. let node_groups: Vec<_> = lower_nodes .chunk_by(|node_a, node_b| { SparseSubtrieType::from_path(&node_a.path) == SparseSubtrieType::from_path(&node_b.path) }) .collect(); // Take the lower subtries in the same order that the nodes were grouped into, so that // the two can be zipped together. This also must be collected into a Vec for rayon's // `zip` to be happy. let lower_subtries: Vec<_> = node_groups .iter() .map(|nodes| { // NOTE: chunk_by won't produce empty groups let node = &nodes[0]; let idx = SparseSubtrieType::from_path(&node.path).lower_index().unwrap_or_else( || panic!("upper subtrie node {node:?} found amongst lower nodes"), ); // due to the nodes being sorted secondarily on their path, and chunk_by keeping // the first element of each group, the `path` here will necessarily be the // shortest path being revealed for each subtrie. Therefore we can reveal the // subtrie itself using this path and retain correct behavior. self.lower_subtries[idx].reveal(&node.path); (idx, self.lower_subtries[idx].take_revealed().expect("just revealed")) }) .collect(); let (tx, rx) = mpsc::channel(); // Zip the lower subtries and their corresponding node groups, and reveal lower subtrie // nodes in parallel lower_subtries .into_par_iter() .zip(node_groups.into_par_iter()) .map(|((subtrie_idx, mut subtrie), nodes)| { // reserve space in the HashMap ahead of time; doing it on a node-by-node basis // can cause multiple re-allocations as the hashmap grows. subtrie.nodes.reserve(nodes.len()); for node in nodes { // Reveal each node in the subtrie, returning early on any errors let res = subtrie.reveal_node(node.path, &node.node, node.masks); if res.is_err() { return (subtrie_idx, subtrie, res) } } (subtrie_idx, subtrie, Ok(())) }) .for_each_init(|| tx.clone(), |tx, result| tx.send(result).unwrap()); drop(tx); // Take back all lower subtries which were sent to the rayon pool, collecting the last // seen error in the process and returning that. If we don't fully drain the channel // then we lose lower sparse tries, putting the whole ParallelSparseTrie in an // inconsistent state. let mut any_err = Ok(()); for (subtrie_idx, subtrie, res) in rx { self.lower_subtries[subtrie_idx] = LowerSparseSubtrie::Revealed(subtrie); if res.is_err() { any_err = res; } } any_err } } fn update_leaf<P: TrieNodeProvider>( &mut self, full_path: Nibbles, value: Vec<u8>, is_private: bool, provider: P, ) -> SparseTrieResult<()> { self.prefix_set.insert(full_path); let existing = self.upper_subtrie.inner.values.insert(full_path, value.clone()); if existing.is_some() { // upper trie structure unchanged, return immediately return Ok(()) } let retain_updates = self.updates_enabled(); // Start at the root, traversing until we find either the node to update or a subtrie to // update. // // We first traverse the upper subtrie for two levels, and moving any created nodes to a // lower subtrie if necessary. // // We use `next` to keep track of the next node that we need to traverse to, and // `new_nodes` to keep track of any nodes that were created during the traversal. let mut new_nodes = Vec::new(); let mut next = Some(Nibbles::default()); // Traverse the upper subtrie to find the node to update or the subtrie to update. // // We stop when the next node to traverse would be in a lower subtrie, or if there are no // more nodes to traverse. while let Some(current) = next.filter(|next| SparseSubtrieType::path_len_is_upper(next.len())) { // Traverse the next node, keeping track of any changed nodes and the next step in the // trie match self.upper_subtrie.update_next_node( current, &full_path, is_private, retain_updates, )? { LeafUpdateStep::Continue { next_node } => { next = Some(next_node); } LeafUpdateStep::Complete { inserted_nodes, reveal_path } => { new_nodes.extend(inserted_nodes); if let Some(reveal_path) = reveal_path { let subtrie = self.subtrie_for_path_mut(&reveal_path); if subtrie.nodes.get(&reveal_path).expect("node must exist").is_hash() { debug!( target: "trie::parallel_sparse", child_path = ?reveal_path, leaf_full_path = ?full_path, "Extension node child not revealed in update_leaf, falling back to db", ); if let Some(RevealedNode { node, tree_mask, hash_mask }) = provider.trie_node(&reveal_path)? { let decoded = TrieNode::decode(&mut &node[..])?; trace!( target: "trie::parallel_sparse", ?reveal_path, ?decoded, ?tree_mask, ?hash_mask, "Revealing child (from upper)", ); subtrie.reveal_node( reveal_path, &decoded, TrieMasks { hash_mask, tree_mask }, )?; } else { return Err(SparseTrieErrorKind::NodeNotFoundInProvider { path: reveal_path, } .into()) } } } next = None; } LeafUpdateStep::NodeNotFound => { next = None; } } } // Move nodes from upper subtrie to lower subtries for node_path in &new_nodes { // Skip nodes that belong in the upper subtrie if SparseSubtrieType::path_len_is_upper(node_path.len()) { continue } let node = self.upper_subtrie.nodes.remove(node_path).expect("node belongs to upper subtrie"); // If it's a leaf node, extract its value before getting mutable reference to subtrie. let leaf_value = if let SparseNode::Leaf { key, .. } = &node { let mut leaf_full_path = *node_path; leaf_full_path.extend(key); Some(( leaf_full_path, self.upper_subtrie .inner .values .remove(&leaf_full_path) .expect("leaf nodes have associated values entries"), )) } else { None }; // Get or create the subtrie with the exact node path (not truncated to 2 nibbles). let subtrie = self.subtrie_for_path_mut(node_path); // Insert the leaf value if we have one if let Some((leaf_full_path, value)) = leaf_value { subtrie.inner.values.insert(leaf_full_path, value); } // Insert the node into the lower subtrie subtrie.nodes.insert(*node_path, node); } // If we reached the max depth of the upper trie, we may have had more nodes to insert. if let Some(next_path) = next.filter(|n| !SparseSubtrieType::path_len_is_upper(n.len())) { // The value was inserted into the upper subtrie's `values` at the top of this method. // At this point we know the value is not in the upper subtrie, and the call to // `update_leaf` below will insert it into the lower subtrie. So remove it from the // upper subtrie. self.upper_subtrie.inner.values.remove(&full_path); // Use subtrie_for_path to ensure the subtrie has the correct path. // // The next_path here represents where we need to continue traversal, which may // be longer than 2 nibbles if we're following an extension node. let subtrie = self.subtrie_for_path_mut(&next_path); // Create an empty root at the subtrie path if the subtrie is empty if subtrie.nodes.is_empty() { subtrie.nodes.insert(subtrie.path, SparseNode::Empty); } // If we didn't update the target leaf, we need to call update_leaf on the subtrie // to ensure that the leaf is updated correctly. subtrie.update_leaf(full_path, value, provider, retain_updates, is_private)?; } Ok(()) } fn remove_leaf<P: TrieNodeProvider>( &mut self, full_path: &Nibbles, provider: P, ) -> SparseTrieResult<()> { // When removing a leaf node it's possibly necessary to modify its parent node, and possibly // the parent's parent node. It is not ever necessary to descend further than that; once an // extension node is hit it must terminate in a branch or the root, which won't need further // updates. So the situation with maximum updates is: // // - Leaf // - Branch with 2 children, one being this leaf // - Extension // // ...which will result in just a leaf or extension, depending on what the branch's other // child is. // // Therefore, first traverse the trie in order to find the leaf node and at most its parent // and grandparent. let leaf_path; let leaf_subtrie; let mut branch_parent_path: Option<Nibbles> = None; let mut branch_parent_node: Option<SparseNode> = None; let mut ext_grandparent_path: Option<Nibbles> = None; let mut ext_grandparent_node: Option<SparseNode> = None; let mut curr_path = Nibbles::new(); // start traversal from root let mut curr_subtrie = self.upper_subtrie.as_mut(); let mut curr_subtrie_is_upper = true; // List of node paths which need to have their hashes reset let mut paths_to_reset_hashes = Vec::new(); loop { let curr_node = curr_subtrie.nodes.get_mut(&curr_path).unwrap(); match Self::find_next_to_leaf(&curr_path, curr_node, full_path) { FindNextToLeafOutcome::NotFound => return Ok(()), // leaf isn't in the trie FindNextToLeafOutcome::BlindedNode(hash) => { return Err(SparseTrieErrorKind::BlindedNode { path: curr_path, hash }.into()) } FindNextToLeafOutcome::Found => { // this node is the target leaf leaf_path = curr_path; leaf_subtrie = curr_subtrie; break; } FindNextToLeafOutcome::ContinueFrom(next_path) => { // Any branches/extensions along the path to the leaf will have their `hash` // field unset, as it will no longer be valid once the leaf is removed. match curr_node { SparseNode::Branch { hash, .. } => { if hash.is_some() { paths_to_reset_hashes .push((SparseSubtrieType::from_path(&curr_path), curr_path)); } // If there is already an extension leading into a branch, then that // extension is no longer relevant. match (&branch_parent_path, &ext_grandparent_path) { (Some(branch), Some(ext)) if branch.len() > ext.len() => { ext_grandparent_path = None; ext_grandparent_node = None; } _ => (), }; branch_parent_path = Some(curr_path); branch_parent_node = Some(curr_node.clone()); } SparseNode::Extension { hash, .. } => { if hash.is_some() { paths_to_reset_hashes .push((SparseSubtrieType::from_path(&curr_path), curr_path)); } // We can assume a new branch node will be found after the extension, so // there's no need to modify branch_parent_path/node even if it's // already set. ext_grandparent_path = Some(curr_path); ext_grandparent_node = Some(curr_node.clone()); } SparseNode::Empty | SparseNode::Hash(_) | SparseNode::Leaf { .. } => { unreachable!( "find_next_to_leaf only continues to a branch or extension" ) } } curr_path = next_path; // If we were previously looking at the upper trie, and the new path is in the // lower trie, we need to pull out a ref to the lower trie. if curr_subtrie_is_upper { if let SparseSubtrieType::Lower(idx) = SparseSubtrieType::from_path(&curr_path) { curr_subtrie = self.lower_subtries[idx] .as_revealed_mut() .expect("lower subtrie is revealed"); curr_subtrie_is_upper = false; } } } }; } // We've traversed to the leaf and collected its ancestors as necessary. Remove the leaf // from its SparseSubtrie and reset the hashes of the nodes along the path. self.prefix_set.insert(*full_path); leaf_subtrie.inner.values.remove(full_path); for (subtrie_type, path) in paths_to_reset_hashes { let node = match subtrie_type { SparseSubtrieType::Upper => self.upper_subtrie.nodes.get_mut(&path), SparseSubtrieType::Lower(idx) => self.lower_subtries[idx] .as_revealed_mut() .expect("lower subtrie is revealed") .nodes .get_mut(&path), } .expect("node exists"); match node { SparseNode::Extension { hash, .. } | SparseNode::Branch { hash, .. } => { *hash = None } SparseNode::Empty | SparseNode::Hash(_) | SparseNode::Leaf { .. } => { unreachable!("only branch and extension node hashes can be reset") } } } self.remove_node(&leaf_path); // If the leaf was at the root replace its node with the empty value. We can stop execution // here, all remaining logic is related to the ancestors of the leaf. if leaf_path.is_empty() { self.upper_subtrie.nodes.insert(leaf_path, SparseNode::Empty); return Ok(()) } // If there is a parent branch node (very likely, unless the leaf is at the root) execute // any required changes for that node, relative to the removed leaf. if let (Some(branch_path), Some(SparseNode::Branch { mut state_mask, .. })) = (&branch_parent_path, &branch_parent_node) { let child_nibble = leaf_path.get_unchecked(branch_path.len()); state_mask.unset_bit(child_nibble); let new_branch_node = if state_mask.count_bits() == 1 { // If only one child is left set in the branch node, we need to collapse it. Get // full path of the only child node left. let remaining_child_path = { let mut p = *branch_path; p.push_unchecked( state_mask.first_set_bit_index().expect("state mask is not empty"), ); p }; trace!( target: "trie::parallel_sparse", ?leaf_path, ?branch_path, ?remaining_child_path, "Branch node has only one child", ); let remaining_child_subtrie = self.subtrie_for_path_mut(&remaining_child_path); // If the remaining child node is not yet revealed then we have to reveal it here, // otherwise it's not possible to know how to collapse the branch. let remaining_child_node = match remaining_child_subtrie.nodes.get(&remaining_child_path).unwrap() { SparseNode::Hash(_) => { debug!( target: "trie::parallel_sparse", child_path = ?remaining_child_path, leaf_full_path = ?full_path, "Branch node child not revealed in remove_leaf, falling back to db", ); if let Some(RevealedNode { node, tree_mask, hash_mask }) = provider.trie_node(&remaining_child_path)? { let decoded = TrieNode::decode(&mut &node[..])?; trace!( target: "trie::parallel_sparse", ?remaining_child_path, ?decoded, ?tree_mask, ?hash_mask, "Revealing remaining blinded branch child" ); remaining_child_subtrie.reveal_node( remaining_child_path, &decoded, TrieMasks { hash_mask, tree_mask }, )?; remaining_child_subtrie.nodes.get(&remaining_child_path).unwrap() } else { return Err(SparseTrieErrorKind::NodeNotFoundInProvider { path: remaining_child_path, } .into()) } } node => node, }; let (new_branch_node, remove_child) = Self::branch_changes_on_leaf_removal( branch_path, &remaining_child_path, remaining_child_node, ); if remove_child { self.move_value_on_leaf_removal( branch_path, &new_branch_node, &remaining_child_path, ); self.remove_node(&remaining_child_path); } if let Some(updates) = self.updates.as_mut() { updates.updated_nodes.remove(branch_path); updates.removed_nodes.insert(*branch_path); } new_branch_node } else { // If more than one child is left set in the branch, we just re-insert it with the // updated state_mask. SparseNode::new_branch(state_mask) }; let branch_subtrie = self.subtrie_for_path_mut(branch_path); branch_subtrie.nodes.insert(*branch_path, new_branch_node.clone()); branch_parent_node = Some(new_branch_node); }; // If there is a grandparent extension node then there will necessarily be a parent branch // node. Execute any required changes for the extension node, relative to the (possibly now // replaced with a leaf or extension) branch node. if let (Some(ext_path), Some(SparseNode::Extension { key: shortkey, .. })) = (ext_grandparent_path, &ext_grandparent_node) { let ext_subtrie = self.subtrie_for_path_mut(&ext_path); let branch_path = branch_parent_path.as_ref().unwrap(); if let Some(new_ext_node) = Self::extension_changes_on_leaf_removal( &ext_path, shortkey, branch_path, branch_parent_node.as_ref().unwrap(), ) { ext_subtrie.nodes.insert(ext_path, new_ext_node.clone()); self.move_value_on_leaf_removal(&ext_path, &new_ext_node, branch_path); self.remove_node(branch_path); }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
true
SeismicSystems/seismic-reth
https://github.com/SeismicSystems/seismic-reth/blob/62834bd8deb86513778624a3ba33f55f4d6a1471/crates/trie/parallel/src/proof.rs
crates/trie/parallel/src/proof.rs
use crate::{ metrics::ParallelTrieMetrics, proof_task::{ProofTaskKind, ProofTaskManagerHandle, StorageProofInput}, root::ParallelStateRootError, stats::ParallelTrieTracker, StorageRootTargets, }; use alloy_primitives::{ map::{B256Map, B256Set, HashMap}, B256, }; use alloy_rlp::{BufMut, Encodable}; use itertools::Itertools; use reth_execution_errors::StorageRootError; use reth_provider::{ providers::ConsistentDbView, BlockReader, DBProvider, DatabaseProviderFactory, FactoryTx, ProviderError, }; use reth_storage_errors::db::DatabaseError; use reth_trie::{ hashed_cursor::{HashedCursorFactory, HashedPostStateCursorFactory}, node_iter::{TrieElement, TrieNodeIter}, prefix_set::{PrefixSet, PrefixSetMut, TriePrefixSetsMut}, proof::StorageProof, trie_cursor::{InMemoryTrieCursorFactory, TrieCursorFactory}, updates::TrieUpdatesSorted, walker::TrieWalker, DecodedMultiProof, DecodedStorageMultiProof, HashBuilder, HashedPostStateSorted, MultiProofTargets, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE, }; use reth_trie_common::{ added_removed_keys::MultiAddedRemovedKeys, proof::{DecodedProofNodes, ProofRetainer}, }; use reth_trie_db::{DatabaseHashedCursorFactory, DatabaseTrieCursorFactory}; use std::sync::{mpsc::Receiver, Arc}; use tracing::debug; /// Parallel proof calculator. /// /// This can collect proof for many targets in parallel, spawning a task for each hashed address /// that has proof targets. #[derive(Debug)] pub struct ParallelProof<Factory: DatabaseProviderFactory> { /// Consistent view of the database. view: ConsistentDbView<Factory>, /// The sorted collection of cached in-memory intermediate trie nodes that /// can be reused for computation. pub nodes_sorted: Arc<TrieUpdatesSorted>, /// The sorted in-memory overlay hashed state. pub state_sorted: Arc<HashedPostStateSorted>, /// The collection of prefix sets for the computation. Since the prefix sets _always_ /// invalidate the in-memory nodes, not all keys from `state_sorted` might be present here, /// if we have cached nodes for them. pub prefix_sets: Arc<TriePrefixSetsMut>, /// Flag indicating whether to include branch node masks in the proof. collect_branch_node_masks: bool, /// Provided by the user to give the necessary context to retain extra proofs. multi_added_removed_keys: Option<Arc<MultiAddedRemovedKeys>>, /// Handle to the storage proof task. storage_proof_task_handle: ProofTaskManagerHandle<FactoryTx<Factory>>, #[cfg(feature = "metrics")] metrics: ParallelTrieMetrics, } impl<Factory: DatabaseProviderFactory> ParallelProof<Factory> { /// Create new state proof generator. pub fn new( view: ConsistentDbView<Factory>, nodes_sorted: Arc<TrieUpdatesSorted>, state_sorted: Arc<HashedPostStateSorted>, prefix_sets: Arc<TriePrefixSetsMut>, storage_proof_task_handle: ProofTaskManagerHandle<FactoryTx<Factory>>, ) -> Self { Self { view, nodes_sorted, state_sorted, prefix_sets, collect_branch_node_masks: false, multi_added_removed_keys: None, storage_proof_task_handle, #[cfg(feature = "metrics")] metrics: ParallelTrieMetrics::new_with_labels(&[("type", "proof")]), } } /// Set the flag indicating whether to include branch node masks in the proof. pub const fn with_branch_node_masks(mut self, branch_node_masks: bool) -> Self { self.collect_branch_node_masks = branch_node_masks; self } /// Configure the `ParallelProof` with a [`MultiAddedRemovedKeys`], allowing for retaining /// extra proofs needed to add and remove leaf nodes from the tries. pub fn with_multi_added_removed_keys( mut self, multi_added_removed_keys: Option<Arc<MultiAddedRemovedKeys>>, ) -> Self { self.multi_added_removed_keys = multi_added_removed_keys; self } } impl<Factory> ParallelProof<Factory> where Factory: DatabaseProviderFactory<Provider: BlockReader> + Clone + 'static, { /// Spawns a storage proof on the storage proof task and returns a receiver for the result. fn spawn_storage_proof( &self, hashed_address: B256, prefix_set: PrefixSet, target_slots: B256Set, ) -> Receiver<Result<DecodedStorageMultiProof, ParallelStateRootError>> { let input = StorageProofInput::new( hashed_address, prefix_set, target_slots, self.collect_branch_node_masks, self.multi_added_removed_keys.clone(), ); let (sender, receiver) = std::sync::mpsc::channel(); let _ = self.storage_proof_task_handle.queue_task(ProofTaskKind::StorageProof(input, sender)); receiver } /// Generate a storage multiproof according to the specified targets and hashed address. pub fn storage_proof( self, hashed_address: B256, target_slots: B256Set, ) -> Result<DecodedStorageMultiProof, ParallelStateRootError> { let total_targets = target_slots.len(); let prefix_set = PrefixSetMut::from(target_slots.iter().map(Nibbles::unpack)); let prefix_set = prefix_set.freeze(); debug!( target: "trie::parallel_proof", total_targets, ?hashed_address, "Starting storage proof generation" ); let receiver = self.spawn_storage_proof(hashed_address, prefix_set, target_slots); let proof_result = receiver.recv().map_err(|_| { ParallelStateRootError::StorageRoot(StorageRootError::Database(DatabaseError::Other( format!("channel closed for {hashed_address}"), ))) })?; debug!( target: "trie::parallel_proof", total_targets, ?hashed_address, "Storage proof generation completed" ); proof_result } /// Generate a [`DecodedStorageMultiProof`] for the given proof by first calling /// `storage_proof`, then decoding the proof nodes. pub fn decoded_storage_proof( self, hashed_address: B256, target_slots: B256Set, ) -> Result<DecodedStorageMultiProof, ParallelStateRootError> { self.storage_proof(hashed_address, target_slots) } /// Generate a state multiproof according to specified targets. pub fn decoded_multiproof( self, targets: MultiProofTargets, ) -> Result<DecodedMultiProof, ParallelStateRootError> { let mut tracker = ParallelTrieTracker::default(); // Extend prefix sets with targets let mut prefix_sets = (*self.prefix_sets).clone(); prefix_sets.extend(TriePrefixSetsMut { account_prefix_set: PrefixSetMut::from(targets.keys().copied().map(Nibbles::unpack)), storage_prefix_sets: targets .iter() .filter(|&(_hashed_address, slots)| !slots.is_empty()) .map(|(hashed_address, slots)| { (*hashed_address, PrefixSetMut::from(slots.iter().map(Nibbles::unpack))) }) .collect(), destroyed_accounts: Default::default(), }); let prefix_sets = prefix_sets.freeze(); let storage_root_targets = StorageRootTargets::new( prefix_sets.account_prefix_set.iter().map(|nibbles| B256::from_slice(&nibbles.pack())), prefix_sets.storage_prefix_sets.clone(), ); let storage_root_targets_len = storage_root_targets.len(); debug!( target: "trie::parallel_proof", total_targets = storage_root_targets_len, "Starting parallel proof generation" ); // Pre-calculate storage roots for accounts which were changed. tracker.set_precomputed_storage_roots(storage_root_targets_len as u64); // stores the receiver for the storage proof outcome for the hashed addresses // this way we can lazily await the outcome when we iterate over the map let mut storage_proof_receivers = B256Map::with_capacity_and_hasher(storage_root_targets.len(), Default::default()); for (hashed_address, prefix_set) in storage_root_targets.into_iter().sorted_unstable_by_key(|(address, _)| *address) { let target_slots = targets.get(&hashed_address).cloned().unwrap_or_default(); let receiver = self.spawn_storage_proof(hashed_address, prefix_set, target_slots); // store the receiver for that result with the hashed address so we can await this in // place when we iterate over the trie storage_proof_receivers.insert(hashed_address, receiver); } let provider_ro = self.view.provider_ro()?; let trie_cursor_factory = InMemoryTrieCursorFactory::new( DatabaseTrieCursorFactory::new(provider_ro.tx_ref()), &self.nodes_sorted, ); let hashed_cursor_factory = HashedPostStateCursorFactory::new( DatabaseHashedCursorFactory::new(provider_ro.tx_ref()), &self.state_sorted, ); let accounts_added_removed_keys = self.multi_added_removed_keys.as_ref().map(|keys| keys.get_accounts()); // Create the walker. let walker = TrieWalker::<_>::state_trie( trie_cursor_factory.account_trie_cursor().map_err(ProviderError::Database)?, prefix_sets.account_prefix_set, ) .with_added_removed_keys(accounts_added_removed_keys) .with_deletions_retained(true); // Create a hash builder to rebuild the root node since it is not available in the database. let retainer = targets .keys() .map(Nibbles::unpack) .collect::<ProofRetainer>() .with_added_removed_keys(accounts_added_removed_keys); let mut hash_builder = HashBuilder::default() .with_proof_retainer(retainer) .with_updates(self.collect_branch_node_masks); // Initialize all storage multiproofs as empty. // Storage multiproofs for non empty tries will be overwritten if necessary. let mut collected_decoded_storages: B256Map<DecodedStorageMultiProof> = targets.keys().map(|key| (*key, DecodedStorageMultiProof::empty())).collect(); let mut account_rlp = Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE); let mut account_node_iter = TrieNodeIter::state_trie( walker, hashed_cursor_factory.hashed_account_cursor().map_err(ProviderError::Database)?, ); while let Some(account_node) = account_node_iter.try_next().map_err(ProviderError::Database)? { match account_node { TrieElement::Branch(node) => { hash_builder.add_branch(node.key, node.value, node.children_are_in_trie); } TrieElement::Leaf(hashed_address, account) => { let decoded_storage_multiproof = match storage_proof_receivers .remove(&hashed_address) { Some(rx) => rx.recv().map_err(|e| { ParallelStateRootError::StorageRoot(StorageRootError::Database( DatabaseError::Other(format!( "channel closed for {hashed_address}: {e}" )), )) })??, // Since we do not store all intermediate nodes in the database, there might // be a possibility of re-adding a non-modified leaf to the hash builder. None => { tracker.inc_missed_leaves(); let raw_fallback_proof = StorageProof::new_hashed( trie_cursor_factory.clone(), hashed_cursor_factory.clone(), hashed_address, ) .with_prefix_set_mut(Default::default()) .storage_multiproof( targets.get(&hashed_address).cloned().unwrap_or_default(), ) .map_err(|e| { ParallelStateRootError::StorageRoot(StorageRootError::Database( DatabaseError::Other(e.to_string()), )) })?; raw_fallback_proof.try_into()? } }; // Encode account account_rlp.clear(); let account = account.into_trie_account(decoded_storage_multiproof.root); account.encode(&mut account_rlp as &mut dyn BufMut); let is_private = false; // account leaves are always public. Their storage leaves can be private. hash_builder.add_leaf( Nibbles::unpack(hashed_address), &account_rlp, is_private, ); // We might be adding leaves that are not necessarily our proof targets. if targets.contains_key(&hashed_address) { collected_decoded_storages .insert(hashed_address, decoded_storage_multiproof); } } } } let _ = hash_builder.root(); let stats = tracker.finish(); #[cfg(feature = "metrics")] self.metrics.record(stats); let account_subtree_raw_nodes = hash_builder.take_proof_nodes(); let decoded_account_subtree = DecodedProofNodes::try_from(account_subtree_raw_nodes)?; let (branch_node_hash_masks, branch_node_tree_masks) = if self.collect_branch_node_masks { let updated_branch_nodes = hash_builder.updated_branch_nodes.unwrap_or_default(); ( updated_branch_nodes.iter().map(|(path, node)| (*path, node.hash_mask)).collect(), updated_branch_nodes .into_iter() .map(|(path, node)| (path, node.tree_mask)) .collect(), ) } else { (HashMap::default(), HashMap::default()) }; debug!( target: "trie::parallel_proof", total_targets = storage_root_targets_len, duration = ?stats.duration(), branches_added = stats.branches_added(), leaves_added = stats.leaves_added(), missed_leaves = stats.missed_leaves(), precomputed_storage_roots = stats.precomputed_storage_roots(), "Calculated decoded proof" ); Ok(DecodedMultiProof { account_subtree: decoded_account_subtree, branch_node_hash_masks, branch_node_tree_masks, storages: collected_decoded_storages, }) } } #[cfg(test)] mod tests { use super::*; use crate::proof_task::{ProofTaskCtx, ProofTaskManager}; use alloy_primitives::{ keccak256, map::{B256Set, DefaultHashBuilder}, Address, U256, }; use rand::Rng; use reth_primitives_traits::{Account, StorageEntry}; use reth_provider::{test_utils::create_test_provider_factory, HashingWriter}; use reth_trie::proof::Proof; use tokio::runtime::Runtime; #[test] fn random_parallel_proof() { let factory = create_test_provider_factory(); let consistent_view = ConsistentDbView::new(factory.clone(), None); let mut rng = rand::rng(); let state = (0..100) .map(|_| { let address = Address::random(); let account = Account { balance: U256::from(rng.random::<u64>()), ..Default::default() }; let mut storage = HashMap::<B256, U256, DefaultHashBuilder>::default(); let has_storage = rng.random_bool(0.7); if has_storage { for _ in 0..100 { storage.insert( B256::from(U256::from(rng.random::<u64>())), U256::from(rng.random::<u64>()), ); } } (address, (account, storage)) }) .collect::<HashMap<_, _, DefaultHashBuilder>>(); { let provider_rw = factory.provider_rw().unwrap(); provider_rw .insert_account_for_hashing( state.iter().map(|(address, (account, _))| (*address, Some(*account))), ) .unwrap(); provider_rw .insert_storage_for_hashing(state.iter().map(|(address, (_, storage))| { ( *address, storage.iter().map(|(slot, value)| StorageEntry { key: *slot, value: alloy_primitives::FlaggedStorage::public(*value), }), ) })) .unwrap(); provider_rw.commit().unwrap(); } let mut targets = MultiProofTargets::default(); for (address, (_, storage)) in state.iter().take(10) { let hashed_address = keccak256(*address); let mut target_slots = B256Set::default(); for (slot, _) in storage.iter().take(5) { target_slots.insert(*slot); } if !target_slots.is_empty() { targets.insert(hashed_address, target_slots); } } let provider_rw = factory.provider_rw().unwrap(); let trie_cursor_factory = DatabaseTrieCursorFactory::new(provider_rw.tx_ref()); let hashed_cursor_factory = DatabaseHashedCursorFactory::new(provider_rw.tx_ref()); let rt = Runtime::new().unwrap(); let task_ctx = ProofTaskCtx::new(Default::default(), Default::default(), Default::default()); let proof_task = ProofTaskManager::new(rt.handle().clone(), consistent_view.clone(), task_ctx, 1); let proof_task_handle = proof_task.handle(); // keep the join handle around to make sure it does not return any errors // after we compute the state root let join_handle = rt.spawn_blocking(move || proof_task.run()); let parallel_result = ParallelProof::new( consistent_view, Default::default(), Default::default(), Default::default(), proof_task_handle.clone(), ) .decoded_multiproof(targets.clone()) .unwrap(); let sequential_result_raw = Proof::new(trie_cursor_factory, hashed_cursor_factory) .multiproof(targets.clone()) .unwrap(); // targets might be consumed by parallel_result let sequential_result_decoded: DecodedMultiProof = sequential_result_raw .try_into() .expect("Failed to decode sequential_result for test comparison"); // to help narrow down what is wrong - first compare account subtries assert_eq!(parallel_result.account_subtree, sequential_result_decoded.account_subtree); // then compare length of all storage subtries assert_eq!(parallel_result.storages.len(), sequential_result_decoded.storages.len()); // then compare each storage subtrie for (hashed_address, storage_proof) in &parallel_result.storages { let sequential_storage_proof = sequential_result_decoded.storages.get(hashed_address).unwrap(); assert_eq!(storage_proof, sequential_storage_proof); } // then compare the entire thing for any mask differences assert_eq!(parallel_result, sequential_result_decoded); // drop the handle to terminate the task and then block on the proof task handle to make // sure it does not return any errors drop(proof_task_handle); rt.block_on(join_handle).unwrap().expect("The proof task should not return an error"); } }
rust
Apache-2.0
62834bd8deb86513778624a3ba33f55f4d6a1471
2026-01-04T20:20:17.218210Z
false