Skip to main content

reth_rpc_eth_types/
simulate.rs

1//! Utilities for serving `eth_simulateV1`
2
3use crate::{
4    error::{api::FromEthApiError, FromEvmError, ToRpcError},
5    EthApiError,
6};
7use alloy_chains::Chain;
8use alloy_consensus::{transaction::TxHashRef, BlockHeader, Transaction as _};
9use alloy_eips::eip2718::WithEncoded;
10use alloy_network::{NetworkTransactionBuilder, TransactionBuilder};
11use alloy_primitives::{keccak256, map::AddressMap, Address, Bytes, TxKind, U256};
12use alloy_rpc_types_eth::{
13    simulate::{SimBlock, SimCallResult, SimulateError, SimulatedBlock},
14    state::StateOverride,
15    BlockId, BlockOverrides, BlockTransactionsKind,
16};
17use evm2::{interpreter::InstrStop, precompiles::MovePrecompileError, EvmFeatures, TxResult};
18use evm2_inspectors::transfer::TransferInspector;
19use jsonrpsee_types::{error::INTERNAL_ERROR_CODE, ErrorObject};
20use reth_errors::ProviderResult;
21use reth_evm::{
22    execute::{BlockBuilder, BlockBuilderOutcome, BlockTransactionResult},
23    BlockExecutionError, BundleState, Database, DynDatabase, Evm as RethEvm, EvmEnv,
24};
25use reth_primitives_traits::{
26    BlockBody as _, BlockTy, NodePrimitives, Recovered, RecoveredBlock, SealedHeader,
27};
28use reth_rpc_convert::{RpcBlock, RpcConvert, RpcTxReq};
29use reth_rpc_server_types::result::rpc_err;
30use reth_storage_api::{noop::NoopProvider, HashedPostStateProvider, StateProvider};
31use reth_tasks::cancel::is_cancelled;
32use reth_trie_common::{HashedPostState, KeccakKeyHasher};
33use std::mem;
34
35/// Fallback seconds added between simulated block timestamps when neither the user nor the chain
36/// hint provides a value.
37const SIMULATE_FALLBACK_TIMESTAMP_INCREMENT: u64 = 12;
38
39/// Maximum length of a block's withdrawals override in the execution-apis withdrawals schema.
40const MAX_WITHDRAWALS_PER_PAYLOAD: usize = 16;
41
42/// Error code for execution reverted in `eth_simulateV1`.
43///
44/// Consistent with `eth_call` revert error code.
45///
46/// <https://github.com/ethereum/execution-apis/pull/748>
47pub const SIMULATE_REVERT_CODE: i32 = 3;
48
49/// Error code for VM execution errors (e.g., out of gas) in `eth_simulateV1`.
50///
51/// <https://github.com/ethereum/execution-apis>
52pub const SIMULATE_VM_ERROR_CODE: i32 = -32015;
53
54/// Errors which may occur during `eth_simulateV1` execution.
55#[derive(Debug, thiserror::Error)]
56pub enum EthSimulateError {
57    /// Total gas limit of transactions for the block exceeds the block gas limit.
58    #[error("Block gas limit exceeded by the block's transactions")]
59    BlockGasLimitExceeded,
60    /// Number of simulated blocks exceeds the configured client limit.
61    #[error("too many blocks")]
62    TooManyBlocks,
63    /// Max gas limit for entire operation exceeded.
64    #[error("Client adjustable limit reached")]
65    GasLimitReached,
66    /// Base block for the simulation was not found.
67    #[error("block not found: {block}")]
68    BlockNotFound {
69        /// The block id that was requested.
70        block: BlockId,
71    },
72    /// Block number in sequence did not increase.
73    #[error("block numbers must be in order: {got} <= {parent}")]
74    BlockNumberInvalid {
75        /// The block number that was provided.
76        got: u64,
77        /// The parent block number.
78        parent: u64,
79    },
80    /// Block timestamp in sequence did not increase.
81    #[error("block timestamps must be in order: {got} <= {parent}")]
82    BlockTimestampInvalid {
83        /// The block timestamp that was provided.
84        got: u64,
85        /// The parent block timestamp.
86        parent: u64,
87    },
88    /// Transaction nonce is too low.
89    #[error("nonce too low: next nonce {state}, tx nonce {tx}")]
90    NonceTooLow {
91        /// Transaction nonce.
92        tx: u64,
93        /// Current state nonce.
94        state: u64,
95    },
96    /// Transaction nonce is too high.
97    #[error("nonce too high")]
98    NonceTooHigh,
99    /// Transaction nonce cannot be incremented.
100    #[error("nonce has max value")]
101    NonceMaxValue,
102    /// Transaction's baseFeePerGas is too low.
103    #[error("max fee per gas less than block base fee")]
104    BaseFeePerGasTooLow,
105    /// Not enough gas provided to pay for intrinsic gas.
106    #[error("intrinsic gas too low")]
107    IntrinsicGasTooLow,
108    /// Insufficient funds to pay for gas fees and value.
109    #[error("insufficient funds for gas * price + value: have {balance} want {cost}")]
110    InsufficientFunds {
111        /// Transaction cost.
112        cost: U256,
113        /// Sender balance.
114        balance: U256,
115    },
116    /// Sender is not an EOA.
117    #[error("sender is not an EOA")]
118    SenderNotEOA,
119    /// Max init code size exceeded.
120    #[error("max initcode size exceeded")]
121    MaxInitCodeSizeExceeded,
122    /// Attempted to move a non-precompile address.
123    #[error("account {0} is not a precompile")]
124    NotAPrecompile(Address),
125    /// Attempted to move a precompile to its own address.
126    #[error("cannot move precompile {0} to itself")]
127    MovePrecompileToSelf(Address),
128}
129
130impl EthSimulateError {
131    /// Returns the JSON-RPC error code for a `eth_simulateV1` error.
132    pub const fn error_code(&self) -> i32 {
133        match self {
134            Self::NonceTooLow { .. } => -38010,
135            Self::NonceTooHigh => -38011,
136            Self::NonceMaxValue => INTERNAL_ERROR_CODE,
137            Self::BaseFeePerGasTooLow => -38012,
138            Self::IntrinsicGasTooLow => -38013,
139            Self::InsufficientFunds { .. } => -38014,
140            Self::BlockGasLimitExceeded => -38015,
141            Self::BlockNumberInvalid { .. } => -38020,
142            Self::BlockTimestampInvalid { .. } => -38021,
143            Self::SenderNotEOA => -38024,
144            Self::MaxInitCodeSizeExceeded => -38025,
145            Self::TooManyBlocks | Self::GasLimitReached => -38026,
146            Self::MovePrecompileToSelf(_) => -38022,
147            Self::BlockNotFound { .. } | Self::NotAPrecompile(_) => -32000,
148        }
149    }
150}
151
152impl ToRpcError for EthSimulateError {
153    fn to_rpc_error(&self) -> ErrorObject<'static> {
154        rpc_err(self.error_code(), self.to_string(), None)
155    }
156}
157
158/// Sanitizes and gap-fills the chain of [`SimBlock`]s for `eth_simulateV1`.
159///
160/// Walks the provided block-state calls in order and:
161/// - validates that each block number and timestamp strictly increases relative to the parent and
162///   prior simulated block;
163/// - rejects withdrawals overrides longer than the per-block limit;
164/// - rejects base fee overrides above `u64::MAX`, which a block header cannot hold;
165/// - inserts empty filler blocks for every gap in block numbers, so a request like `[block at
166///   number N + k]` over a parent at `N` expands to `k - 1` empty blocks followed by the requested
167///   one (per the execution-apis spec: "If the block number is increased more than `1` compared to
168///   the previous block, new empty blocks are generated in between.");
169/// - assigns default block numbers (`prev_number + 1`) and timestamps (`prev_timestamp + chain
170///   block time`) when missing, so every returned entry has explicit `number` and `time` overrides.
171///   The block time defaults to [`Chain::average_blocktime_hint`] for the chain id, falling back to
172///   `SIMULATE_FALLBACK_TIMESTAMP_INCREMENT` when no hint is registered. Sub-second chain hints are
173///   rounded up because block timestamps are second-granular;
174/// - enforces the global `max_simulate_blocks` cap on the total number of blocks (including
175///   generated fillers).
176pub fn sanitize_chain<TxReq, H>(
177    blocks: Vec<SimBlock<TxReq>>,
178    parent: &SealedHeader<H>,
179    chain_id: u64,
180    max_simulate_blocks: u64,
181) -> Result<Vec<SimBlock<TxReq>>, EthApiError>
182where
183    H: BlockHeader,
184{
185    let timestamp_increment = Chain::from(chain_id)
186        .average_blocktime_hint()
187        .map(|d| d.as_secs().saturating_add(u64::from(d.subsec_nanos() > 0)))
188        .filter(|&s| s > 0)
189        .unwrap_or(SIMULATE_FALLBACK_TIMESTAMP_INCREMENT);
190
191    let mut out = Vec::with_capacity(blocks.len());
192    let base_number = parent.number();
193    let mut prev_number = base_number;
194    let mut prev_timestamp = parent.timestamp();
195
196    for mut block in blocks {
197        let overrides = block.block_overrides.get_or_insert_with(BlockOverrides::default);
198
199        if let Some(withdrawals) = &overrides.withdrawals &&
200            withdrawals.len() > MAX_WITHDRAWALS_PER_PAYLOAD
201        {
202            return Err(EthApiError::InvalidParams(format!(
203                "withdrawals count {} exceeds limit {MAX_WITHDRAWALS_PER_PAYLOAD}",
204                withdrawals.len()
205            )))
206        }
207
208        // The block header stores the base fee as `u64`, so a larger override is rejected instead
209        // of being clamped.
210        if overrides.base_fee.is_some_and(|base_fee| base_fee > U256::from(u64::MAX)) {
211            return Err(EthApiError::InvalidParams(
212                "baseFeePerGas override exceeds u64::MAX".to_string(),
213            ))
214        }
215
216        // Default block number to prev + 1 if not specified.
217        let target_number = if let Some(n) = overrides.number {
218            u64::try_from(n).unwrap_or(u64::MAX)
219        } else {
220            let n = prev_number.saturating_add(1);
221            overrides.number = Some(U256::from(n));
222            n
223        };
224
225        if target_number <= prev_number {
226            return Err(EthApiError::other(EthSimulateError::BlockNumberInvalid {
227                got: target_number,
228                parent: prev_number,
229            }));
230        }
231
232        if target_number.saturating_sub(base_number) > max_simulate_blocks {
233            return Err(EthApiError::other(EthSimulateError::TooManyBlocks));
234        }
235
236        // Insert empty filler blocks for any gap between prev_number and target_number.
237        let gap = target_number - prev_number;
238        if gap > 1 {
239            for i in 1..gap {
240                let filler_number = prev_number + i;
241                let filler_time =
242                    prev_timestamp.checked_add(timestamp_increment).ok_or_else(|| {
243                        EthApiError::other(EthSimulateError::BlockTimestampInvalid {
244                            got: prev_timestamp,
245                            parent: prev_timestamp,
246                        })
247                    })?;
248                out.push(SimBlock {
249                    block_overrides: Some(BlockOverrides {
250                        number: Some(U256::from(filler_number)),
251                        time: Some(filler_time),
252                        ..Default::default()
253                    }),
254                    state_overrides: None,
255                    calls: Vec::new(),
256                });
257                prev_timestamp = filler_time;
258            }
259        }
260
261        prev_number = target_number;
262        // Default timestamp to prev + increment if not specified, otherwise validate ordering.
263        let block_time = if let Some(t) = overrides.time {
264            if t <= prev_timestamp {
265                return Err(EthApiError::other(EthSimulateError::BlockTimestampInvalid {
266                    got: t,
267                    parent: prev_timestamp,
268                }));
269            }
270            t
271        } else {
272            let t = prev_timestamp.checked_add(timestamp_increment).ok_or_else(|| {
273                EthApiError::other(EthSimulateError::BlockTimestampInvalid {
274                    got: prev_timestamp,
275                    parent: prev_timestamp,
276                })
277            })?;
278            overrides.time = Some(t);
279            t
280        };
281        prev_timestamp = block_time;
282
283        out.push(block);
284    }
285
286    Ok(out)
287}
288
289/// Applies precompile move overrides from state overrides to the EVM's precompiles map.
290///
291/// This function processes `movePrecompileToAddress` entries from the state overrides and
292/// moves precompiles from their original addresses to new addresses. The original address
293/// is cleared (precompile removed) and the precompile is installed at the destination address.
294pub fn apply_precompile_overrides(
295    state_overrides: &StateOverride,
296    evm: &mut impl RethEvm,
297) -> Result<(), EthSimulateError> {
298    let mut moves: Vec<_> = state_overrides
299        .iter()
300        .filter_map(|(source, account_override)| {
301            account_override.move_precompile_to.map(|dest| (*source, dest))
302        })
303        .collect();
304    // `StateOverride` iterates in a randomly seeded order. Apply moves in ascending source order so
305    // the result is deterministic and the higher source wins at a shared destination.
306    moves.sort_unstable_by_key(|(source, _)| *source);
307    if moves.is_empty() {
308        return Ok(())
309    }
310
311    for (source, dest) in &moves {
312        if source == dest {
313            if !evm.has_precompile(source) {
314                return Err(EthSimulateError::NotAPrecompile(*source))
315            }
316            return Err(EthSimulateError::MovePrecompileToSelf(*source))
317        }
318    }
319
320    evm.move_precompiles(moves).map_err(|MovePrecompileError::NotAPrecompile(addr)| {
321        EthSimulateError::NotAPrecompile(addr)
322    })?;
323
324    Ok(())
325}
326
327/// Converts all [`TransactionRequest`]s into [`Recovered`] transactions and applies them to the
328/// given [`BlockBuilder`].
329///
330/// Returns all executed transactions and the result of the execution.
331///
332/// For each call without an explicit `gas` field, the remaining block gas is used as the default.
333/// The RPC gas cap is tracked as a request-wide remaining budget and caps each call before
334/// execution. This matches the spec rule `"gasLimit: blockGasLimit - soFarUsedGasInBlock"` and
335/// geth's per-call `sanitizeCall` behavior.
336///
337/// `call_nonce` returns the nonce for a call without one from the state before the call, or `None`
338/// to use the sender's account nonce.
339///
340/// [`TransactionRequest`]: alloy_rpc_types_eth::TransactionRequest
341#[expect(clippy::type_complexity, clippy::too_many_arguments)]
342pub fn execute_transactions<S, T, EvmTypes>(
343    mut builder: S,
344    state_provider: impl StateProvider,
345    calls: Vec<RpcTxReq<T::Network>>,
346    remaining_call_gas_limit: &mut Option<u64>,
347    chain_id: u64,
348    simulation_state: Option<&mut SimulatedState>,
349    converter: &T,
350    mut call_nonce: impl FnMut(
351        &RpcTxReq<T::Network>,
352        &mut dyn DynDatabase,
353    ) -> Result<Option<u64>, EthApiError>,
354) -> Result<(BlockBuilderOutcome<S::Primitives>, Vec<TxResult<EvmTypes>>), EthApiError>
355where
356    S: BlockBuilder<Executor: reth_evm::BlockExecutor<Evm: RethEvm<EvmTypes = EvmTypes>>>,
357    T: RpcConvert<Primitives = S::Primitives>,
358    EvmTypes: evm2::EvmTypes,
359{
360    if is_cancelled() {
361        return Err(EthApiError::InternalEthError)
362    }
363    builder.apply_pre_execution_changes()?;
364
365    let mut results = Vec::with_capacity(calls.len());
366    let mut cumulative_tx_gas_used: u64 = 0;
367    let mut block_regular_gas_used: u64 = 0;
368    let mut block_state_gas_used: u64 = 0;
369    let block_gas_limit = builder.evm_env().block_env().gas_limit.to::<u64>();
370    let is_amsterdam = builder.evm_env().version().feature(EvmFeatures::EIP8037);
371    let tx_gas_limit_cap = builder.evm_env().version().tx_gas_limit_cap;
372    for mut call in calls {
373        if is_cancelled() {
374            return Err(EthApiError::InternalEthError)
375        }
376        let block_gas_remaining = if is_amsterdam {
377            let regular_available_gas = block_gas_limit.saturating_sub(block_regular_gas_used);
378            let state_available_gas = block_gas_limit.saturating_sub(block_state_gas_used);
379            // Gas above the tx gas cap goes to the state gas reservoir and only needs state gas.
380            if regular_available_gas >= tx_gas_limit_cap {
381                state_available_gas
382            } else {
383                regular_available_gas.min(state_available_gas)
384            }
385        } else {
386            block_gas_limit.saturating_sub(cumulative_tx_gas_used)
387        };
388        let mut default_gas_limit = block_gas_remaining;
389
390        if let Some(gas_limit) = call.as_ref().gas_limit() &&
391            gas_limit > block_gas_remaining
392        {
393            return Err(EthApiError::other(EthSimulateError::BlockGasLimitExceeded))
394        }
395
396        if let Some(remaining_call_gas_limit) = *remaining_call_gas_limit {
397            if let Some(gas_limit) = call.as_ref().gas_limit() {
398                if gas_limit > remaining_call_gas_limit {
399                    call.as_mut().set_gas_limit(remaining_call_gas_limit);
400                }
401            } else {
402                default_gas_limit = default_gas_limit.min(remaining_call_gas_limit);
403            }
404        }
405
406        if call.as_ref().nonce().is_none() &&
407            let Some(nonce) = call_nonce(&call, builder.evm_mut().state_db_mut())?
408        {
409            call.as_mut().set_nonce(nonce);
410        }
411
412        // Resolve transaction, populate missing fields and enforce calls
413        // correctness.
414        let tx = resolve_transaction_with_evm(
415            call,
416            default_gas_limit,
417            builder.evm_env().block_base_fee(),
418            chain_id,
419            !builder.evm_env().version().feature(EvmFeatures::NONCE_CHECK),
420            builder.evm_mut(),
421            converter,
422        )?;
423        // Create transaction with an empty envelope.
424        // The effect for a layer-2 execution client is that it does not charge L1 cost.
425        let tx = WithEncoded::new(Default::default(), tx);
426
427        let mut tx_regular_gas_used = 0;
428        let gas_output = builder.execute_transaction_with_result_closure(tx, |output| {
429            let output = &output.result().result;
430            tx_regular_gas_used = output.execution_gas_spent();
431            results.push(output.clone())
432        })?;
433
434        // The transfer tracer keeps the transaction's logs, with the synthetic transfer logs
435        // among them, outside the EVM's own logs.
436        // SAFETY: `TransferInspector` has no lifetime parameters.
437        if let Some(logs) = unsafe {
438            builder
439                .evm_mut()
440                .with_inspector(|inspector: &mut TransferInspector| inspector.take_logs())
441        } && let Some(result) = results.last_mut()
442        {
443            result.logs = logs;
444        }
445
446        let gas_used = gas_output.tx_gas_used();
447        if let Some(remaining_call_gas_limit) = remaining_call_gas_limit.as_mut() {
448            if gas_used > *remaining_call_gas_limit {
449                return Err(EthApiError::other(EthSimulateError::GasLimitReached))
450            }
451            *remaining_call_gas_limit -= gas_used;
452        }
453
454        cumulative_tx_gas_used = cumulative_tx_gas_used.saturating_add(gas_used);
455        block_regular_gas_used = block_regular_gas_used.saturating_add(tx_regular_gas_used);
456        block_state_gas_used = block_state_gas_used.saturating_add(gas_output.state_gas_used());
457    }
458
459    let result = if let Some(simulation_state) = simulation_state {
460        builder.finish_with_state_root(&state_provider, |output| {
461            simulation_state
462                .extend(&state_provider, &output.state)
463                .map_err(BlockExecutionError::other)?;
464            state_provider
465                .state_root_with_updates(simulation_state.hashed_state().clone())
466                .map(Some)
467                .map_err(BlockExecutionError::other)
468        })?
469    } else {
470        builder.finish(NoopProvider::default(), None)?
471    };
472
473    Ok((result, results))
474}
475
476/// Goes over the list of [`TransactionRequest`]s and populates missing fields trying to resolve
477/// them into primitive transactions.
478///
479/// This will set the defaults as defined in <https://github.com/ethereum/execution-apis/blob/e56d3208789259d0b09fa68e9d8594aa4d73c725/docs/ethsimulatev1-notes.md#default-values-for-transactions>
480///
481/// [`TransactionRequest`]: alloy_rpc_types_eth::TransactionRequest
482pub fn resolve_transaction<DB: Database, Tx, T>(
483    tx: RpcTxReq<T::Network>,
484    default_gas_limit: u64,
485    block_base_fee_per_gas: u64,
486    chain_id: u64,
487    disable_nonce_check: bool,
488    db: &mut DB,
489    converter: &T,
490) -> Result<Recovered<Tx>, EthApiError>
491where
492    DB::Error: Into<EthApiError>,
493    T: RpcConvert<Primitives: NodePrimitives<SignedTx = Tx>>,
494{
495    resolve_transaction_with_account(
496        tx,
497        default_gas_limit,
498        block_base_fee_per_gas,
499        chain_id,
500        disable_nonce_check,
501        |address| db.get_account(address).map_err(Into::into),
502        converter,
503    )
504}
505
506fn resolve_transaction_with_evm<Tx, T, E>(
507    tx: RpcTxReq<T::Network>,
508    default_gas_limit: u64,
509    block_base_fee_per_gas: u64,
510    chain_id: u64,
511    disable_nonce_check: bool,
512    evm: &mut E,
513    converter: &T,
514) -> Result<Recovered<Tx>, EthApiError>
515where
516    T: RpcConvert<Primitives: NodePrimitives<SignedTx = Tx>>,
517    E: RethEvm,
518{
519    resolve_transaction_with_account(
520        tx,
521        default_gas_limit,
522        block_base_fee_per_gas,
523        chain_id,
524        disable_nonce_check,
525        |address| evm.account_info(address).map_err(Into::into),
526        converter,
527    )
528}
529
530fn resolve_transaction_with_account<Tx, T, F>(
531    mut tx: RpcTxReq<T::Network>,
532    default_gas_limit: u64,
533    block_base_fee_per_gas: u64,
534    chain_id: u64,
535    disable_nonce_check: bool,
536    mut account: F,
537    converter: &T,
538) -> Result<Recovered<Tx>, EthApiError>
539where
540    T: RpcConvert<Primitives: NodePrimitives<SignedTx = Tx>>,
541    F: FnMut(&Address) -> Result<Option<evm2::evm::AccountInfo>, EthApiError>,
542{
543    if tx.as_ref().has_conflicting_fee_fields() {
544        return Err(EthApiError::ConflictingFeeFieldsInRequest)
545    }
546
547    // If we're missing any fields we try to fill nonce, gas and
548    // gas price.
549    let tx_type = tx.as_ref().output_tx_type();
550
551    let from = tx.as_ref().from().unwrap_or_else(|| {
552        tx.as_mut().set_from(Address::ZERO);
553        Address::ZERO
554    });
555
556    let state_nonce = account(&from)?.map(|acc| acc.nonce).unwrap_or_default();
557    if tx.as_ref().nonce().is_none() {
558        tx.as_mut().set_nonce(state_nonce);
559    }
560    // EIP-2681 applies in both modes. Check it here before checking the fee cap.
561    if state_nonce == u64::MAX && (disable_nonce_check || tx.as_ref().nonce() == Some(u64::MAX)) {
562        return Err(EthApiError::other(EthSimulateError::NonceMaxValue))
563    }
564    // The EVM rejects a tx nonce of u64::MAX even with the nonce check disabled. The state nonce is
565    // below the limit here, so only the tx object changes.
566    if disable_nonce_check && tx.as_ref().nonce() == Some(u64::MAX) {
567        tx.as_mut().set_nonce(0);
568    }
569
570    if tx.as_ref().gas_limit().is_none() {
571        tx.as_mut().set_gas_limit(default_gas_limit);
572    }
573
574    if tx.as_ref().chain_id().is_none() {
575        tx.as_mut().set_chain_id(chain_id);
576    }
577
578    if tx.as_ref().kind().is_none() {
579        tx.as_mut().set_kind(TxKind::Create);
580    }
581
582    // if we can't build the _entire_ transaction yet, fill the fee fields.
583    //
584    // Per the eth_simulateV1 spec, unspecified fee fields default to 0 (not the block base fee),
585    // matching geth's `CallDefaults` behavior. This lets simulation behave like a free-gas
586    // `eth_call` when validation is off, and surfaces "max fee per gas less than block base fee"
587    // errors when validation is on with a real base fee. `complete_4844` needs a sidecar and
588    // `maxFeePerBlobGas`, so a blob call missing either is never buildable and takes this branch.
589    // Simulate blob calls usually have no sidecar.
590    let _ = block_base_fee_per_gas;
591    if tx.as_ref().output_tx_type_checked().is_none() {
592        if tx_type.is_legacy() || tx_type.is_eip2930() {
593            if tx.as_ref().gas_price().is_none() {
594                tx.as_mut().set_gas_price(0);
595            }
596        } else {
597            // A `gasPrice` can only reach this branch in an EIP-4844 or EIP-7702 request, where it
598            // sets both fee caps.
599            let fee = tx.as_ref().gas_price().unwrap_or_default();
600            if tx.as_ref().max_fee_per_gas().is_none() {
601                tx.as_mut().set_max_fee_per_gas(fee);
602            }
603            if tx.as_ref().max_priority_fee_per_gas().is_none() {
604                tx.as_mut().set_max_priority_fee_per_gas(fee);
605            }
606            if tx_type.is_eip4844() {
607                tx.as_mut().max_fee_per_blob_gas.get_or_insert(0);
608            }
609        }
610    }
611
612    let tx =
613        converter.build_simulate_v1_transaction(tx).map_err(|e| EthApiError::other(e.into()))?;
614
615    Ok(Recovered::new_unchecked(tx, from))
616}
617
618/// Handles outputs of the calls execution and builds a [`SimulatedBlock`].
619pub fn build_simulated_block<Err, T, EvmTypes>(
620    block: RecoveredBlock<BlockTy<T::Primitives>>,
621    results: Vec<TxResult<EvmTypes>>,
622    txs_kind: BlockTransactionsKind,
623    converter: &T,
624) -> Result<SimulatedBlock<RpcBlock<T::Network>>, Err>
625where
626    Err: std::error::Error
627        + FromEthApiError
628        + FromEvmError<T::Evm>
629        + From<T::Error>
630        + Into<jsonrpsee_types::ErrorObject<'static>>,
631    T: RpcConvert,
632    EvmTypes: evm2::EvmTypes,
633{
634    let mut calls: Vec<SimCallResult> = Vec::with_capacity(results.len());
635
636    let mut log_index = 0;
637    for (index, (result, tx)) in results.into_iter().zip(block.body().transactions()).enumerate() {
638        let gas_used = result.tx_gas_used();
639        let max_used_gas = Some(result.total_gas_spent.max(result.floor_gas));
640        let call = if result.status {
641            SimCallResult {
642                return_data: result.output,
643                error: None,
644                gas_used,
645                max_used_gas,
646                logs: result
647                    .logs
648                    .into_iter()
649                    .map(|log| {
650                        log_index += 1;
651                        alloy_rpc_types_eth::Log {
652                            inner: log,
653                            log_index: Some(log_index - 1),
654                            transaction_index: Some(index as u64),
655                            transaction_hash: Some(*tx.tx_hash()),
656                            block_hash: Some(block.hash()),
657                            block_number: Some(block.header().number()),
658                            block_timestamp: Some(block.header().timestamp()),
659                            ..Default::default()
660                        }
661                    })
662                    .collect(),
663                status: true,
664            }
665        } else if result.stop == InstrStop::Revert {
666            let error = Err::from_revert(result.output.clone());
667            SimCallResult {
668                return_data: Bytes::new(),
669                error: Some(SimulateError {
670                    message: error.to_string(),
671                    code: SIMULATE_REVERT_CODE,
672                    data: Some(result.output),
673                }),
674                gas_used,
675                max_used_gas,
676                status: false,
677                logs: Vec::new(),
678            }
679        } else {
680            let error = Err::from_evm_halt(result.stop, tx.gas_limit());
681            SimCallResult {
682                return_data: Bytes::new(),
683                error: Some(SimulateError {
684                    message: error.to_string(),
685                    code: SIMULATE_VM_ERROR_CODE,
686                    ..SimulateError::invalid_params()
687                }),
688                gas_used,
689                max_used_gas,
690                logs: Vec::new(),
691                status: false,
692            }
693        };
694
695        calls.push(call);
696    }
697
698    let block = block.into_rpc_block(
699        txs_kind,
700        |tx, tx_info| converter.fill(tx, tx_info),
701        |header, block_size| converter.convert_header(header, Some(block_size)),
702    )?;
703    Ok(SimulatedBlock { inner: block, calls })
704}
705
706/// The hashed post-state accumulated across simulated blocks, relative to the parent state.
707///
708/// Each block's changes are hashed once when they are added. Re-hashing a cumulative
709/// [`BundleState`] instead would read the parent storage of every destroyed account again for
710/// every block.
711#[derive(Debug, Default)]
712pub struct SimulatedState {
713    hashed: HashedPostState,
714    /// Whether the parent storage of an account still has to be zeroed in `hashed`, by the
715    /// account's first appearance in the changes.
716    parent_storage_unzeroed: AddressMap<bool>,
717}
718
719impl SimulatedState {
720    /// Returns the accumulated hashed post-state.
721    pub const fn hashed_state(&self) -> &HashedPostState {
722        &self.hashed
723    }
724
725    /// Adds the changes of a block or of state overrides on top of the accumulated state.
726    ///
727    /// A destroyed account drops every storage value recorded so far. Its parent storage is read
728    /// from `provider` only the first time, and later wipes zero the recorded slots in place.
729    pub fn extend(
730        &mut self,
731        provider: &impl HashedPostStateProvider,
732        changes: &BundleState,
733    ) -> ProviderResult<()> {
734        let mut parent_storage = BundleState::default();
735        for (address, account) in &changes.state {
736            // The first change to an account starts from its parent state.
737            let unzeroed = self
738                .parent_storage_unzeroed
739                .entry(*address)
740                .or_insert_with(|| account.original_info.is_some());
741            if !account.was_destroyed() {
742                continue
743            }
744            if let Some(storage) = self.hashed.storages.get_mut(&keccak256(address)) {
745                storage.storage.values_mut().for_each(|value| *value = U256::ZERO);
746            }
747            if mem::take(unzeroed) {
748                let mut account = account.clone();
749                account.storage.clear();
750                parent_storage.state.insert(*address, account);
751            }
752        }
753
754        if !parent_storage.state.is_empty() {
755            self.hashed.extend(provider.hashed_post_state(&parent_storage)?);
756        }
757
758        self.hashed.extend(HashedPostState::from_bundle_state::<KeccakKeyHasher>(&changes.state));
759        Ok(())
760    }
761}
762
763#[cfg(test)]
764mod tests {
765    use super::{
766        apply_precompile_overrides, sanitize_chain, EthSimulateError, ProviderResult,
767        SimulatedState, INTERNAL_ERROR_CODE,
768    };
769    use crate::{cache::db::apply_state_overrides_with_state, error::ToRpcError, EthApiError};
770    use alloy_chains::Chain;
771    use alloy_consensus::Header;
772    use alloy_primitives::{
773        address, keccak256,
774        map::{AddressMap, B256Map},
775        Address, B256, U256,
776    };
777    use alloy_rpc_types_eth::{
778        simulate::SimBlock,
779        state::{AccountOverride, StateOverride},
780        BlockOverrides, TransactionRequest,
781    };
782    use evm2::{
783        ethereum::ethereum_tx_registry,
784        evm::{AccountInfo, CacheDB, EmptyDB, InMemoryDB},
785        precompiles::PrecompileId,
786        BaseEvmTypes, Evm, Precompiles, SpecId,
787    };
788    use reth_concurrency::sync::atomic::{AtomicUsize, Ordering};
789    use reth_evm::BundleState;
790    use reth_primitives_traits::SealedHeader;
791    use reth_storage_api::HashedPostStateProvider;
792    use reth_trie_common::{HashedPostState, KeccakKeyHasher};
793    use std::collections::BTreeMap;
794
795    fn test_evm() -> Evm<'static, BaseEvmTypes> {
796        Evm::new(
797            SpecId::PRAGUE,
798            Default::default(),
799            ethereum_tx_registry(SpecId::PRAGUE),
800            EmptyDB::default(),
801            Precompiles::base(SpecId::PRAGUE),
802        )
803    }
804
805    /// Mimics the parent-state storage reads of the database-backed providers and counts them.
806    #[derive(Default)]
807    struct CountingProvider {
808        storage: AddressMap<B256Map<U256>>,
809        scans: AtomicUsize,
810        reads: AtomicUsize,
811    }
812
813    impl CountingProvider {
814        /// Returns the non-zero storage that results from layering `hashed` over the parent state.
815        fn resulting_storage(&self, hashed: &HashedPostState) -> BTreeMap<(B256, B256), U256> {
816            let parent = self.storage.iter().flat_map(|(address, slots)| {
817                slots.iter().map(move |(slot, value)| ((keccak256(address), *slot), *value))
818            });
819            let changes = hashed.storages.iter().flat_map(|(address, storage)| {
820                storage.storage.iter().map(|(slot, value)| ((*address, *slot), *value))
821            });
822            parent
823                .chain(changes)
824                .collect::<BTreeMap<_, _>>()
825                .into_iter()
826                .filter(|(_, v)| !v.is_zero())
827                .collect()
828        }
829    }
830
831    impl HashedPostStateProvider for CountingProvider {
832        fn hashed_post_state(&self, bundle_state: &BundleState) -> ProviderResult<HashedPostState> {
833            let mut hashed =
834                HashedPostState::from_bundle_state::<KeccakKeyHasher>(&bundle_state.state);
835            for (address, account) in &bundle_state.state {
836                if account.was_destroyed() && account.original_info.is_some() {
837                    self.scans.fetch_add(1, Ordering::Relaxed);
838                    let storage = self.storage.get(address).into_iter().flatten();
839                    let slots = &mut hashed.storages.entry(keccak256(address)).or_default().storage;
840                    for (slot, _) in storage {
841                        self.reads.fetch_add(1, Ordering::Relaxed);
842                        slots.entry(*slot).or_insert(U256::ZERO);
843                    }
844                }
845            }
846            Ok(hashed)
847        }
848    }
849
850    #[test]
851    fn nonce_max_value_error_uses_internal_error_code() {
852        let err = EthSimulateError::NonceMaxValue.to_rpc_error();
853
854        assert_eq!(err.code(), INTERNAL_ERROR_CODE);
855        assert_eq!(err.message(), "nonce has max value");
856    }
857
858    #[test]
859    fn block_not_found_error_uses_simulate_code() {
860        let err = EthSimulateError::BlockNotFound { block: 100000.into() }.to_rpc_error();
861
862        assert_eq!(err.code(), -32000);
863        assert_eq!(err.message(), "block not found: 0x186a0");
864    }
865
866    fn parent_at(number: u64, timestamp: u64) -> SealedHeader<Header> {
867        SealedHeader::seal_slow(Header { number, timestamp, ..Default::default() })
868    }
869
870    fn block_with_number(number: u64) -> SimBlock<TransactionRequest> {
871        SimBlock {
872            block_overrides: Some(BlockOverrides {
873                number: Some(U256::from(number)),
874                ..Default::default()
875            }),
876            ..Default::default()
877        }
878    }
879
880    #[test]
881    fn precompile_self_move_requires_existing_precompile() {
882        let address = address!("c100000000000000000000000000000000000000");
883        let mut state_overrides = StateOverride::default();
884        state_overrides.insert(
885            address,
886            AccountOverride { move_precompile_to: Some(address), ..Default::default() },
887        );
888        let mut evm = test_evm();
889
890        let err = apply_precompile_overrides(&state_overrides, &mut evm).unwrap_err();
891
892        assert!(matches!(err, EthSimulateError::NotAPrecompile(addr) if addr == address));
893    }
894
895    #[test]
896    fn precompile_self_move_errors_for_existing_precompile() {
897        let address = Address::with_last_byte(1);
898        let mut state_overrides = StateOverride::default();
899        state_overrides.insert(
900            address,
901            AccountOverride { move_precompile_to: Some(address), ..Default::default() },
902        );
903        let mut evm = test_evm();
904
905        let err = apply_precompile_overrides(&state_overrides, &mut evm).unwrap_err();
906
907        assert!(matches!(err, EthSimulateError::MovePrecompileToSelf(addr) if addr == address));
908    }
909
910    #[test]
911    fn moved_precompile_is_callable() {
912        let source = Address::with_last_byte(1);
913        let dest = address!("0000000000000000000000000000000000123456");
914        let mut state_overrides = StateOverride::default();
915        state_overrides.insert(
916            source,
917            AccountOverride { move_precompile_to: Some(dest), ..Default::default() },
918        );
919        let mut evm = test_evm();
920
921        apply_precompile_overrides(&state_overrides, &mut evm).unwrap();
922
923        let precompiles = evm.precompiles_as::<Precompiles>().unwrap().as_map();
924        assert!(!precompiles.contains(&source));
925        assert!(precompiles.contains(&dest));
926    }
927
928    #[test]
929    fn precompiles_moved_to_same_destination_resolve_to_higher_source() {
930        let dest = address!("0000000000000000000000000000000000001111");
931
932        // Every `StateOverride` gets a new random hasher seed, so repeat to cover both orders.
933        for _ in 0..64 {
934            let mut state_overrides = StateOverride::default();
935            for source in [Address::with_last_byte(2), Address::with_last_byte(4)] {
936                state_overrides.insert(
937                    source,
938                    AccountOverride { move_precompile_to: Some(dest), ..Default::default() },
939                );
940            }
941            let mut evm = test_evm();
942
943            apply_precompile_overrides(&state_overrides, &mut evm).unwrap();
944
945            let precompiles = evm.precompiles_as::<Precompiles>().unwrap().as_map();
946            assert_eq!(precompiles.get(&dest).unwrap().id(), &PrecompileId::Identity);
947        }
948    }
949
950    #[test]
951    fn sanitize_chain_fills_gaps_with_empty_blocks() {
952        // parent at block 5; user requests one block at 8 — sanitize should insert fillers at 6
953        // and 7 before the requested block.
954        let parent = parent_at(5, 100);
955        let blocks = vec![block_with_number(8)];
956
957        let out = sanitize_chain(blocks, &parent, Chain::mainnet().id(), 256).unwrap();
958        assert_eq!(out.len(), 3);
959
960        let numbers: Vec<u64> = out
961            .iter()
962            .map(|b| b.block_overrides.as_ref().unwrap().number.unwrap().try_into().unwrap())
963            .collect();
964        assert_eq!(numbers, vec![6, 7, 8]);
965
966        assert!(out[0].calls.is_empty());
967        assert!(out[1].calls.is_empty());
968
969        // Mainnet hint is 12s, so timestamps should auto-increment from 100 by 12.
970        let times: Vec<u64> =
971            out.iter().map(|b| b.block_overrides.as_ref().unwrap().time.unwrap()).collect();
972        assert_eq!(times, vec![112, 124, 136]);
973    }
974
975    #[test]
976    fn sanitize_chain_defaults_missing_number_and_time() {
977        let parent = parent_at(10, 1000);
978        let blocks: Vec<SimBlock<TransactionRequest>> =
979            vec![SimBlock::default(), SimBlock::default()];
980
981        let out = sanitize_chain(blocks, &parent, Chain::mainnet().id(), 256).unwrap();
982        assert_eq!(out.len(), 2);
983
984        let overrides = out[0].block_overrides.as_ref().unwrap();
985        assert_eq!(overrides.number.unwrap(), U256::from(11));
986        assert_eq!(overrides.time, Some(1012));
987
988        let overrides = out[1].block_overrides.as_ref().unwrap();
989        assert_eq!(overrides.number.unwrap(), U256::from(12));
990        assert_eq!(overrides.time, Some(1024));
991    }
992
993    #[test]
994    fn sanitize_chain_uses_chain_blocktime_hint() {
995        // Optimism has a 2s blocktime hint; filler/auto timestamps should reflect that.
996        let parent = parent_at(0, 0);
997        let blocks = vec![block_with_number(3)];
998
999        let out = sanitize_chain(blocks, &parent, Chain::optimism_mainnet().id(), 256).unwrap();
1000        let times: Vec<u64> =
1001            out.iter().map(|b| b.block_overrides.as_ref().unwrap().time.unwrap()).collect();
1002        assert_eq!(times, vec![2, 4, 6]);
1003    }
1004
1005    #[test]
1006    fn sanitize_chain_rounds_subsecond_blocktime_hint_up() {
1007        // Arbitrum has a 260ms blocktime hint. Simulated timestamps are second-granular, so this
1008        // rounds up to a 1s increment instead of falling back to the default.
1009        let parent = parent_at(0, 0);
1010        let blocks = vec![block_with_number(3)];
1011
1012        let out = sanitize_chain(blocks, &parent, Chain::arbitrum_mainnet().id(), 256).unwrap();
1013        let times: Vec<u64> =
1014            out.iter().map(|b| b.block_overrides.as_ref().unwrap().time.unwrap()).collect();
1015        assert_eq!(times, vec![1, 2, 3]);
1016    }
1017
1018    #[test]
1019    fn sanitize_chain_falls_back_when_chain_has_no_hint() {
1020        // An unknown chain id has no blocktime hint — fall back to the 12s default.
1021        let parent = parent_at(0, 0);
1022        let blocks = vec![block_with_number(2)];
1023
1024        let out = sanitize_chain(blocks, &parent, Chain::from_id(123_456_789).id(), 256).unwrap();
1025        let times: Vec<u64> =
1026            out.iter().map(|b| b.block_overrides.as_ref().unwrap().time.unwrap()).collect();
1027        assert_eq!(times, vec![12, 24]);
1028    }
1029
1030    #[test]
1031    fn sanitize_chain_rejects_non_increasing_number() {
1032        let parent = parent_at(10, 100);
1033        let err = sanitize_chain(vec![block_with_number(10)], &parent, Chain::mainnet().id(), 256)
1034            .unwrap_err();
1035        assert!(matches!(err, EthApiError::Other(_)));
1036    }
1037
1038    #[test]
1039    fn sanitize_chain_rejects_timestamp_overflow() {
1040        // A block may set any timestamp above its parent's, including `u64::MAX`. The following
1041        // block then defaults to `prev + increment`, which must not wrap.
1042        let parent = parent_at(0, 0);
1043        let blocks: Vec<SimBlock<TransactionRequest>> = vec![
1044            SimBlock {
1045                block_overrides: Some(BlockOverrides {
1046                    time: Some(u64::MAX),
1047                    ..Default::default()
1048                }),
1049                ..Default::default()
1050            },
1051            SimBlock::default(),
1052        ];
1053
1054        let err = sanitize_chain(blocks, &parent, Chain::mainnet().id(), 256).unwrap_err();
1055        assert!(matches!(err, EthApiError::Other(_)));
1056    }
1057
1058    #[test]
1059    fn sanitize_chain_rejects_filler_timestamp_overflow() {
1060        // Same, but the wrap would happen while generating filler blocks for a number gap.
1061        let parent = parent_at(0, 0);
1062        let blocks = vec![
1063            SimBlock {
1064                block_overrides: Some(BlockOverrides {
1065                    number: Some(U256::ONE),
1066                    time: Some(u64::MAX),
1067                    ..Default::default()
1068                }),
1069                ..Default::default()
1070            },
1071            block_with_number(4),
1072        ];
1073
1074        let err = sanitize_chain(blocks, &parent, Chain::mainnet().id(), 256).unwrap_err();
1075        assert!(matches!(err, EthApiError::Other(_)));
1076    }
1077
1078    #[test]
1079    fn sanitize_chain_enforces_max_blocks() {
1080        let parent = parent_at(0, 0);
1081        let err = sanitize_chain(vec![block_with_number(257)], &parent, Chain::mainnet().id(), 256)
1082            .unwrap_err();
1083        assert!(matches!(err, EthApiError::Other(_)));
1084    }
1085
1086    /// Hashing each block's changes once gives the same state as hashing the cumulative bundle
1087    /// again after every block, without reading the parent storage of destroyed accounts again.
1088    #[reth_concurrency::test]
1089    fn simulated_state_reads_parent_storage_once() {
1090        let wiped = Address::with_last_byte(1);
1091        let emptied = Address::with_last_byte(2);
1092        let created = Address::with_last_byte(3);
1093        let slot = |n: u64| B256::from(U256::from(n));
1094        let slots = |range: std::ops::Range<u64>| {
1095            range.map(|n| (slot(n), slot(n + 1000))).collect::<Vec<_>>()
1096        };
1097
1098        let mut db = InMemoryDB::default();
1099        let mut provider = CountingProvider::default();
1100        for (address, count) in [(wiped, 100), (emptied, 10)] {
1101            db.insert_account_info(
1102                &address,
1103                AccountInfo { balance: U256::from(5), ..Default::default() },
1104            );
1105            for (key, value) in slots(0..count) {
1106                db.insert_account_storage(
1107                    &address,
1108                    &U256::from_be_bytes(key.0),
1109                    &U256::from_be_bytes(value.0),
1110                );
1111                provider
1112                    .storage
1113                    .entry(address)
1114                    .or_default()
1115                    .insert(keccak256(key), U256::from_be_bytes(value.0));
1116            }
1117        }
1118        let mut db = CacheDB::new(db);
1119
1120        let blocks = [
1121            // Full replacement of an existing account's storage, an emptied account, and a new
1122            // account.
1123            StateOverride::from_iter([
1124                (
1125                    wiped,
1126                    AccountOverride::default()
1127                        .with_state([(slot(1), slot(7)), (slot(500), slot(8))]),
1128                ),
1129                (emptied, AccountOverride::default().with_balance(U256::ZERO)),
1130                (created, AccountOverride::default().with_balance(U256::from(3))),
1131            ]),
1132            // Later blocks touch the same account without wiping it. The new account has no
1133            // parent storage to read when its storage is replaced.
1134            StateOverride::from_iter([
1135                (wiped, AccountOverride::default().with_state_diff([(slot(2), slot(9))])),
1136                (created, AccountOverride::default().with_state([(slot(1), slot(4))])),
1137            ]),
1138            StateOverride::from_iter([(
1139                wiped,
1140                AccountOverride::default().with_balance(U256::from(6)),
1141            )]),
1142            // A second wipe, recreating a slot of the first.
1143            StateOverride::from_iter([(
1144                wiped,
1145                AccountOverride::default().with_state([(slot(500), slot(10))]),
1146            )]),
1147            StateOverride::from_iter([(
1148                wiped,
1149                AccountOverride::default().with_state_diff([(slot(3), slot(11))]),
1150            )]),
1151        ];
1152
1153        let mut simulated = SimulatedState::default();
1154        let mut cumulative = BundleState::default();
1155        for (index, state_overrides) in blocks.into_iter().enumerate() {
1156            let mut changes = BundleState::default();
1157            apply_state_overrides_with_state(state_overrides, &mut db, Some(&mut changes)).unwrap();
1158
1159            simulated.extend(&provider, &changes).unwrap();
1160            // Parent storage is read only when an account existing in the parent is first
1161            // destroyed.
1162            let reads = provider.reads.swap(0, Ordering::Relaxed);
1163            assert_eq!(reads, [110, 0, 0, 0, 0][index], "block {index}");
1164            let scans = provider.scans.swap(0, Ordering::Relaxed);
1165            assert_eq!(scans, [2, 0, 0, 0, 0][index], "block {index}");
1166
1167            cumulative.extend(changes);
1168            let expected = provider.hashed_post_state(&cumulative).unwrap();
1169            provider.reads.store(0, Ordering::Relaxed);
1170            provider.scans.store(0, Ordering::Relaxed);
1171            assert_eq!(simulated.hashed_state().accounts, expected.accounts, "block {index}");
1172            assert_eq!(
1173                provider.resulting_storage(simulated.hashed_state()),
1174                provider.resulting_storage(&expected),
1175                "block {index}"
1176            );
1177        }
1178    }
1179}