Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 78 additions & 24 deletions rust/op-reth/crates/trie/tests/live.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
//! End-to-end test of the live trie collector.

use alloy_consensus::{BlockHeader, Header, TxEip2930, constants::ETH_TO_WEI};
use alloy_eips::BlockNumHash;
use alloy_consensus::{
BlockHeader, Header, TxEip2930,
constants::{EMPTY_WITHDRAWALS, ETH_TO_WEI},
};
use alloy_eips::{BlockNumHash, eip4895::Withdrawals};
use alloy_genesis::{Genesis, GenesisAccount};
use alloy_primitives::{Address, B256, Bytes, TxKind, U256, keccak256};
use derive_more::Constructor;
use reth_chainspec::{ChainSpec, ChainSpecBuilder, EthereumHardfork, MAINNET, MIN_TRANSACTION_GAS};
use reth_chainspec::{
ChainSpec, ChainSpecBuilder, EthereumHardfork, EthereumHardforks, MAINNET, MIN_TRANSACTION_GAS,
};
use reth_db::Database;
use reth_db_common::init::init_genesis;
use reth_ethereum_primitives::{Block, BlockBody, Receipt, Transaction, TransactionSigned};
Expand All @@ -32,8 +37,27 @@ use std::sync::Arc;
use tempfile::TempDir;
use test_case::test_case;

#[path = "live/contracts.rs"]
mod contracts;
#[path = "live/index_execute_parity.rs"]
mod index_execute_parity;
#[path = "live/parent_states.rs"]
mod parent_states;
#[path = "live/simulated_reth.rs"]
mod simulated_reth;
#[path = "live/store_view.rs"]
mod store_view;

/// Seconds between consecutive blocks.
const BLOCK_TIME: u64 = 2;

/// Blocks between pruner runs, far beyond any test chain.
const PRUNE_INTERVAL_BLOCKS: u64 = 1000;

/// Timestamp of the block at `number`.
const fn block_timestamp(number: u64) -> u64 {
number * BLOCK_TIME
}

