Skip to content
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

feat(anvil): add support for injecting precompiles #7589

Merged
merged 17 commits into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
15 changes: 12 additions & 3 deletions crates/anvil/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ use crate::{
fees::{INITIAL_BASE_FEE, INITIAL_GAS_PRICE},
pool::transactions::TransactionOrder,
},
mem,
mem::in_memory_db::MemDb,
FeeManager, Hardfork,
mem::{self, in_memory_db::MemDb},
FeeManager, Hardfork, PrecompileFactory,
};
use alloy_genesis::Genesis;
use alloy_primitives::{hex, utils::Unit, U256};
Expand Down Expand Up @@ -174,6 +173,8 @@ pub struct NodeConfig {
pub slots_in_an_epoch: u64,
/// The memory limit per EVM execution in bytes.
pub memory_limit: Option<u64>,
/// Set of precompiles to extend the EVM with. Empty by default.
pub precompile_factory: Option<Arc<dyn PrecompileFactory>>,
}

impl NodeConfig {
Expand Down Expand Up @@ -410,6 +411,7 @@ impl Default for NodeConfig {
enable_optimism: false,
slots_in_an_epoch: 32,
memory_limit: None,
precompile_factory: None,
}
}
}
Expand Down Expand Up @@ -822,6 +824,13 @@ impl NodeConfig {
self
}

/// Injects precompiles to `anvil`'s EVM.
#[must_use]
pub fn with_precompile_factory(mut self, factory: impl PrecompileFactory + 'static) -> Self {
self.precompile_factory = Some(Arc::new(factory));
self
}

/// Configures everything related to env, backend and database and returns the
/// [Backend](mem::Backend)
///
Expand Down
10 changes: 5 additions & 5 deletions crates/anvil/src/eth/backend/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,18 +155,18 @@ impl<'a, DB: Db + ?Sized, Validator: TransactionValidator> TransactionExecutor<'
}
TransactionExecutionOutcome::Exhausted(tx) => {
trace!(target: "backend", tx_gas_limit = %tx.pending_transaction.transaction.gas_limit(), ?tx, "block gas limit exhausting, skipping transaction");
continue
continue;
}
TransactionExecutionOutcome::Invalid(tx, _) => {
trace!(target: "backend", ?tx, "skipping invalid transaction");
invalid.push(tx);
continue
continue;
}
TransactionExecutionOutcome::DatabaseError(_, err) => {
// Note: this is only possible in forking mode, if for example a rpc request
// failed
trace!(target: "backend", ?err, "Failed to execute transaction due to database error");
continue
continue;
}
};
let receipt = tx.create_receipt();
Expand Down Expand Up @@ -270,7 +270,7 @@ impl<'a, 'b, DB: Db + ?Sized, Validator: TransactionValidator> Iterator
// check that we comply with the block's gas limit
let max_gas = self.gas_used.saturating_add(U256::from(env.tx.gas_limit));
if max_gas > env.block.gas_limit {
return Some(TransactionExecutionOutcome::Exhausted(transaction))
return Some(TransactionExecutionOutcome::Exhausted(transaction));
}

// validate before executing
Expand All @@ -280,7 +280,7 @@ impl<'a, 'b, DB: Db + ?Sized, Validator: TransactionValidator> Iterator
&env,
) {
warn!(target: "backend", "Skipping invalid tx execution [{:?}] {}", transaction.hash(), err);
return Some(TransactionExecutionOutcome::Invalid(transaction, err))
return Some(TransactionExecutionOutcome::Invalid(transaction, err));
}

