1use 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
28pub struct TracingCtx<'a, Insp, EvmTypes: evm2::EvmTypes> {
30 pub result: &'a evm2::TxResultWithState<EvmTypes>,
32 pub db: &'a mut dyn evm2::evm::DynDatabase,
34 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 pub fn take_inspector(self) -> Insp {
47 self.inspector
48 }
49}
50
51pub struct InspectedTx<I, Evm: ConfigureEvm> {
53 pub inspector: I,
55 pub result: TxResultWithStateFor<Evm>,
57 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
67pub trait Trace: LoadState<Error: FromEvmError<Self::Evm>> + Call {
69 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 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 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 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 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 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 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 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 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 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 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 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 return Ok(Some(Vec::new()))
390 }
391
392 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 let max_transactions = highest_index.map_or_else(
407 || block.body().transaction_count(),
408 |highest| {
409 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 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 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 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 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 fn tracing_inspector(&self, config: TracingInspectorConfig) -> TracingInspector {
535 TracingInspector::new(config).with_limits(self.trace_limits())
536 }
537
538 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#[derive(Debug)]
570pub struct RequestTraceBudget {
571 limits: TraceLimits,
572 recorded: AtomicUsize,
575}
576
577impl RequestTraceBudget {
578 pub const fn new(limits: TraceLimits) -> Self {
580 Self { limits, recorded: AtomicUsize::new(0) }
581 }
582
583 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 pub fn charge(&self, recorded: usize) {
594 self.recorded.fetch_add(recorded, Ordering::Relaxed);
595 }
596}