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

perf: avoid cloning precompiles #1486

Merged
merged 7 commits into from
Jun 17, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
34 changes: 32 additions & 2 deletions crates/precompile/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ use core::hash::Hash;
use once_cell::race::OnceBox;
#[doc(hidden)]
pub use revm_primitives as primitives;
use revm_primitives::HashSet;
pub use revm_primitives::{
precompile::{PrecompileError as Error, *},
Address, Bytes, HashMap, Log, B256,
Expand All @@ -39,7 +40,9 @@ pub fn calc_linear_cost_u32(len: usize, base: u64, word: u64) -> u64 {
#[derive(Clone, Default, Debug)]
pub struct Precompiles {
/// Precompiles.
pub inner: HashMap<Address, Precompile>,
inner: HashMap<Address, Precompile>,
/// Addresses of precompile.
addresses: HashSet<Address>,
}

impl Precompiles {
Expand Down Expand Up @@ -71,6 +74,11 @@ impl Precompiles {
})
}

/// Returns inner HashMap of precompiles.
pub fn inner(&self) -> &HashMap<Address, Precompile> {
&self.inner
}

/// Returns precompiles for Byzantium spec.
pub fn byzantium() -> &'static Self {
static INSTANCE: OnceBox<Precompiles> = OnceBox::new();
Expand Down Expand Up @@ -206,11 +214,19 @@ impl Precompiles {
self.inner.len()
}

/// Returns the precompiles addresses as a set.
pub fn addresses_set(&self) -> &HashSet<Address> {
&self.addresses
}

/// Extends the precompiles with the given precompiles.
///
/// Other precompiles with overwrite existing precompiles.
#[inline]
pub fn extend(&mut self, other: impl IntoIterator<Item = PrecompileWithAddress>) {
self.inner.extend(other.into_iter().map(Into::into));
let items = other.into_iter().collect::<Vec<_>>();
self.addresses.extend(items.iter().map(|p| *p.address()));
self.inner.extend(items.into_iter().map(Into::into));
}
}

Expand All @@ -229,6 +245,20 @@ impl From<PrecompileWithAddress> for (Address, Precompile) {
}
}

