diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 0dba2145903..a9566183cf8 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -14190,6 +14190,7 @@ name = "reth-optimism-rpc" version = "2.0.0" dependencies = [ "alloy-consensus 2.4.2", + "alloy-eip7928 0.4.10", "alloy-eips 2.5.0", "alloy-genesis", "alloy-hardforks", diff --git a/rust/alloy-op-evm/src/lib.rs b/rust/alloy-op-evm/src/lib.rs index fb086890949..a985a31a4eb 100644 --- a/rust/alloy-op-evm/src/lib.rs +++ b/rust/alloy-op-evm/src/lib.rs @@ -392,8 +392,9 @@ where let tx = OpTx(tx.into()); // Post-exec transactions never execute: the block executor short-circuits them, and revm - // would reject their tx env outright. Replay paths (e.g. RPC tracing) transact each - // transaction directly, so synthesize the consensus-defined result here. + // would reject their tx env outright. Callers that transact a block's transactions + // directly on the EVM rather than through the executor still reach this, so synthesize the + // consensus-defined result here. if tx.tx_type() == POST_EXEC_TX_TYPE_ID { return Ok(post_exec::noop_post_exec_result()); } diff --git a/rust/alloy-op-evm/src/tests.rs b/rust/alloy-op-evm/src/tests.rs index 60ed2313bfc..4cbb78e272d 100644 --- a/rust/alloy-op-evm/src/tests.rs +++ b/rust/alloy-op-evm/src/tests.rs @@ -210,10 +210,9 @@ fn tracing_inspector_traces_post_exec_tx_as_noop() { ); } -/// The `trace_*` namespace iterates a block's transactions through `TxTracer::try_trace_many`, -/// which ends the iteration early — without surfacing an error — when a replay fails. A block -/// carrying a post-exec tx must produce one trace result per transaction, not a silently -/// truncated list. +/// `TxTracer::try_trace_many` ends the iteration early — without surfacing an error — when a replay +/// fails. A block carrying a post-exec tx must produce one trace result per transaction, not a +/// silently truncated list, for any caller that traces a block through it. #[test] fn try_trace_many_covers_every_tx_in_a_post_exec_block() { let mut tracer = OpEvmFactory::::default().create_tracer( diff --git a/rust/op-reth/crates/node/tests/it/debug_trace_post_exec.rs b/rust/op-reth/crates/node/tests/it/debug_trace_post_exec.rs index 0cbcd40ea85..a5f6183bb00 100644 --- a/rust/op-reth/crates/node/tests/it/debug_trace_post_exec.rs +++ b/rust/op-reth/crates/node/tests/it/debug_trace_post_exec.rs @@ -1,30 +1,56 @@ -//! `debug_trace*` over blocks containing an SDM post-exec (0x7d) transaction. +//! RPC replay over blocks containing an SDM post-exec (0x7d) transaction. //! -//! The RPC trace path replays each transaction directly through the EVM instead of going through -//! the block executor, so it only works on post-exec transactions because `OpEvm::transact_raw` -//! short-circuits them with the consensus-defined no-op result. Without that, tracing any block -//! that carries a 0x7d tx fails whole-block ([the bug]): the replayed post-exec tx env inherited -//! revm's mainnet default chain id, and no honest env for a zero-gas-limit transaction passes -//! validation either. +//! The settlement of an SDM refund (canonical gas, sender credit, fee-vault debits) only happens +//! inside the block executor, so every RPC path that replays block transactions must go through it. +//! A replay on the bare EVM reports pre-refund gas and unsettled balances ([#485]). //! -//! [the bug]: https://github.com/ethereum-optimism/optimism-premium/issues/163 +//! Tracing must also not fail whole-block on the 0x7d tx itself ([premium#163]): the block executor +//! and `OpEvm::transact_raw` both give it the consensus-defined no-op result. +//! +//! [#485]: https://github.com/ethereum-optimism/protocol-team/issues/485 +//! [premium#163]: https://github.com/ethereum-optimism/optimism-premium/issues/163 -use alloy_consensus::{Block, BlockBody, Header, Sealable, SignableTransaction, TxEip1559}; -use alloy_primitives::{Address, B256, Bytes, Signature, TxKind, U256}; -use alloy_rpc_types_eth::TransactionRequest; -use alloy_rpc_types_trace::{common::TraceResult, geth::GethDebugTracingOptions}; +use crate::lagoon; +use alloy_consensus::{ + Block, BlockBody, Header, Sealable, SignableTransaction, TxEip1559, TxReceipt, +}; +use alloy_network::eip2718::Encodable2718; +use alloy_primitives::{Address, B256, Bytes, Signature, TxKind, U256, map::HashSet}; +use alloy_rpc_types_eth::{TransactionInput, TransactionRequest}; +use alloy_rpc_types_trace::{ + common::TraceResult, + geth::{ + GethDebugBuiltInTracerType, GethDebugTracerConfig, GethDebugTracerType, + GethDebugTracingCallOptions, GethDebugTracingOptions, GethTrace, PreStateConfig, + PreStateFrame, + }, + parity::{Delta, StateDiff, TraceType}, +}; use op_alloy_consensus::{OpTxEnvelope, SDMGasEntry, TxDeposit, build_post_exec_tx}; use reth_chainspec::EthChainSpec; +use reth_e2e_test_utils::{ + node::NodeTestContext, transaction::TransactionTestContext, wallet::Wallet, +}; use reth_node_builder::{NodeBuilder, NodeHandle}; use reth_node_core::{ args::{NetworkArgs, RpcServerArgs}, node_config::NodeConfig, }; -use reth_optimism_chainspec::OpChainSpecBuilder; -use reth_optimism_node::OpNode; -use reth_rpc_api::clients::DebugApiClient; +use reth_optimism_chainspec::{OpChainSpec, OpChainSpecBuilder}; +use reth_optimism_node::{OpNode, args::RollupArgs}; +use reth_optimism_primitives::OpTransactionSigned; +use reth_provider::{ReceiptProvider, StateProviderFactory}; +use reth_rpc_api::clients::{DebugApiClient, TraceApiClient}; use reth_rpc_server_types::RpcModuleSelection; use reth_tasks::Runtime; +use std::sync::Arc; + +/// Gas used by a plain transfer before the SDM refund. +const TRANSFER_GAS: u64 = 21_000; + +/// Gas used before the SDM refund by a deployment of the one-byte init code `STOP`: intrinsic +/// 21000, CREATE 32000, one zero calldata byte 4, one init code word 2, and no code deposit. +const DEPLOY_GAS: u64 = 53_006; /// `debug_traceBlock` over a raw block that ends in a post-exec (0x7d) transaction must return /// one successful trace per transaction. Before the `transact_raw` short-circuit this failed for @@ -33,23 +59,13 @@ use reth_tasks::Runtime; async fn test_debug_trace_block_with_post_exec_tx() -> eyre::Result<()> { reth_tracing::init_test_tracing(); - let chain_spec = OpChainSpecBuilder::optimism_sepolia().lagoon_activated().build(); + let chain_spec = Arc::new(OpChainSpecBuilder::optimism_sepolia().lagoon_activated().build()); - let exec = Runtime::test(); - let mut network_args = NetworkArgs::default().with_unused_ports(); - network_args.discovery.discv5_port = Some(0); - network_args.discovery.discv5_port_ipv6 = Some(0); - let node_config = - NodeConfig::test().map_chain(chain_spec.clone()).with_network(network_args).with_rpc( - RpcServerArgs::default() - .with_unused_ports() - .with_http() - // `debug_*` is not part of the default HTTP module selection. - .with_http_api(RpcModuleSelection::All), - ); - - let NodeHandle { node, node_exit_future: _ } = - NodeBuilder::new(node_config).testing_node(exec).node(OpNode::default()).launch().await?; + let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(rpc_node_config(&chain_spec)) + .testing_node(Runtime::test()) + .node(OpNode::default()) + .launch() + .await?; let client = node.add_ons_handle.rpc_server_handles().rpc.http_client().unwrap(); // `debug_traceBlock` replays a caller-supplied raw block on its parent's state, so the block @@ -79,7 +95,7 @@ async fn test_debug_trace_block_with_post_exec_tx() -> eyre::Result<()> { chain_id: chain_spec.chain_id(), // The preceding deposit increments the depositor nonce after Regolith. nonce: 1, - gas_limit: 21_000, + gas_limit: TRANSFER_GAS, max_fee_per_gas: u128::from(header.base_fee_per_gas.unwrap_or_default()), to: TxKind::Call(Address::with_last_byte(1)), ..Default::default() @@ -122,3 +138,179 @@ async fn test_debug_trace_block_with_post_exec_tx() -> eyre::Result<()> { Ok(()) } + +/// Every RPC path that replays a single transaction of a block must agree with what the chain +/// committed for an SDM-refunded transaction: the receipt's canonical gas and the post-settlement +/// balances. +/// +/// The block is sequenced by a Lagoon node running the fixed test policy, which refunds every +/// regular transaction one gas, so it is a real, imported block with a 0x7d tx and a settled state. +/// The refunded transaction is a contract deployment: the producer never refunds below the EIP-7623 +/// floor, which a plain transfer already sits on. +#[tokio::test] +async fn test_rpc_replay_matches_sdm_settlement() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let chain_spec = lagoon::chain_spec()?; + let op_node = OpNode::new(RollupArgs { + operator_sdm_opt_in: true, + // The fixed one-gas policy, without an excessive-refund target. + testing_sdm_fixed_policy: Some(None), + ..Default::default() + }); + let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(rpc_node_config(&chain_spec)) + .testing_node(Runtime::test()) + .node(op_node) + .launch() + .await?; + let client = node.add_ons_handle.rpc_server_handles().rpc.http_client().unwrap(); + let mut node = NodeTestContext::new(node, lagoon::payload_attributes).await?; + + let wallet = Wallet::default().with_chain_id(chain_spec.chain_id()); + let sender = wallet.inner.address(); + // Init code `STOP` deploys an empty contract. + let deploy = TransactionRequest { + chain_id: Some(wallet.chain_id), + nonce: Some(0), + gas: Some(100_000), + max_fee_per_gas: Some(20_000_000_000), + max_priority_fee_per_gas: Some(1_000_000_000), + to: Some(TxKind::Create), + input: TransactionInput::new(Bytes::from_static(&[0x00])), + ..Default::default() + }; + let deploy = TransactionTestContext::sign_tx(wallet.inner, deploy).await; + node.rpc.inject_tx(deploy.encoded_2718().into()).await?; + let payload = node.advance_block().await?; + let block = payload.block(); + + // The fixture must be what the assertions below assume: a refunded deployment, then the 0x7d. + let transactions = &block.body().transactions; + assert_eq!(transactions.len(), 2, "deployment and post-exec tx, got {transactions:?}"); + let OpTransactionSigned::PostExec(post_exec) = &transactions[1] else { + panic!("block must end in a post-exec tx, got {:?}", transactions[1]); + }; + assert_eq!( + post_exec.inner().payload.gas_refund_entries, + vec![SDMGasEntry { index: 0, gas_refund: 1 }], + ); + let tx_hash = transactions[0].tx_hash(); + let canonical_gas = node + .inner + .provider + .receipt_by_hash(tx_hash)? + .expect("deployment receipt") + .cumulative_gas_used(); + // Pins the settlement itself: every check below compares a replay with what the node committed. + assert_eq!(canonical_gas, DEPLOY_GAS - 1, "receipt holds canonical gas"); + let state = node.inner.provider.state_by_block_hash(block.hash())?; + let committed_balance = |address| -> eyre::Result { + Ok(state.account_balance(&address)?.unwrap_or_default()) + }; + + // debug_traceTransaction: canonical gas and a settled prestate diff. + let trace = + DebugApiClient::::debug_trace_transaction(&client, tx_hash, None) + .await?; + let GethTrace::Default(frame) = trace else { panic!("unexpected trace shape: {trace:?}") }; + assert_eq!(frame.gas, canonical_gas, "debug_traceTransaction gas"); + + let trace = DebugApiClient::::debug_trace_transaction( + &client, + tx_hash, + Some(prestate_tracer(PreStateConfig { diff_mode: Some(true), ..Default::default() })), + ) + .await?; + let GethTrace::PreStateTracer(PreStateFrame::Diff(diff)) = trace else { + panic!("unexpected trace shape: {trace:?}") + }; + // Sender, block beneficiary and base-fee vault all change, and each must land on the committed + // balance; the 0x7d tx after the deployment leaves state untouched. + assert_eq!( + diff.post[&sender].balance, + Some(committed_balance(sender)?), + "prestate diff balance of the sender", + ); + for (address, account) in &diff.post { + if let Some(balance) = account.balance { + assert_eq!(balance, committed_balance(*address)?, "prestate diff balance of {address}"); + } + } + + // debug_traceCall after the deployment: the replayed prefix (shared with eth_callMany and + // debug_traceCallMany) must leave the sender with its settled balance. + let trace = DebugApiClient::::debug_trace_call( + &client, + TransactionRequest::default().from(sender).to(Address::with_last_byte(1)), + Some(block.hash().into()), + Some(GethDebugTracingCallOptions { + tracing_options: prestate_tracer(PreStateConfig::default()), + tx_index: Some(1), + ..Default::default() + }), + ) + .await?; + let GethTrace::PreStateTracer(PreStateFrame::Default(prestate)) = trace else { + panic!("unexpected trace shape: {trace:?}") + }; + assert_eq!( + prestate.0[&sender].balance, + Some(committed_balance(sender)?), + "debug_traceCall prestate after the deployment", + ); + + // trace_replayTransaction: a settled state diff. + let state_diff = HashSet::from_iter([TraceType::StateDiff]); + let results = + TraceApiClient::::replay_transaction(&client, tx_hash, state_diff) + .await?; + assert_state_diff_settled(results.state_diff.as_ref(), sender, &committed_balance)?; + + Ok(()) +} + +/// Returns a test node config serving every RPC module over HTTP on unused ports. +fn rpc_node_config(chain_spec: &Arc) -> NodeConfig { + let mut network_args = NetworkArgs::default().with_unused_ports(); + network_args.discovery.discv5_port = Some(0); + network_args.discovery.discv5_port_ipv6 = Some(0); + NodeConfig::test().map_chain(chain_spec.clone()).with_network(network_args).with_rpc( + RpcServerArgs::default() + .with_unused_ports() + .with_http() + // `debug_*` is not part of the default HTTP module selection. + .with_http_api(RpcModuleSelection::All), + ) +} + +/// Returns tracing options selecting the prestate tracer with the given config. +fn prestate_tracer(config: PreStateConfig) -> GethDebugTracingOptions { + GethDebugTracingOptions::default() + .with_tracer(GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::PreStateTracer)) + .with_config(GethDebugTracerConfig::from(config)) +} + +/// Asserts that the sender's balance changes and that every balance a parity state diff ends on is +/// the committed one. +fn assert_state_diff_settled( + state_diff: Option<&StateDiff>, + sender: Address, + committed_balance: &impl Fn(Address) -> eyre::Result, +) -> eyre::Result<()> { + let state_diff = state_diff.expect("state diff requested"); + assert!( + matches!(state_diff[&sender].balance, Delta::Changed(_)), + "sender balance must change: {:?}", + state_diff[&sender], + ); + for (address, account) in state_diff.iter() { + let to = match &account.balance { + Delta::Unchanged => continue, + Delta::Added(to) => to, + Delta::Changed(changed) => &changed.to, + Delta::Removed(_) => panic!("{address} must not be removed"), + }; + assert_eq!(*to, committed_balance(*address)?, "state diff balance of {address}"); + } + Ok(()) +} diff --git a/rust/op-reth/crates/node/tests/it/invalid_post_exec.rs b/rust/op-reth/crates/node/tests/it/invalid_post_exec.rs index d0db3438858..9b796859947 100644 --- a/rust/op-reth/crates/node/tests/it/invalid_post_exec.rs +++ b/rust/op-reth/crates/node/tests/it/invalid_post_exec.rs @@ -6,20 +6,14 @@ //! [SDM-M1]: https://github.com/ethereum-optimism/protocol-team/issues/371 use alloy_consensus::{Sealable, proofs::calculate_transaction_root}; -use alloy_genesis::Genesis; -use alloy_primitives::B64; use alloy_rpc_types_engine::{PayloadStatus, PayloadStatusEnum, PayloadValidationError}; -use op_alloy_consensus::{ - PostExecPayloadValidationError, SDMGasEntry, build_post_exec_tx, encode_jovian_extra_data, -}; +use op_alloy_consensus::{PostExecPayloadValidationError, SDMGasEntry, build_post_exec_tx}; use op_alloy_rpc_types_engine::{OpExecutionData, OpExecutionPayload}; -use reth_chainspec::BaseFeeParams; use reth_e2e_test_utils::{NodeHelperType, setup_engine_with_connection, wallet::Wallet}; -use reth_optimism_chainspec::OpChainSpecBuilder; use reth_optimism_node::{ OpBuiltPayload, OpNode, payload::OpExecData, - utils::{advance_chain, optimism_payload_attributes, setup}, + utils::{advance_chain, setup}, }; use reth_optimism_primitives::OpTransactionSigned; use std::sync::Arc; @@ -27,24 +21,12 @@ use tokio::sync::Mutex; /// Creates Lagoon-active nodes without changing the shared Ecotone fixture. async fn setup_lagoon(num_nodes: usize) -> eyre::Result<(Vec>, Wallet)> { - let mut genesis: Genesis = serde_json::from_str(include_str!("../assets/genesis.json"))?; - // Lagoon is active at genesis, so the first child's base fee uses Jovian extra data. - genesis.extra_data = encode_jovian_extra_data(B64::ZERO, BaseFeeParams::optimism(), 0)?; - genesis.base_fee_per_gas = Some(1_000_000_000); - let chain_spec = Arc::new( - OpChainSpecBuilder::optimism_sepolia().genesis(genesis).lagoon_activated().build(), - ); setup_engine_with_connection( num_nodes, - chain_spec, + crate::lagoon::chain_spec()?, false, Default::default(), - |timestamp| { - let mut attributes = optimism_payload_attributes(timestamp); - attributes.0.eip_1559_params = Some(B64::ZERO); - attributes.0.min_base_fee = Some(0); - attributes - }, + crate::lagoon::payload_attributes, // The buffered-child test must learn the parent only through its explicit newPayload. false, ) diff --git a/rust/op-reth/crates/node/tests/it/lagoon.rs b/rust/op-reth/crates/node/tests/it/lagoon.rs new file mode 100644 index 00000000000..b25fb3097e1 --- /dev/null +++ b/rust/op-reth/crates/node/tests/it/lagoon.rs @@ -0,0 +1,27 @@ +//! Lagoon-at-genesis fixtures shared by the SDM integration tests. + +use alloy_genesis::Genesis; +use alloy_primitives::B64; +use op_alloy_consensus::encode_jovian_extra_data; +use reth_chainspec::BaseFeeParams; +use reth_optimism_chainspec::{OpChainSpec, OpChainSpecBuilder}; +use reth_optimism_node::utils::optimism_payload_attributes; +use reth_optimism_payload_builder::OpPayloadAttrs; +use std::sync::Arc; + +/// Builds a Lagoon-at-genesis spec that funds the e2e test wallet. +pub(crate) fn chain_spec() -> eyre::Result> { + let mut genesis: Genesis = serde_json::from_str(include_str!("../assets/genesis.json"))?; + // Lagoon is active at genesis, so the first child's base fee uses Jovian extra data. + genesis.extra_data = encode_jovian_extra_data(B64::ZERO, BaseFeeParams::optimism(), 0)?; + genesis.base_fee_per_gas = Some(1_000_000_000); + Ok(Arc::new(OpChainSpecBuilder::optimism_sepolia().genesis(genesis).lagoon_activated().build())) +} + +/// Payload attributes carrying the Jovian fields a Lagoon block requires. +pub(crate) const fn payload_attributes(timestamp: u64) -> OpPayloadAttrs { + let mut attributes = optimism_payload_attributes(timestamp); + attributes.0.eip_1559_params = Some(B64::ZERO); + attributes.0.min_base_fee = Some(0); + attributes +} diff --git a/rust/op-reth/crates/node/tests/it/main.rs b/rust/op-reth/crates/node/tests/it/main.rs index c849c74e424..cc7f4bab3f0 100644 --- a/rust/op-reth/crates/node/tests/it/main.rs +++ b/rust/op-reth/crates/node/tests/it/main.rs @@ -16,6 +16,8 @@ mod debug_trace_post_exec; mod invalid_post_exec; +mod lagoon; + mod estimate_gas_7825; mod p2p_version; diff --git a/rust/op-reth/crates/rpc/Cargo.toml b/rust/op-reth/crates/rpc/Cargo.toml index 6b853be110b..a2379bb8204 100644 --- a/rust/op-reth/crates/rpc/Cargo.toml +++ b/rust/op-reth/crates/rpc/Cargo.toml @@ -46,6 +46,7 @@ reth-optimism-forks.workspace = true reth-optimism-trie.workspace = true # ethereum +alloy-eip7928.workspace = true alloy-eips.workspace = true alloy-hardforks.workspace = true alloy-json-rpc.workspace = true diff --git a/rust/op-reth/crates/rpc/src/eth/call.rs b/rust/op-reth/crates/rpc/src/eth/call.rs index 258b02b8b5f..323c0c9e158 100644 --- a/rust/op-reth/crates/rpc/src/eth/call.rs +++ b/rust/op-reth/crates/rpc/src/eth/call.rs @@ -1,8 +1,21 @@ use crate::{OpEthApi, OpEthApiError, eth::RpcNodeCore}; +use alloy_consensus::{BlockHeader, transaction::TxHashRef}; +use alloy_primitives::B256; +use alloy_rpc_types_eth::TransactionInfo; +use reth_errors::RethError; +use reth_evm::{ + ConfigureEvm, HaltReasonFor, + block::{BlockExecutor, TxResult}, +}; +use reth_revm::{State, database::StateProviderDatabase}; use reth_rpc_eth_api::{ - FromEvmError, RpcConvert, - helpers::{Call, EthCall, estimate::EstimateCall}, + FromEthApiError, FromEvmError, RpcConvert, + helpers::{ + Call, EthCall, LoadBlock, LoadState, LoadTransaction, SpawnBlocking, estimate::EstimateCall, + }, }; +use reth_rpc_eth_types::StateCacheDb; +use revm::context_interface::result::ResultAndState; impl EthCall for OpEthApi where @@ -20,6 +33,10 @@ where { } +/// UPSTREAM-MIRROR(override): reth@rev:8d359d0 `reth_rpc_eth_api::helpers::Call` +/// +/// `spawn_replay_transaction` executes the target through the block executor, see +/// [`crate::eth::trace`]. impl Call for OpEthApi where N: RpcNodeCore, @@ -45,4 +62,55 @@ where fn evm_memory_limit(&self) -> u64 { self.inner.eth_api.evm_memory_limit() } + + async fn spawn_replay_transaction( + &self, + hash: B256, + f: F, + ) -> Result, Self::Error> + where + Self: LoadBlock + LoadTransaction, + F: FnOnce( + TransactionInfo, + ResultAndState>, + StateCacheDb, + ) -> Result + + Send + + 'static, + R: Send + 'static, + { + let Some((transaction, block)) = self.transaction_and_block(hash).await? else { + return Ok(None); + }; + let (tx, tx_info) = transaction.split(); + + // `Call::spawn_with_state_at_block`, inlined: calling it here would need this impl's + // own `Call` bounds, which the compiler can't prove inside it. + let parent_hash = block.parent_hash(); + self.spawn_blocking_io_fut(async move |this| { + let state = this.state_at_block_id(parent_hash.into()).await?; + let mut db = State::builder().with_database(StateProviderDatabase::new(state)).build(); + 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)?; + + for block_tx in block.transactions_recovered() { + if block_tx.tx_hash() == tx.tx_hash() { + break; + } + executor.execute_transaction(block_tx).map_err(Self::Error::from_eth_err)?; + } + + let res = executor + .execute_transaction_without_commit(tx) + .map_err(Self::Error::from_eth_err)? + .into_result(); + drop(executor); + f(tx_info, res, db) + }) + .await + .map(Some) + } } diff --git a/rust/op-reth/crates/rpc/src/eth/mod.rs b/rust/op-reth/crates/rpc/src/eth/mod.rs index 10454035b7e..a201abc327a 100644 --- a/rust/op-reth/crates/rpc/src/eth/mod.rs +++ b/rust/op-reth/crates/rpc/src/eth/mod.rs @@ -8,6 +8,7 @@ pub mod transaction; mod block; mod call; mod pending_block; +mod trace; use crate::{ OpEthApiError, SequencerClient, @@ -39,7 +40,7 @@ use reth_rpc_eth_api::{ RpcNodeCoreExt, RpcTypes, helpers::{ EthApiSpec, EthFees, EthState, EthSubscriptions, LoadFee, LoadPendingBlock, LoadState, - SpawnBlocking, Trace, bal::GetBlockAccessList, pending_block::BuildPendingEnv, + SpawnBlocking, bal::GetBlockAccessList, pending_block::BuildPendingEnv, }, }; use reth_rpc_eth_types::{ @@ -432,14 +433,6 @@ where { } -impl Trace for OpEthApi -where - N: RpcNodeCore, - OpEthApiError: FromEvmError, - Rpc: RpcConvert, -{ -} - // Upstream's `FullEthApi` requires this helper trait even when its RPC methods are not served. // op-reth explicitly removes the untested BAL endpoints in `op-reth/crates/node/src/node.rs`. impl GetBlockAccessList for OpEthApi diff --git a/rust/op-reth/crates/rpc/src/eth/trace.rs b/rust/op-reth/crates/rpc/src/eth/trace.rs new file mode 100644 index 00000000000..3ea0562bc87 --- /dev/null +++ b/rust/op-reth/crates/rpc/src/eth/trace.rs @@ -0,0 +1,96 @@ +//! Replays of a block's own transactions for the `debug_` and `trace_` namespaces. +//! +//! SDM settlement (canonical gas, the sender's refund and the fee vaults' debits) is applied by the +//! block executor, keyed by each transaction's position in the block, so a replay on the bare EVM +//! reports pre-refund gas and unsettled balances. These overrides replay through the executor. +//! +//! op-reth never caches a block access list (`ensure_no_computed_bals` rejects the options that +//! would), so the BAL argument upstream uses to skip the replay is always `None` here. + +use crate::{OpEthApi, OpEthApiError}; +use alloy_eip7928::bal::DecodedBal; +use reth_errors::RethError; +use reth_evm::{ + ConfigureEvm, Evm, EvmEnvFor, HaltReasonFor, InspectorFor, IntoTxEnv, TxEnvFor, + block::{BlockExecutor, TxResult}, +}; +use reth_primitives_traits::{BlockBody, BlockTy, RecoveredBlock}; +use reth_rpc_eth_api::{ + FromEthApiError, FromEvmError, RpcConvert, RpcNodeCore, + helpers::{LoadState, Trace}, +}; +use reth_rpc_eth_types::{EthApiError, StateCacheDb}; +use revm::{context_interface::result::ResultAndState, state::bal::Bal as RevmBal}; +use std::sync::Arc; + +/// UPSTREAM-MIRROR(override): reth@rev:8d359d0 `reth_rpc_eth_api::helpers::Trace` +/// +/// Replays through the block executor where upstream replays on the bare EVM. +impl Trace for OpEthApi +where + N: RpcNodeCore, + OpEthApiError: FromEvmError, + Rpc: RpcConvert, +{ + fn replay_block_until( + &self, + db: &mut StateCacheDb, + block: &RecoveredBlock>, + target_tx_index: usize, + _bal: Option<&DecodedBal>>, + ) -> Result<(), 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)?; + + for tx in block.transactions_recovered().take(target_tx_index) { + executor.execute_transaction(tx).map_err(Self::Error::from_eth_err)?; + } + Ok(()) + } + + /// Executes the block's transaction at the target index, not `target_tx_env`: the executor + /// derives the refund from the transaction it runs and its position. + fn inspect_transaction_in_block<'a>( + &self, + block: &RecoveredBlock>, + 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 evm_env = self.evm_env_for_header(block.sealed_block().sealed_header())?; + 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.clone(), inspector); + // The transactions before the target replay uninspected. + 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)?; + + let mut block_txs = block.transactions_recovered(); + for tx in block_txs.by_ref().take(target_tx_index) { + executor.execute_transaction(tx).map_err(Self::Error::from_eth_err)?; + } + let target_tx = block_txs.next().ok_or_else(|| { + Self::Error::from_eth_err(EthApiError::InvalidParams(format!( + "tx_index {target_tx_index} out of bounds for block with {} transactions", + block.body().transaction_count() + ))) + })?; + + 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)) + } +}