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

Commit

Permalink
refactor: removed duplicated code between test_ctx and test_ctx2
Browse files Browse the repository at this point in the history
  • Loading branch information
KimiWu123 committed Oct 4, 2023
1 parent bc3e735 commit 5c8f0d8
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 199 deletions.
37 changes: 3 additions & 34 deletions mock/src/test_ctx.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
//! Mock types and functions to generate Test enviroments for ZKEVM tests
//! Mock types and functions to generate Test environments for ZKEVM tests
use crate::{eth, MockAccount, MockBlock, MockTransaction, TestContext2};
use eth_types::{
geth_types::{Account, BlockConstants, GethData},
Block, Bytecode, Error, GethExecTrace, Transaction, Word,
geth_types::{Account, GethData},
Bytecode, Error, Word,
};
use external_tracer::{trace, TraceConfig};
use helpers::*;

pub use external_tracer::LoggerConfig;
Expand Down Expand Up @@ -89,7 +88,6 @@ 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 Down Expand Up @@ -174,35 +172,6 @@ impl<const NACC: usize, const NTX: usize> TestContext<NACC, NTX> {
}
}

/// Generates execution traces for the transactions included in the provided
/// Block
pub fn gen_geth_traces(
chain_id: Word,
block: Block<Transaction>,
accounts: Vec<Account>,
history_hashes: Option<Vec<Word>>,
logger_config: LoggerConfig,
) -> Result<Vec<GethExecTrace>, Error> {
let trace_config = TraceConfig {
chain_id,
history_hashes: history_hashes.unwrap_or_default(),
block_constants: BlockConstants::try_from(&block)?,
accounts: accounts
.iter()
.map(|account| (account.address, account.clone()))
.collect(),
transactions: block
.transactions
.iter()
.map(eth_types::geth_types::Transaction::from)
.collect(),
withdrawals: vec![],
logger_config,
};
let traces = trace(&trace_config)?;
Ok(traces)
}

/// Collection of helper functions which contribute to specific rutines on the
/// builder pattern used to construct [`TestContext`]s.
pub mod helpers {
Expand Down
167 changes: 4 additions & 163 deletions mock/src/test_ctx2.rs
Original file line number Diff line number Diff line change
@@ -1,80 +1,17 @@
//! Mock types and functions to generate Test enviroments for ZKEVM tests
use crate::{eth, withdrawal::MockWithdrawal, MockAccount, MockBlock, MockTransaction};
use crate::{withdrawal::MockWithdrawal, MockAccount, MockBlock, MockTransaction};
use eth_types::{
geth_types::{Account, BlockConstants, GethData, Withdrawal},
Address, Block, Bytecode, Error, GethExecTrace, Transaction, Word, H160,
Block, Error, GethExecTrace, Transaction, Word,
};
use external_tracer::{trace, TraceConfig};
use helpers::*;
use itertools::Itertools;

pub use external_tracer::LoggerConfig;

/// TestContext2 is a type that contains all the information from a block
/// required to build the circuit inputs.
///
/// It is specifically used to generate Test cases with very precise information
/// details about any specific part of a block. That includes of course, its
/// transactions too and the accounts involved in all of them.
///
/// The intended way to interact with the structure is through the fn `new`
/// which is designed to return a [`GethData`] which then can be used to query
/// any specific part of the logs generated by the transactions executed within
/// this context.
///
/// ## Example
/// ```rust
/// use eth_types::evm_types::{stack::Stack, OpcodeId};
/// use eth_types::{address, bytecode, geth_types::GethData, word, Bytecode, ToWord, Word};
/// use lazy_static::lazy_static;
/// use mock::test_ctx::{helpers::*, TestContext2};
/// // code_a calls code
/// // jump to 0x10 which is outside the code (and also not marked with
/// // JUMPDEST)
/// let code = bytecode! {
/// PUSH1(0x10)
/// JUMP
/// STOP
/// };
/// let code_a = bytecode! {
/// PUSH1(0x0) // retLength
/// PUSH1(0x0) // retOffset
/// PUSH1(0x0) // argsLength
/// PUSH1(0x0) // argsOffset
/// PUSH32(address!("0x000000000000000000000000000000000cafe001").to_word()) // addr
/// PUSH32(0x1_0000) // gas
/// STATICCALL
/// PUSH2(0xaa)
/// };
/// let index = 8; // JUMP
///
/// // Get the execution steps from the external tracer
/// let block: GethData = TestContext2::<3, 2>::new(
/// None,
/// |accs| {
/// accs[0]
/// .address(address!("0x0000000000000000000000000000000000000000"))
/// .code(code_a);
/// accs[1].address(address!("0x000000000000000000000000000000000cafe001")).code(code);
/// accs[2]
/// .address(address!("0x000000000000000000000000000000000cafe002"))
/// .balance(Word::from(1u64 << 30));
/// },
/// |mut txs, accs| {
/// txs[0].to(accs[0].address).from(accs[2].address);
/// txs[1]
/// .to(accs[1].address)
/// .from(accs[2].address);
/// },
/// |block, _tx| block.number(0xcafeu64),
/// )
/// .unwrap()
/// .into();
///
/// // Now we can start generating the traces and items we need to inspect
/// // the behaviour of the generated env.
/// ```
/// TestContext2 is an extended struct of TestContext. For more details and usage, see TestContext
/// file.
#[derive(Debug, Clone)]
pub struct TestContext2<const NACC: usize, const NTX: usize, const NWD: usize> {
/// chain id
Expand Down Expand Up @@ -234,21 +171,6 @@ impl<const NACC: usize, const NTX: usize, const NWD: usize> TestContext2<NACC, N
LoggerConfig::default(),
)
}