fn create_mdbx_proofs_storage() -> Arc<MdbxProofsStorage> {
let path = TempDir::new().unwrap().keep();
Expand Down Expand Up @@ -91,6 +115,11 @@ impl TxSpec {
const fn call(contract: Address, data: Bytes, gas_limit: u64) -> Self {
Self { to: TxKind::Call(contract), data, gas_limit, value: U256::ZERO, nonce: None }
}

/// Send `value` along with the transaction.
fn with_value(self, value: U256) -> Self {
Self { value, ..self }
}
}

/// Specification for a block in the test chain
Expand All @@ -100,6 +129,13 @@ struct BlockSpec {
txs: Vec<TxSpec>,
}

impl BlockSpec {
/// A block without transactions.
const fn empty() -> Self {
Self { txs: Vec::new() }
}
}

/// Configuration for a test scenario
#[derive(Debug, Constructor)]
struct TestScenario {
Expand All @@ -109,22 +145,24 @@ struct TestScenario {
blocks_after_initialization: Vec<BlockSpec>,
}

/// A mainnet-shaped chain spec whose genesis allocation is `alloc`, with the hardforks still to
/// be chosen.
fn chain_spec_builder(
alloc: impl IntoIterator<Item = (Address, GenesisAccount)>,
) -> ChainSpecBuilder {
ChainSpecBuilder::default()
.chain(MAINNET.chain)
.genesis(Genesis { alloc: alloc.into_iter().collect(), ..MAINNET.genesis.clone() })
}

/// A genesis allocation funding `address`.
fn funded(address: Address) -> (Address, GenesisAccount) {
(address, GenesisAccount { balance: U256::from(10 * ETH_TO_WEI), ..Default::default() })
}

/// Helper to create a chain spec with a genesis account funded
fn chain_spec_with_address(address: Address) -> Arc<ChainSpec> {
Arc::new(
ChainSpecBuilder::default()
.chain(MAINNET.chain)
.genesis(Genesis {
alloc: [(
address,
GenesisAccount { balance: U256::from(10 * ETH_TO_WEI), ..Default::default() },
)]
.into(),
..MAINNET.genesis.clone()
})
.paris_activated()
.build(),
)
Arc::new(chain_spec_builder([funded(address)]).paris_activated().build())
}

/// Creates a block from a spec, executing transactions with the given keypair
Expand Down Expand Up @@ -164,6 +202,9 @@ fn create_block_from_spec(
.collect();

let gas_total = spec.txs.iter().map(|tx| tx.gas_limit).sum::<u64>();
let timestamp = block_timestamp(block_number);
let shanghai = chain_spec.is_shanghai_active_at_timestamp(timestamp);
let cancun = chain_spec.is_cancun_active_at_timestamp(timestamp);

Block {
header: Header {
Expand All @@ -175,10 +216,19 @@ fn create_block_from_spec(
number: block_number,
gas_limit: gas_total.max(MIN_TRANSACTION_GAS),
gas_used: gas_total,
timestamp,
state_root: B256::ZERO, // Will be calculated by executor
withdrawals_root: shanghai.then_some(EMPTY_WITHDRAWALS),
blob_gas_used: cancun.then_some(0),
excess_blob_gas: cancun.then_some(0),
parent_beacon_block_root: cancun.then(|| keccak256(block_number.to_be_bytes())),
..Default::default()
},
body: BlockBody {
transactions,
withdrawals: shanghai.then(Withdrawals::default),
..Default::default()
},
body: BlockBody { transactions, ..Default::default() },
}
.try_into_recovered()
.unwrap()
Expand Down Expand Up @@ -317,7 +367,8 @@ where
// state between iterations (the new async-persistence architecture requires this).
let evm_config = EthEvmConfig::ethereum(chain_spec.clone());
let blockchain_db = BlockchainProvider::new(provider_factory.clone())?;
let pruner = OpProofStoragePruner::new(storage.clone(), blockchain_db.clone(), 1000);
let pruner =
OpProofStoragePruner::new(storage.clone(), blockchain_db.clone(), PRUNE_INTERVAL_BLOCKS);
let engine_handle = EngineHandle::spawn(evm_config, blockchain_db, storage, pruner);

for (idx, block_spec) in scenario.blocks_after_initialization.iter().enumerate() {
Expand Down Expand Up @@ -420,7 +471,7 @@ where

let mut nonce_counter = 0;
let incorrect_block = create_block_from_spec(
&BlockSpec::new(vec![]),
&BlockSpec::empty(),
incorrect_block_number,
incorrect_parent_hash,
&chain_spec,
Expand All @@ -429,7 +480,8 @@ where
);

let blockchain_db = BlockchainProvider::new(provider_factory).unwrap();
let pruner = OpProofStoragePruner::new(storage.clone(), blockchain_db.clone(), 1000);
let pruner =
OpProofStoragePruner::new(storage.clone(), blockchain_db.clone(), PRUNE_INTERVAL_BLOCKS);
let engine_handle = EngineHandle::spawn(
EthEvmConfig::ethereum(chain_spec.clone()),
blockchain_db,
Expand Down Expand Up @@ -477,7 +529,8 @@ where

// Generate a second block normally
let blockchain_db = BlockchainProvider::new(provider_factory.clone()).unwrap();
let pruner = OpProofStoragePruner::new(storage.clone(), blockchain_db.clone(), 1000);
let pruner =
OpProofStoragePruner::new(storage.clone(), blockchain_db.clone(), PRUNE_INTERVAL_BLOCKS);
let engine_handle = EngineHandle::spawn(
EthEvmConfig::ethereum(chain_spec.clone()),
blockchain_db,
Expand All @@ -492,7 +545,7 @@ where
let next_number = 1;

let mut block = create_block_from_spec(
&BlockSpec::new(vec![]),
&BlockSpec::empty(),
next_number,
last_block_hash,
&chain_spec,
Expand Down Expand Up @@ -550,7 +603,8 @@ where
)?;

let blockchain_db = BlockchainProvider::new(provider_factory.clone()).unwrap();
let pruner = OpProofStoragePruner::new(storage.clone(), blockchain_db.clone(), 1000);
let pruner =
OpProofStoragePruner::new(storage.clone(), blockchain_db.clone(), PRUNE_INTERVAL_BLOCKS);
let engine_handle = EngineHandle::spawn(
EthEvmConfig::ethereum(chain_spec.clone()),
blockchain_db,
Expand Down
102 changes: 102 additions & 0 deletions rust/op-reth/crates/trie/tests/live/contracts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
//! EVM bytecode of the contracts the live tests deploy, and the storage slots they write.

use alloy_primitives::{Address, B256, Bytes, U256};

/// Storage slot every call to the block-hash recorder sets to one.
pub(super) const CALLED_SLOT: B256 = B256::ZERO;

/// Storage slot a call to the block-hash recorder with calldata sets to `BLOCKHASH(calldata)`.
pub(super) const BLOCK_HASH_SLOT: B256 = B256::with_last_byte(1);

/// Runtime code of the block-hash recorder: `slot 0 = 1`, then
/// `slot 1 = BLOCKHASH(calldata[0..32])` unless the call has no calldata.
///
/// ```text
/// PUSH1 1 PUSH1 0 SSTORE
/// CALLDATASIZE ISZERO PUSH1 0x11 JUMPI
/// PUSH1 0 CALLDATALOAD BLOCKHASH PUSH1 1 SSTORE
/// JUMPDEST STOP
/// ```
pub(super) const BLOCK_HASH_RECORDER_RUNTIME: [u8; 19] = [
0x60, 0x01, 0x60, 0x00, 0x55, 0x36, 0x15, 0x60, 0x11, 0x57, 0x60, 0x00, 0x35, 0x40, 0x60, 0x01,
0x55, 0x5b, 0x00,
];

/// Number of storage slots the slot writer takes from calldata.
pub(super) const SLOT_WRITER_SLOTS: usize = 8;

/// Runtime code of the slot writer: a call with calldata stores one 32-byte calldata word per
/// entry of `slots`, in order; a call without calldata self-destructs to `beneficiary`.
///
/// ```text
/// CALLDATASIZE ISZERO PUSH1 <selfdestruct> JUMPI
/// PUSH1 0x00 CALLDATALOAD PUSH1 slots[0] SSTORE
/// ...
/// PUSH1 0xe0 CALLDATALOAD PUSH1 slots[7] SSTORE
/// STOP
/// JUMPDEST PUSH20 beneficiary SELFDESTRUCT
/// ```
pub(super) fn slot_writer_runtime(beneficiary: Address, slots: [u8; SLOT_WRITER_SLOTS]) -> Vec<u8> {
let mut store_slots = Vec::new();
for (word, slot) in slots.into_iter().enumerate() {
store_slots.extend_from_slice(&[0x60, word as u8 * 32, 0x35, 0x60, slot, 0x55]);
}
store_slots.push(0x00);
let dispatch_len = 5;
let selfdestruct_at = u8::try_from(dispatch_len + store_slots.len()).expect("short code");
let mut code = vec![0x36, 0x15, 0x60, selfdestruct_at, 0x57];
code.extend_from_slice(&store_slots);
code.push(0x5b);
code.push(0x73);
code.extend_from_slice(beneficiary.as_slice());
code.push(0xff);
code
}

/// Number of storage slots [`create_and_selfdestruct_initcode`] writes before self-destructing.
pub(super) const CREATE_AND_SELFDESTRUCT_SLOTS: u8 = 4;

/// Initcode that stores seven into the first [`CREATE_AND_SELFDESTRUCT_SLOTS`] slots and then
/// self-destructs to `beneficiary` within the creating transaction, which under EIP-6780 removes
/// the account with its storage.
///
/// ```text
/// PUSH1 7 PUSH1 0 SSTORE
/// ...
/// PUSH1 7 PUSH1 3 SSTORE
/// PUSH20 beneficiary SELFDESTRUCT
/// ```
pub(super) fn create_and_selfdestruct_initcode(beneficiary: Address) -> Bytes {
let mut code = Vec::new();
for slot in 0..CREATE_AND_SELFDESTRUCT_SLOTS {
code.extend_from_slice(&[0x60, 0x07, 0x60, slot, 0x55]);
}
code.push(0x73);
code.extend_from_slice(beneficiary.as_slice());
code.push(0xff);
code.into()
}

/// Initcode deploying `runtime`, which follows the twelve initcode bytes:
/// `PUSH1 len PUSH1 12 PUSH1 0 CODECOPY PUSH1 len PUSH1 0 RETURN`.
pub(super) fn initcode_returning(runtime: &[u8]) -> Bytes {
let runtime_len = u8::try_from(runtime.len()).expect("runtime fits one PUSH1");
let mut initcode =
vec![0x60, runtime_len, 0x60, 0x0c, 0x60, 0x00, 0x39, 0x60, runtime_len, 0x60, 0x00, 0xf3];
initcode.extend_from_slice(runtime);
initcode.into()
}

/// Calldata for the slot writer: the value of each of its slots, in the order of its `slots`.
pub(super) fn slot_writer_calldata(values: [u64; SLOT_WRITER_SLOTS]) -> Bytes {
values
.iter()
.flat_map(|value| U256::from(*value).to_be_bytes::<32>())
.collect::<Vec<u8>>()
.into()
}

/// Calldata for the block-hash recorder: the number of the block to read.
pub(super) fn block_number_calldata(number: u64) -> Bytes {
Bytes::copy_from_slice(&U256::from(number).to_be_bytes::<32>())
}
Loading
Loading