Skip to content

Commit

Permalink
refactor: always create Evm through ConfigureEvm (#13812)
Browse files Browse the repository at this point in the history
  • Loading branch information
klkvr authored Jan 16, 2025
1 parent f1f9d5a commit 265f783
Show file tree
Hide file tree
Showing 9 changed files with 49 additions and 100 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 2 additions & 8 deletions crates/ethereum/payload/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,12 +202,7 @@ where

// apply eip-4788 pre block contract call
system_caller
.pre_block_beacon_root_contract_call(
&mut db,
evm_env.cfg_env_with_handler_cfg(),
evm_env.block_env(),
attributes.parent_beacon_block_root,
)
.pre_block_beacon_root_contract_call(&mut db, &evm_env, attributes.parent_beacon_block_root)
.map_err(|err| {
warn!(target: "payload_builder",
parent_hash=%parent_header.hash(),
Expand All @@ -220,8 +215,7 @@ where
// apply eip-2935 blockhashes update
system_caller.pre_block_blockhashes_contract_call(
&mut db,
evm_env.cfg_env_with_handler_cfg(),
evm_env.block_env(),
&evm_env,
parent_header.hash(),
)
.map_err(|err| {
Expand Down
55 changes: 19 additions & 36 deletions crates/evm/src/system_calls/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! System contract call functions.
use crate::ConfigureEvm;
use crate::{ConfigureEvm, EvmEnv};
use alloc::{boxed::Box, sync::Arc};
use alloy_consensus::BlockHeader;
use alloy_eips::{
Expand All @@ -11,7 +11,7 @@ use core::fmt::Display;
use reth_chainspec::EthereumHardforks;
use reth_execution_errors::BlockExecutionError;
use revm::{Database, DatabaseCommit, Evm};
use revm_primitives::{BlockEnv, CfgEnvWithHandlerCfg, EnvWithHandlerCfg, EvmState, B256};
use revm_primitives::{EvmState, B256};

mod eip2935;
mod eip4788;
Expand Down Expand Up @@ -70,24 +70,6 @@ impl<EvmConfig, Chainspec> SystemCaller<EvmConfig, Chainspec> {
pub fn finish(self) {}
}

fn initialize_evm<'a, DB>(
db: &'a mut DB,
initialized_cfg: &'a CfgEnvWithHandlerCfg,
initialized_block_env: &'a BlockEnv,
) -> Evm<'a, (), &'a mut DB>
where
DB: Database,
{
Evm::builder()
.with_db(db)
.with_env_with_handler_cfg(EnvWithHandlerCfg::new_with_cfg_env(
initialized_cfg.clone(),
initialized_block_env.clone(),
Default::default(),
))
.build()
}

impl<EvmConfig, Chainspec> SystemCaller<EvmConfig, Chainspec>
where
EvmConfig: ConfigureEvm,
Expand Down Expand Up @@ -149,18 +131,19 @@ where
pub fn pre_block_blockhashes_contract_call<DB>(
&mut self,
db: &mut DB,
initialized_cfg: &CfgEnvWithHandlerCfg,
initialized_block_env: &BlockEnv,
evm_env: &EvmEnv,
parent_block_hash: B256,
) -> Result<(), BlockExecutionError>
where
DB: Database + DatabaseCommit,
DB::Error: Display,
{
let mut evm = initialize_evm(db, initialized_cfg, initialized_block_env);
let evm_config = self.evm_config.clone();
let mut evm = evm_config.evm_with_env(db, evm_env.clone(), Default::default());

self.apply_blockhashes_contract_call(
initialized_block_env.timestamp.to(),
initialized_block_env.number.to(),
evm_env.block_env.timestamp.to(),
evm_env.block_env.number.to(),
parent_block_hash,
&mut evm,
)?;
Expand Down Expand Up @@ -203,19 +186,19 @@ where
pub fn pre_block_beacon_root_contract_call<DB>(
&mut self,
db: &mut DB,
initialized_cfg: &CfgEnvWithHandlerCfg,
initialized_block_env: &BlockEnv,
evm_env: &EvmEnv,
parent_beacon_block_root: Option<B256>,
) -> Result<(), BlockExecutionError>
where
DB: Database + DatabaseCommit,
DB::Error: Display,
{
let mut evm = initialize_evm(db, initialized_cfg, initialized_block_env);
let evm_config = self.evm_config.clone();
let mut evm = evm_config.evm_with_env(db, evm_env.clone(), Default::default());

self.apply_beacon_root_contract_call(
initialized_block_env.timestamp.to(),
initialized_block_env.number.to(),
evm_env.block_env.timestamp.to(),
evm_env.block_env.number.to(),
parent_beacon_block_root,
&mut evm,
)?;
Expand Down Expand Up @@ -258,14 +241,14 @@ where
pub fn post_block_withdrawal_requests_contract_call<DB>(
&mut self,
db: &mut DB,
initialized_cfg: &CfgEnvWithHandlerCfg,
initialized_block_env: &BlockEnv,
evm_env: &EvmEnv,
) -> Result<Bytes, BlockExecutionError>
where
DB: Database + DatabaseCommit,
DB::Error: Display,
{
let mut evm = initialize_evm(db, initialized_cfg, initialized_block_env);
let evm_config = self.evm_config.clone();
let mut evm = evm_config.evm_with_env(db, evm_env.clone(), Default::default());

let result = self.apply_withdrawal_requests_contract_call(&mut evm)?;

Expand Down Expand Up @@ -296,14 +279,14 @@ where
pub fn post_block_consolidation_requests_contract_call<DB>(
&mut self,
db: &mut DB,
initialized_cfg: &CfgEnvWithHandlerCfg,
initialized_block_env: &BlockEnv,
evm_env: &EvmEnv,
) -> Result<Bytes, BlockExecutionError>
where
DB: Database + DatabaseCommit,
DB::Error: Display,
{
let mut evm = initialize_evm(db, initialized_cfg, initialized_block_env);
let evm_config = self.evm_config.clone();
let mut evm = evm_config.evm_with_env(db, evm_env.clone(), Default::default());

let res = self.apply_consolidation_requests_contract_call(&mut evm)?;

Expand Down
3 changes: 1 addition & 2 deletions crates/optimism/payload/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -713,8 +713,7 @@ where
SystemCaller::new(self.evm_config.clone(), self.chain_spec.clone())
.pre_block_beacon_root_contract_call(
db,
&self.evm_env.cfg_env_with_handler_cfg,
&self.evm_env.block_env,
&self.evm_env,
self.attributes().payload_attributes.parent_beacon_block_root,
)
.map_err(|err| {
Expand Down
50 changes: 17 additions & 33 deletions crates/rpc/rpc-eth-api/src/helpers/pending_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,7 @@ use reth_provider::{
};
use reth_revm::{
database::StateProviderDatabase,
primitives::{
BlockEnv, CfgEnvWithHandlerCfg, EVMError, Env, ExecutionResult, InvalidTransaction,
ResultAndState,
},
primitives::{BlockEnv, EVMError, ExecutionResult, InvalidTransaction, ResultAndState},
};
use reth_rpc_eth_types::{EthApiError, PendingBlock, PendingBlockEnv, PendingBlockEnvOrigin};
use reth_transaction_pool::{
Expand Down Expand Up @@ -65,7 +62,7 @@ pub trait LoadPendingBlock:
&self,
) -> &Mutex<Option<PendingBlock<ProviderBlock<Self::Provider>, ProviderReceipt<Self::Provider>>>>;

/// Configures the [`CfgEnvWithHandlerCfg`] and [`BlockEnv`] for the pending block
/// Configures the [`EvmEnv`] for the pending block
///
/// If no pending block is available, this will derive it from the `latest` block
#[expect(clippy::type_complexity)]
Expand All @@ -86,12 +83,10 @@ pub trait LoadPendingBlock:
// Note: for the PENDING block we assume it is past the known merge block and
// thus this will not fail when looking up the total
// difficulty value for the blockenv.
let EvmEnv { cfg_env_with_handler_cfg, block_env } =
self.evm_config().cfg_and_block_env(block.header());
let evm_env = self.evm_config().cfg_and_block_env(block.header());

return Ok(PendingBlockEnv::new(
cfg_env_with_handler_cfg,
block_env,
evm_env,
PendingBlockEnvOrigin::ActualPending(block, receipts),
));
}
Expand All @@ -105,7 +100,7 @@ pub trait LoadPendingBlock:
.map_err(Self::Error::from_eth_err)?
.ok_or(EthApiError::HeaderNotFound(BlockNumberOrTag::Latest.into()))?;

let EvmEnv { cfg_env_with_handler_cfg, block_env } = self
let evm_env = self
.evm_config()
.next_cfg_and_block_env(
&latest,
Expand All @@ -119,11 +114,7 @@ pub trait LoadPendingBlock:
.map_err(RethError::other)
.map_err(Self::Error::from_eth_err)?;

Ok(PendingBlockEnv::new(
cfg_env_with_handler_cfg,
block_env,
PendingBlockEnvOrigin::DerivedFromLatest(latest.hash()),
))
Ok(PendingBlockEnv::new(evm_env, PendingBlockEnvOrigin::DerivedFromLatest(latest.hash())))
}

/// Returns the locally built pending block
Expand Down Expand Up @@ -159,7 +150,7 @@ pub trait LoadPendingBlock:
// check if the block is still good
if let Some(pending_block) = lock.as_ref() {
// this is guaranteed to be the `latest` header
if pending.block_env.number.to::<u64>() == pending_block.block.number() &&
if pending.evm_env.block_env.number.to::<u64>() == pending_block.block.number() &&
parent_hash == pending_block.block.parent_hash() &&
now <= pending_block.expires_at
{
Expand All @@ -171,7 +162,7 @@ pub trait LoadPendingBlock:
let (sealed_block, receipts) = match self
.spawn_blocking_io(move |this| {
// we rebuild the block
this.build_block(pending.cfg, pending.block_env, parent_hash)
this.build_block(pending.evm_env, parent_hash)
})
.await
{
Expand Down Expand Up @@ -243,8 +234,7 @@ pub trait LoadPendingBlock:
#[expect(clippy::type_complexity)]
fn build_block(
&self,
cfg: CfgEnvWithHandlerCfg,
block_env: BlockEnv,
evm_env: EvmEnv,
parent_hash: B256,
) -> Result<
(RecoveredBlock<ProviderBlock<Self::Provider>>, Vec<ProviderReceipt<Self::Provider>>),
Expand All @@ -262,23 +252,23 @@ pub trait LoadPendingBlock:

let mut cumulative_gas_used = 0;
let mut sum_blob_gas_used = 0;
let block_gas_limit: u64 = block_env.gas_limit.to::<u64>();
let base_fee = block_env.basefee.to::<u64>();
let block_gas_limit: u64 = evm_env.block_env.gas_limit.to::<u64>();
let base_fee = evm_env.block_env.basefee.to::<u64>();

let mut executed_txs = Vec::new();
let mut senders = Vec::new();
let mut best_txs =
self.pool().best_transactions_with_attributes(BestTransactionsAttributes::new(
base_fee,
block_env.get_blob_gasprice().map(|gasprice| gasprice as u64),
evm_env.block_env.get_blob_gasprice().map(|gasprice| gasprice as u64),
));

let chain_spec = self.provider().chain_spec();

let mut system_caller = SystemCaller::new(self.evm_config().clone(), chain_spec.clone());

system_caller
.pre_block_blockhashes_contract_call(&mut db, &cfg, &block_env, parent_hash)
.pre_block_blockhashes_contract_call(&mut db, &evm_env, parent_hash)
.map_err(|err| EthApiError::Internal(err.into()))?;

let mut results = Vec::new();
Expand Down Expand Up @@ -334,14 +324,8 @@ pub trait LoadPendingBlock:
}
}

// Configure the environment for the block.
let env = Env::boxed(
cfg.cfg_env.clone(),
block_env.clone(),
Self::evm_config(self).tx_env(tx.tx(), tx.signer()),
);

let mut evm = revm::Evm::builder().with_env(env).with_db(&mut db).build();
let tx_env = self.evm_config().tx_env(tx.tx(), tx.signer());
let mut evm = self.evm_config().evm_with_env(&mut db, evm_env.clone(), tx_env);

let ResultAndState { result, state } = match evm.transact() {
Ok(res) => res,
Expand Down Expand Up @@ -399,7 +383,7 @@ pub trait LoadPendingBlock:
// executes the withdrawals and commits them to the Database and BundleState.
let balance_increments = post_block_withdrawals_balance_increments(
chain_spec.as_ref(),
block_env.timestamp.try_into().unwrap_or(u64::MAX),
evm_env.block_env.timestamp.try_into().unwrap_or(u64::MAX),
&[],
);

Expand All @@ -416,7 +400,7 @@ pub trait LoadPendingBlock:
let state_root = db.database.state_root(hashed_state).map_err(Self::Error::from_eth_err)?;

let (block, receipts) = self.assemble_block_and_receipts(
&block_env,
&evm_env.block_env,
parent_hash,
state_root,
executed_txs,
Expand Down
5 changes: 2 additions & 3 deletions crates/rpc/rpc-eth-api/src/helpers/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,9 +219,8 @@ pub trait LoadState:
{
async move {
if at.is_pending() {
let PendingBlockEnv { cfg, block_env, origin } =
self.pending_block_env_and_cfg()?;
Ok(((cfg, block_env).into(), origin.state_block_id()))
let PendingBlockEnv { evm_env, origin } = self.pending_block_env_and_cfg()?;
Ok((evm_env, origin.state_block_id()))
} else {
// Use cached values if there is no pending block
let block_hash = RpcNodeCore::provider(self)
Expand Down
14 changes: 2 additions & 12 deletions crates/rpc/rpc-eth-api/src/helpers/trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -457,21 +457,11 @@ pub trait Trace:
SystemCaller::new(self.evm_config().clone(), self.provider().chain_spec());
// apply relevant system calls
system_caller
.pre_block_beacon_root_contract_call(
db,
evm_env.cfg_env_with_handler_cfg(),
evm_env.block_env(),
block.parent_beacon_block_root(),
)
.pre_block_beacon_root_contract_call(db, evm_env, block.parent_beacon_block_root())
.map_err(|_| EthApiError::EvmCustom("failed to apply 4788 system call".to_string()))?;

system_caller
.pre_block_blockhashes_contract_call(
db,
evm_env.cfg_env_with_handler_cfg(),
evm_env.block_env(),
block.parent_hash(),
)
.pre_block_blockhashes_contract_call(db, evm_env, block.parent_hash())
.map_err(|_| {
EthApiError::EvmCustom("failed to apply blockhashes system call".to_string())
})?;
Expand Down
1 change: 1 addition & 0 deletions crates/rpc/rpc-eth-types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ workspace = true
reth-chainspec.workspace = true
reth-chain-state.workspace = true
reth-errors.workspace = true
reth-evm.workspace = true
reth-execution-types.workspace = true
reth-metrics.workspace = true
reth-primitives = { workspace = true, features = ["secp256k1"] }
Expand Down
10 changes: 4 additions & 6 deletions crates/rpc/rpc-eth-types/src/pending_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,15 @@ use alloy_consensus::BlockHeader;
use alloy_eips::{BlockId, BlockNumberOrTag};
use alloy_primitives::B256;
use derive_more::Constructor;
use reth_evm::EvmEnv;
use reth_primitives::{Receipt, RecoveredBlock};
use reth_primitives_traits::Block;
use revm_primitives::{BlockEnv, CfgEnvWithHandlerCfg};

/// Configured [`BlockEnv`] and [`CfgEnvWithHandlerCfg`] for a pending block.
/// Configured [`EvmEnv`] for a pending block.
#[derive(Debug, Clone, Constructor)]
pub struct PendingBlockEnv<B: Block = reth_primitives::Block, R = Receipt> {
/// Configured [`CfgEnvWithHandlerCfg`] for the pending block.
pub cfg: CfgEnvWithHandlerCfg,
/// Configured [`BlockEnv`] for the pending block.
pub block_env: BlockEnv,
/// Configured [`EvmEnv`] for the pending block.
pub evm_env: EvmEnv,
/// Origin block for the config
pub origin: PendingBlockEnvOrigin<B, R>,
}
Expand Down

0 comments on commit 265f783

Please sign in to comment.