From 59653ca95074bb85da952c6b8d06db4c97f4ce2f Mon Sep 17 00:00:00 2001 From: DaniPopes <57450786+DaniPopes@users.noreply.github.com> Date: Mon, 25 Sep 2023 15:28:50 +0200 Subject: [PATCH 1/7] feat: derive more traits --- bins/revme/src/statetest/merkle_trie.rs | 2 +- crates/interpreter/src/gas.rs | 2 +- crates/interpreter/src/host/dummy.rs | 5 ++-- crates/interpreter/src/inner_models.rs | 10 ++++---- crates/interpreter/src/instruction_result.rs | 4 ++-- crates/interpreter/src/instructions/i256.rs | 2 +- crates/interpreter/src/interpreter/memory.rs | 2 +- crates/interpreter/src/interpreter/stack.rs | 2 +- crates/interpreter/src/lib.rs | 3 +++ crates/precompile/src/lib.rs | 10 +++++--- crates/precompile/src/secp256k1.rs | 5 ++-- crates/primitives/src/bits.rs | 10 ++++---- crates/primitives/src/bytecode.rs | 6 ++--- crates/primitives/src/db.rs | 2 ++ crates/primitives/src/env.rs | 16 ++++++------- crates/primitives/src/kzg/env_settings.rs | 24 ++++++++++++++++++- crates/primitives/src/lib.rs | 3 +++ crates/primitives/src/log.rs | 2 +- crates/primitives/src/precompile.rs | 2 +- crates/primitives/src/result.rs | 16 ++++++------- crates/primitives/src/specification.rs | 3 ++- crates/primitives/src/state.rs | 13 ++++++++-- crates/revm/src/db/ethersdb.rs | 1 + crates/revm/src/db/in_memory_db.rs | 2 +- crates/revm/src/db/states/account_status.rs | 2 +- crates/revm/src/db/states/bundle_state.rs | 1 + crates/revm/src/db/states/cache.rs | 2 +- crates/revm/src/db/states/cache_account.rs | 2 +- crates/revm/src/db/states/plain_account.rs | 4 ++-- crates/revm/src/db/states/reverts.rs | 4 ++-- crates/revm/src/db/states/state.rs | 3 ++- crates/revm/src/db/states/state_builder.rs | 1 + .../revm/src/db/states/transition_account.rs | 2 +- crates/revm/src/db/states/transition_state.rs | 2 +- crates/revm/src/evm.rs | 2 +- crates/revm/src/evm_impl.rs | 13 ++++++++++ crates/revm/src/inspector/customprinter.rs | 5 ++-- crates/revm/src/inspector/noop.rs | 2 +- crates/revm/src/inspector/tracer_eip3155.rs | 1 + crates/revm/src/journaled_state.rs | 5 ++-- crates/revm/src/lib.rs | 4 +++- 41 files changed, 134 insertions(+), 68 deletions(-) diff --git a/bins/revme/src/statetest/merkle_trie.rs b/bins/revme/src/statetest/merkle_trie.rs index b37ec4a2ee..4f1653f5f7 100644 --- a/bins/revme/src/statetest/merkle_trie.rs +++ b/bins/revme/src/statetest/merkle_trie.rs @@ -65,7 +65,7 @@ pub fn trie_root(acc_data: Vec<(H160, Bytes)>) -> B256 { B256(sec_trie_root::(acc_data).0) } -#[derive(Default, Debug, Clone, PartialEq, Eq)] +#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)] pub struct KeccakHasher; impl Hasher for KeccakHasher { diff --git a/crates/interpreter/src/gas.rs b/crates/interpreter/src/gas.rs index 79d6f3905d..90cdc0a6eb 100644 --- a/crates/interpreter/src/gas.rs +++ b/crates/interpreter/src/gas.rs @@ -5,7 +5,7 @@ pub use calc::*; pub use constants::*; /// Represents the state of gas during execution. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct Gas { /// The initial gas limit. limit: u64, diff --git a/crates/interpreter/src/host/dummy.rs b/crates/interpreter/src/host/dummy.rs index c2df6b2f65..272134b90d 100644 --- a/crates/interpreter/src/host/dummy.rs +++ b/crates/interpreter/src/host/dummy.rs @@ -5,6 +5,7 @@ use crate::{ }; use alloc::vec::Vec; +#[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct DummyHost { pub env: Env, pub storage: HashMap, @@ -18,9 +19,7 @@ impl DummyHost { pub fn new(env: Env) -> Self { Self { env, - storage: HashMap::new(), - transient_storage: Default::default(), - log: Vec::new(), + ..Default::default() } } diff --git a/crates/interpreter/src/inner_models.rs b/crates/interpreter/src/inner_models.rs index 5467876995..0eb7867661 100644 --- a/crates/interpreter/src/inner_models.rs +++ b/crates/interpreter/src/inner_models.rs @@ -2,6 +2,7 @@ pub use crate::primitives::CreateScheme; use crate::primitives::{Bytes, B160, U256}; /// Inputs for a call. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct CallInputs { /// The target of the call. @@ -22,6 +23,7 @@ pub struct CallInputs { pub is_static: bool, } +#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct CreateInputs { pub caller: B160, @@ -36,7 +38,7 @@ pub struct CreateInputs { } /// Call schemes. -#[derive(Clone, Copy, Eq, PartialEq, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum CallScheme { /// `CALL` @@ -50,7 +52,7 @@ pub enum CallScheme { } /// CallContext of the runtime. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct CallContext { /// Execution address. @@ -78,7 +80,7 @@ impl Default for CallContext { } /// Transfer from source to target, with given value. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Transfer { /// Source address. @@ -89,7 +91,7 @@ pub struct Transfer { pub value: U256, } -#[derive(Default)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct SelfDestructResult { pub had_value: bool, diff --git a/crates/interpreter/src/instruction_result.rs b/crates/interpreter/src/instruction_result.rs index 6644a58e81..4214dc7288 100644 --- a/crates/interpreter/src/instruction_result.rs +++ b/crates/interpreter/src/instruction_result.rs @@ -1,7 +1,7 @@ use crate::primitives::{Eval, Halt}; #[repr(u8)] -#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum InstructionResult { // success codes @@ -89,7 +89,7 @@ impl InstructionResult { } } -#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum SuccessOrHalt { Success(Eval), Revert, diff --git a/crates/interpreter/src/instructions/i256.rs b/crates/interpreter/src/instructions/i256.rs index 5b7d21de88..6f217b9911 100644 --- a/crates/interpreter/src/instructions/i256.rs +++ b/crates/interpreter/src/instructions/i256.rs @@ -1,7 +1,7 @@ use crate::primitives::U256; use core::cmp::Ordering; -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[repr(i8)] pub enum Sign { // same as `cmp::Ordering` diff --git a/crates/interpreter/src/interpreter/memory.rs b/crates/interpreter/src/interpreter/memory.rs index 9982cf6096..2273671656 100644 --- a/crates/interpreter/src/interpreter/memory.rs +++ b/crates/interpreter/src/interpreter/memory.rs @@ -7,7 +7,7 @@ use core::{ /// A sequential memory. It uses Rust's `Vec` for internal /// representation. -#[derive(Clone, Eq, PartialEq)] +#[derive(Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Memory { data: Vec, diff --git a/crates/interpreter/src/interpreter/stack.rs b/crates/interpreter/src/interpreter/stack.rs index 0a3f8a2edb..7abaa6c41c 100644 --- a/crates/interpreter/src/interpreter/stack.rs +++ b/crates/interpreter/src/interpreter/stack.rs @@ -9,7 +9,7 @@ use core::fmt; pub const STACK_LIMIT: usize = 1024; /// EVM stack. -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Stack { data: Vec, diff --git a/crates/interpreter/src/lib.rs b/crates/interpreter/src/lib.rs index 7ecbd729d2..aab11ab93d 100644 --- a/crates/interpreter/src/lib.rs +++ b/crates/interpreter/src/lib.rs @@ -1,4 +1,7 @@ +#![warn(missing_debug_implementations)] +#![deny(unused_must_use, rust_2018_idioms)] #![cfg_attr(not(feature = "std"), no_std)] +#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] extern crate alloc; diff --git a/crates/precompile/src/lib.rs b/crates/precompile/src/lib.rs index 46f4c1bb96..9b8d1c5f73 100644 --- a/crates/precompile/src/lib.rs +++ b/crates/precompile/src/lib.rs @@ -1,4 +1,7 @@ -#![no_std] +#![warn(missing_debug_implementations)] +#![deny(unused_must_use, rust_2018_idioms)] +#![cfg_attr(not(feature = "std"), no_std)] +#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #[macro_use] extern crate alloc; @@ -64,7 +67,7 @@ impl Default for Precompiles { } } -#[derive(Clone)] +#[derive(Clone, PartialEq, Eq, Hash)] pub enum Precompile { Standard(StandardPrecompileFn), Env(EnvPrecompileFn), @@ -79,6 +82,7 @@ impl fmt::Debug for Precompile { } } +#[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct PrecompileAddress(B160, Precompile); impl From for (B160, Precompile) { @@ -87,7 +91,7 @@ impl From for (B160, Precompile) { } } -#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)] pub enum SpecId { HOMESTEAD, BYZANTIUM, diff --git a/crates/precompile/src/secp256k1.rs b/crates/precompile/src/secp256k1.rs index 7bd44d09d6..3097f16204 100644 --- a/crates/precompile/src/secp256k1.rs +++ b/crates/precompile/src/secp256k1.rs @@ -1,4 +1,6 @@ use crate::{Error, Precompile, PrecompileAddress, PrecompileResult, StandardPrecompileFn}; +use alloc::vec::Vec; +use core::cmp::min; pub const ECRECOVER: PrecompileAddress = PrecompileAddress( crate::u64_to_b160(1), @@ -60,9 +62,6 @@ mod secp256k1 { } fn ec_recover_run(i: &[u8], target_gas: u64) -> PrecompileResult { - use alloc::vec::Vec; - use core::cmp::min; - const ECRECOVER_BASE: u64 = 3_000; if ECRECOVER_BASE > target_gas { diff --git a/crates/primitives/src/bits.rs b/crates/primitives/src/bits.rs index 440c3029ee..5503f424f6 100644 --- a/crates/primitives/src/bits.rs +++ b/crates/primitives/src/bits.rs @@ -164,7 +164,7 @@ mod serialize { } /// Decoding bytes from hex string error. - #[derive(Debug, PartialEq, Eq)] + #[derive(Debug, PartialEq, Eq, Hash)] pub enum FromHexError { /// Invalid (non-hex) character encountered. InvalidHex { @@ -179,7 +179,7 @@ mod serialize { impl std::error::Error for FromHexError {} impl fmt::Display for FromHexError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Self::InvalidHex { character, index } => { write!(fmt, "invalid hex character: {character}, at {index}") @@ -245,7 +245,7 @@ mod serialize { } /// Expected length of bytes vector. - #[derive(Debug, PartialEq, Eq)] + #[derive(Debug, PartialEq, Eq, Hash)] pub enum ExpectedLen<'a> { /// Exact length in bytes. Exact(&'a mut [u8]), @@ -255,7 +255,7 @@ mod serialize { } impl<'a> fmt::Display for ExpectedLen<'a> { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { ExpectedLen::Exact(ref v) => write!(fmt, "length of {}", v.len() * 2), ExpectedLen::Between(min, ref v) => { @@ -281,7 +281,7 @@ mod serialize { impl<'a, 'b> de::Visitor<'b> for Visitor<'a> { type Value = usize; - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!( formatter, "a (both 0x-prefixed or not) hex string with {}", diff --git a/crates/primitives/src/bytecode.rs b/crates/primitives/src/bytecode.rs index 5701654f58..b7b03c425f 100644 --- a/crates/primitives/src/bytecode.rs +++ b/crates/primitives/src/bytecode.rs @@ -6,7 +6,7 @@ use bytes::Bytes; use core::fmt::Debug; /// A map of valid `jump` destinations. -#[derive(Clone, Eq, PartialEq, Default)] +#[derive(Clone, Default, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct JumpMap(pub Arc>); @@ -39,7 +39,7 @@ impl JumpMap { } /// State of the [`Bytecode`] analysis. -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum BytecodeState { /// No analysis has been performed. @@ -50,7 +50,7 @@ pub enum BytecodeState { Analysed { len: usize, jump_map: JumpMap }, } -#[derive(Clone, Eq, PartialEq)] +#[derive(Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Bytecode { #[cfg_attr(feature = "serde", serde(with = "crate::utilities::serde_hex_bytes"))] diff --git a/crates/primitives/src/db.rs b/crates/primitives/src/db.rs index f376bd6f1e..62d66db451 100644 --- a/crates/primitives/src/db.rs +++ b/crates/primitives/src/db.rs @@ -58,6 +58,7 @@ pub trait DatabaseRef { } /// Wraps a [`DatabaseRef`] to provide a [`Database`] implementation. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct WrapDatabaseRef(pub T); impl Database for WrapDatabaseRef { @@ -87,6 +88,7 @@ impl Database for WrapDatabaseRef { /// Wraps a `dyn DatabaseRef` to provide a [`Database`] implementation. #[doc(hidden)] #[deprecated = "use `WrapDatabaseRef` instead"] +#[allow(missing_debug_implementations)] pub struct RefDBWrapper<'a, E> { pub db: &'a dyn DatabaseRef, } diff --git a/crates/primitives/src/env.rs b/crates/primitives/src/env.rs index 8d4e58a40a..c2a4af49c2 100644 --- a/crates/primitives/src/env.rs +++ b/crates/primitives/src/env.rs @@ -6,7 +6,7 @@ use crate::{ use bytes::Bytes; use core::cmp::{min, Ordering}; -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Env { pub cfg: CfgEnv, @@ -15,7 +15,7 @@ pub struct Env { } /// The block environment. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct BlockEnv { /// The number of ancestor blocks of this block (block height). @@ -59,7 +59,7 @@ pub struct BlockEnv { /// Incorporated as part of the Cancun upgrade via [EIP-4844]. /// /// [EIP-4844]: https://eips.ethereum.org/EIPS/eip-4844 -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct BlobExcessGasAndPrice { pub excess_blob_gas: u64, @@ -109,7 +109,7 @@ impl BlockEnv { } /// The transaction environment. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct TxEnv { /// The caller, author or signer of the transaction. @@ -175,7 +175,7 @@ impl TxEnv { } /// Transaction destination. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum TransactTo { /// Simple call to an address. @@ -217,7 +217,7 @@ impl TransactTo { } /// Create scheme. -#[derive(Clone, Copy, Eq, PartialEq, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum CreateScheme { /// Legacy create scheme of `CREATE`. @@ -230,7 +230,7 @@ pub enum CreateScheme { } /// EVM configuration. -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[non_exhaustive] pub struct CfgEnv { @@ -335,7 +335,7 @@ impl CfgEnv { } /// What bytecode analysis to perform. -#[derive(Clone, Default, Debug, Eq, PartialEq)] +#[derive(Clone, Default, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum AnalysisKind { /// Do not perform bytecode analysis. diff --git a/crates/primitives/src/kzg/env_settings.rs b/crates/primitives/src/kzg/env_settings.rs index ecf760c0a2..9b41f02908 100644 --- a/crates/primitives/src/kzg/env_settings.rs +++ b/crates/primitives/src/kzg/env_settings.rs @@ -3,11 +3,12 @@ use super::{ KzgSettings, }; use alloc::{boxed::Box, sync::Arc}; +use core::hash::{Hash, Hasher}; use once_cell::race::OnceBox; /// KZG Settings that allow us to specify a custom trusted setup. /// or use hardcoded default settings. -#[derive(Debug, Clone, Default, Eq, PartialEq)] +#[derive(Debug, Clone, Default, Eq)] pub enum EnvKzgSettings { /// Default mainnet trusted setup #[default] @@ -16,6 +17,27 @@ pub enum EnvKzgSettings { Custom(Arc), } +// Implement PartialEq and Hash manually because `c_kzg::KzgSettings` does not implement them +impl PartialEq for EnvKzgSettings { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Self::Default, Self::Default) => true, + (Self::Custom(a), Self::Custom(b)) => Arc::ptr_eq(a, b), + _ => false, + } + } +} + +impl Hash for EnvKzgSettings { + fn hash(&self, state: &mut H) { + core::mem::discriminant(self).hash(state); + match self { + Self::Default => {} + Self::Custom(settings) => Arc::as_ptr(settings).hash(state), + } + } +} + impl EnvKzgSettings { /// Return set KZG settings. /// diff --git a/crates/primitives/src/lib.rs b/crates/primitives/src/lib.rs index e41ef8b2e8..695ac0fad0 100644 --- a/crates/primitives/src/lib.rs +++ b/crates/primitives/src/lib.rs @@ -1,4 +1,7 @@ +#![warn(missing_debug_implementations)] +#![deny(unused_must_use, rust_2018_idioms)] #![cfg_attr(not(feature = "std"), no_std)] +#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] extern crate alloc; diff --git a/crates/primitives/src/log.rs b/crates/primitives/src/log.rs index 3c16ed035a..7cc19c5c2b 100644 --- a/crates/primitives/src/log.rs +++ b/crates/primitives/src/log.rs @@ -1,7 +1,7 @@ use crate::{bytes::Bytes, B160, B256}; use alloc::vec::Vec; -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Log { pub address: B160, diff --git a/crates/primitives/src/precompile.rs b/crates/primitives/src/precompile.rs index a02a86f010..d231f4c912 100644 --- a/crates/primitives/src/precompile.rs +++ b/crates/primitives/src/precompile.rs @@ -9,7 +9,7 @@ pub type PrecompileResult = Result<(u64, Vec), PrecompileError>; pub type StandardPrecompileFn = fn(&[u8], u64) -> PrecompileResult; pub type EnvPrecompileFn = fn(&[u8], u64, env: &Env) -> PrecompileResult; -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum PrecompileError { /// out of gas is the main error. Other are just here for completeness OutOfGas, diff --git a/crates/primitives/src/result.rs b/crates/primitives/src/result.rs index d7ed3f2133..e6d3f8f0a7 100644 --- a/crates/primitives/src/result.rs +++ b/crates/primitives/src/result.rs @@ -15,7 +15,7 @@ pub struct ResultAndState { pub state: State, } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum ExecutionResult { /// Returned successfully @@ -91,7 +91,7 @@ impl ExecutionResult { } } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum Output { #[cfg_attr(feature = "serde", serde(with = "crate::utilities::serde_hex_bytes"))] @@ -120,7 +120,7 @@ impl Output { } } -#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum EVMError { Transaction(InvalidTransaction), @@ -147,7 +147,7 @@ impl From for EVMError { } } -#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum InvalidTransaction { /// When using the EIP-1559 fee model introduced in the London upgrade, transactions specify two primary fee fields: @@ -215,7 +215,7 @@ impl From for EVMError { } /// Errors related to misconfiguration of the `BlockEnv` -#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum InvalidHeader { /// `prevrandao` is not set for Merge and above. @@ -225,7 +225,7 @@ pub enum InvalidHeader { } /// Reason a transaction successfully completed. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum Eval { Stop, @@ -235,7 +235,7 @@ pub enum Eval { /// Indicates that the EVM has experienced an exceptional halt. This causes execution to /// immediately end with all gas being consumed. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum Halt { OutOfGas(OutOfGasError), @@ -264,7 +264,7 @@ pub enum Halt { CallTooDeep, } -#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum OutOfGasError { // Basic OOG error diff --git a/crates/primitives/src/specification.rs b/crates/primitives/src/specification.rs index 60d753981d..4f028176c2 100644 --- a/crates/primitives/src/specification.rs +++ b/crates/primitives/src/specification.rs @@ -6,7 +6,7 @@ pub use SpecId::*; /// /// Information was obtained from: #[repr(u8)] -#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, enumn::N)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, enumn::N)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum SpecId { FRONTIER = 0, // Frontier 0 @@ -77,6 +77,7 @@ pub trait Spec: Sized { macro_rules! spec { ($spec_id:ident, $spec_name:ident) => { + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct $spec_name; impl Spec for $spec_name { diff --git a/crates/primitives/src/state.rs b/crates/primitives/src/state.rs index c562cfb5a0..5cf61692e4 100644 --- a/crates/primitives/src/state.rs +++ b/crates/primitives/src/state.rs @@ -1,8 +1,9 @@ use crate::{Bytecode, B160, B256, KECCAK_EMPTY, U256}; use bitflags::bitflags; +use core::hash::{Hash, Hasher}; use hashbrown::HashMap; -#[derive(Debug, Clone, Eq, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq, Eq, Default)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Account { /// Balance of the account. @@ -125,7 +126,7 @@ impl From for Account { } } -#[derive(Debug, Clone, Default, Eq, PartialEq)] +#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct StorageSlot { pub previous_or_original_value: U256, @@ -196,6 +197,14 @@ impl PartialEq for AccountInfo { } } +impl Hash for AccountInfo { + fn hash(&self, state: &mut H) { + self.balance.hash(state); + self.nonce.hash(state); + self.code_hash.hash(state); + } +} + impl AccountInfo { pub fn new(balance: U256, nonce: u64, code_hash: B256, code: Bytecode) -> Self { Self { diff --git a/crates/revm/src/db/ethersdb.rs b/crates/revm/src/db/ethersdb.rs index 69bbc6b5b8..27e7e52f1a 100644 --- a/crates/revm/src/db/ethersdb.rs +++ b/crates/revm/src/db/ethersdb.rs @@ -5,6 +5,7 @@ use ethers_providers::Middleware; use std::sync::Arc; use tokio::runtime::{Handle, Runtime}; +#[derive(Debug)] pub struct EthersDB { client: Arc, runtime: Option, diff --git a/crates/revm/src/db/in_memory_db.rs b/crates/revm/src/db/in_memory_db.rs index 4909b0bab2..645dac760f 100644 --- a/crates/revm/src/db/in_memory_db.rs +++ b/crates/revm/src/db/in_memory_db.rs @@ -328,7 +328,7 @@ impl From for DbAccount { } } -#[derive(Debug, Clone, Default, Eq, PartialEq)] +#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)] pub enum AccountState { /// Before Spurious Dragon hardfork there was a difference between empty and not existing. /// And we are flagging it here. diff --git a/crates/revm/src/db/states/account_status.rs b/crates/revm/src/db/states/account_status.rs index 25d8d2c396..7f9be37973 100644 --- a/crates/revm/src/db/states/account_status.rs +++ b/crates/revm/src/db/states/account_status.rs @@ -1,7 +1,7 @@ /// After account get loaded from database it can be in a lot of different states /// while we execute multiple transaction and even blocks over account that is in memory. /// This structure models all possible states that account can be in. -#[derive(Clone, Copy, Default, Debug, Eq, PartialEq)] +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Hash)] pub enum AccountStatus { #[default] LoadedNotExisting, diff --git a/crates/revm/src/db/states/bundle_state.rs b/crates/revm/src/db/states/bundle_state.rs index f2965a51a0..a4cad8756e 100644 --- a/crates/revm/src/db/states/bundle_state.rs +++ b/crates/revm/src/db/states/bundle_state.rs @@ -30,6 +30,7 @@ pub struct BundleBuilder { } /// Option for [`BundleState`] when converting it to the plain state. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum OriginalValuesKnown { /// Check changed with original values that [BundleState] has /// If we dont expect parent blocks to be committed or unwinded from database diff --git a/crates/revm/src/db/states/cache.rs b/crates/revm/src/db/states/cache.rs index 9dc8d98642..18c9d85b58 100644 --- a/crates/revm/src/db/states/cache.rs +++ b/crates/revm/src/db/states/cache.rs @@ -10,7 +10,7 @@ use revm_interpreter::primitives::{AccountInfo, Bytecode, HashMap, State as EVMS /// It loads all accounts from database and applies revm output to it. /// /// It generates transitions that is used to build BundleState. -#[derive(Debug, Clone)] +#[derive(Clone, Debug, PartialEq, Eq)] pub struct CacheState { /// Block state account with account state pub accounts: HashMap, diff --git a/crates/revm/src/db/states/cache_account.rs b/crates/revm/src/db/states/cache_account.rs index 29d7b81a2a..374360432d 100644 --- a/crates/revm/src/db/states/cache_account.rs +++ b/crates/revm/src/db/states/cache_account.rs @@ -7,7 +7,7 @@ use revm_precompile::HashMap; /// Cache account contains plain state that gets updated /// at every transaction when evm output is applied to CacheState. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub struct CacheAccount { pub account: Option, pub status: AccountStatus, diff --git a/crates/revm/src/db/states/plain_account.rs b/crates/revm/src/db/states/plain_account.rs index 716d6540b8..f6cb76618c 100644 --- a/crates/revm/src/db/states/plain_account.rs +++ b/crates/revm/src/db/states/plain_account.rs @@ -1,7 +1,7 @@ use revm_interpreter::primitives::{AccountInfo, HashMap, StorageSlot, U256}; -/// TODO rename this to BundleAccount. As for the block level we have original state. -#[derive(Clone, Debug, Default)] +// TODO rename this to BundleAccount. As for the block level we have original state. +#[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct PlainAccount { pub info: AccountInfo, pub storage: PlainStorage, diff --git a/crates/revm/src/db/states/reverts.rs b/crates/revm/src/db/states/reverts.rs index c4b1346708..ec8646dac1 100644 --- a/crates/revm/src/db/states/reverts.rs +++ b/crates/revm/src/db/states/reverts.rs @@ -181,7 +181,7 @@ impl AccountRevert { /// Depending on previous state of account info this /// will tell us what to do on revert. -#[derive(Clone, Default, Debug, PartialEq, Eq)] +#[derive(Clone, Default, Debug, PartialEq, Eq, Hash)] pub enum AccountInfoRevert { #[default] /// Nothing changed @@ -199,7 +199,7 @@ pub enum AccountInfoRevert { /// /// Note: It is completely different state if Storage is Zero or Some or if Storage was /// Destroyed. Because if it is destroyed, previous values can be found in database or it can be zero. -#[derive(Clone, Debug, Copy, PartialEq, Eq)] +#[derive(Clone, Debug, Copy, PartialEq, Eq, Hash)] pub enum RevertToSlot { Some(U256), Destroyed, diff --git a/crates/revm/src/db/states/state.rs b/crates/revm/src/db/states/state.rs index 140145c7c5..c651f7ebc0 100644 --- a/crates/revm/src/db/states/state.rs +++ b/crates/revm/src/db/states/state.rs @@ -25,6 +25,7 @@ pub type StateDBBox<'a, E> = State>; /// /// State clear flag is set inside CacheState and by default it is enabled. /// If you want to disable it use `set_state_clear_flag` function. +#[derive(Debug)] pub struct State { /// Cached state contains both changed from evm execution and cached/loaded account/storages /// from database. This allows us to have only one layer of cache where we can fetch data. @@ -34,7 +35,7 @@ pub struct State { /// return not existing account and storage. /// /// Note: It is marked as Send so database can be shared between threads. - pub database: DB, //Box + Send + 'a>, + pub database: DB, /// Block state, it aggregates transactions transitions into one state. /// /// Build reverts and state that gets applied to the state. diff --git a/crates/revm/src/db/states/state_builder.rs b/crates/revm/src/db/states/state_builder.rs index 79cfdc20f3..07978a518b 100644 --- a/crates/revm/src/db/states/state_builder.rs +++ b/crates/revm/src/db/states/state_builder.rs @@ -7,6 +7,7 @@ use revm_interpreter::primitives::{ }; /// Allows building of State and initializing it with different options. +#[derive(Clone, Debug, PartialEq, Eq)] pub struct StateBuilder { /// Database that we use to fetch data from. database: DB, diff --git a/crates/revm/src/db/states/transition_account.rs b/crates/revm/src/db/states/transition_account.rs index fc9e4eed80..4c596bbadc 100644 --- a/crates/revm/src/db/states/transition_account.rs +++ b/crates/revm/src/db/states/transition_account.rs @@ -7,7 +7,7 @@ use revm_interpreter::primitives::{hash_map, AccountInfo, Bytecode, B256}; /// /// It is used when block state gets merged to bundle state to /// create needed Reverts. -#[derive(Clone, Debug, Eq, PartialEq, Default)] +#[derive(Clone, Debug, PartialEq, Eq, Default)] pub struct TransitionAccount { pub info: Option, pub status: AccountStatus, diff --git a/crates/revm/src/db/states/transition_state.rs b/crates/revm/src/db/states/transition_state.rs index f4d9829fcd..3f9f8703e9 100644 --- a/crates/revm/src/db/states/transition_state.rs +++ b/crates/revm/src/db/states/transition_state.rs @@ -2,7 +2,7 @@ use super::TransitionAccount; use alloc::vec::Vec; use revm_interpreter::primitives::{hash_map::Entry, HashMap, B160}; -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub struct TransitionState { /// Block state account with account state pub transitions: HashMap, diff --git a/crates/revm/src/evm.rs b/crates/revm/src/evm.rs index c047a8a342..df429dc033 100644 --- a/crates/revm/src/evm.rs +++ b/crates/revm/src/evm.rs @@ -38,7 +38,7 @@ use revm_precompile::Precompiles; /// assert!(evm.db.is_none()); /// ``` /// -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct EVM { pub env: Env, pub db: Option, diff --git a/crates/revm/src/evm_impl.rs b/crates/revm/src/evm_impl.rs index 6927cddbed..10364a8add 100644 --- a/crates/revm/src/evm_impl.rs +++ b/crates/revm/src/evm_impl.rs @@ -12,11 +12,13 @@ use crate::primitives::{ use crate::{db::Database, journaled_state::JournaledState, precompile, Inspector}; use alloc::boxed::Box; use alloc::vec::Vec; +use core::fmt; use core::{cmp::min, marker::PhantomData}; use revm_interpreter::gas::initial_tx_gas; use revm_interpreter::MAX_CODE_SIZE; use revm_precompile::{Precompile, Precompiles}; +#[derive(Debug)] pub struct EVMData<'a, DB: Database> { pub env: &'a mut Env, pub journaled_state: JournaledState, @@ -31,6 +33,17 @@ pub struct EVMImpl<'a, GSPEC: Spec, DB: Database, const INSPECT: bool> { _phantomdata: PhantomData, } +impl fmt::Debug for EVMImpl<'_, GSPEC, DB, INSPECT> +where + GSPEC: Spec, + DB: Database + fmt::Debug, + DB::Error: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("EVMImpl").field("data", &self.data).finish() + } +} + struct PreparedCreate { gas: Gas, created_address: B160, diff --git a/crates/revm/src/inspector/customprinter.rs b/crates/revm/src/inspector/customprinter.rs index ba69bdf249..57bbe3ae7c 100644 --- a/crates/revm/src/inspector/customprinter.rs +++ b/crates/revm/src/inspector/customprinter.rs @@ -1,10 +1,11 @@ //! Custom print inspector, it has step level information of execution. //! It is a great tool if some debugging is needed. -//! + use crate::interpreter::{opcode, CallInputs, CreateInputs, Gas, InstructionResult, Interpreter}; use crate::primitives::{hex, Bytes, B160, U256}; use crate::{inspectors::GasInspector, Database, EVMData, Inspector}; -#[derive(Clone, Default)] + +#[derive(Clone, Debug, Default)] pub struct CustomPrintTracer { gas_inspector: GasInspector, } diff --git a/crates/revm/src/inspector/noop.rs b/crates/revm/src/inspector/noop.rs index 12123b47f3..9e75ef1168 100644 --- a/crates/revm/src/inspector/noop.rs +++ b/crates/revm/src/inspector/noop.rs @@ -2,7 +2,7 @@ use crate::{Database, Inspector}; -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct NoOpInspector; impl Inspector for NoOpInspector {} diff --git a/crates/revm/src/inspector/tracer_eip3155.rs b/crates/revm/src/inspector/tracer_eip3155.rs index cd8ff0f3b8..a53bb596f9 100644 --- a/crates/revm/src/inspector/tracer_eip3155.rs +++ b/crates/revm/src/inspector/tracer_eip3155.rs @@ -9,6 +9,7 @@ use revm_interpreter::{opcode, Interpreter, Memory, Stack}; use serde_json::json; use std::io::Write; +#[allow(missing_debug_implementations)] pub struct TracerEip3155 { output: Box, gas_inspector: GasInspector, diff --git a/crates/revm/src/journaled_state.rs b/crates/revm/src/journaled_state.rs index c866f38ac1..8fc8bc9d3d 100644 --- a/crates/revm/src/journaled_state.rs +++ b/crates/revm/src/journaled_state.rs @@ -7,7 +7,7 @@ use alloc::vec::Vec; use core::mem; use revm_interpreter::primitives::SpecId; -#[derive(Debug, Clone, Eq, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct JournaledState { /// Current state. @@ -29,7 +29,7 @@ pub struct JournaledState { pub num_of_precompiles: usize, } -#[derive(Debug, Clone, Eq, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum JournalEntry { /// Used to mark account that is hot inside EVM in regards to EIP-2929 AccessList. @@ -88,6 +88,7 @@ pub enum JournalEntry { } /// SubRoutine checkpoint that will help us to go back from this +#[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct JournalCheckpoint { log_i: usize, journal_i: usize, diff --git a/crates/revm/src/lib.rs b/crates/revm/src/lib.rs index 6b93b8705b..c0c9060026 100644 --- a/crates/revm/src/lib.rs +++ b/crates/revm/src/lib.rs @@ -1,5 +1,7 @@ +#![warn(missing_debug_implementations)] +#![deny(unused_must_use, rust_2018_idioms)] #![cfg_attr(not(feature = "std"), no_std)] -#![warn(unreachable_pub)] +#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #[macro_use] extern crate alloc; From c1413d5eb38e85bfa029d73e1cd4dad300c2be3a Mon Sep 17 00:00:00 2001 From: DaniPopes <57450786+DaniPopes@users.noreply.github.com> Date: Mon, 25 Sep 2023 15:33:27 +0200 Subject: [PATCH 2/7] chore: add unreachable_pub lint --- crates/interpreter/src/interpreter.rs | 4 ++-- crates/interpreter/src/interpreter/stack.rs | 2 +- crates/interpreter/src/lib.rs | 2 +- crates/primitives/src/bits.rs | 2 +- crates/primitives/src/lib.rs | 2 +- crates/revm/src/lib.rs | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/interpreter/src/interpreter.rs b/crates/interpreter/src/interpreter.rs index d13bd1998a..e1a6f3ed86 100644 --- a/crates/interpreter/src/interpreter.rs +++ b/crates/interpreter/src/interpreter.rs @@ -1,6 +1,6 @@ pub mod analysis; mod contract; -pub mod memory; +pub(crate) mod memory; mod stack; use crate::primitives::{Bytes, Spec}; @@ -9,7 +9,7 @@ use crate::{alloc::boxed::Box, opcode::eval, Gas, Host, InstructionResult}; pub use analysis::BytecodeLocked; pub use contract::Contract; pub use memory::Memory; -pub use stack::{Stack, STACK_LIMIT}; +pub use stack::Stack; pub const CALL_STACK_LIMIT: u64 = 1024; diff --git a/crates/interpreter/src/interpreter/stack.rs b/crates/interpreter/src/interpreter/stack.rs index 7abaa6c41c..a8c052c475 100644 --- a/crates/interpreter/src/interpreter/stack.rs +++ b/crates/interpreter/src/interpreter/stack.rs @@ -6,7 +6,7 @@ use alloc::vec::Vec; use core::fmt; /// The EVM stack limit, in number of items. -pub const STACK_LIMIT: usize = 1024; +const STACK_LIMIT: usize = 1024; /// EVM stack. #[derive(Clone, Debug, PartialEq, Eq, Hash)] diff --git a/crates/interpreter/src/lib.rs b/crates/interpreter/src/lib.rs index aab11ab93d..41ef33fc10 100644 --- a/crates/interpreter/src/lib.rs +++ b/crates/interpreter/src/lib.rs @@ -1,4 +1,4 @@ -#![warn(missing_debug_implementations)] +#![warn(missing_debug_implementations, unreachable_pub)] #![deny(unused_must_use, rust_2018_idioms)] #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] diff --git a/crates/primitives/src/bits.rs b/crates/primitives/src/bits.rs index 5503f424f6..153f6fc285 100644 --- a/crates/primitives/src/bits.rs +++ b/crates/primitives/src/bits.rs @@ -130,8 +130,8 @@ impl<'de> serde::Deserialize<'de> for B160 { // code optained from: https://docs.rs/impl-serde/0.4.0/impl_serde/ #[cfg(feature = "serde")] +#[allow(unreachable_pub)] mod serialize { - use alloc::string::String; use core::{fmt, result::Result}; use serde::{de, Deserializer, Serializer}; diff --git a/crates/primitives/src/lib.rs b/crates/primitives/src/lib.rs index 695ac0fad0..bc2a22bd05 100644 --- a/crates/primitives/src/lib.rs +++ b/crates/primitives/src/lib.rs @@ -1,4 +1,4 @@ -#![warn(missing_debug_implementations)] +#![warn(missing_debug_implementations, unreachable_pub)] #![deny(unused_must_use, rust_2018_idioms)] #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] diff --git a/crates/revm/src/lib.rs b/crates/revm/src/lib.rs index c0c9060026..680521a8c1 100644 --- a/crates/revm/src/lib.rs +++ b/crates/revm/src/lib.rs @@ -1,4 +1,4 @@ -#![warn(missing_debug_implementations)] +#![warn(missing_debug_implementations, unreachable_pub)] #![deny(unused_must_use, rust_2018_idioms)] #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] From 3a452f37b8a6f458c3fae486ff1e4cd9f1179c75 Mon Sep 17 00:00:00 2001 From: DaniPopes <57450786+DaniPopes@users.noreply.github.com> Date: Fri, 29 Sep 2023 20:38:51 +0200 Subject: [PATCH 3/7] Update crates/revm/src/evm_impl.rs Co-authored-by: Matthias Seitz --- crates/revm/src/evm_impl.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/revm/src/evm_impl.rs b/crates/revm/src/evm_impl.rs index 9f7d8759ce..45be0016d7 100644 --- a/crates/revm/src/evm_impl.rs +++ b/crates/revm/src/evm_impl.rs @@ -48,7 +48,7 @@ where DB::Error: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("EVMImpl").field("data", &self.data).finish() + f.debug_struct("EVMImpl").field("data", &self.data).finish_non_exhaustive() } } From 9aa88664f9c3196208e709f3f4b0ae054715a3f4 Mon Sep 17 00:00:00 2001 From: DaniPopes <57450786+DaniPopes@users.noreply.github.com> Date: Fri, 29 Sep 2023 20:56:49 +0200 Subject: [PATCH 4/7] fmt --- crates/revm/src/evm_impl.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/revm/src/evm_impl.rs b/crates/revm/src/evm_impl.rs index 45be0016d7..836e404dbb 100644 --- a/crates/revm/src/evm_impl.rs +++ b/crates/revm/src/evm_impl.rs @@ -48,7 +48,9 @@ where DB::Error: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("EVMImpl").field("data", &self.data).finish_non_exhaustive() + f.debug_struct("EVMImpl") + .field("data", &self.data) + .finish_non_exhaustive() } } From 9b63927e912cf495cfefe8ca44a4f50a3422995c Mon Sep 17 00:00:00 2001 From: rakita Date: Wed, 11 Oct 2023 13:13:18 +0200 Subject: [PATCH 5/7] cleanup --- bins/revme/src/cli_env.rs | 6 +- bins/revme/src/statetest/models/spec.rs | 2 +- crates/interpreter/src/inner_models.rs | 2 +- crates/interpreter/src/interpreter.rs | 3 +- crates/interpreter/src/lib.rs | 4 +- crates/precompile/src/lib.rs | 9 +- crates/primitives/src/bits.rs | 378 --------------------- crates/primitives/src/env.rs | 2 +- crates/revm/src/db/ethersdb.rs | 6 +- crates/revm/src/inspector.rs | 6 +- crates/revm/src/inspector/customprinter.rs | 6 +- crates/revm/src/inspector/eip3155.rs | 6 +- crates/revm/src/inspector/gas.rs | 4 +- 13 files changed, 33 insertions(+), 401 deletions(-) delete mode 100644 crates/primitives/src/bits.rs diff --git a/bins/revme/src/cli_env.rs b/bins/revme/src/cli_env.rs index 9ab82dc3d3..45cb7261c1 100644 --- a/bins/revme/src/cli_env.rs +++ b/bins/revme/src/cli_env.rs @@ -1,7 +1,7 @@ use revm::primitives::{Address, Bytes, Env, TransactTo, U256}; use structopt::StructOpt; -#[derive(StructOpt, Clone, Debug)] +#[derive(StructOpt, Clone, Debug, PartialEq, Eq)] pub struct CliEnv { #[structopt(flatten)] block: CliEnvBlock, @@ -51,7 +51,7 @@ impl From for Env { } } -#[derive(StructOpt, Clone, Debug)] +#[derive(StructOpt, Clone, Debug, PartialEq, Eq)] pub struct CliEnvBlock { #[structopt(long = "env.block.gas_limit")] pub block_gas_limit: Option, @@ -71,7 +71,7 @@ pub struct CliEnvBlock { pub basefee: Option, } -#[derive(StructOpt, Clone, Debug)] +#[derive(StructOpt, Clone, Debug, PartialEq, Eq)] pub struct CliEnvTx { /// Caller or Author or tx signer #[structopt(long = "env.tx.caller")] diff --git a/bins/revme/src/statetest/models/spec.rs b/bins/revme/src/statetest/models/spec.rs index 5a5561c27f..53c134e479 100644 --- a/bins/revme/src/statetest/models/spec.rs +++ b/bins/revme/src/statetest/models/spec.rs @@ -1,7 +1,7 @@ use revm::primitives::SpecId; use serde::Deserialize; -#[derive(Debug, PartialEq, Eq, PartialOrd, Hash, Ord, Deserialize)] +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Hash)] pub enum SpecName { Frontier, FrontierToHomesteadAt5, diff --git a/crates/interpreter/src/inner_models.rs b/crates/interpreter/src/inner_models.rs index df36478938..97758ba79a 100644 --- a/crates/interpreter/src/inner_models.rs +++ b/crates/interpreter/src/inner_models.rs @@ -90,7 +90,7 @@ pub struct Transfer { } /// Result of a call that resulted in a self destruct. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Default, Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct SelfDestructResult { pub had_value: bool, diff --git a/crates/interpreter/src/interpreter.rs b/crates/interpreter/src/interpreter.rs index 119540f07b..57495391ce 100644 --- a/crates/interpreter/src/interpreter.rs +++ b/crates/interpreter/src/interpreter.rs @@ -6,12 +6,11 @@ mod stack; pub use analysis::BytecodeLocked; pub use contract::Contract; pub use shared_memory::{next_multiple_of_32, SharedMemory}; -pub use stack::Stack; +pub use stack::{Stack, STACK_LIMIT}; use crate::primitives::{Bytes, Spec}; use crate::{alloc::boxed::Box, opcode::eval, Gas, Host, InstructionResult}; - /// EIP-170: Contract code size limit /// /// By default this limit is 0x6000 (~25kb) diff --git a/crates/interpreter/src/lib.rs b/crates/interpreter/src/lib.rs index 925bde577c..cd77099648 100644 --- a/crates/interpreter/src/lib.rs +++ b/crates/interpreter/src/lib.rs @@ -31,8 +31,8 @@ pub use inner_models::*; pub use instruction_result::*; pub use instructions::{opcode, Instruction, OpCode, OPCODE_JUMPMAP}; pub use interpreter::{ - analysis, BytecodeLocked, Contract, Interpreter, SharedMemory, Stack, MAX_CODE_SIZE, - MAX_INITCODE_SIZE, + analysis, next_multiple_of_32, BytecodeLocked, Contract, Interpreter, SharedMemory, Stack, + MAX_CODE_SIZE, MAX_INITCODE_SIZE, STACK_LIMIT, }; #[doc(hidden)] pub use revm_primitives as primitives; diff --git a/crates/precompile/src/lib.rs b/crates/precompile/src/lib.rs index 89b1266bc9..e016414c2b 100644 --- a/crates/precompile/src/lib.rs +++ b/crates/precompile/src/lib.rs @@ -35,14 +35,14 @@ pub fn calc_linear_cost_u32(len: usize, base: u64, word: u64) -> u64 { (len as u64 + 32 - 1) / 32 * word + base } -#[derive(Debug)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct PrecompileOutput { pub cost: u64, pub output: Vec, pub logs: Vec, } -#[derive(Debug, Default)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct Log { pub address: Address, pub topics: Vec, @@ -58,8 +58,7 @@ impl PrecompileOutput { } } } - -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub struct Precompiles { pub fun: HashMap, } @@ -94,7 +93,7 @@ impl From for (Address, Precompile) { } } -#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Ord, PartialOrd)] pub enum SpecId { HOMESTEAD, BYZANTIUM, diff --git a/crates/primitives/src/bits.rs b/crates/primitives/src/bits.rs deleted file mode 100644 index 153f6fc285..0000000000 --- a/crates/primitives/src/bits.rs +++ /dev/null @@ -1,378 +0,0 @@ -#![allow(clippy::non_canonical_clone_impl)] - -use derive_more::{AsRef, Deref}; -use fixed_hash::{construct_fixed_hash, impl_fixed_hash_conversions}; - -#[cfg(any(test, feature = "arbitrary"))] -use arbitrary::Arbitrary; -#[cfg(any(test, feature = "arbitrary"))] -use proptest_derive::Arbitrary as PropTestArbitrary; - -construct_fixed_hash! { - /// revm 256 bits type. - #[cfg_attr(any(test, feature = "arbitrary"), derive(Arbitrary, PropTestArbitrary))] - #[derive(AsRef,Deref)] - pub struct B256(32); -} - -construct_fixed_hash! { - /// revm 160 bits type. - #[cfg_attr(any(test, feature = "arbitrary"), derive(Arbitrary, PropTestArbitrary))] - #[derive(AsRef,Deref)] - pub struct B160(20); -} - -impl From for B160 { - fn from(fr: u64) -> Self { - let x_bytes = fr.to_be_bytes(); - B160([ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, x_bytes[0], x_bytes[1], x_bytes[2], x_bytes[3], - x_bytes[4], x_bytes[5], x_bytes[6], x_bytes[7], - ]) - } -} - -impl From for B160 { - fn from(fr: primitive_types::H160) -> Self { - B160(fr.0) - } -} - -impl From for B256 { - fn from(fr: primitive_types::H256) -> Self { - B256(fr.0) - } -} - -impl From for primitive_types::H160 { - fn from(fr: B160) -> Self { - primitive_types::H160(fr.0) - } -} - -impl From for primitive_types::H256 { - fn from(fr: B256) -> Self { - primitive_types::H256(fr.0) - } -} - -impl From for B256 { - fn from(fr: primitive_types::U256) -> Self { - let mut ret = B256::zero(); - fr.to_big_endian(ret.as_bytes_mut()); - ret - } -} - -impl From for primitive_types::U256 { - fn from(fr: B256) -> Self { - primitive_types::U256::from(fr.as_ref() as &[u8]) - } -} - -impl From for B256 { - fn from(fr: ruint::aliases::U256) -> Self { - B256(fr.to_be_bytes()) - } -} - -impl From for ruint::aliases::U256 { - fn from(fr: B256) -> Self { - ruint::aliases::U256::from_be_bytes(fr.0) - } -} - -impl_fixed_hash_conversions!(B256, B160); - -#[cfg(feature = "serde")] -impl serde::Serialize for B256 { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - let mut slice = [0u8; 2 + 2 * 32]; - serialize::serialize_raw(&mut slice, &self.0, serializer) - } -} -#[cfg(feature = "serde")] -impl<'de> serde::Deserialize<'de> for B256 { - fn deserialize(deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { - let mut bytes = [0u8; 32]; - serialize::deserialize_check_len(deserializer, serialize::ExpectedLen::Exact(&mut bytes))?; - Ok(B256(bytes)) - } -} -#[cfg(feature = "serde")] -impl serde::Serialize for B160 { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - let mut slice = [0u8; 2 + 2 * 20]; - serialize::serialize_raw(&mut slice, &self.0, serializer) - } -} - -#[cfg(feature = "serde")] -impl<'de> serde::Deserialize<'de> for B160 { - fn deserialize(deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { - let mut bytes = [0u8; 20]; - serialize::deserialize_check_len(deserializer, serialize::ExpectedLen::Exact(&mut bytes))?; - Ok(B160(bytes)) - } -} - -// code optained from: https://docs.rs/impl-serde/0.4.0/impl_serde/ -#[cfg(feature = "serde")] -#[allow(unreachable_pub)] -mod serialize { - use alloc::string::String; - use core::{fmt, result::Result}; - use serde::{de, Deserializer, Serializer}; - - static CHARS: &[u8] = b"0123456789abcdef"; - - fn to_hex_raw<'a>(v: &'a mut [u8], bytes: &[u8], skip_leading_zero: bool) -> &'a str { - assert!(v.len() > 1 + bytes.len() * 2); - - v[0] = b'0'; - v[1] = b'x'; - - let mut idx = 2; - let first_nibble = bytes[0] >> 4; - if first_nibble != 0 || !skip_leading_zero { - v[idx] = CHARS[first_nibble as usize]; - idx += 1; - } - v[idx] = CHARS[(bytes[0] & 0xf) as usize]; - idx += 1; - - for &byte in bytes.iter().skip(1) { - v[idx] = CHARS[(byte >> 4) as usize]; - v[idx + 1] = CHARS[(byte & 0xf) as usize]; - idx += 2; - } - - // SAFETY: all characters come either from CHARS or "0x", therefore valid UTF8 - unsafe { core::str::from_utf8_unchecked(&v[0..idx]) } - } - - /// Decoding bytes from hex string error. - #[derive(Debug, PartialEq, Eq, Hash)] - pub enum FromHexError { - /// Invalid (non-hex) character encountered. - InvalidHex { - /// The unexpected character. - character: char, - /// Index of that occurrence. - index: usize, - }, - } - - #[cfg(feature = "std")] - impl std::error::Error for FromHexError {} - - impl fmt::Display for FromHexError { - fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - Self::InvalidHex { character, index } => { - write!(fmt, "invalid hex character: {character}, at {index}") - } - } - } - } - - /// Decode given 0x-prefix-stripped hex string into provided slice. - /// Used internally by `from_hex` and `deserialize_check_len`. - /// - /// The method will panic if `bytes` have incorrect length (make sure to allocate enough beforehand). - fn from_hex_raw(v: &str, bytes: &mut [u8], stripped: bool) -> Result { - let bytes_len = v.len(); - let mut modulus = bytes_len % 2; - let mut buf = 0; - let mut pos = 0; - for (index, byte) in v.bytes().enumerate() { - buf <<= 4; - - match byte { - b'A'..=b'F' => buf |= byte - b'A' + 10, - b'a'..=b'f' => buf |= byte - b'a' + 10, - b'0'..=b'9' => buf |= byte - b'0', - b' ' | b'\r' | b'\n' | b'\t' => { - buf >>= 4; - continue; - } - b => { - let character = char::from(b); - return Err(FromHexError::InvalidHex { - character, - index: index + if stripped { 2 } else { 0 }, - }); - } - } - - modulus += 1; - if modulus == 2 { - modulus = 0; - bytes[pos] = buf; - pos += 1; - } - } - - Ok(pos) - } - - /// Serializes a slice of bytes. - pub fn serialize_raw( - slice: &mut [u8], - bytes: &[u8], - serializer: S, - ) -> Result - where - S: Serializer, - { - if bytes.is_empty() { - serializer.serialize_str("0x") - } else { - serializer.serialize_str(to_hex_raw(slice, bytes, false)) - } - } - - /// Expected length of bytes vector. - #[derive(Debug, PartialEq, Eq, Hash)] - pub enum ExpectedLen<'a> { - /// Exact length in bytes. - Exact(&'a mut [u8]), - /// A bytes length between (min; slice.len()]. - #[allow(dead_code)] - Between(usize, &'a mut [u8]), - } - - impl<'a> fmt::Display for ExpectedLen<'a> { - fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - ExpectedLen::Exact(ref v) => write!(fmt, "length of {}", v.len() * 2), - ExpectedLen::Between(min, ref v) => { - write!(fmt, "length between ({}; {}]", min * 2, v.len() * 2) - } - } - } - } - - /// Deserialize into vector of bytes with additional size check. - /// Returns number of bytes written. - pub fn deserialize_check_len<'a, 'de, D>( - deserializer: D, - len: ExpectedLen<'a>, - ) -> Result - where - D: Deserializer<'de>, - { - struct Visitor<'a> { - len: ExpectedLen<'a>, - } - - impl<'a, 'b> de::Visitor<'b> for Visitor<'a> { - type Value = usize; - - fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - formatter, - "a (both 0x-prefixed or not) hex string with {}", - self.len - ) - } - - fn visit_str(self, v: &str) -> Result { - let (v, stripped) = v.strip_prefix("0x").map_or((v, false), |v| (v, true)); - - let len = v.len(); - let is_len_valid = match self.len { - ExpectedLen::Exact(ref slice) => len == 2 * slice.len(), - ExpectedLen::Between(min, ref slice) => len <= 2 * slice.len() && len > 2 * min, - }; - - if !is_len_valid { - return Err(E::invalid_length(v.len(), &self)); - } - - let bytes = match self.len { - ExpectedLen::Exact(slice) => slice, - ExpectedLen::Between(_, slice) => slice, - }; - - from_hex_raw(v, bytes, stripped).map_err(E::custom) - } - - fn visit_string(self, v: String) -> Result { - self.visit_str(&v) - } - } - - deserializer.deserialize_str(Visitor { len }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn arbitrary() { - proptest::proptest!(|(_v1: B160, _v2: B256)| {}); - } - - #[test] - fn should_convert_from_primitive_types_h160() { - let h160 = primitive_types::H160::random(); - let b160: B160 = h160.into(); - let new_h160: primitive_types::H160 = b160.into(); - assert_eq!(h160, new_h160) - } - - #[test] - fn should_convert_to_primitive_types_h160() { - let b160 = B160::random(); - let h160: primitive_types::H160 = b160.into(); - let new_b160: B160 = h160.into(); - assert_eq!(b160, new_b160) - } - - #[test] - fn should_convert_from_primitive_types_h256() { - let h256 = primitive_types::H256::random(); - let b256: B256 = h256.into(); - let new_h256: primitive_types::H256 = b256.into(); - assert_eq!(h256, new_h256) - } - - #[test] - fn should_convert_to_primitive_types_h256() { - let b256 = B256::random(); - let h256: primitive_types::H256 = b256.into(); - let new_b256: B256 = h256.into(); - assert_eq!(b256, new_b256) - } - - #[test] - fn should_convert_to_primitive_types_h256_u256() { - let b256 = B256::random(); - let u256: primitive_types::U256 = b256.into(); - let new_b256: B256 = u256.into(); - assert_eq!(b256, new_b256) - } - - #[test] - fn should_convert_to_ruint_u256() { - let b256 = B256::random(); - let u256: ruint::aliases::U256 = b256.into(); - let new_b256: B256 = u256.into(); - assert_eq!(b256, new_b256) - } -} diff --git a/crates/primitives/src/env.rs b/crates/primitives/src/env.rs index c8c963cfce..e93c571630 100644 --- a/crates/primitives/src/env.rs +++ b/crates/primitives/src/env.rs @@ -664,7 +664,7 @@ impl TransactTo { } /// Create scheme. -#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)] +#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum CreateScheme { /// Legacy create scheme of `CREATE`. diff --git a/crates/revm/src/db/ethersdb.rs b/crates/revm/src/db/ethersdb.rs index af793c1a58..48e4b0836b 100644 --- a/crates/revm/src/db/ethersdb.rs +++ b/crates/revm/src/db/ethersdb.rs @@ -154,7 +154,7 @@ mod tests { .unwrap(); let client = Arc::new(client); - let mut ethersdb = EthersDB::new( + let ethersdb = EthersDB::new( Arc::clone(&client), // public infura mainnet Some(BlockId::from(16148323)), ) @@ -180,7 +180,7 @@ mod tests { .unwrap(); let client = Arc::new(client); - let mut ethersdb = EthersDB::new( + let ethersdb = EthersDB::new( Arc::clone(&client), // public infura mainnet Some(BlockId::from(16148323)), ) @@ -211,7 +211,7 @@ mod tests { .unwrap(); let client = Arc::new(client); - let mut ethersdb = EthersDB::new( + let ethersdb = EthersDB::new( Arc::clone(&client), // public infura mainnet None, ) diff --git a/crates/revm/src/inspector.rs b/crates/revm/src/inspector.rs index a033d28397..7868da2e5a 100644 --- a/crates/revm/src/inspector.rs +++ b/crates/revm/src/inspector.rs @@ -47,7 +47,11 @@ pub trait Inspector { /// /// To get the current opcode, use `interp.current_opcode()`. #[inline] - fn step(&mut self, interp: &mut Interpreter<'_>, data: &mut EVMData<'_, DB>) -> InstructionResult { + fn step( + &mut self, + interp: &mut Interpreter<'_>, + data: &mut EVMData<'_, DB>, + ) -> InstructionResult { let _ = interp; let _ = data; InstructionResult::Continue diff --git a/crates/revm/src/inspector/customprinter.rs b/crates/revm/src/inspector/customprinter.rs index f16c364e9e..f47d80f1d8 100644 --- a/crates/revm/src/inspector/customprinter.rs +++ b/crates/revm/src/inspector/customprinter.rs @@ -25,7 +25,11 @@ impl Inspector for CustomPrintTracer { // get opcode by calling `interp.contract.opcode(interp.program_counter())`. // all other information can be obtained from interp. - fn step(&mut self, interp: &mut Interpreter<'_>, data: &mut EVMData<'_, DB>) -> InstructionResult { + fn step( + &mut self, + interp: &mut Interpreter<'_>, + data: &mut EVMData<'_, DB>, + ) -> InstructionResult { let opcode = interp.current_opcode(); let opcode_str = opcode::OPCODE_JUMPMAP[opcode as usize]; diff --git a/crates/revm/src/inspector/eip3155.rs b/crates/revm/src/inspector/eip3155.rs index 34570fbff1..5d2e672a19 100644 --- a/crates/revm/src/inspector/eip3155.rs +++ b/crates/revm/src/inspector/eip3155.rs @@ -58,7 +58,11 @@ impl Inspector for TracerEip3155 { // get opcode by calling `interp.contract.opcode(interp.program_counter())`. // all other information can be obtained from interp. - fn step(&mut self, interp: &mut Interpreter<'_>, data: &mut EVMData<'_, DB>) -> InstructionResult { + fn step( + &mut self, + interp: &mut Interpreter<'_>, + data: &mut EVMData<'_, DB>, + ) -> InstructionResult { self.gas_inspector.step(interp, data); self.stack = interp.stack.clone(); self.pc = interp.program_counter(); diff --git a/crates/revm/src/inspector/gas.rs b/crates/revm/src/inspector/gas.rs index 1620cab416..ef6e345b2c 100644 --- a/crates/revm/src/inspector/gas.rs +++ b/crates/revm/src/inspector/gas.rs @@ -26,7 +26,7 @@ impl Inspector for GasInspector { #[cfg(not(feature = "no_gas_measuring"))] fn initialize_interp( &mut self, - interp: &mut crate::interpreter::Interpreter, + interp: &mut crate::interpreter::Interpreter<'_>, _data: &mut EVMData<'_, DB>, ) -> InstructionResult { self.gas_remaining = interp.gas.limit(); @@ -36,7 +36,7 @@ impl Inspector for GasInspector { #[cfg(not(feature = "no_gas_measuring"))] fn step_end( &mut self, - interp: &mut crate::interpreter::Interpreter, + interp: &mut crate::interpreter::Interpreter<'_>, _data: &mut EVMData<'_, DB>, _eval: InstructionResult, ) -> InstructionResult { From 51f8a95063d86f765f51673a8459537dcf527e21 Mon Sep 17 00:00:00 2001 From: rakita Date: Wed, 11 Oct 2023 16:51:55 +0200 Subject: [PATCH 6/7] rm memory --- crates/interpreter/src/interpreter/memory.rs | 233 ------------------ .../src/interpreter/shared_memory.rs | 2 + 2 files changed, 2 insertions(+), 233 deletions(-) delete mode 100644 crates/interpreter/src/interpreter/memory.rs diff --git a/crates/interpreter/src/interpreter/memory.rs b/crates/interpreter/src/interpreter/memory.rs deleted file mode 100644 index 2273671656..0000000000 --- a/crates/interpreter/src/interpreter/memory.rs +++ /dev/null @@ -1,233 +0,0 @@ -use crate::{alloc::vec::Vec, primitives::U256}; -use core::{ - cmp::min, - fmt, - ops::{BitAnd, Not}, -}; - -/// A sequential memory. It uses Rust's `Vec` for internal -/// representation. -#[derive(Clone, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct Memory { - data: Vec, -} - -impl fmt::Debug for Memory { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Memory") - .field("data", &crate::primitives::hex::encode(&self.data)) - .finish() - } -} - -impl Default for Memory { - #[inline] - fn default() -> Self { - Self { - data: Vec::with_capacity(4 * 1024), // took it from evmone - } - } -} - -impl Memory { - /// Create a new memory with the given limit. - #[inline] - pub fn new() -> Self { - Self { - data: Vec::with_capacity(4 * 1024), // took it from evmone - } - } - - #[deprecated = "Use `len` instead"] - #[doc(hidden)] - #[inline] - pub fn effective_len(&self) -> usize { - self.len() - } - - /// Returns the length of the current memory range. - #[inline] - pub fn len(&self) -> usize { - self.data.len() - } - - /// Returns true if current memory range length is zero. - #[inline] - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - /// Return a reference to the full memory. - #[inline] - pub fn data(&self) -> &Vec { - &self.data - } - - /// Consumes the type and returns the full memory. - #[inline] - pub fn into_data(self) -> Vec { - self.data - } - - /// Shrinks the capacity of the data buffer as much as possible. - #[inline] - pub fn shrink_to_fit(&mut self) { - self.data.shrink_to_fit() - } - - /// Resizes the stack in-place so that then length is equal to `new_size`. - /// - /// `new_size` should be a multiple of 32. - #[inline] - pub fn resize(&mut self, new_size: usize) { - self.data.resize(new_size, 0); - } - - /// Returns a byte slice of the memory region at the given offset. - /// - /// Panics on out of bounds. - #[inline(always)] - #[cfg_attr(debug_assertions, track_caller)] - pub fn slice(&self, offset: usize, size: usize) -> &[u8] { - match self.data.get(offset..offset + size) { - Some(slice) => slice, - None => debug_unreachable!("slice OOB: {offset}..{size}; len: {}", self.len()), - } - } - - #[deprecated = "use `slice` instead"] - #[inline(always)] - #[cfg_attr(debug_assertions, track_caller)] - pub fn get_slice(&self, offset: usize, size: usize) -> &[u8] { - self.slice(offset, size) - } - - /// Returns a mutable byte slice of the memory region at the given offset. - /// - /// Panics on out of bounds. - #[inline(always)] - #[cfg_attr(debug_assertions, track_caller)] - pub fn slice_mut(&mut self, offset: usize, size: usize) -> &mut [u8] { - let _len = self.len(); - match self.data.get_mut(offset..offset + size) { - Some(slice) => slice, - None => debug_unreachable!("slice_mut OOB: {offset}..{size}; len: {_len}"), - } - } - - /// Sets the `byte` at the given `index`. - /// - /// Panics when `index` is out of bounds. - #[inline(always)] - #[cfg_attr(debug_assertions, track_caller)] - pub fn set_byte(&mut self, index: usize, byte: u8) { - match self.data.get_mut(index) { - Some(b) => *b = byte, - None => debug_unreachable!("set_byte OOB: {index}; len: {}", self.len()), - } - } - - /// Sets the given `value` to the memory region at the given `offset`. - /// - /// Panics on out of bounds. - #[inline(always)] - #[cfg_attr(debug_assertions, track_caller)] - pub fn set_u256(&mut self, offset: usize, value: U256) { - self.set(offset, &value.to_be_bytes::<32>()); - } - - /// Set memory region at given `offset`. - /// - /// Panics on out of bounds. - #[inline(always)] - #[cfg_attr(debug_assertions, track_caller)] - pub fn set(&mut self, offset: usize, value: &[u8]) { - if !value.is_empty() { - self.slice_mut(offset, value.len()).copy_from_slice(value); - } - } - - /// Set memory from data. Our memory offset+len is expected to be correct but we - /// are doing bound checks on data/data_offeset/len and zeroing parts that is not copied. - /// - /// Panics on out of bounds. - #[inline(always)] - #[cfg_attr(debug_assertions, track_caller)] - pub fn set_data(&mut self, memory_offset: usize, data_offset: usize, len: usize, data: &[u8]) { - if data_offset >= data.len() { - // nullify all memory slots - self.slice_mut(memory_offset, len).fill(0); - return; - } - let data_end = min(data_offset + len, data.len()); - let data_len = data_end - data_offset; - debug_assert!(data_offset < data.len() && data_end <= data.len()); - let data = unsafe { data.get_unchecked(data_offset..data_end) }; - self.slice_mut(memory_offset, data_len) - .copy_from_slice(data); - - // nullify rest of memory slots - // Safety: Memory is assumed to be valid. And it is commented where that assumption is made - self.slice_mut(memory_offset + data_len, len - data_len) - .fill(0); - } - - /// Copies elements from one part of the memory to another part of itself. - /// - /// Panics on out of bounds. - #[inline(always)] - #[cfg_attr(debug_assertions, track_caller)] - pub fn copy(&mut self, dst: usize, src: usize, len: usize) { - self.data.copy_within(src..src + len, dst); - } -} - -/// Rounds up `x` to the closest multiple of 32. If `x % 32 == 0` then `x` is returned. -#[inline] -pub(crate) fn next_multiple_of_32(x: usize) -> Option { - let r = x.bitand(31).not().wrapping_add(1).bitand(31); - x.checked_add(r) -} - -#[cfg(test)] -mod tests { - use super::next_multiple_of_32; - use crate::Memory; - - #[test] - fn test_copy() { - // Create a sample memory instance - let mut memory = Memory::new(); - - // Set up initial memory data - let data: Vec = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - memory.resize(data.len()); - memory.set_data(0, 0, data.len(), &data); - - // Perform a copy operation - memory.copy(5, 0, 4); - - // Verify the copied data - let copied_data = memory.slice(5, 4); - assert_eq!(copied_data, &[1, 2, 3, 4]); - } - - #[test] - fn test_next_multiple_of_32() { - // next_multiple_of_32 returns x when it is a multiple of 32 - for i in 0..32 { - let x = i * 32; - assert_eq!(Some(x), next_multiple_of_32(x)); - } - - // next_multiple_of_32 rounds up to the nearest multiple of 32 when `x % 32 != 0` - for x in 0..1024 { - if x % 32 == 0 { - continue; - } - let next_multiple = x + 32 - (x % 32); - assert_eq!(Some(next_multiple), next_multiple_of_32(x)); - } - } -} diff --git a/crates/interpreter/src/interpreter/shared_memory.rs b/crates/interpreter/src/interpreter/shared_memory.rs index 2b3fbafe51..389194e797 100644 --- a/crates/interpreter/src/interpreter/shared_memory.rs +++ b/crates/interpreter/src/interpreter/shared_memory.rs @@ -11,6 +11,8 @@ use core::{ /// a `Vec` for internal representation. /// A [SharedMemory] instance should always be obtained using /// the `new` static method to ensure memory safety. +#[derive(Clone, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct SharedMemory { /// Shared buffer data: Vec, From 8fd6321c3f810636a65b842b48eee2544542fb97 Mon Sep 17 00:00:00 2001 From: rakita Date: Wed, 11 Oct 2023 17:01:58 +0200 Subject: [PATCH 7/7] remove required Debug --- crates/interpreter/src/lib.rs | 6 +----- crates/precompile/src/lib.rs | 2 +- crates/primitives/src/db.rs | 1 - crates/primitives/src/lib.rs | 6 +----- crates/revm/src/inspector/eip3155.rs | 1 - crates/revm/src/lib.rs | 2 +- 6 files changed, 4 insertions(+), 14 deletions(-) diff --git a/crates/interpreter/src/lib.rs b/crates/interpreter/src/lib.rs index cd77099648..5ec60baa55 100644 --- a/crates/interpreter/src/lib.rs +++ b/crates/interpreter/src/lib.rs @@ -1,11 +1,7 @@ //! # revm-interpreter //! //! REVM Interpreter. -#![warn( - missing_debug_implementations, - unreachable_pub, - unused_crate_dependencies -)] +#![warn(unreachable_pub, unused_crate_dependencies)] #![deny(unused_must_use, rust_2018_idioms)] #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] diff --git a/crates/precompile/src/lib.rs b/crates/precompile/src/lib.rs index e016414c2b..6ab2385f3a 100644 --- a/crates/precompile/src/lib.rs +++ b/crates/precompile/src/lib.rs @@ -1,7 +1,7 @@ //! # revm-precompile //! //! Implementations of EVM precompiled contracts. -#![warn(missing_debug_implementations, unused_crate_dependencies)] +#![warn(unused_crate_dependencies)] #![deny(unused_must_use, rust_2018_idioms)] #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] diff --git a/crates/primitives/src/db.rs b/crates/primitives/src/db.rs index 8519b23b75..fc7906ffce 100644 --- a/crates/primitives/src/db.rs +++ b/crates/primitives/src/db.rs @@ -90,7 +90,6 @@ impl Database for WrapDatabaseRef { /// Wraps a `dyn DatabaseRef` to provide a [`Database`] implementation. #[doc(hidden)] #[deprecated = "use `WrapDatabaseRef` instead"] -#[allow(missing_debug_implementations)] pub struct RefDBWrapper<'a, E> { pub db: &'a dyn DatabaseRef, } diff --git a/crates/primitives/src/lib.rs b/crates/primitives/src/lib.rs index 2580650a44..d84225bbbc 100644 --- a/crates/primitives/src/lib.rs +++ b/crates/primitives/src/lib.rs @@ -1,11 +1,7 @@ //! # revm-primitives //! //! EVM primitive types. -#![warn( - missing_debug_implementations, - unreachable_pub, - unused_crate_dependencies -)] +#![warn(unreachable_pub, unused_crate_dependencies)] #![deny(unused_must_use, rust_2018_idioms)] #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] diff --git a/crates/revm/src/inspector/eip3155.rs b/crates/revm/src/inspector/eip3155.rs index 5d2e672a19..b7a635b62f 100644 --- a/crates/revm/src/inspector/eip3155.rs +++ b/crates/revm/src/inspector/eip3155.rs @@ -8,7 +8,6 @@ use serde_json::json; use std::io::Write; /// [EIP-3155](https://eips.ethereum.org/EIPS/eip-3155) tracer [Inspector]. -#[allow(missing_debug_implementations)] pub struct TracerEip3155 { output: Box, gas_inspector: GasInspector, diff --git a/crates/revm/src/lib.rs b/crates/revm/src/lib.rs index d8296e29ca..6a5814e0f8 100644 --- a/crates/revm/src/lib.rs +++ b/crates/revm/src/lib.rs @@ -1,4 +1,4 @@ -#![warn(missing_debug_implementations, unreachable_pub)] +#![warn(unreachable_pub)] #![cfg_attr(not(test), warn(unused_crate_dependencies))] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #![deny(unused_must_use, rust_2018_idioms)]