impl PrecompileWithAddress {
/// Returns reference of address.
#[inline]
pub fn address(&self) -> &Address {
&self.0
}

/// Returns reference of precompile.
#[inline]
pub fn precompile(&self) -> &Precompile {
&self.1
}
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub enum PrecompileSpecId {
HOMESTEAD,
Expand Down
4 changes: 3 additions & 1 deletion crates/primitives/src/precompile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,9 @@ impl Precompile {
Precompile::Standard(p) => p(bytes, gas_price),
Precompile::Env(p) => p(bytes, gas_price, env),
Precompile::Stateful(ref p) => p.call(bytes, gas_price, env),
Precompile::StatefulMut(_) => panic!("call_ref on mutable stateful precompile"),
Precompile::StatefulMut(_) => Err(PrecompileErrors::Fatal {
msg: "call_ref on mutable stateful precompile".to_string(),
}),
}
}
}
Expand Down
85 changes: 35 additions & 50 deletions crates/revm/src/context/context_precompiles.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::InnerEvmContext;
use crate::{
precompile::{Precompile, PrecompileResult},
primitives::{db::Database, Address, Bytes, HashMap},
primitives::{db::Database, Address, Bytes, HashMap, HashSet},
};
use dyn_clone::DynClone;
use revm_precompile::{PrecompileSpecId, PrecompileWithAddress, Precompiles};
Expand Down Expand Up @@ -31,32 +31,25 @@ impl<DB: Database> Clone for ContextPrecompile<DB> {

enum PrecompilesCow<DB: Database> {
/// Default precompiles, returned by `Precompiles::new`. Used to fast-path the default case.
Default(&'static Precompiles),
StaticRef(&'static Precompiles),
Owned(HashMap<Address, ContextPrecompile<DB>>),
}

impl<DB: Database> Clone for PrecompilesCow<DB> {
fn clone(&self) -> Self {
match *self {
PrecompilesCow::Default(p) => PrecompilesCow::Default(p),
PrecompilesCow::StaticRef(p) => PrecompilesCow::StaticRef(p),
PrecompilesCow::Owned(ref inner) => PrecompilesCow::Owned(inner.clone()),
}
}
}

/// Precompiles context.
#[derive(Clone)]
pub struct ContextPrecompiles<DB: Database> {
inner: PrecompilesCow<DB>,
}

impl<DB: Database> Clone for ContextPrecompiles<DB> {
rakita marked this conversation as resolved.
Show resolved Hide resolved
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}

impl<DB: Database> ContextPrecompiles<DB> {
/// Creates a new precompiles context at the given spec ID.
///
Expand All @@ -73,7 +66,7 @@ impl<DB: Database> ContextPrecompiles<DB> {
#[inline]
pub fn from_static_precompiles(precompiles: &'static Precompiles) -> Self {
Self {
inner: PrecompilesCow::Default(precompiles),
inner: PrecompilesCow::StaticRef(precompiles),
}
}

Expand All @@ -85,36 +78,29 @@ impl<DB: Database> ContextPrecompiles<DB> {
}
}

/// Returns precompiles addresses as a HashSet.
pub fn addresses_set(&self) -> HashSet<Address> {
match self.inner {
PrecompilesCow::StaticRef(inner) => inner.addresses_set().clone(),
PrecompilesCow::Owned(ref inner) => inner.keys().cloned().collect(),
}
}

/// Returns precompiles addresses.
#[inline]
pub fn addresses(&self) -> impl ExactSizeIterator<Item = &Address> {
// SAFETY: `keys` does not touch values.
unsafe { self.fake_as_owned() }.keys()
pub fn addresses<'a>(&'a self) -> Box<dyn ExactSizeIterator<Item = &Address> + 'a> {
match self.inner {
PrecompilesCow::StaticRef(inner) => Box::new(inner.addresses()),
PrecompilesCow::Owned(ref inner) => Box::new(inner.keys()),
}
}

/// Returns `true` if the precompiles contains the given address.
#[inline]
pub fn contains(&self, address: &Address) -> bool {
// SAFETY: `contains_key` does not touch values.
unsafe { self.fake_as_owned() }.contains_key(address)
}

/// View the internal precompiles map as the `Owned` variant.
///
/// # Safety
///
/// The resulting value type is wrong if this is `Default`,
/// but this works for methods that operate only on keys because both maps' internal value types
/// have the same size.
#[inline]
unsafe fn fake_as_owned(&self) -> &HashMap<Address, ContextPrecompile<DB>> {
const _: () = assert!(
core::mem::size_of::<ContextPrecompile<crate::db::EmptyDB>>()
== core::mem::size_of::<Precompile>()
);
match self.inner {
PrecompilesCow::Default(inner) => unsafe { core::mem::transmute(inner) },
PrecompilesCow::Owned(ref inner) => inner,
PrecompilesCow::StaticRef(inner) => inner.contains(address),
PrecompilesCow::Owned(ref inner) => inner.contains_key(address),
}
}

Expand All @@ -130,7 +116,7 @@ impl<DB: Database> ContextPrecompiles<DB> {
evmctx: &mut InnerEvmContext<DB>,
) -> Option<PrecompileResult> {
Some(match self.inner {
PrecompilesCow::Default(p) => p.get(address)?.call_ref(bytes, gas_price, &evmctx.env),
PrecompilesCow::StaticRef(p) => p.get(address)?.call_ref(bytes, gas_price, &evmctx.env),
PrecompilesCow::Owned(ref mut owned) => match owned.get_mut(address)? {
ContextPrecompile::Ordinary(p) => p.call(bytes, gas_price, &evmctx.env),
ContextPrecompile::ContextStateful(p) => p.call(bytes, gas_price, evmctx),
Expand All @@ -144,29 +130,28 @@ impl<DB: Database> ContextPrecompiles<DB> {
/// Clones the precompiles map if it is shared.
#[inline]
pub fn to_mut(&mut self) -> &mut HashMap<Address, ContextPrecompile<DB>> {
match self.inner {
PrecompilesCow::Default(_) => self.to_mut_slow(),
PrecompilesCow::Owned(ref mut inner) => inner,
}
}
self.mutate_into_owned();

#[allow(clippy::wrong_self_convention)]
#[cold]
fn to_mut_slow(&mut self) -> &mut HashMap<Address, ContextPrecompile<DB>> {
DaniPopes marked this conversation as resolved.
Show resolved Hide resolved
let PrecompilesCow::Default(precompiles) = self.inner else {
let PrecompilesCow::Owned(inner) = &mut self.inner else {
unreachable!()
};
inner
}

/// Mutates Self into Owned variant, or do nothing if it is already Owned.
/// Mutation will clone all precompiles.
rakita marked this conversation as resolved.
Show resolved Hide resolved
#[inline]
pub fn mutate_into_owned(&mut self) {
let PrecompilesCow::StaticRef(precompiles) = self.inner else {
return;
};
self.inner = PrecompilesCow::Owned(
precompiles
.inner
.inner()
.iter()
.map(|(k, v)| (*k, v.clone().into()))
.collect(),
);
match self.inner {
PrecompilesCow::Default(_) => unreachable!(),
PrecompilesCow::Owned(ref mut inner) => inner,
}
}
}

Expand Down Expand Up @@ -246,7 +231,7 @@ mod tests {

let mut precompiles = ContextPrecompiles::<EmptyDB>::new(PrecompileSpecId::HOMESTEAD);
assert_eq!(precompiles.addresses().count(), 4);
assert!(matches!(precompiles.inner, PrecompilesCow::Default(_)));
assert!(matches!(precompiles.inner, PrecompilesCow::StaticRef(_)));
assert!(!precompiles.contains(&custom_address));

let precompile = Precompile::Standard(|_, _| panic!());
Expand Down
7 changes: 3 additions & 4 deletions crates/revm/src/context/evm_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
interpreter::{
return_ok, CallInputs, Contract, Gas, InstructionResult, Interpreter, InterpreterResult,
},
primitives::{Address, Bytes, EVMError, Env, HashSet, U256},
primitives::{Address, Bytes, EVMError, Env, U256},
ContextPrecompiles, FrameOrResult, CALL_STACK_LIMIT,
};
use core::{
Expand Down Expand Up @@ -96,8 +96,7 @@ impl<DB: Database> EvmContext<DB> {
#[inline]
pub fn set_precompiles(&mut self, precompiles: ContextPrecompiles<DB>) {
// set warm loaded addresses.
self.journaled_state.warm_preloaded_addresses =
precompiles.addresses().copied().collect::<HashSet<_>>();
self.journaled_state.warm_preloaded_addresses = precompiles.addresses_set();
rakita marked this conversation as resolved.
Show resolved Hide resolved
self.precompiles = precompiles;
}

Expand Down Expand Up @@ -232,7 +231,7 @@ pub(crate) mod test_utils {
use crate::{
db::{CacheDB, EmptyDB},
journaled_state::JournaledState,
primitives::{address, SpecId, B256},
primitives::{address, HashSet, SpecId, B256},
};

/// Mock caller address.
Expand Down
Loading