1use crate::{ConfigureEvm, Database, DynDatabase, EvmEnv, TxEnvFor};
4use alloc::{boxed::Box, sync::Arc, vec::Vec};
5use alloy_consensus::{
6 transaction::{Either, Recovered, TransactionEnvelope},
7 BlockHeader as _, Header, Transaction, TxEip2930, TxEip4844, TxLegacy,
8};
9use alloy_eip7928::{
10 bal::DecodedBal, compute_block_access_list_hash_with_buf, BlockAccessIndex, BlockAccessList,
11};
12use alloy_eips::{
13 eip2718::{Typed2718, WithEncoded},
14 eip2930::AccessList,
15};
16use alloy_primitives::{Address, B256};
17use core::fmt::Debug;
18use evm2::interpreter::{Interpreter, Message, MessageResult};
19use reth_execution_types::{BlockExecutionResult, StateUpdate};
20use reth_primitives_traits::{
21 Block, HeaderTy, NodePrimitives, ReceiptTy, RecoveredBlock, SealedHeader, SignedTransaction,
22 TxTy,
23};
24use reth_storage_api::StateProvider;
25use reth_trie_common::{bundle_state::BundleState, updates::TrieUpdates, HashedPostState};
26
27#[cfg(feature = "std")]
28use evm2::evm::{CacheDB, Db};
29#[cfg(feature = "std")]
30use reth_execution_types::BundleSource;
31#[cfg(feature = "std")]
32use reth_primitives_traits::BlockTy;
33
34pub use evm2::block::{
35 map_database_error, map_handler_error, BlockTransactionResult, CommitChanges, GasOutput,
36 ReceiptBuilderCtx,
37};
38pub use reth_execution_errors::{
39 BlockExecutionError, BlockValidationError, InternalBlockExecutionError, InvalidTxError,
40};
41pub use reth_execution_types::{BlockExecutionOutput, ExecutionOutcome};
42
43#[auto_impl::auto_impl(&, Arc)]
45pub trait ReceiptBuilder {
46 type Transaction: SignedTransaction + TransactionEnvelope<TxType: Send + 'static>;
48 type Receipt: reth_primitives_traits::Receipt;
50
51 fn build_receipt<T: evm2::EvmTypes>(
53 &self,
54 ctx: ReceiptBuilderCtx<
55 <Self::Transaction as TransactionEnvelope>::TxType,
56 evm2::TxResult<T>,
57 >,
58 ) -> Self::Receipt;
59}
60
61pub trait Evm {
63 type EvmTypes: evm2::EvmTypes<Tx = Self::Transaction>;
65 type Transaction;
67
68 fn transact(
70 &mut self,
71 transaction: &Recovered<Self::Transaction>,
72 ) -> Result<evm2::TxResultWithState<Self::EvmTypes>, BlockExecutionError>;
73
74 fn transact_commit(
76 &mut self,
77 transaction: &Recovered<Self::Transaction>,
78 ) -> Result<evm2::TxResult<Self::EvmTypes>, BlockExecutionError>;
79
80 fn transact_result(
82 &mut self,
83 transaction: &Recovered<Self::Transaction>,
84 ) -> Result<evm2::TxResult<Self::EvmTypes>, BlockExecutionError>;
85
86 fn transact_with_inspector<I>(
88 &mut self,
89 transaction: &Recovered<Self::Transaction>,
90 inspector: I,
91 ) -> Result<(I, evm2::TxResultWithState<Self::EvmTypes>), BlockExecutionError>
92 where
93 I: evm2::Inspector<Self::EvmTypes> + 'static;
94
95 fn set_inspector<I>(&mut self, inspector: I)
97 where
98 I: evm2::Inspector<Self::EvmTypes> + 'static;
99
100 unsafe fn with_inspector<I, R>(&mut self, f: impl FnOnce(&mut I) -> R) -> Option<R>
108 where
109 I: evm2::Inspector<Self::EvmTypes> + 'static;
110
111 fn take_inspector(&mut self) -> Option<Box<dyn evm2::Inspector<Self::EvmTypes> + '_>>;
113
114 fn state_db_mut(&mut self) -> &mut dyn DynDatabase;
116
117 fn commit_state(&mut self, state: &evm2::evm::PendingState);
119
120 fn take_state_cache(&mut self) -> evm2::evm::Cache;
122
123 fn precompile_ids(&self) -> Vec<(Address, evm2::precompiles::PrecompileId)>;
125
126 fn has_precompile(&self, address: &Address) -> bool;
128
129 fn account_info(
131 &mut self,
132 address: &Address,
133 ) -> Result<Option<evm2::evm::AccountInfo>, BlockExecutionError>;
134
135 fn move_precompiles(
137 &mut self,
138 moves: impl IntoIterator<Item = (Address, Address)>,
139 ) -> Result<(), evm2::precompiles::MovePrecompileError>;
140
141 fn transact_and_discard<R>(
144 &mut self,
145 transaction: &Recovered<Self::Transaction>,
146 observe: impl FnOnce(&evm2::ExecutedTx<'_, '_, Self::EvmTypes>) -> R,
147 ) -> Result<R, BlockExecutionError>;
148}
149
150impl<'a, T: evm2::EvmTypes<Tx: Typed2718>> Evm for evm2::Evm<'a, T> {
151 type EvmTypes = T;
152 type Transaction = T::Tx;
153
154 fn transact(
155 &mut self,
156 transaction: &Recovered<Self::Transaction>,
157 ) -> Result<evm2::TxResultWithState<T>, BlockExecutionError> {
158 evm2::Evm::transact(self, transaction)
159 .map(|executed| executed.detach())
160 .map_err(map_handler_error)
161 }
162
163 fn transact_commit(
164 &mut self,
165 transaction: &Recovered<Self::Transaction>,
166 ) -> Result<evm2::TxResult<T>, BlockExecutionError> {
167 execute_result(self, transaction, true)
168 }
169
170 fn transact_result(
171 &mut self,
172 transaction: &Recovered<Self::Transaction>,
173 ) -> Result<evm2::TxResult<T>, BlockExecutionError> {
174 execute_result(self, transaction, false)
175 }
176
177 fn transact_with_inspector<I: evm2::Inspector<T> + 'a>(
178 &mut self,
179 transaction: &Recovered<Self::Transaction>,
180 mut inspector: I,
181 ) -> Result<(I, evm2::TxResultWithState<T>), BlockExecutionError> {
182 let result = evm2::Evm::transact_with_inspector(self, transaction, &mut inspector)
185 .map(|executed| executed.detach())
186 .map_err(map_handler_error);
187 result.map(|result| (inspector, result))
188 }
189
190 fn set_inspector<I: evm2::Inspector<T> + 'a>(&mut self, inspector: I) {
191 evm2::Evm::set_inspector(self, inspector);
192 }
193
194 unsafe fn with_inspector<I, R>(&mut self, f: impl FnOnce(&mut I) -> R) -> Option<R>
195 where
196 I: evm2::Inspector<T> + 'static,
197 {
198 let inspector: &mut (dyn evm2::evm::NonStaticAny + 'a) = &mut **self.inspector_mut()?;
199 if evm2::evm::NonStaticAny::type_id(inspector) != core::any::TypeId::of::<I>() {
200 return None
201 }
202 Some(f(unsafe { inspector.downcast_mut_unchecked::<I>() }))
205 }
206
207 fn take_inspector(&mut self) -> Option<Box<dyn evm2::Inspector<T> + '_>> {
208 self.clear_inspector()
209 }
210
211 fn state_db_mut(&mut self) -> &mut dyn DynDatabase {
212 self.overlay_db_mut()
213 }
214
215 fn commit_state(&mut self, state: &evm2::evm::PendingState) {
216 self.overlay_db_mut().commit_pending(state);
217 }
218
219 fn take_state_cache(&mut self) -> evm2::evm::Cache {
220 core::mem::take(&mut self.overlay_db_mut().cache)
221 }
222
223 fn precompile_ids(&self) -> Vec<(Address, evm2::precompiles::PrecompileId)> {
224 self.precompiles().precompile_ids()
225 }
226
227 fn has_precompile(&self, address: &Address) -> bool {
228 self.precompiles().contains(address)
229 }
230
231 fn account_info(
232 &mut self,
233 address: &Address,
234 ) -> Result<Option<evm2::evm::AccountInfo>, BlockExecutionError> {
235 self.state_mut().account_info_untracked(address).map_err(map_database_error)
236 }
237
238 fn move_precompiles(
239 &mut self,
240 moves: impl IntoIterator<Item = (Address, Address)>,
241 ) -> Result<(), evm2::precompiles::MovePrecompileError> {
242 self.precompiles_mut().move_precompiles(&moves.into_iter().collect::<Vec<_>>())
243 }
244
245 fn transact_and_discard<R>(
246 &mut self,
247 transaction: &Recovered<Self::Transaction>,
248 observe: impl FnOnce(&evm2::ExecutedTx<'_, '_, T>) -> R,
249 ) -> Result<R, BlockExecutionError> {
250 let executed = self.transact(transaction).map_err(map_handler_error)?;
251 let observed = observe(&executed);
252 drop(executed);
253 Ok(observed)
254 }
255}
256
257fn execute_result<T: evm2::EvmTypes<Tx: Typed2718>>(
258 evm: &mut evm2::Evm<'_, T>,
259 transaction: &Recovered<T::Tx>,
260 commit: bool,
261) -> Result<evm2::TxResult<T>, BlockExecutionError> {
262 let executed = evm2::Evm::transact(evm, transaction).map_err(map_handler_error)?;
263 Ok(if commit { executed.commit() } else { executed.discard() })
264}
265
266#[derive(Debug)]
272struct TracedInspector<I>(I);
273
274impl<I: 'static> TracedInspector<I> {
275 fn downcast<T: evm2::EvmTypesHost>(inspector: Box<dyn evm2::Inspector<T> + '_>) -> Option<I> {
277 let erased: &dyn evm2::evm::NonStaticAny = &*inspector;
278 if erased.type_id() != core::any::TypeId::of::<Self>() {
279 return None
280 }
281 let traced = unsafe { Box::from_raw(Box::into_raw(inspector).cast::<Self>()) };
285 Some(traced.0)
286 }
287}
288
289impl<T: evm2::EvmTypesHost, I: evm2::Inspector<T>> evm2::Inspector<T> for TracedInspector<I> {
290 fn initialize_interp(&mut self, interp: &mut Interpreter<'_, '_, T>) {
291 self.0.initialize_interp(interp);
292 }
293
294 fn inspector_config(&self) -> evm2::InspectorConfig {
295 self.0.inspector_config()
296 }
297
298 fn step(&mut self, interp: &mut Interpreter<'_, '_, T>) {
299 self.0.step(interp);
300 }
301
302 fn step_end(&mut self, interp: &mut Interpreter<'_, '_, T>) {
303 self.0.step_end(interp);
304 }
305
306 fn log(&mut self, log: &alloy_primitives::Log, host: &mut T::Host<'_>) {
307 self.0.log(log, host);
308 }
309
310 fn call(
311 &mut self,
312 interp: &mut Interpreter<'_, '_, T>,
313 message: &mut Message<T>,
314 ) -> Option<MessageResult<T>> {
315 self.0.call(interp, message)
316 }
317
318 fn call_end(
319 &mut self,
320 interp: &mut Interpreter<'_, '_, T>,
321 message: &Message<T>,
322 result: &mut MessageResult<T>,
323 ) {
324 self.0.call_end(interp, message, result);
325 }
326
327 fn create(
328 &mut self,
329 interp: &mut Interpreter<'_, '_, T>,
330 message: &mut Message<T>,
331 ) -> Option<MessageResult<T>> {
332 self.0.create(interp, message)
333 }
334
335 fn create_end(
336 &mut self,
337 interp: &mut Interpreter<'_, '_, T>,
338 message: &Message<T>,
339 result: &mut MessageResult<T>,
340 ) {
341 self.0.create_end(interp, message, result);
342 }
343
344 fn selfdestruct(
345 &mut self,
346 contract: &Address,
347 target: &Address,
348 value: &alloy_primitives::U256,
349 host: &mut T::Host<'_>,
350 ) {
351 self.0.selfdestruct(contract, target, value, host);
352 }
353}
354
355pub trait BlockExecutor: Sized {
357 type Transaction;
359 type Receipt;
361 type Evm: Evm;
363 type TransactionResultWithState: BlockTransactionResult<<Self::Evm as Evm>::EvmTypes> + Send;
365 type BlockAccessList: Send + Sync;
367
368 fn evm(&self) -> &Self::Evm;
370
371 fn evm_mut(&mut self) -> &mut Self::Evm;
373
374 fn set_state_hook(&mut self, _hook: impl FnMut(StateUpdate) + Send + 'static) -> bool {
379 false
380 }
381
382 fn convert_block_access_list(
384 block_access_list: &BlockAccessList,
385 ) -> Result<Self::BlockAccessList, BlockExecutionError>;
386
387 fn set_block_access_list(&mut self, block_access_list: Arc<Self::BlockAccessList>);
389
390 fn set_block_access_index(&mut self, index: BlockAccessIndex);
392
393 fn enable_block_access_list_builder(&mut self);
395
396 fn take_block_access_list(&mut self) -> Option<BlockAccessList>;
398
399 fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError>;
401
402 fn into_state(self) -> BundleState;
405
406 fn execute_transaction_with_commit_condition(
412 &mut self,
413 transaction: impl ExecutorTx<Self>,
414 f: impl FnOnce(
415 &evm2::TxResult<<Self::Evm as Evm>::EvmTypes>,
416 evm2::TxStateChanges<'_>,
417 ) -> CommitChanges,
418 ) -> Result<Option<GasOutput>, BlockExecutionError> {
419 let output = self.execute_transaction_without_commit(transaction)?;
420 let result = output.result();
421 if f(&result.result, result.pending_state.changes()).should_commit() {
422 self.commit_transaction(output).map(Some)
423 } else {
424 Ok(None)
425 }
426 }
427
428 fn validate_transaction_gas_limit(&mut self, gas_limit: u64)
432 -> Result<(), BlockExecutionError>;
433
434 fn execute_transaction_without_commit(
436 &mut self,
437 transaction: impl ExecutorTx<Self>,
438 ) -> Result<Self::TransactionResultWithState, BlockExecutionError>;
439
440 fn inspect_transaction_without_commit<I>(
448 &mut self,
449 transaction: impl ExecutorTx<Self>,
450 inspector: I,
451 ) -> Result<(I, Self::TransactionResultWithState), BlockExecutionError>
452 where
453 I: evm2::Inspector<<Self::Evm as Evm>::EvmTypes> + 'static,
454 {
455 self.evm_mut().set_inspector(TracedInspector(inspector));
456 let output = self.execute_transaction_without_commit(transaction);
457 let inspector =
458 self.evm_mut().take_inspector().and_then(TracedInspector::downcast).ok_or_else(|| {
459 BlockExecutionError::msg("block executor replaced the tracing inspector")
460 });
461 let (inspector, output) = (inspector?, output?);
462 Ok((inspector, output))
463 }
464
465 fn commit_transaction(
467 &mut self,
468 output: Self::TransactionResultWithState,
469 ) -> Result<GasOutput, BlockExecutionError>;
470
471 fn execute_transaction_with_result_closure(
474 &mut self,
475 transaction: impl ExecutorTx<Self>,
476 f: impl FnOnce(&evm2::TxResult<<Self::Evm as Evm>::EvmTypes>),
477 ) -> Result<GasOutput, BlockExecutionError> {
478 self.execute_transaction_with_commit_condition(transaction, |result, _| {
479 f(result);
480 CommitChanges::Yes
481 })
482 .map(Option::unwrap_or_default)
483 }
484
485 fn execute_transaction(
487 &mut self,
488 transaction: impl ExecutorTx<Self>,
489 ) -> Result<GasOutput, BlockExecutionError> {
490 self.execute_transaction_with_result_closure(transaction, |_| {})
491 }
492
493 fn receipts(&self) -> &[Self::Receipt];
495
496 fn finish_with_block_access_list(
498 self,
499 ) -> Result<(BlockExecutionOutput<Self::Receipt>, Option<BlockAccessList>), BlockExecutionError>;
500
501 fn finish_with_prepared_block_access_list(
506 self,
507 ) -> Result<(BlockExecutionOutput<Self::Receipt>, Option<evm2::evm::Bal>), BlockExecutionError>
508 {
509 let (output, bal) = self.finish_with_block_access_list()?;
510 let bal = bal
511 .map(|bal| evm2::evm::Bal::try_from(bal.as_slice()))
512 .transpose()
513 .map_err(BlockExecutionError::other)?;
514 Ok((output, bal))
515 }
516
517 fn finish(self) -> Result<BlockExecutionOutput<Self::Receipt>, BlockExecutionError> {
519 self.finish_with_block_access_list().map(|(output, _)| output)
520 }
521}
522
523pub trait BlockExecutorFactory {
525 type EvmFactory;
527 type EvmTypes: evm2::EvmTypes<
529 TxResultExt: Send + Sync,
530 SpecId: Eq + core::hash::Hash + Debug + Send + Sync + 'static,
531 >;
532 type Transaction: Debug + Clone + Send + Sync + 'static;
534 type Receipt;
536 type Evm<'a>: Evm<
538 EvmTypes = Self::EvmTypes,
539 Transaction = <Self::EvmTypes as evm2::EvmTypesHost>::Tx,
540 >;
541 type EvmEnv: EvmEnv<EvmTypes = Self::EvmTypes>;
543 type ExecutionCtx<'a>: Debug + Clone + Send
545 where
546 Self: 'a;
547 type Executor<'a>: BlockExecutor<
549 Transaction = Self::Transaction,
550 Receipt = Self::Receipt,
551 Evm = Self::Evm<'a>,
552 BlockAccessList = evm2::evm::Bal,
553 >
554 where
555 Self: 'a;
556
557 fn create_executor<'a>(
559 &'a self,
560 evm: Self::Evm<'a>,
561 ctx: Self::ExecutionCtx<'a>,
562 ) -> Self::Executor<'a>
563 where
564 Self: 'a;
565
566 fn evm_factory(&self) -> &Self::EvmFactory;
568
569 fn evm_with_env<'a, DB>(&self, db: DB, evm_env: Self::EvmEnv) -> Self::Evm<'a>
571 where
572 DB: DynDatabase + 'a;
573
574 #[cfg(feature = "std")]
576 fn evm_with_database<'a, DB>(&self, db: DB, evm_env: Self::EvmEnv) -> Self::Evm<'a>
577 where
578 DB: Database + 'a,
579 {
580 self.evm_with_env(Db::new(db), evm_env)
581 }
582}
583
584#[expect(missing_debug_implementations)]
586#[non_exhaustive]
587pub struct BlockAssemblerInput<'a, 'b, F: BlockExecutorFactory + 'a, H = Header> {
588 pub evm_env: F::EvmEnv,
590 pub execution_ctx: F::ExecutionCtx<'a>,
592 pub parent: &'a SealedHeader<H>,
594 pub transactions: Vec<F::Transaction>,
596 pub output: &'b BlockExecutionResult<F::Receipt>,
598 pub execution_state: &'b BundleState,
600 pub state_provider: &'b dyn StateProvider,
602 pub state_root: B256,
604 pub block_access_list_hash: Option<B256>,
606}
607
608impl<'a, 'b, F: BlockExecutorFactory + 'a, H> BlockAssemblerInput<'a, 'b, F, H> {
609 #[expect(clippy::too_many_arguments)]
611 pub const fn new(
612 evm_env: F::EvmEnv,
613 execution_ctx: F::ExecutionCtx<'a>,
614 parent: &'a SealedHeader<H>,
615 transactions: Vec<F::Transaction>,
616 output: &'b BlockExecutionResult<F::Receipt>,
617 execution_state: &'b BundleState,
618 state_provider: &'b dyn StateProvider,
619 state_root: B256,
620 block_access_list_hash: Option<B256>,
621 ) -> Self {
622 Self {
623 evm_env,
624 execution_ctx,
625 parent,
626 transactions,
627 output,
628 execution_state,
629 state_provider,
630 state_root,
631 block_access_list_hash,
632 }
633 }
634}
635
636#[auto_impl::auto_impl(&, Arc)]
638pub trait BlockAssembler<F: BlockExecutorFactory> {
639 type Block: Block;
641
642 fn assemble_block(
644 &self,
645 input: BlockAssemblerInput<'_, '_, F, <Self::Block as Block>::Header>,
646 ) -> Result<Self::Block, BlockExecutionError>;
647}
648
649#[derive(Debug, Clone)]
651pub struct BlockBuilderOutcome<N: NodePrimitives> {
652 pub execution_result: BlockExecutionResult<N::Receipt>,
654 pub execution_state: BundleState,
656 pub hashed_state: HashedPostState,
658 pub trie_updates: TrieUpdates,
660 pub block: RecoveredBlock<N::Block>,
662 pub block_access_list: Option<DecodedBal>,
664}
665
666pub trait BlockBuilder: Sized {
668 type Primitives: NodePrimitives;
670 type Executor: BlockExecutor<
672 Transaction = TxTy<Self::Primitives>,
673 Receipt = ReceiptTy<Self::Primitives>,
674 Evm: Evm<Transaction: FromTxWithEncoded<TxTy<Self::Primitives>>>,
675 >;
676 type EvmEnv: EvmEnv;
678
679 fn evm_env(&self) -> &Self::EvmEnv;
681
682 fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError>;
684
685 fn execute_transaction_with_commit_condition(
688 &mut self,
689 tx: impl ExecutorTx<Self::Executor>,
690 f: impl FnOnce(
691 &evm2::TxResult<<<Self::Executor as BlockExecutor>::Evm as Evm>::EvmTypes>,
692 evm2::TxStateChanges<'_>,
693 ) -> CommitChanges,
694 ) -> Result<Option<GasOutput>, BlockExecutionError>;
695
696 fn execute_transaction_with_result_closure(
699 &mut self,
700 tx: impl ExecutorTx<Self::Executor>,
701 f: impl FnOnce(&<Self::Executor as BlockExecutor>::TransactionResultWithState),
702 ) -> Result<GasOutput, BlockExecutionError>;
703
704 fn execute_transaction(
706 &mut self,
707 tx: impl ExecutorTx<Self::Executor>,
708 ) -> Result<GasOutput, BlockExecutionError> {
709 self.execute_transaction_with_commit_condition(tx, |_, _| CommitChanges::Yes)
710 .map(Option::unwrap_or_default)
711 }
712
713 fn finish(
715 self,
716 state_provider: impl StateProvider,
717 state_root_precomputed: Option<(B256, TrieUpdates)>,
718 ) -> Result<BlockBuilderOutcome<Self::Primitives>, BlockExecutionError> {
719 self.finish_with_state_root(state_provider, move |_| Ok(state_root_precomputed))
720 }
721
722 fn finish_with_state_root(
724 self,
725 state_provider: impl StateProvider,
726 state_root: impl FnOnce(
727 &BlockExecutionOutput<ReceiptTy<Self::Primitives>>,
728 ) -> Result<Option<(B256, TrieUpdates)>, BlockExecutionError>,
729 ) -> Result<BlockBuilderOutcome<Self::Primitives>, BlockExecutionError>;
730
731 fn set_state_hook(&mut self, _hook: impl FnMut(StateUpdate) + Send + 'static) -> bool {
735 false
736 }
737
738 fn executor_mut(&mut self) -> &mut Self::Executor;
740
741 fn executor(&self) -> &Self::Executor;
743
744 fn evm_mut(&mut self) -> &mut <Self::Executor as BlockExecutor>::Evm {
746 self.executor_mut().evm_mut()
747 }
748
749 fn evm(&self) -> &<Self::Executor as BlockExecutor>::Evm {
751 self.executor().evm()
752 }
753
754 fn into_executor(self) -> Self::Executor;
756}
757
758#[derive(Debug)]
760pub struct BasicBlockBuilder<'a, F, Executor, Assembler, N>
761where
762 F: BlockExecutorFactory + 'a,
763 N: NodePrimitives,
764{
765 pub executor: Executor,
767 pub evm_env: F::EvmEnv,
769 pub transactions: Vec<Recovered<TxTy<N>>>,
771 pub ctx: F::ExecutionCtx<'a>,
773 pub parent: &'a SealedHeader<HeaderTy<N>>,
775 pub assembler: &'a Assembler,
777}
778
779impl<'a, F, Assembler, N> BasicBlockBuilder<'a, F, F::Executor<'a>, Assembler, N>
780where
781 F: BlockExecutorFactory<Transaction = TxTy<N>, Receipt = ReceiptTy<N>> + 'a,
782 Assembler: BlockAssembler<F, Block = N::Block> + 'a,
783 N: NodePrimitives,
784{
785 pub fn new(
787 executor_factory: &'a F,
788 assembler: &'a Assembler,
789 evm: F::Evm<'a>,
790 evm_env: F::EvmEnv,
791 parent: &'a SealedHeader<HeaderTy<N>>,
792 ctx: F::ExecutionCtx<'a>,
793 ) -> Self {
794 Self {
795 executor: executor_factory.create_executor(evm, ctx.clone()),
796 evm_env,
797 transactions: Vec::new(),
798 ctx,
799 parent,
800 assembler,
801 }
802 }
803}
804
805pub trait ExecutorTx<Executor: BlockExecutor>:
807 ExecutableTxParts<Recovered<<Executor::Evm as Evm>::Transaction>, Executor::Transaction>
808{
809}
810
811impl<T, Executor> ExecutorTx<Executor> for T
812where
813 Executor: BlockExecutor,
814 T: ExecutableTxParts<Recovered<<Executor::Evm as Evm>::Transaction>, Executor::Transaction>,
815{
816}
817
818impl<'a, F, Executor, Assembler, N> BlockBuilder
819 for BasicBlockBuilder<'a, F, Executor, Assembler, N>
820where
821 F: BlockExecutorFactory<Transaction = TxTy<N>, Receipt = ReceiptTy<N>>,
822 Executor: BlockExecutor<
823 Transaction = TxTy<N>,
824 Receipt = ReceiptTy<N>,
825 Evm: Evm<EvmTypes = F::EvmTypes>,
826 >,
827 Assembler: BlockAssembler<F, Block = N::Block>,
828 N: NodePrimitives,
829 TxTy<N>: Clone,
830 <<Executor as BlockExecutor>::Evm as Evm>::Transaction: FromTxWithEncoded<TxTy<N>>,
831{
832 type Primitives = N;
833 type Executor = Executor;
834 type EvmEnv = F::EvmEnv;
835
836 fn evm_env(&self) -> &Self::EvmEnv {
837 &self.evm_env
838 }
839
840 fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> {
841 self.executor.apply_pre_execution_changes()
842 }
843
844 fn execute_transaction_with_commit_condition(
845 &mut self,
846 tx: impl ExecutorTx<Self::Executor>,
847 f: impl FnOnce(
848 &evm2::TxResult<<<Self::Executor as BlockExecutor>::Evm as Evm>::EvmTypes>,
849 evm2::TxStateChanges<'_>,
850 ) -> CommitChanges,
851 ) -> Result<Option<GasOutput>, BlockExecutionError> {
852 let (tx_env, tx) = tx.into_parts();
853 if let Some(output) =
854 self.executor.execute_transaction_with_commit_condition((tx_env, &tx), f)?
855 {
856 self.transactions.push(Recovered::new_unchecked(tx.tx().clone(), *tx.signer()));
857 Ok(Some(output))
858 } else {
859 Ok(None)
860 }
861 }
862
863 fn execute_transaction_with_result_closure(
864 &mut self,
865 tx: impl ExecutorTx<Self::Executor>,
866 f: impl FnOnce(&<Self::Executor as BlockExecutor>::TransactionResultWithState),
867 ) -> Result<GasOutput, BlockExecutionError> {
868 let (tx_env, tx) = tx.into_parts();
869 let output = self.executor.execute_transaction_without_commit((tx_env, &tx))?;
870 f(&output);
871 let gas_output = self.executor.commit_transaction(output)?;
872 self.transactions.push(Recovered::new_unchecked(tx.tx().clone(), *tx.signer()));
873 Ok(gas_output)
874 }
875
876 fn finish_with_state_root(
877 self,
878 state_provider: impl StateProvider,
879 state_root: impl FnOnce(
880 &BlockExecutionOutput<ReceiptTy<Self::Primitives>>,
881 ) -> Result<Option<(B256, TrieUpdates)>, BlockExecutionError>,
882 ) -> Result<BlockBuilderOutcome<N>, BlockExecutionError> {
883 let Self { executor, evm_env, transactions, ctx, parent, assembler } = self;
884
885 let (output, block_access_list) = executor.finish_with_block_access_list()?;
886 let block_access_list = block_access_list.map(|bal| {
887 let mut raw = Vec::new();
888 let hash = compute_block_access_list_hash_with_buf(&bal, &mut raw);
889 DecodedBal::new_unchecked(bal.into(), raw.into(), hash)
890 });
891 let block_access_list_hash = block_access_list.as_ref().map(DecodedBal::hash);
892 let hashed_state =
893 state_provider.hashed_post_state(&output.state).map_err(BlockExecutionError::other)?;
894 let (state_root, trie_updates) = match state_root(&output)? {
895 Some(precomputed) => precomputed,
896 None => state_provider
897 .state_root_with_updates(hashed_state.clone())
898 .map_err(BlockExecutionError::other)?,
899 };
900 let (transactions, senders) = transactions.into_iter().map(|tx| tx.into_parts()).unzip();
901
902 let block = assembler.assemble_block(BlockAssemblerInput {
903 evm_env,
904 execution_ctx: ctx,
905 parent,
906 transactions,
907 output: &output.result,
908 execution_state: &output.state,
909 state_provider: &state_provider,
910 state_root,
911 block_access_list_hash,
912 })?;
913 let block = RecoveredBlock::new_unhashed(block, senders);
914
915 Ok(BlockBuilderOutcome {
916 execution_result: output.result,
917 execution_state: output.state,
918 hashed_state,
919 trie_updates,
920 block,
921 block_access_list,
922 })
923 }
924
925 fn set_state_hook(&mut self, hook: impl FnMut(StateUpdate) + Send + 'static) -> bool {
926 self.executor.set_state_hook(hook)
927 }
928
929 fn executor_mut(&mut self) -> &mut Self::Executor {
930 &mut self.executor
931 }
932
933 fn executor(&self) -> &Self::Executor {
934 &self.executor
935 }
936
937 fn into_executor(self) -> Self::Executor {
938 self.executor
939 }
940}
941
942pub trait Executor<DB: Database>: Sized {
944 type Primitives: NodePrimitives;
946 type Error;
948
949 fn execute_one(
951 &mut self,
952 block: &RecoveredBlock<<Self::Primitives as NodePrimitives>::Block>,
953 ) -> Result<BlockExecutionResult<<Self::Primitives as NodePrimitives>::Receipt>, Self::Error>;
954
955 fn execute_one_with_state_hook<F>(
957 &mut self,
958 block: &RecoveredBlock<<Self::Primitives as NodePrimitives>::Block>,
959 state_hook: F,
960 ) -> Result<BlockExecutionResult<<Self::Primitives as NodePrimitives>::Receipt>, Self::Error>
961 where
962 F: FnMut(StateUpdate) + Send + 'static;
963
964 fn execute(
966 mut self,
967 block: &RecoveredBlock<<Self::Primitives as NodePrimitives>::Block>,
968 ) -> Result<BlockExecutionOutput<<Self::Primitives as NodePrimitives>::Receipt>, Self::Error>
969 {
970 let result = self.execute_one(block)?;
971 let state = self.into_state();
972 Ok(BlockExecutionOutput::new(result, state))
973 }
974
975 fn execute_with_state_hook<F>(
978 mut self,
979 block: &RecoveredBlock<<Self::Primitives as NodePrimitives>::Block>,
980 state_hook: F,
981 ) -> Result<BlockExecutionOutput<<Self::Primitives as NodePrimitives>::Receipt>, Self::Error>
982 where
983 F: FnMut(StateUpdate) + Send + 'static,
984 {
985 let result = self.execute_one_with_state_hook(block, state_hook)?;
986 let state = self.into_state();
987 Ok(BlockExecutionOutput::new(result, state))
988 }
989
990 fn execute_with_state_closure<F>(
992 mut self,
993 block: &RecoveredBlock<<Self::Primitives as NodePrimitives>::Block>,
994 mut f: F,
995 ) -> Result<BlockExecutionOutput<<Self::Primitives as NodePrimitives>::Receipt>, Self::Error>
996 where
997 F: FnMut(&BundleState),
998 {
999 let result = self.execute_one(block)?;
1000 let state = self.into_state();
1001 f(&state);
1002
1003 Ok(BlockExecutionOutput::new(result, state))
1004 }
1005
1006 fn execute_with_state_closure_always<F>(
1009 mut self,
1010 block: &RecoveredBlock<<Self::Primitives as NodePrimitives>::Block>,
1011 mut f: F,
1012 ) -> Result<BlockExecutionOutput<<Self::Primitives as NodePrimitives>::Receipt>, Self::Error>
1013 where
1014 F: FnMut(&BundleState),
1015 {
1016 let result = self.execute_one(block);
1017 let state = self.into_state();
1018 f(&state);
1019
1020 Ok(BlockExecutionOutput::new(result?, state))
1021 }
1022
1023 fn execute_batch<'a, I>(
1025 mut self,
1026 blocks: I,
1027 ) -> Result<ExecutionOutcome<<Self::Primitives as NodePrimitives>::Receipt>, Self::Error>
1028 where
1029 I: IntoIterator<Item = &'a RecoveredBlock<<Self::Primitives as NodePrimitives>::Block>>,
1030 {
1031 let blocks_iter = blocks.into_iter();
1032 let capacity = blocks_iter.size_hint().0;
1033 let mut results = Vec::with_capacity(capacity);
1034 let mut first_block = None;
1035 for block in blocks_iter {
1036 if first_block.is_none() {
1037 first_block = Some(block.header().number());
1038 }
1039 results.push(self.execute_one(block)?);
1040 }
1041
1042 Ok(ExecutionOutcome::from_blocks(
1043 first_block.unwrap_or_default(),
1044 self.into_state(),
1045 results,
1046 ))
1047 }
1048
1049 fn size_hint(&self) -> usize;
1051
1052 fn into_state(self) -> BundleState;
1054
1055 fn take_bal(&mut self) -> Option<BlockAccessList>;
1057}
1058
1059#[cfg(feature = "std")]
1061#[expect(missing_debug_implementations)]
1062pub struct BasicBlockExecutor<Evm, DB: Database> {
1063 evm_config: Evm,
1064 batch_database: CacheDB<Db<DB>>,
1065 batch_state: BundleState,
1066 block_access_list: Option<BlockAccessList>,
1067}
1068
1069#[cfg(feature = "std")]
1070impl<Evm, DB: Database> BasicBlockExecutor<Evm, DB> {
1071 pub fn new(evm_config: Evm, database: DB) -> Self {
1073 Self {
1074 evm_config,
1075 batch_database: CacheDB::new(Db::new(database)),
1076 batch_state: BundleState::default(),
1077 block_access_list: None,
1078 }
1079 }
1080}
1081
1082#[cfg(feature = "std")]
1083impl<Evm, DB> BasicBlockExecutor<Evm, DB>
1084where
1085 Evm: ConfigureEvm,
1086 DB: Database,
1087{
1088 fn merge_batch_output(
1089 mut batch_state: BundleState,
1090 output: BlockExecutionOutput<ReceiptTy<Evm::Primitives>>,
1091 ) -> BlockExecutionOutput<ReceiptTy<Evm::Primitives>> {
1092 if batch_state.reverts.is_empty() {
1093 return output
1094 }
1095
1096 let result = output.result;
1097 let state = output.state;
1098 batch_state.extend(state);
1099 BlockExecutionOutput::new(result, batch_state)
1100 }
1101
1102 #[expect(clippy::type_complexity)]
1103 fn execute_block_with_database(
1104 evm_config: &Evm,
1105 block: &RecoveredBlock<BlockTy<Evm::Primitives>>,
1106 database: impl DynDatabase,
1107 ) -> Result<
1108 (BlockExecutionOutput<ReceiptTy<Evm::Primitives>>, Option<BlockAccessList>),
1109 BlockExecutionError,
1110 > {
1111 Self::execute_block_with_database_and_state_hook(evm_config, block, database, None)
1112 }
1113
1114 #[expect(clippy::type_complexity)]
1115 fn execute_block_with_database_and_state_hook(
1116 evm_config: &Evm,
1117 block: &RecoveredBlock<BlockTy<Evm::Primitives>>,
1118 database: impl DynDatabase,
1119 state_hook: Option<Box<dyn FnMut(StateUpdate) + Send>>,
1120 ) -> Result<
1121 (BlockExecutionOutput<ReceiptTy<Evm::Primitives>>, Option<BlockAccessList>),
1122 BlockExecutionError,
1123 > {
1124 let evm_env = evm_config.evm_env(block.header()).map_err(BlockExecutionError::other)?;
1125 let evm = evm_config.block_executor_factory().evm_with_env(database, evm_env);
1126 let ctx = evm_config
1127 .context_for_block(block.sealed_block())
1128 .map_err(BlockExecutionError::other)?;
1129 let mut executor = evm_config.block_executor_factory().create_executor(evm, ctx);
1130 if block.header().block_access_list_hash().is_some() {
1131 executor.enable_block_access_list_builder();
1132 }
1133 if let Some(hook) = state_hook &&
1134 !executor.set_state_hook(hook)
1135 {
1136 return Err(BlockExecutionError::msg("block executor does not support state hooks"))
1137 }
1138
1139 executor.apply_pre_execution_changes()?;
1140 for transaction in block.transactions_recovered() {
1141 executor.execute_transaction(transaction)?;
1142 }
1143 let (output, block_access_list) = executor.finish_with_block_access_list()?;
1144 Ok((output, block_access_list))
1145 }
1146}
1147
1148#[cfg(feature = "std")]
1149impl<Evm, DB> Executor<DB> for BasicBlockExecutor<Evm, DB>
1150where
1151 Evm: ConfigureEvm,
1152 DB: Database,
1153{
1154 type Primitives = Evm::Primitives;
1155 type Error = BlockExecutionError;
1156
1157 fn execute_one(
1158 &mut self,
1159 block: &RecoveredBlock<<Self::Primitives as NodePrimitives>::Block>,
1160 ) -> Result<BlockExecutionResult<<Self::Primitives as NodePrimitives>::Receipt>, Self::Error>
1161 {
1162 let (output, block_access_list) =
1163 Self::execute_block_with_database(&self.evm_config, block, &mut self.batch_database)?;
1164 self.block_access_list = block_access_list;
1165 self.batch_database.commit_source(&BundleSource(&output.state));
1166
1167 let block_state = output.state;
1168 self.batch_state.extend(block_state);
1169
1170 Ok(output.result)
1171 }
1172
1173 fn execute_one_with_state_hook<F>(
1174 &mut self,
1175 block: &RecoveredBlock<<Self::Primitives as NodePrimitives>::Block>,
1176 state_hook: F,
1177 ) -> Result<BlockExecutionResult<<Self::Primitives as NodePrimitives>::Receipt>, Self::Error>
1178 where
1179 F: FnMut(StateUpdate) + Send + 'static,
1180 {
1181 let (output, block_access_list) = Self::execute_block_with_database_and_state_hook(
1182 &self.evm_config,
1183 block,
1184 &mut self.batch_database,
1185 Some(Box::new(state_hook)),
1186 )?;
1187 self.block_access_list = block_access_list;
1188 self.batch_database.commit_source(&BundleSource(&output.state));
1189
1190 let block_state = output.state;
1191 self.batch_state.extend(block_state);
1192
1193 Ok(output.result)
1194 }
1195
1196 fn execute(
1197 self,
1198 block: &RecoveredBlock<<Self::Primitives as NodePrimitives>::Block>,
1199 ) -> Result<BlockExecutionOutput<<Self::Primitives as NodePrimitives>::Receipt>, Self::Error>
1200 {
1201 let Self { evm_config, batch_database, batch_state, .. } = self;
1202 let (output, _) = Self::execute_block_with_database(&evm_config, block, batch_database)?;
1203 Ok(Self::merge_batch_output(batch_state, output))
1204 }
1205
1206 fn execute_with_state_hook<F>(
1207 self,
1208 block: &RecoveredBlock<<Self::Primitives as NodePrimitives>::Block>,
1209 state_hook: F,
1210 ) -> Result<BlockExecutionOutput<<Self::Primitives as NodePrimitives>::Receipt>, Self::Error>
1211 where
1212 F: FnMut(StateUpdate) + Send + 'static,
1213 {
1214 let Self { evm_config, batch_database, batch_state, .. } = self;
1215 let (output, _) = Self::execute_block_with_database_and_state_hook(
1216 &evm_config,
1217 block,
1218 batch_database,
1219 Some(Box::new(state_hook)),
1220 )?;
1221 Ok(Self::merge_batch_output(batch_state, output))
1222 }
1223
1224 fn size_hint(&self) -> usize {
1225 self.batch_state.size_hint()
1226 }
1227
1228 fn into_state(self) -> BundleState {
1229 self.batch_state
1230 }
1231
1232 fn take_bal(&mut self) -> Option<BlockAccessList> {
1233 self.block_access_list.take()
1234 }
1235}
1236
1237#[cfg(not(feature = "std"))]
1239pub(crate) struct UnsupportedExecutor<N> {
1240 _marker: core::marker::PhantomData<N>,
1241}
1242
1243#[cfg(not(feature = "std"))]
1244impl<N> Default for UnsupportedExecutor<N> {
1245 fn default() -> Self {
1246 Self { _marker: core::marker::PhantomData }
1247 }
1248}
1249
1250#[cfg(not(feature = "std"))]
1251impl<N, DB> Executor<DB> for UnsupportedExecutor<N>
1252where
1253 N: NodePrimitives,
1254 DB: Database,
1255{
1256 type Primitives = N;
1257 type Error = BlockExecutionError;
1258
1259 fn execute_one(
1260 &mut self,
1261 _block: &RecoveredBlock<<Self::Primitives as NodePrimitives>::Block>,
1262 ) -> Result<BlockExecutionResult<<Self::Primitives as NodePrimitives>::Receipt>, Self::Error>
1263 {
1264 Err(BlockExecutionError::msg("block execution is unsupported by this EVM configuration"))
1265 }
1266
1267 fn execute(
1268 self,
1269 _block: &RecoveredBlock<<Self::Primitives as NodePrimitives>::Block>,
1270 ) -> Result<BlockExecutionOutput<<Self::Primitives as NodePrimitives>::Receipt>, Self::Error>
1271 {
1272 Err(BlockExecutionError::msg("block execution is unsupported by this EVM configuration"))
1273 }
1274
1275 fn execute_one_with_state_hook<F>(
1276 &mut self,
1277 _block: &RecoveredBlock<<Self::Primitives as NodePrimitives>::Block>,
1278 _state_hook: F,
1279 ) -> Result<BlockExecutionResult<<Self::Primitives as NodePrimitives>::Receipt>, Self::Error>
1280 where
1281 F: FnMut(StateUpdate) + Send + 'static,
1282 {
1283 Err(BlockExecutionError::msg("block execution is unsupported by this EVM configuration"))
1284 }
1285
1286 fn execute_with_state_hook<F>(
1287 self,
1288 _block: &RecoveredBlock<<Self::Primitives as NodePrimitives>::Block>,
1289 _state_hook: F,
1290 ) -> Result<BlockExecutionOutput<<Self::Primitives as NodePrimitives>::Receipt>, Self::Error>
1291 where
1292 F: FnMut(StateUpdate) + Send + 'static,
1293 {
1294 Err(BlockExecutionError::msg("block execution is unsupported by this EVM configuration"))
1295 }
1296
1297 fn execute_batch<'a, I>(
1298 self,
1299 _blocks: I,
1300 ) -> Result<ExecutionOutcome<<Self::Primitives as NodePrimitives>::Receipt>, Self::Error>
1301 where
1302 I: IntoIterator<Item = &'a RecoveredBlock<<Self::Primitives as NodePrimitives>::Block>>,
1303 {
1304 Err(BlockExecutionError::msg("block execution is unsupported by this EVM configuration"))
1305 }
1306
1307 fn size_hint(&self) -> usize {
1308 0
1309 }
1310
1311 fn into_state(self) -> BundleState {
1312 BundleState::default()
1313 }
1314
1315 fn take_bal(&mut self) -> Option<BlockAccessList> {
1316 None
1317 }
1318}
1319
1320#[auto_impl::auto_impl(&)]
1324pub trait RecoveredTx<T> {
1325 fn tx(&self) -> &T;
1327
1328 fn signer(&self) -> &Address;
1330}
1331
1332impl<T> RecoveredTx<T> for Recovered<&T> {
1333 fn tx(&self) -> &T {
1334 self.inner()
1335 }
1336
1337 fn signer(&self) -> &Address {
1338 self.signer_ref()
1339 }
1340}
1341
1342impl<T> RecoveredTx<T> for Recovered<Arc<T>> {
1343 fn tx(&self) -> &T {
1344 self.inner().as_ref()
1345 }
1346
1347 fn signer(&self) -> &Address {
1348 self.signer_ref()
1349 }
1350}
1351
1352impl<T> RecoveredTx<T> for Recovered<T> {
1353 fn tx(&self) -> &T {
1354 self.inner()
1355 }
1356
1357 fn signer(&self) -> &Address {
1358 self.signer_ref()
1359 }
1360}
1361
1362impl<Tx, T: RecoveredTx<Tx>> RecoveredTx<Tx> for WithEncoded<T> {
1363 fn tx(&self) -> &Tx {
1364 self.1.tx()
1365 }
1366
1367 fn signer(&self) -> &Address {
1368 self.1.signer()
1369 }
1370}
1371
1372impl<L, R, Tx> RecoveredTx<Tx> for Either<L, R>
1373where
1374 L: RecoveredTx<Tx>,
1375 R: RecoveredTx<Tx>,
1376{
1377 fn tx(&self) -> &Tx {
1378 match self {
1379 Self::Left(l) => l.tx(),
1380 Self::Right(r) => r.tx(),
1381 }
1382 }
1383
1384 fn signer(&self) -> &Address {
1385 match self {
1386 Self::Left(l) => l.signer(),
1387 Self::Right(r) => r.signer(),
1388 }
1389 }
1390}
1391
1392impl<Tx, T: RecoveredTx<Tx>> RecoveredTx<Tx> for Arc<T> {
1393 fn tx(&self) -> &Tx {
1394 (**self).tx()
1395 }
1396
1397 fn signer(&self) -> &Address {
1398 (**self).signer()
1399 }
1400}
1401
1402pub trait ExecutableTxParts<TxEnv, T> {
1405 type Recovered: RecoveredTx<T>;
1407
1408 fn into_parts(self) -> (TxEnv, Self::Recovered);
1411}
1412
1413pub trait FromRecoveredTx<T> {
1415 fn from_recovered_tx(tx: Recovered<T>) -> Self;
1417}
1418
1419impl<T> FromRecoveredTx<T> for evm2::ethereum::TxEnvelope
1420where
1421 Self: From<T>,
1422{
1423 fn from_recovered_tx(tx: Recovered<T>) -> Self {
1424 tx.into_inner().into()
1425 }
1426}
1427
1428impl<T, TxEnv> FromRecoveredTx<T> for Recovered<TxEnv>
1429where
1430 TxEnv: FromRecoveredTx<T>,
1431{
1432 fn from_recovered_tx(tx: Recovered<T>) -> Self {
1433 let signer = tx.signer();
1434 Self::new_unchecked(TxEnv::from_recovered_tx(tx), signer)
1435 }
1436}
1437
1438pub trait FromTxWithEncoded<T>: FromRecoveredTx<T> {
1441 fn from_tx_with_encoded(tx: WithEncoded<Recovered<T>>) -> Self
1444 where
1445 Self: Sized,
1446 {
1447 Self::from_recovered_tx(tx.1)
1448 }
1449}
1450
1451impl<T> FromTxWithEncoded<T> for evm2::ethereum::TxEnvelope where Self: From<T> {}
1452
1453impl<T, TxEnv> FromTxWithEncoded<T> for Recovered<TxEnv>
1454where
1455 TxEnv: FromTxWithEncoded<T>,
1456{
1457 fn from_tx_with_encoded(tx: WithEncoded<Recovered<T>>) -> Self {
1458 let signer = tx.1.signer();
1459 Self::new_unchecked(TxEnv::from_tx_with_encoded(tx), signer)
1460 }
1461}
1462
1463pub trait IntoTxEnv<TxEnv> {
1465 fn into_tx_env(self) -> TxEnv;
1467}
1468
1469impl<T, TxEnv> IntoTxEnv<TxEnv> for Recovered<T>
1470where
1471 TxEnv: FromRecoveredTx<T>,
1472{
1473 fn into_tx_env(self) -> TxEnv {
1474 TxEnv::from_recovered_tx(self)
1475 }
1476}
1477
1478impl<T, TxEnv> IntoTxEnv<TxEnv> for WithEncoded<Recovered<T>>
1479where
1480 TxEnv: FromTxWithEncoded<T>,
1481{
1482 fn into_tx_env(self) -> TxEnv {
1483 TxEnv::from_tx_with_encoded(self)
1484 }
1485}
1486
1487pub trait TransactionEnvMut: Transaction + Clone {
1493 fn set_gas_limit(&mut self, gas_limit: u64);
1495
1496 fn set_access_list(&mut self, access_list: AccessList);
1498}
1499
1500impl TransactionEnvMut for evm2::ethereum::TxEnvelope {
1501 fn set_gas_limit(&mut self, gas_limit: u64) {
1502 match self {
1503 Self::Legacy(tx) => tx.gas_limit = gas_limit,
1504 Self::Eip2930(tx) => tx.gas_limit = gas_limit,
1505 Self::Eip1559(tx) => tx.gas_limit = gas_limit,
1506 Self::Eip4844(tx) => AsMut::<TxEip4844>::as_mut(tx).gas_limit = gas_limit,
1507 Self::Eip7702(tx) => tx.gas_limit = gas_limit,
1508 }
1509 }
1510
1511 fn set_access_list(&mut self, access_list: AccessList) {
1512 match self {
1513 Self::Legacy(tx) => {
1516 let TxLegacy { chain_id, nonce, gas_price, gas_limit, to, value, input } =
1517 core::mem::take(tx);
1518 *self = Self::Eip2930(TxEip2930 {
1519 chain_id: chain_id.unwrap_or_default(),
1520 nonce,
1521 gas_price,
1522 gas_limit,
1523 to,
1524 value,
1525 access_list,
1526 input,
1527 });
1528 }
1529 Self::Eip2930(tx) => tx.access_list = access_list,
1530 Self::Eip1559(tx) => tx.access_list = access_list,
1531 Self::Eip4844(tx) => AsMut::<TxEip4844>::as_mut(tx).access_list = access_list,
1532 Self::Eip7702(tx) => tx.access_list = access_list,
1533 }
1534 }
1535}
1536
1537impl<T: Clone, TxEnv> ExecutableTxParts<TxEnv, T> for Recovered<T>
1538where
1539 TxEnv: FromRecoveredTx<T>,
1540{
1541 type Recovered = Self;
1542
1543 fn into_parts(self) -> (TxEnv, Self) {
1544 (TxEnv::from_recovered_tx(self.clone()), self)
1545 }
1546}
1547
1548impl<T: Clone, TxEnv> ExecutableTxParts<TxEnv, T> for Recovered<&T>
1549where
1550 TxEnv: FromRecoveredTx<T>,
1551{
1552 type Recovered = Self;
1553
1554 fn into_parts(self) -> (TxEnv, Self) {
1555 (
1556 TxEnv::from_recovered_tx(Recovered::new_unchecked(
1557 (*self.inner()).clone(),
1558 *self.signer_ref(),
1559 )),
1560 self,
1561 )
1562 }
1563}
1564
1565impl<T: Clone, TxEnv> ExecutableTxParts<TxEnv, T> for WithEncoded<Recovered<T>>
1566where
1567 TxEnv: FromTxWithEncoded<T>,
1568{
1569 type Recovered = Self;
1570
1571 fn into_parts(self) -> (TxEnv, Self) {
1572 (TxEnv::from_tx_with_encoded(self.clone()), self)
1573 }
1574}
1575
1576impl<TxEnv, Tx, T> ExecutableTxParts<TxEnv, Tx> for (TxEnv, T)
1577where
1578 T: RecoveredTx<Tx>,
1579{
1580 type Recovered = T;
1581
1582 fn into_parts(self) -> (TxEnv, Self::Recovered) {
1583 self
1584 }
1585}
1586
1587impl<L, R, TxEnv, T> ExecutableTxParts<TxEnv, T> for Either<L, R>
1588where
1589 L: ExecutableTxParts<TxEnv, T>,
1590 R: ExecutableTxParts<TxEnv, T>,
1591{
1592 type Recovered = Either<L::Recovered, R::Recovered>;
1593
1594 fn into_parts(self) -> (TxEnv, Self::Recovered) {
1595 match self {
1596 Self::Left(l) => {
1597 let (tx_env, recovered) = l.into_parts();
1598 (tx_env, Either::Left(recovered))
1599 }
1600 Self::Right(r) => {
1601 let (tx_env, recovered) = r.into_parts();
1602 (tx_env, Either::Right(recovered))
1603 }
1604 }
1605 }
1606}
1607
1608pub trait ExecutableTxFor<Evm: ConfigureEvm>:
1611 ExecutableTxParts<TxEnvFor<Evm>, TxTy<Evm::Primitives>> + RecoveredTx<TxTy<Evm::Primitives>>
1612{
1613}
1614
1615impl<T, Evm: ConfigureEvm> ExecutableTxFor<Evm> for T where
1616 T: ExecutableTxParts<TxEnvFor<Evm>, TxTy<Evm::Primitives>> + RecoveredTx<TxTy<Evm::Primitives>>
1617{
1618}
1619
1620#[derive(Debug)]
1625pub struct WithTxEnv<TxEnv, T> {
1626 pub tx_env: TxEnv,
1628 pub tx: Arc<T>,
1630}
1631
1632impl<TxEnv, T> WithTxEnv<TxEnv, T> {
1633 pub fn new<Tx, InnerTx>(tx: Tx) -> Self
1636 where
1637 Tx: ExecutableTxParts<TxEnv, InnerTx, Recovered = T>,
1638 {
1639 let (tx_env, tx) = tx.into_parts();
1640 Self { tx_env, tx: Arc::new(tx) }
1641 }
1642}
1643
1644impl<TxEnv: Clone, T> Clone for WithTxEnv<TxEnv, T> {
1645 fn clone(&self) -> Self {
1646 Self { tx_env: self.tx_env.clone(), tx: self.tx.clone() }
1647 }
1648}
1649
1650impl<TxEnv, Tx, T: RecoveredTx<Tx>> RecoveredTx<Tx> for WithTxEnv<TxEnv, T> {
1651 fn tx(&self) -> &Tx {
1652 self.tx.tx()
1653 }
1654
1655 fn signer(&self) -> &Address {
1656 self.tx.signer()
1657 }
1658}
1659
1660impl<TxEnv, T: RecoveredTx<Tx>, Tx> ExecutableTxParts<TxEnv, Tx> for WithTxEnv<TxEnv, T> {
1661 type Recovered = Arc<T>;
1662
1663 fn into_parts(self) -> (TxEnv, Self::Recovered) {
1664 (self.tx_env, self.tx)
1665 }
1666}
1667
1668#[cfg(test)]
1669mod tests {
1670 use super::*;
1671 use alloy_eips::eip2930::AccessListItem;
1672 use alloy_primitives::{Bytes, TxKind, U256};
1673
1674 #[test]
1675 fn traced_inspector_forwards_inspector_config() {
1676 struct NoSteps;
1677 impl<T: evm2::EvmTypesHost> evm2::Inspector<T> for NoSteps {
1678 fn inspector_config(&self) -> evm2::InspectorConfig {
1679 evm2::InspectorConfig::without_steps()
1680 }
1681 }
1682
1683 assert_eq!(
1685 evm2::Inspector::<evm2::BaseEvmTypes>::inspector_config(&TracedInspector(NoSteps)),
1686 evm2::InspectorConfig::without_steps(),
1687 );
1688 }
1689
1690 #[test]
1691 fn transaction_env_mut_upgrades_legacy_with_access_list() {
1692 let mut tx = evm2::ethereum::TxEnvelope::Legacy(TxLegacy {
1693 chain_id: Some(1),
1694 nonce: 2,
1695 gas_price: 3,
1696 gas_limit: 4,
1697 to: TxKind::Call(Address::with_last_byte(5)),
1698 value: U256::from(6),
1699 input: Bytes::from_static(&[7]),
1700 });
1701 let access_list = AccessList(vec![AccessListItem {
1702 address: Address::with_last_byte(8),
1703 storage_keys: vec![B256::with_last_byte(9)],
1704 }]);
1705
1706 tx.set_gas_limit(10);
1707 tx.set_access_list(access_list.clone());
1708
1709 assert_eq!(
1710 tx,
1711 evm2::ethereum::TxEnvelope::Eip2930(TxEip2930 {
1712 chain_id: 1,
1713 nonce: 2,
1714 gas_price: 3,
1715 gas_limit: 10,
1716 to: TxKind::Call(Address::with_last_byte(5)),
1717 value: U256::from(6),
1718 access_list,
1719 input: Bytes::from_static(&[7]),
1720 })
1721 );
1722 }
1723
1724 #[test]
1725 fn recovered_tx_wrappers_preserve_transaction_and_signer() {
1726 let transaction = TxLegacy { nonce: 7, ..Default::default() };
1727 let signer = Address::with_last_byte(42);
1728 let recovered = Recovered::new_unchecked(transaction.clone(), signer);
1729
1730 let assert_parts = |tx: &dyn RecoveredTx<TxLegacy>| {
1731 assert_eq!(tx.tx(), &transaction);
1732 assert_eq!(tx.signer(), &signer);
1733 };
1734
1735 assert_parts(&recovered);
1736 assert_parts(&&recovered);
1737 assert_parts(&Recovered::new_unchecked(&transaction, signer));
1738 assert_parts(&Recovered::new_unchecked(Arc::new(transaction.clone()), signer));
1739 assert_parts(&Arc::new(recovered.clone()));
1740 assert_parts(&WithEncoded::new(Bytes::new(), recovered.clone()));
1741 assert_parts(&Either::<_, Recovered<TxLegacy>>::Left(recovered.clone()));
1742 assert_parts(&Either::<Recovered<TxLegacy>, _>::Right(recovered.clone()));
1743 assert_parts(&WithTxEnv { tx_env: (), tx: Arc::new(recovered) });
1744 }
1745}