diff --git a/crates/rpc/rpc-eth-api/src/helpers/call.rs b/crates/rpc/rpc-eth-api/src/helpers/call.rs index 48249a286fa..baf193524ea 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/call.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/call.rs @@ -7,7 +7,7 @@ use super::{LoadBlock, LoadPendingBlock, LoadState, LoadTransaction, SpawnBlocki use crate::{ helpers::estimate::EstimateCall, FromEvmError, FullEthApiTypes, RpcBlock, RpcNodeCore, }; -use alloy_consensus::{transaction::TxHashRef, BlockHeader}; +use alloy_consensus::BlockHeader; use alloy_eips::eip2930::AccessListResult; use alloy_evm::overrides::{apply_block_overrides, apply_state_overrides, OverrideBlockHashes}; use alloy_network::TransactionBuilder; @@ -21,11 +21,14 @@ use futures::Future; use reth_chainspec::{ChainSpecProvider, EthChainSpec, EthereumHardforks}; use reth_errors::{ProviderError, RethError}; use reth_evm::{ - block::BlockExecutor, env::BlockEnvironment, execute::BlockBuilder, ConfigureEvm, Evm, - EvmEnvFor, EvmFor, HaltReasonFor, InspectorFor, TransactionEnvMut, TxEnvFor, + block::{BlockExecutor, TxResult}, + env::BlockEnvironment, + execute::BlockBuilder, + BlockExecutorForEvm, ConfigureEvm, Evm, EvmEnvFor, HaltReasonFor, InspectorFor, + TransactionEnvMut, TxEnvFor, }; use reth_node_api::BlockBody; -use reth_primitives_traits::Recovered; +use reth_primitives_traits::{BlockTy, Recovered, RecoveredBlock}; use reth_revm::{ cancelled::CancelOnDrop, database::StateProviderDatabase, @@ -41,7 +44,7 @@ use reth_rpc_eth_types::{ simulate::{self, EthSimulateError}, EthApiError, StateCacheDb, }; -use reth_storage_api::{BlockIdReader, ProviderTx}; +use reth_storage_api::{BlockIdReader, ProviderTx, StateProviderBox}; use revm::{ context::Block, context_interface::{result::ResultAndState, Cfg, Transaction}, @@ -704,7 +707,7 @@ pub trait Call: /// /// Before the transaction is executed, the state is positioned right before the transaction, /// either by attaching the block's cached BAL or by executing all previous transactions in the - /// block. + /// block through the block executor, which then also executes the transaction. /// The callback `f` is invoked with the [`ResultAndState`] after the transaction was executed /// and the database that points to the beginning of the transaction. The database may have /// the block's BAL attached and must only be used for reads, because an attached BAL takes @@ -750,25 +753,16 @@ pub trait Call: return f(tx_info, res, db) } - let block_txs = block.transactions_recovered(); - - let mut executor = RpcNodeCore::evm_config(&this) - .executor_for_block(&mut db, block.sealed_block()) - .map_err(RethError::other) - .map_err(Self::Error::from_eth_err)?; - executor.apply_pre_execution_changes().map_err(Self::Error::from_eth_err)?; - - // replay all transactions prior to the targeted transaction - for block_tx in block_txs { - if block_tx.tx_hash() == tx.tx_hash() { - break; - } - executor.execute_transaction(block_tx).map_err(Self::Error::from_eth_err)?; - } - - let tx_env = RpcNodeCore::evm_config(&this).tx_env(tx); - - let res = executor.evm_mut().transact(tx_env).map_err(Self::Error::from_evm_err)?; + let mut executor = this.block_executor(&block, &mut db)?; + this.replay_transactions_until_with_executor( + &mut executor, + block.transactions_recovered(), + tx_info.index.expect("included transaction has an index") as usize, + )?; + let res = executor + .execute_transaction_without_commit(tx) + .map_err(Self::Error::from_eth_err)? + .into_result(); drop(executor); f(tx_info, res, db) }) @@ -777,34 +771,45 @@ pub trait Call: } } - /// Replays all transactions before the target transaction index on the given EVM. + /// Creates a block executor for `block` on `db` and applies the block's pre-execution + /// changes. /// - /// This executes on a caller provided EVM, so the target transaction can then be run on the - /// same EVM, keeping any block-scoped EVM state intact. The EVM's inspector configuration is - /// left untouched; see - /// [`Trace::inspect_transaction_in_block`] to replay without inspection and trace the target. + /// Replaying a block's own transactions through the executor rather than a bare EVM includes + /// the changes the executor applies on top of each EVM result, so replayed results agree with + /// the block's receipts and state. + fn block_executor<'a>( + &'a self, + block: &'a RecoveredBlock>, + db: &'a mut StateCacheDb, + ) -> Result< + BlockExecutorForEvm<'a, Self::Evm, StateProviderDatabase>, + Self::Error, + > { + let mut executor = self + .evm_config() + .executor_for_block(db, block.sealed_block()) + .map_err(RethError::other) + .map_err(Self::Error::from_eth_err)?; + executor.apply_pre_execution_changes().map_err(Self::Error::from_eth_err)?; + Ok(executor) + } + + /// Replays all transactions before the target transaction index through the given executor. /// /// If the target index is greater than or equal to the iterator length, all transactions are /// replayed. - fn replay_transactions_until_with_evm<'a, DB, I, Txs>( + fn replay_transactions_until_with_executor<'a, E, Txs>( &self, - evm: &mut EvmFor, + executor: &mut E, transactions: Txs, target_tx_index: usize, ) -> Result<(), Self::Error> where - DB: Database> + DatabaseCommit + core::fmt::Debug, - I: InspectorFor, + E: BlockExecutor>, Txs: IntoIterator>>, { - for (index, tx) in transactions.into_iter().enumerate() { - if index == target_tx_index { - // reached the target transaction - break - } - - let tx_env = self.evm_config().tx_env(tx); - evm.transact_commit(tx_env).map_err(Self::Error::from_evm_err)?; + for tx in transactions.into_iter().take(target_tx_index) { + executor.execute_transaction(tx).map_err(Self::Error::from_eth_err)?; } Ok(()) } diff --git a/crates/rpc/rpc-eth-api/src/helpers/trace.rs b/crates/rpc/rpc-eth-api/src/helpers/trace.rs index d51921713e5..010c153f195 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/trace.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/trace.rs @@ -9,12 +9,15 @@ use alloy_rpc_types_eth::{BlockId, TransactionInfo}; use futures::Future; use reth_errors::RethError; use reth_evm::{ - block::BlockExecutor, evm::EvmFactoryExt, tracing::TracingCtx, ConfigureEvm, Evm, EvmEnvFor, - EvmFor, HaltReasonFor, InspectorFor, IntoTxEnv, TxEnvFor, + block::{BlockExecutor, BlockExecutorFor, TxResult}, + ConfigureEvm, Evm, EvmEnvFor, EvmFor, HaltReasonFor, InspectorFor, IntoTxEnv, TxEnvFor, }; -use reth_primitives_traits::{BlockBody, BlockTy, Recovered, RecoveredBlock}; -use reth_rpc_eth_types::cache::db::{attach_bal_before_tx, StateCacheDb}; -use reth_storage_api::{ProviderBlock, ProviderTx}; +use reth_primitives_traits::{BlockBody, BlockTy, RecoveredBlock}; +use reth_rpc_eth_types::{ + cache::db::{attach_bal_before_tx, StateCacheDb}, + EthApiError, +}; +use reth_storage_api::ProviderBlock; use revm::{context::Block, context_interface::result::ResultAndState, state::bal::Bal as RevmBal}; use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; use std::sync::Arc; @@ -40,7 +43,7 @@ pub trait Trace: LoadState> + Call { /// /// Before the transaction is traced, the state is positioned right before the transaction, /// either by attaching the block's cached BAL or by executing all previous transactions in - /// the block. + /// the block, see [`Trace::inspect_transaction_in_block`]. /// The callback `f` is invoked with the [`ResultAndState`] after the transaction was executed /// and the database that points to the beginning of the transaction. The database may have /// the block's BAL attached and must only be used for reads, because an attached BAL takes @@ -73,7 +76,7 @@ pub trait Trace: LoadState> + Call { /// /// Before the transaction is traced, the state is positioned right before the transaction, /// either by attaching the block's cached BAL or by executing all previous transactions in - /// the block. + /// the block, see [`Trace::inspect_transaction_in_block`]. /// The callback `f` is invoked with the [`ResultAndState`] after the transaction was executed /// and the database that points to the beginning of the transaction. The database may have /// the block's BAL attached and must only be used for reads, because an attached BAL takes @@ -106,7 +109,7 @@ pub trait Trace: LoadState> + Call { None => return Ok(None), Some(res) => res, }; - let (tx, tx_info) = transaction.split(); + let (_, tx_info) = transaction.split(); // we need to get the state of the parent block because we're essentially replaying the // block the transaction is included in @@ -121,7 +124,6 @@ pub trait Trace: LoadState> + Call { // returns transactions included in a block tx_info.index.expect("transaction_and_block only returns block transactions") as usize, - tx, bal.as_deref(), )?; f(tx_info, inspector, res, db) @@ -134,9 +136,10 @@ pub trait Trace: LoadState> + Call { /// Positions the state of `db` right before the transaction at the target index. /// /// If the block's cached BAL is given, it is attached to the database at the target index and - /// no transactions are executed, see [`attach_bal_before_tx`]. Otherwise all transactions - /// before the target transaction are executed and their changes are written to the - /// _runtime_ db ([`StateCacheDb`]). + /// no transactions are executed, see [`attach_bal_before_tx`]. Otherwise the block's + /// pre-execution changes and all transactions before the target transaction are executed + /// through the block executor, and their changes are written to the _runtime_ db + /// ([`StateCacheDb`]). /// /// If the target index is greater than or equal to the block's transaction count, all /// transactions are replayed. @@ -152,23 +155,26 @@ pub trait Trace: LoadState> + Call { return Ok(()) } - self.apply_pre_execution_changes(block, db)?; - - let evm_env = self.evm_env_for_header(block.sealed_block().sealed_header())?; - let mut evm = self.evm_config().evm_with_env(db, evm_env); - self.replay_transactions_until_with_evm( - &mut evm, + let mut executor = self.block_executor(block, db)?; + self.replay_transactions_until_with_executor( + &mut executor, block.transactions_recovered(), target_tx_index, ) } - /// Executes the target transaction with the configured inspector on the state right before - /// the transaction. + /// Executes the block's transaction at the target index with the configured inspector on the + /// state right before the transaction. /// /// If the block's cached BAL is given, the state is positioned by attaching the BAL at the - /// target index, see [`attach_bal_before_tx`]. Otherwise all transactions before the target - /// transaction are replayed without inspection first. + /// target index, see [`attach_bal_before_tx`], and the transaction is executed on its own, so + /// per-transaction changes the block executor applies are skipped. Otherwise all transactions + /// before the target transaction are replayed without inspection through the block executor, + /// see [`Call::block_executor`], which then executes the target transaction, so the result + /// includes any per-transaction changes the executor applies. The result is not committed + /// to `db`. + /// + /// Returns [`EthApiError::InvalidParams`] if the block has no transaction at that index. #[expect(clippy::type_complexity)] fn inspect_transaction_in_block<'a>( &self, @@ -176,36 +182,81 @@ pub trait Trace: LoadState> + Call { db: &'a mut StateCacheDb, inspector: impl InspectorFor, target_tx_index: usize, - target_tx_env: impl IntoTxEnv>, bal: Option<&DecodedBal>>, ) -> Result<(ResultAndState>, EvmEnvFor), Self::Error> { + let Some(target_tx) = block.transactions_recovered().nth(target_tx_index) else { + return Err(Self::Error::from_eth_err(EthApiError::InvalidParams(format!( + "tx_index {target_tx_index} out of bounds for block with {} transactions", + block.transaction_count() + )))) + }; + let evm_env = self.evm_env_for_header(block.sealed_block().sealed_header())?; + if let Some(bal) = bal { // the BAL also covers the block's pre-execution changes attach_bal_before_tx(db, bal, target_tx_index); - } else { - self.apply_pre_execution_changes(block, db)?; + let mut evm = self.evm_config().evm_with_env_and_inspector(db, evm_env, inspector); + let res = evm + .transact(self.evm_config().tx_env(target_tx)) + .map_err(Self::Error::from_evm_err)?; + let (_, evm_env) = evm.finish(); + return Ok((res, evm_env)) } - let evm_env = self.evm_env_for_header(block.sealed_block().sealed_header())?; - let mut evm = self.evm_config().evm_with_env_and_inspector(db, evm_env, inspector); - - if bal.is_none() { - evm.disable_inspector(); - self.replay_transactions_until_with_evm( - &mut evm, - block.transactions_recovered(), - target_tx_index, - )?; - evm.enable_inspector(); - } - - let res = evm.transact(target_tx_env).map_err(Self::Error::from_evm_err)?; + let mut executor = self.inspected_block_executor(block, db, evm_env.clone(), inspector)?; + self.replay_transactions_until_with_executor( + &mut executor, + block.transactions_recovered(), + target_tx_index, + )?; - let (_, evm_env) = evm.finish(); + executor.evm_mut().enable_inspector(); + let res = executor + .execute_transaction_without_commit(target_tx) + .map_err(Self::Error::from_eth_err)? + .into_result(); Ok((res, evm_env)) } + /// Creates a block executor for `block` whose EVM runs the given inspector, and applies the + /// block's pre-execution changes. The inspector is left disabled. + /// + /// The uninspected counterpart is [`Call::block_executor`]; this one exists because the EVM + /// takes its inspector as a type parameter, so a tracer has to be in place when the executor + /// is created. + #[expect(clippy::type_complexity, reason = "the executor type is spelled out by its factory")] + fn inspected_block_executor<'a, 'db, I>( + &'a self, + block: &'a RecoveredBlock>, + db: &'db mut StateCacheDb, + evm_env: EvmEnvFor, + inspector: I, + ) -> Result< + BlockExecutorFor< + 'a, + ::BlockExecutorFactory, + &'db mut StateCacheDb, + I, + >, + Self::Error, + > + where + I: InspectorFor, + { + let evm_config = self.evm_config(); + let ctx = evm_config + .context_for_block(block.sealed_block()) + .map_err(RethError::other) + .map_err(Self::Error::from_eth_err)?; + let mut evm = evm_config.evm_with_env_and_inspector(db, evm_env, inspector); + evm.disable_inspector(); + + let mut executor = evm_config.create_executor_with_state(evm, ctx); + executor.apply_pre_execution_changes().map_err(Self::Error::from_eth_err)?; + Ok(executor) + } + /// Executes all transactions of a block up to a given index. /// /// If a `highest_index` is given, this will only execute the first `highest_index` @@ -226,7 +277,7 @@ pub trait Trace: LoadState> + Call { TransactionInfo, TracingCtx< '_, - Recovered<&ProviderTx>, + TracingInspector, EvmFor, >, ) -> Result @@ -265,16 +316,12 @@ pub trait Trace: LoadState> + Call { Self: LoadBlock, F: Fn( TransactionInfo, - TracingCtx< - '_, - Recovered<&ProviderTx>, - EvmFor, - >, + TracingCtx<'_, Insp, EvmFor>, ) -> Result + Send + 'static, Setup: FnMut() -> Insp + Send + 'static, - Insp: Clone + for<'a> InspectorFor, + Insp: for<'a> InspectorFor, R: Send + 'static, { async move { @@ -299,38 +346,49 @@ pub trait Trace: LoadState> + Call { let block_timestamp = evm_env.block_env.timestamp().saturating_to(); let base_fee = evm_env.block_env.basefee(); - this.apply_pre_execution_changes(&block, &mut db)?; - // prepare transactions, we do everything upfront to reduce time spent with open // state - let max_transactions = highest_index.map_or_else( - || block.body().transaction_count(), - |highest| { - // we need + 1 because the index is 0-based - highest as usize + 1 - }, - ); - - let mut idx = 0; - - let results = this - .evm_config() - .evm_factory() - .create_tracer(&mut db, evm_env, inspector_setup()) - .try_trace_many(block.transactions_recovered().take(max_transactions), |ctx| { - let tx_info = TransactionInfo { - hash: Some(*ctx.tx.tx_hash()), - index: Some(idx), - block_hash: Some(block_hash), - block_number: Some(block_number), - block_timestamp: Some(block_timestamp), - base_fee: Some(base_fee), - }; - idx += 1; - - f(tx_info, ctx) - }) - .collect::>()?; + let max_transactions = highest_index + .map_or_else( + || block.body().transaction_count(), + |highest| { + // we need + 1 because the index is 0-based + (highest as usize).saturating_add(1) + }, + ) + .min(block.body().transaction_count()); + + let mut executor = + this.inspected_block_executor(&block, &mut db, evm_env, inspector_setup())?; + executor.evm_mut().enable_inspector(); + + let mut results = Vec::with_capacity(max_transactions); + let mut transactions = + block.transactions_recovered().take(max_transactions).enumerate().peekable(); + while let Some((idx, tx)) = transactions.next() { + let output = executor + .execute_transaction_without_commit(tx) + .map_err(Self::Error::from_eth_err)?; + + let tx_info = TransactionInfo { + hash: Some(*tx.tx_hash()), + index: Some(idx as u64), + block_hash: Some(block_hash), + block_number: Some(block_number), + block_timestamp: Some(block_timestamp), + base_fee: Some(base_fee), + }; + let (db, inspector, _) = executor.evm_mut().components_mut(); + let inspector = core::mem::replace(inspector, inspector_setup()); + results.push(f( + tx_info, + TracingCtx { result: output.result(), db: &mut *db, inspector }, + )?); + // The state of the last traced transaction is not needed. + if transactions.peek().is_some() { + executor.commit_transaction(output); + } + } Ok(Some(results)) }) @@ -363,7 +421,7 @@ pub trait Trace: LoadState> + Call { TransactionInfo, TracingCtx< '_, - Recovered<&ProviderTx>, + TracingInspector, EvmFor, >, ) -> Result @@ -401,16 +459,12 @@ pub trait Trace: LoadState> + Call { // state and db F: Fn( TransactionInfo, - TracingCtx< - '_, - Recovered<&ProviderTx>, - EvmFor, - >, + TracingCtx<'_, Insp, EvmFor>, ) -> Result + Send + 'static, Setup: FnMut() -> Insp + Send + 'static, - Insp: Clone + for<'a> InspectorFor, + Insp: for<'a> InspectorFor, R: Send + 'static, { self.trace_block_until_with_inspector(block_id, block, None, insp_setup, f) @@ -435,3 +489,28 @@ pub trait Trace: LoadState> + Call { Ok(()) } } + +/// Context passed to per-transaction trace callbacks. +/// +/// Explicit callback annotations must import this type instead of alloy-evm's tracing context. +pub struct TracingCtx<'a, Insp, E: Evm> { + /// Execution result and state changes for the transaction. + pub result: &'a ResultAndState, + /// Database pointing to the transaction pre-state. + pub db: &'a mut E::DB, + /// Inspector used while executing the transaction. + pub inspector: Insp, +} + +impl core::fmt::Debug for TracingCtx<'_, Insp, E> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("TracingCtx").finish_non_exhaustive() + } +} + +impl TracingCtx<'_, Insp, E> { + /// Consumes this context and returns the inspector. + pub fn take_inspector(self) -> Insp { + self.inspector + } +} diff --git a/crates/rpc/rpc/src/debug.rs b/crates/rpc/rpc/src/debug.rs index 1154f793839..51cff756ff7 100644 --- a/crates/rpc/rpc/src/debug.rs +++ b/crates/rpc/rpc/src/debug.rs @@ -20,7 +20,11 @@ use parking_lot::RwLock; use reth_chainspec::{ChainSpecProvider, EthChainSpec, EthereumHardforks}; use reth_engine_primitives::ConsensusEngineEvent; use reth_errors::RethError; -use reth_evm::{block::BlockExecutor, execute::Executor, ConfigureEvm, EvmEnvFor}; +use reth_evm::{ + block::{BlockExecutor, TxResult}, + execute::Executor, + ConfigureEvm, EvmEnvFor, +}; use reth_primitives_traits::{ Block as BlockTrait, BlockBody, BlockTy, ReceiptWithBloom, RecoveredBlock, }; @@ -113,7 +117,10 @@ where self.inner.blocking_task_guard.clone().acquire_owned().await } - /// Trace the entire block asynchronously + /// Trace the entire block asynchronously. + /// + /// Transactions run on a bare EVM, so a block the executor would reject, such as a bad block, + /// is still traced. async fn trace_block( &self, block: Arc>>, @@ -166,6 +173,62 @@ where .await } + /// Traces a canonical block like [`Self::trace_block`], but replays it through the block + /// executor, so the traces include the per-transaction changes the executor applies. + async fn trace_canonical_block( + &self, + block: Arc>>, + evm_env: EvmEnvFor, + opts: GethDebugTracingOptions, + ) -> Result, Eth::Error> { + self.eth_api() + .spawn_with_state_at_block(block.parent_hash(), move |eth_api, mut db| { + let mut results = Vec::with_capacity(block.body().transactions().len()); + + let block_env = evm_env.block_env.clone(); + + let inspector = DebugInspector::new(opts).map_err(Eth::Error::from_eth_err)?; + let mut executor = + eth_api.inspected_block_executor(&block, &mut db, evm_env, inspector)?; + executor.evm_mut().enable_inspector(); + + let mut transactions = block.transactions_recovered().enumerate().peekable(); + while let Some((index, tx)) = transactions.next() { + let tx_env = eth_api.evm_config().tx_env(tx); + + let output = executor + .execute_transaction_without_commit(tx) + .map_err(Eth::Error::from_eth_err)?; + + let (db, inspector, _) = executor.evm_mut().components_mut(); + let result = inspector + .get_result( + Some(TransactionContext { + block_hash: Some(block.hash()), + tx_hash: Some(*tx.tx_hash()), + tx_index: Some(index), + }), + &tx_env, + &block_env, + output.result(), + db, + ) + .map_err(Eth::Error::from_eth_err)?; + + results.push(TraceResult::Success { result, tx_hash: Some(*tx.tx_hash()) }); + if transactions.peek().is_some() { + inspector.fuse().map_err(Eth::Error::from_eth_err)?; + // need to apply the state changes of this transaction before executing the + // next transaction + executor.commit_transaction(output); + } + } + + Ok(results) + }) + .await + } + /// Traces a block for `traceChain`, preserving transaction-level tracing failures in the /// subscription result instead of failing the entire range. async fn trace_chain_block( @@ -180,8 +243,6 @@ where let tx_count = block.body().transactions().len(); let mut results = Vec::with_capacity(tx_count); - eth_api.apply_pre_execution_changes(&block, &mut db)?; - let block_env = evm_env.block_env.clone(); let mut transactions = block.transactions_recovered().enumerate().peekable(); let inspector = match DebugInspector::new(opts) { @@ -197,14 +258,15 @@ where return Ok(results) } }; - let mut evm = - eth_api.evm_config().evm_with_env_and_inspector(&mut db, evm_env, inspector); + let mut executor = + eth_api.inspected_block_executor(&block, &mut db, evm_env, inspector)?; + executor.evm_mut().enable_inspector(); while let Some((index, tx)) = transactions.next() { let tx_hash = *tx.tx_hash(); let tx_env = eth_api.evm_config().tx_env(tx); - let res = match evm.transact(tx_env.clone()) { - Ok(res) => res, + let output = match executor.execute_transaction_without_commit(tx) { + Ok(output) => output, Err(err) => { results.push(Some(TraceResult::Error { error: err.to_string(), @@ -214,7 +276,7 @@ where } }; - let (db, inspector, _) = evm.components_mut(); + let (db, inspector, _) = executor.evm_mut().components_mut(); let result = match inspector.get_result( Some(TransactionContext { block_hash: Some(block.hash()), @@ -223,7 +285,7 @@ where }), &tx_env, &block_env, - &res, + output.result(), db, ) { Ok(result) => result, @@ -245,7 +307,7 @@ where })); break } - db.commit(res.state); + executor.commit_transaction(output); } } @@ -305,7 +367,7 @@ where } let evm_env = self.eth_api().evm_env_for_header(block.sealed_block().sealed_header())?; - self.trace_block(block, evm_env, opts).await + self.trace_canonical_block(block, evm_env, opts).await } /// Trace the transaction according to the provided options. @@ -340,7 +402,6 @@ where &mut db, &mut inspector, index, - tx_env.clone(), bal.as_deref(), )?; @@ -701,16 +762,12 @@ where self.eth_api() .spawn_with_state_at_block(block.parent_hash(), move |eth_api, mut db| { - let mut executor = eth_api - .evm_config() - .executor_for_block(&mut db, block.sealed_block()) - .map_err(RethError::other) - .map_err(Eth::Error::from_eth_err)?; - executor.apply_pre_execution_changes().map_err(Eth::Error::from_eth_err)?; - - for tx in block.transactions_recovered().take(tx_index + 1) { - executor.execute_transaction(tx).map_err(Eth::Error::from_eth_err)?; - } + let mut executor = eth_api.block_executor(&block, &mut db)?; + eth_api.replay_transactions_until_with_executor( + &mut executor, + block.transactions_recovered(), + tx_index + 1, + )?; drop(executor); f(&mut db) @@ -810,22 +867,19 @@ where .recovered_block(block_hash.into()) .await? .ok_or(EthApiError::HeaderNotFound(block_hash.into()))?; - let evm_env = self.eth_api().evm_env_for_header(block.sealed_block().sealed_header())?; self.eth_api() .spawn_with_state_at_block(block.parent_hash(), move |eth_api, mut db| { // Enable transition tracking so that merge_transitions works db.transition_state = Some(Default::default()); - eth_api.apply_pre_execution_changes(&block, &mut db)?; + let mut executor = eth_api.block_executor(&block, &mut db)?; let mut roots = Vec::with_capacity(block.body().transactions().len()); - let mut evm = eth_api.evm_config().evm_with_env(&mut db, evm_env); for tx in block.transactions_recovered() { - let tx_env = eth_api.evm_config().tx_env(tx); - evm.transact_commit(tx_env).map_err(Eth::Error::from_evm_err)?; + executor.execute_transaction(tx).map_err(Eth::Error::from_eth_err)?; - let state = evm.db_mut(); + let state = executor.evm_mut().db_mut(); // Merge transitions into cumulative bundle_state state.merge_transitions(BundleRetention::PlainState); // Compute state root from the accumulated state changes diff --git a/crates/rpc/rpc/src/eth/helpers/trace.rs b/crates/rpc/rpc/src/eth/helpers/trace.rs index 55b1604eeae..ddfaea5c66b 100644 --- a/crates/rpc/rpc/src/eth/helpers/trace.rs +++ b/crates/rpc/rpc/src/eth/helpers/trace.rs @@ -13,3 +13,42 @@ where Rpc: RpcConvert, { } + +#[cfg(test)] +mod tests { + use super::*; + use crate::eth::helpers::types::EthRpcConverter; + use alloy_eips::BlockId; + use reth_chainspec::ChainSpec; + use reth_ethereum_primitives::Block; + use reth_evm_ethereum::EthEvmConfig; + use reth_network_api::noop::NoopNetwork; + use reth_primitives_traits::RecoveredBlock; + use reth_provider::test_utils::NoopProvider; + use reth_rpc_eth_api::helpers::Call; + use reth_transaction_pool::test_utils::testing_pool; + use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; + + #[tokio::test] + async fn inspect_transaction_in_block_out_of_bounds_is_invalid_params() { + let eth_api = EthApi::<_, EthRpcConverter>::builder( + NoopProvider::default(), + testing_pool(), + NoopNetwork::default(), + EthEvmConfig::mainnet(), + ) + .build(); + let block = RecoveredBlock::new_unhashed(Block::default(), vec![]); + + let err = eth_api + .spawn_with_state_at_block(BlockId::latest(), move |this, mut db| { + let mut inspector = TracingInspector::new(TracingInspectorConfig::default_parity()); + this.inspect_transaction_in_block(&block, &mut db, &mut inspector, 0, None) + .map(|_| ()) + }) + .await + .unwrap_err(); + + assert_eq!(err.to_string(), "tx_index 0 out of bounds for block with 0 transactions"); + } +} diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index 7d43540b7fe..a3f493764f8 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -340,7 +340,7 @@ where num.into(), None, TracingInspectorConfig::default_parity(), - |tx_info, mut ctx| { + |tx_info, ctx| { Ok(ctx .take_inspector() .into_parity_builder() diff --git a/crates/rpc/rpc/src/trace.rs b/crates/rpc/rpc/src/trace.rs index c79b087b169..bf587654c07 100644 --- a/crates/rpc/rpc/src/trace.rs +++ b/crates/rpc/rpc/src/trace.rs @@ -34,7 +34,7 @@ use revm::DatabaseCommit; use revm_inspectors::{ opcode::OpcodeGasInspector, storage::StorageInspector, - tracing::{parity::populate_state_diff, TracingInspector, TracingInspectorConfig}, + tracing::{TracingInspector, TracingInspectorConfig}, }; use serde::{Deserialize, Serialize}; use std::sync::Arc; @@ -443,7 +443,7 @@ where Some(block.clone()), None, TracingInspectorConfig::default_parity(), - move |tx_info, mut ctx| { + move |tx_info, ctx| { // Keep the block replay permit inside the spawned replay task. let _block_replay_permit = &permit; let mut traces = ctx @@ -525,7 +525,7 @@ where block_id, Some(block.clone()), TracingInspectorConfig::default_parity(), - |tx_info, mut ctx| { + |tx_info, ctx| { let traces = ctx .take_inspector() .into_parity_builder() @@ -561,18 +561,12 @@ where block_id, None, TracingInspectorConfig::from_parity_config(&trace_types), - move |tx_info, mut ctx| { - let mut full_trace = ctx - .take_inspector() + move |tx_info, ctx| { + let full_trace = ctx + .inspector .into_parity_builder() - .into_trace_results(&ctx.result, &trace_types); - - // If statediffs were requested, populate them with the account balance and - // nonce from pre-state - if let Some(ref mut state_diff) = full_trace.state_diff { - populate_state_diff(state_diff, &ctx.db, ctx.state.iter()) - .map_err(Eth::Error::from_eth_err)?; - } + .into_trace_results_with_state(ctx.result, &trace_types, &**ctx.db) + .map_err(Eth::Error::from_eth_err)?; let trace = TraceResultsWithTransactionHash { transaction_hash: tx_info.hash.expect("tx hash is set"), @@ -638,7 +632,7 @@ where block_id, Some(block.clone()), StorageInspector::default, - move |tx_info, mut ctx| { + move |tx_info, ctx| { let unique_loads = ctx.inspector.unique_loads(); let warm_loads = ctx.inspector.warm_loads(); let trace = TransactionStorageAccess {