reth_evm/lib.rs
1//! Traits for configuring an EVM specifics.
2//!
3//! # Revm features
4//!
5//! This crate does __not__ enforce specific revm features such as `blst` or `c-kzg`, which are
6//! critical for revm's evm internals, it is the responsibility of the implementer to ensure the
7//! proper features are selected.
8
9#![doc(
10 html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
11 html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
12 issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
13)]
14#![cfg_attr(not(test), warn(unused_crate_dependencies))]
15#![cfg_attr(docsrs, feature(doc_cfg))]
16#![cfg_attr(not(feature = "std"), no_std)]
17
18extern crate alloc;
19
20use crate::execute::{BasicBlockBuilder, Executor};
21use alloc::vec::Vec;
22use alloy_eips::{
23 eip2718::{EIP2930_TX_TYPE_ID, LEGACY_TX_TYPE_ID},
24 eip2930::AccessList,
25 eip4895::Withdrawals,
26};
27use alloy_evm::{
28 block::{BlockExecutorFactory, BlockExecutorFor},
29 precompiles::PrecompilesMap,
30};
31use alloy_primitives::{Address, Bytes, B256};
32use core::{error::Error, fmt::Debug};
33use execute::{BasicBlockExecutor, BlockAssembler, BlockBuilder};
34use reth_execution_errors::BlockExecutionError;
35use reth_primitives_traits::{
36 BlockTy, HeaderTy, NodePrimitives, ReceiptTy, SealedBlock, SealedHeader, TxTy,
37};
38use revm::{context::TxEnv, database::State, primitives::hardfork::SpecId};
39
40pub mod either;
41/// EVM environment configuration.
42pub mod execute;
43
44mod aliases;
45pub use aliases::*;
46
47#[cfg(feature = "std")]
48mod engine;
49#[cfg(feature = "std")]
50pub use engine::{ConfigureEngineEvm, ConvertTx, ExecutableTxIterator, ExecutableTxTuple};
51
52#[cfg(feature = "metrics")]
53pub mod metrics;
54pub mod noop;
55#[cfg(any(test, feature = "test-utils"))]
56/// test helpers for mocking executor
57pub mod test_utils;
58
59pub use alloy_evm::{
60 block::{state_changes, system_calls, OnStateHook},
61 *,
62};
63
64/// A complete configuration of EVM for Reth.
65///
66/// This trait encapsulates complete configuration required for transaction execution and block
67/// execution/building, providing a unified interface for EVM operations.
68///
69/// # Architecture Overview
70///
71/// The EVM abstraction consists of the following layers:
72///
73/// 1. **[`Evm`] (produced by [`EvmFactory`])**: The core EVM implementation responsible for
74/// executing individual transactions and producing outputs including state changes, logs, gas
75/// usage, etc.
76///
77/// 2. **[`BlockExecutor`] (produced by [`BlockExecutorFactory`])**: A higher-level component that
78/// operates on top of [`Evm`] to execute entire blocks. This involves:
79/// - Executing all transactions in sequence
80/// - Building receipts from transaction outputs
81/// - Applying block rewards to the beneficiary
82/// - Executing system calls (e.g., EIP-4788 beacon root updates)
83/// - Managing state changes and bundle accumulation
84///
85/// 3. **[`BlockAssembler`]**: Responsible for assembling valid blocks from executed transactions.
86/// It takes the output from [`BlockExecutor`] along with execution context and produces a
87/// complete block ready for inclusion in the chain.
88///
89/// # Usage Patterns
90///
91/// The abstraction supports two primary use cases:
92///
93/// ## 1. Executing Externally Provided Blocks (e.g., during sync)
94///
95/// ```rust,ignore
96/// use reth_evm::ConfigureEvm;
97///
98/// // Execute a received block
99/// let mut executor = evm_config.executor(state_db);
100/// let output = executor.execute(&block)?;
101///
102/// // Access the execution results
103/// println!("Gas used: {}", output.result.gas_used);
104/// println!("Receipts: {:?}", output.result.receipts);
105/// ```
106///
107/// ## 2. Building New Blocks (e.g., payload building)
108///
109/// Payload building is slightly different as it doesn't have the block's header yet, but rather
110/// attributes for the block's environment, such as timestamp, fee recipient, and randomness value.
111/// The block's header will be the outcome of the block building process.
112///
113/// ```rust,ignore
114/// use reth_evm::{ConfigureEvm, NextBlockEnvAttributes};
115///
116/// // Create attributes for the next block
117/// let attributes = NextBlockEnvAttributes {
118/// timestamp: current_time + 12,
119/// suggested_fee_recipient: beneficiary_address,
120/// prev_randao: randomness_value,
121/// gas_limit: 30_000_000,
122/// withdrawals: Some(withdrawals),
123/// parent_beacon_block_root: Some(beacon_root),
124/// };
125///
126/// // Build a new block on top of parent
127/// let mut builder = evm_config.builder_for_next_block(
128/// &mut state_db,
129/// &parent_header,
130/// attributes
131/// )?;
132///
133/// // Apply pre-execution changes (e.g., beacon root update)
134/// builder.apply_pre_execution_changes()?;
135///
136/// // Execute transactions
137/// for tx in pending_transactions {
138/// match builder.execute_transaction(tx) {
139/// Ok(gas_used) => {
140/// println!("Transaction executed, gas used: {}", gas_used);
141/// }
142/// Err(e) => {
143/// println!("Transaction failed: {:?}", e);
144/// }
145/// }
146/// }
147///
148/// // Finish block building and get the outcome (block)
149/// let outcome = builder.finish(state_provider)?;
150/// let block = outcome.block;
151/// ```
152///
153/// # Key Components
154///
155/// ## [`NextBlockEnvCtx`]
156///
157/// Contains attributes needed to configure the next block that cannot be derived from the
158/// parent block alone. This includes data typically provided by the consensus layer:
159/// - `timestamp`: Block timestamp
160/// - `suggested_fee_recipient`: Beneficiary address
161/// - `prev_randao`: Randomness value
162/// - `gas_limit`: Block gas limit
163/// - `withdrawals`: Consensus layer withdrawals
164/// - `parent_beacon_block_root`: EIP-4788 beacon root
165///
166/// ## [`BlockAssembler`]
167///
168/// Takes the execution output and produces a complete block. It receives:
169/// - Transaction execution results (receipts, gas used)
170/// - Final state root after all executions
171/// - Bundle state with all changes
172/// - Execution context and environment
173///
174/// The assembler is responsible for:
175/// - Setting the correct block header fields
176/// - Including executed transactions
177/// - Setting gas used and receipts root
178/// - Applying any chain-specific rules
179///
180/// [`ExecutionCtx`]: BlockExecutorFactory::ExecutionCtx
181/// [`NextBlockEnvCtx`]: ConfigureEvm::NextBlockEnvCtx
182/// [`BlockExecutor`]: alloy_evm::block::BlockExecutor
183#[auto_impl::auto_impl(&, Arc)]
184pub trait ConfigureEvm: Clone + Debug + Send + Sync + Unpin {
185 /// The primitives type used by the EVM.
186 type Primitives: NodePrimitives;
187
188 /// The error type that is returned by [`Self::next_evm_env`].
189 type Error: Error + Send + Sync + 'static;
190
191 /// Context required for configuring next block environment.
192 ///
193 /// Contains values that can't be derived from the parent block.
194 type NextBlockEnvCtx: Debug + Clone;
195
196 /// Configured [`BlockExecutorFactory`], contains [`EvmFactory`] internally.
197 type BlockExecutorFactory: for<'a> BlockExecutorFactory<
198 Transaction = TxTy<Self::Primitives>,
199 Receipt = ReceiptTy<Self::Primitives>,
200 ExecutionCtx<'a>: Debug + Send,
201 EvmFactory: EvmFactory<
202 Tx: TransactionEnv
203 + FromRecoveredTx<TxTy<Self::Primitives>>
204 + FromTxWithEncoded<TxTy<Self::Primitives>>,
205 Precompiles = PrecompilesMap,
206 Spec: Into<SpecId>,
207 >,
208 >;
209
210 /// A type that knows how to build a block.
211 type BlockAssembler: BlockAssembler<
212 Self::BlockExecutorFactory,
213 Block = BlockTy<Self::Primitives>,
214 >;
215
216 /// Returns reference to the configured [`BlockExecutorFactory`].
217 fn block_executor_factory(&self) -> &Self::BlockExecutorFactory;
218
219 /// Returns reference to the configured [`BlockAssembler`].
220 fn block_assembler(&self) -> &Self::BlockAssembler;
221
222 /// Creates a new [`EvmEnv`] for the given header.
223 fn evm_env(&self, header: &HeaderTy<Self::Primitives>) -> Result<EvmEnvFor<Self>, Self::Error>;
224
225 /// Returns the configured [`EvmEnv`] for `parent + 1` block.
226 ///
227 /// This is intended for usage in block building after the merge and requires additional
228 /// attributes that can't be derived from the parent block: attributes that are determined by
229 /// the CL, such as the timestamp, suggested fee recipient, and randomness value.
230 ///
231 /// # Example
232 ///
233 /// ```rust,ignore
234 /// let evm_env = evm_config.next_evm_env(&parent_header, &attributes)?;
235 /// // evm_env now contains:
236 /// // - Correct spec ID based on timestamp and block number
237 /// // - Block environment with next block's parameters
238 /// // - Configuration like chain ID and blob parameters
239 /// ```
240 fn next_evm_env(
241 &self,
242 parent: &HeaderTy<Self::Primitives>,
243 attributes: &Self::NextBlockEnvCtx,
244 ) -> Result<EvmEnvFor<Self>, Self::Error>;
245
246 /// Returns the configured [`BlockExecutorFactory::ExecutionCtx`] for a given block.
247 fn context_for_block<'a>(
248 &self,
249 block: &'a SealedBlock<BlockTy<Self::Primitives>>,
250 ) -> Result<ExecutionCtxFor<'a, Self>, Self::Error>;
251
252 /// Returns the configured [`BlockExecutorFactory::ExecutionCtx`] for `parent + 1`
253 /// block.
254 fn context_for_next_block(
255 &self,
256 parent: &SealedHeader<HeaderTy<Self::Primitives>>,
257 attributes: Self::NextBlockEnvCtx,
258 ) -> Result<ExecutionCtxFor<'_, Self>, Self::Error>;
259
260 /// Returns a [`TxEnv`] from a transaction.
261 fn tx_env(&self, transaction: impl IntoTxEnv<TxEnvFor<Self>>) -> TxEnvFor<Self> {
262 transaction.into_tx_env()
263 }
264
265 /// Provides a reference to [`EvmFactory`] implementation.
266 fn evm_factory(&self) -> &EvmFactoryFor<Self> {
267 self.block_executor_factory().evm_factory()
268 }
269
270 /// Returns a new EVM with the given database configured with the given environment settings,
271 /// including the spec id and transaction environment.
272 ///
273 /// This will preserve any handler modifications
274 fn evm_with_env<DB: Database>(&self, db: DB, evm_env: EvmEnvFor<Self>) -> EvmFor<Self, DB> {
275 self.evm_factory().create_evm(db, evm_env)
276 }
277
278 /// Returns a new EVM with the given database configured with `cfg` and `block_env`
279 /// configuration derived from the given header. Relies on
280 /// [`ConfigureEvm::evm_env`].
281 ///
282 /// # Caution
283 ///
284 /// This does not initialize the tx environment.
285 fn evm_for_block<DB: Database>(
286 &self,
287 db: DB,
288 header: &HeaderTy<Self::Primitives>,
289 ) -> Result<EvmFor<Self, DB>, Self::Error> {
290 let evm_env = self.evm_env(header)?;
291 Ok(self.evm_with_env(db, evm_env))
292 }
293
294 /// Returns a new EVM with the given database configured with the given environment settings,
295 /// including the spec id.
296 ///
297 /// This will use the given external inspector as the EVM external context.
298 ///
299 /// This will preserve any handler modifications
300 fn evm_with_env_and_inspector<DB, I>(
301 &self,
302 db: DB,
303 evm_env: EvmEnvFor<Self>,
304 inspector: I,
305 ) -> EvmFor<Self, DB, I>
306 where
307 DB: Database,
308 I: InspectorFor<Self, DB>,
309 {
310 self.evm_factory().create_evm_with_inspector(db, evm_env, inspector)
311 }
312
313 /// Creates a strategy with given EVM and execution context.
314 fn create_executor<'a, DB, I>(
315 &'a self,
316 evm: EvmFor<Self, &'a mut State<DB>, I>,
317 ctx: <Self::BlockExecutorFactory as BlockExecutorFactory>::ExecutionCtx<'a>,
318 ) -> impl BlockExecutorFor<'a, Self::BlockExecutorFactory, DB, I>
319 where
320 DB: Database,
321 I: InspectorFor<Self, &'a mut State<DB>> + 'a,
322 {
323 self.block_executor_factory().create_executor(evm, ctx)
324 }
325
326 /// Creates a strategy for execution of a given block.
327 fn executor_for_block<'a, DB: Database>(
328 &'a self,
329 db: &'a mut State<DB>,
330 block: &'a SealedBlock<<Self::Primitives as NodePrimitives>::Block>,
331 ) -> Result<impl BlockExecutorFor<'a, Self::BlockExecutorFactory, DB>, Self::Error> {
332 let evm = self.evm_for_block(db, block.header())?;
333 let ctx = self.context_for_block(block)?;
334 Ok(self.create_executor(evm, ctx))
335 }
336
337 /// Creates a [`BlockBuilder`]. Should be used when building a new block.
338 ///
339 /// Block builder wraps an inner [`alloy_evm::block::BlockExecutor`] and has a similar
340 /// interface. Builder collects all of the executed transactions, and once
341 /// [`BlockBuilder::finish`] is called, it invokes the configured [`BlockAssembler`] to
342 /// create a block.
343 ///
344 /// # Example
345 ///
346 /// ```rust,ignore
347 /// // Create a builder with specific EVM configuration
348 /// let evm = evm_config.evm_with_env(&mut state_db, evm_env);
349 /// let ctx = evm_config.context_for_next_block(&parent, attributes);
350 /// let builder = evm_config.create_block_builder(evm, &parent, ctx);
351 /// ```
352 fn create_block_builder<'a, DB, I>(
353 &'a self,
354 evm: EvmFor<Self, &'a mut State<DB>, I>,
355 parent: &'a SealedHeader<HeaderTy<Self::Primitives>>,
356 ctx: <Self::BlockExecutorFactory as BlockExecutorFactory>::ExecutionCtx<'a>,
357 ) -> impl BlockBuilder<
358 Primitives = Self::Primitives,
359 Executor: BlockExecutorFor<'a, Self::BlockExecutorFactory, DB, I>,
360 >
361 where
362 DB: Database,
363 I: InspectorFor<Self, &'a mut State<DB>> + 'a,
364 {
365 BasicBlockBuilder {
366 executor: self.create_executor(evm, ctx.clone()),
367 ctx,
368 assembler: self.block_assembler(),
369 parent,
370 transactions: Vec::new(),
371 }
372 }
373
374 /// Creates a [`BlockBuilder`] for building of a new block. This is a helper to invoke
375 /// [`ConfigureEvm::create_block_builder`].
376 ///
377 /// This is the primary method for building new blocks. It combines:
378 /// 1. Creating the EVM environment for the next block
379 /// 2. Setting up the execution context from attributes
380 /// 3. Initializing the block builder with proper configuration
381 ///
382 /// # Example
383 ///
384 /// ```rust,ignore
385 /// // Build a block with specific attributes
386 /// let mut builder = evm_config.builder_for_next_block(
387 /// &mut state_db,
388 /// &parent_header,
389 /// attributes
390 /// )?;
391 ///
392 /// // Execute system calls (e.g., beacon root update)
393 /// builder.apply_pre_execution_changes()?;
394 ///
395 /// // Execute transactions
396 /// for tx in transactions {
397 /// builder.execute_transaction(tx)?;
398 /// }
399 ///
400 /// // Complete block building
401 /// let outcome = builder.finish(state_provider)?;
402 /// ```
403 fn builder_for_next_block<'a, DB: Database + 'a>(
404 &'a self,
405 db: &'a mut State<DB>,
406 parent: &'a SealedHeader<<Self::Primitives as NodePrimitives>::BlockHeader>,
407 attributes: Self::NextBlockEnvCtx,
408 ) -> Result<
409 impl BlockBuilder<
410 Primitives = Self::Primitives,
411 Executor: BlockExecutorFor<'a, Self::BlockExecutorFactory, DB>,
412 >,
413 Self::Error,
414 > {
415 let evm_env = self.next_evm_env(parent, &attributes)?;
416 let evm = self.evm_with_env(db, evm_env);
417 let ctx = self.context_for_next_block(parent, attributes)?;
418 Ok(self.create_block_builder(evm, parent, ctx))
419 }
420
421 /// Returns a new [`Executor`] for executing blocks.
422 ///
423 /// The executor processes complete blocks including:
424 /// - All transactions in order
425 /// - Block rewards and fees
426 /// - Block level system calls
427 /// - State transitions
428 ///
429 /// # Example
430 ///
431 /// ```rust,ignore
432 /// // Create an executor
433 /// let mut executor = evm_config.executor(state_db);
434 ///
435 /// // Execute a single block
436 /// let output = executor.execute(&block)?;
437 ///
438 /// // Execute multiple blocks
439 /// let batch_output = executor.execute_batch(&blocks)?;
440 /// ```
441 #[auto_impl(keep_default_for(&, Arc))]
442 fn executor<DB: Database>(
443 &self,
444 db: DB,
445 ) -> impl Executor<DB, Primitives = Self::Primitives, Error = BlockExecutionError> {
446 BasicBlockExecutor::new(self, db)
447 }
448
449 /// Returns a new [`BasicBlockExecutor`].
450 #[auto_impl(keep_default_for(&, Arc))]
451 fn batch_executor<DB: Database>(
452 &self,
453 db: DB,
454 ) -> impl Executor<DB, Primitives = Self::Primitives, Error = BlockExecutionError> {
455 BasicBlockExecutor::new(self, db)
456 }
457}
458
459/// Represents additional attributes required to configure the next block.
460///
461/// This struct contains all the information needed to build a new block that cannot be
462/// derived from the parent block header alone. These attributes are typically provided
463/// by the consensus layer (CL) through the Engine API during payload building.
464///
465/// # Relationship with [`ConfigureEvm`] and [`BlockAssembler`]
466///
467/// The flow for building a new block involves:
468///
469/// 1. **Receive attributes** from the consensus layer containing:
470/// - Timestamp for the new block
471/// - Fee recipient (coinbase/beneficiary)
472/// - Randomness value (prevRandao)
473/// - Withdrawals to process
474/// - Parent beacon block root for EIP-4788
475///
476/// 2. **Configure EVM environment** using these attributes: ```rust,ignore let evm_env =
477/// evm_config.next_evm_env(&parent, &attributes)?; ```
478///
479/// 3. **Build the block** with transactions: ```rust,ignore let mut builder =
480/// evm_config.builder_for_next_block( &mut state, &parent, attributes )?; ```
481///
482/// 4. **Assemble the final block** using [`BlockAssembler`] which takes:
483/// - Execution results from all transactions
484/// - The attributes used during execution
485/// - Final state root after all changes
486///
487/// This design cleanly separates:
488/// - **Configuration** (what parameters to use) - handled by `NextBlockEnvAttributes`
489/// - **Execution** (running transactions) - handled by `BlockExecutor`
490/// - **Assembly** (creating the final block) - handled by `BlockAssembler`
491#[derive(Debug, Clone, PartialEq, Eq)]
492pub struct NextBlockEnvAttributes {
493 /// The timestamp of the next block.
494 pub timestamp: u64,
495 /// The suggested fee recipient for the next block.
496 pub suggested_fee_recipient: Address,
497 /// The randomness value for the next block.
498 pub prev_randao: B256,
499 /// Block gas limit.
500 pub gas_limit: u64,
501 /// The parent beacon block root.
502 pub parent_beacon_block_root: Option<B256>,
503 /// Withdrawals
504 pub withdrawals: Option<Withdrawals>,
505 /// Optional extra data.
506 pub extra_data: Bytes,
507}
508
509/// Abstraction over transaction environment.
510pub trait TransactionEnv:
511 revm::context_interface::Transaction + Debug + Clone + Send + Sync + 'static
512{
513 /// Set the gas limit.
514 fn set_gas_limit(&mut self, gas_limit: u64);
515
516 /// Set the gas limit.
517 fn with_gas_limit(mut self, gas_limit: u64) -> Self {
518 self.set_gas_limit(gas_limit);
519 self
520 }
521
522 /// Returns the configured nonce.
523 fn nonce(&self) -> u64;
524
525 /// Sets the nonce.
526 fn set_nonce(&mut self, nonce: u64);
527
528 /// Sets the nonce.
529 fn with_nonce(mut self, nonce: u64) -> Self {
530 self.set_nonce(nonce);
531 self
532 }
533
534 /// Set access list.
535 fn set_access_list(&mut self, access_list: AccessList);
536
537 /// Set access list.
538 fn with_access_list(mut self, access_list: AccessList) -> Self {
539 self.set_access_list(access_list);
540 self
541 }
542}
543
544impl TransactionEnv for TxEnv {
545 fn set_gas_limit(&mut self, gas_limit: u64) {
546 self.gas_limit = gas_limit;
547 }
548
549 fn nonce(&self) -> u64 {
550 self.nonce
551 }
552
553 fn set_nonce(&mut self, nonce: u64) {
554 self.nonce = nonce;
555 }
556
557 fn set_access_list(&mut self, access_list: AccessList) {
558 self.access_list = access_list;
559
560 if self.tx_type == LEGACY_TX_TYPE_ID {
561 // if this was previously marked as legacy tx, this must be upgraded to eip2930 with an
562 // accesslist
563 self.tx_type = EIP2930_TX_TYPE_ID;
564 }
565 }
566}
567
568#[cfg(feature = "op")]
569impl<T: TransactionEnv> TransactionEnv for op_revm::OpTransaction<T> {
570 fn set_gas_limit(&mut self, gas_limit: u64) {
571 self.base.set_gas_limit(gas_limit);
572 }
573
574 fn nonce(&self) -> u64 {
575 TransactionEnv::nonce(&self.base)
576 }
577
578 fn set_nonce(&mut self, nonce: u64) {
579 self.base.set_nonce(nonce);
580 }
581
582 fn set_access_list(&mut self, access_list: AccessList) {
583 self.base.set_access_list(access_list);
584 }
585}