Skip to content

Feat: Use generic BuilderEvm trait with EvmFactory #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions crates/rbuilder/src/building/evm/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
use alloy_evm::{eth::EthEvmContext, Database, Evm, EvmEnv, IntoTxEnv};
use revm::{
context::{result::ResultAndState, TxEnv},
context_interface::result::{EVMError, HaltReason},
interpreter::interpreter::EthInterpreter,
Inspector,
};

pub trait BuilderEvm<DB: Database> {
fn transact(
&mut self,
tx: impl IntoTxEnv<TxEnv>,
) -> Result<ResultAndState<HaltReason>, EVMError<DB::Error>>;
}

impl<DB, EVM> BuilderEvm<DB> for EVM
where
DB: Database<Error: Send + Sync + 'static>,
EVM: Evm<DB = DB, Tx = TxEnv, Error = EVMError<DB::Error>, HaltReason = HaltReason>,
{
fn transact(
&mut self,
tx: impl IntoTxEnv<TxEnv>,
) -> Result<ResultAndState<HaltReason>, EVMError<DB::Error>> {
EVM::transact(self, tx)
}
}

/// Main trait to create instance of EVM.
/// Allows to use implementations of EVM with a simpler, more concrete interface than `reth_evm::EvmFactory`.
pub trait EvmFactory {
fn create_evm<DB>(&self, db: DB, env: EvmEnv) -> impl BuilderEvm<DB>
where
DB: Database<Error: Send + Sync + 'static>;

fn create_evm_with_inspector<DB, I>(
&self,
db: DB,
env: EvmEnv,
inspector: I,
) -> impl BuilderEvm<DB>
where
DB: Database<Error: Send + Sync + 'static>,
I: Inspector<EthEvmContext<DB>, EthInterpreter>;
}

mod revm_evm;
pub type RBuilderEvm = revm_evm::RevmEvmFactory;
53 changes: 53 additions & 0 deletions crates/rbuilder/src/building/evm/revm_evm.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use crate::building::{
evm::{BuilderEvm, EvmFactory},
precompile_cache::{PrecompileCache, WrappedPrecompile},
};
use alloy_evm::{eth::EthEvmContext, Database, EthEvm, EvmEnv};
use parking_lot::Mutex;
use revm::{
handler::EthPrecompiles, inspector::NoOpInspector, interpreter::interpreter::EthInterpreter,
Context, Inspector, MainBuilder, MainContext,
};
use std::sync::Arc;

#[derive(Debug, Default, Clone)]
pub struct RevmEvmFactory {
cache: Arc<Mutex<PrecompileCache>>,
}

