Skip to content
This repository has been archived by the owner on Jul 5, 2024. It is now read-only.

Commit

Permalink
test: add a test for withdrawal
Browse files Browse the repository at this point in the history
  • Loading branch information
KimiWu123 committed Oct 4, 2023
1 parent f3ccc42 commit a2c7a12
Show file tree
Hide file tree
Showing 15 changed files with 703 additions and 146 deletions.
2 changes: 1 addition & 1 deletion bus-mapping/src/circuit_input_builder/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ impl Block {

/// Return root of withdrawals of this block
pub fn withdrawals_root(&self) -> H256 {
self.eth_block.withdrawals_root.clone().unwrap()
self.eth_block.withdrawals_root.unwrap()
}

/// Push a copy event to the block.
Expand Down
16 changes: 15 additions & 1 deletion eth-types/src/geth_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,20 @@ impl BlockConstants {
}
}

/// Definition of all of the constants related to an Ethereum withdrawal.
#[derive(Debug, Default, Clone, Serialize)]
pub struct Withdrawal {
/// Unique identifier of a withdrawal. This value starts from 0 and then increases
/// monotonically.
pub id: u64,
/// Unique identifier of a validator.
pub validator_id: u64,
/// Address to be withdrawn to.
pub address: Address,
/// Withdrawal amount in Gwei.
pub amount: u64,
}

