use alloc::{boxed::Box, string::ToString};
use alloy_eips::eip2935::HISTORY_STORAGE_ADDRESS;
use crate::ConfigureEvm;
use core::fmt::Display;
use reth_chainspec::{ChainSpec, EthereumHardforks};
use reth_execution_errors::{BlockExecutionError, BlockValidationError};
use reth_primitives::Header;
use revm::{interpreter::Host, Database, DatabaseCommit, Evm};
use revm_primitives::{BlockEnv, CfgEnvWithHandlerCfg, EnvWithHandlerCfg, ResultAndState, B256};
pub fn pre_block_blockhashes_contract_call<EvmConfig, DB>(
db: &mut DB,
evm_config: &EvmConfig,
chain_spec: &ChainSpec,
initialized_cfg: &CfgEnvWithHandlerCfg,
initialized_block_env: &BlockEnv,
parent_block_hash: B256,
) -> Result<(), BlockExecutionError>
where
DB: Database + DatabaseCommit,
DB::Error: Display,
EvmConfig: ConfigureEvm<Header = Header>,
{
let mut evm_pre_block = 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();
apply_blockhashes_contract_call(
evm_config,
chain_spec,
initialized_block_env.timestamp.to(),
initialized_block_env.number.to(),
parent_block_hash,
&mut evm_pre_block,
)
}
#[inline]
pub fn transact_blockhashes_contract_call<EvmConfig, EXT, DB>(
evm_config: &EvmConfig,
chain_spec: &ChainSpec,
block_timestamp: u64,
block_number: u64,
parent_block_hash: B256,
evm: &mut Evm<'_, EXT, DB>,
) -> Result<Option<ResultAndState>, BlockExecutionError>
where
DB: Database + DatabaseCommit,
DB::Error: core::fmt::Display,
EvmConfig: ConfigureEvm<Header = Header>,
{
if !chain_spec.is_prague_active_at_timestamp(block_timestamp) {
return Ok(None)
}
if block_number == 0 {
return Ok(None)
}
let previous_env = Box::new(evm.context.env().clone());
evm_config.fill_tx_env_system_contract_call(
&mut evm.context.evm.env,
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())
}
};
res.state.remove(&alloy_eips::eip4788::SYSTEM_ADDRESS);
res.state.remove(&evm.block().coinbase);
evm.context.evm.env = previous_env;
Ok(Some(res))
}
#[inline]
pub fn apply_blockhashes_contract_call<EvmConfig, EXT, DB>(
evm_config: &EvmConfig,
chain_spec: &ChainSpec,
block_timestamp: u64,
block_number: u64,
parent_block_hash: B256,
evm: &mut Evm<'_, EXT, DB>,
) -> Result<(), BlockExecutionError>
where
DB: Database + DatabaseCommit,
DB::Error: core::fmt::Display,
EvmConfig: ConfigureEvm<Header = Header>,
{
if let Some(res) = transact_blockhashes_contract_call(
evm_config,
chain_spec,
block_timestamp,
block_number,
parent_block_hash,
evm,
)? {
evm.context.evm.db.commit(res.state);
}
Ok(())
}