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 4 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
20 changes: 19 additions & 1 deletion crates/anvil/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use crate::{
FeeManager, Hardfork,
};
use alloy_genesis::Genesis;
use alloy_primitives::{hex, utils::Unit, U256};
use alloy_primitives::{hex, utils::Unit, Address, U256};
use alloy_providers::tmp::TempProvider;
use alloy_rpc_types::BlockNumberOrTag;
use alloy_signer::{
Expand All @@ -39,6 +39,7 @@ use foundry_evm::{
};
use parking_lot::RwLock;
use rand::thread_rng;
use revm::primitives::Precompile;
use serde_json::{json, to_writer, Value};
use std::{
collections::HashMap,
Expand Down Expand Up @@ -85,6 +86,13 @@ const BANNER: &str = r"
\__,_| |_| |_| \_/ |_| |_|
";

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

/// Configurations of the EVM node
#[derive(Clone, Debug)]
pub struct NodeConfig {
Expand Down Expand Up @@ -174,6 +182,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 extra_precompiles: Vec<(Address, Precompile)>,
}

impl NodeConfig {
Expand Down Expand Up @@ -410,6 +420,7 @@ impl Default for NodeConfig {
enable_optimism: false,
slots_in_an_epoch: 32,
memory_limit: None,
extra_precompiles: vec![],
}
}
}
Expand Down Expand Up @@ -822,6 +833,13 @@ impl NodeConfig {
self
}

/// Injects precompiles to `anvil`'s EVM.
#[must_use]
pub fn with_extra_precompiles(mut self, factory: impl PrecompileFactory) -> Self {
self.extra_precompiles.extend(factory.precompiles());
self
}

/// Configures everything related to env, backend and database and returns the
/// [Backend](mem::Backend)
///
Expand Down
18 changes: 11 additions & 7 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 All @@ -292,8 +292,12 @@ impl<'a, 'b, DB: Db + ?Sized, Validator: TransactionValidator> Iterator
}