/// Returns a simple TestContext2 setup with a single tx executing the
/// bytecode passed as parameters. The balances of the 2 accounts and
/// addresses are the ones used in [`TestContext2::
/// account_0_code_account_1_no_code`]. Extra accounts, txs and/or block
/// configs are set as [`Default`].
pub fn simple_ctx_with_bytecode(bytecode: Bytecode) -> Result<TestContext2<2, 1, 1>, Error> {
TestContext2::new(
None,
account_0_code_account_1_no_code(bytecode),
tx_from_1_to_0,
default_withdrawal,
|block, _txs| block,
)
}
}

/// Generates execution traces for the transactions included in the provided
Expand Down Expand Up @@ -280,84 +202,3 @@ pub fn gen_geth_traces(
let traces = trace(&trace_config)?;
Ok(traces)
}

/// Collection of helper functions which contribute to specific rutines on the
/// builder pattern used to construct [`TestContext2`]s.
pub mod helpers {
use super::*;
use crate::MOCK_ACCOUNTS;

/// Generate a simple setup which adds balance to two default accounts from
/// [`static@MOCK_ACCOUNTS`]:
/// - 0x000000000000000000000000000000000cafe111
/// - 0x000000000000000000000000000000000cafe222
/// And injects the provided bytecode into the first one.
pub fn account_0_code_account_1_no_code(code: Bytecode) -> impl FnOnce([&mut MockAccount; 2]) {
|accs| {
accs[0]
.address(MOCK_ACCOUNTS[0])
.balance(eth(10))
.code(code);
accs[1].address(MOCK_ACCOUNTS[1]).balance(eth(10));
}
}

/// Generate a single transaction from the second account of the list to the
/// first one.
pub fn tx_from_1_to_0(mut txs: Vec<&mut MockTransaction>, accs: [MockAccount; 2]) {
txs[0].from(accs[1].address).to(accs[0].address);
}

pub fn default_withdrawal(mut wds: Vec<&mut MockWithdrawal>) {
wds[0]
.id(0)
.validator_id(0)
.address(Address::random())
.amount(1e9 as u64);
}
}

#[cfg(test)]
mod tests {
use eth_types::{address, U256, U64};

use super::{eth, TestContext2};

#[test]
fn test_nonce() {
let block = TestContext2::<2, 5, 0>::new(
None,
|accs| {
accs[0]
.address(address!("0x0000000000000000000000000000000000000000"))
.balance(eth(10));
accs[1]
.address(address!("0x000000000000000000000000000000000cafe001"))
.balance(eth(10))
.nonce(100);
},
|mut txs, accs| {
txs[0].from(accs[0].address);
txs[1].from(accs[0].address);
txs[2].from(accs[1].address);
txs[3].from(accs[1].address);
txs[4].from(accs[1].address).nonce(12345); // set nonce here is ignored
},
|block, _tx| block.number(0xcafeu64),
)
.unwrap();

// account 0 starts with nonce default 0
assert_eq!(block.eth_block.transactions[0].nonce, U256::from(0));
assert_eq!(block.eth_block.transactions[1].nonce, U256::from(1));

// account 1 starts with nonce specified 100
assert_eq!(block.eth_block.transactions[2].nonce, U256::from(100));
assert_eq!(block.eth_block.transactions[3].nonce, U256::from(101));
assert_eq!(block.eth_block.transactions[4].nonce, U256::from(102)); // 12345 is ignored

// nonce in accounts is the nonce before the block processing
assert_eq!(block.accounts[0].nonce, U64::from(0));
assert_eq!(block.accounts[1].nonce, U64::from(100));
}
}
1 change: 0 additions & 1 deletion zkevm-circuits/src/pi_circuit/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,6 @@ fn test_1wd_1wdmax() {
.input(calldata.into())
.gas((1e16 as u64).into());
},
// |_|{},
|mut wds| {
wds[0]
.id(101)
Expand Down
3 changes: 2 additions & 1 deletion zkevm-circuits/tests/prover_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use eth_types::{
Block, Bytes, Error, Transaction, Word, H160, U256,
};
use halo2_proofs::{dev::MockProver, halo2curves::bn256::Fr};
use mock::test_ctx::{gen_geth_traces, LoggerConfig};
use mock::{test_ctx::LoggerConfig, test_ctx2::gen_geth_traces};
use serde_json::{from_value, Value};
use std::{collections::HashMap, fs::File, io::BufReader};
use zkevm_circuits::{super_circuit::SuperCircuit, util::SubCircuit, witness::block_convert};
Expand Down Expand Up @@ -75,6 +75,7 @@ fn prover_error() {
chain_id,
eth_block.clone(),
accounts.clone(),
vec![],
Some(history_hashes.clone()),
LoggerConfig::default(),
)
Expand Down

0 comments on commit 5c8f0d8

Please sign in to comment.