Skip to main content

reth_rpc_eth_api/helpers/
trace.rs

1//! Loads a pending block from database. Helper trait for `eth_` call and trace RPC methods.
2
3use super::{Call, LoadBlock, LoadState, LoadTransaction};
4use crate::{FromEthApiError, FromEvmError};
5use alloy_consensus::{transaction::TxHashRef, BlockHeader, TxReceipt};
6use alloy_eip7928::{bal::DecodedBal, BlockAccessIndex};
7use alloy_primitives::B256;
8use alloy_rpc_types_eth::{BlockId, TransactionInfo};
9use evm2::evm::Bal as EvmBal;
10use evm2_inspectors::tracing::{
11    TraceLimitBehavior, TraceLimits, TracingInspector, TracingInspectorConfig,
12};
13use futures::Future;
14use reth_errors::RethError;
15use reth_evm::{
16    execute::{BlockExecutor, BlockTransactionResult},
17    ConfigureEvm, Database, Evm, EvmEnvFor, EvmTypesFor, TxEnvFor, TxResultWithStateFor,
18};
19use reth_primitives_traits::{BlockBody, BlockTy, RecoveredBlock};
20use reth_rpc_eth_types::{cache::db::attach_bal_before_tx, EthApiError, StateCacheDb};
21use reth_storage_api::ProviderBlock;
22use reth_tasks::cancel::is_cancelled;
23use std::sync::{
24    atomic::{AtomicUsize, Ordering},
25    Arc,
26};
27
28/// Context passed to per-transaction trace callbacks.
29pub struct TracingCtx<'a, Insp, EvmTypes: evm2::EvmTypes> {
30    /// Execution result and detached state changes for the transaction.
31    pub result: &'a evm2::TxResultWithState<EvmTypes>,
32    /// Database pointing to the transaction pre-state.
33    pub db: &'a mut dyn evm2::evm::DynDatabase,
34    /// Inspector used while executing the transaction.
35    pub inspector: Insp,
36}
37
38impl<Insp, EvmTypes: evm2::EvmTypes> core::fmt::Debug for TracingCtx<'_, Insp, EvmTypes> {
39    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
40        f.debug_struct("TracingCtx").finish_non_exhaustive()
41    }
42}
43
44impl<Insp, EvmTypes: evm2::EvmTypes> TracingCtx<'_, Insp, EvmTypes> {
45    /// Consumes this context and returns the inspector.
46    pub fn take_inspector(self) -> Insp {
47        self.inspector
48    }
49}
50
51/// Transaction executed by [`Trace::inspect_transaction_in_block`].
52pub struct InspectedTx<I, Evm: ConfigureEvm> {
53    /// Inspector used while executing the transaction.
54    pub inspector: I,
55    /// Execution result and detached state changes for the transaction.
56    pub result: TxResultWithStateFor<Evm>,
57    /// EVM environment of the transaction's block.
58    pub evm_env: EvmEnvFor<Evm>,
59}
60
61impl<I, Evm: ConfigureEvm> core::fmt::Debug for InspectedTx<I, Evm> {
62    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
63        f.debug_struct("InspectedTx").finish_non_exhaustive()
64    }
65}
66
67/// Executes CPU heavy trace tasks.
68pub trait Trace: LoadState<Error: FromEvmError<Self::Evm>> + Call {
69    /// Executes a transaction with the provided inspector without committing state changes.
70    fn inspect<DB, I>(
71        &self,
72        db: DB,
73        evm_env: EvmEnvFor<Self::Evm>,
74        tx_env: &TxEnvFor<Self::Evm>,
75        inspector: I,
76    ) -> Result<(I, TxResultWithStateFor<Self::Evm>), Self::Error>
77    where
78        DB: Database,
79        I: evm2::Inspector<EvmTypesFor<Self::Evm>> + 'static,
80    {
81        let mut evm = self.evm_config().evm_with_env(db, evm_env);
82        evm.transact_with_inspector(tx_env, inspector).map_err(Self::Error::from_evm_err)
83    }
84
85    /// Executes the transaction on top of the given [`BlockId`] with a tracer configured by the
86    /// config and provides the used database to the callback.
87    fn spawn_trace_at_with_state<F, R>(
88        &self,
89        evm_env: EvmEnvFor<Self::Evm>,
90        tx_env: TxEnvFor<Self::Evm>,
91        config: TracingInspectorConfig,
92        at: BlockId,
93        f: F,
94    ) -> impl Future<Output = Result<R, Self::Error>> + Send
95    where
96        F: FnOnce(
97                TracingInspector,
98                TxResultWithStateFor<Self::Evm>,
99                StateCacheDb,
100            ) -> Result<R, Self::Error>
101            + Send
102            + 'static,
103        R: Send + 'static,
104    {
105        self.spawn_with_state_at_block(at, move |this, mut db| {
106            let inspector = this.tracing_inspector(config);
107            let (inspector, result) = this.inspect(&mut db, evm_env, &tx_env, inspector)?;
108            f(inspector, result, db)
109        })
110    }
111
112    /// Retrieves the transaction if it exists and returns its trace.
113    ///
114    /// Before the transaction is traced, the state is positioned right before the transaction,
115    /// either by attaching the block's cached BAL or by executing all previous transactions in
116    /// the block.
117    /// The callback `f` is invoked with the [`TxResultWithStateFor`] after the transaction was
118    /// executed and the database that points to the beginning of the transaction. The database may
119    /// have the block's BAL attached and must only be used for reads, because an attached BAL takes
120    /// read precedence over state committed on top, see [`attach_bal_before_tx`].
121    ///
122    /// Note: Implementers should use a threadpool where blocking is allowed, such as
123    /// [`BlockingTaskPool`](reth_tasks::pool::BlockingTaskPool).
124    fn spawn_trace_transaction_in_block<F, R>(
125        &self,
126        hash: B256,
127        config: TracingInspectorConfig,
128        f: F,
129    ) -> impl Future<Output = Result<Option<R>, Self::Error>> + Send
130    where
131        Self: LoadTransaction,
132        F: FnOnce(
133                TransactionInfo,
134                TracingInspector,
135                TxResultWithStateFor<Self::Evm>,
136                StateCacheDb,
137            ) -> Result<R, Self::Error>
138            + Send
139            + 'static,
140        R: Send + 'static,
141    {
142        self.spawn_trace_transaction_in_block_with_inspector(
143            hash,
144            self.tracing_inspector(config),
145            f,
146        )
147    }
148
149    /// Retrieves the transaction if it exists and returns its trace.
150    ///
151    /// Before the transaction is traced, the state is positioned right before the transaction,
152    /// either by attaching the block's cached BAL or by executing all previous transactions in
153    /// the block.
154    /// The callback `f` is invoked with the [`TxResultWithStateFor`] after the transaction was
155    /// executed and the database that points to the beginning of the transaction. The database may
156    /// have the block's BAL attached and must only be used for reads, because an attached BAL takes
157    /// read precedence over state committed on top, see [`attach_bal_before_tx`].
158    ///
159    /// Note: Implementers should use a threadpool where blocking is allowed, such as
160    /// [`BlockingTaskPool`](reth_tasks::pool::BlockingTaskPool).
161    fn spawn_trace_transaction_in_block_with_inspector<Insp, F, R>(
162        &self,
163        hash: B256,
164        inspector: Insp,
165        f: F,
166    ) -> impl Future<Output = Result<Option<R>, Self::Error>> + Send
167    where
168        Self: LoadTransaction,
169        F: FnOnce(
170                TransactionInfo,
171                Insp,
172                TxResultWithStateFor<Self::Evm>,
173                StateCacheDb,
174            ) -> Result<R, Self::Error>
175            + Send
176            + 'static,
177        Insp: evm2::Inspector<EvmTypesFor<Self::Evm>> + Send + 'static,
178        R: Send + 'static,
179    {
180        async move {
181            let Some((transaction, block, bal)) =
182                self.transaction_and_block_and_maybe_bal(hash).await?
183            else {
184                return Ok(None);
185            };
186            let (_, tx_info) = transaction.split();
187
188            // we need to get the state of the parent block because we're essentially replaying the
189            // block the transaction is included in
190            self.spawn_with_state_at_block(block.parent_hash(), move |this, mut db| {
191                let InspectedTx { inspector, result, .. } = this.inspect_transaction_in_block(
192                    &block,
193                    &mut db,
194                    |_| inspector,
195                    // index should always be available because `transaction_and_block` only
196                    // returns transactions included in a block
197                    tx_info.index.expect("transaction_and_block only returns block transactions")
198                        as usize,
199                    bal.as_deref(),
200                )?;
201                f(tx_info, inspector, result, db)
202            })
203            .await
204            .map(Some)
205        }
206    }
207
208    /// Positions the state of `db` right before the transaction at the target index.
209    ///
210    /// If the block's cached BAL is given, it is attached to the database at the target index and
211    /// no transactions are executed, see [`attach_bal_before_tx`]. Otherwise all transactions
212    /// before the target transaction are executed through the block executor, see
213    /// [`Call::block_executor`], and their changes are written to the _runtime_ db
214    /// ([`StateCacheDb`]).
215    ///
216    /// If the target index is greater than or equal to the block's transaction count, all
217    /// transactions are replayed.
218    fn replay_block_until(
219        &self,
220        db: &mut StateCacheDb,
221        block: &RecoveredBlock<BlockTy<Self::Primitives>>,
222        target_tx_index: usize,
223        bal: Option<&DecodedBal<Arc<EvmBal>>>,
224    ) -> Result<(), Self::Error> {
225        if let Some(bal) = bal {
226            attach_bal_before_tx(db, bal, target_tx_index);
227            return Ok(())
228        }
229
230        self.apply_pre_execution_changes(block, db)?;
231
232        let evm_env = self.evm_env_for_header(block.sealed_block().sealed_header())?;
233        let mut executor = self.block_executor(block, db, evm_env)?;
234        self.replay_transactions_until_with_executor(
235            &mut executor,
236            block.transactions_recovered(),
237            target_tx_index,
238        )?;
239        let cache = executor.evm_mut().take_state_cache();
240        drop(executor);
241        db.cache.merge(cache);
242        Ok(())
243    }
244
245    /// Executes the block's transaction at the target index with the configured inspector on the
246    /// state right before the transaction.
247    ///
248    /// The transaction is executed through the block executor, see [`Call::block_executor`]. If
249    /// the block's cached BAL is given, the state is positioned by attaching the BAL at the target
250    /// index, see [`attach_bal_before_tx`], and the executor is told the transaction's position
251    /// with [`BlockExecutor::set_block_access_index`]. Otherwise all transactions before the
252    /// target transaction are replayed through the executor without inspection first.
253    ///
254    /// `inspector_setup` is called right before the target runs, with the log count of the
255    /// replayed transactions (zero when a BAL is given).
256    ///
257    /// Returns [`EthApiError::InvalidParams`] if the block has no transaction at that index.
258    fn inspect_transaction_in_block<I>(
259        &self,
260        block: &RecoveredBlock<BlockTy<Self::Primitives>>,
261        db: &mut StateCacheDb,
262        inspector_setup: impl FnOnce(usize) -> I,
263        target_tx_index: usize,
264        bal: Option<&DecodedBal<Arc<EvmBal>>>,
265    ) -> Result<InspectedTx<I, Self::Evm>, Self::Error>
266    where
267        I: evm2::Inspector<EvmTypesFor<Self::Evm>> + 'static,
268    {
269        let Some(target_tx) = block.transactions_recovered().nth(target_tx_index) else {
270            return Err(EthApiError::InvalidParams(format!(
271                "tx_index {target_tx_index} out of bounds for block with {} transactions",
272                block.transaction_count()
273            ))
274            .into())
275        };
276
277        if let Some(bal) = bal {
278            // the BAL also covers the block's pre-execution changes
279            attach_bal_before_tx(db, bal, target_tx_index);
280        } else {
281            self.apply_pre_execution_changes(block, db)?;
282        }
283
284        let evm_env = self.evm_env_for_header(block.sealed_block().sealed_header())?;
285        let mut executor = self.block_executor(block, db, evm_env.clone())?;
286
287        if bal.is_some() {
288            executor
289                .set_block_access_index(BlockAccessIndex::from_tx_index(target_tx_index as u64));
290        } else {
291            self.replay_transactions_until_with_executor(
292                &mut executor,
293                block.transactions_recovered(),
294                target_tx_index,
295            )?;
296        }
297        let inspector =
298            inspector_setup(executor.receipts().iter().map(|receipt| receipt.logs().len()).sum());
299        let (inspector, result) = executor
300            .inspect_transaction_without_commit(target_tx, inspector)
301            .map(|(inspector, output)| (inspector, output.into_result()))
302            .map_err(Self::Error::from_evm_err)?;
303        let cache = executor.evm_mut().take_state_cache();
304        drop(executor);
305        db.cache.merge(cache);
306        Ok(InspectedTx { inspector, result, evm_env })
307    }
308
309    /// Executes all transactions of a block up to a given index.
310    ///
311    /// If a `highest_index` is given, this will only execute the first `highest_index`
312    /// transactions, in other words, it will stop executing transactions after the
313    /// `highest_index`th transaction. If `highest_index` is `None`, all transactions
314    /// are executed.
315    fn trace_block_until<F, R>(
316        &self,
317        block_id: BlockId,
318        block: Option<Arc<RecoveredBlock<ProviderBlock<Self::Provider>>>>,
319        highest_index: Option<u64>,
320        config: TracingInspectorConfig,
321        f: F,
322    ) -> impl Future<Output = Result<Option<Vec<R>>, Self::Error>> + Send
323    where
324        Self: LoadBlock,
325        F: Fn(
326                TransactionInfo,
327                TracingCtx<'_, TracingInspector, EvmTypesFor<Self::Evm>>,
328            ) -> Result<R, Self::Error>
329            + Send
330            + 'static,
331        R: Send + 'static,
332    {
333        // The transactions of the block share one trace byte budget, since they share one response.
334        let budget = Arc::new(RequestTraceBudget::new(self.trace_limits()));
335        self.trace_block_until_with_inspector(
336            block_id,
337            block,
338            highest_index,
339            {
340                let budget = Arc::clone(&budget);
341                move || TracingInspector::new(config).with_limits(budget.limits())
342            },
343            move |tx_info, ctx| {
344                budget.charge(ctx.inspector.recorded_bytes());
345                f(tx_info, ctx)
346            },
347        )
348    }
349
350    /// Executes all transactions of a block.
351    ///
352    /// If a `highest_index` is given, this will only execute the first `highest_index`
353    /// transactions, in other words, it will stop executing transactions after the
354    /// `highest_index`th transaction.
355    ///
356    /// Note: This expect tx index to be 0-indexed, so the first transaction is at index 0.
357    ///
358    /// This accepts a `inspector_setup` closure that returns the inspector to be used for tracing
359    /// the transactions.
360    fn trace_block_until_with_inspector<Setup, Insp, F, R>(
361        &self,
362        block_id: BlockId,
363        block: Option<Arc<RecoveredBlock<ProviderBlock<Self::Provider>>>>,
364        highest_index: Option<u64>,
365        mut inspector_setup: Setup,
366        f: F,
367    ) -> impl Future<Output = Result<Option<Vec<R>>, Self::Error>> + Send
368    where
369        Self: LoadBlock,
370        F: Fn(
371                TransactionInfo,
372                TracingCtx<'_, Insp, EvmTypesFor<Self::Evm>>,
373            ) -> Result<R, Self::Error>
374            + Send
375            + 'static,
376        Setup: FnMut() -> Insp + Send + 'static,
377        Insp: evm2::Inspector<EvmTypesFor<Self::Evm>> + 'static,
378        R: Send + 'static,
379    {
380        async move {
381            let block =
382                if block.is_some() { block } else { self.recovered_block(block_id).await? };
383
384            let Some(block) = block else { return Ok(None) };
385            let evm_env = self.evm_env_for_header(block.sealed_block().sealed_header())?;
386
387            if block.body().transactions().is_empty() {
388                // nothing to trace
389                return Ok(Some(Vec::new()))
390            }
391
392            // replay all transactions of the block
393            // we need to get the state of the parent block because we're replaying this block
394            // on top of its parent block's state
395            self.spawn_with_state_at_block(block.parent_hash(), move |this, mut db| {
396                let block_hash = block.hash();
397
398                let block_number = block.number();
399                let block_timestamp = block.timestamp();
400                let base_fee = block.base_fee_per_gas();
401
402                this.apply_pre_execution_changes(&block, &mut db)?;
403
404                // prepare transactions, we do everything upfront to reduce time spent with open
405                // state
406                let max_transactions = highest_index.map_or_else(
407                    || block.body().transaction_count(),
408                    |highest| {
409                        // we need + 1 because the index is 0-based
410                        highest as usize + 1
411                    },
412                );
413                let tx_count = max_transactions.min(block.body().transaction_count());
414
415                let mut results = Vec::new();
416                let mut executor = this.block_executor(&block, &mut db, evm_env)?;
417
418                for (idx, tx) in block.transactions_recovered().take(max_transactions).enumerate() {
419                    if is_cancelled() {
420                        return Err(EthApiError::InternalEthError.into())
421                    }
422                    let tx_hash = *tx.tx_hash();
423                    let (inspector, output) = executor
424                        .inspect_transaction_without_commit(tx, inspector_setup())
425                        .map_err(Self::Error::from_evm_err)?;
426                    let tx_info = TransactionInfo {
427                        hash: Some(tx_hash),
428                        index: Some(idx as u64),
429                        block_hash: Some(block_hash),
430                        block_number: Some(block_number),
431                        block_timestamp: Some(block_timestamp),
432                        base_fee,
433                    };
434                    let item = f(
435                        tx_info,
436                        TracingCtx {
437                            result: output.result(),
438                            db: executor.evm_mut().state_db_mut(),
439                            inspector,
440                        },
441                    )?;
442                    // the executor is dropped after the last transaction, so its state needs no
443                    // commit
444                    if idx + 1 < tx_count {
445                        executor.commit_transaction(output).map_err(Self::Error::from_evm_err)?;
446                    }
447                    results.push(item);
448                }
449
450                Ok(Some(results))
451            })
452            .await
453        }
454    }
455
456    /// Executes all transactions of a block and returns a list of callback results invoked for each
457    /// transaction in the block.
458    ///
459    /// This
460    /// 1. fetches all transactions of the block
461    /// 2. configures the EVM env
462    /// 3. loops over all transactions and executes them
463    /// 4. calls the callback with the transaction info, the execution result, the changed state
464    ///    _after_ the transaction [`StateCacheDb`] and the database that points to the state right
465    ///    _before_ the transaction.
466    fn trace_block_with<F, R>(
467        &self,
468        block_id: BlockId,
469        block: Option<Arc<RecoveredBlock<ProviderBlock<Self::Provider>>>>,
470        config: TracingInspectorConfig,
471        f: F,
472    ) -> impl Future<Output = Result<Option<Vec<R>>, Self::Error>> + Send
473    where
474        Self: LoadBlock,
475        F: Fn(
476                TransactionInfo,
477                TracingCtx<'_, TracingInspector, EvmTypesFor<Self::Evm>>,
478            ) -> Result<R, Self::Error>
479            + Send
480            + 'static,
481        R: Send + 'static,
482    {
483        self.trace_block_until(block_id, block, None, config, f)
484    }
485
486    /// Executes all transactions of a block and returns a list of callback results invoked for each
487    /// transaction in the block.
488    ///
489    /// This
490    /// 1. fetches all transactions of the block
491    /// 2. configures the EVM env
492    /// 3. loops over all transactions and executes them
493    /// 4. calls the callback with the transaction info, the execution result, the changed state
494    ///    _after_ the transaction `EvmState` and the database that points to the state right
495    ///    _before_ the transaction, in other words the state the transaction was executed on:
496    ///    `changed_state = tx(cached_state)`
497    ///
498    /// This accepts a `inspector_setup` closure that returns the inspector to be used for tracing
499    /// a transaction. This is invoked for each transaction.
500    fn trace_block_inspector<Setup, Insp, F, R>(
501        &self,
502        block_id: BlockId,
503        block: Option<Arc<RecoveredBlock<ProviderBlock<Self::Provider>>>>,
504        insp_setup: Setup,
505        f: F,
506    ) -> impl Future<Output = Result<Option<Vec<R>>, Self::Error>> + Send
507    where
508        Self: LoadBlock,
509        F: Fn(
510                TransactionInfo,
511                TracingCtx<'_, Insp, EvmTypesFor<Self::Evm>>,
512            ) -> Result<R, Self::Error>
513            + Send
514            + 'static,
515        Setup: FnMut() -> Insp + Send + 'static,
516        Insp: evm2::Inspector<EvmTypesFor<Self::Evm>> + 'static,
517        R: Send + 'static,
518    {
519        self.trace_block_until_with_inspector(block_id, block, None, insp_setup, f)
520    }
521
522    /// Returns the limits for the tracers of the trace and debug APIs.
523    ///
524    /// A traced transaction that records more than the configured
525    /// [`max_trace_bytes`](reth_rpc_eth_types::EthApiSettings::max_trace_bytes) halts with an
526    /// error.
527    fn trace_limits(&self) -> TraceLimits {
528        TraceLimits::default()
529            .set_max_recorded_bytes(self.eth_api_settings().max_trace_bytes)
530            .set_behavior(TraceLimitBehavior::Halt)
531    }
532
533    /// Returns a [`TracingInspector`] for the config, bounded by [`Self::trace_limits`].
534    fn tracing_inspector(&self, config: TracingInspectorConfig) -> TracingInspector {
535        TracingInspector::new(config).with_limits(self.trace_limits())
536    }
537
538    /// Applies chain-specific state transitions required before executing a block.
539    ///
540    /// Note: This should only be called when tracing an entire block vs individual transactions.
541    /// When tracing transactions on top of an already committed block state, those transitions are
542    /// already applied.
543    fn apply_pre_execution_changes(
544        &self,
545        block: &RecoveredBlock<ProviderBlock<Self::Provider>>,
546        db: &mut StateCacheDb,
547    ) -> Result<reth_trie_common::bundle_state::BundleState, Self::Error> {
548        let evm_env = self.evm_env_for_header(block.sealed_block().sealed_header())?;
549        let ctx = self
550            .evm_config()
551            .context_for_block(block.sealed_block())
552            .map_err(RethError::other)
553            .map_err(Self::Error::from_eth_err)?;
554        let changes = self
555            .evm_config()
556            .pre_block_state_changes(&mut *db, evm_env, ctx)
557            .map_err(Self::Error::from_eth_err)?;
558        db.commit_source(&reth_execution_types::BundleSource(&changes));
559        Ok(changes)
560    }
561}
562
563/// The trace bytes a request has left for the transactions it traces after each other.
564///
565/// The trace byte limit of [`Trace::trace_limits`] applies to each traced transaction, and a
566/// tracer starts its count over for every transaction. Requests that trace several transactions
567/// into one response take each one's limits from this budget and charge what it recorded, so that
568/// together they record at most the limit.
569#[derive(Debug)]
570pub struct RequestTraceBudget {
571    limits: TraceLimits,
572    /// Bytes recorded by the transactions traced so far. They are traced one after the other, so
573    /// relaxed ordering suffices.
574    recorded: AtomicUsize,
575}
576
577impl RequestTraceBudget {
578    /// Creates the budget of a request traced with `limits`.
579    pub const fn new(limits: TraceLimits) -> Self {
580        Self { limits, recorded: AtomicUsize::new(0) }
581    }
582
583    /// Returns the limits for the next transaction: the request's, with the byte limit lowered to
584    /// the bytes left.
585    pub fn limits(&self) -> TraceLimits {
586        let recorded = self.recorded.load(Ordering::Relaxed);
587        self.limits.set_max_recorded_bytes(
588            self.limits.max_recorded_bytes.map(|max| max.saturating_sub(recorded)),
589        )
590    }
591
592    /// Takes `recorded` bytes, what a transaction traced with [`Self::limits`] recorded.
593    pub fn charge(&self, recorded: usize) {
594        self.recorded.fetch_add(recorded, Ordering::Relaxed);
595    }
596}