let exec_result = {
let mut evm =
foundry_evm::utils::new_evm_with_inspector(&mut *self.db, env, &mut inspector);
let mut evm = foundry_evm::utils::new_evm_with_inspector(
&mut *self.db,
env,
&mut inspector,
vec![],
);

trace!(target: "backend", "[{:?}] executing", transaction.hash());
// transact and commit the transaction
Expand Down
13 changes: 9 additions & 4 deletions crates/anvil/src/eth/backend/mem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -814,9 +814,10 @@ impl Backend {
env.tx = tx.pending_transaction.to_revm_tx_env();
let db = self.db.read().await;
let mut inspector = Inspector::default();
let extra_precompiles = self.node_config.read().await.extra_precompiles.clone();

let ResultAndState { result, state } =
new_evm_with_inspector_ref(&*db, env, &mut inspector).transact()?;
new_evm_with_inspector_ref(&*db, env, &mut inspector, extra_precompiles).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 Down Expand Up @@ -1122,8 +1123,9 @@ impl Backend {
let mut inspector = Inspector::default();

let env = self.build_call_env(request, fee_details, block_env);
let extra_precompiles = self.node_config.try_read().unwrap().extra_precompiles.clone();
let ResultAndState { result, state } =
new_evm_with_inspector_ref(state, env, &mut inspector).transact()?;
new_evm_with_inspector_ref(state, env, &mut inspector, extra_precompiles).transact()?;
let (exit_reason, gas_used, out) = match result {
ExecutionResult::Success { reason, gas_used, output, .. } => {
(reason.into(), gas_used, Some(output))
Expand All @@ -1149,8 +1151,10 @@ impl Backend {
let block_number = block.number;

let env = self.build_call_env(request, fee_details, block);
let extra_precompiles = self.node_config.try_read().unwrap().extra_precompiles.clone();
let ResultAndState { result, state: _ } =
new_evm_with_inspector_ref(state, env, &mut inspector).transact()?;
new_evm_with_inspector_ref(state, env, &mut inspector, extra_precompiles)
.transact()?;
let (exit_reason, gas_used, out) = match result {
ExecutionResult::Success { reason, gas_used, output, .. } => {
(reason.into(), gas_used, Some(output))
Expand Down Expand Up @@ -1195,8 +1199,9 @@ impl Backend {
);

let env = self.build_call_env(request, fee_details, block_env);
let extra_precompiles = self.node_config.try_read().unwrap().extra_precompiles.clone();
let ResultAndState { result, state: _ } =
new_evm_with_inspector_ref(state, env, &mut inspector).transact()?;
new_evm_with_inspector_ref(state, env, &mut inspector, extra_precompiles).transact()?;
let (exit_reason, gas_used, out) = match result {
ExecutionResult::Success { reason, gas_used, output, .. } => {
(reason.into(), gas_used, Some(output))
Expand Down
2 changes: 1 addition & 1 deletion crates/anvil/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ use tokio::{
mod service;

mod config;
pub use config::{AccountGenerator, NodeConfig, CHAIN_ID, VERSION_MESSAGE};
pub use config::{AccountGenerator, NodeConfig, PrecompileFactory, CHAIN_ID, VERSION_MESSAGE};
mod hardfork;
use crate::server::{
error::{NodeError, NodeResult},
Expand Down
8 changes: 4 additions & 4 deletions crates/evm/core/src/backend/cow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ impl<'a> CowBackend<'a> {
// already, we reset the initialized state
self.is_initialized = false;
self.spec_id = env.handler_cfg.spec_id;
let mut evm = crate::utils::new_evm_with_inspector(self, env.clone(), inspector);
let mut evm = crate::utils::new_evm_with_inspector(self, env.clone(), inspector, vec![]);

let res = evm.transact().wrap_err("backend: failed while inspecting")?;

Expand All @@ -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
8 changes: 4 additions & 4 deletions crates/evm/core/src/backend/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -786,7 +786,7 @@ impl Backend {
inspector: I,
) -> eyre::Result<ResultAndState> {
self.initialize(env);
let mut evm = crate::utils::new_evm_with_inspector(self, env.clone(), inspector);
let mut evm = crate::utils::new_evm_with_inspector(self, env.clone(), inspector, vec![]);

let res = evm.transact().wrap_err("backend: failed while inspecting")?;

Expand Down 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 Expand Up @@ -1882,7 +1882,7 @@ fn commit_transaction<I: Inspector<Backend>>(
let fork = fork.clone();
let journaled_state = journaled_state.clone();
let db = Backend::new_with_fork(fork_id, fork, journaled_state);
crate::utils::new_evm_with_inspector(db, env, inspector)
crate::utils::new_evm_with_inspector(db, env, inspector, vec![])
.transact()
.wrap_err("backend: failed committing transaction")?
};
Expand Down
57 changes: 54 additions & 3 deletions crates/evm/core/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
use std::sync::Arc;

use alloy_json_abi::{Function, JsonAbi};
use alloy_primitives::{FixedBytes, U256};
use alloy_primitives::{Address, FixedBytes, U256};
use alloy_rpc_types::{Block, Transaction};
use eyre::ContextCompat;
use foundry_config::NamedChain;
use revm::{
db::WrapDatabaseRef,
precompile::Precompile,
primitives::{SpecId, TransactTo},
ContextPrecompile, ContextPrecompiles, Handler,
};

pub use foundry_compilers::utils::RuntimeOrHandle;
Expand Down Expand Up @@ -103,6 +107,7 @@ pub fn new_evm_with_inspector<'a, DB, I>(
db: DB,
env: revm::primitives::EnvWithHandlerCfg,
inspector: I,
precompiles: Vec<(Address, Precompile)>,
) -> revm::Evm<'a, I, DB>
where
DB: revm::Database,
Expand All @@ -114,6 +119,23 @@ where
let context = revm::Context::new(revm::EvmContext::new_with_env(db, env), inspector);
let mut handler = revm::Handler::new(handler_cfg);
handler.append_handler_register_plain(revm::inspector_handle_register);
handler.append_handler_register_box(Box::new(move |handler: &mut Handler<'_, _, _, DB>| {
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
});
}));

revm::Evm::new(context, handler)
}

Expand All @@ -122,17 +144,19 @@ pub fn new_evm_with_inspector_ref<'a, DB, I>(
db: DB,
env: revm::primitives::EnvWithHandlerCfg,
inspector: I,
precompiles: Vec<(Address, Precompile)>,
) -> revm::Evm<'a, I, WrapDatabaseRef<DB>>
where
DB: revm::DatabaseRef,
I: revm::Inspector<WrapDatabaseRef<DB>>,
{
new_evm_with_inspector(WrapDatabaseRef(db), env, inspector)
new_evm_with_inspector(WrapDatabaseRef(db), env, inspector, precompiles)
}

#[cfg(test)]
mod tests {
use super::*;
use revm::primitives::{address, Address, Bytes, Precompile, PrecompileResult};

#[test]
fn build_evm() {
Expand All @@ -145,7 +169,34 @@ mod tests {

let mut inspector = revm::inspectors::NoOpInspector;

let mut evm = new_evm_with_inspector(&mut db, cfg, &mut inspector);
let mut evm = new_evm_with_inspector(&mut db, cfg, &mut inspector, vec![]);
let result = evm.transact().unwrap();
assert!(result.result.is_success());
}

#[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()))
}

let mut 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 cfg = revm::primitives::EnvWithHandlerCfg::new(env, handler_cfg);

let mut inspector = revm::inspectors::NoOpInspector;
let extra_precompiles = vec![(PRECOMPILE_ADDR, Precompile::Standard(my_precompile))];
let mut evm = new_evm_with_inspector(&mut db, cfg, &mut inspector, extra_precompiles);
assert!(evm
.handler
.pre_execution()
.load_precompiles()
.addresses()
.any(|&addr| addr == PRECOMPILE_ADDR));

let result = evm.transact().unwrap();
assert!(result.result.is_success());
}
Expand Down
Loading
Loading