feat: move next block cfg and env to configureevm (#10962)

This commit is contained in:
Matthias Seitz
2024-09-17 18:21:11 +02:00
committed by GitHub
parent 192f59f1b5
commit cd10cbf4ff
10 changed files with 245 additions and 180 deletions

1
Cargo.lock generated
View File

@ -7164,7 +7164,6 @@ version = "1.0.6"
dependencies = [
"reth-basic-payload-builder",
"reth-chain-state",
"reth-chainspec",
"reth-errors",
"reth-evm",
"reth-evm-ethereum",

View File

@ -13,13 +13,18 @@ extern crate alloc;
use alloc::vec::Vec;
use reth_chainspec::{ChainSpec, Head};
use reth_evm::{ConfigureEvm, ConfigureEvmEnv};
use reth_evm::{ConfigureEvm, ConfigureEvmEnv, NextBlockEnvAttributes};
use reth_primitives::{transaction::FillTxEnv, Address, Header, TransactionSigned, U256};
use revm_primitives::{AnalysisKind, Bytes, CfgEnvWithHandlerCfg, Env, TxEnv, TxKind};
use revm_primitives::{
AnalysisKind, BlobExcessGasAndPrice, BlockEnv, Bytes, CfgEnv, CfgEnvWithHandlerCfg, Env,
SpecId, TxEnv, TxKind,
};
use std::sync::Arc;
mod config;
pub use config::{revm_spec, revm_spec_by_timestamp_after_merge};
use reth_ethereum_forks::EthereumHardfork;
use reth_primitives::constants::EIP1559_INITIAL_BASE_FEE;
pub mod execute;
@ -50,29 +55,6 @@ impl EthEvmConfig {
impl ConfigureEvmEnv for EthEvmConfig {
type Header = Header;
fn fill_cfg_env(
&self,
cfg_env: &mut CfgEnvWithHandlerCfg,
header: &Header,
total_difficulty: U256,
) {
let spec_id = config::revm_spec(
self.chain_spec(),
&Head {
number: header.number,
timestamp: header.timestamp,
difficulty: header.difficulty,
total_difficulty,
hash: Default::default(),
},
);
cfg_env.chain_id = self.chain_spec.chain().id();
cfg_env.perf_analyse_created_bytecodes = AnalysisKind::Analyse;
cfg_env.handler_cfg.spec_id = spec_id;
}
fn fill_tx_env(&self, tx_env: &mut TxEnv, transaction: &TransactionSigned, sender: Address) {
transaction.fill_tx_env(tx_env, sender);
}
@ -116,6 +98,91 @@ impl ConfigureEvmEnv for EthEvmConfig {
// disable the base fee check for this call by setting the base fee to zero
env.block.basefee = U256::ZERO;
}
fn fill_cfg_env(
&self,
cfg_env: &mut CfgEnvWithHandlerCfg,
header: &Header,
total_difficulty: U256,
) {
let spec_id = config::revm_spec(
self.chain_spec(),
&Head {
number: header.number,
timestamp: header.timestamp,
difficulty: header.difficulty,
total_difficulty,
hash: Default::default(),
},
);
cfg_env.chain_id = self.chain_spec.chain().id();
cfg_env.perf_analyse_created_bytecodes = AnalysisKind::Analyse;
cfg_env.handler_cfg.spec_id = spec_id;
}
fn next_cfg_and_block_env(
&self,
parent: &Header,
attributes: NextBlockEnvAttributes,
) -> (CfgEnvWithHandlerCfg, BlockEnv) {
// configure evm env based on parent block
let cfg = CfgEnv::default().with_chain_id(self.chain_spec.chain().id());
// ensure we're not missing any timestamp based hardforks
let spec_id = revm_spec_by_timestamp_after_merge(&self.chain_spec, attributes.timestamp);
// if the parent block did not have excess blob gas (i.e. it was pre-cancun), but it is
// cancun now, we need to set the excess blob gas to the default value
let blob_excess_gas_and_price = parent
.next_block_excess_blob_gas()
.or_else(|| {
if spec_id == SpecId::CANCUN {
// default excess blob gas is zero
Some(0)
} else {
None
}
})
.map(BlobExcessGasAndPrice::new);
let mut basefee = parent.next_block_base_fee(
self.chain_spec.base_fee_params_at_timestamp(attributes.timestamp),
);
let mut gas_limit = U256::from(parent.gas_limit);
// If we are on the London fork boundary, we need to multiply the parent's gas limit by the
// elasticity multiplier to get the new gas limit.
if self.chain_spec.fork(EthereumHardfork::London).transitions_at_block(parent.number + 1) {
let elasticity_multiplier = self
.chain_spec
.base_fee_params_at_timestamp(attributes.timestamp)
.elasticity_multiplier;
// multiply the gas limit by the elasticity multiplier
gas_limit *= U256::from(elasticity_multiplier);
// set the base fee to the initial base fee from the EIP-1559 spec
basefee = Some(EIP1559_INITIAL_BASE_FEE)
}
let block_env = BlockEnv {
number: U256::from(parent.number + 1),
coinbase: attributes.suggested_fee_recipient,
timestamp: U256::from(attributes.timestamp),
difficulty: U256::ZERO,
prevrandao: Some(attributes.prev_randao),
gas_limit,
// calculate basefee based on parent block's gas usage
basefee: basefee.map(U256::from).unwrap_or_default(),
// calculate excess gas based on parent block's blob gas usage
blob_excess_gas_and_price,
};
(CfgEnvWithHandlerCfg::new_with_spec_id(cfg, spec_id), block_env)
}
}
impl ConfigureEvm for EthEvmConfig {

View File

@ -24,7 +24,6 @@ reth-basic-payload-builder.workspace = true
reth-evm.workspace = true
reth-evm-ethereum.workspace = true
reth-errors.workspace = true
reth-chainspec.workspace = true
reth-trie.workspace = true
reth-chain-state.workspace = true

View File

@ -14,7 +14,6 @@ use reth_basic_payload_builder::{
PayloadConfig, WithdrawalsOutcome,
};
use reth_chain_state::ExecutedBlock;
use reth_chainspec::EthereumHardfork;
use reth_errors::RethError;
use reth_evm::{
system_calls::{
@ -22,21 +21,19 @@ use reth_evm::{
post_block_withdrawal_requests_contract_call, pre_block_beacon_root_contract_call,
pre_block_blockhashes_contract_call,
},
ConfigureEvm,
};
use reth_evm_ethereum::{
eip6110::parse_deposits_from_receipts, revm_spec_by_timestamp_after_merge, EthEvmConfig,
ConfigureEvm, NextBlockEnvAttributes,
};
use reth_evm_ethereum::{eip6110::parse_deposits_from_receipts, EthEvmConfig};
use reth_execution_types::ExecutionOutcome;
use reth_payload_builder::{
error::PayloadBuilderError, EthBuiltPayload, EthPayloadBuilderAttributes,
};
use reth_payload_primitives::PayloadBuilderAttributes;
use reth_primitives::{
constants::{eip4844::MAX_DATA_GAS_PER_BLOCK, BEACON_NONCE, EIP1559_INITIAL_BASE_FEE},
constants::{eip4844::MAX_DATA_GAS_PER_BLOCK, BEACON_NONCE},
eip4844::calculate_excess_blob_gas,
proofs::{self, calculate_requests_root},
revm_primitives::{BlockEnv, CfgEnv, CfgEnvWithHandlerCfg, SpecId},
revm_primitives::{BlockEnv, CfgEnvWithHandlerCfg},
Block, EthereumHardforks, Header, IntoRecoveredTransaction, Receipt, EMPTY_OMMER_ROOT_HASH,
U256,
};
@ -48,9 +45,7 @@ use reth_transaction_pool::{
use reth_trie::HashedPostState;
use revm::{
db::states::bundle_state::BundleRetention,
primitives::{
BlobExcessGasAndPrice, EVMError, EnvWithHandlerCfg, InvalidTransaction, ResultAndState,
},
primitives::{EVMError, EnvWithHandlerCfg, InvalidTransaction, ResultAndState},
DatabaseCommit, State,
};
use std::sync::Arc;
@ -76,75 +71,17 @@ where
{
/// Returns the configured [`CfgEnvWithHandlerCfg`] and [`BlockEnv`] for the targeted payload
/// (that has the `parent` as its parent).
///
/// The `chain_spec` is used to determine the correct chain id and hardfork for the payload
/// based on its timestamp.
///
/// Block related settings are derived from the `parent` block and the configured attributes.
///
/// NOTE: This is only intended for beacon consensus (after merge).
fn cfg_and_block_env(
&self,
config: &PayloadConfig<EthPayloadBuilderAttributes>,
parent: &Header,
) -> (CfgEnvWithHandlerCfg, BlockEnv) {
// configure evm env based on parent block
let cfg = CfgEnv::default().with_chain_id(config.chain_spec.chain().id());
// ensure we're not missing any timestamp based hardforks
let spec_id =
revm_spec_by_timestamp_after_merge(&config.chain_spec, config.attributes.timestamp());
// if the parent block did not have excess blob gas (i.e. it was pre-cancun), but it is
// cancun now, we need to set the excess blob gas to the default value
let blob_excess_gas_and_price = parent
.next_block_excess_blob_gas()
.or_else(|| {
if spec_id == SpecId::CANCUN {
// default excess blob gas is zero
Some(0)
} else {
None
}
})
.map(BlobExcessGasAndPrice::new);
let mut basefee = parent.next_block_base_fee(
config.chain_spec.base_fee_params_at_timestamp(config.attributes.timestamp()),
);
let mut gas_limit = U256::from(parent.gas_limit);
// If we are on the London fork boundary, we need to multiply the parent's gas limit by the
// elasticity multiplier to get the new gas limit.
if config.chain_spec.fork(EthereumHardfork::London).transitions_at_block(parent.number + 1)
{
let elasticity_multiplier = config
.chain_spec
.base_fee_params_at_timestamp(config.attributes.timestamp())
.elasticity_multiplier;
// multiply the gas limit by the elasticity multiplier
gas_limit *= U256::from(elasticity_multiplier);
// set the base fee to the initial base fee from the EIP-1559 spec
basefee = Some(EIP1559_INITIAL_BASE_FEE)
}
let block_env = BlockEnv {
number: U256::from(parent.number + 1),
coinbase: config.attributes.suggested_fee_recipient(),
timestamp: U256::from(config.attributes.timestamp()),
difficulty: U256::ZERO,
prevrandao: Some(config.attributes.prev_randao()),
gas_limit,
// calculate basefee based on parent block's gas usage
basefee: basefee.map(U256::from).unwrap_or_default(),
// calculate excess gas based on parent block's blob gas usage
blob_excess_gas_and_price,
let next_attributes = NextBlockEnvAttributes {
timestamp: config.attributes.timestamp(),
suggested_fee_recipient: config.attributes.suggested_fee_recipient(),
prev_randao: config.attributes.prev_randao(),
};
(CfgEnvWithHandlerCfg::new_with_spec_id(cfg, spec_id), block_env)
self.evm_config.next_cfg_and_block_env(parent, next_attributes)
}
}

View File

@ -14,7 +14,9 @@ extern crate alloc;
use core::ops::Deref;
use crate::builder::RethEvmBuilder;
use reth_primitives::{Address, Header, TransactionSigned, TransactionSignedEcRecovered, U256};
use reth_primitives::{
Address, Header, TransactionSigned, TransactionSignedEcRecovered, B256, U256,
};
use revm::{Database, Evm, GetInspector};
use revm_primitives::{
BlockEnv, Bytes, CfgEnvWithHandlerCfg, Env, EnvWithHandlerCfg, SpecId, TxEnv,
@ -177,4 +179,29 @@ pub trait ConfigureEvmEnv: Send + Sync + Unpin + Clone + 'static {
let after_merge = cfg.handler_cfg.spec_id >= SpecId::MERGE;
self.fill_block_env(block_env, header, after_merge);
}
/// Returns the configured [`CfgEnvWithHandlerCfg`] and [`BlockEnv`] for `parent + 1` block.
///
/// This is intended for usage in block building after the merge and requires additional
/// attributes that can't be derived from the parent block: attributes that are determined by
/// the CL, such as the timestamp, suggested fee recipient, and randomness value.
fn next_cfg_and_block_env(
&self,
parent: &Header,
attributes: NextBlockEnvAttributes,
) -> (CfgEnvWithHandlerCfg, BlockEnv);
}
/// Represents additional attributes required to configure the next block.
/// This is used to configure the next block's environment
/// [`ConfigureEvmEnv::next_cfg_and_block_env`] and contains fields that can't be derived from the
/// parent header alone (attributes that are determined by the CL.)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NextBlockEnvAttributes {
/// The timestamp of the next block.
pub timestamp: u64,
/// The suggested fee recipient for the next block.
pub suggested_fee_recipient: Address,
/// The randomness value for the next block.
pub prev_randao: B256,
}

View File

@ -17,7 +17,7 @@ pub use reth_payload_primitives as payload;
pub use reth_payload_primitives::*;
/// Traits and helper types used to abstract over EVM methods and types.
pub use reth_evm::{ConfigureEvm, ConfigureEvmEnv};
pub use reth_evm::{ConfigureEvm, ConfigureEvmEnv, NextBlockEnvAttributes};
pub mod node;
pub use node::*;

View File

@ -10,7 +10,7 @@
#![cfg(feature = "optimism")]
use alloy_primitives::{Address, U256};
use reth_evm::{ConfigureEvm, ConfigureEvmEnv};
use reth_evm::{ConfigureEvm, ConfigureEvmEnv, NextBlockEnvAttributes};
use reth_optimism_chainspec::OpChainSpec;
use reth_primitives::{
revm_primitives::{AnalysisKind, CfgEnvWithHandlerCfg, TxEnv},
@ -29,7 +29,9 @@ pub use l1::*;
mod error;
pub use error::OptimismBlockExecutionError;
use revm_primitives::{Bytes, Env, OptimismFields, TxKind};
use revm_primitives::{
BlobExcessGasAndPrice, BlockEnv, Bytes, CfgEnv, Env, HandlerCfg, OptimismFields, SpecId, TxKind,
};
/// Optimism-related EVM configuration.
#[derive(Debug, Clone)]
@ -124,6 +126,61 @@ impl ConfigureEvmEnv for OptimismEvmConfig {
cfg_env.handler_cfg.spec_id = spec_id;
cfg_env.handler_cfg.is_optimism = self.chain_spec.is_optimism();
}
fn next_cfg_and_block_env(
&self,
parent: &Header,
attributes: NextBlockEnvAttributes,
) -> (CfgEnvWithHandlerCfg, BlockEnv) {
// configure evm env based on parent block
let cfg = CfgEnv::default().with_chain_id(self.chain_spec.chain().id());
// ensure we're not missing any timestamp based hardforks
let spec_id = revm_spec_by_timestamp_after_bedrock(&self.chain_spec, attributes.timestamp);
// if the parent block did not have excess blob gas (i.e. it was pre-cancun), but it is
// cancun now, we need to set the excess blob gas to the default value
let blob_excess_gas_and_price = parent
.next_block_excess_blob_gas()
.or_else(|| {
if spec_id.is_enabled_in(SpecId::CANCUN) {
// default excess blob gas is zero
Some(0)
} else {
None
}
})
.map(BlobExcessGasAndPrice::new);
let block_env = BlockEnv {
number: U256::from(parent.number + 1),
coinbase: attributes.suggested_fee_recipient,
timestamp: U256::from(attributes.timestamp),
difficulty: U256::ZERO,
prevrandao: Some(attributes.prev_randao),
gas_limit: U256::from(parent.gas_limit),
// calculate basefee based on parent block's gas usage
basefee: U256::from(
parent
.next_block_base_fee(
self.chain_spec.base_fee_params_at_timestamp(attributes.timestamp),
)
.unwrap_or_default(),
),
// calculate excess gas based on parent block's blob gas usage
blob_excess_gas_and_price,
};
let cfg_with_handler_cfg;
{
cfg_with_handler_cfg = CfgEnvWithHandlerCfg {
cfg_env: cfg,
handler_cfg: HandlerCfg { spec_id, is_optimism: true },
};
}
(cfg_with_handler_cfg, block_env)
}
}
impl ConfigureEvm for OptimismEvmConfig {

View File

@ -8,8 +8,10 @@ use alloy_primitives::U256;
use reth_basic_payload_builder::*;
use reth_chain_state::ExecutedBlock;
use reth_chainspec::{EthereumHardforks, OptimismHardfork};
use reth_evm::{system_calls::pre_block_beacon_root_contract_call, ConfigureEvm};
use reth_evm_optimism::revm_spec_by_timestamp_after_bedrock;
use reth_evm::{
system_calls::pre_block_beacon_root_contract_call, ConfigureEvm, ConfigureEvmEnv,
NextBlockEnvAttributes,
};
use reth_execution_types::ExecutionOutcome;
use reth_payload_builder::error::PayloadBuilderError;
use reth_payload_primitives::PayloadBuilderAttributes;
@ -17,7 +19,7 @@ use reth_primitives::{
constants::BEACON_NONCE,
eip4844::calculate_excess_blob_gas,
proofs,
revm_primitives::{BlockEnv, CfgEnv, CfgEnvWithHandlerCfg, SpecId},
revm_primitives::{BlockEnv, CfgEnvWithHandlerCfg},
Block, Header, IntoRecoveredTransaction, Receipt, TxType, EMPTY_OMMER_ROOT_HASH,
};
use reth_provider::StateProviderFactory;
@ -28,10 +30,7 @@ use reth_transaction_pool::{
use reth_trie::HashedPostState;
use revm::{
db::states::bundle_state::BundleRetention,
primitives::{
BlobExcessGasAndPrice, EVMError, EnvWithHandlerCfg, HandlerCfg, InvalidTransaction,
ResultAndState,
},
primitives::{EVMError, EnvWithHandlerCfg, InvalidTransaction, ResultAndState},
DatabaseCommit, State,
};
use std::sync::Arc;
@ -68,63 +67,24 @@ impl<EvmConfig> OptimismPayloadBuilder<EvmConfig> {
pub const fn is_compute_pending_block(&self) -> bool {
self.compute_pending_block
}
}
impl<EvmConfig> OptimismPayloadBuilder<EvmConfig>
where
EvmConfig: ConfigureEvmEnv,
{
/// Returns the configured [`CfgEnvWithHandlerCfg`] and [`BlockEnv`] for the targeted payload
/// (that has the `parent` as its parent).
fn cfg_and_block_env(
&self,
config: &PayloadConfig<OptimismPayloadBuilderAttributes>,
parent: &Header,
) -> (CfgEnvWithHandlerCfg, BlockEnv) {
// configure evm env based on parent block
let cfg = CfgEnv::default().with_chain_id(config.chain_spec.chain().id());
// ensure we're not missing any timestamp based hardforks
let spec_id =
revm_spec_by_timestamp_after_bedrock(&config.chain_spec, config.attributes.timestamp());
// if the parent block did not have excess blob gas (i.e. it was pre-cancun), but it is
// cancun now, we need to set the excess blob gas to the default value
let blob_excess_gas_and_price = parent
.next_block_excess_blob_gas()
.or_else(|| {
if spec_id.is_enabled_in(SpecId::CANCUN) {
// default excess blob gas is zero
Some(0)
} else {
None
}
})
.map(BlobExcessGasAndPrice::new);
let block_env = BlockEnv {
number: U256::from(parent.number + 1),
coinbase: config.attributes.suggested_fee_recipient(),
timestamp: U256::from(config.attributes.timestamp()),
difficulty: U256::ZERO,
prevrandao: Some(config.attributes.prev_randao()),
gas_limit: U256::from(parent.gas_limit),
// calculate basefee based on parent block's gas usage
basefee: U256::from(
parent
.next_block_base_fee(
config
.chain_spec
.base_fee_params_at_timestamp(config.attributes.timestamp()),
)
.unwrap_or_default(),
),
// calculate excess gas based on parent block's blob gas usage
blob_excess_gas_and_price,
let next_attributes = NextBlockEnvAttributes {
timestamp: config.attributes.timestamp(),
suggested_fee_recipient: config.attributes.suggested_fee_recipient(),
prev_randao: config.attributes.prev_randao(),
};
let cfg_with_handler_cfg;
{
cfg_with_handler_cfg = CfgEnvWithHandlerCfg {
cfg_env: cfg,
handler_cfg: HandlerCfg { spec_id, is_optimism: true },
};
}
(cfg_with_handler_cfg, block_env)
self.evm_config.next_cfg_and_block_env(parent, next_attributes)
}
}

View File

@ -18,6 +18,7 @@ use reth::{
handler::register::EvmHandler,
inspector_handle_register,
precompile::{Precompile, PrecompileOutput, PrecompileSpecId},
primitives::BlockEnv,
ContextPrecompiles, Database, Evm, EvmBuilder, GetInspector,
},
rpc::types::engine::PayloadAttributes,
@ -27,7 +28,8 @@ use reth::{
use reth_chainspec::{Chain, ChainSpec};
use reth_evm_ethereum::EthEvmConfig;
use reth_node_api::{
ConfigureEvm, ConfigureEvmEnv, FullNodeTypes, NodeTypes, NodeTypesWithEngine, PayloadTypes,
ConfigureEvm, ConfigureEvmEnv, FullNodeTypes, NextBlockEnvAttributes, NodeTypes,
NodeTypesWithEngine, PayloadTypes,
};
use reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};
use reth_node_ethereum::{
@ -89,15 +91,6 @@ impl MyEvmConfig {
impl ConfigureEvmEnv for MyEvmConfig {
type Header = Header;
fn fill_cfg_env(
&self,
cfg_env: &mut CfgEnvWithHandlerCfg,
header: &Header,
total_difficulty: U256,
) {
self.inner.fill_cfg_env(cfg_env, header, total_difficulty);
}
fn fill_tx_env(&self, tx_env: &mut TxEnv, transaction: &TransactionSigned, sender: Address) {
self.inner.fill_tx_env(tx_env, transaction, sender);
}
@ -111,6 +104,23 @@ impl ConfigureEvmEnv for MyEvmConfig {
) {
self.inner.fill_tx_env_system_contract_call(env, caller, contract, data);
}
fn fill_cfg_env(
&self,
cfg_env: &mut CfgEnvWithHandlerCfg,
header: &Header,
total_difficulty: U256,
) {
self.inner.fill_cfg_env(cfg_env, header, total_difficulty);
}
fn next_cfg_and_block_env(
&self,
parent: &Header,
attributes: NextBlockEnvAttributes,
) -> (CfgEnvWithHandlerCfg, BlockEnv) {
self.inner.next_cfg_and_block_env(parent, attributes)
}
}
impl ConfigureEvm for MyEvmConfig {

View File

@ -5,9 +5,10 @@
use alloy_genesis::Genesis;
use parking_lot::RwLock;
use reth::{
api::NextBlockEnvAttributes,
builder::{components::ExecutorBuilder, BuilderContext, NodeBuilder},
primitives::{
revm_primitives::{CfgEnvWithHandlerCfg, Env, PrecompileResult, TxEnv},
revm_primitives::{BlockEnv, CfgEnvWithHandlerCfg, Env, PrecompileResult, TxEnv},
Address, Bytes, U256,
},
revm::{
@ -150,6 +151,16 @@ impl ConfigureEvmEnv for MyEvmConfig {
self.inner.fill_tx_env(tx_env, transaction, sender)
}
fn fill_tx_env_system_contract_call(
&self,
env: &mut Env,
caller: Address,
contract: Address,
data: Bytes,
) {
self.inner.fill_tx_env_system_contract_call(env, caller, contract, data)
}
fn fill_cfg_env(
&self,
cfg_env: &mut CfgEnvWithHandlerCfg,
@ -159,14 +170,12 @@ impl ConfigureEvmEnv for MyEvmConfig {
self.inner.fill_cfg_env(cfg_env, header, total_difficulty)
}
fn fill_tx_env_system_contract_call(
fn next_cfg_and_block_env(
&self,
env: &mut Env,
caller: Address,
contract: Address,
data: Bytes,
) {
self.inner.fill_tx_env_system_contract_call(env, caller, contract, data)
parent: &Header,
attributes: NextBlockEnvAttributes,
) -> (CfgEnvWithHandlerCfg, BlockEnv) {
self.inner.next_cfg_and_block_env(parent, attributes)
}
}