1use alloy_consensus::BlockHeader as _;
2use alloy_eips::BlockId;
3use alloy_evm::block::calc::{base_block_reward_pre_merge, block_reward, ommer_reward};
4use alloy_primitives::{
5 map::{HashMap, HashSet},
6 Address, BlockHash, Bytes, B256, U256,
7};
8use alloy_rpc_types_eth::{
9 state::{EvmOverrides, StateOverride},
10 BlockOverrides, Index,
11};
12use alloy_rpc_types_trace::{
13 filter::TraceFilter,
14 opcode::{BlockOpcodeGas, TransactionOpcodeGas},
15 parity::*,
16 tracerequest::TraceCallRequest,
17};
18use async_trait::async_trait;
19use jsonrpsee::core::RpcResult;
20use reth_chainspec::{ChainSpecProvider, EthereumHardforks};
21use reth_evm::ConfigureEvm;
22use reth_primitives_traits::{BlockBody, BlockHeader};
23use reth_rpc_api::TraceApiServer;
24use reth_rpc_convert::RpcTxReq;
25use reth_rpc_eth_api::{
26 helpers::{Call, LoadPendingBlock, LoadTransaction, Trace, TraceExt},
27 FromEthApiError, RpcNodeCore,
28};
29use reth_rpc_eth_types::{error::EthApiError, utils::recover_raw_transaction, EthConfig};
30use reth_storage_api::{BlockNumReader, BlockReader};
31use reth_tasks::pool::BlockingTaskGuard;
32use reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};
33use revm::DatabaseCommit;
34use revm_inspectors::{
35 opcode::OpcodeGasInspector,
36 storage::StorageInspector,
37 tracing::{parity::populate_state_diff, TracingInspector, TracingInspectorConfig},
38};
39use serde::{Deserialize, Serialize};
40use std::sync::Arc;
41use tokio::sync::{AcquireError, OwnedSemaphorePermit};
42
43pub struct TraceApi<Eth> {
47 inner: Arc<TraceApiInner<Eth>>,
48}
49
50impl<Eth> TraceApi<Eth> {
53 pub fn new(
55 eth_api: Eth,
56 blocking_task_guard: BlockingTaskGuard,
57 eth_config: EthConfig,
58 ) -> Self {
59 let inner = Arc::new(TraceApiInner { eth_api, blocking_task_guard, eth_config });
60 Self { inner }
61 }
62
63 async fn acquire_trace_permit(
65 &self,
66 ) -> std::result::Result<OwnedSemaphorePermit, AcquireError> {
67 self.inner.blocking_task_guard.clone().acquire_owned().await
68 }
69
70 pub fn eth_api(&self) -> &Eth {
72 &self.inner.eth_api
73 }
74}
75
76impl<Eth: RpcNodeCore> TraceApi<Eth> {
77 pub fn provider(&self) -> &Eth::Provider {
79 self.inner.eth_api.provider()
80 }
81}
82
83impl<Eth> TraceApi<Eth>
86where
87 Eth: Trace + Call + LoadPendingBlock + LoadTransaction + 'static,
90{
91 pub async fn trace_call(
93 &self,
94 trace_request: TraceCallRequest<RpcTxReq<Eth::NetworkTypes>>,
95 ) -> Result<TraceResults, Eth::Error> {
96 let at = trace_request.block_id.unwrap_or_default();
97 let config = TracingInspectorConfig::from_parity_config(&trace_request.trace_types);
98 let overrides =
99 EvmOverrides::new(trace_request.state_overrides, trace_request.block_overrides);
100 let mut inspector = TracingInspector::new(config);
101 let this = self.clone();
102 self.eth_api()
103 .spawn_with_call_at(trace_request.call, at, overrides, move |db, evm_env, tx_env| {
104 let res = this.eth_api().inspect(&mut *db, evm_env, tx_env, &mut inspector)?;
105 let trace_res = inspector
106 .into_parity_builder()
107 .into_trace_results_with_state(&res, &trace_request.trace_types, &db)
108 .map_err(Eth::Error::from_eth_err)?;
109 Ok(trace_res)
110 })
111 .await
112 }
113
114 pub async fn trace_raw_transaction(
116 &self,
117 tx: Bytes,
118 trace_types: HashSet<TraceType>,
119 block_id: Option<BlockId>,
120 ) -> Result<TraceResults, Eth::Error> {
121 let tx = recover_raw_transaction::<PoolPooledTx<Eth::Pool>>(&tx)?
122 .map(<Eth::Pool as TransactionPool>::Transaction::pooled_into_consensus);
123
124 let (evm_env, at) = self.eth_api().evm_env_at(block_id.unwrap_or_default()).await?;
125 let tx_env = self.eth_api().evm_config().tx_env(tx);
126
127 let config = TracingInspectorConfig::from_parity_config(&trace_types);
128
129 self.eth_api()
130 .spawn_trace_at_with_state(evm_env, tx_env, config, at, move |inspector, res, db| {
131 inspector
132 .into_parity_builder()
133 .into_trace_results_with_state(&res, &trace_types, &db)
134 .map_err(Eth::Error::from_eth_err)
135 })
136 .await
137 }
138
139 pub async fn trace_call_many(
144 &self,
145 calls: Vec<(RpcTxReq<Eth::NetworkTypes>, HashSet<TraceType>)>,
146 block_id: Option<BlockId>,
147 ) -> Result<Vec<TraceResults>, Eth::Error> {
148 let at = block_id.unwrap_or(BlockId::pending());
149 let (evm_env, at) = self.eth_api().evm_env_at(at).await?;
150
151 self.eth_api()
153 .spawn_with_state_at_block(at, move |eth_api, mut db| {
154 let mut results = Vec::with_capacity(calls.len());
155 let mut calls = calls.into_iter().peekable();
156
157 while let Some((call, trace_types)) = calls.next() {
158 let (evm_env, tx_env) = eth_api.prepare_call_env(
159 evm_env.clone(),
160 call,
161 &mut db,
162 Default::default(),
163 )?;
164 let config = TracingInspectorConfig::from_parity_config(&trace_types);
165 let mut inspector = TracingInspector::new(config);
166 let res = eth_api.inspect(&mut db, evm_env, tx_env, &mut inspector)?;
167
168 let trace_res = inspector
169 .into_parity_builder()
170 .into_trace_results_with_state(&res, &trace_types, &db)
171 .map_err(Eth::Error::from_eth_err)?;
172
173 results.push(trace_res);
174
175 if calls.peek().is_some() {
178 db.commit(res.state)
179 }
180 }
181
182 Ok(results)
183 })
184 .await
185 }
186
187 pub async fn replay_transaction(
189 &self,
190 hash: B256,
191 trace_types: HashSet<TraceType>,
192 ) -> Result<TraceResults, Eth::Error> {
193 let config = TracingInspectorConfig::from_parity_config(&trace_types);
194 self.eth_api()
195 .spawn_trace_transaction_in_block(hash, config, move |_, inspector, res, db| {
196 let trace_res = inspector
197 .into_parity_builder()
198 .into_trace_results_with_state(&res, &trace_types, &db)
199 .map_err(Eth::Error::from_eth_err)?;
200 Ok(trace_res)
201 })
202 .await
203 .transpose()
204 .ok_or(EthApiError::TransactionNotFound)?
205 }
206
207 pub async fn trace_get(
214 &self,
215 hash: B256,
216 indices: Vec<usize>,
217 ) -> Result<Option<LocalizedTransactionTrace>, Eth::Error> {
218 if indices.len() != 1 {
219 return Ok(None)
221 }
222 self.trace_get_index(hash, indices[0]).await
223 }
224
225 pub async fn trace_get_index(
229 &self,
230 hash: B256,
231 index: usize,
232 ) -> Result<Option<LocalizedTransactionTrace>, Eth::Error> {
233 Ok(self.trace_transaction(hash).await?.and_then(|traces| traces.into_iter().nth(index)))
234 }
235
236 pub async fn trace_transaction(
238 &self,
239 hash: B256,
240 ) -> Result<Option<Vec<LocalizedTransactionTrace>>, Eth::Error> {
241 self.eth_api()
242 .spawn_trace_transaction_in_block(
243 hash,
244 TracingInspectorConfig::default_parity(),
245 move |tx_info, inspector, _, _| {
246 let traces =
247 inspector.into_parity_builder().into_localized_transaction_traces(tx_info);
248 Ok(traces)
249 },
250 )
251 .await
252 }
253
254 pub async fn trace_transaction_opcode_gas(
257 &self,
258 tx_hash: B256,
259 ) -> Result<Option<TransactionOpcodeGas>, Eth::Error> {
260 self.eth_api()
261 .spawn_trace_transaction_in_block_with_inspector(
262 tx_hash,
263 OpcodeGasInspector::default(),
264 move |_tx_info, inspector, _res, _| {
265 let trace = TransactionOpcodeGas {
266 transaction_hash: tx_hash,
267 opcode_gas: inspector.opcode_gas_iter().collect(),
268 };
269 Ok(trace)
270 },
271 )
272 .await
273 }
274
275 fn calculate_base_block_reward<H: BlockHeader>(
280 &self,
281 header: &H,
282 ) -> Result<Option<u128>, Eth::Error> {
283 let chain_spec = self.provider().chain_spec();
284
285 if chain_spec.is_paris_active_at_block(header.number()) {
286 return Ok(None)
287 }
288
289 Ok(Some(base_block_reward_pre_merge(&chain_spec, header.number())))
290 }
291
292 fn extract_reward_traces<H: BlockHeader>(
296 &self,
297 header: &H,
298 ommers: Option<&[H]>,
299 base_block_reward: u128,
300 ) -> Vec<LocalizedTransactionTrace> {
301 let ommers_cnt = ommers.map(|o| o.len()).unwrap_or_default();
302 let mut traces = Vec::with_capacity(ommers_cnt + 1);
303
304 let block_reward = block_reward(base_block_reward, ommers_cnt);
305 traces.push(reward_trace(
306 header,
307 RewardAction {
308 author: header.beneficiary(),
309 reward_type: RewardType::Block,
310 value: U256::from(block_reward),
311 },
312 ));
313
314 let Some(ommers) = ommers else { return traces };
315
316 for uncle in ommers {
317 let uncle_reward = ommer_reward(base_block_reward, header.number(), uncle.number());
318 traces.push(reward_trace(
319 header,
320 RewardAction {
321 author: uncle.beneficiary(),
322 reward_type: RewardType::Uncle,
323 value: U256::from(uncle_reward),
324 },
325 ));
326 }
327 traces
328 }
329}
330
331impl<Eth> TraceApi<Eth>
332where
333 Eth: TraceExt + 'static,
336{
337 pub async fn trace_filter(
342 &self,
343 filter: TraceFilter,
344 ) -> Result<Vec<LocalizedTransactionTrace>, Eth::Error> {
345 let matcher = Arc::new(filter.matcher());
347 let TraceFilter { from_block, to_block, mut after, count, .. } = filter;
348 let start = from_block.unwrap_or(0);
349
350 let latest_block = self.provider().best_block_number().map_err(Eth::Error::from_eth_err)?;
351 if start > latest_block {
352 return Err(EthApiError::HeaderNotFound(start.into()).into());
354 }
355 let end = to_block.unwrap_or(latest_block);
356
357 if start > end {
358 return Err(EthApiError::InvalidParams(
359 "invalid parameters: fromBlock cannot be greater than toBlock".to_string(),
360 )
361 .into())
362 }
363
364 let distance = end.saturating_sub(start);
366 if distance > self.inner.eth_config.max_trace_filter_blocks {
367 return Err(EthApiError::InvalidParams(
368 "Block range too large; currently limited to 100 blocks".to_string(),
369 )
370 .into())
371 }
372
373 let mut all_traces = Vec::new();
374 let mut block_traces = Vec::with_capacity(self.inner.eth_config.max_tracing_requests);
375 for chunk_start in (start..=end).step_by(self.inner.eth_config.max_tracing_requests) {
376 let chunk_end =
377 std::cmp::min(chunk_start + self.inner.eth_config.max_tracing_requests as u64, end);
378
379 let blocks = self
381 .eth_api()
382 .spawn_blocking_io(move |this| {
383 Ok(this
384 .provider()
385 .recovered_block_range(chunk_start..=chunk_end)
386 .map_err(Eth::Error::from_eth_err)?
387 .into_iter()
388 .map(Arc::new)
389 .collect::<Vec<_>>())
390 })
391 .await?;
392
393 for block in &blocks {
395 let matcher = matcher.clone();
396 let traces = self.eth_api().trace_block_until(
397 block.hash().into(),
398 Some(block.clone()),
399 None,
400 TracingInspectorConfig::default_parity(),
401 move |tx_info, mut ctx| {
402 let mut traces = ctx
403 .take_inspector()
404 .into_parity_builder()
405 .into_localized_transaction_traces(tx_info);
406 traces.retain(|trace| matcher.matches(&trace.trace));
407 Ok(Some(traces))
408 },
409 );
410 block_traces.push(traces);
411 }
412
413 #[allow(clippy::iter_with_drain)]
414 let block_traces = futures::future::try_join_all(block_traces.drain(..)).await?;
415 all_traces.extend(block_traces.into_iter().flatten().flat_map(|traces| {
416 traces.into_iter().flatten().flat_map(|traces| traces.into_iter())
417 }));
418
419 for block in &blocks {
421 if let Some(base_block_reward) = self.calculate_base_block_reward(block.header())? {
422 all_traces.extend(
423 self.extract_reward_traces(
424 block.header(),
425 block.body().ommers(),
426 base_block_reward,
427 )
428 .into_iter()
429 .filter(|trace| matcher.matches(&trace.trace)),
430 );
431 } else {
432 break
435 }
436 }
437
438 if let Some(cutoff) = after.map(|a| a as usize) &&
440 cutoff < all_traces.len()
441 {
442 all_traces.drain(..cutoff);
443 after = None;
445 }
446
447 if let Some(count) = count {
449 let count = count as usize;
450 if count < all_traces.len() {
451 all_traces.truncate(count);
452 return Ok(all_traces)
453 }
454 };
455 }
456
457 if let Some(cutoff) = after.map(|a| a as usize) &&
460 cutoff >= all_traces.len()
461 {
462 return Ok(vec![])
463 }
464
465 Ok(all_traces)
466 }
467
468 pub async fn trace_block(
470 &self,
471 block_id: BlockId,
472 ) -> Result<Option<Vec<LocalizedTransactionTrace>>, Eth::Error> {
473 let traces = self.eth_api().trace_block_with(
474 block_id,
475 None,
476 TracingInspectorConfig::default_parity(),
477 |tx_info, mut ctx| {
478 let traces = ctx
479 .take_inspector()
480 .into_parity_builder()
481 .into_localized_transaction_traces(tx_info);
482 Ok(traces)
483 },
484 );
485
486 let block = self.eth_api().recovered_block(block_id);
487 let (maybe_traces, maybe_block) = futures::try_join!(traces, block)?;
488
489 let mut maybe_traces =
490 maybe_traces.map(|traces| traces.into_iter().flatten().collect::<Vec<_>>());
491
492 if let (Some(block), Some(traces)) = (maybe_block, maybe_traces.as_mut()) &&
493 let Some(base_block_reward) = self.calculate_base_block_reward(block.header())?
494 {
495 traces.extend(self.extract_reward_traces(
496 block.header(),
497 block.body().ommers(),
498 base_block_reward,
499 ));
500 }
501
502 Ok(maybe_traces)
503 }
504
505 pub async fn replay_block_transactions(
507 &self,
508 block_id: BlockId,
509 trace_types: HashSet<TraceType>,
510 ) -> Result<Option<Vec<TraceResultsWithTransactionHash>>, Eth::Error> {
511 self.eth_api()
512 .trace_block_with(
513 block_id,
514 None,
515 TracingInspectorConfig::from_parity_config(&trace_types),
516 move |tx_info, mut ctx| {
517 let mut full_trace = ctx
518 .take_inspector()
519 .into_parity_builder()
520 .into_trace_results(&ctx.result, &trace_types);
521
522 if let Some(ref mut state_diff) = full_trace.state_diff {
525 populate_state_diff(state_diff, &ctx.db, ctx.state.iter())
526 .map_err(Eth::Error::from_eth_err)?;
527 }
528
529 let trace = TraceResultsWithTransactionHash {
530 transaction_hash: tx_info.hash.expect("tx hash is set"),
531 full_trace,
532 };
533 Ok(trace)
534 },
535 )
536 .await
537 }
538
539 pub async fn trace_block_opcode_gas(
544 &self,
545 block_id: BlockId,
546 ) -> Result<Option<BlockOpcodeGas>, Eth::Error> {
547 let res = self
548 .eth_api()
549 .trace_block_inspector(
550 block_id,
551 None,
552 OpcodeGasInspector::default,
553 move |tx_info, ctx| {
554 let trace = TransactionOpcodeGas {
555 transaction_hash: tx_info.hash.expect("tx hash is set"),
556 opcode_gas: ctx.inspector.opcode_gas_iter().collect(),
557 };
558 Ok(trace)
559 },
560 )
561 .await?;
562
563 let Some(transactions) = res else { return Ok(None) };
564
565 let Some(block) = self.eth_api().recovered_block(block_id).await? else { return Ok(None) };
566
567 Ok(Some(BlockOpcodeGas {
568 block_hash: block.hash(),
569 block_number: block.number(),
570 transactions,
571 }))
572 }
573
574 pub async fn trace_block_storage_access(
577 &self,
578 block_id: BlockId,
579 ) -> Result<Option<BlockStorageAccess>, Eth::Error> {
580 let res = self
581 .eth_api()
582 .trace_block_inspector(
583 block_id,
584 None,
585 StorageInspector::default,
586 move |tx_info, ctx| {
587 let trace = TransactionStorageAccess {
588 transaction_hash: tx_info.hash.expect("tx hash is set"),
589 storage_access: ctx.inspector.accessed_slots().clone(),
590 unique_loads: ctx.inspector.unique_loads(),
591 warm_loads: ctx.inspector.warm_loads(),
592 };
593 Ok(trace)
594 },
595 )
596 .await?;
597
598 let Some(transactions) = res else { return Ok(None) };
599
600 let Some(block) = self.eth_api().recovered_block(block_id).await? else { return Ok(None) };
601
602 Ok(Some(BlockStorageAccess {
603 block_hash: block.hash(),
604 block_number: block.number(),
605 transactions,
606 }))
607 }
608}
609
610#[async_trait]
611impl<Eth> TraceApiServer<RpcTxReq<Eth::NetworkTypes>> for TraceApi<Eth>
612where
613 Eth: TraceExt + 'static,
614{
615 async fn trace_call(
619 &self,
620 call: RpcTxReq<Eth::NetworkTypes>,
621 trace_types: HashSet<TraceType>,
622 block_id: Option<BlockId>,
623 state_overrides: Option<StateOverride>,
624 block_overrides: Option<Box<BlockOverrides>>,
625 ) -> RpcResult<TraceResults> {
626 let _permit = self.acquire_trace_permit().await;
627 let request =
628 TraceCallRequest { call, trace_types, block_id, state_overrides, block_overrides };
629 Ok(Self::trace_call(self, request).await.map_err(Into::into)?)
630 }
631
632 async fn trace_call_many(
634 &self,
635 calls: Vec<(RpcTxReq<Eth::NetworkTypes>, HashSet<TraceType>)>,
636 block_id: Option<BlockId>,
637 ) -> RpcResult<Vec<TraceResults>> {
638 let _permit = self.acquire_trace_permit().await;
639 Ok(Self::trace_call_many(self, calls, block_id).await.map_err(Into::into)?)
640 }
641
642 async fn trace_raw_transaction(
644 &self,
645 data: Bytes,
646 trace_types: HashSet<TraceType>,
647 block_id: Option<BlockId>,
648 ) -> RpcResult<TraceResults> {
649 let _permit = self.acquire_trace_permit().await;
650 Ok(Self::trace_raw_transaction(self, data, trace_types, block_id)
651 .await
652 .map_err(Into::into)?)
653 }
654
655 async fn replay_block_transactions(
657 &self,
658 block_id: BlockId,
659 trace_types: HashSet<TraceType>,
660 ) -> RpcResult<Option<Vec<TraceResultsWithTransactionHash>>> {
661 let _permit = self.acquire_trace_permit().await;
662 Ok(Self::replay_block_transactions(self, block_id, trace_types)
663 .await
664 .map_err(Into::into)?)
665 }
666
667 async fn replay_transaction(
669 &self,
670 transaction: B256,
671 trace_types: HashSet<TraceType>,
672 ) -> RpcResult<TraceResults> {
673 let _permit = self.acquire_trace_permit().await;
674 Ok(Self::replay_transaction(self, transaction, trace_types).await.map_err(Into::into)?)
675 }
676
677 async fn trace_block(
679 &self,
680 block_id: BlockId,
681 ) -> RpcResult<Option<Vec<LocalizedTransactionTrace>>> {
682 let _permit = self.acquire_trace_permit().await;
683 Ok(Self::trace_block(self, block_id).await.map_err(Into::into)?)
684 }
685
686 async fn trace_filter(&self, filter: TraceFilter) -> RpcResult<Vec<LocalizedTransactionTrace>> {
693 let _permit = self.inner.blocking_task_guard.clone().acquire_many_owned(2).await;
694 Ok(Self::trace_filter(self, filter).await.map_err(Into::into)?)
695 }
696
697 async fn trace_get(
700 &self,
701 hash: B256,
702 indices: Vec<Index>,
703 ) -> RpcResult<Option<LocalizedTransactionTrace>> {
704 let _permit = self.acquire_trace_permit().await;
705 Ok(Self::trace_get(self, hash, indices.into_iter().map(Into::into).collect())
706 .await
707 .map_err(Into::into)?)
708 }
709
710 async fn trace_transaction(
712 &self,
713 hash: B256,
714 ) -> RpcResult<Option<Vec<LocalizedTransactionTrace>>> {
715 let _permit = self.acquire_trace_permit().await;
716 Ok(Self::trace_transaction(self, hash).await.map_err(Into::into)?)
717 }
718
719 async fn trace_transaction_opcode_gas(
721 &self,
722 tx_hash: B256,
723 ) -> RpcResult<Option<TransactionOpcodeGas>> {
724 let _permit = self.acquire_trace_permit().await;
725 Ok(Self::trace_transaction_opcode_gas(self, tx_hash).await.map_err(Into::into)?)
726 }
727
728 async fn trace_block_opcode_gas(&self, block_id: BlockId) -> RpcResult<Option<BlockOpcodeGas>> {
730 let _permit = self.acquire_trace_permit().await;
731 Ok(Self::trace_block_opcode_gas(self, block_id).await.map_err(Into::into)?)
732 }
733}
734
735impl<Eth> std::fmt::Debug for TraceApi<Eth> {
736 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
737 f.debug_struct("TraceApi").finish_non_exhaustive()
738 }
739}
740impl<Eth> Clone for TraceApi<Eth> {
741 fn clone(&self) -> Self {
742 Self { inner: Arc::clone(&self.inner) }
743 }
744}
745
746struct TraceApiInner<Eth> {
747 eth_api: Eth,
749 blocking_task_guard: BlockingTaskGuard,
751 eth_config: EthConfig,
753}
754
755#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
758#[serde(rename_all = "camelCase")]
759pub struct TransactionStorageAccess {
760 pub transaction_hash: B256,
762 pub storage_access: HashMap<Address, HashMap<B256, u64>>,
764 pub unique_loads: u64,
766 pub warm_loads: u64,
768}
769
770#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
772#[serde(rename_all = "camelCase")]
773pub struct BlockStorageAccess {
774 pub block_hash: BlockHash,
776 pub block_number: u64,
778 pub transactions: Vec<TransactionStorageAccess>,
780}
781
782fn reward_trace<H: BlockHeader>(header: &H, reward: RewardAction) -> LocalizedTransactionTrace {
785 LocalizedTransactionTrace {
786 block_hash: Some(header.hash_slow()),
787 block_number: Some(header.number()),
788 transaction_hash: None,
789 transaction_position: None,
790 trace: TransactionTrace {
791 trace_address: vec![],
792 subtraces: 0,
793 action: Action::Reward(reward),
794 error: None,
795 result: None,
796 },
797 }
798}