let nonce = account.nonce;
Expand Down
46 changes: 38 additions & 8 deletions crates/anvil/src/eth/backend/mem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use crate::{
pool::transactions::PoolTransaction,
util::get_precompiles_for,
},
inject_precompiles,
mem::{
inspector::Inspector,
storage::{BlockchainStorage, InMemoryBlockStates, MinedBlockOutcome},
Expand Down Expand Up @@ -814,9 +815,14 @@ impl Backend {
env.tx = tx.pending_transaction.to_revm_tx_env();
let db = self.db.read().await;
let mut inspector = Inspector::default();
let mut evm = new_evm_with_inspector_ref(&*db, env, &mut inspector);

let ResultAndState { result, state } =
new_evm_with_inspector_ref(&*db, env, &mut inspector).transact()?;
let cfg = self.node_config.read().await;
if let Some(ref factory) = cfg.precompile_factory {
inject_precompiles(&mut evm, factory.precompiles());
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can put this in a function of Backend::new_evm_with_inspector_ref


let ResultAndState { result, state } = evm.transact()?;
let (exit_reason, gas_used, out, logs) = match result {
ExecutionResult::Success { reason, gas_used, logs, output, .. } => {
(reason.into(), gas_used, Some(output), Some(logs))
Expand All @@ -827,6 +833,7 @@ impl Backend {
ExecutionResult::Halt { reason, gas_used } => (reason.into(), gas_used, None, None),
};

drop(evm);
inspector.print_logs();

Ok((exit_reason, out, gas_used, state, logs.unwrap_or_default()))
Expand Down Expand Up @@ -1122,8 +1129,14 @@ impl Backend {
let mut inspector = Inspector::default();

let env = self.build_call_env(request, fee_details, block_env);
let ResultAndState { result, state } =
new_evm_with_inspector_ref(state, env, &mut inspector).transact()?;
let mut evm = new_evm_with_inspector_ref(state, env, &mut inspector);

let cfg = self.node_config.try_read().unwrap();
if let Some(ref factory) = cfg.precompile_factory {
inject_precompiles(&mut evm, factory.precompiles());
}

let ResultAndState { result, state } = evm.transact()?;
let (exit_reason, gas_used, out) = match result {
ExecutionResult::Success { reason, gas_used, output, .. } => {
(reason.into(), gas_used, Some(output))
Expand All @@ -1133,6 +1146,7 @@ impl Backend {
}
ExecutionResult::Halt { reason, gas_used } => (reason.into(), gas_used, None),
};
drop(evm);
inspector.print_logs();
Ok((exit_reason, out, gas_used, state))
}
Expand All @@ -1149,8 +1163,15 @@ impl Backend {
let block_number = block.number;

let env = self.build_call_env(request, fee_details, block);
let ResultAndState { result, state: _ } =
new_evm_with_inspector_ref(state, env, &mut inspector).transact()?;
let mut evm = new_evm_with_inspector_ref(state, env, &mut inspector);

let cfg = self.node_config.try_read().unwrap();
if let Some(ref factory) = cfg.precompile_factory {
inject_precompiles(&mut evm, factory.precompiles());
}

let ResultAndState { result, state: _ } = evm.transact()?;

let (exit_reason, gas_used, out) = match result {
ExecutionResult::Success { reason, gas_used, output, .. } => {
(reason.into(), gas_used, Some(output))
Expand All @@ -1160,6 +1181,8 @@ impl Backend {
}
ExecutionResult::Halt { reason, gas_used } => (reason.into(), gas_used, None),
};

drop(evm);
let tracer = inspector.tracer.expect("tracer disappeared");
let return_value = out.as_ref().map(|o| o.data().clone()).unwrap_or_default();
let res = tracer.into_geth_builder().geth_traces(gas_used, return_value, opts);
Expand Down Expand Up @@ -1195,8 +1218,14 @@ impl Backend {
);

let env = self.build_call_env(request, fee_details, block_env);
let ResultAndState { result, state: _ } =
new_evm_with_inspector_ref(state, env, &mut inspector).transact()?;
let mut evm = new_evm_with_inspector_ref(state, env, &mut inspector);

let cfg = self.node_config.try_read().unwrap();
if let Some(ref factory) = cfg.precompile_factory {
inject_precompiles(&mut evm, factory.precompiles());
}

let ResultAndState { result, state: _ } = evm.transact()?;
let (exit_reason, gas_used, out) = match result {
ExecutionResult::Success { reason, gas_used, output, .. } => {
(reason.into(), gas_used, Some(output))
Expand All @@ -1206,6 +1235,7 @@ impl Backend {
}
ExecutionResult::Halt { reason, gas_used } => (reason.into(), gas_used, None),
};
drop(evm);
let access_list = inspector.access_list();
Ok((exit_reason, out, gas_used, access_list))
}
Expand Down
91 changes: 91 additions & 0 deletions crates/anvil/src/evm.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
use std::{fmt::Debug, sync::Arc};

use alloy_primitives::Address;
use foundry_evm::revm::{self, precompile::Precompile, ContextPrecompile, ContextPrecompiles};

/// Object-safe trait that enables injecting extra precompiles when using
/// `anvil` as a library.
pub trait PrecompileFactory: Send + Sync + Unpin + Debug {
/// Returns a set of precompiles to extend the EVM with.
fn precompiles(&self) -> Vec<(Address, Precompile)>;
}

/// Appends a handler register to `evm` that injects the given `precompiles`.
pub fn inject_precompiles<DB, I>(
evm: &mut revm::Evm<'_, I, DB>,
precompiles: Vec<(Address, Precompile)>,
) where
DB: revm::Database,
I: revm::Inspector<DB>,
{
evm.handler.append_handler_register_box(Box::new(move |handler| {
let precompiles = precompiles.clone();
let loaded_precompiles = handler.pre_execution().load_precompiles();
handler.pre_execution.load_precompiles = Arc::new(move || {
let mut loaded_precompiles = loaded_precompiles.clone();
loaded_precompiles.extend(
precompiles
.clone()
.into_iter()
.map(|(addr, p)| (addr, ContextPrecompile::Ordinary(p))),
);
let mut default_precompiles = ContextPrecompiles::default();
default_precompiles.extend(loaded_precompiles);
default_precompiles
});
}));
}

#[cfg(test)]
mod tests {
use alloy_primitives::Address;
use foundry_evm::revm::{
self,
primitives::{address, Bytes, Precompile, PrecompileResult, SpecId},
};

use crate::{evm::inject_precompiles, PrecompileFactory};

#[test]
fn build_evm_with_extra_precompiles() {
const PRECOMPILE_ADDR: Address = address!("0000000000000000000000000000000000000071");
fn my_precompile(_bytes: &Bytes, _gas_limit: u64) -> PrecompileResult {
Ok((0, Bytes::new()))
}

#[derive(Debug)]
struct CustomPrecompileFactory;

impl PrecompileFactory for CustomPrecompileFactory {
fn precompiles(&self) -> Vec<(Address, Precompile)> {
vec![(PRECOMPILE_ADDR, Precompile::Standard(my_precompile))]
}
}

let db = revm::db::EmptyDB::default();
let env = Box::<revm::primitives::Env>::default();
let spec = SpecId::LATEST;
let handler_cfg = revm::primitives::HandlerCfg::new(spec);
let inspector = revm::inspectors::NoOpInspector;
let context = revm::Context::new(revm::EvmContext::new_with_env(db, env), inspector);
let handler = revm::Handler::new(handler_cfg);
let mut evm = revm::Evm::new(context, handler);
assert!(!evm
.handler
.pre_execution()
.load_precompiles()
.addresses()
.any(|&addr| addr == PRECOMPILE_ADDR));

inject_precompiles(&mut evm, CustomPrecompileFactory.precompiles());
assert!(evm
.handler
.pre_execution()
.load_precompiles()
.addresses()
.any(|&addr| addr == PRECOMPILE_ADDR));

let result = evm.transact().unwrap();
assert!(result.result.is_success());
}
}
3 changes: 3 additions & 0 deletions crates/anvil/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ pub use hardfork::Hardfork;

/// ethereum related implementations
pub mod eth;
/// Evm related abstractions
mod evm;
pub use evm::{inject_precompiles, PrecompileFactory};
/// support for polling filters
pub mod filter;
/// commandline output
Expand Down
6 changes: 3 additions & 3 deletions crates/evm/core/src/backend/cow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,15 +92,15 @@ impl<'a> CowBackend<'a> {
let env = EnvWithHandlerCfg::new_with_spec_id(Box::new(env.clone()), self.spec_id);
backend.initialize(&env);
self.is_initialized = true;
return backend
return backend;
}
self.backend.to_mut()
}

/// Returns a mutable instance of the Backend if it is initialized.
fn initialized_backend_mut(&mut self) -> Option<&mut Backend> {
if self.is_initialized {
return Some(self.backend.to_mut())
return Some(self.backend.to_mut());
}
None
}
Expand All @@ -124,7 +124,7 @@ impl<'a> DatabaseExt for CowBackend<'a> {
fn delete_snapshot(&mut self, id: U256) -> bool {
// delete snapshot requires a previous snapshot to be initialized
if let Some(backend) = self.initialized_backend_mut() {
return backend.delete_snapshot(id)
return backend.delete_snapshot(id);
}
false
}
Expand Down
4 changes: 2 additions & 2 deletions crates/evm/core/src/backend/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -838,7 +838,7 @@ impl Backend {
// created account takes precedence: for example contract creation in setups
if init_account.is_created() {
trace!(?loaded_account, "skipping created account");
continue
continue;
}

// otherwise we need to replace the account's info with the one from the fork's
Expand Down Expand Up @@ -912,7 +912,7 @@ impl Backend {

if tx.hash == tx_hash {
// found the target transaction
return Ok(Some(tx))
return Ok(Some(tx));
}
trace!(tx=?tx.hash, "committing transaction");

Expand Down
Loading
Loading