Skip to main content

reth_rpc/
debug.rs

1use alloy_consensus::{transaction::TxHashRef, BlockHeader, Sealable, TxReceipt};
2use alloy_eips::{eip2718::Encodable2718, BlockId, BlockNumberOrTag};
3use alloy_genesis::ChainConfig;
4use alloy_primitives::{bytes, hex::decode, uint, Address, Bytes, B256, U256, U64};
5use alloy_rlp::{Decodable, Encodable};
6use alloy_rpc_types::BlockTransactionsKind;
7use alloy_rpc_types_debug::ExecutionWitness;
8use alloy_rpc_types_eth::{
9    state::EvmOverrides, Account, AccountInfo, BlockError, Bundle, Index, StateContext,
10};
11use alloy_rpc_types_trace::{
12    common::TraceResult,
13    geth::{
14        GethDebugBuiltInTracerType, GethDebugTracerType, GethDebugTracingCallOptions,
15        GethDebugTracingOptions,
16    },
17};
18use evm2::evm::StateChangeSource;
19use evm2_inspectors::tracing::{
20    DebugInspector, DebugInspectorError, DebugTrace, StructLogMode, TraceLimits, TransactionContext,
21};
22use futures::Stream;
23use jsonrpsee::{
24    core::RpcResult, PendingSubscriptionSink, ResponseSink, ResponseStream, SubscriptionMessage,
25};
26use parking_lot::RwLock;
27use reth_chainspec::{ChainSpecProvider, EthereumHardforks};
28use reth_consensus::ConsensusError;
29use reth_engine_primitives::ConsensusEngineEvent;
30use reth_errors::RethError;
31use reth_evm::{
32    execute::{BlockExecutor, BlockTransactionResult, Executor},
33    witness::ExecutionWitnessRecord,
34    BlockExecutionError, ConfigureEvm, DynDatabase, Evm, EvmEnv, EvmEnvFor,
35};
36use reth_primitives_traits::{
37    constants::GAS_LIMIT_BOUND_DIVISOR, Block as BlockTrait, BlockBody, BlockTy, ReceiptWithBloom,
38    RecoveredBlock,
39};
40use reth_rpc_api::DebugApiServer;
41use reth_rpc_convert::RpcTxReq;
42use reth_rpc_eth_api::{
43    helpers::{EthTransactions, InspectedTx, TraceExt},
44    AsEthApiError, BoundedCallMany, FromEthApiError, FromEvmError, RpcConvert, RpcNodeCore,
45};
46use reth_rpc_eth_types::{utils::CallManyBudget, EthApiError, StateCacheDb, TransactionSource};
47use reth_rpc_server_types::{result::internal_rpc_err, ToRpcResult};
48use reth_storage_api::{
49    BlockIdReader, BlockReaderIdExt, HashedPostStateProvider, HeaderProvider, ProviderBlock,
50    ProviderHeader, ReceiptProviderIdExt, StateProviderFactory, StateRootProvider,
51    StorageRootProvider, TransactionVariant,
52};
53use reth_tasks::{cancel::is_cancelled, pool::BlockingTaskGuard, Runtime};
54use reth_transaction_pool::TransactionPool;
55use reth_trie_common::{
56    root::storage_root_unsorted, updates::TrieUpdates, ExecutionWitnessMode, HashedPostState,
57    HashedStorage,
58};
59use serde::{Deserialize, Serialize};
60use serde_json::value::RawValue;
61use std::{collections::VecDeque, io, sync::Arc, time::Duration};
62use tokio::sync::{AcquireError, OwnedSemaphorePermit};
63use tokio_stream::StreamExt;
64
65#[cfg(feature = "js-tracer")]
66use alloy_rpc_types_trace::geth::GethDebugTracerConfig;
67#[cfg(feature = "js-tracer")]
68use evm2_inspectors::tracing::js::JsInspectorInterrupt;
69#[cfg(feature = "js-tracer")]
70use jiff::fmt::friendly::SpanParser;
71
72/// `debug` API implementation.
73///
74/// This type provides the functionality for handling `debug` related requests.
75pub struct DebugApi<Eth: RpcNodeCore> {
76    inner: Arc<DebugApiInner<Eth>>,
77}
78
79impl<Eth> DebugApi<Eth>
80where
81    Eth: RpcNodeCore,
82{
83    /// Create a new instance of the [`DebugApi`]
84    pub fn new(
85        eth_api: Eth,
86        blocking_task_guard: BlockingTaskGuard,
87        executor: &Runtime,
88        mut stream: impl Stream<Item = ConsensusEngineEvent<Eth::Primitives>> + Send + Unpin + 'static,
89    ) -> Self {
90        let bad_block_store = BadBlockStore::default();
91        let inner = Arc::new(DebugApiInner {
92            eth_api,
93            blocking_task_guard,
94            task_spawner: executor.clone(),
95            bad_block_store: bad_block_store.clone(),
96        });
97
98        // Spawn a task caching bad blocks
99        executor.spawn_task(async move {
100            while let Some(event) = stream.next().await {
101                if let ConsensusEngineEvent::InvalidBlock { block, error } = event &&
102                    let Ok(recovered) = RecoveredBlock::try_recover_sealed(*block)
103                {
104                    bad_block_store.insert(recovered, error);
105                }
106            }
107        });
108
109        Self { inner }
110    }
111
112    /// Access the underlying `Eth` API.
113    pub fn eth_api(&self) -> &Eth {
114        &self.inner.eth_api
115    }
116
117    /// Access the underlying provider.
118    pub fn provider(&self) -> &Eth::Provider {
119        self.inner.eth_api.provider()
120    }
121}
122
123// === impl DebugApi ===
124
125impl<Eth> DebugApi<Eth>
126where
127    Eth: TraceExt,
128{
129    /// Acquires a permit to execute a tracing call.
130    async fn acquire_trace_permit(&self) -> Result<OwnedSemaphorePermit, AcquireError> {
131        self.inner.blocking_task_guard.clone().acquire_owned().await
132    }
133
134    /// Traces every transaction of a block through the block executor, see
135    /// [`Call::block_executor`](reth_rpc_eth_api::helpers::Call::block_executor).
136    ///
137    /// A supplied permit stays with the worker if the waiting request times out or is dropped.
138    async fn trace_block(
139        &self,
140        block: Arc<RecoveredBlock<ProviderBlock<Eth::Provider>>>,
141        evm_env: EvmEnvFor<Eth::Evm>,
142        opts: GethDebugTracingOptions,
143        permit: Option<OwnedSemaphorePermit>,
144    ) -> Result<Vec<TraceResult<DebugTrace, String>>, Eth::Error> {
145        let results = Vec::with_capacity(block.body().transactions().len());
146        self.trace_block_with(block, evm_env, opts, permit, results, |results, result| {
147            results.push(result);
148            Ok(())
149        })
150        .await
151    }
152
153    /// Same as [`Self::trace_block`], but passes the result of each transaction to `push`, in block
154    /// order, as soon as the transaction is traced, and returns `results` after the last one.
155    ///
156    /// `push` runs on the tracing thread, so it may block. An error from `push` stops the trace
157    /// and is returned.
158    async fn trace_block_with<T, F>(
159        &self,
160        block: Arc<RecoveredBlock<ProviderBlock<Eth::Provider>>>,
161        evm_env: EvmEnvFor<Eth::Evm>,
162        opts: GethDebugTracingOptions,
163        permit: Option<OwnedSemaphorePermit>,
164        mut results: T,
165        mut push: F,
166    ) -> Result<T, Eth::Error>
167    where
168        T: Send + 'static,
169        F: FnMut(&mut T, TraceResult<DebugTrace, String>) -> Result<(), Eth::Error>
170            + Send
171            + 'static,
172    {
173        self.eth_api()
174            .spawn_with_state_at_block(block.parent_hash(), move |eth_api, mut db| {
175                let _permit = permit;
176
177                eth_api.apply_pre_execution_changes(&block, &mut db)?;
178
179                let block_env = *evm_env.block_env();
180
181                let mut transactions = block.transactions_recovered().enumerate().peekable();
182                let trace_limits = eth_api.trace_limits();
183                let inspector = new_debug_inspector(opts).map_err(Eth::Error::from_eth_err)?;
184                let mut response =
185                    ResponseBudget::new(&inspector, eth_api.eth_api_settings().max_response_size);
186                let mut inspector = inspector.with_limits(response.limit(trace_limits));
187                let mut executor = eth_api.block_executor(&block, &mut db, evm_env)?;
188                while let Some((index, tx)) = transactions.next() {
189                    if is_cancelled() {
190                        return Err(EthApiError::InternalEthError.into())
191                    }
192                    let tx_hash = *tx.tx_hash();
193                    let tx_env = eth_api.evm_config().tx_env(tx.cloned());
194
195                    let (next_inspector, output) = executor
196                        .inspect_transaction_without_commit(tx, inspector)
197                        .map_err(Eth::Error::from_evm_err)?;
198                    inspector = next_inspector;
199                    let result = inspector
200                        .get_trace(
201                            Some(TransactionContext {
202                                block_hash: Some(block.hash()),
203                                tx_hash: Some(tx_hash),
204                                tx_index: Some(index),
205                            }),
206                            &tx_env,
207                            &block_env,
208                            output.result(),
209                            executor.evm_mut().state_db_mut(),
210                        )
211                        .map_err(Eth::Error::from_eth_err)?;
212                    response.charge(&inspector);
213
214                    push(&mut results, TraceResult::Success { result, tx_hash: Some(tx_hash) })?;
215                    if transactions.peek().is_some() {
216                        inspector.fuse().map_err(Eth::Error::from_eth_err)?;
217                        inspector.set_limits(response.limit(trace_limits));
218                        // need to apply the state changes of this transaction before executing the
219                        // next transaction
220                        executor.commit_transaction(output).map_err(Eth::Error::from_evm_err)?;
221                        inspector.set_next_log_index(
222                            executor.receipts().iter().map(|receipt| receipt.logs().len()).sum(),
223                        );
224                    }
225                }
226
227                Ok(results)
228            })
229            .await
230    }
231
232    /// Traces a block for `traceChain`, preserving transaction-level tracing failures in the
233    /// subscription result instead of failing the entire range.
234    async fn trace_chain_block(
235        &self,
236        block: Arc<RecoveredBlock<ProviderBlock<Eth::Provider>>>,
237        opts: GethDebugTracingOptions,
238    ) -> Result<Vec<Option<TraceResult<DebugTrace, String>>>, Eth::Error> {
239        let evm_env = self.eth_api().evm_env_for_header(block.sealed_block().sealed_header())?;
240
241        self.eth_api()
242            .spawn_with_state_at_block(block.parent_hash(), move |eth_api, mut db| {
243                let tx_count = block.body().transactions().len();
244                let mut results = Vec::with_capacity(tx_count);
245
246                eth_api.apply_pre_execution_changes(&block, &mut db)?;
247
248                let block_env = *evm_env.block_env();
249                let mut transactions = block.transactions_recovered().enumerate().peekable();
250                // Notifications are not bound by the response size limit, so only the trace byte
251                // limit of each transaction applies.
252                let mut inspector = match new_debug_inspector(opts) {
253                    Ok(inspector) => inspector.with_limits(eth_api.trace_limits()),
254                    Err(err) => {
255                        if let Some((_, tx)) = transactions.peek() {
256                            results.push(Some(TraceResult::Error {
257                                error: err.to_string(),
258                                tx_hash: Some(*tx.tx_hash()),
259                            }));
260                        }
261                        results.resize(tx_count, None);
262                        return Ok(results)
263                    }
264                };
265                let mut executor = eth_api.block_executor(&block, &mut db, evm_env)?;
266
267                while let Some((index, tx)) = transactions.next() {
268                    let tx_hash = *tx.tx_hash();
269                    let tx_env = eth_api.evm_config().tx_env(tx.cloned());
270                    let output = match executor.inspect_transaction_without_commit(tx, inspector) {
271                        Ok((next_inspector, output)) => {
272                            inspector = next_inspector;
273                            output
274                        }
275                        Err(err) => {
276                            results.push(Some(TraceResult::Error {
277                                error: err.to_string(),
278                                tx_hash: Some(tx_hash),
279                            }));
280                            break
281                        }
282                    };
283
284                    let result = match inspector.get_trace(
285                        Some(TransactionContext {
286                            block_hash: Some(block.hash()),
287                            tx_hash: Some(tx_hash),
288                            tx_index: Some(index),
289                        }),
290                        &tx_env,
291                        &block_env,
292                        output.result(),
293                        executor.evm_mut().state_db_mut(),
294                    ) {
295                        Ok(result) => result,
296                        Err(err) => {
297                            results.push(Some(TraceResult::Error {
298                                error: err.to_string(),
299                                tx_hash: Some(tx_hash),
300                            }));
301                            break
302                        }
303                    };
304
305                    results.push(Some(TraceResult::Success { result, tx_hash: Some(tx_hash) }));
306                    if let Some((_, next_tx)) = transactions.peek() {
307                        if let Err(err) = inspector.fuse() {
308                            results.push(Some(TraceResult::Error {
309                                error: err.to_string(),
310                                tx_hash: Some(*next_tx.tx_hash()),
311                            }));
312                            break
313                        }
314                        if let Err(err) = executor.commit_transaction(output) {
315                            results.push(Some(TraceResult::Error {
316                                error: err.to_string(),
317                                tx_hash: Some(*next_tx.tx_hash()),
318                            }));
319                            break
320                        }
321                        inspector.set_next_log_index(
322                            executor.receipts().iter().map(|receipt| receipt.logs().len()).sum(),
323                        );
324                    }
325                }
326
327                results.resize(tx_count, None);
328                Ok(results)
329            })
330            .await
331    }
332
333    /// Replays the given block and returns the trace of each transaction.
334    ///
335    /// This expects a rlp encoded block
336    ///
337    /// Note, the parent of this block must be present, or it will fail. Unless the block is
338    /// already stored, its header must extend its parent: the next block number, a timestamp no
339    /// earlier than the parent's and a gas limit within the parent's bound or the RPC gas cap.
340    ///
341    /// The block is supplied by the caller, so its replay is bounded by a timeout of 30 seconds: no
342    /// transaction starts after it expires, the request then fails with
343    /// [`EthApiError::ExecutionTimedOut`].
344    /// The replay retains its tracing permit until the running transaction finishes.
345    pub async fn debug_trace_raw_block(
346        &self,
347        rlp_block: Bytes,
348        opts: GethDebugTracingOptions,
349    ) -> Result<Vec<TraceResult<DebugTrace, String>>, Eth::Error> {
350        let permit =
351            self.acquire_trace_permit().await.map_err(|_| EthApiError::InternalEthError)?;
352        let block: ProviderBlock<Eth::Provider> = Decodable::decode(&mut rlp_block.as_ref())
353            .map_err(BlockError::RlpDecodeRawBlock)
354            .map_err(Eth::Error::from_eth_err)?;
355        // A stored header already passed consensus, which may allow gas limit changes the check
356        // doesn't, such as the London elasticity doubling.
357        if self
358            .provider()
359            .header(block.header().hash_slow())
360            .map_err(Eth::Error::from_eth_err)?
361            .is_none()
362        {
363            self.ensure_header_extends_parent(block.header())?;
364        }
365
366        let evm_env = self
367            .eth_api()
368            .evm_config()
369            .evm_env(block.header())
370            .map_err(RethError::other)
371            .map_err(Eth::Error::from_eth_err)?;
372
373        // Depending on EIP-2 we need to recover the transactions differently
374        let senders =
375            if self.provider().chain_spec().is_homestead_active_at_block(block.header().number()) {
376                block.body().recover_signers()
377            } else {
378                block.body().recover_signers_unchecked()
379            }
380            .map_err(Eth::Error::from_eth_err)?;
381
382        // Dropping the replay cancels it before its next transaction.
383        tokio::time::timeout(
384            RAW_BLOCK_TRACE_TIMEOUT,
385            self.trace_block(
386                Arc::new(block.into_recovered_with_signers(senders)),
387                evm_env,
388                opts,
389                Some(permit),
390            ),
391        )
392        .await
393        .map_err(|_| {
394            Eth::Error::from_eth_err(EthApiError::ExecutionTimedOut(RAW_BLOCK_TRACE_TIMEOUT))
395        })?
396    }
397
398    /// Checks that a header consensus has not validated extends its parent, so the block is not
399    /// traced with a hardfork older than its parent's or a gas limit the chain wouldn't allow.
400    ///
401    /// The header must have the next block number and a timestamp no earlier than its parent's;
402    /// chains with sub-second blocks give consecutive blocks the same timestamp. Its gas limit may
403    /// exceed the parent's by the consensus bound, or reach the RPC gas cap.
404    fn ensure_header_extends_parent(
405        &self,
406        header: &ProviderHeader<Eth::Provider>,
407    ) -> Result<(), Eth::Error> {
408        let parent = self
409            .provider()
410            .header(header.parent_hash())
411            .map_err(Eth::Error::from_eth_err)?
412            .ok_or_else(|| EthApiError::HeaderNotFound(header.parent_hash().into()))?;
413        let max_gas_limit = parent
414            .gas_limit()
415            .saturating_add(parent.gas_limit() / GAS_LIMIT_BOUND_DIVISOR)
416            .max(self.eth_api().call_gas_limit());
417
418        let err = if parent.number().checked_add(1) != Some(header.number()) {
419            ConsensusError::ParentBlockNumberMismatch {
420                parent_block_number: parent.number(),
421                block_number: header.number(),
422            }
423        } else if header.timestamp() < parent.timestamp() {
424            ConsensusError::TimestampIsInPast {
425                parent_timestamp: parent.timestamp(),
426                timestamp: header.timestamp(),
427            }
428        } else if header.gas_limit() > max_gas_limit {
429            ConsensusError::GasLimitInvalidIncrease {
430                parent_gas_limit: parent.gas_limit(),
431                child_gas_limit: header.gas_limit(),
432            }
433        } else {
434            return Ok(())
435        };
436        Err(EthApiError::InvalidParams(err.to_string()).into())
437    }
438
439    /// Replays a block and returns the trace of each transaction.
440    pub async fn debug_trace_block(
441        &self,
442        block_id: BlockId,
443        opts: GethDebugTracingOptions,
444    ) -> Result<Vec<TraceResult<DebugTrace, String>>, Eth::Error> {
445        let (block, evm_env) = self.block_to_trace(block_id).await?;
446        self.trace_block(block, evm_env, opts, None).await
447    }
448
449    /// Same as [`Self::debug_trace_block`], but sends the JSON-RPC result in parts: the list
450    /// opens with the trace of the first transaction and every other trace follows as soon as its
451    /// transaction is traced.
452    ///
453    /// The tracing permit is acquired before the block is looked up and held until the last
454    /// transaction is traced, which doesn't wait for the client to read the parts. Dropping the
455    /// stream cancels the replay before its next transaction.
456    pub async fn debug_trace_block_stream(
457        &self,
458        block_id: BlockId,
459        opts: GethDebugTracingOptions,
460    ) -> Result<ResponseStream, Eth::Error> {
461        let permit = self.acquire_trace_permit().await.ok();
462        let (block, evm_env) = self.block_to_trace(block_id).await?;
463        let this = self.clone();
464        Ok(ResponseStream::new(move |tx| async move {
465            let parts = tx.clone();
466            let first = this
467                .trace_block_with(block, evm_env, opts, permit, true, move |first, result| {
468                    let prefix: &[u8] = if std::mem::take(first) { b"[" } else { b"," };
469                    // If the response was dropped or exceeds the size limit, the client gets
470                    // that instead of this error.
471                    send_trace(&parts, prefix, result).map_err(|err| {
472                        Eth::Error::from_eth_err(EthApiError::Internal(RethError::other(err)))
473                    })
474                })
475                .await?;
476            let end: &'static [u8] = if first { b"[]" } else { b"]" };
477            tx.send(end.into()).map_err(|_| Eth::Error::from_eth_err(EthApiError::InternalEthError))
478        }))
479    }
480
481    /// Looks up a block to replay and the EVM environment to replay it in.
482    async fn block_to_trace(
483        &self,
484        block_id: BlockId,
485    ) -> Result<(Arc<RecoveredBlock<ProviderBlock<Eth::Provider>>>, EvmEnvFor<Eth::Evm>), Eth::Error>
486    {
487        let block = self
488            .eth_api()
489            .recovered_block(block_id)
490            .await?
491            .ok_or(EthApiError::TracingBlockNotFound(block_id))?;
492        // Tracing requires the parent state, which does not exist for the genesis block.
493        if block.number() == 0 {
494            return Err(EthApiError::GenesisNotTraceable.into())
495        }
496        let evm_env = self.eth_api().evm_env_for_header(block.sealed_block().sealed_header())?;
497        Ok((block, evm_env))
498    }
499
500    /// Trace the transaction according to the provided options.
501    ///
502    /// Ref: <https://geth.ethereum.org/docs/developers/evm-tracing/built-in-tracers>
503    pub async fn debug_trace_transaction(
504        &self,
505        tx_hash: B256,
506        opts: GethDebugTracingOptions,
507    ) -> Result<DebugTrace, Eth::Error> {
508        let Some((TransactionSource::Block { transaction: tx, index, .. }, block, mut bal)) =
509            self.eth_api().transaction_and_block_and_maybe_bal(tx_hash).await?
510        else {
511            return Err(EthApiError::TracingTransactionNotFound.into())
512        };
513        let index = index as usize;
514
515        // Only these tracers can report call logs, a new tracer that does must be added here.
516        let needs_log_index = matches!(
517            opts.tracer,
518            Some(GethDebugTracerType::BuiltInTracer(
519                GethDebugBuiltInTracerType::CallTracer |
520                    GethDebugBuiltInTracerType::Erc7562Tracer |
521                    GethDebugBuiltInTracerType::MuxTracer
522            ))
523        );
524        // On the BAL path, use receipts for block-level log indices or replay if they are missing.
525        let mut next_log_index = 0;
526        if needs_log_index && index > 0 && bal.is_some() {
527            if let Some(receipts) = self
528                .eth_api()
529                .cache()
530                .get_receipts(block.hash())
531                .await
532                .map_err(Eth::Error::from_eth_err)?
533            {
534                next_log_index =
535                    receipts.iter().take(index).map(|receipt| receipt.logs().len()).sum();
536            } else {
537                bal = None;
538            }
539        }
540
541        let interrupt = JsTraceInterrupt::new(&opts)?;
542        let tracer_interrupt = interrupt.clone();
543        let trace = self.eth_api().spawn_with_state_at_block(
544            block.parent_hash(),
545            move |eth_api, mut db| {
546                let inspector = new_debug_inspector(opts).map_err(Eth::Error::from_eth_err)?;
547                let limits =
548                    ResponseBudget::new(&inspector, eth_api.eth_api_settings().max_response_size)
549                        .limit(eth_api.trace_limits());
550                let mut inspector = tracer_interrupt.attach(inspector.with_limits(limits));
551                // configure env for the target transaction
552                let tx_env = eth_api.evm_config().tx_env(tx);
553                let InspectedTx { mut inspector, result, evm_env } = eth_api
554                    .inspect_transaction_in_block(
555                        &block,
556                        &mut db,
557                        |replayed_logs| {
558                            inspector.set_next_log_index(next_log_index + replayed_logs);
559                            inspector
560                        },
561                        index,
562                        bal.as_deref(),
563                    )?;
564                let trace = inspector
565                    .get_trace(
566                        Some(TransactionContext {
567                            block_hash: Some(block.hash()),
568                            tx_index: Some(index),
569                            tx_hash: Some(tx_hash),
570                        }),
571                        &tx_env,
572                        evm_env.block_env(),
573                        &result,
574                        &mut db,
575                    )
576                    .map_err(Eth::Error::from_eth_err)?;
577
578                Ok(trace)
579            },
580        );
581        interrupt.run(trace).await
582    }
583
584    /// The `debug_traceCall` method lets you run an `eth_call` within the context of the given
585    /// block execution using the final state of parent block as the base.
586    ///
587    /// If `tx_index` is provided in opts, the call will be traced at the state after executing
588    /// transactions up to the specified index within the block (0-indexed).
589    /// If not provided, then uses the post-state (default behavior).
590    ///
591    /// Differences compare to `eth_call`:
592    ///  - `debug_traceCall` executes with __enabled__ basefee check, `eth_call` does not: <https://github.com/paradigmxyz/reth/issues/6240>
593    pub async fn debug_trace_call(
594        &self,
595        call: RpcTxReq<Eth::NetworkTypes>,
596        block_id: Option<BlockId>,
597        opts: GethDebugTracingCallOptions,
598    ) -> Result<DebugTrace, Eth::Error> {
599        let at = block_id.unwrap_or_default();
600        let GethDebugTracingCallOptions {
601            tracing_options,
602            state_overrides,
603            block_overrides,
604            tx_index,
605        } = opts;
606        // Withdrawals are processed after the transactions and cannot be applied to a trace call.
607        if block_overrides.as_ref().is_some_and(|overrides| overrides.withdrawals.is_some()) {
608            return Err(EthApiError::InvalidParams(
609                "block override \"withdrawals\" is not supported for this RPC method".into(),
610            )
611            .into())
612        }
613        let overrides = EvmOverrides::new(state_overrides, block_overrides.map(Box::new));
614
615        // Check if we need to replay transactions for a specific tx_index
616        if let Some(tx_idx) = tx_index {
617            return self
618                .debug_trace_call_at_tx_index(call, at, tx_idx as usize, tracing_options, overrides)
619                .await;
620        }
621
622        let interrupt = JsTraceInterrupt::new(&tracing_options)?;
623        let tracer_interrupt = interrupt.clone();
624        let this = self.clone();
625        let trace =
626            self.eth_api().spawn_with_call_at(call, at, overrides, move |db, evm_env, tx_env| {
627                let inspector =
628                    new_debug_inspector(tracing_options).map_err(Eth::Error::from_eth_err)?;
629                let limits = ResponseBudget::new(
630                    &inspector,
631                    this.eth_api().eth_api_settings().max_response_size,
632                )
633                .limit(this.eth_api().trace_limits());
634                let inspector = tracer_interrupt.attach(inspector.with_limits(limits));
635                let (mut inspector, res) =
636                    this.eth_api().inspect(&mut *db, evm_env.clone(), &tx_env, inspector)?;
637                let trace = inspector
638                    .get_trace(None, &tx_env, evm_env.block_env(), &res, db)
639                    .map_err(Eth::Error::from_eth_err)?;
640                Ok(trace)
641            });
642        interrupt.run(trace).await.map_err(|err| match err.as_err() {
643            Some(EthApiError::HeaderNotFound(id)) if *id == at => {
644                // Unknown blocks use -32000: https://github.com/ethereum/execution-apis/pull/855
645                EthApiError::TracingBlockNotFound(at).into()
646            }
647            _ => err,
648        })
649    }
650
651    /// Helper method to execute `debug_trace_call` at a specific transaction index within a block.
652    /// This replays transactions up to the specified index, then executes the trace call in that
653    /// state.
654    async fn debug_trace_call_at_tx_index(
655        &self,
656        call: RpcTxReq<Eth::NetworkTypes>,
657        block_id: BlockId,
658        tx_index: usize,
659        tracing_options: GethDebugTracingOptions,
660        overrides: EvmOverrides,
661    ) -> Result<DebugTrace, Eth::Error> {
662        // Get the target block to check transaction count
663        let (block, bal) = self
664            .eth_api()
665            .recovered_block_and_maybe_bal(block_id)
666            .await?
667            .ok_or(EthApiError::TracingBlockNotFound(block_id))?;
668
669        if tx_index >= block.transaction_count() {
670            // tx_index out of bounds
671            return Err(EthApiError::InvalidParams(format!(
672                "tx_index {} out of bounds for block with {} transactions",
673                tx_index,
674                block.transaction_count()
675            ))
676            .into())
677        }
678
679        // state overrides commit changes to the database, which an attached BAL would take read
680        // precedence over, so only position via BAL if there are none
681        let bal = bal.filter(|_| !overrides.has_state());
682
683        let evm_env = self.eth_api().evm_env_for_header(block.sealed_block().sealed_header())?;
684
685        let interrupt = JsTraceInterrupt::new(&tracing_options)?;
686        let tracer_interrupt = interrupt.clone();
687        let trace = self.eth_api().spawn_with_state_at_block(
688            block.parent_hash(),
689            move |eth_api, mut db| {
690                // 1. position the state before the transaction at the index
691                eth_api.replay_block_until(&mut db, &block, tx_index, bal.as_deref())?;
692
693                // 2. now execute the trace call on this state
694                let (evm_env, tx_env) =
695                    eth_api.prepare_call_env(evm_env, call, &mut db, overrides)?;
696
697                let inspector =
698                    new_debug_inspector(tracing_options).map_err(Eth::Error::from_eth_err)?;
699                let limits =
700                    ResponseBudget::new(&inspector, eth_api.eth_api_settings().max_response_size)
701                        .limit(eth_api.trace_limits());
702                let inspector = tracer_interrupt.attach(inspector.with_limits(limits));
703                let (mut inspector, res) =
704                    eth_api.inspect(&mut db, evm_env.clone(), &tx_env, inspector)?;
705                let trace = inspector
706                    .get_trace(None, &tx_env, evm_env.block_env(), &res, &mut db)
707                    .map_err(Eth::Error::from_eth_err)?;
708
709                Ok(trace)
710            },
711        );
712        interrupt.run(trace).await
713    }
714
715    /// The `debug_traceCallMany` method lets you run an `eth_callMany` within the context of the
716    /// given block execution using the first n transactions in the given block as base.
717    /// Each following bundle increments block number by 1 and block timestamp by 12 seconds
718    pub async fn debug_trace_call_many(
719        &self,
720        bundles: Vec<Bundle<RpcTxReq<Eth::NetworkTypes>>>,
721        state_context: Option<StateContext>,
722        opts: Option<GethDebugTracingCallOptions>,
723    ) -> Result<Vec<Vec<DebugTrace>>, Eth::Error> {
724        if bundles.is_empty() {
725            return Err(EthApiError::InvalidParams(String::from("bundles are empty.")).into())
726        }
727        let mut budget = CallManyBudget::for_bundles(&bundles, self.eth_api().call_gas_limit())?;
728
729        let StateContext { transaction_index, block_number } = state_context.unwrap_or_default();
730        let transaction_index = transaction_index.unwrap_or_default();
731
732        let target_block = block_number.unwrap_or_default();
733        let block = self
734            .eth_api()
735            .recovered_block(target_block)
736            .await?
737            .ok_or(EthApiError::HeaderNotFound(target_block))?;
738        let mut evm_env =
739            self.eth_api().evm_env_for_header(block.sealed_block().sealed_header())?;
740
741        let opts = opts.unwrap_or_default();
742        let GethDebugTracingCallOptions { tracing_options, mut state_overrides, .. } = opts;
743
744        // we're essentially replaying the transactions in the block here, hence we need the state
745        // that points to the beginning of the block, which is the state at the parent block
746        let mut at = block.parent_hash();
747        let mut replay_block_txs = true;
748
749        // if a transaction index is provided, we need to replay the transactions until the index
750        let num_txs =
751            transaction_index.index().unwrap_or_else(|| block.body().transactions().len());
752        // but if all transactions are to be replayed, we can use the state at the block itself
753        // this works with the exception of the PENDING block, because its state might not exist if
754        // built locally
755        if !target_block.is_pending() && num_txs == block.body().transactions().len() {
756            at = block.hash();
757            replay_block_txs = false;
758        }
759
760        self.eth_api()
761            .spawn_with_state_at_block(at, move |eth_api, mut db| {
762                // the outer vec for the bundles
763                let mut all_bundles = Vec::with_capacity(bundles.len());
764
765                if replay_block_txs {
766                    // only need to replay the transactions in the block if not all transactions are
767                    // to be replayed
768                    // Execute all transactions until index. No BAL positioning here: bundle
769                    // transactions commit state on top, and an attached BAL would take read
770                    // precedence over the committed changes
771                    eth_api.replay_block_until(&mut db, &block, num_txs, None)?;
772                }
773
774                // Trace all bundles
775                let mut bundles = bundles.into_iter().peekable();
776                let trace_limits = eth_api.trace_limits();
777                // All bundles share one response.
778                let inspector = new_debug_inspector(tracing_options.clone())
779                    .map_err(Eth::Error::from_eth_err)?;
780                let mut response =
781                    ResponseBudget::new(&inspector, eth_api.eth_api_settings().max_response_size);
782                let mut inspector = inspector.with_limits(response.limit(trace_limits));
783                while let Some(bundle) = bundles.next() {
784                    let mut results = Vec::with_capacity(bundle.transactions.len());
785                    let Bundle { transactions, block_override } = bundle;
786
787                    let block_overrides = block_override.map(Box::new);
788
789                    let mut transactions = transactions.into_iter().peekable();
790                    while let Some(tx) = transactions.next() {
791                        if is_cancelled() {
792                            return Err(EthApiError::InternalEthError.into())
793                        }
794                        // apply state overrides only once, before the first transaction
795                        let state_overrides = state_overrides.take();
796                        let overrides = EvmOverrides::new(state_overrides, block_overrides.clone());
797
798                        let (evm_env, mut tx_env) =
799                            eth_api.prepare_call_env(evm_env.clone(), tx, &mut db, overrides)?;
800                        budget.admit(&mut tx_env)?;
801
802                        let (next_inspector, res) = eth_api
803                            .inspect(&mut db, evm_env.clone(), &tx_env, inspector)
804                            .map_err(|err| budget.map_call_err(err))?;
805                        budget.charge(&res.result)?;
806                        inspector = next_inspector;
807                        let trace = inspector
808                            .get_trace(None, &tx_env, evm_env.block_env(), &res, &mut db)
809                            .map_err(Eth::Error::from_eth_err)?;
810                        response.charge(&inspector);
811
812                        // If there is more transactions, commit the database
813                        // If there is no transactions, but more bundles, commit to the database too
814                        if transactions.peek().is_some() || bundles.peek().is_some() {
815                            inspector.fuse().map_err(Eth::Error::from_eth_err)?;
816                            inspector.set_limits(response.limit(trace_limits));
817                            db.commit_source(&res.pending_state);
818                        }
819                        results.push(trace);
820                    }
821                    // Increment block_env number and timestamp for the next bundle
822                    evm_env.block_env_mut().number += uint!(1_U256);
823                    evm_env.block_env_mut().timestamp += uint!(12_U256);
824
825                    all_bundles.push(results);
826                }
827                Ok(all_bundles)
828            })
829            .await
830    }
831
832    /// Generates an execution witness for the given block hash. see
833    /// [`Self::debug_execution_witness`] for more info.
834    pub async fn debug_execution_witness_by_block_hash(
835        &self,
836        hash: B256,
837        mode: Option<ExecutionWitnessMode>,
838    ) -> Result<ExecutionWitness, Eth::Error> {
839        let this = self.clone();
840        let block = this
841            .eth_api()
842            .recovered_block(hash.into())
843            .await?
844            .ok_or(EthApiError::HeaderNotFound(hash.into()))?;
845
846        self.debug_execution_witness_for_block(block, mode.unwrap_or_default()).await
847    }
848
849    /// The `debug_executionWitness` method allows for re-execution of a block with the purpose of
850    /// generating an execution witness. The witness comprises of a map of all hashed trie nodes to
851    /// their preimages that were required during the execution of the block, including during state
852    /// root recomputation.
853    pub async fn debug_execution_witness(
854        &self,
855        block_id: BlockId,
856        mode: Option<ExecutionWitnessMode>,
857    ) -> Result<ExecutionWitness, Eth::Error> {
858        let this = self.clone();
859        let block = this
860            .eth_api()
861            .recovered_block(block_id)
862            .await?
863            .ok_or(EthApiError::HeaderNotFound(block_id))?;
864
865        self.debug_execution_witness_for_block(block, mode.unwrap_or_default()).await
866    }
867
868    /// Generates an execution witness, using the given recovered block.
869    pub async fn debug_execution_witness_for_block(
870        &self,
871        block: Arc<RecoveredBlock<ProviderBlock<Eth::Provider>>>,
872        mode: ExecutionWitnessMode,
873    ) -> Result<ExecutionWitness, Eth::Error> {
874        let block_number = block.header().number();
875        self.eth_api()
876            .spawn_with_state_at_block(block.parent_hash(), move |eth_api, mut db| {
877                let output = eth_api
878                    .evm_config()
879                    .executor(&mut db)
880                    .execute(&block)
881                    .map_err(|err| EthApiError::Internal(err.into()))?;
882                let codes = ExecutionWitnessRecord::commit_execution(&mut db, &output.state);
883
884                Ok(ExecutionWitnessRecord::new(&db)
885                    .with_canonical_codes(codes)
886                    .into_execution_witness(
887                        &db.db.inner().0 .0,
888                        eth_api.provider(),
889                        block_number,
890                        mode,
891                    )
892                    .map_err(EthApiError::from)?)
893            })
894            .await
895    }
896
897    /// Returns account information, including the storage root, after replaying the block through
898    /// the transaction at the given index.
899    pub async fn debug_account_at(
900        &self,
901        block_id: BlockId,
902        tx_index: Index,
903        address: Address,
904    ) -> Result<Option<Account>, Eth::Error> {
905        self.replay_block_until(block_id, tx_index, move |db| Self::account(db, address))
906            .await
907            .map(Option::flatten)
908    }
909
910    /// Returns account information after replaying the block through the transaction at the given
911    /// index.
912    pub async fn debug_account_info_at(
913        &self,
914        block_id: BlockId,
915        tx_index: Index,
916        address: Address,
917    ) -> Result<Option<AccountInfo>, Eth::Error> {
918        self.replay_block_until(block_id, tx_index, move |db| Self::account_info(db, address)).await
919    }
920
921    /// Replays a block through the transaction at the given index and calls `f` with the resulting
922    /// state.
923    async fn replay_block_until<F, R>(
924        &self,
925        block_id: BlockId,
926        tx_index: Index,
927        f: F,
928    ) -> Result<Option<R>, Eth::Error>
929    where
930        F: FnOnce(&mut StateCacheDb) -> Result<R, Eth::Error> + Send + 'static,
931        R: Send + 'static,
932    {
933        let block = self
934            .eth_api()
935            .recovered_block(block_id)
936            .await?
937            .ok_or(EthApiError::HeaderNotFound(block_id))?;
938        let tx_index = usize::from(tx_index);
939        let transaction_count = block.transaction_count();
940        if tx_index >= transaction_count {
941            return Err(EthApiError::InvalidParams(format!(
942                "tx_index {tx_index} out of bounds for block with {transaction_count} transactions"
943            ))
944            .into())
945        }
946
947        self.eth_api()
948            .spawn_with_state_at_block(block.parent_hash(), move |eth_api, mut db| {
949                eth_api.replay_block_until(&mut db, &block, tx_index + 1, None)?;
950
951                f(&mut db)
952            })
953            .await
954            .map(Some)
955    }
956
957    /// Retrieves the account's balance, nonce, code hash, and storage root from the given state.
958    fn account(db: &mut StateCacheDb, address: Address) -> Result<Option<Account>, Eth::Error> {
959        let account = db.get_account(&address).map_err(Eth::Error::from_eth_err)?;
960        let Some(account) = account else { return Ok(None) };
961
962        let storage = db.cache.storage.get(&address);
963        let hashed_storage = storage.map_or_else(HashedStorage::default, |s| {
964            HashedStorage::from_plain_storage(s.slots.iter())
965        });
966        let storage_root = if storage.is_some_and(|s| s.wiped) {
967            storage_root_unsorted(
968                hashed_storage.storage.into_iter().filter(|(_, value)| !value.is_zero()),
969            )
970        } else {
971            db.db.inner().storage_root(address, hashed_storage).map_err(Eth::Error::from_eth_err)?
972        };
973
974        Ok(Some(reth_primitives_traits::Account::from(&account).into_trie_account(storage_root)))
975    }
976
977    /// Retrieves the account's balance, nonce, and code from the given state.
978    #[allow(clippy::needless_update)]
979    fn account_info(db: &mut StateCacheDb, address: Address) -> Result<AccountInfo, Eth::Error> {
980        let account =
981            db.get_account(&address).map_err(Eth::Error::from_eth_err)?.unwrap_or_default();
982        let code = if account.is_empty_code_hash() {
983            Default::default()
984        } else if let Some(code) = account.code {
985            code.original_bytes()
986        } else {
987            db.get_code_by_hash(&account.code_hash)
988                .map_err(Eth::Error::from_eth_err)?
989                .original_bytes()
990        };
991
992        Ok(AccountInfo {
993            balance: account.balance,
994            nonce: account.nonce,
995            code,
996            #[cfg(feature = "account-ext")]
997            extension: reth_primitives_traits::AccountExtension::from_shared(
998                account.extension.into_shared(),
999            ),
1000            ..Default::default()
1001        })
1002    }
1003
1004    /// Returns the code associated with a given hash at the specified block ID. If no code is
1005    /// found, it returns None. If no block ID is provided, it defaults to the latest block.
1006    pub async fn debug_code_by_hash(
1007        &self,
1008        hash: B256,
1009        block_id: Option<BlockId>,
1010    ) -> Result<Option<Bytes>, Eth::Error> {
1011        Ok(self
1012            .provider()
1013            .state_by_block_id(block_id.unwrap_or_default())
1014            .map_err(Eth::Error::from_eth_err)?
1015            .bytecode_by_hash(&hash)
1016            .map_err(Eth::Error::from_eth_err)?
1017            .map(|b| b.original_bytes()))
1018    }
1019
1020    /// Returns the state root of the `HashedPostState` on top of the state for the given block with
1021    /// trie updates.
1022    async fn debug_state_root_with_updates(
1023        &self,
1024        hashed_state: HashedPostState,
1025        block_id: Option<BlockId>,
1026    ) -> Result<(B256, TrieUpdates), Eth::Error> {
1027        self.inner
1028            .eth_api
1029            .spawn_blocking_io(move |this| {
1030                let state = this
1031                    .provider()
1032                    .state_by_block_id(block_id.unwrap_or_default())
1033                    .map_err(Eth::Error::from_eth_err)?;
1034                state.state_root_with_updates(hashed_state).map_err(Eth::Error::from_eth_err)
1035            })
1036            .await
1037    }
1038
1039    /// Executes a block and returns the state root after each transaction.
1040    ///
1041    /// The block is either canonical or a bad block the engine rejected. Execution stops at the
1042    /// first transaction that is invalid on top of its predecessors, so the result for a bad block
1043    /// holds the roots before that transaction. A bad block's header must extend its parent like a
1044    /// raw block's, see [`Self::debug_trace_raw_block`].
1045    pub async fn intermediate_roots(&self, block_hash: B256) -> Result<Vec<B256>, Eth::Error> {
1046        let block = match self.eth_api().recovered_block(block_hash.into()).await? {
1047            Some(block) => block,
1048            None => {
1049                let block = self
1050                    .inner
1051                    .bad_block_store
1052                    .get(block_hash)
1053                    .ok_or(EthApiError::HeaderNotFound(block_hash.into()))?
1054                    .block;
1055                // Bad blocks include blocks that failed header validation against their parent.
1056                self.ensure_header_extends_parent(block.header())?;
1057                block
1058            }
1059        };
1060        let evm_env = self.eth_api().evm_env_for_header(block.sealed_block().sealed_header())?;
1061
1062        self.eth_api()
1063            .spawn_with_state_at_block(block.parent_hash(), move |eth_api, mut db| {
1064                let tx_count = block.body().transactions().len();
1065                let mut state = eth_api.apply_pre_execution_changes(&block, &mut db)?;
1066
1067                // the executor borrows the database, so collect each transaction's changes first
1068                // and compute the roots once it is dropped
1069                let mut transaction_states = Vec::with_capacity(tx_count);
1070                let mut executor = eth_api.block_executor(&block, &mut db, evm_env)?;
1071                for tx in block.transactions_recovered() {
1072                    if is_cancelled() {
1073                        return Err(EthApiError::InternalEthError.into())
1074                    }
1075                    let output = match executor.execute_transaction_without_commit(tx) {
1076                        Ok(output) => output,
1077                        Err(BlockExecutionError::Validation(_)) => break,
1078                        Err(err) => return Err(Eth::Error::from_evm_err(err)),
1079                    };
1080                    let mut changes = reth_execution_types::TransactionChanges::default();
1081                    let Ok(()) = output.result().pending_state.visit(&mut changes);
1082                    let mut transaction_state = reth_execution_types::BlockState::default();
1083                    transaction_state.commit(&changes);
1084                    transaction_states.push(transaction_state.into_bundle());
1085                    executor.commit_transaction(output).map_err(Eth::Error::from_evm_err)?;
1086                }
1087                drop(executor);
1088
1089                let mut roots = Vec::with_capacity(tx_count);
1090                for transaction_state in transaction_states {
1091                    if is_cancelled() {
1092                        return Err(EthApiError::InternalEthError.into())
1093                    }
1094                    state.extend(transaction_state);
1095                    let hashed_state = db
1096                        .db
1097                        .inner()
1098                        .hashed_post_state(&state)
1099                        .map_err(Eth::Error::from_eth_err)?;
1100                    let root =
1101                        db.db.inner().state_root(hashed_state).map_err(Eth::Error::from_eth_err)?;
1102                    roots.push(root);
1103                }
1104
1105                Ok(roots)
1106            })
1107            .await
1108    }
1109}
1110
1111/// The bytes a debug trace response has left for the struct logs of the default tracer.
1112///
1113/// The default struct logger writes the JSON of the response as it records, so the response size
1114/// limit bounds what it may record, across every transaction the response traces. Other tracers
1115/// record data that is several times larger or smaller than their JSON, so only the trace byte
1116/// limit of each transaction bounds them.
1117///
1118/// The budget counts the struct logs alone, not the separators between them or the other fields of
1119/// the response, so the server can still reject a response that is slightly over its limit.
1120#[derive(Debug, Clone, Copy)]
1121struct ResponseBudget {
1122    /// Bytes left in the response, `None` for other tracers or without a response size limit.
1123    remaining: Option<usize>,
1124}
1125
1126impl ResponseBudget {
1127    /// Creates the budget of a response traced by `inspector`, whose size is limited to
1128    /// `max_response_size` bytes.
1129    ///
1130    /// Decided by the inspector rather than the request's options, since the inspector also
1131    /// treats an empty tracer name as the default struct logger.
1132    const fn new(inspector: &DebugInspector, max_response_size: Option<usize>) -> Self {
1133        Self {
1134            remaining: if matches!(inspector, DebugInspector::RawDefault(_)) {
1135                max_response_size
1136            } else {
1137                None
1138            },
1139        }
1140    }
1141
1142    /// Returns `limits` with the byte limit lowered to the bytes left in the response.
1143    fn limit(&self, limits: TraceLimits) -> TraceLimits {
1144        let Some(remaining) = self.remaining else { return limits };
1145        limits.set_max_recorded_bytes(Some(
1146            limits.max_recorded_bytes.map_or(remaining, |max| max.min(remaining)),
1147        ))
1148    }
1149
1150    /// Takes the bytes `inspector` recorded for its last transaction from the response.
1151    fn charge(&mut self, inspector: &DebugInspector) {
1152        if let Some(remaining) = &mut self.remaining {
1153            *remaining = remaining.saturating_sub(inspector.recorded_bytes());
1154        }
1155    }
1156}
1157
1158/// Creates the inspector of a trace request.
1159///
1160/// The default struct logger writes its struct logs as JSON, which only
1161/// [`DebugInspector::get_trace`] returns.
1162fn new_debug_inspector(
1163    opts: GethDebugTracingOptions,
1164) -> Result<DebugInspector, DebugInspectorError> {
1165    DebugInspector::new_with_struct_log_mode(opts, StructLogMode::Raw)
1166}
1167
1168/// Sends `result` after `prefix` as the next parts of a streamed block trace.
1169///
1170/// The struct logs of a default trace are already JSON, which can be most of the trace, so they
1171/// are sent as a part of their own instead of being copied into the serialized trace.
1172fn send_trace(
1173    sink: &ResponseSink,
1174    prefix: &[u8],
1175    result: TraceResult<DebugTrace, String>,
1176) -> Result<(), serde_json::Error> {
1177    /// The struct logs are the last field of the frame, and the hex `txHash` that may follow it
1178    /// can't contain this.
1179    const EMPTY_LOGS: &[u8] = br#""structLogs":[]"#;
1180
1181    let TraceResult::Success { result: DebugTrace::RawDefault(mut frame), tx_hash } = result else {
1182        return sink.send_json(prefix, &result)
1183    };
1184    let logs = std::mem::replace(&mut frame.struct_logs, RawValue::from_string("[]".to_owned())?);
1185    let mut head = prefix.to_vec();
1186    serde_json::to_writer(
1187        &mut head,
1188        &TraceResult::<_, String>::Success { result: DebugTrace::RawDefault(frame), tx_hash },
1189    )?;
1190    let Some(at) = head.windows(EMPTY_LOGS.len()).rposition(|field| field == EMPTY_LOGS) else {
1191        return Err(serde_json::Error::io(io::Error::other("struct logs not found in the trace")))
1192    };
1193    // The struct logs replace the empty list at the end of the field.
1194    let end = at + EMPTY_LOGS.len();
1195    let mut head = bytes::Bytes::from(head);
1196    let tail = head.split_off(end);
1197    head.truncate(end - b"[]".len());
1198    let logs = bytes::Bytes::from(Box::<str>::from(logs).into_boxed_bytes());
1199    [head, logs, tail].into_iter().try_for_each(|part| {
1200        sink.send(part).map_err(|_| serde_json::Error::io(io::ErrorKind::BrokenPipe.into()))
1201    })
1202}
1203
1204impl<Eth> DebugApiServer<RpcTxReq<Eth::NetworkTypes>> for DebugApi<Eth>
1205where
1206    Eth: EthTransactions + TraceExt,
1207{
1208    /// Handler for `debug_getRawHeader`
1209    async fn raw_header(&self, block_id: BlockId) -> RpcResult<Bytes> {
1210        let header = match block_id {
1211            BlockId::Hash(hash) => self.provider().header(hash.into()).to_rpc_result()?,
1212            BlockId::Number(number_or_tag) => {
1213                let number = self
1214                    .provider()
1215                    .convert_block_number(number_or_tag)
1216                    .to_rpc_result()?
1217                    .ok_or(EthApiError::HeaderNotFound(block_id))?;
1218                self.provider().header_by_number(number).to_rpc_result()?
1219            }
1220        }
1221        .ok_or(EthApiError::HeaderNotFound(block_id))?;
1222
1223        let mut res = Vec::new();
1224        header.encode(&mut res);
1225        Ok(res.into())
1226    }
1227
1228    /// Handler for `debug_getRawBlock`
1229    async fn raw_block(&self, block_id: BlockId) -> RpcResult<Bytes> {
1230        let block = self
1231            .provider()
1232            .block_by_id(block_id)
1233            .to_rpc_result()?
1234            .ok_or(EthApiError::HeaderNotFound(block_id))?;
1235        let mut res = Vec::new();
1236        block.encode(&mut res);
1237        Ok(res.into())
1238    }
1239
1240    /// Handler for `debug_getRawBlockAccessList`
1241    async fn raw_block_access_list(&self, block_id: BlockId) -> RpcResult<Bytes> {
1242        self.eth_api()
1243            .get_raw_block_access_list(block_id)
1244            .await
1245            .map_err(Into::into)?
1246            .ok_or_else(|| EthApiError::HeaderNotFound(block_id).into())
1247    }
1248
1249    /// Handler for `debug_getRawTransaction`
1250    ///
1251    /// If this is a pooled EIP-4844 transaction, the blob sidecar is included.
1252    ///
1253    /// Returns the bytes of the transaction for the given hash.
1254    async fn raw_transaction(&self, hash: B256) -> RpcResult<Option<Bytes>> {
1255        self.eth_api().raw_transaction_by_hash(hash).await.map_err(Into::into)
1256    }
1257
1258    /// Handler for `debug_getRawTransactions`
1259    /// Returns the bytes of the transaction for the given hash.
1260    async fn raw_transactions(&self, block_id: BlockId) -> RpcResult<Vec<Bytes>> {
1261        let block: RecoveredBlock<BlockTy<Eth::Primitives>> = self
1262            .provider()
1263            .block_with_senders_by_id(block_id, TransactionVariant::NoHash)
1264            .to_rpc_result()?
1265            .unwrap_or_default();
1266        Ok(block.into_transactions_recovered().map(|tx| tx.encoded_2718().into()).collect())
1267    }
1268
1269    /// Handler for `debug_getRawReceipts`
1270    async fn raw_receipts(&self, block_id: BlockId) -> RpcResult<Vec<Bytes>> {
1271        Ok(self
1272            .provider()
1273            .receipts_by_block_id(block_id)
1274            .to_rpc_result()?
1275            .ok_or(EthApiError::HeaderNotFound(block_id))?
1276            .into_iter()
1277            .map(|receipt| ReceiptWithBloom::from(receipt).encoded_2718().into())
1278            .collect())
1279    }
1280
1281    /// Handler for `debug_getBadBlocks`
1282    async fn bad_blocks(&self) -> RpcResult<Vec<serde_json::Value>> {
1283        let entries = self.inner.bad_block_store.all();
1284        let mut bad_blocks = Vec::with_capacity(entries.len());
1285
1286        #[derive(Serialize, Deserialize)]
1287        struct BadBlockSerde<T> {
1288            block: T,
1289            hash: B256,
1290            rlp: Bytes,
1291            reason: String,
1292        }
1293
1294        for entry in entries {
1295            let rlp = Bytes::from(alloy_rlp::encode(entry.block.sealed_block()));
1296            let hash = entry.block.hash();
1297
1298            let block = entry
1299                .block
1300                .clone_into_rpc_block(
1301                    BlockTransactionsKind::Full,
1302                    |tx, tx_info| self.eth_api().converter().fill(tx, tx_info),
1303                    |header, block_size| {
1304                        self.eth_api().converter().convert_header(header, Some(block_size))
1305                    },
1306                )
1307                .map_err(|err| Eth::Error::from(err).into())?;
1308
1309            let bad_block =
1310                serde_json::to_value(BadBlockSerde { block, hash, rlp, reason: entry.reason })
1311                    .map_err(|err| EthApiError::other(internal_rpc_err(err.to_string())))?;
1312
1313            bad_blocks.push(bad_block);
1314        }
1315
1316        Ok(bad_blocks)
1317    }
1318
1319    /// Handler for `debug_clearTxpool`
1320    async fn debug_clear_txpool(&self) -> RpcResult<()> {
1321        let pool = self.eth_api().pool();
1322        let all_hashes = pool.all_transaction_hashes();
1323        let _ = pool.remove_transactions(all_hashes);
1324        Ok(())
1325    }
1326
1327    /// Handler for `debug_subscribe("traceChain", ...)`.
1328    async fn debug_subscribe(
1329        &self,
1330        pending: PendingSubscriptionSink,
1331        subscription: String,
1332        start_exclusive: BlockNumberOrTag,
1333        end_inclusive: BlockNumberOrTag,
1334        opts: Option<GethDebugTracingOptions>,
1335    ) -> jsonrpsee::core::SubscriptionResult {
1336        if subscription != "traceChain" {
1337            pending
1338                .reject(EthApiError::InvalidParams(format!(
1339                    "unsupported debug subscription: {subscription}"
1340                )))
1341                .await;
1342            return Ok(())
1343        }
1344
1345        let start_id = BlockId::Number(start_exclusive);
1346        let start = match self.eth_api().recovered_block(start_id).await {
1347            Ok(Some(block)) => block,
1348            Ok(None) => {
1349                pending.reject(EthApiError::TracingBlockNotFound(start_id)).await;
1350                return Ok(())
1351            }
1352            Err(err) => {
1353                pending.reject(err).await;
1354                return Ok(())
1355            }
1356        };
1357        let end_id = BlockId::Number(end_inclusive);
1358        let end = match self.eth_api().recovered_block(end_id).await {
1359            Ok(Some(block)) => block,
1360            Ok(None) => {
1361                pending.reject(EthApiError::TracingBlockNotFound(end_id)).await;
1362                return Ok(())
1363            }
1364            Err(err) => {
1365                pending.reject(err).await;
1366                return Ok(())
1367            }
1368        };
1369
1370        if start.number() >= end.number() {
1371            pending
1372                .reject(EthApiError::InvalidParams(format!(
1373                    "end block (#{}) needs to come after start block (#{})",
1374                    end.number(),
1375                    start.number()
1376                )))
1377                .await;
1378            return Ok(())
1379        }
1380
1381        let sink = pending.accept().await?;
1382        let this = self.clone();
1383        let task_spawner = self.inner.task_spawner.clone();
1384        task_spawner.spawn_task(async move {
1385            let end_number = end.number();
1386            let opts = opts.unwrap_or_default();
1387
1388            for number in (start.number() + 1)..=end_number {
1389                if sink.is_closed() {
1390                    break
1391                }
1392
1393                let block_id = BlockId::number(number);
1394                let block = match this.eth_api().recovered_block(block_id).await {
1395                    Ok(Some(block)) => block,
1396                    Ok(None) => {
1397                        tracing::warn!(target: "rpc::debug", %number, "Chain tracing block not found");
1398                        break
1399                    }
1400                    Err(err) => {
1401                        tracing::warn!(target: "rpc::debug", %number, %err, "Failed to load chain tracing block");
1402                        break
1403                    }
1404                };
1405                let permit = tokio::select! {
1406                    _ = sink.closed() => break,
1407                    permit = this.acquire_trace_permit() => match permit {
1408                        Ok(permit) => permit,
1409                        Err(err) => {
1410                            tracing::debug!(target: "rpc::debug", %err, "Failed to acquire trace permit");
1411                            break
1412                        }
1413                    }
1414                };
1415                if sink.is_closed() {
1416                    break
1417                }
1418                let traces = match this.trace_chain_block(block.clone(), opts.clone()).await {
1419                    Ok(traces) => traces,
1420                    Err(err) => {
1421                        tracing::warn!(target: "rpc::debug", %number, %err, "Failed to trace chain block");
1422                        break
1423                    }
1424                };
1425                drop(permit);
1426
1427                if traces.is_empty() && number != end_number {
1428                    continue
1429                }
1430                let result =
1431                    ChainBlockTraces { block: U256::from(number), hash: block.hash(), traces };
1432                let message = match SubscriptionMessage::new(
1433                    sink.method_name(),
1434                    sink.subscription_id(),
1435                    &result,
1436                ) {
1437                    Ok(message) => message,
1438                    Err(err) => {
1439                        tracing::warn!(target: "rpc::debug", %number, %err, "Failed to serialize chain trace");
1440                        break
1441                    }
1442                };
1443                if sink.send(message).await.is_err() {
1444                    break
1445                }
1446            }
1447
1448            // Dropping jsonrpsee's final sink unregisters the subscription without notifying the
1449            // client that this finite stream completed. Retain it so the subscription remains
1450            // explicitly unsubscribable until the client unsubscribes or disconnects.
1451            sink.closed().await;
1452        });
1453
1454        Ok(())
1455    }
1456
1457    /// Handler for `debug_traceBlock`
1458    async fn debug_trace_block(
1459        &self,
1460        rlp_block: Bytes,
1461        opts: Option<GethDebugTracingOptions>,
1462    ) -> RpcResult<Vec<TraceResult<DebugTrace, String>>> {
1463        Self::debug_trace_raw_block(self, rlp_block, opts.unwrap_or_default())
1464            .await
1465            .map_err(Into::into)
1466    }
1467
1468    /// Handler for `debug_traceBlockByHash`
1469    async fn debug_trace_block_by_hash(
1470        &self,
1471        block: B256,
1472        opts: Option<GethDebugTracingOptions>,
1473    ) -> RpcResult<ResponseStream> {
1474        self.debug_trace_block_stream(block.into(), opts.unwrap_or_default())
1475            .await
1476            .map_err(Into::into)
1477    }
1478
1479    /// Handler for `debug_traceBlockByNumber`
1480    async fn debug_trace_block_by_number(
1481        &self,
1482        block: BlockNumberOrTag,
1483        opts: Option<GethDebugTracingOptions>,
1484    ) -> RpcResult<ResponseStream> {
1485        self.debug_trace_block_stream(block.into(), opts.unwrap_or_default())
1486            .await
1487            .map_err(Into::into)
1488    }
1489
1490    /// Handler for `debug_traceTransaction`
1491    async fn debug_trace_transaction(
1492        &self,
1493        tx_hash: B256,
1494        opts: Option<GethDebugTracingOptions>,
1495    ) -> RpcResult<DebugTrace> {
1496        let _permit = self.acquire_trace_permit().await;
1497        Self::debug_trace_transaction(self, tx_hash, opts.unwrap_or_default())
1498            .await
1499            .map_err(Into::into)
1500    }
1501
1502    /// Handler for `debug_traceCall`
1503    async fn debug_trace_call(
1504        &self,
1505        request: RpcTxReq<Eth::NetworkTypes>,
1506        block_id: Option<BlockId>,
1507        opts: Option<GethDebugTracingCallOptions>,
1508    ) -> RpcResult<DebugTrace> {
1509        let _permit = self.acquire_trace_permit().await;
1510        Self::debug_trace_call(self, request, block_id, opts.unwrap_or_default())
1511            .await
1512            .map_err(Into::into)
1513    }
1514
1515    async fn debug_trace_call_many(
1516        &self,
1517        bundles: BoundedCallMany<Vec<Bundle<RpcTxReq<Eth::NetworkTypes>>>>,
1518        state_context: Option<StateContext>,
1519        opts: Option<GethDebugTracingCallOptions>,
1520    ) -> RpcResult<Vec<Vec<DebugTrace>>> {
1521        let _permit = self.acquire_trace_permit().await;
1522        Self::debug_trace_call_many(self, bundles.0, state_context, opts).await.map_err(Into::into)
1523    }
1524
1525    /// Handler for `debug_executionWitness`
1526    async fn debug_execution_witness(
1527        &self,
1528        block: BlockId,
1529        mode: Option<ExecutionWitnessMode>,
1530    ) -> RpcResult<ExecutionWitness> {
1531        let _permit = self.acquire_trace_permit().await;
1532        Self::debug_execution_witness(self, block, mode).await.map_err(Into::into)
1533    }
1534
1535    /// Handler for `debug_executionWitnessByBlockHash`
1536    async fn debug_execution_witness_by_block_hash(
1537        &self,
1538        hash: B256,
1539        mode: Option<ExecutionWitnessMode>,
1540    ) -> RpcResult<ExecutionWitness> {
1541        let _permit = self.acquire_trace_permit().await;
1542        Self::debug_execution_witness_by_block_hash(self, hash, mode).await.map_err(Into::into)
1543    }
1544
1545    /// Handler for `debug_accountAt`
1546    async fn debug_account_at(
1547        &self,
1548        block_id: BlockId,
1549        tx_index: Index,
1550        address: Address,
1551    ) -> RpcResult<Option<Account>> {
1552        let _permit = self.acquire_trace_permit().await;
1553        Self::debug_account_at(self, block_id, tx_index, address).await.map_err(Into::into)
1554    }
1555
1556    /// Handler for `debug_accountInfoAt`
1557    async fn debug_account_info_at(
1558        &self,
1559        block_id: BlockId,
1560        tx_index: Index,
1561        address: Address,
1562    ) -> RpcResult<Option<AccountInfo>> {
1563        let _permit = self.acquire_trace_permit().await;
1564        Self::debug_account_info_at(self, block_id, tx_index, address).await.map_err(Into::into)
1565    }
1566
1567    async fn debug_account_range(
1568        &self,
1569        _block_number: BlockNumberOrTag,
1570        _start: Bytes,
1571        _max_results: u64,
1572        _nocode: bool,
1573        _nostorage: bool,
1574        _incompletes: bool,
1575    ) -> RpcResult<()> {
1576        Ok(())
1577    }
1578
1579    async fn debug_chaindb_compact(&self) -> RpcResult<()> {
1580        Ok(())
1581    }
1582
1583    async fn debug_chain_config(&self) -> RpcResult<ChainConfig> {
1584        Ok(crate::chain_config::chain_config(&*self.provider().chain_spec()))
1585    }
1586
1587    async fn debug_chaindb_property(&self, _property: String) -> RpcResult<()> {
1588        Ok(())
1589    }
1590
1591    async fn debug_code_by_hash(
1592        &self,
1593        hash: B256,
1594        block_id: Option<BlockId>,
1595    ) -> RpcResult<Option<Bytes>> {
1596        Self::debug_code_by_hash(self, hash, block_id).await.map_err(Into::into)
1597    }
1598
1599    async fn debug_db_ancient(&self, _kind: String, _number: u64) -> RpcResult<()> {
1600        Ok(())
1601    }
1602
1603    async fn debug_db_ancients(&self) -> RpcResult<()> {
1604        Ok(())
1605    }
1606
1607    /// `debug_db_get` - database key lookup
1608    ///
1609    /// Currently supported:
1610    /// * Contract bytecode associated with a code hash. The key format is: `<0x63><code_hash>`
1611    ///     * Prefix byte: 0x63 (required)
1612    ///     * Code hash: 32 bytes
1613    ///
1614    ///   Must be provided as either:
1615    ///     * Hex string: "0x63..." (66 hex characters after 0x)
1616    ///     * Raw byte string: raw byte string (33 bytes)
1617    ///
1618    ///   See Geth impl: <https://github.com/ethereum/go-ethereum/blob/737ffd1bf0cbee378d0111a5b17ae4724fb2216c/core/rawdb/schema.go#L120>
1619    async fn debug_db_get(&self, key: String) -> RpcResult<Option<Bytes>> {
1620        let key_bytes = if key.starts_with("0x") {
1621            decode(&key).map_err(|_| EthApiError::InvalidParams("Invalid hex key".to_string()))?
1622        } else {
1623            key.into_bytes()
1624        };
1625
1626        if key_bytes.len() != 33 {
1627            return Err(EthApiError::InvalidParams(format!(
1628                "Key must be 33 bytes, got {}",
1629                key_bytes.len()
1630            ))
1631            .into());
1632        }
1633        if key_bytes[0] != 0x63 {
1634            return Err(EthApiError::InvalidParams("Key prefix must be 0x63".to_string()).into());
1635        }
1636
1637        let code_hash = B256::from_slice(&key_bytes[1..33]);
1638
1639        // No block ID is provided, so it defaults to the latest block
1640        self.debug_code_by_hash(code_hash, None).await.map_err(Into::into)
1641    }
1642
1643    async fn debug_dump_block(&self, _number: BlockId) -> RpcResult<()> {
1644        Ok(())
1645    }
1646
1647    async fn debug_free_os_memory(&self) -> RpcResult<()> {
1648        Ok(())
1649    }
1650
1651    async fn debug_gc_stats(&self) -> RpcResult<()> {
1652        Ok(())
1653    }
1654
1655    async fn debug_get_accessible_state(
1656        &self,
1657        _from: BlockNumberOrTag,
1658        _to: BlockNumberOrTag,
1659    ) -> RpcResult<()> {
1660        Ok(())
1661    }
1662
1663    async fn debug_get_modified_accounts_by_hash(
1664        &self,
1665        _start_hash: B256,
1666        _end_hash: B256,
1667    ) -> RpcResult<()> {
1668        Ok(())
1669    }
1670
1671    async fn debug_get_modified_accounts_by_number(
1672        &self,
1673        _start_number: u64,
1674        _end_number: u64,
1675    ) -> RpcResult<()> {
1676        Ok(())
1677    }
1678
1679    async fn debug_intermediate_roots(
1680        &self,
1681        block_hash: B256,
1682        _opts: Option<GethDebugTracingCallOptions>,
1683    ) -> RpcResult<Vec<B256>> {
1684        let _permit = self.acquire_trace_permit().await;
1685        self.intermediate_roots(block_hash).await.map_err(Into::into)
1686    }
1687
1688    async fn debug_mem_stats(&self) -> RpcResult<()> {
1689        Ok(())
1690    }
1691
1692    async fn debug_preimage(&self, _hash: B256) -> RpcResult<()> {
1693        Ok(())
1694    }
1695
1696    async fn debug_print_block(&self, _number: u64) -> RpcResult<()> {
1697        Ok(())
1698    }
1699
1700    async fn debug_seed_hash(&self, _number: u64) -> RpcResult<B256> {
1701        Ok(Default::default())
1702    }
1703
1704    async fn debug_set_gc_percent(&self, _v: i32) -> RpcResult<()> {
1705        Ok(())
1706    }
1707
1708    async fn debug_set_head(&self, _number: U64) -> RpcResult<()> {
1709        Ok(())
1710    }
1711
1712    async fn debug_set_trie_flush_interval(&self, _interval: String) -> RpcResult<()> {
1713        Ok(())
1714    }
1715
1716    async fn debug_standard_trace_bad_block_to_file(
1717        &self,
1718        _block: BlockNumberOrTag,
1719        _opts: Option<GethDebugTracingCallOptions>,
1720    ) -> RpcResult<()> {
1721        Ok(())
1722    }
1723
1724    async fn debug_standard_trace_block_to_file(
1725        &self,
1726        _block: BlockNumberOrTag,
1727        _opts: Option<GethDebugTracingCallOptions>,
1728    ) -> RpcResult<()> {
1729        Ok(())
1730    }
1731
1732    async fn debug_state_root_with_updates(
1733        &self,
1734        hashed_state: HashedPostState,
1735        block_id: Option<BlockId>,
1736    ) -> RpcResult<(B256, TrieUpdates)> {
1737        Self::debug_state_root_with_updates(self, hashed_state, block_id).await.map_err(Into::into)
1738    }
1739
1740    async fn debug_storage_range_at(
1741        &self,
1742        _block_hash: B256,
1743        _tx_idx: usize,
1744        _contract_address: Address,
1745        _key_start: B256,
1746        _max_result: u64,
1747    ) -> RpcResult<()> {
1748        Ok(())
1749    }
1750
1751    async fn debug_trace_bad_block(
1752        &self,
1753        block_hash: B256,
1754        opts: Option<GethDebugTracingCallOptions>,
1755    ) -> RpcResult<Vec<TraceResult<DebugTrace, String>>> {
1756        let _permit = self.acquire_trace_permit().await;
1757        let entry = self
1758            .inner
1759            .bad_block_store
1760            .get(block_hash)
1761            .ok_or_else(|| internal_rpc_err("bad block not found in cache"))?;
1762        // Bad blocks include blocks that failed header validation against their parent.
1763        self.ensure_header_extends_parent(entry.block.header()).map_err(Into::into)?;
1764
1765        let evm_env = self
1766            .eth_api()
1767            .evm_config()
1768            .evm_env(entry.block.header())
1769            .map_err(RethError::other)
1770            .to_rpc_result()?;
1771
1772        let opts = opts.map(|o| o.tracing_options).unwrap_or_default();
1773        self.trace_block(entry.block.clone(), evm_env, opts, None).await.map_err(Into::into)
1774    }
1775}
1776
1777impl<Eth: RpcNodeCore> std::fmt::Debug for DebugApi<Eth> {
1778    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1779        f.debug_struct("DebugApi").finish_non_exhaustive()
1780    }
1781}
1782
1783impl<Eth: RpcNodeCore> Clone for DebugApi<Eth> {
1784    fn clone(&self) -> Self {
1785        Self { inner: Arc::clone(&self.inner) }
1786    }
1787}
1788
1789struct DebugApiInner<Eth: RpcNodeCore> {
1790    /// The implementation of `eth` API
1791    eth_api: Eth,
1792    // restrict the number of concurrent calls to blocking calls
1793    blocking_task_guard: BlockingTaskGuard,
1794    /// Spawns long-running subscription tasks.
1795    task_spawner: Runtime,
1796    /// Cache for bad blocks.
1797    bad_block_store: BadBlockStore<BlockTy<Eth::Primitives>>,
1798}
1799
1800/// A bounded, deduplicating store of recently observed bad blocks.
1801#[derive(Clone, Debug)]
1802struct BadBlockStore<B: BlockTrait> {
1803    inner: Arc<RwLock<VecDeque<BadBlockEntry<B>>>>,
1804    limit: usize,
1805}
1806
1807/// A cached bad block paired with the reason it was rejected.
1808#[derive(Clone, Debug)]
1809struct BadBlockEntry<B: BlockTrait> {
1810    block: Arc<RecoveredBlock<B>>,
1811    reason: String,
1812}
1813
1814impl<B: BlockTrait> BadBlockStore<B> {
1815    /// Creates a new store with the given capacity.
1816    fn new(limit: usize) -> Self {
1817        Self { inner: Arc::new(RwLock::new(VecDeque::with_capacity(limit))), limit }
1818    }
1819
1820    /// Inserts a recovered block with its rejection reason, keeping only the most recent `limit`
1821    /// entries and deduplicating by block hash.
1822    fn insert(&self, block: RecoveredBlock<B>, reason: String) {
1823        let hash = block.hash();
1824        let mut guard = self.inner.write();
1825
1826        // skip if we already recorded this bad block , and keep original ordering
1827        if guard.iter().any(|entry| entry.block.hash() == hash) {
1828            return;
1829        }
1830        guard.push_back(BadBlockEntry { block: Arc::new(block), reason });
1831
1832        while guard.len() > self.limit {
1833            guard.pop_front();
1834        }
1835    }
1836
1837    /// Returns all cached bad block entries ordered from newest to oldest.
1838    fn all(&self) -> Vec<BadBlockEntry<B>> {
1839        let guard = self.inner.read();
1840        guard.iter().rev().cloned().collect()
1841    }
1842
1843    /// Returns the bad block entry with the given hash, if cached.
1844    fn get(&self, hash: B256) -> Option<BadBlockEntry<B>> {
1845        let guard = self.inner.read();
1846        guard.iter().find(|entry| entry.block.hash() == hash).cloned()
1847    }
1848}
1849
1850impl<B: BlockTrait> Default for BadBlockStore<B> {
1851    fn default() -> Self {
1852        Self::new(64)
1853    }
1854}
1855
1856/// Timeout of tracing a block supplied by the caller, whose work no consensus rule bounds.
1857const RAW_BLOCK_TRACE_TIMEOUT: Duration = Duration::from_secs(30);
1858
1859/// Default timeout of a JS tracer, matching geth.
1860#[cfg(feature = "js-tracer")]
1861const DEFAULT_JS_TRACER_TIMEOUT: Duration = Duration::from_secs(5);
1862
1863/// Returns whether `tracer` is a JS tracer or a mux tracer that holds one, at any depth.
1864#[cfg(feature = "js-tracer")]
1865fn runs_js_tracer(tracer: &GethDebugTracerType, config: &GethDebugTracerConfig) -> bool {
1866    match tracer {
1867        GethDebugTracerType::JsTracer(_) => true,
1868        GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::MuxTracer) => {
1869            config.clone().into_mux_config().is_ok_and(|mux| {
1870                mux.0.iter().any(|(tracer, config)| {
1871                    runs_js_tracer(tracer, &config.clone().unwrap_or_default())
1872                })
1873            })
1874        }
1875        GethDebugTracerType::BuiltInTracer(_) => false,
1876    }
1877}
1878
1879/// Interrupts a JS tracer once its request is dropped or its timeout expires.
1880///
1881/// Built-in tracers can't be interrupted, so for them this does nothing.
1882#[derive(Clone, Debug, Default)]
1883struct JsTraceInterrupt {
1884    #[cfg(feature = "js-tracer")]
1885    js: Option<(JsInspectorInterrupt, Duration)>,
1886}
1887
1888impl JsTraceInterrupt {
1889    /// Creates an interrupt if `opts` selects a JS tracer, using its `timeout` or geth's default.
1890    #[cfg_attr(
1891        not(feature = "js-tracer"),
1892        expect(unused_variables, reason = "only JS tracers can be interrupted")
1893    )]
1894    fn new(opts: &GethDebugTracingOptions) -> Result<Self, EthApiError> {
1895        #[cfg(feature = "js-tracer")]
1896        if let Some(tracer) = &opts.tracer &&
1897            runs_js_tracer(tracer, &opts.tracer_config)
1898        {
1899            let timeout = match &opts.timeout {
1900                Some(timeout) => {
1901                    SpanParser::new().parse_unsigned_duration(timeout).map_err(|err| {
1902                        EthApiError::InvalidParams(format!(
1903                            "invalid tracer timeout {timeout:?}: {err}"
1904                        ))
1905                    })?
1906                }
1907                None => DEFAULT_JS_TRACER_TIMEOUT,
1908            };
1909            return Ok(Self { js: Some((JsInspectorInterrupt::new(), timeout)) })
1910        }
1911        Ok(Self::default())
1912    }
1913
1914    /// Lets this interrupt stop the JS tracers of `inspector`, including those in a mux tracer.
1915    #[cfg_attr(
1916        not(feature = "js-tracer"),
1917        expect(
1918            unused_mut,
1919            clippy::missing_const_for_fn,
1920            reason = "only JS tracers can be interrupted"
1921        )
1922    )]
1923    fn attach(&self, mut inspector: DebugInspector) -> DebugInspector {
1924        #[cfg(feature = "js-tracer")]
1925        if let Some((interrupt, _)) = &self.js {
1926            inspector.set_js_interrupt(interrupt);
1927        }
1928        inspector
1929    }
1930
1931    /// Awaits `trace`, interrupting the tracer if the returned future is dropped or the timeout
1932    /// expires.
1933    ///
1934    /// The interrupt is armed before the future is first polled, so dropping it unpolled still
1935    /// stops a trace that is already running on a blocking task.
1936    #[cfg_attr(
1937        not(feature = "js-tracer"),
1938        expect(
1939            clippy::manual_async_fn,
1940            clippy::redundant_async_block,
1941            reason = "only JS tracers can be interrupted"
1942        )
1943    )]
1944    fn run<T, E: FromEthApiError>(
1945        &self,
1946        trace: impl Future<Output = Result<T, E>>,
1947    ) -> impl Future<Output = Result<T, E>> {
1948        #[cfg(feature = "js-tracer")]
1949        let js = self.js.as_ref().map(|(interrupt, timeout)| (interrupt.drop_guard(), *timeout));
1950        async move {
1951            #[cfg(feature = "js-tracer")]
1952            if let Some((_interrupt_on_drop, timeout)) = js {
1953                return tokio::time::timeout(timeout, trace)
1954                    .await
1955                    .map_err(|_| E::from_eth_err(EthApiError::ExecutionTimedOut(timeout)))?
1956            }
1957            trace.await
1958        }
1959    }
1960}
1961
1962/// The message of a `traceChain` subscription.
1963///
1964/// Serializes like a
1965/// [`ChainBlockTraceResult`](alloy_rpc_types_trace::geth::ChainBlockTraceResult), whose traces
1966/// can't hold raw struct logs.
1967#[derive(Debug, Serialize)]
1968struct ChainBlockTraces {
1969    block: U256,
1970    hash: B256,
1971    traces: Vec<Option<TraceResult<DebugTrace, String>>>,
1972}
1973
1974#[cfg(test)]
1975mod tests {
1976    use super::*;
1977    use crate::{eth::helpers::types::EthRpcConverter, EthApi};
1978    use alloy_consensus::{Header, TxLegacy};
1979    use alloy_genesis::{Genesis, GenesisAccount};
1980    use alloy_primitives::{bytes, keccak256, TxKind, U256};
1981    use alloy_rpc_types_eth::TransactionRequest;
1982    use alloy_rpc_types_trace::geth::{CallConfig, GethTrace};
1983    use evm2::{bytecode::Bytecode, evm::AccountInfo};
1984    use evm2_inspectors::tracing::RawDefaultFrame;
1985    use jsonrpsee::{types::ErrorCode, RpcModule};
1986    use reth_chainspec::{ChainSpec, ChainSpecBuilder};
1987    use reth_db_api::{tables, transaction::DbTxMut};
1988    use reth_db_common::init::init_genesis;
1989    use reth_ethereum_primitives::{Block, BlockBody, EthPrimitives, Transaction};
1990    use reth_evm_ethereum::EthEvmConfig;
1991    use reth_network_api::noop::NoopNetwork;
1992    use reth_primitives_traits::{SealedBlock, StorageEntry};
1993    use reth_provider::test_utils::{
1994        create_test_provider_factory, create_test_provider_factory_with_chain_spec,
1995        ExtendedAccount, MockEthProvider, NoopProvider,
1996    };
1997    use reth_rpc_eth_api::{
1998        helpers::GetBlockAccessList,
1999        node::{RpcNodeCoreAdapter, RpcNodeCoreExt},
2000        EthApiServer,
2001    };
2002    use reth_testing_utils::generators::{self, generate_key, sign_tx_with_key_pair};
2003    use reth_transaction_pool::test_utils::{testing_pool, TestPool};
2004    use reth_trie_common::bundle_state::{AccountStatus, BundleAccount, BundleState, StorageSlot};
2005
2006    #[reth_concurrency::test]
2007    async fn trace_call_out_of_range_block_error() {
2008        let eth_api = EthApi::<_, EthRpcConverter<ChainSpec>>::builder(
2009            NoopProvider::default(),
2010            testing_pool(),
2011            NoopNetwork::default(),
2012            EthEvmConfig::mainnet(),
2013        )
2014        .build();
2015        let debug_api = DebugApi::new(
2016            eth_api.clone(),
2017            BlockingTaskGuard::new(1),
2018            &Runtime::test(),
2019            futures::stream::empty(),
2020        );
2021        let block_id = BlockId::number(0xfffffffff);
2022        for tx_index in [None, Some(0)] {
2023            let mut opts: GethDebugTracingCallOptions =
2024                serde_json::from_value(serde_json::json!({ "tracer": "callTracer" })).unwrap();
2025            opts.tx_index = tx_index;
2026            let err = DebugApiServer::debug_trace_call(
2027                &debug_api,
2028                Default::default(),
2029                Some(block_id),
2030                Some(opts),
2031            )
2032            .await
2033            .unwrap_err();
2034            assert_eq!(err.code(), -32000);
2035            assert!(err.message().contains("not found"));
2036        }
2037
2038        let err = EthApiServer::call(&eth_api, Default::default(), Some(block_id), None, None)
2039            .await
2040            .unwrap_err();
2041        assert_eq!(err.code(), -32001);
2042    }
2043
2044    #[reth_concurrency::test]
2045    async fn struct_logs_halt_past_byte_limit() {
2046        let provider = MockEthProvider::default();
2047        let target = Address::with_last_byte(0x42);
2048        // JUMPDEST PUSH1 0 JUMP: loops until out of gas, recording steps but no memory.
2049        provider.add_account(
2050            target,
2051            ExtendedAccount::new(0, U256::ZERO).with_bytecode(bytes!("5b600056")),
2052        );
2053        let header = Header { number: 1, gas_limit: 30_000_000, ..Default::default() };
2054        provider.add_block(header.hash_slow(), Block { header, body: BlockBody::default() });
2055        let call = TransactionRequest::default().to(target).gas_limit(1_000_000);
2056
2057        for max_trace_bytes in [None, Some(1 << 16)] {
2058            let eth_api = EthApi::<_, EthRpcConverter<ChainSpec>>::builder(
2059                provider.clone(),
2060                testing_pool(),
2061                NoopNetwork::default(),
2062                EthEvmConfig::new(provider.chain_spec()),
2063            )
2064            .max_trace_bytes(max_trace_bytes)
2065            .build();
2066            let debug_api = DebugApi::new(
2067                eth_api,
2068                BlockingTaskGuard::new(1),
2069                &Runtime::test(),
2070                futures::stream::empty(),
2071            );
2072            let result = debug_api.debug_trace_call(call.clone(), None, Default::default()).await;
2073            match max_trace_bytes {
2074                None => {
2075                    let DebugTrace::RawDefault(frame) = result.unwrap() else {
2076                        panic!("expected raw struct logs")
2077                    };
2078                    let logs =
2079                        serde_json::from_str::<Vec<serde_json::Value>>(frame.struct_logs.get());
2080                    assert!(logs.unwrap().len() > 100_000);
2081                }
2082                Some(_) => assert_eq!(
2083                    result.unwrap_err().to_string(),
2084                    "fatal error: trace recorded byte limit exceeded"
2085                ),
2086            }
2087        }
2088    }
2089
2090    #[reth_concurrency::test]
2091    async fn struct_logs_share_response_size_limit() {
2092        let provider = MockEthProvider::default();
2093        let target = Address::with_last_byte(0x42);
2094        // JUMPDEST PUSH1 0 JUMP: loops until out of gas, recording steps but no memory.
2095        provider.add_account(
2096            target,
2097            ExtendedAccount::new(0, U256::ZERO).with_bytecode(bytes!("5b600056")),
2098        );
2099        // The block holds two transactions that call the loop.
2100        let key = generate_key(&mut generators::rng());
2101        let transactions = (0..2)
2102            .map(|nonce| {
2103                let tx = TxLegacy {
2104                    nonce,
2105                    gas_limit: 100_000,
2106                    to: TxKind::Call(target),
2107                    ..Default::default()
2108                };
2109                sign_tx_with_key_pair(key, Transaction::Legacy(tx))
2110            })
2111            .collect::<Vec<_>>();
2112        let tx_hash = *transactions[1].tx_hash();
2113        let header = Header { number: 1, gas_limit: 30_000_000, ..Default::default() };
2114        let block_hash = header.hash_slow();
2115        let block = Block { header, body: BlockBody { transactions, ..Default::default() } };
2116        provider.add_block(block_hash, block.clone());
2117        let call = TransactionRequest::default().to(target).gas_limit(100_000);
2118        let debug_api = |max_response_size| {
2119            let eth_api = EthApi::<_, EthRpcConverter<ChainSpec>>::builder(
2120                provider.clone(),
2121                testing_pool(),
2122                NoopNetwork::default(),
2123                EthEvmConfig::new(provider.chain_spec()),
2124            )
2125            .max_response_size(max_response_size)
2126            .build();
2127            DebugApi::new(
2128                eth_api,
2129                BlockingTaskGuard::new(1),
2130                &Runtime::test(),
2131                futures::stream::empty(),
2132            )
2133        };
2134        let exceeded = "fatal error: trace recorded byte limit exceeded";
2135
2136        let DebugTrace::RawDefault(frame) =
2137            debug_api(None).debug_trace_call(call.clone(), None, Default::default()).await.unwrap()
2138        else {
2139            panic!("expected raw struct logs")
2140        };
2141        let logs_len = frame.struct_logs.get().len();
2142
2143        // The struct logs of one call fit in the response, those of two do not.
2144        let api = debug_api(Some(logs_len + logs_len / 2));
2145        api.debug_trace_call(call.clone(), None, Default::default()).await.unwrap();
2146        let bundles =
2147            vec![Bundle { transactions: vec![call.clone(), call.clone()], block_override: None }];
2148        let err = api.debug_trace_call_many(bundles, None, None).await.unwrap_err();
2149        assert_eq!(err.to_string(), exceeded);
2150        // Neither do those of the two transactions of the block, unless it is traced for a
2151        // `traceChain` notification, which the response size limit does not bound.
2152        let block_err =
2153            format!("internal EVM error occurred when executing transaction {tx_hash}: {exceeded}");
2154        let err = api.debug_trace_block(block_hash.into(), Default::default()).await.unwrap_err();
2155        assert_eq!(err.to_string(), block_err);
2156        let block = Arc::new(block.try_into_recovered().unwrap());
2157        let traces = api.trace_chain_block(block, Default::default()).await.unwrap();
2158        assert!(traces.iter().all(|trace| matches!(trace, Some(TraceResult::Success { .. }))));
2159
2160        let api = debug_api(Some(logs_len / 2));
2161        let err = api.debug_trace_call(call.clone(), None, Default::default()).await.unwrap_err();
2162        assert_eq!(err.to_string(), exceeded);
2163        let err = api.debug_trace_transaction(tx_hash, Default::default()).await.unwrap_err();
2164        assert_eq!(err.to_string(), block_err);
2165        let opts = GethDebugTracingCallOptions { tx_index: Some(1), ..Default::default() };
2166        let err = api.debug_trace_call(call.clone(), None, opts).await.unwrap_err();
2167        assert_eq!(err.to_string(), exceeded);
2168
2169        // An empty tracer name selects the default struct logger too.
2170        let opts: GethDebugTracingCallOptions =
2171            serde_json::from_value(serde_json::json!({ "tracer": "" })).unwrap();
2172        let err = api.debug_trace_call(call, None, opts).await.unwrap_err();
2173        assert_eq!(err.to_string(), exceeded);
2174
2175        // Other tracers have no budget. The call tracer records the 32 bytes of input of the call
2176        // this contract makes: PUSH1 0, 0, 32, 0, 0, 0x99, PUSH2 0x1000, CALL, STOP.
2177        let caller = Address::with_last_byte(0x43);
2178        provider.add_account(
2179            caller,
2180            ExtendedAccount::new(0, U256::ZERO)
2181                .with_bytecode(bytes!("600060006020600060006099611000f100")),
2182        );
2183        let call = TransactionRequest::default().to(caller).gas_limit(100_000);
2184        let opts: GethDebugTracingCallOptions =
2185            serde_json::from_value(serde_json::json!({ "tracer": "callTracer" })).unwrap();
2186        debug_api(Some(1)).debug_trace_call(call, None, opts).await.unwrap();
2187    }
2188
2189    type MockDebugApi = DebugApi<
2190        EthApi<
2191            RpcNodeCoreAdapter<MockEthProvider, TestPool, NoopNetwork, EthEvmConfig>,
2192            EthRpcConverter<ChainSpec>,
2193        >,
2194    >;
2195
2196    /// Parent of the blocks traced by the header tests: number 1 with a 30M gas limit.
2197    fn header_test_parent() -> Header {
2198        Header { number: 1, timestamp: 100, gas_limit: 30_000_000, ..Default::default() }
2199    }
2200
2201    fn header_test_debug_api(
2202        gas_cap: u64,
2203        events: Vec<ConsensusEngineEvent<EthPrimitives>>,
2204    ) -> MockDebugApi {
2205        let provider = MockEthProvider::default();
2206        let parent = header_test_parent();
2207        provider.add_header(parent.hash_slow(), parent);
2208        let eth_api = EthApi::<_, EthRpcConverter<ChainSpec>>::builder(
2209            provider.clone(),
2210            testing_pool(),
2211            NoopNetwork::default(),
2212            EthEvmConfig::new(provider.chain_spec()),
2213        )
2214        .gas_cap(gas_cap.into())
2215        .build();
2216        DebugApi::new(
2217            eth_api,
2218            BlockingTaskGuard::new(1),
2219            &Runtime::test(),
2220            futures::stream::iter(events),
2221        )
2222    }
2223
2224    /// Returns a child of [`header_test_parent`] changed by `f`.
2225    fn header_test_block(f: impl FnOnce(&mut Header)) -> Block {
2226        let parent = header_test_parent();
2227        let mut header = Header {
2228            parent_hash: parent.hash_slow(),
2229            number: 2,
2230            timestamp: parent.timestamp,
2231            gas_limit: parent.gas_limit,
2232            ..Default::default()
2233        };
2234        f(&mut header);
2235        Block { header, body: Default::default() }
2236    }
2237
2238    #[reth_concurrency::test]
2239    async fn trace_raw_block_requires_header_to_extend_parent() {
2240        let max_increase = 30_000_000 + 30_000_000 / GAS_LIMIT_BOUND_DIVISOR;
2241        for (gas_cap, block, expected) in [
2242            (1_000_000, header_test_block(|_| {}), None),
2243            (1_000_000, header_test_block(|h| h.gas_limit = max_increase), None),
2244            (100_000_000, header_test_block(|h| h.gas_limit = 100_000_000), None),
2245            (
2246                1_000_000,
2247                header_test_block(|h| h.gas_limit = max_increase + 1),
2248                Some("child gas_limit 30029297 exceeds the max allowed increase (30000000/1024)"),
2249            ),
2250            (
2251                100_000_000,
2252                header_test_block(|h| h.gas_limit = u64::MAX),
2253                Some(
2254                    "child gas_limit 18446744073709551615 exceeds the max allowed increase (30000000/1024)",
2255                ),
2256            ),
2257            (
2258                100_000_000,
2259                header_test_block(|h| h.timestamp = 99),
2260                Some("block timestamp 99 is in the past compared to the parent timestamp 100"),
2261            ),
2262            (
2263                100_000_000,
2264                header_test_block(|h| h.number = 3),
2265                Some("block number 3 does not match parent block number 1"),
2266            ),
2267        ] {
2268            let debug_api = header_test_debug_api(gas_cap, Vec::new());
2269            let rlp_block = alloy_rlp::encode(&block).into();
2270            let result = debug_api.debug_trace_raw_block(rlp_block, Default::default()).await;
2271            match expected {
2272                None => assert!(result.unwrap().is_empty()),
2273                Some(expected) => assert_eq!(result.unwrap_err().to_string(), expected),
2274            }
2275        }
2276
2277        // A stored header passed consensus, so a gas limit jump past the bound still traces.
2278        let block = header_test_block(|h| h.gas_limit = 60_000_000);
2279        let debug_api = header_test_debug_api(1_000_000, Vec::new());
2280        debug_api.provider().add_header(block.header.hash_slow(), block.header.clone());
2281        let result =
2282            debug_api.debug_trace_raw_block(alloy_rlp::encode(&block).into(), Default::default());
2283        assert!(result.await.unwrap().is_empty());
2284    }
2285
2286    #[reth_concurrency::test]
2287    async fn trace_bad_block_requires_header_to_extend_parent() {
2288        let block = SealedBlock::seal_slow(header_test_block(|h| h.gas_limit = u64::MAX));
2289        let hash = block.hash();
2290        let debug_api = header_test_debug_api(
2291            100_000_000,
2292            vec![ConsensusEngineEvent::InvalidBlock {
2293                block: Box::new(block),
2294                error: "invalid header".to_string(),
2295            }],
2296        );
2297        tokio::time::timeout(Duration::from_secs(5), async {
2298            while debug_api.inner.bad_block_store.get(hash).is_none() {
2299                tokio::task::yield_now().await;
2300            }
2301        })
2302        .await
2303        .unwrap();
2304
2305        let expected =
2306            "child gas_limit 18446744073709551615 exceeds the max allowed increase (30000000/1024)";
2307        let err = DebugApiServer::debug_trace_bad_block(&debug_api, hash, None).await.unwrap_err();
2308        assert_eq!(err.code(), -32602);
2309        assert_eq!(err.message(), expected);
2310        let err =
2311            DebugApiServer::debug_intermediate_roots(&debug_api, hash, None).await.unwrap_err();
2312        assert_eq!(err.code(), -32602);
2313        assert_eq!(err.message(), expected);
2314    }
2315
2316    #[cfg(feature = "js-tracer")]
2317    fn js_tracer_opts(timeout: Option<&str>) -> GethDebugTracingOptions {
2318        GethDebugTracingOptions {
2319            tracer: Some(GethDebugTracerType::JsTracer(
2320                "{ fault: function() {}, result: function() { return null; } }".into(),
2321            )),
2322            timeout: timeout.map(Into::into),
2323            ..Default::default()
2324        }
2325    }
2326
2327    #[cfg(feature = "js-tracer")]
2328    #[test]
2329    fn js_trace_interrupt_stops_attached_js_tracer() {
2330        let opts = js_tracer_opts(None);
2331        let interrupt = JsTraceInterrupt::new(&opts).unwrap();
2332        let inspector = interrupt.attach(DebugInspector::new(opts).unwrap());
2333        interrupt.js.as_ref().unwrap().0.interrupt();
2334
2335        let config = EthEvmConfig::mainnet();
2336        let mut evm = config.evm_with_env(
2337            evm2::evm::CacheDB::<evm2::evm::EmptyDB>::default(),
2338            reth_evm_ethereum::EthEvmEnv::new(evm2::SpecId::CANCUN, Default::default(), 1),
2339        );
2340        let tx = alloy_consensus::transaction::Recovered::new_unchecked(
2341            evm2::ethereum::TxEnvelope::Legacy(alloy_consensus::TxLegacy {
2342                gas_limit: 1_000_000,
2343                to: alloy_primitives::TxKind::Call(Address::with_last_byte(1)),
2344                ..Default::default()
2345            }),
2346            Address::ZERO,
2347        );
2348        let err = Evm::transact_with_inspector(&mut evm, &tx, inspector).unwrap_err();
2349        assert_eq!(err.to_string(), "fatal error: JavaScript tracing interrupted");
2350    }
2351
2352    #[cfg(feature = "js-tracer")]
2353    #[test]
2354    fn js_trace_interrupt_covers_mux_tracers_with_js_children() {
2355        let mux = |config: serde_json::Value| GethDebugTracingOptions {
2356            tracer: Some(GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::MuxTracer)),
2357            tracer_config: serde_json::from_value(config).unwrap(),
2358            ..Default::default()
2359        };
2360        let js = "{ fault: function() {}, result: function() { return null; } }";
2361        let nested = mux(serde_json::json!({ "muxTracer": { (js): {} } }));
2362        let nested = serde_json::json!({ "muxTracer": nested.tracer_config });
2363        for (config, interrupted) in [
2364            (serde_json::json!({ (js): {} }), true),
2365            (nested, true),
2366            (serde_json::json!({ "callTracer": {} }), false),
2367        ] {
2368            let opts = mux(config);
2369            let interrupt = JsTraceInterrupt::new(&opts).unwrap();
2370            assert_eq!(interrupt.js.is_some(), interrupted);
2371        }
2372    }
2373
2374    #[cfg(feature = "js-tracer")]
2375    #[tokio::test]
2376    async fn js_trace_interrupt_times_out_and_interrupts_tracer() {
2377        let interrupt = JsTraceInterrupt::new(&js_tracer_opts(Some("10ms"))).unwrap();
2378        let err =
2379            interrupt.run(std::future::pending::<Result<(), EthApiError>>()).await.unwrap_err();
2380        assert!(
2381            matches!(err, EthApiError::ExecutionTimedOut(timeout) if timeout == Duration::from_millis(10))
2382        );
2383        assert!(interrupt.js.unwrap().0.is_interrupted());
2384    }
2385
2386    #[cfg(feature = "js-tracer")]
2387    #[test]
2388    fn js_trace_interrupt_interrupts_tracer_when_dropped_unpolled() {
2389        let interrupt = JsTraceInterrupt::new(&js_tracer_opts(None)).unwrap();
2390        let (tracer_interrupt, _) = interrupt.js.clone().unwrap();
2391        let trace = interrupt.run(std::future::pending::<Result<(), EthApiError>>());
2392        assert!(!tracer_interrupt.is_interrupted());
2393        drop(trace);
2394        assert!(tracer_interrupt.is_interrupted());
2395    }
2396
2397    #[test]
2398    fn witness_preserves_parent_storage_and_code_reads() {
2399        let address = Address::with_last_byte(1);
2400        let slots = [B256::with_last_byte(1), B256::with_last_byte(2)];
2401        let genesis = Genesis::default().extend_accounts([(
2402            address,
2403            GenesisAccount::default().with_nonce(Some(1)).with_storage(Some(
2404                slots.into_iter().map(|slot| (slot, B256::with_last_byte(10))).collect(),
2405            )),
2406        )]);
2407        let factory = create_test_provider_factory_with_chain_spec(Arc::new(
2408            ChainSpecBuilder::mainnet().genesis(genesis).build(),
2409        ));
2410        init_genesis(&factory).unwrap();
2411        let provider = factory.latest().unwrap();
2412        let proof = provider.proof(address, &slots).unwrap();
2413        let mut state = evm2::evm::CacheDB::<evm2::evm::EmptyDB>::default();
2414        state.cache.accounts.insert(address, None);
2415        state.cache.storage.entry(address).or_default().wipe();
2416
2417        let read_code = Bytecode::new_raw(alloy_primitives::bytes!("600100"));
2418        let created_code = Bytecode::new_raw(alloy_primitives::bytes!("600200"));
2419        state.cache.contracts.insert(read_code.hash_slow(), read_code.clone());
2420        let mut output = BundleState::default();
2421        // Recreating code already read from parent state must not remove it from the witness.
2422        output.contracts.insert(read_code.hash_slow(), read_code.clone());
2423        output.contracts.insert(created_code.hash_slow(), created_code.clone());
2424        let codes = ExecutionWitnessRecord::commit_execution(&mut state, &output);
2425
2426        for mode in [ExecutionWitnessMode::Legacy, ExecutionWitnessMode::Canonical] {
2427            let witness = ExecutionWitnessRecord::new(&state)
2428                .with_canonical_codes(codes.clone())
2429                .into_execution_witness_without_headers(&provider, mode)
2430                .unwrap();
2431            // Canonical mode needs only parent code; legacy also includes execution output.
2432            let mut expected_codes = vec![read_code.original_bytes()];
2433            if !mode.is_canonical() {
2434                expected_codes.push(created_code.original_bytes());
2435                expected_codes.push(Bytes::new());
2436                expected_codes.sort_unstable();
2437            }
2438            let mut actual_codes = witness.codes;
2439            actual_codes.sort_unstable();
2440            assert_eq!(actual_codes, expected_codes);
2441            for storage in &proof.storage_proofs {
2442                assert!(!storage.proof.is_empty());
2443                assert!(storage.proof.iter().all(|node| witness.state.contains(node)));
2444            }
2445        }
2446    }
2447
2448    #[test]
2449    fn hashed_post_state_zeroes_destroyed_account_parent_storage() {
2450        let factory = create_test_provider_factory();
2451        let address = Address::with_last_byte(1);
2452        let old_slot = U256::ONE;
2453        let new_slot = U256::from(2);
2454        let old_value = U256::from(10);
2455        let new_value = U256::from(20);
2456        let hashed_address = keccak256(address);
2457        let hashed_old_slot = keccak256(B256::from(old_slot));
2458        let hashed_new_slot = keccak256(B256::from(new_slot));
2459
2460        let provider_rw = factory.provider_rw().unwrap();
2461        provider_rw
2462            .tx_ref()
2463            .put::<tables::HashedStorages>(
2464                hashed_address,
2465                StorageEntry { key: hashed_old_slot, value: old_value },
2466            )
2467            .unwrap();
2468        provider_rw.commit().unwrap();
2469
2470        let mut bundle_state = BundleState::default();
2471        bundle_state.state.insert(
2472            address,
2473            BundleAccount::new(
2474                Some(AccountInfo::default()),
2475                Some(AccountInfo::default()),
2476                std::iter::once((new_slot, StorageSlot::new_changed(U256::ZERO, new_value)))
2477                    .collect(),
2478                AccountStatus::DestroyedChanged,
2479            ),
2480        );
2481
2482        let provider = factory.latest().unwrap();
2483        let hashed_state = provider.hashed_post_state(&bundle_state).unwrap();
2484        let storage = &hashed_state.storages[&hashed_address];
2485
2486        assert_eq!(storage.storage[&hashed_old_slot], U256::ZERO);
2487        assert_eq!(storage.storage[&hashed_new_slot], new_value);
2488    }
2489
2490    #[reth_concurrency::test]
2491    async fn debug_trace_transaction_counts_pruned_logs() {
2492        let provider = MockEthProvider::default();
2493        let target = Address::with_last_byte(0x42);
2494        provider.add_account(
2495            target,
2496            ExtendedAccount::new(0, U256::ZERO).with_bytecode(bytes!("60006000a060006000a000")),
2497        );
2498        let key = generate_key(&mut generators::rng());
2499        let sender = Address::from_raw_public_key(&key.public_key().serialize_uncompressed()[1..]);
2500        let transactions = (0..2)
2501            .map(|nonce| {
2502                sign_tx_with_key_pair(
2503                    key,
2504                    Transaction::Legacy(TxLegacy {
2505                        nonce,
2506                        gas_limit: 100_000,
2507                        to: TxKind::Call(target),
2508                        ..Default::default()
2509                    }),
2510                )
2511            })
2512            .collect::<Vec<_>>();
2513        let tx_hash = *transactions[1].tx_hash();
2514        let header = Header { number: 1, gas_limit: 30_000_000, ..Default::default() };
2515        let block_hash = header.hash_slow();
2516        provider.add_block(
2517            block_hash,
2518            Block { header, body: BlockBody { transactions, ..Default::default() } },
2519        );
2520        let evm_config = EthEvmConfig::new(provider.chain_spec());
2521        let api = EthApi::<_, EthRpcConverter<ChainSpec>>::builder(
2522            provider.clone(),
2523            testing_pool(),
2524            NoopNetwork::default(),
2525            evm_config,
2526        )
2527        .modify_eth_state_cache_config(|config| config.cache_computed_bals = true)
2528        .build();
2529        assert!(!api.get_block_access_list(block_hash.into()).await.unwrap().unwrap().is_empty());
2530        let (_, cached_bal) =
2531            api.cache().get_recovered_block_and_maybe_bal(block_hash).await.unwrap().unwrap();
2532        assert!(cached_bal.is_some());
2533        assert!(api.cache().get_receipts(block_hash).await.unwrap().is_none());
2534        let debug = DebugApi::new(
2535            api,
2536            BlockingTaskGuard::new(1),
2537            &Runtime::test(),
2538            futures::stream::empty(),
2539        );
2540        let trace = debug
2541            .debug_trace_transaction(
2542                tx_hash,
2543                GethDebugTracingOptions::call_tracer(CallConfig::default().with_log()),
2544            )
2545            .await
2546            .unwrap();
2547        let DebugTrace::Geth(GethTrace::CallTracer(frame)) = trace else {
2548            panic!("expected call trace")
2549        };
2550        assert_eq!(frame.logs.iter().map(|log| log.index.unwrap()).collect::<Vec<_>>(), [2, 3]);
2551
2552        // The BAL has the sender's nonce at the target. Make ordinary replay fail on the prefix
2553        // so successful traces demonstrate that they kept using the cached BAL.
2554        provider.add_account(sender, ExtendedAccount::new(1, U256::ZERO));
2555        let noop = GethDebugTracingOptions::default()
2556            .with_tracer(GethDebugBuiltInTracerType::NoopTracer.into());
2557        let trace = debug.debug_trace_transaction(tx_hash, noop).await.unwrap();
2558        assert!(matches!(trace, DebugTrace::Geth(GethTrace::NoopTracer(_))));
2559        let trace = debug
2560            .debug_trace_transaction(tx_hash, GethDebugTracingOptions::default())
2561            .await
2562            .unwrap();
2563        assert!(matches!(trace, DebugTrace::RawDefault(_)));
2564    }
2565
2566    #[reth_concurrency::test]
2567    async fn send_trace_matches_serialized_traces() {
2568        let frame = |gas_used| {
2569            DebugTrace::RawDefault(RawDefaultFrame {
2570                failed: false,
2571                gas: 21_000,
2572                execution_gas_used: gas_used,
2573                state_gas_used: gas_used,
2574                gas_refund: gas_used,
2575                return_value: bytes!("c0ffee"),
2576                struct_logs: RawValue::from_string(r#"[{"pc":0,"op":"STOP"}]"#.to_owned()).unwrap(),
2577            })
2578        };
2579        // Struct logs with and without the EIP-8037 gas fields and a transaction hash, and a trace
2580        // of another tracer.
2581        let traces = vec![
2582            TraceResult::Success { result: frame(None), tx_hash: Some(B256::repeat_byte(1)) },
2583            TraceResult::Success { result: frame(Some(7)), tx_hash: None },
2584            TraceResult::Success {
2585                result: DebugTrace::Geth(GethTrace::NoopTracer(Default::default())),
2586                tx_hash: Some(B256::repeat_byte(2)),
2587            },
2588        ];
2589        let expected = format!(
2590            r#"{{"jsonrpc":"2.0","id":1,"result":{}}}"#,
2591            serde_json::to_string(&traces).unwrap()
2592        );
2593
2594        let mut module = RpcModule::new(());
2595        module
2596            .register_streaming_method("trace", move |_, _| {
2597                let traces = traces.clone();
2598                async move {
2599                    Ok(ResponseStream::new(move |sink| async move {
2600                        for (index, trace) in traces.into_iter().enumerate() {
2601                            let prefix: &[u8] = if index == 0 { b"[" } else { b"," };
2602                            send_trace(&sink, prefix, trace)
2603                                .map_err(|_| ErrorCode::InternalError)?;
2604                        }
2605                        sink.send(bytes::Bytes::from_static(b"]"))
2606                            .map_err(|_| ErrorCode::InternalError)
2607                    }))
2608                }
2609            })
2610            .unwrap();
2611        let (response, _) = module
2612            .raw_json_request(r#"{"jsonrpc":"2.0","id":1,"method":"trace"}"#, 1)
2613            .await
2614            .unwrap();
2615        assert_eq!(response, expected);
2616    }
2617}