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 10 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>,
/// Factory used by `anvil` to extend the EVM's precompiles.
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
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
90 changes: 90 additions & 0 deletions crates/anvil/src/evm.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
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,
{
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