impl EvmFactory for RevmEvmFactory {
fn create_evm<DB: Database>(&self, db: DB, env: EvmEnv) -> impl BuilderEvm<DB> {
EthEvm::new(
Context::mainnet()
.with_block(env.block_env)
.with_cfg(env.cfg_env)
.with_db(db)
.build_mainnet_with_inspector(NoOpInspector {})
.with_precompiles(WrappedPrecompile::new(
EthPrecompiles::default(),
self.cache.clone(),
)),
false,
)
}

fn create_evm_with_inspector<DB, I>(
&self,
db: DB,
env: EvmEnv,
inspector: I,
) -> impl BuilderEvm<DB>
where
DB: Database<Error: Send + Sync + 'static>,
I: Inspector<EthEvmContext<DB>, EthInterpreter>,
{
EthEvm::new(
Context::mainnet()
.with_block(env.block_env)
.with_cfg(env.cfg_env)
.with_db(db)
.build_mainnet_with_inspector(inspector),
true,
)
}
}
9 changes: 5 additions & 4 deletions crates/rbuilder/src/building/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ use alloy_eips::{
use alloy_evm::{block::system_calls::SystemCaller, env::EvmEnv, eth::eip6110};
use alloy_primitives::{Address, Bytes, B256, U256};
use alloy_rpc_types_beacon::events::PayloadAttributesEvent;
use evm::RBuilderEvm;
use jsonrpsee::core::Serialize;
use precompile_cache::EthCachedEvmFactory;
use reth::{
payload::PayloadId,
primitives::{Block, Receipt, SealedBlock},
Expand Down Expand Up @@ -55,6 +55,7 @@ pub mod builders;
pub mod built_block_trace;
#[cfg(test)]
pub mod conflict;
pub mod evm;
pub mod evm_inspector;
pub mod fmt;
pub mod order_commit;
Expand All @@ -74,7 +75,7 @@ pub use conflict::*;

#[derive(Debug, Clone)]
pub struct BlockBuildingContext {
pub evm_factory: EthCachedEvmFactory,
pub evm_factory: RBuilderEvm,
pub evm_env: EvmEnv,
pub attributes: EthPayloadBuilderAttributes,
pub chain_spec: Arc<ChainSpec>,
Expand Down Expand Up @@ -163,7 +164,7 @@ impl BlockBuildingContext {
)
});
Some(BlockBuildingContext {
evm_factory: EthCachedEvmFactory::default(),
evm_factory: RBuilderEvm::default(),
evm_env,
attributes,
chain_spec,
Expand Down Expand Up @@ -246,7 +247,7 @@ impl BlockBuildingContext {
)
});
BlockBuildingContext {
evm_factory: EthCachedEvmFactory::default(),
evm_factory: RBuilderEvm::default(),
evm_env,
attributes,
chain_spec,
Expand Down
23 changes: 7 additions & 16 deletions crates/rbuilder/src/building/order_commit.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use super::{
create_payout_tx, tracers::SimulationTracer, BlockBuildingContext, EstimatePayoutGasErr,
};
use crate::building::evm::{BuilderEvm, EvmFactory};
use crate::{
building::{
estimate_payout_gas_limit,
Expand All @@ -18,14 +19,11 @@ use alloy_eips::eip4844::{DATA_GAS_PER_BLOB, MAX_DATA_GAS_PER_BLOCK};
use alloy_primitives::{Address, B256, U256};
use reth::revm::{cached::CachedReads, database::StateProviderDatabase};
use reth_errors::ProviderError;
use reth_evm::{Evm, EvmEnv, EvmFactory};
use reth_evm::EvmEnv;
use reth_primitives::Receipt;
use reth_provider::{StateProvider, StateProviderBox};
use revm::{
context::{
result::{HaltReason, ResultAndState},
TxEnv,
},
context::result::ResultAndState,
context_interface::result::{EVMError, ExecutionResult, InvalidTransaction},
database::{states::bundle_state::BundleRetention, BundleState, State, WrapDatabaseRef},
Database, DatabaseCommit,
Expand Down Expand Up @@ -1216,21 +1214,14 @@ fn update_nonce_list_with_updates(
///
/// Gas checks must be done before calling this methods
/// thats why it can't return `TransactionErr::GasLeft` and `TransactionErr::BlobGasLeft`
fn execute_evm<Factory>(
evm_factory: &Factory,
evm_env: EvmEnv<Factory::Spec>,
fn execute_evm(
evm_factory: &impl EvmFactory,
evm_env: EvmEnv,
tx_with_blobs: &TransactionSignedEcRecoveredWithBlobs,
used_state_tracer: Option<&mut UsedStateTrace>,
db: impl Database<Error = ProviderError>,
blocklist: &HashSet<Address>,
) -> Result<Result<ResultAndState, TransactionErr>, CriticalCommitOrderError>
where
Factory: EvmFactory<
Tx = TxEnv,
HaltReason = HaltReason,
Error<ProviderError> = EVMError<ProviderError>,
>,
{
) -> Result<Result<ResultAndState, TransactionErr>, CriticalCommitOrderError> {
let tx = tx_with_blobs.internal_tx_unsecure();
let mut rbuilder_inspector = RBuilderEVMInspector::new(tx, used_state_tracer);

Expand Down
8 changes: 4 additions & 4 deletions crates/rbuilder/src/building/payout_tx.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use super::{BlockBuildingContext, BlockState};
use crate::building::evm::{BuilderEvm, EvmFactory};
use crate::utils::Signer;
use alloy_consensus::{constants::KECCAK_EMPTY, TxEip1559};
use alloy_primitives::{Address, TxKind as TransactionKind, U256};
use reth_chainspec::ChainSpec;
use reth_errors::ProviderError;
use reth_evm::{Evm, EvmFactory};
use reth_primitives::{Recovered, Transaction, TransactionSigned};
use revm::context::result::{EVMError, ExecutionResult};

Expand Down Expand Up @@ -65,11 +65,11 @@ pub fn insert_test_payout_tx(
)?;

let mut db = state.new_db_ref();
let mut evm = ctx.evm_factory.create_evm(db.as_mut(), ctx.evm_env.clone());

let cache_account = evm.db_mut().load_cache_account(builder_signer.address)?;
let cache_account = db.as_mut().load_cache_account(builder_signer.address)?;
cache_account.increment_balance(tx_value * 2); // double to cover tx value and fee

let mut evm = ctx.evm_factory.create_evm(db.as_mut(), ctx.evm_env.clone());

let res = evm.transact(&tx)?;
match res.result {
ExecutionResult::Success {
Expand Down
74 changes: 3 additions & 71 deletions crates/rbuilder/src/building/precompile_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,11 @@ use alloy_primitives::{Address, Bytes};
use derive_more::{Deref, DerefMut};
use lru::LruCache;
use parking_lot::Mutex;
use reth_evm::{eth::EthEvmContext, EthEvm, EthEvmFactory, EvmEnv, EvmFactory};
use revm::{
context::{
result::{EVMError, HaltReason},
BlockEnv, Cfg, CfgEnv, ContextTr, TxEnv,
},
handler::{EthPrecompiles, PrecompileProvider},
inspector::NoOpInspector,
interpreter::{interpreter::EthInterpreter, InterpreterResult},
context::{Cfg, ContextTr},
handler::PrecompileProvider,
interpreter::InterpreterResult,
primitives::hardfork::SpecId,
Context, Database, Inspector,
};
use std::{num::NonZeroUsize, sync::Arc};

Expand Down Expand Up @@ -100,65 +94,3 @@ impl<CTX: ContextTr, P: PrecompileProvider<CTX, Output = InterpreterResult>> Pre
self.precompile.contains(address)
}
}

#[derive(Debug, Clone, Default)]
pub struct EthCachedEvmFactory {
evm_factory: EthEvmFactory,
cache: Arc<Mutex<PrecompileCache>>,
}

impl EvmFactory for EthCachedEvmFactory {
type Evm<DB, I>
= EthEvm<DB, I, WrappedPrecompile<EthPrecompiles>>
where
DB: Database<Error: Send + Sync + 'static>,
I: Inspector<EthEvmContext<DB>>;

type Context<DB>
= Context<BlockEnv, TxEnv, CfgEnv, DB>
where
DB: Database<Error: Send + Sync + 'static>;

type Error<DBError>
= EVMError<DBError>
where
DBError: core::error::Error + Send + Sync + 'static;

type Tx = TxEnv;
type HaltReason = HaltReason;
type Spec = SpecId;

fn create_evm<DB>(&self, db: DB, input: EvmEnv) -> Self::Evm<DB, NoOpInspector>
where
DB: Database<Error: Send + Sync + 'static>,
{
let evm = self
.evm_factory
.create_evm(db, input)
.into_inner()
.with_precompiles(WrappedPrecompile::new(
EthPrecompiles::default(),
self.cache.clone(),
));

EthEvm::new(evm, false)
}

fn create_evm_with_inspector<DB, I>(
&self,
db: DB,
input: EvmEnv,
inspector: I,
) -> Self::Evm<DB, I>
where
DB: Database<Error: Send + Sync + 'static>,
I: Inspector<Self::Context<DB>, EthInterpreter>,
{
EthEvm::new(
self.create_evm(db, input)
.into_inner()
.with_inspector(inspector),
true,
)
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use crate::building::{
evm::{BuilderEvm, EvmFactory},
evm_inspector::{RBuilderEVMInspector, UsedStateTrace},
testing::test_chain_state::{BlockArgs, NamedAddr, TestChainState, TestContracts, TxArgs},
BlockState,
};
use alloy_primitives::Address;
use reth_evm::{Evm, EvmFactory};
use reth_primitives::{Recovered, TransactionSigned};

#[derive(Debug)]
Expand Down