/// Definition of all of the constants related to an Ethereum transaction.
#[derive(Debug, Default, Clone, Serialize)]
pub struct Transaction {
Expand Down Expand Up @@ -322,7 +336,7 @@ pub struct GethData {
/// chain id
pub chain_id: Word,
/// history hashes contains most recent 256 block hashes in history, where
/// the lastest one is at history_hashes[history_hashes.len() - 1].
/// the latest one is at history_hashes[history_hashes.len() - 1].
pub history_hashes: Vec<Word>,
/// Block from geth
pub eth_block: Block<crate::Transaction>,
Expand Down
8 changes: 5 additions & 3 deletions external-tracer/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,28 @@
//! This module generates traces by connecting to an external tracer
use eth_types::{
geth_types::{Account, BlockConstants, Transaction},
geth_types::{Account, BlockConstants, Transaction, Withdrawal},
Address, Error, GethExecTrace, Word,
};
use serde::Serialize;
use std::collections::HashMap;

/// Configuration structure for `geth_utlis::trace`
/// Configuration structure for `geth_utils::trace`
#[derive(Debug, Default, Clone, Serialize)]
pub struct TraceConfig {
/// chain id
pub chain_id: Word,
/// history hashes contains most recent 256 block hashes in history, where
/// the lastest one is at history_hashes[history_hashes.len() - 1].
/// the latest one is at history_hashes[history_hashes.len() - 1].
pub history_hashes: Vec<Word>,
/// block constants
pub block_constants: BlockConstants,
/// accounts
pub accounts: HashMap<Address, Account>,
/// transaction
pub transactions: Vec<Transaction>,
/// withdrawal
pub withdrawals: Vec<Withdrawal>,
/// logger
pub logger_config: LoggerConfig,
}
Expand Down
27 changes: 21 additions & 6 deletions mock/src/block.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
//! Mock Block definition and builder related methods.
use crate::{MockTransaction, MOCK_BASEFEE, MOCK_CHAIN_ID, MOCK_DIFFICULTY, MOCK_GASLIMIT};
use crate::{
withdrawal::MockWithdrawal, MockTransaction, MOCK_BASEFEE, MOCK_CHAIN_ID, MOCK_DIFFICULTY,
MOCK_GASLIMIT,
};
use eth_types::{Address, Block, Bytes, Hash, Transaction, Word, H64, U64};
use ethers_core::{
types::{Bloom, OtherFields},
Expand Down Expand Up @@ -37,6 +40,7 @@ pub struct MockBlock {
seal_fields: Vec<Bytes>,
uncles: Vec<Hash>,
pub(crate) transactions: Vec<MockTransaction>,
pub(crate) withdrawals: Vec<MockWithdrawal>,
size: Word,
// This field is handled here as we assume that all block txs have the same ChainId.
// Also, the field is stored in the block_table since we don't have a chain_config
Expand Down Expand Up @@ -65,12 +69,13 @@ impl Default for MockBlock {
mix_hash: Hash::zero(),
nonce: H64::zero(),
base_fee_per_gas: Some(*MOCK_BASEFEE),
withdrawal_hash: None,
withdrawal_hash: Some(Hash::zero()),
// Other information
total_difficulty: Word::zero(),
seal_fields: Vec::new(),
uncles: Vec::new(),
transactions: Vec::new(),
withdrawals: Vec::new(),
size: Word::zero(),
chain_id: *MOCK_CHAIN_ID,
}
Expand Down Expand Up @@ -109,8 +114,13 @@ impl From<MockBlock> for Block<Transaction> {
.collect::<Vec<Transaction>>(),
size: Some(mock.size),
other: OtherFields::default(),
withdrawals_root: None,
withdrawals: None,
withdrawals_root: mock.withdrawal_hash,
withdrawals: Some(
mock.withdrawals
.iter_mut()
.map(|mock_wd| mock_wd.to_owned().into())
.collect(),
),
}
}
}
Expand Down Expand Up @@ -143,8 +153,13 @@ impl From<MockBlock> for Block<()> {
transactions: vec![],
size: Some(mock.size),
other: OtherFields::default(),
withdrawals_root: None,
withdrawals: None,
withdrawals_root: mock.withdrawal_hash,
withdrawals: Some(
mock.withdrawals
.iter()
.map(|mock_wd| mock_wd.to_owned().into())
.collect(),
),
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions mock/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,17 @@ mod account;
mod block;
mod sha3;
pub mod test_ctx;
pub mod test_ctx2;
mod transaction;
mod withdrawal;

pub(crate) use account::MockAccount;
pub(crate) use block::MockBlock;
pub use sha3::Sha3CodeGen;
pub use test_ctx::TestContext;
pub use test_ctx2::TestContext2;
pub use transaction::{AddrOrWallet, MockTransaction, CORRECT_MOCK_TXS};
pub(crate) use withdrawal::MockWithdrawal;

Check failure on line 22 in mock/src/lib.rs

View workflow job for this annotation

GitHub Actions / Various lints

unused import: `withdrawal::MockWithdrawal`

/// Mock block gas limit
pub const MOCK_BLOCK_GAS_LIMIT: u64 = 10_000_000_000_000_000;
Expand Down
80 changes: 14 additions & 66 deletions mock/src/test_ctx.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
//! Mock types and functions to generate Test enviroments for ZKEVM tests
use crate::{eth, MockAccount, MockBlock, MockTransaction};
use crate::{eth, MockAccount, MockBlock, MockTransaction, TestContext2};
use eth_types::{
geth_types::{Account, BlockConstants, GethData},
Block, Bytecode, Error, GethExecTrace, Transaction, Word,
};
use external_tracer::{trace, TraceConfig};
use helpers::*;
use itertools::Itertools;

pub use external_tracer::LoggerConfig;

Expand Down Expand Up @@ -90,6 +89,7 @@ pub struct TestContext<const NACC: usize, const NTX: usize> {
pub geth_traces: Vec<eth_types::GethExecTrace>,
}

// FIXME: refactor with TestContext2 to reduce duplicated code
impl<const NACC: usize, const NTX: usize> From<TestContext<NACC, NTX>> for GethData {
fn from(ctx: TestContext<NACC, NTX>) -> GethData {
GethData {
Expand All @@ -115,74 +115,21 @@ impl<const NACC: usize, const NTX: usize> TestContext<NACC, NTX> {
Fb: FnOnce(&mut MockBlock, Vec<MockTransaction>) -> &mut MockBlock,
FAcc: FnOnce([&mut MockAccount; NACC]),
{
let mut accounts: Vec<MockAccount> = vec![MockAccount::default(); NACC];
// Build Accounts modifiers
let account_refs = accounts
.iter_mut()
.collect_vec()
.try_into()
.expect("Mismatched len err");
acc_fns(account_refs);
let accounts: [MockAccount; NACC] = accounts
.iter_mut()
.map(|acc| acc.build())
.collect_vec()
.try_into()
.expect("Mismatched acc len");

let mut transactions = vec![MockTransaction::default(); NTX];
let tx_refs = transactions.iter_mut().collect();

// Build Tx modifiers.
func_tx(tx_refs, accounts.clone());

// Sets the transaction_idx and nonce after building the tx modifiers. Hence, if user has
// overridden these values above using the tx modifiers, that will be ignored.
let mut acc_tx_count = vec![0u64; NACC];
transactions.iter_mut().enumerate().for_each(|(idx, tx)| {
let idx = u64::try_from(idx).expect("Unexpected idx conversion error");
tx.transaction_idx(idx);
if let Some((pos, from_acc)) = accounts
.iter()
.find_position(|acc| acc.address == tx.from.address())
{
tx.nonce(from_acc.nonce + acc_tx_count[pos]);
acc_tx_count[pos] += 1;
}
});

let transactions: Vec<MockTransaction> =
transactions.iter_mut().map(|tx| tx.build()).collect();

// Build Block modifiers
let mut block = MockBlock::default();
block.transactions.extend_from_slice(&transactions);
func_block(&mut block, transactions).build();

let chain_id = block.chain_id;
let block = Block::<Transaction>::from(block);
let accounts: [Account; NACC] = accounts
.iter()
.cloned()
.map(Account::from)
.collect_vec()
.try_into()
.expect("Mismatched acc len");

let geth_traces = gen_geth_traces(
chain_id,
block.clone(),
accounts.to_vec(),
history_hashes.clone(),
let test_ctx2 = TestContext2::<NACC, NTX, 0>::new_with_logger_config(
history_hashes,
acc_fns,
func_tx,
|_| {},
func_block,
logger_config,
)?;

Ok(Self {
chain_id,
accounts,
history_hashes: history_hashes.unwrap_or_default(),
eth_block: block,
geth_traces,
chain_id: test_ctx2.chain_id,
accounts: test_ctx2.accounts,
history_hashes: test_ctx2.history_hashes.clone(),
eth_block: test_ctx2.eth_block,
geth_traces: test_ctx2.geth_traces,
})
}

Expand Down Expand Up @@ -249,6 +196,7 @@ pub fn gen_geth_traces(
.iter()
.map(eth_types::geth_types::Transaction::from)
.collect(),
withdrawals: vec![],
logger_config,
};
let traces = trace(&trace_config)?;
Expand Down
Loading

0 comments on commit a2c7a12

Please sign in to comment.