Skip to content

Commit

Permalink
Sync database (bluealloy#17)
Browse files Browse the repository at this point in the history
* rename SyncDatabase

* contracts: Vec<((u64, B256), Bytecode)>,

* StateChangeset ilter_for_chain(&mut self, chain_id: u64)

* fix comment on state_size

* remove

* use db::SyncDatabase as Database
  • Loading branch information
CeciliaZ030 authored Sep 23, 2024
1 parent f12a99d commit 959611e
Show file tree
Hide file tree
Showing 39 changed files with 209 additions and 72 deletions.
7 changes: 3 additions & 4 deletions bins/revm-test/src/bin/burntpix/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ use regex::bytes::Regex;
use revm::{
db::{CacheDB, EmptyDB},
primitives::{
address, hex, keccak256, AccountInfo, Address, Bytecode, Bytes, ExecutionResult, Output,
TxKind, B256, U256,
address, hex, keccak256, AccountInfo, Address, Bytecode, Bytes, ChainAddress, ExecutionResult, Output, TransactTo, TxKind, B256, U256
},
Evm,
};
Expand Down Expand Up @@ -37,8 +36,8 @@ fn main() {

let mut evm = Evm::builder()
.modify_tx_env(|tx| {
tx.caller = address!("1000000000000000000000000000000000000000");
tx.transact_to = TxKind::Call(BURNTPIX_MAIN_ADDRESS);
tx.caller = ChainAddress(1, address!("1000000000000000000000000000000000000000"));
tx.transact_to = TransactTo::Call(BURNTPIX_MAIN_ADDRESS);
tx.data = run_call_data.clone().into();
})
.with_db(db)
Expand Down
8 changes: 4 additions & 4 deletions crates/interpreter/src/instructions/bitwise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ mod tests {
#[test]
fn test_shift_left() {
let mut host = DummyHost::new(Env::default());
let mut interpreter = Interpreter::new(Contract::default(), u64::MAX, false);
let mut interpreter = Interpreter::new(Contract::default(), u64::MAX, false, 1, false);

struct TestCase {
value: U256,
Expand Down Expand Up @@ -211,7 +211,7 @@ mod tests {
#[test]
fn test_logical_shift_right() {
let mut host = DummyHost::new(Env::default());
let mut interpreter = Interpreter::new(Contract::default(), u64::MAX, false);
let mut interpreter = Interpreter::new(Contract::default(), u64::MAX, false, 1, false);

struct TestCase {
value: U256,
Expand Down Expand Up @@ -292,7 +292,7 @@ mod tests {
#[test]
fn test_arithmetic_shift_right() {
let mut host = DummyHost::new(Env::default());
let mut interpreter = Interpreter::new(Contract::default(), u64::MAX, false);
let mut interpreter = Interpreter::new(Contract::default(), u64::MAX, false, 1, false);

struct TestCase {
value: U256,
Expand Down Expand Up @@ -404,7 +404,7 @@ mod tests {
}

let mut host = DummyHost::new(Env::default());
let mut interpreter = Interpreter::new(Contract::default(), u64::MAX, false);
let mut interpreter = Interpreter::new(Contract::default(), u64::MAX, false, 1, false);

let input_value = U256::from(0x1234567890abcdef1234567890abcdef_u128);
let test_cases = (0..32)
Expand Down
10 changes: 7 additions & 3 deletions crates/interpreter/src/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,18 +116,22 @@ impl Interpreter {
/// Test related helper
#[cfg(test)]
pub fn new_bytecode(bytecode: Bytecode) -> Self {
use revm_primitives::ChainAddress;

Self::new(
Contract::new(
Bytes::new(),
bytecode,
None,
crate::primitives::Address::default(),
ChainAddress::default(),
None,
crate::primitives::Address::default(),
ChainAddress::default(),
U256::ZERO,
),
0,
false,
1,
false
)
}

Expand Down Expand Up @@ -482,7 +486,7 @@ mod tests {

#[test]
fn object_safety() {
let mut interp = Interpreter::new(Contract::default(), u64::MAX, false);
let mut interp = Interpreter::new(Contract::default(), u64::MAX, false, 1, false);

let mut host = crate::DummyHost::default();
let table: &InstructionTable<DummyHost> =
Expand Down
2 changes: 1 addition & 1 deletion crates/interpreter/src/interpreter/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ mod tests {

#[test]
fn test_serde() {
let interp = Interpreter::new(Contract::default(), u64::MAX, false);
let interp = Interpreter::new(Contract::default(), u64::MAX, false, 1, false);
let serialized = bincode::serialize(&interp).unwrap();
let de: Interpreter = bincode::deserialize(&serialized).unwrap();
assert_eq!(interp.program_counter(), de.program_counter());
Expand Down
49 changes: 43 additions & 6 deletions crates/primitives/src/db.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,54 @@
use crate::{Account, AccountInfo, ChainAddress, Bytecode, HashMap, B256, U256};
use alloy_primitives::Address;
use auto_impl::auto_impl;

pub mod components;
pub use components::{
BlockHash, BlockHashRef, DatabaseComponentError, DatabaseComponents, State, StateRef,
};

/// EVM database interface.
#[auto_impl(&mut, Box)]
pub trait Database {
/// The database error type.
type Error;

/// Get basic account information.
fn basic(&mut self, address: Address) -> Result<Option<AccountInfo>, Self::Error>;

/// Get account code by its hash.
fn code_by_hash(&mut self, code_hash: B256) -> Result<Bytecode, Self::Error>;

/// Get storage value of address at index.
fn storage(&mut self, address: Address, index: U256) -> Result<U256, Self::Error>;

/// Get block hash by block number.
fn block_hash(&mut self, number: u64) -> Result<B256, Self::Error>;
}

#[auto_impl(&, &mut, Box, Rc, Arc)]
pub trait DatabaseRef {
/// The database error type.
type Error;

/// Get basic account information.
fn basic_ref(&self, address: Address) -> Result<Option<AccountInfo>, Self::Error>;

/// Get account code by its hash.
fn code_by_hash_ref(&self, code_hash: B256) -> Result<Bytecode, Self::Error>;

/// Get storage value of address at index.
fn storage_ref(&self, address: Address, index: U256) -> Result<U256, Self::Error>;

/// Get block hash by block number.
fn block_hash_ref(&self, number: u64) -> Result<B256, Self::Error>;
}

/// EVM database interface.
#[auto_impl(&mut, Box)]
pub trait SyncDatabase {
/// The database error type.
type Error;

/// Get basic account information.
fn basic(&mut self, address: ChainAddress) -> Result<Option<AccountInfo>, Self::Error>;

Expand Down Expand Up @@ -39,7 +76,7 @@ pub trait DatabaseCommit {
/// Use [`WrapDatabaseRef`] to provide [`Database`] implementation for a type
/// that only implements this trait.
#[auto_impl(&, &mut, Box, Rc, Arc)]
pub trait DatabaseRef {
pub trait SyncDatabaseRef {
/// The database error type.
type Error;

Expand All @@ -58,16 +95,16 @@ pub trait DatabaseRef {

/// Wraps a [`DatabaseRef`] to provide a [`Database`] implementation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct WrapDatabaseRef<T: DatabaseRef>(pub T);
pub struct WrapDatabaseRef<T: SyncDatabaseRef>(pub T);

impl<F: DatabaseRef> From<F> for WrapDatabaseRef<F> {
impl<F: SyncDatabaseRef> From<F> for WrapDatabaseRef<F> {
#[inline]
fn from(f: F) -> Self {
WrapDatabaseRef(f)
}
}

impl<T: DatabaseRef> Database for WrapDatabaseRef<T> {
impl<T: SyncDatabaseRef> SyncDatabase for WrapDatabaseRef<T> {
type Error = T::Error;

#[inline]
Expand All @@ -91,7 +128,7 @@ impl<T: DatabaseRef> Database for WrapDatabaseRef<T> {
}
}

impl<T: DatabaseRef + DatabaseCommit> DatabaseCommit for WrapDatabaseRef<T> {
impl<T: SyncDatabaseRef + DatabaseCommit> DatabaseCommit for WrapDatabaseRef<T> {
#[inline]
fn commit(&mut self, changes: HashMap<ChainAddress, Account>) {
self.0.commit(changes)
Expand Down
2 changes: 1 addition & 1 deletion crates/primitives/src/db/components.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub use block_hash::{BlockHash, BlockHashRef};
pub use state::{State, StateRef};

use crate::{
db::{Database, DatabaseRef},
db::{SyncDatabase as Database, SyncDatabaseRef as DatabaseRef},
Account, AccountInfo, Address, ChainAddress, Bytecode, HashMap, B256, U256,
};

Expand Down
1 change: 0 additions & 1 deletion crates/primitives/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -720,7 +720,6 @@ use alloy_rlp::{Buf, BufMut, Decodable, Encodable, EMPTY_STRING_CODE};
/// The `to` field of a transaction. Either a target address, or empty for a
/// contract creation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(derive_arbitrary::Arbitrary, proptest_derive::Arbitrary))]
pub enum TransactTo {
/// A transaction that creates a contract.
#[default]
Expand Down
2 changes: 1 addition & 1 deletion crates/revm/src/builder.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{
db::{Database, DatabaseRef, EmptyDB, WrapDatabaseRef},
db::{SyncDatabase as Database, SyncDatabaseRef as DatabaseRef, EmptyDB, WrapDatabaseRef},
handler::register,
primitives::{
BlockEnv, CfgEnv, CfgEnvWithHandlerCfg, Env, EnvWithHandlerCfg, HandlerCfg, SpecId, TxEnv,
Expand Down
2 changes: 1 addition & 1 deletion crates/revm/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub use inner_evm_context::InnerEvmContext;
use revm_interpreter::{as_u64_saturated, Eip7702CodeLoad, StateLoad};

use crate::{
db::{Database, EmptyDB},
db::{SyncDatabase as Database, EmptyDB},
interpreter::{AccountLoad, Host, SStoreResult, SelfDestructResult},
primitives::{Address, Bytes, ChainAddress, Env, HandlerCfg, Log, B256, BLOCK_HASH_HISTORY, U256},
};
Expand Down
2 changes: 1 addition & 1 deletion 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, HashSet},
primitives::{db::SyncDatabase as Database, Address, Bytes, HashMap, HashSet},
};
use dyn_clone::DynClone;
use revm_precompile::{PrecompileSpecId, PrecompileWithAddress, Precompiles};
Expand Down
2 changes: 1 addition & 1 deletion crates/revm/src/context/evm_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use revm_precompile::PrecompileErrors;

use super::inner_evm_context::InnerEvmContext;
use crate::{
db::Database,
db::SyncDatabase as Database,
interpreter::{
analysis::validate_eof, return_ok, CallInputs, Contract, CreateInputs, EOFCreateInputs,
EOFCreateKind, Gas, InstructionResult, Interpreter, InterpreterResult,
Expand Down
2 changes: 1 addition & 1 deletion crates/revm/src/context/inner_evm_context.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{
db::Database,
db::SyncDatabase as Database,
interpreter::{
analysis::to_analysed, gas, return_ok, AccountLoad, Eip7702CodeLoad, InstructionResult,
InterpreterResult, SStoreResult, SelfDestructResult, StateLoad,
Expand Down
2 changes: 1 addition & 1 deletion crates/revm/src/db/emptydb.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use core::{convert::Infallible, fmt, marker::PhantomData};
use revm_interpreter::primitives::{
db::{Database, DatabaseRef},
db::{SyncDatabase as Database, SyncDatabaseRef as DatabaseRef},
keccak256, AccountInfo, ChainAddress, Bytecode, B256, U256,
};
use std::string::ToString;
Expand Down
2 changes: 1 addition & 1 deletion crates/revm/src/db/ethersdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use ethers_providers::Middleware;
use tokio::runtime::{Handle, Runtime};

use crate::primitives::{AccountInfo, Address, Bytecode, ChainAddress, B256, U256};
use crate::{Database, DatabaseRef};
use crate::{SyncDatabase as Database, SyncDatabaseRef as DatabaseRef};

use super::utils::HandleOrRuntime;

Expand Down
13 changes: 7 additions & 6 deletions crates/revm/src/db/in_memory_db.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use super::{DatabaseCommit, DatabaseRef, EmptyDB};
use super::{DatabaseCommit, SyncDatabaseRef as DatabaseRef, EmptyDB};
use crate::primitives::{
hash_map::Entry, Account, AccountInfo, Address, ChainAddress, Bytecode, HashMap, Log, B256, KECCAK_EMPTY,
U256,
};
use crate::Database;
use crate::SyncDatabase as Database;
use core::convert::Infallible;
use std::vec::Vec;

Expand All @@ -24,6 +24,7 @@ pub struct CacheDB<ExtDB> {
/// `code` is always `None`, and bytecode can be found in `contracts`.
pub accounts: HashMap<ChainAddress, DbAccount>,
/// Tracks all contracts by their code hash.
// FIX(Cecilia): should be (u64, B256)
pub contracts: HashMap<B256, Bytecode>,
/// All logs that were committed via [DatabaseCommit::commit].
pub logs: Vec<Log>,
Expand Down Expand Up @@ -411,7 +412,7 @@ impl Database for BenchmarkDB {
#[cfg(test)]
mod tests {
use super::{CacheDB, EmptyDB};
use crate::primitives::{db::Database, AccountInfo, Address, ChainAddress, U256};
use crate::primitives::{db::SyncDatabase as Database, AccountInfo, Address, ChainAddress, U256};

#[test]
fn test_insert_account_storage() {
Expand Down Expand Up @@ -474,7 +475,7 @@ mod tests {
let nonce = 420;
let mut init_state = CacheDB::new(EmptyDB::default());
init_state.insert_account_info(
account,
ChainAddress(0, account),
AccountInfo {
nonce,
..Default::default()
Expand All @@ -484,9 +485,9 @@ mod tests {
let serialized = serde_json::to_string(&init_state).unwrap();
let deserialized: CacheDB<EmptyDB> = serde_json::from_str(&serialized).unwrap();

assert!(deserialized.accounts.contains_key(&account));
assert!(deserialized.accounts.contains_key(&ChainAddress(0, account)));
assert_eq!(
deserialized.accounts.get(&account).unwrap().info.nonce,
deserialized.accounts.get(&ChainAddress(0, account)).unwrap().info.nonce,
nonce
);
}
Expand Down
Loading

0 comments on commit 959611e

Please sign in to comment.