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