feat: add Evm trait (#13823)

This commit is contained in:
Arsenii Kulikov
2025-01-18 19:42:39 +04:00
committed by GitHub
parent cef0c927c9
commit c46f23f8de
25 changed files with 453 additions and 460 deletions

View File

@ -20,8 +20,8 @@ extern crate alloc;
use alloy_consensus::BlockHeader as _;
use alloy_primitives::{Address, Bytes, B256, U256};
use reth_primitives_traits::{BlockHeader, SignedTransaction};
use revm::{Database, Evm, GetInspector};
use revm_primitives::{BlockEnv, CfgEnvWithHandlerCfg, Env, SpecId, TxEnv};
use revm::{Database, DatabaseCommit, GetInspector};
use revm_primitives::{BlockEnv, CfgEnvWithHandlerCfg, EVMError, ResultAndState, SpecId, TxEnv};
pub mod either;
/// EVM environment configuration.
@ -38,13 +38,64 @@ pub mod system_calls;
/// test helpers for mocking executor
pub mod test_utils;
/// An abstraction over EVM.
///
/// At this point, assumed to be implemented on wrappers around [`revm::Evm`].
pub trait Evm {
/// Database type held by the EVM.
type DB;
/// Transaction environment
type Tx;
/// Error type.
type Error;
/// Reference to [`BlockEnv`].
fn block(&self) -> &BlockEnv;
/// Consumes the type and returns the underlying [`EvmEnv`].
fn into_env(self) -> EvmEnv;
/// Executes the given transaction.
fn transact(&mut self, tx: Self::Tx) -> Result<ResultAndState, Self::Error>;
/// Executes a system call.
fn transact_system_call(
&mut self,
caller: Address,
contract: Address,
data: Bytes,
) -> Result<ResultAndState, Self::Error>;
/// Returns a mutable reference to the underlying database.
fn db_mut(&mut self) -> &mut Self::DB;
/// Executes a transaction and commits the state changes to the underlying database.
fn transact_commit(&mut self, tx_env: Self::Tx) -> Result<ResultAndState, Self::Error>
where
Self::DB: DatabaseCommit,
{
let result = self.transact(tx_env)?;
self.db_mut().commit(result.state.clone());
Ok(result)
}
}
/// Trait for configuring the EVM for executing full blocks.
pub trait ConfigureEvm: ConfigureEvmEnv {
/// The EVM implementation.
type Evm<'a, DB: Database + 'a, I: 'a>: Evm<Tx = TxEnv, DB = DB, Error = EVMError<DB::Error>>;
/// Returns a new EVM with the given database configured with the given environment settings,
/// including the spec id and transaction environment.
///
/// This will preserve any handler modifications
fn evm_with_env<DB: Database>(&self, db: DB, evm_env: EvmEnv, tx: TxEnv) -> Evm<'_, (), DB>;
fn evm_with_env<DB: Database>(
&self,
db: DB,
evm_env: EvmEnv,
tx: TxEnv,
) -> Self::Evm<'_, DB, ()>;
/// Returns a new EVM with the given database configured with `cfg` and `block_env`
/// configuration derived from the given header. Relies on
@ -53,7 +104,7 @@ pub trait ConfigureEvm: ConfigureEvmEnv {
/// # Caution
///
/// This does not initialize the tx environment.
fn evm_for_block<DB: Database>(&self, db: DB, header: &Self::Header) -> Evm<'_, (), DB> {
fn evm_for_block<DB: Database>(&self, db: DB, header: &Self::Header) -> Self::Evm<'_, DB, ()> {
let evm_env = self.cfg_and_block_env(header);
self.evm_with_env(db, evm_env, Default::default())
}
@ -70,7 +121,7 @@ pub trait ConfigureEvm: ConfigureEvmEnv {
evm_env: EvmEnv,
tx: TxEnv,
inspector: I,
) -> Evm<'_, I, DB>
) -> Self::Evm<'_, DB, I>
where
DB: Database,
I: GetInspector<DB>;
@ -81,11 +132,18 @@ where
T: ConfigureEvm,
&'b T: ConfigureEvmEnv<Header = T::Header>,
{
fn evm_for_block<DB: Database>(&self, db: DB, header: &Self::Header) -> Evm<'_, (), DB> {
type Evm<'a, DB: Database + 'a, I: 'a> = T::Evm<'a, DB, I>;
fn evm_for_block<DB: Database>(&self, db: DB, header: &Self::Header) -> Self::Evm<'_, DB, ()> {
(*self).evm_for_block(db, header)
}
fn evm_with_env<DB: Database>(&self, db: DB, evm_env: EvmEnv, tx: TxEnv) -> Evm<'_, (), DB> {
fn evm_with_env<DB: Database>(
&self,
db: DB,
evm_env: EvmEnv,
tx: TxEnv,
) -> Self::Evm<'_, DB, ()> {
(*self).evm_with_env(db, evm_env, tx)
}
@ -95,7 +153,7 @@ where
evm_env: EvmEnv,
tx_env: TxEnv,
inspector: I,
) -> Evm<'_, I, DB>
) -> Self::Evm<'_, DB, I>
where
DB: Database,
I: GetInspector<DB>,
@ -129,15 +187,6 @@ pub trait ConfigureEvmEnv: Send + Sync + Unpin + Clone + 'static {
/// Fill transaction environment from a transaction and the given sender address.
fn fill_tx_env(&self, tx_env: &mut TxEnv, transaction: &Self::Transaction, sender: Address);
/// Fill transaction environment with a system contract call.
fn fill_tx_env_system_contract_call(
&self,
env: &mut Env,
caller: Address,
contract: Address,
data: Bytes,
);
/// Returns a [`CfgEnvWithHandlerCfg`] for the given header.
fn cfg_env(&self, header: &Self::Header) -> CfgEnvWithHandlerCfg {
let mut cfg = CfgEnvWithHandlerCfg::new(Default::default(), Default::default());

View File

@ -1,13 +1,14 @@
//! [EIP-2935](https://eips.ethereum.org/EIPS/eip-2935) system call implementation.
use alloc::{boxed::Box, string::ToString};
use core::fmt::Display;
use alloc::string::ToString;
use alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS;
use crate::ConfigureEvm;
use crate::Evm;
use alloy_primitives::B256;
use reth_chainspec::EthereumHardforks;
use reth_execution_errors::{BlockExecutionError, BlockValidationError};
use revm::{interpreter::Host, Database, Evm};
use revm_primitives::ResultAndState;
/// Applies the pre-block call to the [EIP-2935] blockhashes contract, using the given block,
@ -23,19 +24,13 @@ use revm_primitives::ResultAndState;
///
/// [EIP-2935]: https://eips.ethereum.org/EIPS/eip-2935
#[inline]
pub(crate) fn transact_blockhashes_contract_call<EvmConfig, EXT, DB>(
evm_config: &EvmConfig,
pub(crate) fn transact_blockhashes_contract_call(
chain_spec: impl EthereumHardforks,
block_timestamp: u64,
block_number: u64,
parent_block_hash: B256,
evm: &mut Evm<'_, EXT, DB>,
) -> Result<Option<ResultAndState>, BlockExecutionError>
where
DB: Database,
DB::Error: core::fmt::Display,
EvmConfig: ConfigureEvm,
{
evm: &mut impl Evm<Error: Display>,
) -> Result<Option<ResultAndState>, BlockExecutionError> {
if !chain_spec.is_prague_active_at_timestamp(block_timestamp) {
return Ok(None)
}
@ -46,21 +41,13 @@ where
return Ok(None)
}
// get previous env
let previous_env = Box::new(evm.context.env().clone());
// modify env for pre block call
evm_config.fill_tx_env_system_contract_call(
&mut evm.context.evm.env,
let mut res = match evm.transact_system_call(
alloy_eips::eip4788::SYSTEM_ADDRESS,
HISTORY_STORAGE_ADDRESS,
parent_block_hash.0.into(),
);
let mut res = match evm.transact() {
) {
Ok(res) => res,
Err(e) => {
evm.context.evm.env = previous_env;
return Err(BlockValidationError::BlockHashContractCall { message: e.to_string() }.into())
}
};
@ -73,8 +60,5 @@ where
res.state.remove(&alloy_eips::eip4788::SYSTEM_ADDRESS);
res.state.remove(&evm.block().coinbase);
// re-set the previous env
evm.context.evm.env = previous_env;
Ok(Some(res))
}

View File

@ -1,12 +1,11 @@
//! [EIP-4788](https://eips.ethereum.org/EIPS/eip-4788) system call implementation.
use crate::Evm;
use alloc::{boxed::Box, string::ToString};
use crate::ConfigureEvm;
use alloy_eips::eip4788::BEACON_ROOTS_ADDRESS;
use alloy_primitives::B256;
use core::fmt::Display;
use reth_chainspec::EthereumHardforks;
use reth_execution_errors::{BlockExecutionError, BlockValidationError};
use revm::{interpreter::Host, Database, Evm};
use revm_primitives::ResultAndState;
/// Applies the pre-block call to the [EIP-4788] beacon block root contract, using the given block,
@ -19,20 +18,13 @@ use revm_primitives::ResultAndState;
///
/// [EIP-4788]: https://eips.ethereum.org/EIPS/eip-4788
#[inline]
pub(crate) fn transact_beacon_root_contract_call<EvmConfig, EXT, DB, Spec>(
evm_config: &EvmConfig,
chain_spec: &Spec,
pub(crate) fn transact_beacon_root_contract_call(
chain_spec: impl EthereumHardforks,
block_timestamp: u64,
block_number: u64,
parent_beacon_block_root: Option<B256>,
evm: &mut Evm<'_, EXT, DB>,
) -> Result<Option<ResultAndState>, BlockExecutionError>
where
DB: Database,
DB::Error: core::fmt::Display,
EvmConfig: ConfigureEvm,
Spec: EthereumHardforks,
{
evm: &mut impl Evm<Error: Display>,
) -> Result<Option<ResultAndState>, BlockExecutionError> {
if !chain_spec.is_cancun_active_at_timestamp(block_timestamp) {
return Ok(None)
}
@ -52,21 +44,13 @@ where
return Ok(None)
}
// get previous env
let previous_env = Box::new(evm.context.env().clone());
// modify env for pre block call
evm_config.fill_tx_env_system_contract_call(
&mut evm.context.evm.env,
let mut res = match evm.transact_system_call(
alloy_eips::eip4788::SYSTEM_ADDRESS,
BEACON_ROOTS_ADDRESS,
parent_beacon_block_root.0.into(),
);
let mut res = match evm.transact() {
) {
Ok(res) => res,
Err(e) => {
evm.context.evm.env = previous_env;
return Err(BlockValidationError::BeaconRootContractCall {
parent_beacon_block_root: Box::new(parent_beacon_block_root),
message: e.to_string(),
@ -83,8 +67,5 @@ where
res.state.remove(&alloy_eips::eip4788::SYSTEM_ADDRESS);
res.state.remove(&evm.block().coinbase);
// re-set the previous env
evm.context.evm.env = previous_env;
Ok(Some(res))
}

View File

@ -1,10 +1,10 @@
//! [EIP-7002](https://eips.ethereum.org/EIPS/eip-7002) system call implementation.
use crate::ConfigureEvm;
use alloc::{boxed::Box, format};
use crate::Evm;
use alloc::format;
use alloy_eips::eip7002::WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS;
use alloy_primitives::Bytes;
use core::fmt::Display;
use reth_execution_errors::{BlockExecutionError, BlockValidationError};
use revm::{interpreter::Host, Database, Evm};
use revm_primitives::{ExecutionResult, ResultAndState};
/// Applies the post-block call to the EIP-7002 withdrawal requests contract.
@ -13,19 +13,10 @@ use revm_primitives::{ExecutionResult, ResultAndState};
///
/// Note: this does not commit the state changes to the database, it only transact the call.
#[inline]
pub(crate) fn transact_withdrawal_requests_contract_call<EvmConfig, EXT, DB>(
evm_config: &EvmConfig,
evm: &mut Evm<'_, EXT, DB>,
) -> Result<ResultAndState, BlockExecutionError>
where
DB: Database,
DB::Error: core::fmt::Display,
EvmConfig: ConfigureEvm,
{
// get previous env
let previous_env = Box::new(evm.context.env().clone());
// Fill transaction environment with the EIP-7002 withdrawal requests contract message data.
pub(crate) fn transact_withdrawal_requests_contract_call(
evm: &mut impl Evm<Error: Display>,
) -> Result<ResultAndState, BlockExecutionError> {
// Execute EIP-7002 withdrawal requests contract message data.
//
// This requirement for the withdrawal requests contract call defined by
// [EIP-7002](https://eips.ethereum.org/EIPS/eip-7002) is:
@ -33,17 +24,13 @@ where
// At the end of processing any execution block where `block.timestamp >= FORK_TIMESTAMP` (i.e.
// after processing all transactions and after performing the block body withdrawal requests
// validations), call the contract as `SYSTEM_ADDRESS`.
evm_config.fill_tx_env_system_contract_call(
&mut evm.context.evm.env,
let mut res = match evm.transact_system_call(
alloy_eips::eip7002::SYSTEM_ADDRESS,
WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS,
Bytes::new(),
);
let mut res = match evm.transact() {
) {
Ok(res) => res,
Err(e) => {
evm.context.evm.env = previous_env;
return Err(BlockValidationError::WithdrawalRequestsContractCall {
message: format!("execution failed: {e}"),
}
@ -59,9 +46,6 @@ where
res.state.remove(&alloy_eips::eip7002::SYSTEM_ADDRESS);
res.state.remove(&evm.block().coinbase);
// re-set the previous env
evm.context.evm.env = previous_env;
Ok(res)
}

View File

@ -1,10 +1,10 @@
//! [EIP-7251](https://eips.ethereum.org/EIPS/eip-7251) system call implementation.
use crate::ConfigureEvm;
use alloc::{boxed::Box, format};
use crate::Evm;
use alloc::format;
use alloy_eips::eip7251::CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS;
use alloy_primitives::Bytes;
use core::fmt::Display;
use reth_execution_errors::{BlockExecutionError, BlockValidationError};
use revm::{interpreter::Host, Database, Evm};
use revm_primitives::{ExecutionResult, ResultAndState};
/// Applies the post-block call to the EIP-7251 consolidation requests contract.
@ -14,19 +14,10 @@ use revm_primitives::{ExecutionResult, ResultAndState};
///
/// Note: this does not commit the state changes to the database, it only transact the call.
#[inline]
pub(crate) fn transact_consolidation_requests_contract_call<EvmConfig, EXT, DB>(
evm_config: &EvmConfig,
evm: &mut Evm<'_, EXT, DB>,
) -> Result<ResultAndState, BlockExecutionError>
where
DB: Database,
DB::Error: core::fmt::Display,
EvmConfig: ConfigureEvm,
{
// get previous env
let previous_env = Box::new(evm.context.env().clone());
// Fill transaction environment with the EIP-7251 consolidation requests contract message data.
pub(crate) fn transact_consolidation_requests_contract_call(
evm: &mut impl Evm<Error: Display>,
) -> Result<ResultAndState, BlockExecutionError> {
// Execute EIP-7251 consolidation requests contract message data.
//
// This requirement for the consolidation requests contract call defined by
// [EIP-7251](https://eips.ethereum.org/EIPS/eip-7251) is:
@ -35,17 +26,13 @@ where
// after processing all transactions and after performing the block body requests validations)
// clienst software MUST [..] call the contract as `SYSTEM_ADDRESS` and empty input data to
// trigger the system subroutine execute.
evm_config.fill_tx_env_system_contract_call(
&mut evm.context.evm.env,
let mut res = match evm.transact_system_call(
alloy_eips::eip7002::SYSTEM_ADDRESS,
CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS,
Bytes::new(),
);
let mut res = match evm.transact() {
) {
Ok(res) => res,
Err(e) => {
evm.context.evm.env = previous_env;
return Err(BlockValidationError::ConsolidationRequestsContractCall {
message: format!("execution failed: {e}"),
}
@ -61,9 +48,6 @@ where
res.state.remove(&alloy_eips::eip7002::SYSTEM_ADDRESS);
res.state.remove(&evm.block().coinbase);
// re-set the previous env
evm.context.evm.env = previous_env;
Ok(res)
}

View File

@ -1,6 +1,6 @@
//! System contract call functions.
use crate::{ConfigureEvm, EvmEnv};
use crate::{ConfigureEvm, Evm, EvmEnv};
use alloc::{boxed::Box, sync::Arc};
use alloy_consensus::BlockHeader;
use alloy_eips::{
@ -10,7 +10,7 @@ use alloy_primitives::Bytes;
use core::fmt::Display;
use reth_chainspec::EthereumHardforks;
use reth_execution_errors::BlockExecutionError;
use revm::{Database, DatabaseCommit, Evm};
use revm::{Database, DatabaseCommit};
use revm_primitives::{EvmState, B256};
mod eip2935;
@ -76,15 +76,11 @@ where
Chainspec: EthereumHardforks,
{
/// Apply pre execution changes.
pub fn apply_pre_execution_changes<DB, Ext>(
pub fn apply_pre_execution_changes(
&mut self,
header: &EvmConfig::Header,
evm: &mut Evm<'_, Ext, DB>,
) -> Result<(), BlockExecutionError>
where
DB: Database + DatabaseCommit,
DB::Error: Display,
{
evm: &mut impl Evm<DB: DatabaseCommit, Error: Display>,
) -> Result<(), BlockExecutionError> {
self.apply_blockhashes_contract_call(
header.timestamp(),
header.number(),
@ -102,14 +98,10 @@ where
}
/// Apply post execution changes.
pub fn apply_post_execution_changes<DB, Ext>(
pub fn apply_post_execution_changes(
&mut self,
evm: &mut Evm<'_, Ext, DB>,
) -> Result<Requests, BlockExecutionError>
where
DB: Database + DatabaseCommit,
DB::Error: Display,
{
evm: &mut impl Evm<DB: DatabaseCommit, Error: Display>,
) -> Result<Requests, BlockExecutionError> {
let mut requests = Requests::default();
// Collect all EIP-7685 requests
@ -152,19 +144,14 @@ where
}
/// Applies the pre-block call to the EIP-2935 blockhashes contract.
pub fn apply_blockhashes_contract_call<DB, Ext>(
pub fn apply_blockhashes_contract_call(
&mut self,
timestamp: u64,
block_number: u64,
parent_block_hash: B256,
evm: &mut Evm<'_, Ext, DB>,
) -> Result<(), BlockExecutionError>
where
DB: Database + DatabaseCommit,
DB::Error: Display,
{
evm: &mut impl Evm<DB: DatabaseCommit, Error: Display>,
) -> Result<(), BlockExecutionError> {
let result_and_state = eip2935::transact_blockhashes_contract_call(
&self.evm_config,
&self.chain_spec,
timestamp,
block_number,
@ -176,7 +163,7 @@ where
if let Some(ref mut hook) = self.hook {
hook.on_state(&res.state);
}
evm.context.evm.db.commit(res.state);
evm.db_mut().commit(res.state);
}
Ok(())
@ -207,19 +194,14 @@ where
}
/// Applies the pre-block call to the EIP-4788 beacon root contract.
pub fn apply_beacon_root_contract_call<DB, Ext>(
pub fn apply_beacon_root_contract_call(
&mut self,
timestamp: u64,
block_number: u64,
parent_block_hash: Option<B256>,
evm: &mut Evm<'_, Ext, DB>,
) -> Result<(), BlockExecutionError>
where
DB: Database + DatabaseCommit,
DB::Error: Display,
{
evm: &mut impl Evm<DB: DatabaseCommit, Error: Display>,
) -> Result<(), BlockExecutionError> {
let result_and_state = eip4788::transact_beacon_root_contract_call(
&self.evm_config,
&self.chain_spec,
timestamp,
block_number,
@ -231,7 +213,7 @@ where
if let Some(ref mut hook) = self.hook {
hook.on_state(&res.state);
}
evm.context.evm.db.commit(res.state);
evm.db_mut().commit(res.state);
}
Ok(())
@ -256,21 +238,16 @@ where
}
/// Applies the post-block call to the EIP-7002 withdrawal request contract.
pub fn apply_withdrawal_requests_contract_call<DB, Ext>(
pub fn apply_withdrawal_requests_contract_call(
&mut self,
evm: &mut Evm<'_, Ext, DB>,
) -> Result<Bytes, BlockExecutionError>
where
DB: Database + DatabaseCommit,
DB::Error: Display,
{
let result_and_state =
eip7002::transact_withdrawal_requests_contract_call(&self.evm_config.clone(), evm)?;
evm: &mut impl Evm<DB: DatabaseCommit, Error: Display>,
) -> Result<Bytes, BlockExecutionError> {
let result_and_state = eip7002::transact_withdrawal_requests_contract_call(evm)?;
if let Some(ref mut hook) = self.hook {
hook.on_state(&result_and_state.state);
}
evm.context.evm.db.commit(result_and_state.state);
evm.db_mut().commit(result_and_state.state);
eip7002::post_commit(result_and_state.result)
}
@ -294,21 +271,16 @@ where
}
/// Applies the post-block call to the EIP-7251 consolidation requests contract.
pub fn apply_consolidation_requests_contract_call<DB, Ext>(
pub fn apply_consolidation_requests_contract_call(
&mut self,
evm: &mut Evm<'_, Ext, DB>,
) -> Result<Bytes, BlockExecutionError>
where
DB: Database + DatabaseCommit,
DB::Error: Display,
{
let result_and_state =
eip7251::transact_consolidation_requests_contract_call(&self.evm_config.clone(), evm)?;
evm: &mut impl Evm<DB: DatabaseCommit, Error: Display>,
) -> Result<Bytes, BlockExecutionError> {
let result_and_state = eip7251::transact_consolidation_requests_contract_call(evm)?;
if let Some(ref mut hook) = self.hook {
hook.on_state(&result_and_state.state);
}
evm.context.evm.db.commit(result_and_state.state);
evm.db_mut().commit(result_and_state.state);
eip7251::post_commit(result_and_state.result)
}