From 738cbc2e4e32e46a8f899506c184e77b11c12d68 Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Thu, 6 Jul 2023 23:28:06 +0800 Subject: [PATCH 01/27] clean up feature flags --- circuit-benchmarks/Cargo.toml | 2 +- integration-tests/Cargo.toml | 2 +- testool/Cargo.toml | 2 +- zkevm-circuits/Cargo.toml | 9 +++--- zkevm-circuits/src/bytecode_circuit.rs | 6 ++-- zkevm-circuits/src/bytecode_circuit/test.rs | 3 +- zkevm-circuits/src/copy_circuit.rs | 4 +-- zkevm-circuits/src/evm_circuit.rs | 9 +++--- zkevm-circuits/src/evm_circuit/test.rs | 11 +------ zkevm-circuits/src/exp_circuit.rs | 6 ++-- zkevm-circuits/src/exp_circuit/test.rs | 1 - zkevm-circuits/src/keccak_circuit.rs | 6 ++-- zkevm-circuits/src/keccak_circuit/test.rs | 1 - zkevm-circuits/src/lib.rs | 4 +-- zkevm-circuits/src/pi_circuit.rs | 11 +++---- zkevm-circuits/src/pi_circuit/dev.rs | 14 +++++++-- zkevm-circuits/src/pi_circuit/test.rs | 1 - zkevm-circuits/src/root_circuit.rs | 2 +- zkevm-circuits/src/root_circuit/test.rs | 1 - zkevm-circuits/src/state_circuit.rs | 14 ++++----- zkevm-circuits/src/state_circuit/dev.rs | 3 +- zkevm-circuits/src/state_circuit/lookups.rs | 34 +-------------------- zkevm-circuits/src/state_circuit/test.rs | 1 - zkevm-circuits/src/tx_circuit.rs | 6 ++-- zkevm-circuits/src/tx_circuit/test.rs | 1 - zkevm-circuits/src/util.rs | 2 +- 26 files changed, 57 insertions(+), 99 deletions(-) diff --git a/circuit-benchmarks/Cargo.toml b/circuit-benchmarks/Cargo.toml index cd3969407c..f8b6d7e410 100644 --- a/circuit-benchmarks/Cargo.toml +++ b/circuit-benchmarks/Cargo.toml @@ -9,7 +9,7 @@ license = "MIT OR Apache-2.0" [dependencies] halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2.git", tag = "v2023_04_20" } ark-std = { version = "0.3", features = ["print-trace"] } -zkevm-circuits = { path = "../zkevm-circuits", features = ["test"]} +zkevm-circuits = { path = "../zkevm-circuits", features = ["test-circuits"] } bus-mapping = { path = "../bus-mapping", features = ["test"] } rand_xorshift = "0.3" rand = "0.8" diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml index 6c3ab020d7..dc847e9f9d 100644 --- a/integration-tests/Cargo.toml +++ b/integration-tests/Cargo.toml @@ -13,7 +13,7 @@ serde_json = "1.0.66" serde = { version = "1.0.130", features = ["derive"] } bus-mapping = { path = "../bus-mapping" , features = ["test"] } eth-types = { path = "../eth-types" } -zkevm-circuits = { path = "../zkevm-circuits", features = ["test"] } +zkevm-circuits = { path = "../zkevm-circuits", features = ["test-circuits"] } tokio = { version = "1.13", features = ["macros", "rt-multi-thread"] } url = "2.2.2" pretty_assertions = "1.0.0" diff --git a/testool/Cargo.toml b/testool/Cargo.toml index 69a53a9af0..c842bc2543 100644 --- a/testool/Cargo.toml +++ b/testool/Cargo.toml @@ -29,7 +29,7 @@ strum_macros = "0.24" thiserror = "1.0" toml = "0.5" yaml-rust = "0.4.5" -zkevm-circuits = { path="../zkevm-circuits", features=["test"] } +zkevm-circuits = { path="../zkevm-circuits", features=["test-util"] } rand_chacha = "0.3" rand = "0.8" halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2.git", tag = "v2023_04_20" } diff --git a/zkevm-circuits/Cargo.toml b/zkevm-circuits/Cargo.toml index add6ba75ef..735facb71b 100644 --- a/zkevm-circuits/Cargo.toml +++ b/zkevm-circuits/Cargo.toml @@ -49,10 +49,11 @@ serde_json = "1.0.78" [features] default = [] -test = ["ethers-signers", "mock", "bus-mapping/test"] -test-circuits = [] -warn-unimplemented = ["eth-types/warn-unimplemented"] -stats = ["warn-unimplemented", "dep:cli-table"] +# We export some test circuits for other crates to consume +test-circuits = ["eth-types/warn-unimplemented"] +test-util = ["dep:mock"] + +stats = ["eth-types/warn-unimplemented", "dep:cli-table"] [[bin]] name = "stats" diff --git a/zkevm-circuits/src/bytecode_circuit.rs b/zkevm-circuits/src/bytecode_circuit.rs index 297e3a1622..ab810d6cbc 100644 --- a/zkevm-circuits/src/bytecode_circuit.rs +++ b/zkevm-circuits/src/bytecode_circuit.rs @@ -6,10 +6,10 @@ pub mod bytecode_unroller; pub mod circuit; pub(crate) mod param; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] +#[cfg(any(test, feature = "test-circuits"))] mod dev; /// Bytecode circuit tester -#[cfg(any(feature = "test", test))] +#[cfg(test)] mod test; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] +#[cfg(feature = "test-circuits")] pub use dev::BytecodeCircuit as TestBytecodeCircuit; diff --git a/zkevm-circuits/src/bytecode_circuit/test.rs b/zkevm-circuits/src/bytecode_circuit/test.rs index c765aec905..349b1544c1 100644 --- a/zkevm-circuits/src/bytecode_circuit/test.rs +++ b/zkevm-circuits/src/bytecode_circuit/test.rs @@ -1,8 +1,7 @@ -#![allow(unused_imports)] use crate::{ bytecode_circuit::{bytecode_unroller::*, circuit::BytecodeCircuit}, table::BytecodeFieldTag, - util::{is_push, keccak, unusable_rows, Challenges, SubCircuit}, + util::{is_push, keccak, unusable_rows, SubCircuit}, }; use bus_mapping::evm::OpcodeId; use eth_types::{Bytecode, Field, Word}; diff --git a/zkevm-circuits/src/copy_circuit.rs b/zkevm-circuits/src/copy_circuit.rs index d6fdafc375..08b4dd7b02 100644 --- a/zkevm-circuits/src/copy_circuit.rs +++ b/zkevm-circuits/src/copy_circuit.rs @@ -3,11 +3,11 @@ //! etc. pub(crate) mod util; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] +#[cfg(any(test, feature = "test-circuits"))] mod dev; #[cfg(test)] mod test; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] +#[cfg(feature = "test-circuits")] pub use dev::CopyCircuit as TestCopyCircuit; use bus_mapping::{ diff --git a/zkevm-circuits/src/evm_circuit.rs b/zkevm-circuits/src/evm_circuit.rs index d3bb3e4b2a..d3ea1a204c 100644 --- a/zkevm-circuits/src/evm_circuit.rs +++ b/zkevm-circuits/src/evm_circuit.rs @@ -12,10 +12,10 @@ pub mod step; pub mod table; pub(crate) mod util; -#[cfg(any(feature = "test", test))] +#[cfg(test)] pub(crate) mod test; use self::step::HasExecutionState; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] +#[cfg(feature = "test-circuits")] pub use self::EvmCircuit as TestEvmCircuit; pub use crate::witness; @@ -184,7 +184,8 @@ impl EvmCircuit { } } - pub fn new_dev(block: Block, fixed_table_tags: Vec) -> Self { + pub fn get_test_cicuit_from_block(block: Block) -> Self { + let fixed_table_tags = detect_fixed_table_tags(&block); Self { block: Some(block), fixed_table_tags, @@ -290,7 +291,7 @@ pub(crate) fn detect_fixed_table_tags(block: &Block) -> Vec() -> [u8; N] { pub(crate) fn rand_word() -> Word { Word::from_big_endian(&rand_bytes_array::<32>()) } - -impl EvmCircuit { - pub fn get_test_cicuit_from_block(block: Block) -> Self { - let fixed_table_tags = detect_fixed_table_tags(&block); - EvmCircuit::::new_dev(block, fixed_table_tags) - } -} diff --git a/zkevm-circuits/src/exp_circuit.rs b/zkevm-circuits/src/exp_circuit.rs index 8d108a9557..80a8173385 100644 --- a/zkevm-circuits/src/exp_circuit.rs +++ b/zkevm-circuits/src/exp_circuit.rs @@ -1,11 +1,11 @@ //! Exponentiation verification circuit. -#[cfg(any(feature = "test", test, feature = "test-circuits"))] +#[cfg(any(test, feature = "test-circuits"))] mod dev; pub(crate) mod param; -#[cfg(any(feature = "test", test))] +#[cfg(test)] mod test; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] +#[cfg(feature = "test-circuits")] pub use dev::ExpCircuit as TestExpCircuit; use crate::{ diff --git a/zkevm-circuits/src/exp_circuit/test.rs b/zkevm-circuits/src/exp_circuit/test.rs index 1c190231e8..5ff01c0e9f 100644 --- a/zkevm-circuits/src/exp_circuit/test.rs +++ b/zkevm-circuits/src/exp_circuit/test.rs @@ -1,4 +1,3 @@ -#![allow(unused_imports)] use crate::{ evm_circuit::witness::{block_convert, Block}, exp_circuit::ExpCircuit, diff --git a/zkevm-circuits/src/keccak_circuit.rs b/zkevm-circuits/src/keccak_circuit.rs index 9183b306c2..96a5c5fc22 100644 --- a/zkevm-circuits/src/keccak_circuit.rs +++ b/zkevm-circuits/src/keccak_circuit.rs @@ -7,11 +7,11 @@ mod table; /// Util mod util; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] +#[cfg(any(test, feature = "test-circuits"))] mod dev; -#[cfg(any(feature = "test", test))] +#[cfg(test)] mod test; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] +#[cfg(feature = "test-circuits")] pub use dev::KeccakCircuit as TestKeccakCircuit; use std::marker::PhantomData; diff --git a/zkevm-circuits/src/keccak_circuit/test.rs b/zkevm-circuits/src/keccak_circuit/test.rs index 9711f978d5..8e1a2ec598 100644 --- a/zkevm-circuits/src/keccak_circuit/test.rs +++ b/zkevm-circuits/src/keccak_circuit/test.rs @@ -1,4 +1,3 @@ -#![allow(unused_imports)] use super::*; use crate::util::unusable_rows; use eth_types::Field; diff --git a/zkevm-circuits/src/lib.rs b/zkevm-circuits/src/lib.rs index 0ced14d041..7ef25f232c 100644 --- a/zkevm-circuits/src/lib.rs +++ b/zkevm-circuits/src/lib.rs @@ -7,8 +7,6 @@ #![feature(adt_const_params)] // Needed by some builder patterns in testing modules. #![cfg_attr(docsrs, feature(doc_cfg))] -// Temporary until we have more of the crate implemented. -#![allow(dead_code)] // We want to have UPPERCASE idents sometimes. #![allow(clippy::upper_case_acronyms)] // Catch documentation errors caused by code changes. @@ -30,7 +28,7 @@ pub mod state_circuit; pub mod super_circuit; pub mod table; -#[cfg(any(feature = "test", test))] +#[cfg(feature = "test-util")] pub mod test_util; pub mod instance; diff --git a/zkevm-circuits/src/pi_circuit.rs b/zkevm-circuits/src/pi_circuit.rs index a6f380558b..c4e482b97a 100644 --- a/zkevm-circuits/src/pi_circuit.rs +++ b/zkevm-circuits/src/pi_circuit.rs @@ -1,14 +1,14 @@ //! Public Input Circuit implementation mod param; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] +#[cfg(any(test, feature = "test-circuits"))] mod dev; -#[cfg(any(feature = "test", test))] +#[cfg(test)] mod test; use std::{cmp::min, iter, marker::PhantomData}; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] -pub use dev::PiCircuit as TestPiCircuit; +#[cfg(feature = "test-circuits")] +pub use PiCircuit as TestPiCircuit; use eth_types::{self, Field, ToLittleEndian}; use halo2_proofs::plonk::{Expression, Instance, SecondPhase}; @@ -45,9 +45,6 @@ use halo2_proofs::{ poly::Rotation, }; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] -use halo2_proofs::{circuit::SimpleFloorPlanner, plonk::Circuit}; - /// Config for PiCircuit #[derive(Clone, Debug)] pub struct PiCircuitConfig { diff --git a/zkevm-circuits/src/pi_circuit/dev.rs b/zkevm-circuits/src/pi_circuit/dev.rs index 6a8033a07e..ad6ae3d1fc 100644 --- a/zkevm-circuits/src/pi_circuit/dev.rs +++ b/zkevm-circuits/src/pi_circuit/dev.rs @@ -1,5 +1,15 @@ -pub use super::PiCircuit; -use super::*; +use super::{PiCircuit, PiCircuitConfig, PiCircuitConfigArgs}; + +use eth_types::{self, Field}; + +use crate::{ + table::{BlockTable, KeccakTable, TxTable}, + util::{Challenges, SubCircuit, SubCircuitConfig}, +}; +use halo2_proofs::{ + circuit::{Layouter, SimpleFloorPlanner}, + plonk::{Circuit, ConstraintSystem, Error}, +}; /// Public Input Circuit configuration parameters #[derive(Default)] diff --git a/zkevm-circuits/src/pi_circuit/test.rs b/zkevm-circuits/src/pi_circuit/test.rs index 21cc929d46..f474a9c2ac 100644 --- a/zkevm-circuits/src/pi_circuit/test.rs +++ b/zkevm-circuits/src/pi_circuit/test.rs @@ -1,4 +1,3 @@ -#![allow(unused_imports)] use std::collections::HashMap; use crate::{pi_circuit::dev::PiCircuitParams, util::unusable_rows, witness::block_convert}; diff --git a/zkevm-circuits/src/root_circuit.rs b/zkevm-circuits/src/root_circuit.rs index ec51a01ccd..6915986a9e 100644 --- a/zkevm-circuits/src/root_circuit.rs +++ b/zkevm-circuits/src/root_circuit.rs @@ -25,7 +25,7 @@ mod aggregation; #[cfg(any(feature = "test", test))] mod test; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] +#[cfg(test)] pub use self::RootCircuit as TestRootCircuit; pub use aggregation::{ diff --git a/zkevm-circuits/src/root_circuit/test.rs b/zkevm-circuits/src/root_circuit/test.rs index 544fa5c92d..70a11bbf34 100644 --- a/zkevm-circuits/src/root_circuit/test.rs +++ b/zkevm-circuits/src/root_circuit/test.rs @@ -1,4 +1,3 @@ -#![allow(unused_imports)] use crate::{ root_circuit::{compile, Config, Gwc, PoseidonTranscript, RootCircuit}, super_circuit::{test::block_1tx, SuperCircuit}, diff --git a/zkevm-circuits/src/state_circuit.rs b/zkevm-circuits/src/state_circuit.rs index 38a72b27ae..f4d3e9d55c 100644 --- a/zkevm-circuits/src/state_circuit.rs +++ b/zkevm-circuits/src/state_circuit.rs @@ -5,12 +5,12 @@ mod lookups; mod multiple_precision_integer; mod param; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] +#[cfg(any(test, feature = "test-circuits"))] mod dev; -#[cfg(any(feature = "test", test))] +#[cfg(test)] mod test; use bus_mapping::operation::Target; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] +#[cfg(feature = "test-circuits")] pub use dev::StateCircuit as TestStateCircuit; use self::{ @@ -42,7 +42,7 @@ use multiple_precision_integer::{Chip as MpiChip, Config as MpiConfig, Queries a use param::*; use std::marker::PhantomData; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] +#[cfg(test)] use std::collections::HashMap; /// Config for StateCircuit @@ -436,7 +436,7 @@ pub struct StateCircuit { pub rows: Vec, updates: MptUpdates, pub(crate) n_rows: usize, - #[cfg(any(feature = "test", test, feature = "test-circuits"))] + #[cfg(test)] overrides: HashMap<(dev::AdviceColumn, isize), F>, _marker: PhantomData, } @@ -450,7 +450,7 @@ impl StateCircuit { rows, updates, n_rows, - #[cfg(any(feature = "test", test, feature = "test-circuits"))] + #[cfg(test)] overrides: HashMap::new(), _marker: PhantomData::default(), } @@ -498,7 +498,7 @@ impl SubCircuit for StateCircuit { .load_with_region(&mut region, &self.rows, self.n_rows)?; config.assign_with_region(&mut region, &self.rows, &self.updates, self.n_rows)?; - #[cfg(any(feature = "test", test, feature = "test-circuits"))] + #[cfg(test)] { let first_non_padding_index = if self.rows.len() < self.n_rows { RwMap::padding_len(self.rows.len(), self.n_rows) diff --git a/zkevm-circuits/src/state_circuit/dev.rs b/zkevm-circuits/src/state_circuit/dev.rs index 8799610f45..6110b3d814 100644 --- a/zkevm-circuits/src/state_circuit/dev.rs +++ b/zkevm-circuits/src/state_circuit/dev.rs @@ -1,9 +1,8 @@ -use super::test::UXTable; pub use super::StateCircuit; use crate::{ state_circuit::{StateCircuitConfig, StateCircuitConfigArgs}, - table::{MptTable, RwTable}, + table::{MptTable, RwTable, UXTable}, util::{Challenges, SubCircuit, SubCircuitConfig}, }; use eth_types::Field; diff --git a/zkevm-circuits/src/state_circuit/lookups.rs b/zkevm-circuits/src/state_circuit/lookups.rs index 7bc77126dc..83297636f3 100644 --- a/zkevm-circuits/src/state_circuit/lookups.rs +++ b/zkevm-circuits/src/state_circuit/lookups.rs @@ -1,4 +1,4 @@ -use crate::table::CallContextFieldTag; +use crate::table::{CallContextFieldTag, LookupTable, UXTable}; use eth_types::Field; use halo2_proofs::{ circuit::{Layouter, Value}, @@ -9,8 +9,6 @@ use itertools::Itertools; use std::marker::PhantomData; use strum::IntoEnumIterator; -use super::test::{LookupTable, UXTable}; - #[derive(Clone, Copy, Debug)] pub struct Config { // Can these be TableColumn's? @@ -22,36 +20,6 @@ pub struct Config { } impl Config { - pub fn range_check_u8( - &self, - meta: &mut ConstraintSystem, - msg: &'static str, - exp_fn: impl FnOnce(&mut VirtualCells<'_, F>) -> Expression, - ) { - meta.lookup_any(msg, |meta| { - let exp = exp_fn(meta); - vec![exp] - .into_iter() - .zip_eq(self.u8_table.table_exprs(meta)) - .map(|(exp, table_expr)| (exp, table_expr)) - .collect() - }); - } - pub fn range_check_u10( - &self, - meta: &mut ConstraintSystem, - msg: &'static str, - exp_fn: impl FnOnce(&mut VirtualCells<'_, F>) -> Expression, - ) { - meta.lookup_any(msg, |meta| { - let exp = exp_fn(meta); - vec![exp] - .into_iter() - .zip_eq(self.u10_table.table_exprs(meta)) - .map(|(exp, table_expr)| (exp, table_expr)) - .collect() - }); - } pub fn range_check_u16( &self, meta: &mut ConstraintSystem, diff --git a/zkevm-circuits/src/state_circuit/test.rs b/zkevm-circuits/src/state_circuit/test.rs index 49d25454cf..624844d937 100644 --- a/zkevm-circuits/src/state_circuit/test.rs +++ b/zkevm-circuits/src/state_circuit/test.rs @@ -1,4 +1,3 @@ -#![allow(unused_imports)] pub use super::{dev::*, *}; use crate::{ table::{AccountFieldTag, CallContextFieldTag, TxLogFieldTag, TxReceiptFieldTag}, diff --git a/zkevm-circuits/src/tx_circuit.rs b/zkevm-circuits/src/tx_circuit.rs index 05fe175cad..3c2f2e5191 100644 --- a/zkevm-circuits/src/tx_circuit.rs +++ b/zkevm-circuits/src/tx_circuit.rs @@ -6,11 +6,11 @@ pub mod sign_verify; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] +#[cfg(any(test, feature = "test-circuits"))] mod dev; -#[cfg(any(feature = "test", test))] +#[cfg(test)] mod test; -#[cfg(any(feature = "test", test, feature = "test-circuits"))] +#[cfg(feature = "test-circuits")] pub use dev::TxCircuit as TestTxCircuit; use crate::{ diff --git a/zkevm-circuits/src/tx_circuit/test.rs b/zkevm-circuits/src/tx_circuit/test.rs index 102b32c11d..ba8bf70682 100644 --- a/zkevm-circuits/src/tx_circuit/test.rs +++ b/zkevm-circuits/src/tx_circuit/test.rs @@ -1,4 +1,3 @@ -#![allow(unused_imports)] use super::*; use crate::util::{log2_ceil, unusable_rows}; use eth_types::address; diff --git a/zkevm-circuits/src/util.rs b/zkevm-circuits/src/util.rs index 96b9b70cee..5303e33308 100644 --- a/zkevm-circuits/src/util.rs +++ b/zkevm-circuits/src/util.rs @@ -48,7 +48,7 @@ pub struct Challenges { impl Challenges { /// Construct `Challenges` by allocating challenges in specific phases. pub fn construct(meta: &mut ConstraintSystem) -> Self { - #[cfg(any(feature = "test", test, feature = "test-circuits"))] + #[cfg(any(test, feature = "test-circuits"))] let _dummy_cols = [meta.advice_column(), meta.advice_column_in(SecondPhase)]; Self { From b008a565ba4b4e63a877c0c3bb119cb8ac59730e Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Thu, 6 Jul 2023 23:39:52 +0800 Subject: [PATCH 02/27] rm dead code to a degree that still build --- zkevm-circuits/src/util.rs | 6 +---- zkevm-circuits/src/util/cell_manager.rs | 2 ++ .../src/util/cell_manager_strategy.rs | 4 ++- zkevm-circuits/src/util/word.rs | 25 ------------------- zkevm-circuits/src/witness/block.rs | 2 ++ zkevm-circuits/src/witness/rw.rs | 11 -------- 6 files changed, 8 insertions(+), 42 deletions(-) diff --git a/zkevm-circuits/src/util.rs b/zkevm-circuits/src/util.rs index 5303e33308..5215c1a97d 100644 --- a/zkevm-circuits/src/util.rs +++ b/zkevm-circuits/src/util.rs @@ -11,7 +11,7 @@ use halo2_proofs::{ }, }; -use crate::{evm_circuit::util::rlc, table::TxLogFieldTag, witness}; +use crate::{table::TxLogFieldTag, witness}; use eth_types::{keccak256, Field, ToAddress, Word}; pub use ethers_core::types::{Address, U256}; pub use gadgets::util::Expr; @@ -34,10 +34,6 @@ pub fn query_expression( expr.unwrap() } -pub(crate) fn random_linear_combine_word(bytes: [u8; 32], randomness: F) -> F { - rlc::value(&bytes, randomness) -} - /// All challenges used in `SuperCircuit`. #[derive(Default, Clone, Copy, Debug)] pub struct Challenges { diff --git a/zkevm-circuits/src/util/cell_manager.rs b/zkevm-circuits/src/util/cell_manager.rs index 0f8985530e..110999eec4 100644 --- a/zkevm-circuits/src/util/cell_manager.rs +++ b/zkevm-circuits/src/util/cell_manager.rs @@ -1,3 +1,5 @@ +// Temporarly allow dead code before the strategy is fully implemented +#![allow(dead_code)] use std::collections::HashMap; use eth_types::Field; diff --git a/zkevm-circuits/src/util/cell_manager_strategy.rs b/zkevm-circuits/src/util/cell_manager_strategy.rs index a4330f0e4e..5097e7fd83 100644 --- a/zkevm-circuits/src/util/cell_manager_strategy.rs +++ b/zkevm-circuits/src/util/cell_manager_strategy.rs @@ -1,3 +1,5 @@ +// Temporarly allow dead code before the strategy is fully implemented +#![allow(dead_code)] use std::collections::{BTreeMap, HashMap}; use eth_types::Field; @@ -190,7 +192,7 @@ pub(crate) struct CMFixedHeigthStrategy { } impl CMFixedHeigthStrategy { - pub fn new(height: usize, cell_type: CellType) -> CMFixedHeigthStrategy { + pub(crate) fn new(height: usize, cell_type: CellType) -> CMFixedHeigthStrategy { CMFixedHeigthStrategy { row_width: vec![0; height], cell_type, diff --git a/zkevm-circuits/src/util/word.rs b/zkevm-circuits/src/util/word.rs index 9c2072a588..25747cf59a 100644 --- a/zkevm-circuits/src/util/word.rs +++ b/zkevm-circuits/src/util/word.rs @@ -81,31 +81,6 @@ pub trait WordExpr { } impl WordLimbs, N> { - /// assign limbs - /// N1 is number of bytes to assign, while N is number of limbs. - /// N1 % N = 0 (also implies N1 >= N, assuming N1 and N are not 0) - /// If N1 > N, then N1 will be chunk into N1 / N size then aggregate to single expression - /// then assign to N limbs respectively. - /// e.g. N1 = 4 bytes, [b1, b2, b3, b4], and N = 2 limbs [l1, l2] - /// It equivalent `l1.assign(b1.expr() + b2.expr * F(256))`, `l2.assign(b3.expr() + b4.expr * - /// F(256))` - fn assign( - &self, - region: &mut CachedRegion<'_, '_, F>, - offset: usize, - bytes: Option<[u8; N1]>, - ) -> Result>, Error> { - assert_eq!(N1 % N, 0); // TODO assure N|N1, find way to use static_assertion instead - bytes.map_or(Err(Error::Synthesis), |bytes| { - bytes - .chunks(N1 / N) // chunk in little endian - .map(|chunk| from_bytes::value(chunk)) - .zip(self.limbs.iter()) - .map(|(value, cell)| cell.assign(region, offset, Value::known(value))) - .collect() - }) - } - /// assign bytes to wordlimbs first half/second half respectively // N_LO, N_HI are number of bytes to assign to first half and second half of size N limbs, // respectively N_LO and N_HI can be different size, the only requirement is N_LO % (N/2) diff --git a/zkevm-circuits/src/witness/block.rs b/zkevm-circuits/src/witness/block.rs index 854516eba0..fcfc578544 100644 --- a/zkevm-circuits/src/witness/block.rs +++ b/zkevm-circuits/src/witness/block.rs @@ -55,6 +55,8 @@ pub struct Block { } impl Block { + // This function is useful for debug so we allow it as a deadcode + #[allow(dead_code)] /// For each tx, for each step, print the rwc at the beginning of the step, /// and all the rw operations of the step. pub(crate) fn debug_print_txs_steps_rw_ops(&self) { diff --git a/zkevm-circuits/src/witness/rw.rs b/zkevm-circuits/src/witness/rw.rs index ba42de0871..c07853ac0c 100644 --- a/zkevm-circuits/src/witness/rw.rs +++ b/zkevm-circuits/src/witness/rw.rs @@ -295,10 +295,6 @@ impl RwRow { .rev() .fold(F::ZERO, |acc, value| acc * randomness + value) } - - pub(crate) fn rlc_value(&self, randomness: Value) -> Value { - randomness.map(|randomness| self.rlc(randomness)) - } } impl RwRow> { @@ -403,13 +399,6 @@ impl Rw { } } - pub(crate) fn log_value(&self) -> Word { - match self { - Self::TxLog { value, .. } => *value, - _ => unreachable!(), - } - } - pub(crate) fn receipt_value(&self) -> u64 { match self { Self::TxReceipt { value, .. } => *value, From be33f678a53781700f942404ee2ca3cea2915eeb Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Thu, 6 Jul 2023 23:54:43 +0800 Subject: [PATCH 03/27] some more dead code --- .../src/evm_circuit/util/math_gadget.rs | 1 - .../util/math_gadget/min_max_word.rs | 197 ------------------ zkevm-circuits/src/keccak_circuit/param.rs | 9 - zkevm-circuits/src/keccak_circuit/table.rs | 4 - zkevm-circuits/src/state_circuit/dev.rs | 10 +- zkevm-circuits/src/tx_circuit/sign_verify.rs | 14 -- 6 files changed, 7 insertions(+), 228 deletions(-) delete mode 100644 zkevm-circuits/src/evm_circuit/util/math_gadget/min_max_word.rs diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget.rs index 17ec3799d3..3275596609 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget.rs @@ -17,7 +17,6 @@ mod is_zero_word; mod lt; mod lt_word; mod min_max; -mod min_max_word; mod modulo; mod mul_add_words; mod mul_add_words512; diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/min_max_word.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/min_max_word.rs deleted file mode 100644 index 00e0fbdd0c..0000000000 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/min_max_word.rs +++ /dev/null @@ -1,197 +0,0 @@ -use crate::{ - evm_circuit::util::{constraint_builder::EVMConstraintBuilder, CachedRegion}, - util::word::Word, -}; -use eth_types::{self, Field}; -use halo2_proofs::plonk::{Error, Expression}; - -use super::LtWordGadget; -/// Returns `rhs` when `lhs < rhs`, and returns `lhs` otherwise. -/// lhs and rhs `< 256**N_BYTES` -/// `N_BYTES` is required to be `<= MAX_N_BYTES_INTEGER`. -#[derive(Clone, Debug)] -pub struct MinMaxWordGadget { - lt: LtWordGadget, - min: Word>, - max: Word>, -} - -impl MinMaxWordGadget { - pub(crate) fn construct( - cb: &mut EVMConstraintBuilder, - lhs: &Word>, - rhs: &Word>, - ) -> Self { - let lt = LtWordGadget::construct(cb, lhs, rhs); - let max = Word::select(lt.expr(), rhs.clone(), lhs.clone()); - let min = Word::select(lt.expr(), lhs.clone(), rhs.clone()); - - Self { lt, min, max } - } - - pub(crate) fn min(&self) -> Word> { - self.min.clone() - } - - pub(crate) fn max(&self) -> Word> { - self.max.clone() - } - - fn assign( - &self, - region: &mut CachedRegion<'_, '_, F>, - offset: usize, - lhs: eth_types::Word, - rhs: eth_types::Word, - ) -> Result<(), Error> { - self.lt.assign(region, offset, lhs, rhs)?; - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use crate::evm_circuit::util::{ - constraint_builder::{ConstrainBuilderCommon, EVMConstraintBuilder}, - math_gadget::{ - test_util::{try_test, MathGadgetContainer, WORD_LOW_MAX}, - MinMaxGadget, - }, - CachedRegion, Cell, - }; - - use super::{super::test_util::*, *}; - use eth_types::{Field, ToScalar, Word}; - use gadgets::util::Expr; - use halo2_proofs::{circuit::Value, halo2curves::bn256::Fr, plonk::Error}; - - #[derive(Clone)] - /// MinMaxTestContainer: require(min(a, b) == (a if MIN_IS_A else b)) - struct MinMaxTestContainer { - minmax_gadget: MinMaxGadget, - a: Cell, - b: Cell, - } - - impl MathGadgetContainer - for MinMaxTestContainer - { - fn configure_gadget_container(cb: &mut EVMConstraintBuilder) -> Self { - let a = cb.query_cell(); - let b = cb.query_cell(); - let minmax_gadget = MinMaxGadget::::construct(cb, a.expr(), b.expr()); - - if MIN_IS_A { - cb.require_equal("min == a", minmax_gadget.min(), a.expr()); - cb.require_equal("max == b", minmax_gadget.max(), b.expr()); - } else { - cb.require_equal("min == b", minmax_gadget.min(), b.expr()); - cb.require_equal("max == a", minmax_gadget.max(), a.expr()); - } - - MinMaxTestContainer { - minmax_gadget, - a, - b, - } - } - - fn assign_gadget_container( - &self, - witnesses: &[Word], - region: &mut CachedRegion<'_, '_, F>, - ) -> Result<(), Error> { - let a = witnesses[0].to_scalar().unwrap(); - let b = witnesses[1].to_scalar().unwrap(); - let offset = 0; - - self.a.assign(region, offset, Value::known(a))?; - self.b.assign(region, offset, Value::known(b))?; - self.minmax_gadget.assign(region, offset, a, b)?; - - Ok(()) - } - } - - #[test] - fn test_minmax_eq() { - // a == b - try_test!( - MinMaxTestContainer, - vec![Word::from(0), Word::from(0)], - true, - ); - try_test!( - MinMaxTestContainer, - vec![Word::from(5), Word::from(5)], - true, - ); - try_test!( - MinMaxTestContainer, - vec![WORD_LOW_MAX, WORD_LOW_MAX], - true, - ); - } - - #[test] - fn test_minmax_expect_min_a() { - // min == a, max == b - try_test!( - MinMaxTestContainer, - vec![Word::from(0), Word::from(1)], - true, - ); - try_test!( - MinMaxTestContainer, - vec![Word::from(3), Word::from(5)], - true, - ); - try_test!( - MinMaxTestContainer, - vec![WORD_LOW_MAX, WORD_LOW_MAX], - true, - ); - } - - #[test] - fn test_minmax_unexpect_min_a() { - // min == b, max == a - try_test!( - MinMaxTestContainer, - vec![Word::from(1), Word::from(0)], - false, - ); - try_test!( - MinMaxTestContainer, - vec![Word::from(256), Word::from(3)], - false, - ); - try_test!( - MinMaxTestContainer, - vec![WORD_LOW_MAX, Word::from(123456)], - false, - ); - } - - #[test] - fn test_minmax_expect_min_b() { - // min == a, max == b - try_test!( - MinMaxTestContainer, - vec![Word::from(1), Word::from(0)], - true, - ); - - try_test!( - MinMaxTestContainer, - vec![Word::from(777), Word::from(44)], - true, - ); - - try_test!( - MinMaxTestContainer, - vec![WORD_LOW_MAX+1, WORD_LOW_MAX], - true, - ); - } -} diff --git a/zkevm-circuits/src/keccak_circuit/param.rs b/zkevm-circuits/src/keccak_circuit/param.rs index 847c10e8e6..504229b49a 100644 --- a/zkevm-circuits/src/keccak_circuit/param.rs +++ b/zkevm-circuits/src/keccak_circuit/param.rs @@ -8,16 +8,11 @@ pub(crate) const CHI_BASE_LOOKUP_RANGE: usize = 5; pub(crate) const NUM_BITS_PER_BYTE: usize = 8; pub(crate) const NUM_BYTES_PER_WORD: usize = 8; pub(crate) const NUM_BITS_PER_WORD: usize = NUM_BYTES_PER_WORD * NUM_BITS_PER_BYTE; -pub(crate) const KECCAK_WIDTH: usize = 5 * 5; -pub(crate) const KECCAK_WIDTH_IN_BITS: usize = KECCAK_WIDTH * NUM_BITS_PER_WORD; pub(crate) const NUM_ROUNDS: usize = 24; pub(crate) const NUM_WORDS_TO_ABSORB: usize = 17; pub(crate) const NUM_WORDS_TO_SQUEEZE: usize = 4; -pub(crate) const ABSORB_WIDTH_PER_ROW: usize = NUM_BITS_PER_WORD; -pub(crate) const ABSORB_WIDTH_PER_ROW_BYTES: usize = ABSORB_WIDTH_PER_ROW / NUM_BITS_PER_BYTE; pub(crate) const RATE: usize = NUM_WORDS_TO_ABSORB * NUM_BYTES_PER_WORD; pub(crate) const RATE_IN_BITS: usize = RATE * NUM_BITS_PER_BYTE; -pub(crate) const THETA_C_WIDTH: usize = 5 * NUM_BITS_PER_WORD; pub(crate) const RHO_MATRIX: [[usize; 5]; 5] = [ [0, 36, 3, 41, 18], [1, 44, 10, 45, 2], @@ -52,8 +47,6 @@ pub(crate) const ROUND_CST: [u64; NUM_ROUNDS + 1] = [ 0x8000000080008008, 0x0000000000000000, // absorb round ]; -// Bit positions that have a non-zero value in `IOTA_ROUND_CST`. -pub(crate) const ROUND_CST_BIT_POS: [usize; 7] = [0, 1, 3, 7, 15, 31, 63]; // The number of bits used in the sparse word representation per bit pub(crate) const BIT_COUNT: usize = 3; @@ -62,5 +55,3 @@ pub(crate) const BIT_SIZE: usize = 2usize.pow(BIT_COUNT as u32); // `a ^ ((~b) & c)` is calculated by doing `lookup[3 - 2*a + b - c]` pub(crate) const CHI_BASE_LOOKUP_TABLE: [u8; 5] = [0, 1, 1, 0, 0]; -// `a ^ ((~b) & c) ^ d` is calculated by doing `lookup[5 - 2*a - b + c - 2*d]` -pub(crate) const CHI_EXT_LOOKUP_TABLE: [u8; 7] = [0, 0, 1, 1, 0, 0, 1]; diff --git a/zkevm-circuits/src/keccak_circuit/table.rs b/zkevm-circuits/src/keccak_circuit/table.rs index 5ab2fc5e23..d86813b9d3 100644 --- a/zkevm-circuits/src/keccak_circuit/table.rs +++ b/zkevm-circuits/src/keccak_circuit/table.rs @@ -172,10 +172,6 @@ mod tests { CHI_BASE_LOOKUP_TABLE[3 - 2 * a + b - c], (a ^ ((!b) & c)) as u8 ); - assert_eq!( - CHI_EXT_LOOKUP_TABLE[5 - 2 * a - b + c - 2 * d], - (a ^ ((!b) & c) ^ d) as u8 - ); } // Check the table with multiple parts per row. diff --git a/zkevm-circuits/src/state_circuit/dev.rs b/zkevm-circuits/src/state_circuit/dev.rs index 6110b3d814..b3d0dcfa99 100644 --- a/zkevm-circuits/src/state_circuit/dev.rs +++ b/zkevm-circuits/src/state_circuit/dev.rs @@ -8,7 +8,7 @@ use crate::{ use eth_types::Field; use halo2_proofs::{ circuit::{Layouter, SimpleFloorPlanner}, - plonk::{Advice, Circuit, Column, ConstraintSystem, Error}, + plonk::{Circuit, ConstraintSystem, Error}, }; impl Circuit for StateCircuit @@ -63,8 +63,11 @@ where } } +// allow dead code for unconstructed variants +#[allow(dead_code)] +#[cfg(test)] #[derive(Hash, Eq, PartialEq, Clone, Debug)] -pub enum AdviceColumn { +pub(crate) enum AdviceColumn { IsWrite, Address, AddressLimb0, @@ -98,8 +101,9 @@ pub enum AdviceColumn { NonEmptyWitness, } +#[cfg(test)] impl AdviceColumn { - pub fn value(&self, config: &StateCircuitConfig) -> Column { + pub(crate) fn value(&self, config: &StateCircuitConfig) -> Column { match self { Self::IsWrite => config.rw_table.is_write, Self::Address => config.rw_table.address, diff --git a/zkevm-circuits/src/tx_circuit/sign_verify.rs b/zkevm-circuits/src/tx_circuit/sign_verify.rs index 4a23301f23..a9e436c844 100644 --- a/zkevm-circuits/src/tx_circuit/sign_verify.rs +++ b/zkevm-circuits/src/tx_circuit/sign_verify.rs @@ -248,10 +248,6 @@ impl SignVerifyConfig { pub(crate) fn ecc_chip_config(&self) -> EccConfig { EccConfig::new(self.range_config.clone(), self.main_gate_config.clone()) } - - pub(crate) fn integer_chip_config(&self) -> IntegerConfig { - IntegerConfig::new(self.range_config.clone(), self.main_gate_config.clone()) - } } /// Term provides a wrapper of possible assigned cell with value or unassigned @@ -273,10 +269,6 @@ impl Term { Self::Assigned(cell, value) } - fn unassigned(value: Value) -> Self { - Self::Unassigned(value) - } - fn cell(&self) -> Option { match self { Self::Assigned(cell, _) => Some(*cell), @@ -720,12 +712,6 @@ impl SignVerifyChip { } } -fn pub_key_hash_to_address(pk_hash: &[u8]) -> F { - pk_hash[32 - 20..] - .iter() - .fold(F::ZERO, |acc, b| acc * F::from(256) + F::from(*b as u64)) -} - #[cfg(test)] mod sign_verify_tests { use super::*; From f33f1e256bf3675a419908b18d1c5eefa6bee2f0 Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Thu, 6 Jul 2023 23:56:42 +0800 Subject: [PATCH 04/27] bytecode circuit params --- zkevm-circuits/src/bytecode_circuit.rs | 1 - zkevm-circuits/src/bytecode_circuit/circuit.rs | 7 +++---- zkevm-circuits/src/bytecode_circuit/param.rs | 3 --- zkevm-circuits/src/evm_circuit/util/memory_gadget.rs | 2 -- 4 files changed, 3 insertions(+), 10 deletions(-) delete mode 100644 zkevm-circuits/src/bytecode_circuit/param.rs diff --git a/zkevm-circuits/src/bytecode_circuit.rs b/zkevm-circuits/src/bytecode_circuit.rs index ab810d6cbc..97ce348718 100644 --- a/zkevm-circuits/src/bytecode_circuit.rs +++ b/zkevm-circuits/src/bytecode_circuit.rs @@ -4,7 +4,6 @@ pub mod bytecode_unroller; /// Bytecode circuit pub mod circuit; -pub(crate) mod param; #[cfg(any(test, feature = "test-circuits"))] mod dev; diff --git a/zkevm-circuits/src/bytecode_circuit/circuit.rs b/zkevm-circuits/src/bytecode_circuit/circuit.rs index 5b78de6b74..cae9ec27c4 100644 --- a/zkevm-circuits/src/bytecode_circuit/circuit.rs +++ b/zkevm-circuits/src/bytecode_circuit/circuit.rs @@ -25,10 +25,9 @@ use halo2_proofs::{ use log::trace; use std::vec; -use super::{ - bytecode_unroller::{unroll, UnrolledBytecode}, - param::PUSH_TABLE_WIDTH, -}; +use super::bytecode_unroller::{unroll, UnrolledBytecode}; + +const PUSH_TABLE_WIDTH: usize = 2; #[derive(Debug, Clone, Default)] /// Row for assignment diff --git a/zkevm-circuits/src/bytecode_circuit/param.rs b/zkevm-circuits/src/bytecode_circuit/param.rs deleted file mode 100644 index d23f281759..0000000000 --- a/zkevm-circuits/src/bytecode_circuit/param.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub const HASH_WIDTH: usize = 32; -pub const KECCAK_WIDTH: usize = 3; -pub const PUSH_TABLE_WIDTH: usize = 2; diff --git a/zkevm-circuits/src/evm_circuit/util/memory_gadget.rs b/zkevm-circuits/src/evm_circuit/util/memory_gadget.rs index c18c5f27bd..f8df9e7eb3 100644 --- a/zkevm-circuits/src/evm_circuit/util/memory_gadget.rs +++ b/zkevm-circuits/src/evm_circuit/util/memory_gadget.rs @@ -339,8 +339,6 @@ pub(crate) struct MemoryCopierGasGadget { } impl MemoryCopierGasGadget { - pub const WORD_SIZE: u64 = 32u64; - /// Input requirements: /// - `curr_memory_size < 256**MAX_MEMORY_SIZE_IN_BYTES` /// - `address < 32 * 256**MAX_MEMORY_SIZE_IN_BYTES` From 967ce0aeb80166dba762a3244653f14c4dc31246 Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Fri, 7 Jul 2023 00:04:00 +0800 Subject: [PATCH 05/27] rm more to a degree no break --- .../evm_circuit/util/constraint_builder.rs | 46 +-------------- .../src/keccak_circuit/cell_manager.rs | 12 ---- zkevm-circuits/src/keccak_circuit/util.rs | 34 ----------- zkevm-circuits/src/pi_circuit/param.rs | 3 - zkevm-circuits/src/state_circuit.rs | 2 - .../src/state_circuit/constraint_builder.rs | 56 ------------------- zkevm-circuits/src/state_circuit/dev.rs | 3 + zkevm-circuits/src/util/word.rs | 2 - 8 files changed, 4 insertions(+), 154 deletions(-) diff --git a/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs b/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs index 348a0a801c..4872d2dff4 100644 --- a/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs +++ b/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs @@ -11,7 +11,7 @@ use crate::{ }, util::{ build_tx_log_expression, query_expression, - word::{Word, Word16, Word32, Word32Cell, Word4, WordCell, WordExpr, WordLimbs}, + word::{Word, Word32, Word32Cell, WordCell, WordExpr}, Challenges, Expr, }, }; @@ -388,10 +388,6 @@ impl<'a, F: Field> EVMConstraintBuilder<'a, F> { ) } - pub(crate) fn get_cs(&'a mut self) -> &'a mut ConstraintSystem { - self.meta - } - pub(crate) fn query_expression(&mut self, f: impl FnMut(&mut VirtualCells) -> T) -> T { query_expression(self.meta, f) } @@ -417,18 +413,10 @@ impl<'a, F: Field> EVMConstraintBuilder<'a, F> { self.rw_counter_offset.clone() } - pub(crate) fn program_counter_offset(&self) -> usize { - self.program_counter_offset - } - pub(crate) fn stack_pointer_offset(&self) -> Expression { self.stack_pointer_offset.clone() } - pub(crate) fn log_id_offset(&self) -> usize { - self.log_id_offset - } - // Query pub(crate) fn copy>(&mut self, value: E) -> Cell { @@ -456,38 +444,6 @@ impl<'a, F: Field> EVMConstraintBuilder<'a, F> { ) } - // default query_word is 2 limbs. constrain word equality with external word - pub fn query_word( - &mut self, - w_constrain: WordLimbs, N2>, - ) -> Word> { - let word = Word::new( - self.query_cells(CellType::StoragePhase1, N) - .try_into() - .unwrap(), - ); - self.require_equal_word( - "word limbs equality constrain", - word.to_word(), - w_constrain.to_word(), - ); - word - } - - /// query_word4_unchecked get word with 4 limbs. Each limb is not guaranteed to be 64 bits. - pub fn query_word4_unchecked(&mut self) -> Word4> { - Word4::new( - self.query_cells(CellType::StoragePhase1, N) - .try_into() - .unwrap(), - ) - } - - // each limb is 16 bits, and any conversion to smaller limbs inherits the type check. - pub(crate) fn query_word16(&mut self) -> Word16> { - Word16::new(self.query_u16()) - } - // query_word32 each limb is 8 bits, and any conversion to smaller limbs inherits the type // check. pub(crate) fn query_word32(&mut self) -> Word32Cell { diff --git a/zkevm-circuits/src/keccak_circuit/cell_manager.rs b/zkevm-circuits/src/keccak_circuit/cell_manager.rs index 0706ac93a7..ffd9d981ee 100644 --- a/zkevm-circuits/src/keccak_circuit/cell_manager.rs +++ b/zkevm-circuits/src/keccak_circuit/cell_manager.rs @@ -1,8 +1,6 @@ -use crate::keccak_circuit::util::extract_field; use eth_types::Field; use gadgets::util::Expr; use halo2_proofs::{ - circuit::Value, plonk::{Advice, Column, ConstraintSystem, Expression, VirtualCells}, poly::Rotation, }; @@ -63,16 +61,6 @@ impl Cell { pub(crate) fn assign(&self, region: &mut KeccakRegion, offset: i32, value: F) { region.assign(self.column_idx, (offset + self.rotation) as usize, value); } - - pub(crate) fn assign_value(&self, region: &mut KeccakRegion, offset: i32, value: Value) { - // This is really ugly. But since there's no way to easily adapt the CellManager - // API customized for this impl specifically, for now I'm opening the - // value and extracting it. Once https://github.com/privacy-scaling-explorations/zkevm-circuits/issues/933 is resolved, - // this shouldn't be needed. - let value_f = extract_field(value); - - region.assign(self.column_idx, (offset + self.rotation) as usize, value_f); - } } impl Expr for Cell { diff --git a/zkevm-circuits/src/keccak_circuit/util.rs b/zkevm-circuits/src/keccak_circuit/util.rs index 48b819046e..c2e7ce688a 100644 --- a/zkevm-circuits/src/keccak_circuit/util.rs +++ b/zkevm-circuits/src/keccak_circuit/util.rs @@ -80,13 +80,6 @@ pub(crate) fn rotate_rev(parts: Vec, count: usize, part_size: usize) -> Ve rotated_parts } -/// Rotates bits left -pub(crate) fn rotate_left(bits: &[u8], count: usize) -> [u8; NUM_BITS_PER_WORD] { - let mut rotated = bits.to_vec(); - rotated.rotate_left(count); - rotated.try_into().unwrap() -} - /// The words that absorb data pub(crate) fn get_absorb_positions() -> Vec<(usize, usize)> { let mut absorb_positions = Vec::new(); @@ -233,15 +226,6 @@ pub(crate) fn get_num_bits_per_lookup_impl(range: usize, log_height: usize) -> u num_bits as usize } -pub(crate) fn extract_field(value: Value) -> F { - let mut field = F::ZERO; - let _ = value.map(|f| { - field = f; - f - }); - field -} - /// Encodes the data using rlc pub(crate) mod compose_rlc { use eth_types::Field; @@ -271,24 +255,6 @@ pub(crate) mod scatter { /// Packs bits into bytes pub(crate) mod to_bytes { - use eth_types::Field; - use gadgets::util::Expr; - use halo2_proofs::plonk::Expression; - - pub(crate) fn expr(bits: &[Expression]) -> Vec> { - debug_assert!(bits.len() % 8 == 0, "bits not a multiple of 8"); - let mut bytes = Vec::new(); - for byte_bits in bits.chunks(8) { - let mut value = 0.expr(); - let mut multiplier = F::ONE; - for byte in byte_bits.iter() { - value = value + byte.expr() * multiplier; - multiplier *= F::from(2); - } - bytes.push(value); - } - bytes - } pub(crate) fn value(bits: &[u8]) -> Vec { debug_assert!(bits.len() % 8 == 0, "bits not a multiple of 8"); diff --git a/zkevm-circuits/src/pi_circuit/param.rs b/zkevm-circuits/src/pi_circuit/param.rs index a6e263ac16..fff7391e76 100644 --- a/zkevm-circuits/src/pi_circuit/param.rs +++ b/zkevm-circuits/src/pi_circuit/param.rs @@ -3,11 +3,8 @@ use halo2_proofs::circuit::AssignedCell; use crate::util::word::Word; /// Fixed by the spec -pub(super) const BLOCK_LEN: usize = 7 + 256; -pub(super) const EXTRA_LEN: usize = 2; pub(super) const BYTE_POW_BASE: u64 = 256; pub(super) const EMPTY_TX_ROW_COUNT: usize = 1; -pub(super) const EMPTY_BLOCK_ROW_COUNT: usize = 1; pub(super) const N_BYTES_ONE: usize = 1; pub(super) type AssignedByteCells = (AssignedCell, Word>); diff --git a/zkevm-circuits/src/state_circuit.rs b/zkevm-circuits/src/state_circuit.rs index f4d3e9d55c..6987817e12 100644 --- a/zkevm-circuits/src/state_circuit.rs +++ b/zkevm-circuits/src/state_circuit.rs @@ -427,8 +427,6 @@ impl SortKeysConfig { } } -type Lookup = (&'static str, Expression, Expression); - /// State Circuit for proving RwTable is valid #[derive(Default, Clone, Debug)] pub struct StateCircuit { diff --git a/zkevm-circuits/src/state_circuit/constraint_builder.rs b/zkevm-circuits/src/state_circuit/constraint_builder.rs index 4d2f33d871..7851ebf89c 100644 --- a/zkevm-circuits/src/state_circuit/constraint_builder.rs +++ b/zkevm-circuits/src/state_circuit/constraint_builder.rs @@ -528,21 +528,6 @@ impl ConstraintBuilder { ); } - fn build_tx_receipt_constraints(&mut self, q: &Queries) { - // TODO: implement TxReceipt constraints - self.require_equal("TxReceipt rows not implemented", 1.expr(), 0.expr()); - - self.require_word_equal( - "state_root is unchanged for TxReceipt", - q.state_root(), - q.state_root_prev(), - ); - self.require_word_zero( - "value_prev_column is 0 for TxReceipt", - q.value_prev_column(), - ); - } - fn require_zero(&mut self, name: &'static str, e: Expression) { self.constraints.push((name, self.condition.clone() * e)); } @@ -605,10 +590,6 @@ impl ConstraintBuilder { } impl Queries { - fn selector(&self) -> Expression { - self.selector.clone() - } - fn is_write(&self) -> Expression { self.rw_table.is_write.clone() } @@ -617,18 +598,10 @@ impl Queries { not::expr(self.is_write()) } - fn tag(&self) -> Expression { - self.rw_table.tag.clone() - } - fn id(&self) -> Expression { self.rw_table.id.clone() } - fn id_change(&self) -> Expression { - self.id() - self.rw_table.prev_id.clone() - } - fn field_tag(&self) -> Expression { self.rw_table.field_tag.clone() } @@ -637,10 +610,6 @@ impl Queries { self.rw_table.value.clone() } - fn value_prev(&self) -> word::Word> { - self.rw_table.value_prev.clone() - } - fn initial_value(&self) -> word::Word> { self.initial_value.clone() } @@ -673,22 +642,6 @@ impl Queries { self.rw_table.rw_counter.clone() - self.rw_table.prev_rw_counter.clone() } - fn tx_log_index(&self) -> Expression { - from_digits(&self.address.limbs[0..2], (1u64 << 16).expr()) - } - - fn tx_log_index_prev(&self) -> Expression { - from_digits(&self.address.limbs_prev[0..2], (1u64 << 16).expr()) - } - - fn tx_log_id(&self) -> Expression { - from_digits(&self.address.limbs[3..5], (1u64 << 16).expr()) - } - - fn tx_log_id_prev(&self) -> Expression { - from_digits(&self.address.limbs_prev[3..5], (1u64 << 16).expr()) - } - fn last_access(&self) -> Expression { self.last_access.clone() } @@ -706,15 +659,6 @@ impl Queries { } } -fn from_digits(digits: &[Expression], base: Expression) -> Expression { - digits - .iter() - .rev() - .fold(Expression::Constant(F::ZERO), |result, digit| { - digit.clone() + result * base.clone() - }) -} - fn set>() -> Vec> { T::iter().map(|x| x.expr()).collect() // you don't need this collect if you // can figure out the return type diff --git a/zkevm-circuits/src/state_circuit/dev.rs b/zkevm-circuits/src/state_circuit/dev.rs index b3d0dcfa99..6a6babf714 100644 --- a/zkevm-circuits/src/state_circuit/dev.rs +++ b/zkevm-circuits/src/state_circuit/dev.rs @@ -63,6 +63,9 @@ where } } +#[cfg(test)] +use halo2_proofs::plonk::{Advice, Column}; + // allow dead code for unconstructed variants #[allow(dead_code)] #[cfg(test)] diff --git a/zkevm-circuits/src/util/word.rs b/zkevm-circuits/src/util/word.rs index 25747cf59a..bc70baaecf 100644 --- a/zkevm-circuits/src/util/word.rs +++ b/zkevm-circuits/src/util/word.rs @@ -29,8 +29,6 @@ pub(crate) type Word2 = WordLimbs; pub(crate) type Word4 = WordLimbs; -pub(crate) type Word16 = WordLimbs; - pub(crate) type Word32 = WordLimbs; pub(crate) type WordCell = Word>; From c412ee60e604f79b208645570e9a65d17cd364d5 Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Fri, 7 Jul 2023 00:16:59 +0800 Subject: [PATCH 06/27] some delicate one --- zkevm-circuits/src/evm_circuit/execution.rs | 2 ++ zkevm-circuits/src/evm_circuit/execution/begin_tx.rs | 2 -- zkevm-circuits/src/evm_circuit/execution/end_block.rs | 2 -- .../src/evm_circuit/execution/error_oog_static_memory.rs | 4 +++- zkevm-circuits/src/keccak_circuit/util.rs | 1 - zkevm-circuits/src/tx_circuit/sign_verify.rs | 2 +- 6 files changed, 6 insertions(+), 7 deletions(-) diff --git a/zkevm-circuits/src/evm_circuit/execution.rs b/zkevm-circuits/src/evm_circuit/execution.rs index 4cbc7cc30f..c0a561c091 100644 --- a/zkevm-circuits/src/evm_circuit/execution.rs +++ b/zkevm-circuits/src/evm_circuit/execution.rs @@ -311,7 +311,9 @@ pub struct ExecutionConfig { error_oog_code_store: Box>, error_invalid_jump: Box>, error_invalid_opcode: Box>, + #[allow(dead_code)] // will be implemented soon error_depth: Box>, + #[allow(dead_code)] // will be implemented soon error_contract_address_collision: Box>, error_invalid_creation_code: Box>, diff --git a/zkevm-circuits/src/evm_circuit/execution/begin_tx.rs b/zkevm-circuits/src/evm_circuit/execution/begin_tx.rs index 66172a4789..c22adb67a3 100644 --- a/zkevm-circuits/src/evm_circuit/execution/begin_tx.rs +++ b/zkevm-circuits/src/evm_circuit/execution/begin_tx.rs @@ -47,7 +47,6 @@ pub(crate) struct BeginTxGadget { tx_callee_address: WordCell, call_callee_address: AccountAddress, tx_is_create: Cell, - tx_value: Word32Cell, tx_call_data_length: Cell, tx_call_data_gas_cost: Cell, tx_call_data_word_length: ConstantDivisionGadget, @@ -480,7 +479,6 @@ impl ExecutionGadget for BeginTxGadget { tx_callee_address, call_callee_address, tx_is_create, - tx_value, tx_call_data_length, tx_call_data_gas_cost, tx_call_data_word_length, diff --git a/zkevm-circuits/src/evm_circuit/execution/end_block.rs b/zkevm-circuits/src/evm_circuit/execution/end_block.rs index 50405e92f0..48e083602b 100644 --- a/zkevm-circuits/src/evm_circuit/execution/end_block.rs +++ b/zkevm-circuits/src/evm_circuit/execution/end_block.rs @@ -27,8 +27,6 @@ pub(crate) struct EndBlockGadget { max_txs: Cell, } -const EMPTY_BLOCK_N_RWS: u64 = 0; - impl ExecutionGadget for EndBlockGadget { const NAME: &'static str = "EndBlock"; diff --git a/zkevm-circuits/src/evm_circuit/execution/error_oog_static_memory.rs b/zkevm-circuits/src/evm_circuit/execution/error_oog_static_memory.rs index 50ca74e605..6bea698c3a 100644 --- a/zkevm-circuits/src/evm_circuit/execution/error_oog_static_memory.rs +++ b/zkevm-circuits/src/evm_circuit/execution/error_oog_static_memory.rs @@ -17,7 +17,7 @@ use crate::{ }, }; use eth_types::{evm_types::OpcodeId, Field, ToLittleEndian}; -use halo2_proofs::plonk::Error; +use halo2_proofs::{circuit::Value, plonk::Error}; #[derive(Clone, Debug)] pub(crate) struct ErrorOOGStaticMemoryGadget { @@ -99,6 +99,8 @@ impl ExecutionGadget for ErrorOOGStaticMemoryGadget { step: &ExecStep, ) -> Result<(), Error> { let opcode = step.opcode().unwrap(); + self.opcode + .assign(region, offset, Value::known(F::from(opcode.as_u64())))?; // Inputs/Outputs let address = block.get_rws(step, 0).stack_value(); diff --git a/zkevm-circuits/src/keccak_circuit/util.rs b/zkevm-circuits/src/keccak_circuit/util.rs index c2e7ce688a..8b966a2b98 100644 --- a/zkevm-circuits/src/keccak_circuit/util.rs +++ b/zkevm-circuits/src/keccak_circuit/util.rs @@ -2,7 +2,6 @@ use super::{keccak_packed_multi::keccak_unusable_rows, param::*}; use eth_types::{Field, ToScalar, Word}; -use halo2_proofs::circuit::Value; use std::env::var; /// Description of which bits (positions) a part contains diff --git a/zkevm-circuits/src/tx_circuit/sign_verify.rs b/zkevm-circuits/src/tx_circuit/sign_verify.rs index a9e436c844..cb59d694fb 100644 --- a/zkevm-circuits/src/tx_circuit/sign_verify.rs +++ b/zkevm-circuits/src/tx_circuit/sign_verify.rs @@ -31,7 +31,7 @@ use halo2_proofs::{ plonk::{Advice, Column, ConstraintSystem, Error, Expression, SecondPhase, Selector}, poly::Rotation, }; -use integer::{AssignedInteger, IntegerChip, IntegerConfig, IntegerInstructions, Range}; +use integer::{AssignedInteger, IntegerChip, IntegerInstructions, Range}; use rand::SeedableRng; use rand_chacha::ChaCha20Rng; From 91c1fdeb3976b77d8cdedb725057c650a8e15dbb Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Fri, 7 Jul 2023 00:28:22 +0800 Subject: [PATCH 07/27] rm more --- .../execution/error_write_protection.rs | 59 +------------------ zkevm-circuits/src/evm_circuit/table.rs | 8 --- zkevm-circuits/src/evm_circuit/util.rs | 2 - .../src/evm_circuit/util/common_gadget.rs | 24 -------- .../evm_circuit/util/math_gadget/min_max.rs | 13 ---- .../src/keccak_circuit/cell_manager.rs | 2 - zkevm-circuits/src/keccak_circuit/table.rs | 2 +- zkevm-circuits/src/util.rs | 7 ++- 8 files changed, 7 insertions(+), 110 deletions(-) diff --git a/zkevm-circuits/src/evm_circuit/execution/error_write_protection.rs b/zkevm-circuits/src/evm_circuit/execution/error_write_protection.rs index 445fd45daf..91a1181878 100644 --- a/zkevm-circuits/src/evm_circuit/execution/error_write_protection.rs +++ b/zkevm-circuits/src/evm_circuit/execution/error_write_protection.rs @@ -144,21 +144,10 @@ impl ExecutionGadget for ErrorWriteProtectionGadget { mod test { use crate::test_util::CircuitTestBuilder; use eth_types::{ - address, bytecode, bytecode::Bytecode, evm_types::OpcodeId, geth_types::Account, Address, - ToWord, Word, U64, + address, bytecode, bytecode::Bytecode, geth_types::Account, Address, ToWord, Word, U64, }; use mock::TestContext; - // internal call test - struct Stack { - gas: u64, - value: Word, - cd_offset: u64, - cd_length: u64, - rd_offset: u64, - rd_length: u64, - } - fn callee(code: Bytecode) -> Account { let code = code.to_vec(); let is_empty = code.is_empty(); @@ -172,52 +161,6 @@ mod test { } } - fn caller(opcode: OpcodeId, stack: Stack, caller_is_success: bool) -> Account { - let is_call = opcode == OpcodeId::CALL; - let terminator = if caller_is_success { - OpcodeId::RETURN - } else { - OpcodeId::REVERT - }; - - let mut bytecode = bytecode! { - PUSH32(Word::from(stack.rd_length)) - PUSH32(Word::from(stack.rd_offset)) - PUSH32(Word::from(stack.cd_length)) - PUSH32(Word::from(stack.cd_offset)) - }; - if is_call { - bytecode.push(32, stack.value); - } - bytecode.append(&bytecode! { - PUSH32(Address::repeat_byte(0xff).to_word()) - PUSH32(Word::from(stack.gas)) - .write_op(opcode) - PUSH32(Word::from(stack.rd_length)) - PUSH32(Word::from(stack.rd_offset)) - PUSH32(Word::from(stack.cd_length)) - PUSH32(Word::from(stack.cd_offset)) - }); - if is_call { - bytecode.push(32, stack.value); - } - bytecode.append(&bytecode! { - PUSH32(Address::repeat_byte(0xff).to_word()) - PUSH32(Word::from(stack.gas)) - .write_op(opcode) - PUSH1(0) - PUSH1(0) - .write_op(terminator) - }); - - Account { - address: Address::repeat_byte(0xfe), - balance: Word::from(10).pow(20.into()), - code: bytecode.to_vec().into(), - ..Default::default() - } - } - #[test] fn test_write_protection() { // test sstore with write protection error diff --git a/zkevm-circuits/src/evm_circuit/table.rs b/zkevm-circuits/src/evm_circuit/table.rs index 6152244ab2..f9fd4e468e 100644 --- a/zkevm-circuits/src/evm_circuit/table.rs +++ b/zkevm-circuits/src/evm_circuit/table.rs @@ -423,12 +423,4 @@ impl Lookup { .collect(), } } - - pub(crate) fn degree(&self) -> usize { - self.input_exprs() - .iter() - .map(|expr| expr.degree()) - .max() - .unwrap() - } } diff --git a/zkevm-circuits/src/evm_circuit/util.rs b/zkevm-circuits/src/evm_circuit/util.rs index 92e1609ef2..94cbc890f3 100644 --- a/zkevm-circuits/src/evm_circuit/util.rs +++ b/zkevm-circuits/src/evm_circuit/util.rs @@ -288,8 +288,6 @@ pub struct RandomLinearCombination { } impl RandomLinearCombination { - const N_BYTES: usize = N; - /// XXX for randomness 256.expr(), consider using IntDecomposition instead pub(crate) fn new(cells: [Cell; N], randomness: Expression) -> Self { Self { diff --git a/zkevm-circuits/src/evm_circuit/util/common_gadget.rs b/zkevm-circuits/src/evm_circuit/util/common_gadget.rs index 9c17e74eee..af46113993 100644 --- a/zkevm-circuits/src/evm_circuit/util/common_gadget.rs +++ b/zkevm-circuits/src/evm_circuit/util/common_gadget.rs @@ -315,22 +315,6 @@ impl Self { add_words } } - pub(crate) fn balance(&self) -> &Word32Cell { - if INCREASE { - self.add_words.sum() - } else { - &self.add_words.addends()[0] - } - } - - pub(crate) fn balance_prev(&self) -> &Word32Cell { - if INCREASE { - &self.add_words.addends()[0] - } else { - self.add_words.sum() - } - } - pub(crate) fn assign( &self, region: &mut CachedRegion<'_, '_, F>, @@ -557,14 +541,6 @@ impl TransferGadget { } } - pub(crate) fn sender(&self) -> &UpdateBalanceGadget { - &self.sender - } - - pub(crate) fn receiver(&self) -> &UpdateBalanceGadget { - &self.receiver - } - pub(crate) fn reversible_w_delta(&self) -> Expression { // +1 Write Account (receiver) CodeHash (account creation via code_hash update) or::expr([ diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/min_max.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/min_max.rs index e17f9c7b39..7c20554b7b 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/min_max.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget/min_max.rs @@ -52,19 +52,6 @@ impl MinMaxGadget { (lhs, rhs) }) } - - pub(crate) fn assign_value( - &self, - region: &mut CachedRegion<'_, '_, F>, - offset: usize, - lhs: Value, - rhs: Value, - ) -> Result, Error> { - transpose_val_ret( - lhs.zip(rhs) - .map(|(lhs, rhs)| self.assign(region, offset, lhs, rhs)), - ) - } } #[cfg(test)] diff --git a/zkevm-circuits/src/keccak_circuit/cell_manager.rs b/zkevm-circuits/src/keccak_circuit/cell_manager.rs index ffd9d981ee..d628ec0794 100644 --- a/zkevm-circuits/src/keccak_circuit/cell_manager.rs +++ b/zkevm-circuits/src/keccak_circuit/cell_manager.rs @@ -85,7 +85,6 @@ pub(crate) struct CellColumn { /// CellManager #[derive(Clone, Debug)] pub(crate) struct CellManager { - height: usize, columns: Vec>, rows: Vec, num_unused_cells: usize, @@ -94,7 +93,6 @@ pub(crate) struct CellManager { impl CellManager { pub(crate) fn new(height: usize) -> Self { Self { - height, columns: Vec::new(), rows: vec![0; height], num_unused_cells: 0, diff --git a/zkevm-circuits/src/keccak_circuit/table.rs b/zkevm-circuits/src/keccak_circuit/table.rs index d86813b9d3..c632496a51 100644 --- a/zkevm-circuits/src/keccak_circuit/table.rs +++ b/zkevm-circuits/src/keccak_circuit/table.rs @@ -167,7 +167,7 @@ mod tests { fn chi_table() { // Check the base pattern for all combinations of bits. for i in 0..16_usize { - let (a, b, c, d) = (i & 1, (i >> 1) & 1, (i >> 2) & 1, (i >> 3) & 1); + let (a, b, c) = (i & 1, (i >> 1) & 1, (i >> 2) & 1); assert_eq!( CHI_BASE_LOOKUP_TABLE[3 - 2 * a + b - c], (a ^ ((!b) & c)) as u8 diff --git a/zkevm-circuits/src/util.rs b/zkevm-circuits/src/util.rs index 5215c1a97d..fc86c59101 100644 --- a/zkevm-circuits/src/util.rs +++ b/zkevm-circuits/src/util.rs @@ -6,8 +6,7 @@ use bus_mapping::evm::OpcodeId; use halo2_proofs::{ circuit::{Layouter, Value}, plonk::{ - Challenge, Circuit, ConstraintSystem, Error, Expression, FirstPhase, SecondPhase, - VirtualCells, + Challenge, ConstraintSystem, Error, Expression, FirstPhase, SecondPhase, VirtualCells, }, }; @@ -199,6 +198,10 @@ pub(crate) fn get_push_size(byte: u8) -> u64 { } } +#[cfg(test)] +use halo2_proofs::plonk::Circuit; + +#[cfg(test)] /// Returns number of unusable rows of the Circuit. /// The minimum unusable rows of a circuit is currently 6, where /// - 3 comes from minimum number of distinct queries to permutation argument witness column From 9d3f5c88a0f5c9865542e1163b580046755ab005 Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Fri, 7 Jul 2023 01:02:24 +0800 Subject: [PATCH 08/27] rm more --- .../evm_circuit/util/constraint_builder.rs | 8 --- .../src/evm_circuit/util/math_gadget.rs | 2 +- .../util/math_gadget/binary_number.rs | 68 ------------------- .../util/math_gadget/constant_division.rs | 14 +--- .../evm_circuit/util/math_gadget/is_equal.rs | 13 ---- .../evm_circuit/util/math_gadget/is_zero.rs | 9 --- .../evm_circuit/util/math_gadget/min_max.rs | 8 +-- .../src/evm_circuit/util/math_gadget/rlp.rs | 5 -- zkevm-circuits/src/keccak_circuit/util.rs | 16 ----- .../multiple_precision_integer.rs | 13 +--- zkevm-circuits/src/tx_circuit/sign_verify.rs | 2 + 11 files changed, 8 insertions(+), 150 deletions(-) delete mode 100644 zkevm-circuits/src/evm_circuit/util/math_gadget/binary_number.rs diff --git a/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs b/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs index 4872d2dff4..f7aebd4b69 100644 --- a/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs +++ b/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs @@ -474,14 +474,6 @@ impl<'a, F: Field> EVMConstraintBuilder<'a, F> { self.query_cells(CellType::Lookup(Table::U8), count) } - pub(crate) fn query_u16(&mut self) -> [Cell; N] { - self.query_u16_dyn(N).try_into().unwrap() - } - - pub(crate) fn query_u16_dyn(&mut self, count: usize) -> Vec> { - self.query_cells(CellType::Lookup(Table::U16), count) - } - pub(crate) fn query_cell(&mut self) -> Cell { self.query_cell_with_type(CellType::StoragePhase1) } diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget.rs index 3275596609..ca55ff663a 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget.rs @@ -4,8 +4,8 @@ use halo2_proofs::plonk::Expression; mod abs_word; mod add_words; +#[allow(dead_code)] // we might want to use batched is zero for something mod batched_is_zero; -mod binary_number; mod byte_size; mod cmp_words; mod comparison; diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/binary_number.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/binary_number.rs deleted file mode 100644 index d872bfc6b7..0000000000 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/binary_number.rs +++ /dev/null @@ -1,68 +0,0 @@ -use eth_types::Field; -use gadgets::{binary_number::AsBits, util::Expr}; -use halo2_proofs::{ - circuit::Value, - plonk::{Error, Expression}, -}; - -use crate::evm_circuit::util::{ - constraint_builder::{ConstrainBuilderCommon, EVMConstraintBuilder}, - CachedRegion, Cell, -}; - -#[derive(Clone, Debug)] -pub struct BinaryNumberGadget { - bits: [Cell; N], -} - -impl BinaryNumberGadget { - pub(crate) fn construct(cb: &mut EVMConstraintBuilder, value: Expression) -> Self { - let bits = array_init::array_init(|_| cb.query_bool()); - - // the binary representation of value must be correct. - cb.require_equal( - "binary representation of value should be correct", - value, - bits.iter() - .fold(0.expr(), |res, bit| bit.expr() + res * 2.expr()), - ); - - Self { bits } - } - - pub(crate) fn assign( - &self, - region: &mut CachedRegion<'_, '_, F>, - offset: usize, - value: T, - ) -> Result<(), Error> - where - T: AsBits, - { - for (c, v) in self.bits.iter().zip(value.as_bits().iter()) { - c.assign(region, offset, Value::known(F::from(*v as u64)))?; - } - Ok(()) - } - - pub(crate) fn value(&self) -> Expression { - self.bits - .iter() - .fold(0.expr(), |res, bit| bit.expr() + res * 2.expr()) - } - - pub(crate) fn value_equals(&self, other: T) -> Expression - where - T: AsBits, - { - gadgets::util::and::expr(other.as_bits().iter().zip(self.bits.iter()).map( - |(other_bit, self_bit)| { - if *other_bit { - self_bit.expr() - } else { - gadgets::util::not::expr(self_bit.expr()) - } - }, - )) - } -} diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/constant_division.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/constant_division.rs index 838cc585c2..56d5e45432 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/constant_division.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget/constant_division.rs @@ -2,7 +2,7 @@ use crate::{ evm_circuit::util::{ constraint_builder::{ConstrainBuilderCommon, EVMConstraintBuilder}, math_gadget::*, - transpose_val_ret, CachedRegion, Cell, CellType, + CachedRegion, Cell, CellType, }, util::Expr, }; @@ -60,6 +60,7 @@ impl ConstantDivisionGadget { self.quotient.expr() } + #[allow(dead_code)] pub(crate) fn remainder(&self) -> Expression { self.remainder.expr() } @@ -84,17 +85,6 @@ impl ConstantDivisionGadget { Ok((quotient, remainder)) } - - pub(crate) fn assign_value( - &self, - region: &mut CachedRegion<'_, '_, F>, - offset: usize, - numerator: Value, - ) -> Result, Error> { - transpose_val_ret( - numerator.map(|numerator| self.assign(region, offset, numerator.get_lower_128())), - ) - } } #[cfg(test)] diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/is_equal.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/is_equal.rs index 1c472181c6..5936204337 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/is_equal.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget/is_equal.rs @@ -37,19 +37,6 @@ impl IsEqualGadget { ) -> Result { self.is_zero.assign(region, offset, lhs - rhs) } - - pub(crate) fn assign_value( - &self, - region: &mut CachedRegion<'_, '_, F>, - offset: usize, - lhs: Value, - rhs: Value, - ) -> Result, Error> { - transpose_val_ret( - lhs.zip(rhs) - .map(|(lhs, rhs)| self.assign(region, offset, lhs, rhs)), - ) - } } #[cfg(test)] diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/is_zero.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/is_zero.rs index 9f7d3f252f..7738a718b8 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/is_zero.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget/is_zero.rs @@ -54,15 +54,6 @@ impl IsZeroGadget { F::ZERO }) } - - pub(crate) fn assign_value( - &self, - region: &mut CachedRegion<'_, '_, F>, - offset: usize, - value: Value, - ) -> Result, Error> { - transpose_val_ret(value.map(|value| self.assign(region, offset, value))) - } } #[cfg(test)] diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/min_max.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/min_max.rs index 7c20554b7b..ee6b101ab8 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/min_max.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget/min_max.rs @@ -1,12 +1,8 @@ use crate::evm_circuit::util::{ - constraint_builder::EVMConstraintBuilder, math_gadget::*, select, transpose_val_ret, - CachedRegion, + constraint_builder::EVMConstraintBuilder, math_gadget::*, select, CachedRegion, }; use eth_types::Field; -use halo2_proofs::{ - circuit::Value, - plonk::{Error, Expression}, -}; +use halo2_proofs::plonk::{Error, Expression}; /// Returns `rhs` when `lhs < rhs`, and returns `lhs` otherwise. /// lhs and rhs `< 256**N_BYTES` /// `N_BYTES` is required to be `<= MAX_N_BYTES_INTEGER`. diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/rlp.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/rlp.rs index e097a7cbd2..4b6419b881 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/rlp.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget/rlp.rs @@ -312,11 +312,6 @@ impl ContractCreateGadget { ) } - /// Caller nonce's RLC value. - pub(crate) fn caller_nonce_rlc(&self) -> Expression { - self.nonce.value_rlc.expr() - } - /// Length of the input data to the keccak hash function. pub(crate) fn input_length(&self) -> Expression { if IS_CREATE2 { diff --git a/zkevm-circuits/src/keccak_circuit/util.rs b/zkevm-circuits/src/keccak_circuit/util.rs index 8b966a2b98..c11a98b470 100644 --- a/zkevm-circuits/src/keccak_circuit/util.rs +++ b/zkevm-circuits/src/keccak_circuit/util.rs @@ -225,22 +225,6 @@ pub(crate) fn get_num_bits_per_lookup_impl(range: usize, log_height: usize) -> u num_bits as usize } -/// Encodes the data using rlc -pub(crate) mod compose_rlc { - use eth_types::Field; - use halo2_proofs::plonk::Expression; - - pub(crate) fn expr(expressions: &[Expression], r: Expression) -> Expression { - let mut rlc = expressions[0].clone(); - let mut multiplier = r.clone(); - for expression in expressions[1..].iter() { - rlc = rlc + expression.clone() * multiplier.clone(); - multiplier = multiplier * r.clone(); - } - rlc - } -} - /// Scatters a value into a packed word constant pub(crate) mod scatter { use super::pack; diff --git a/zkevm-circuits/src/state_circuit/multiple_precision_integer.rs b/zkevm-circuits/src/state_circuit/multiple_precision_integer.rs index c6826a3773..0ea236faa5 100644 --- a/zkevm-circuits/src/state_circuit/multiple_precision_integer.rs +++ b/zkevm-circuits/src/state_circuit/multiple_precision_integer.rs @@ -2,7 +2,7 @@ use super::{lookups, param::*}; use crate::util::Expr; use eth_types::{Address, Field, ToLittleEndian, Word}; use halo2_proofs::{ - circuit::{Layouter, Region, Value}, + circuit::{Region, Value}, plonk::{Advice, Column, ConstraintSystem, Error, Expression, Fixed, VirtualCells}, poly::Rotation, }; @@ -120,13 +120,6 @@ impl Chip, { - pub fn construct(config: Config) -> Self { - Self { - config, - _marker: PhantomData, - } - } - pub fn configure( meta: &mut ConstraintSystem, selector: Column, @@ -161,10 +154,6 @@ where _marker: PhantomData, } } - - pub fn load(&self, _layouter: &mut impl Layouter) -> Result<(), Error> { - Ok(()) - } } fn le_bytes_to_limbs(bytes: &[u8]) -> Vec { diff --git a/zkevm-circuits/src/tx_circuit/sign_verify.rs b/zkevm-circuits/src/tx_circuit/sign_verify.rs index cb59d694fb..2be373ca22 100644 --- a/zkevm-circuits/src/tx_circuit/sign_verify.rs +++ b/zkevm-circuits/src/tx_circuit/sign_verify.rs @@ -125,6 +125,7 @@ pub(crate) struct SignVerifyConfig { rlc: Column, // Keccak q_keccak: Selector, + #[allow(dead_code)] // We need keccak_table for test keccak_table: KeccakTable, } @@ -261,6 +262,7 @@ impl SignVerifyConfig { #[derive(Clone, Debug)] pub(crate) enum Term { Assigned(Cell, Value), + #[allow(dead_code)] // We need Unassigned for match Unassigned(Value), } From 36ca1eddcc736f2b57e1ec2aacce005d56e10592 Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Fri, 7 Jul 2023 01:22:39 +0800 Subject: [PATCH 09/27] rm more --- .../src/evm_circuit/execution/create.rs | 1 - .../execution/error_invalid_jump.rs | 57 ------------------- .../execution/error_oog_sload_sstore.rs | 6 -- .../src/evm_circuit/execution/jump.rs | 5 ++ .../src/evm_circuit/util/common_gadget.rs | 3 +- .../evm_circuit/util/constraint_builder.rs | 40 +------------ .../evm_circuit/util/math_gadget/is_equal.rs | 7 +-- .../evm_circuit/util/math_gadget/is_zero.rs | 2 +- .../evm_circuit/util/math_gadget/test_util.rs | 15 +---- zkevm-circuits/src/exp_circuit/test.rs | 5 +- zkevm-circuits/src/keccak_circuit/test.rs | 7 +-- zkevm-circuits/src/lib.rs | 2 +- zkevm-circuits/src/pi_circuit/test.rs | 5 +- zkevm-circuits/src/state_circuit/test.rs | 5 +- 14 files changed, 20 insertions(+), 140 deletions(-) diff --git a/zkevm-circuits/src/evm_circuit/execution/create.rs b/zkevm-circuits/src/evm_circuit/execution/create.rs index 5b50ac321e..14ac7e9603 100644 --- a/zkevm-circuits/src/evm_circuit/execution/create.rs +++ b/zkevm-circuits/src/evm_circuit/execution/create.rs @@ -689,7 +689,6 @@ mod test { use lazy_static::lazy_static; use mock::{eth, TestContext}; - const CALLEE_ADDRESS: Address = Address::repeat_byte(0xff); lazy_static! { static ref CALLER_ADDRESS: Address = address!("0x00bbccddee000000000000000000000000002400"); } diff --git a/zkevm-circuits/src/evm_circuit/execution/error_invalid_jump.rs b/zkevm-circuits/src/evm_circuit/execution/error_invalid_jump.rs index 3007f03033..8edb48b549 100644 --- a/zkevm-circuits/src/evm_circuit/execution/error_invalid_jump.rs +++ b/zkevm-circuits/src/evm_circuit/execution/error_invalid_jump.rs @@ -243,16 +243,6 @@ mod test { .run(); } - // internal call test - struct Stack { - gas: u64, - value: Word, - cd_offset: u64, - cd_length: u64, - rd_offset: u64, - rd_length: u64, - } - fn callee(code: Bytecode) -> Account { let code = code.to_vec(); let is_empty = code.is_empty(); @@ -265,53 +255,6 @@ mod test { } } - fn caller(opcode: OpcodeId, stack: Stack, caller_is_success: bool) -> Account { - let is_call = opcode == OpcodeId::CALL; - let terminator = if caller_is_success { - OpcodeId::RETURN - } else { - OpcodeId::REVERT - }; - - // Call twice for testing both cold and warm access - let mut bytecode = bytecode! { - PUSH32(Word::from(stack.rd_length)) - PUSH32(Word::from(stack.rd_offset)) - PUSH32(Word::from(stack.cd_length)) - PUSH32(Word::from(stack.cd_offset)) - }; - if is_call { - bytecode.push(32, stack.value); - } - bytecode.append(&bytecode! { - PUSH32(Address::repeat_byte(0xff).to_word()) - PUSH32(Word::from(stack.gas)) - .write_op(opcode) - PUSH32(Word::from(stack.rd_length)) - PUSH32(Word::from(stack.rd_offset)) - PUSH32(Word::from(stack.cd_length)) - PUSH32(Word::from(stack.cd_offset)) - }); - if is_call { - bytecode.push(32, stack.value); - } - bytecode.append(&bytecode! { - PUSH32(Address::repeat_byte(0xff).to_word()) - PUSH32(Word::from(stack.gas)) - .write_op(opcode) - PUSH1(0) - PUSH1(0) - .write_op(terminator) - }); - - Account { - address: Address::repeat_byte(0xfe), - balance: Word::from(10).pow(20.into()), - code: bytecode.to_vec().into(), - ..Default::default() - } - } - // jump or jumpi error happen in internal call fn test_internal_jump_error(is_jumpi: bool) { let mut caller_bytecode = bytecode! { diff --git a/zkevm-circuits/src/evm_circuit/execution/error_oog_sload_sstore.rs b/zkevm-circuits/src/evm_circuit/execution/error_oog_sload_sstore.rs index 94e6312d9f..d5ee9c2612 100644 --- a/zkevm-circuits/src/evm_circuit/execution/error_oog_sload_sstore.rs +++ b/zkevm-circuits/src/evm_circuit/execution/error_oog_sload_sstore.rs @@ -367,10 +367,7 @@ mod test { #[derive(Default)] struct TestingData { key: U256, - value: U256, - value_prev: U256, original_value: U256, - is_warm: bool, gas_cost: u64, bytecode: Bytecode, } @@ -443,10 +440,7 @@ mod test { Self { key, - value, - value_prev, original_value, - is_warm, gas_cost, bytecode, } diff --git a/zkevm-circuits/src/evm_circuit/execution/jump.rs b/zkevm-circuits/src/evm_circuit/execution/jump.rs index f99a466993..615d2ba7c3 100644 --- a/zkevm-circuits/src/evm_circuit/execution/jump.rs +++ b/zkevm-circuits/src/evm_circuit/execution/jump.rs @@ -137,6 +137,11 @@ mod test { test_ok(rand_range(34..1 << 11)); } + #[test] + fn invalid_jump_err() { + test_invalid_jump(34); + } + #[test] #[ignore] fn jump_gadget_rand_huge_bytecode() { diff --git a/zkevm-circuits/src/evm_circuit/util/common_gadget.rs b/zkevm-circuits/src/evm_circuit/util/common_gadget.rs index af46113993..f345e9da19 100644 --- a/zkevm-circuits/src/evm_circuit/util/common_gadget.rs +++ b/zkevm-circuits/src/evm_circuit/util/common_gadget.rs @@ -803,7 +803,6 @@ impl CommonCallGadget #[derive(Clone, Debug)] pub(crate) struct SloadGasGadget { - is_warm: Expression, gas_cost: Expression, } @@ -815,7 +814,7 @@ impl SloadGasGadget { GasCost::COLD_SLOAD.expr(), ); - Self { is_warm, gas_cost } + Self { gas_cost } } pub(crate) fn expr(&self) -> Expression { diff --git a/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs b/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs index f7aebd4b69..61ba458128 100644 --- a/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs +++ b/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs @@ -276,6 +276,7 @@ impl BaseConstraintBuilder { enum ConstraintLocation { Step, StepFirst, + #[allow(dead_code)] // step last is meaningful StepLast, NotStepLast, } @@ -302,13 +303,11 @@ pub(crate) struct EVMConstraintBuilder<'a, F: Field> { rw_counter_offset: Expression, program_counter_offset: usize, stack_pointer_offset: Expression, - log_id_offset: usize, in_next_step: bool, conditions: Vec>, constraints_location: ConstraintLocation, stored_expressions: Vec>, pub(crate) debug_expressions: Vec<(String, Expression)>, - meta: &'a mut ConstraintSystem, } @@ -348,7 +347,6 @@ impl<'a, F: Field> EVMConstraintBuilder<'a, F> { rw_counter_offset: 0.expr(), program_counter_offset: 0, stack_pointer_offset: 0.expr(), - log_id_offset: 0, in_next_step: false, conditions: Vec::new(), constraints_location: ConstraintLocation::Step, @@ -522,11 +520,6 @@ impl<'a, F: Field> EVMConstraintBuilder<'a, F> { ); } - pub(crate) fn require_next_state_not(&mut self, execution_state: ExecutionState) { - let next_state = self.next.execution_state_selector([execution_state]); - self.add_constraint("Constrain next execution state not", next_state.expr()); - } - pub(crate) fn require_step_state_transition( &mut self, step_state_transition: StepStateTransition, @@ -1435,32 +1428,6 @@ impl<'a, F: Field> EVMConstraintBuilder<'a, F> { ret } - /// This function needs to be used with extra precaution. You need to make - /// sure the layout is the same as the gadget for `next_step_state`. - /// `query_cell` will return cells in the next step in the `constraint` - /// function. - pub(crate) fn constrain_next_step( - &mut self, - next_step_state: ExecutionState, - condition: Option>, - constraint: impl FnOnce(&mut Self) -> R, - ) -> R { - assert!(!self.in_next_step, "Already in the next step"); - self.in_next_step = true; - let ret = match condition { - None => { - self.require_next_state(next_step_state); - constraint(self) - } - Some(cond) => self.condition(cond, |cb| { - cb.require_next_state(next_step_state); - constraint(cb) - }), - }; - self.in_next_step = false; - ret - } - /// TODO: Doc fn constraint_at_location( &mut self, @@ -1481,10 +1448,7 @@ impl<'a, F: Field> EVMConstraintBuilder<'a, F> { pub(crate) fn step_first(&mut self, constraint: impl FnOnce(&mut Self) -> R) -> R { self.constraint_at_location(ConstraintLocation::StepFirst, constraint) } - /// TODO: Doc - pub(crate) fn step_last(&mut self, constraint: impl FnOnce(&mut Self) -> R) -> R { - self.constraint_at_location(ConstraintLocation::StepLast, constraint) - } + /// TODO: Doc pub(crate) fn not_step_last(&mut self, constraint: impl FnOnce(&mut Self) -> R) -> R { self.constraint_at_location(ConstraintLocation::NotStepLast, constraint) diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/is_equal.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/is_equal.rs index 5936204337..f0ddb64048 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/is_equal.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget/is_equal.rs @@ -1,11 +1,8 @@ use crate::evm_circuit::util::{ - constraint_builder::EVMConstraintBuilder, math_gadget::*, transpose_val_ret, CachedRegion, + constraint_builder::EVMConstraintBuilder, math_gadget::*, CachedRegion, }; use eth_types::Field; -use halo2_proofs::{ - circuit::Value, - plonk::{Error, Expression}, -}; +use halo2_proofs::plonk::{Error, Expression}; /// Returns `1` when `lhs == rhs`, and returns `0` otherwise. #[derive(Clone, Debug)] diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/is_zero.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/is_zero.rs index 7738a718b8..5e88655313 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/is_zero.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget/is_zero.rs @@ -1,7 +1,7 @@ use crate::{ evm_circuit::util::{ constraint_builder::{ConstrainBuilderCommon, EVMConstraintBuilder}, - transpose_val_ret, CachedRegion, Cell, CellType, + CachedRegion, Cell, CellType, }, util::Expr, }; diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/test_util.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/test_util.rs index 3717bdb3fe..6f186838ce 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/test_util.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget/test_util.rs @@ -22,7 +22,7 @@ use halo2_proofs::{ circuit::SimpleFloorPlanner, dev::MockProver, plonk::{ - Circuit, ConstraintSystem, Error, Expression, FirstPhase, SecondPhase, Selector, ThirdPhase, + Circuit, ConstraintSystem, Error, FirstPhase, SecondPhase, Selector, ThirdPhase, }, }; @@ -40,10 +40,6 @@ pub(crate) const WORD_CELL_MAX: Word = U256([ pub(crate) const WORD_SIGNED_MAX: Word = U256([u64::MAX, u64::MAX, u64::MAX, i64::MAX as _]); pub(crate) const WORD_SIGNED_MIN: Word = U256([0, 0, 0, i64::MIN as _]); -pub(crate) fn generate_power_of_randomness(randomness: F) -> Vec { - (1..32).map(|exp| randomness.pow([exp, 0, 0, 0])).collect() -} - pub(crate) trait MathGadgetContainer: Clone { fn configure_gadget_container(cb: &mut EVMConstraintBuilder) -> Self where @@ -68,19 +64,16 @@ where stored_expressions: Vec>, math_gadget_container: G, _marker: PhantomData, - challenges: Challenges>, } pub(crate) struct UnitTestMathGadgetBaseCircuit { - size: usize, witnesses: Vec, _marker: PhantomData, } impl UnitTestMathGadgetBaseCircuit { - fn new(size: usize, witnesses: Vec) -> Self { + fn new(witnesses: Vec) -> Self { UnitTestMathGadgetBaseCircuit { - size, witnesses, _marker: PhantomData, } @@ -94,7 +87,6 @@ impl> Circuit for UnitTestMathGadgetBaseC fn without_witnesses(&self) -> Self { UnitTestMathGadgetBaseCircuit { - size: 0, witnesses: vec![], _marker: PhantomData, } @@ -172,7 +164,6 @@ impl> Circuit for UnitTestMathGadgetBaseC stored_expressions, math_gadget_container, _marker: PhantomData, - challenges: challenges_exprs, }, challenges, ) @@ -257,7 +248,7 @@ pub(crate) fn test_math_gadget_container>( expected_success: bool, ) { const K: usize = 12; - let circuit = UnitTestMathGadgetBaseCircuit::::new(K, witnesses); + let circuit = UnitTestMathGadgetBaseCircuit::::new(witnesses); let prover = MockProver::::run(K as u32, &circuit, vec![]).unwrap(); if expected_success { diff --git a/zkevm-circuits/src/exp_circuit/test.rs b/zkevm-circuits/src/exp_circuit/test.rs index 5ff01c0e9f..5e6fa3c0bf 100644 --- a/zkevm-circuits/src/exp_circuit/test.rs +++ b/zkevm-circuits/src/exp_circuit/test.rs @@ -5,13 +5,10 @@ use crate::{ }; use bus_mapping::{ circuit_input_builder::{CircuitInputBuilder, FixedCParams}, - evm::OpcodeId, mock::BlockData, }; use eth_types::{bytecode, geth_types::GethData, Bytecode, Field, Word}; -use halo2_proofs::{ - circuit::SimpleFloorPlanner, dev::MockProver, halo2curves::bn256::Fr, plonk::Circuit, -}; +use halo2_proofs::{dev::MockProver, halo2curves::bn256::Fr}; use mock::TestContext; #[test] diff --git a/zkevm-circuits/src/keccak_circuit/test.rs b/zkevm-circuits/src/keccak_circuit/test.rs index 8e1a2ec598..04e4b541d6 100644 --- a/zkevm-circuits/src/keccak_circuit/test.rs +++ b/zkevm-circuits/src/keccak_circuit/test.rs @@ -1,12 +1,7 @@ use super::*; use crate::util::unusable_rows; use eth_types::Field; -use halo2_proofs::{ - circuit::{Layouter, SimpleFloorPlanner}, - dev::MockProver, - halo2curves::bn256::Fr, - plonk::{Circuit, ConstraintSystem, Error}, -}; +use halo2_proofs::{dev::MockProver, halo2curves::bn256::Fr}; use log::error; use std::iter::zip; diff --git a/zkevm-circuits/src/lib.rs b/zkevm-circuits/src/lib.rs index 7ef25f232c..6beb928d01 100644 --- a/zkevm-circuits/src/lib.rs +++ b/zkevm-circuits/src/lib.rs @@ -28,7 +28,7 @@ pub mod state_circuit; pub mod super_circuit; pub mod table; -#[cfg(feature = "test-util")] +#[cfg(any(test, feature = "test-util"))] pub mod test_util; pub mod instance; diff --git a/zkevm-circuits/src/pi_circuit/test.rs b/zkevm-circuits/src/pi_circuit/test.rs index f474a9c2ac..88c0c6b7f7 100644 --- a/zkevm-circuits/src/pi_circuit/test.rs +++ b/zkevm-circuits/src/pi_circuit/test.rs @@ -3,10 +3,7 @@ use std::collections::HashMap; use crate::{pi_circuit::dev::PiCircuitParams, util::unusable_rows, witness::block_convert}; use super::*; -use bus_mapping::{ - circuit_input_builder::{CircuitsParams, FixedCParams}, - mock::BlockData, -}; +use bus_mapping::{circuit_input_builder::FixedCParams, mock::BlockData}; use eth_types::{bytecode, geth_types::GethData, Word, H160}; use ethers_signers::{LocalWallet, Signer}; use halo2_proofs::{ diff --git a/zkevm-circuits/src/state_circuit/test.rs b/zkevm-circuits/src/state_circuit/test.rs index 624844d937..8456d8113e 100644 --- a/zkevm-circuits/src/state_circuit/test.rs +++ b/zkevm-circuits/src/state_circuit/test.rs @@ -10,15 +10,14 @@ use bus_mapping::operation::{ use eth_types::{ address, evm_types::{MemoryAddress, StackAddress}, - Address, Field, ToAddress, Word, U256, + Address, ToAddress, Word, U256, }; use gadgets::binary_number::AsBits; use halo2_proofs::{ arithmetic::Field as Halo2Field, - circuit::SimpleFloorPlanner, dev::{MockProver, VerifyFailure}, halo2curves::bn256::{Bn256, Fr}, - plonk::{keygen_vk, Advice, Circuit, Column, ConstraintSystem}, + plonk::{keygen_vk, Circuit, ConstraintSystem}, poly::kzg::commitment::ParamsKZG, }; use rand::SeedableRng; From 477208b88adcbc73222d1699e3d480222072b5a9 Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Fri, 7 Jul 2023 01:33:25 +0800 Subject: [PATCH 10/27] move test aggregation circuit to dev --- zkevm-circuits/src/root_circuit.rs | 12 +- .../src/root_circuit/aggregation.rs | 146 +---------------- zkevm-circuits/src/root_circuit/dev.rs | 154 ++++++++++++++++++ 3 files changed, 166 insertions(+), 146 deletions(-) create mode 100644 zkevm-circuits/src/root_circuit/dev.rs diff --git a/zkevm-circuits/src/root_circuit.rs b/zkevm-circuits/src/root_circuit.rs index 6915986a9e..4badf32e87 100644 --- a/zkevm-circuits/src/root_circuit.rs +++ b/zkevm-circuits/src/root_circuit.rs @@ -23,11 +23,16 @@ use std::{iter, marker::PhantomData, rc::Rc}; mod aggregation; -#[cfg(any(feature = "test", test))] -mod test; +#[cfg(any(test, feature = "test-circuits"))] +mod dev; #[cfg(test)] +mod test; +#[cfg(feature = "test-circuits")] pub use self::RootCircuit as TestRootCircuit; +#[cfg(any(feature = "test-circuits", test))] +pub use dev::TestAggregationCircuit; + pub use aggregation::{ aggregate, AggregationConfig, EccChip, Gwc, Halo2Loader, KzgDk, KzgSvk, PlonkSuccinctVerifier, PlonkVerifier, PoseidonTranscript, Shplonk, Snark, SnarkWitness, BITS, LIMBS, @@ -37,9 +42,6 @@ pub use snark_verifier::{ system::halo2::{compile, transcript::evm::EvmTranscript, Config}, }; -#[cfg(any(feature = "test", test))] -pub use aggregation::TestAggregationCircuit; - /// RootCircuit for aggregating SuperCircuit into a much smaller proof. #[derive(Clone)] pub struct RootCircuit<'a, M: MultiMillerLoop, As> { diff --git a/zkevm-circuits/src/root_circuit/aggregation.rs b/zkevm-circuits/src/root_circuit/aggregation.rs index ff2d558998..2c078013e3 100644 --- a/zkevm-circuits/src/root_circuit/aggregation.rs +++ b/zkevm-circuits/src/root_circuit/aggregation.rs @@ -1,11 +1,10 @@ use eth_types::Field; use halo2_proofs::{ - circuit::{AssignedCell, Layouter, SimpleFloorPlanner, Value}, + circuit::{AssignedCell, Layouter, Value}, halo2curves::{ - ff::Field as Halo2Field, group::prime::PrimeCurveAffine, pairing::Engine, - serde::SerdeObject, CurveAffine, + group::prime::PrimeCurveAffine, pairing::Engine, serde::SerdeObject, CurveAffine, }, - plonk::{Circuit, ConstraintSystem, Error}, + plonk::{ConstraintSystem, Error}, poly::{commitment::ParamsProver, kzg::commitment::ParamsKZG}, }; use itertools::Itertools; @@ -27,7 +26,7 @@ use snark_verifier::{ util::arithmetic::{fe_to_limbs, MultiMillerLoop}, verifier::{self, plonk::PlonkProtocol, SnarkVerifier}, }; -use std::{io, iter, marker::PhantomData, rc::Rc}; +use std::{io, iter, rc::Rc}; /// Number of limbs to decompose a elliptic curve base field element into. pub const LIMBS: usize = 4; @@ -65,7 +64,7 @@ pub type PoseidonTranscript = #[derive(Clone, Copy)] pub struct Snark<'a, C: CurveAffine> { protocol: &'a PlonkProtocol, - instances: &'a Vec>, + pub(crate) instances: &'a Vec>, proof: &'a [u8], } @@ -407,141 +406,6 @@ where Ok(accumulator_limbs) } -/// Aggregation circuit for testing purpose. -#[derive(Clone)] -pub struct TestAggregationCircuit<'a, M: MultiMillerLoop, As> { - svk: KzgSvk, - snarks: Vec>, - instances: Vec, - _marker: PhantomData, -} - -impl<'a, M: MultiMillerLoop, As> TestAggregationCircuit<'a, M, As> -where - M::G1Affine: SerdeObject, - M::G2Affine: SerdeObject, - M::Scalar: Field, - for<'b> As: PolynomialCommitmentScheme< - M::G1Affine, - NativeLoader, - VerifyingKey = KzgSvk, - Output = KzgAccumulator, - > + AccumulationSchemeProver< - M::G1Affine, - Accumulator = KzgAccumulator, - ProvingKey = KzgAsProvingKey, - > + AccumulationDecider>, -{ - /// Create an Aggregation circuit with aggregated accumulator computed. - /// Returns `None` if any given snark is invalid. - pub fn new( - params: &ParamsKZG, - snarks: impl IntoIterator>, - ) -> Result { - let snarks = snarks.into_iter().collect_vec(); - - let accumulator_limbs = aggregate::(params, snarks.clone())?; - let instances = iter::empty() - // Propagate aggregated snarks' instances - .chain( - snarks - .iter() - .flat_map(|snark| snark.instances.clone()) - .flatten(), - ) - // Output aggregated accumulator - .chain(accumulator_limbs) - .collect_vec(); - - Ok(Self { - svk: KzgSvk::::new(params.get_g()[0]), - snarks: snarks.into_iter().map_into().collect(), - instances, - _marker: PhantomData, - }) - } - - /// Returns accumulator indices in instance columns, which will be in - /// the last 4 * LIMBS rows of MainGate's instance column. - pub fn accumulator_indices(&self) -> Vec<(usize, usize)> { - (self.instances.len() - 4 * LIMBS..) - .map(|idx| (0, idx)) - .take(4 * LIMBS) - .collect() - } - - /// Returns number of instance - pub fn num_instance(&self) -> Vec { - vec![self.instances.len()] - } - - /// Returns instances - pub fn instances(&self) -> Vec> { - vec![self.instances.clone()] - } -} - -impl<'a, M: MultiMillerLoop, As> Circuit for TestAggregationCircuit<'a, M, As> -where - M::Scalar: Field, - for<'b> As: PolynomialCommitmentScheme< - M::G1Affine, - Rc>, - VerifyingKey = KzgSvk, - Output = KzgAccumulator>>, - > + AccumulationScheme< - M::G1Affine, - Rc>, - Accumulator = KzgAccumulator>>, - VerifyingKey = KzgAsVerifyingKey, - >, -{ - type Config = AggregationConfig; - type FloorPlanner = SimpleFloorPlanner; - type Params = (); - - fn without_witnesses(&self) -> Self { - Self { - svk: self.svk, - snarks: self - .snarks - .iter() - .map(SnarkWitness::without_witnesses) - .collect(), - instances: vec![M::Scalar::ZERO; self.instances.len()], - _marker: PhantomData, - } - } - - fn configure(meta: &mut ConstraintSystem) -> Self::Config { - AggregationConfig::configure::(meta) - } - - fn synthesize( - &self, - config: Self::Config, - mut layouter: impl Layouter, - ) -> Result<(), Error> { - config.load_table(&mut layouter)?; - let (instances, accumulator_limbs) = - config.aggregate::(&mut layouter, &self.svk, self.snarks.clone())?; - - // Constrain equality to instance values - let main_gate = config.main_gate(); - for (row, limb) in instances - .into_iter() - .flatten() - .flatten() - .chain(accumulator_limbs) - .enumerate() - { - main_gate.expose_public(layouter.namespace(|| ""), limb, row)?; - } - - Ok(()) - } -} - /// Contains TestAggregationCircuit to test whether aggregation is working for /// any given inputs. #[cfg(test)] diff --git a/zkevm-circuits/src/root_circuit/dev.rs b/zkevm-circuits/src/root_circuit/dev.rs new file mode 100644 index 0000000000..c3a8d778d1 --- /dev/null +++ b/zkevm-circuits/src/root_circuit/dev.rs @@ -0,0 +1,154 @@ +use super::{aggregate, AggregationConfig, Halo2Loader, KzgSvk, Snark, SnarkWitness, LIMBS}; +use eth_types::Field; +use halo2_proofs::{ + circuit::{Layouter, SimpleFloorPlanner}, + halo2curves::{ff::Field as Halo2Field, serde::SerdeObject}, + plonk::{Circuit, ConstraintSystem, Error}, + poly::{commitment::ParamsProver, kzg::commitment::ParamsKZG}, +}; +use itertools::Itertools; +use maingate::MainGateInstructions; +use snark_verifier::{ + loader::native::NativeLoader, + pcs::{ + kzg::*, AccumulationDecider, AccumulationScheme, AccumulationSchemeProver, + PolynomialCommitmentScheme, + }, + util::arithmetic::MultiMillerLoop, +}; +use std::{iter, marker::PhantomData, rc::Rc}; + +/// Aggregation circuit for testing purpose. +#[derive(Clone)] +pub struct TestAggregationCircuit<'a, M: MultiMillerLoop, As> { + svk: KzgSvk, + snarks: Vec>, + instances: Vec, + _marker: PhantomData, +} + +impl<'a, M: MultiMillerLoop, As> TestAggregationCircuit<'a, M, As> +where + M::G1Affine: SerdeObject, + M::G2Affine: SerdeObject, + M::Scalar: Field, + for<'b> As: PolynomialCommitmentScheme< + M::G1Affine, + NativeLoader, + VerifyingKey = KzgSvk, + Output = KzgAccumulator, + > + AccumulationSchemeProver< + M::G1Affine, + Accumulator = KzgAccumulator, + ProvingKey = KzgAsProvingKey, + > + AccumulationDecider>, +{ + /// Create an Aggregation circuit with aggregated accumulator computed. + /// Returns `None` if any given snark is invalid. + pub fn new( + params: &ParamsKZG, + snarks: impl IntoIterator>, + ) -> Result { + let snarks = snarks.into_iter().collect_vec(); + + let accumulator_limbs = aggregate::(params, snarks.clone())?; + let instances = iter::empty() + // Propagate aggregated snarks' instances + .chain( + snarks + .iter() + .flat_map(|snark| snark.instances.clone()) + .flatten(), + ) + // Output aggregated accumulator + .chain(accumulator_limbs) + .collect_vec(); + + Ok(Self { + svk: KzgSvk::::new(params.get_g()[0]), + snarks: snarks.into_iter().map_into().collect(), + instances, + _marker: PhantomData, + }) + } + + /// Returns accumulator indices in instance columns, which will be in + /// the last 4 * LIMBS rows of MainGate's instance column. + pub fn accumulator_indices(&self) -> Vec<(usize, usize)> { + (self.instances.len() - 4 * LIMBS..) + .map(|idx| (0, idx)) + .take(4 * LIMBS) + .collect() + } + + /// Returns number of instance + pub fn num_instance(&self) -> Vec { + vec![self.instances.len()] + } + + /// Returns instances + pub fn instances(&self) -> Vec> { + vec![self.instances.clone()] + } +} + +impl<'a, M: MultiMillerLoop, As> Circuit for TestAggregationCircuit<'a, M, As> +where + M::Scalar: Field, + for<'b> As: PolynomialCommitmentScheme< + M::G1Affine, + Rc>, + VerifyingKey = KzgSvk, + Output = KzgAccumulator>>, + > + AccumulationScheme< + M::G1Affine, + Rc>, + Accumulator = KzgAccumulator>>, + VerifyingKey = KzgAsVerifyingKey, + >, +{ + type Config = AggregationConfig; + type FloorPlanner = SimpleFloorPlanner; + type Params = (); + + fn without_witnesses(&self) -> Self { + Self { + svk: self.svk, + snarks: self + .snarks + .iter() + .map(SnarkWitness::without_witnesses) + .collect(), + instances: vec![M::Scalar::ZERO; self.instances.len()], + _marker: PhantomData, + } + } + + fn configure(meta: &mut ConstraintSystem) -> Self::Config { + AggregationConfig::configure::(meta) + } + + fn synthesize( + &self, + config: Self::Config, + mut layouter: impl Layouter, + ) -> Result<(), Error> { + config.load_table(&mut layouter)?; + let (instances, accumulator_limbs) = + config.aggregate::(&mut layouter, &self.svk, self.snarks.clone())?; + + // Constrain equality to instance values + let main_gate = config.main_gate(); + for (row, limb) in instances + .into_iter() + .flatten() + .flatten() + .chain(accumulator_limbs) + .enumerate() + { + main_gate.expose_public(layouter.namespace(|| ""), limb, row)?; + } + + Ok(()) + } +} From 14f8a6bc9e1e290237e734752f4abcc79d658bc6 Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Fri, 7 Jul 2023 01:36:53 +0800 Subject: [PATCH 11/27] max degree can go --- zkevm-circuits/src/evm_circuit/util/constraint_builder.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs b/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs index 61ba458128..dbb71d5cb0 100644 --- a/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs +++ b/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs @@ -294,7 +294,6 @@ pub(crate) struct Constraints { } pub(crate) struct EVMConstraintBuilder<'a, F: Field> { - pub max_degree: usize, pub(crate) curr: Step, pub(crate) next: Step, challenges: &'a Challenges>, @@ -333,7 +332,6 @@ impl<'a, F: Field> EVMConstraintBuilder<'a, F> { execution_state: ExecutionState, ) -> Self { Self { - max_degree: MAX_DEGREE, curr, next, challenges, From 0abc7e4004790c7df8fa48025a471278c91ebe5b Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Fri, 7 Jul 2023 01:48:49 +0800 Subject: [PATCH 12/27] use dash instead of allow dead code --- zkevm-circuits/src/evm_circuit/execution.rs | 10 +++--- zkevm-circuits/src/evm_circuit/util.rs | 14 ++++---- .../evm_circuit/util/constraint_builder.rs | 5 ++- .../evm_circuit/util/math_gadget/add_words.rs | 4 +-- .../util/math_gadget/constant_division.rs | 5 ++- zkevm-circuits/src/state_circuit/dev.rs | 34 +++++++++---------- .../multiple_precision_integer.rs | 2 +- zkevm-circuits/src/tx_circuit/sign_verify.rs | 14 ++++---- zkevm-circuits/src/util/cell_manager.rs | 18 +++++----- .../src/util/cell_manager_strategy.rs | 6 ++-- zkevm-circuits/src/witness/block.rs | 5 ++- 11 files changed, 52 insertions(+), 65 deletions(-) diff --git a/zkevm-circuits/src/evm_circuit/execution.rs b/zkevm-circuits/src/evm_circuit/execution.rs index c0a561c091..6ee67b15f2 100644 --- a/zkevm-circuits/src/evm_circuit/execution.rs +++ b/zkevm-circuits/src/evm_circuit/execution.rs @@ -311,10 +311,8 @@ pub struct ExecutionConfig { error_oog_code_store: Box>, error_invalid_jump: Box>, error_invalid_opcode: Box>, - #[allow(dead_code)] // will be implemented soon - error_depth: Box>, - #[allow(dead_code)] // will be implemented soon - error_contract_address_collision: + _error_depth: Box>, + _error_contract_address_collision: Box>, error_invalid_creation_code: Box>, error_return_data_out_of_bound: Box>, @@ -576,8 +574,8 @@ impl ExecutionConfig { error_invalid_jump: configure_gadget!(), error_invalid_opcode: configure_gadget!(), error_write_protection: configure_gadget!(), - error_depth: configure_gadget!(), - error_contract_address_collision: configure_gadget!(), + _error_depth: configure_gadget!(), + _error_contract_address_collision: configure_gadget!(), error_invalid_creation_code: configure_gadget!(), error_return_data_out_of_bound: configure_gadget!(), // step and presets diff --git a/zkevm-circuits/src/evm_circuit/util.rs b/zkevm-circuits/src/evm_circuit/util.rs index 94cbc890f3..0f65c822df 100644 --- a/zkevm-circuits/src/evm_circuit/util.rs +++ b/zkevm-circuits/src/evm_circuit/util.rs @@ -506,7 +506,7 @@ mod tests { .sum::(); assert_eq!( - cm.get(CellType::StoragePhase1).unwrap().len(), + cm._get(CellType::StoragePhase1).unwrap().len(), STEP_WIDTH - N_PHASE2_COLUMNS - N_COPY_COLUMNS @@ -515,27 +515,27 @@ mod tests { - N_U16_LOOKUPS ); assert_eq!( - cm.get(CellType::StoragePhase2).unwrap().len(), + cm._get(CellType::StoragePhase2).unwrap().len(), N_PHASE2_COLUMNS ); assert_eq!( - cm.get(CellType::StoragePermutation).unwrap().len(), + cm._get(CellType::StoragePermutation).unwrap().len(), N_COPY_COLUMNS ); // CellType::Lookup for &(table, count) in LOOKUP_CONFIG { - assert_eq!(cm.get(CellType::Lookup(table)).unwrap().len(), count); + assert_eq!(cm._get(CellType::Lookup(table)).unwrap().len(), count); } assert_eq!( - cm.get(CellType::Lookup(Table::U8)).unwrap().len(), + cm._get(CellType::Lookup(Table::U8)).unwrap().len(), N_U8_LOOKUPS ); if N_U16_LOOKUPS == 0 { - assert!(cm.get(CellType::Lookup(Table::U16)).is_none()); + assert!(cm._get(CellType::Lookup(Table::U16)).is_none()); } else { assert_eq!( - cm.get(CellType::Lookup(Table::U16)).unwrap().len(), + cm._get(CellType::Lookup(Table::U16)).unwrap().len(), N_U16_LOOKUPS ); } diff --git a/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs b/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs index dbb71d5cb0..cf461fa0d0 100644 --- a/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs +++ b/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs @@ -276,8 +276,7 @@ impl BaseConstraintBuilder { enum ConstraintLocation { Step, StepFirst, - #[allow(dead_code)] // step last is meaningful - StepLast, + _StepLast, NotStepLast, } @@ -1457,7 +1456,7 @@ impl<'a, F: Field> EVMConstraintBuilder<'a, F> { match self.constraints_location { ConstraintLocation::Step => self.constraints.step.push((name, constraint)), ConstraintLocation::StepFirst => self.constraints.step_first.push((name, constraint)), - ConstraintLocation::StepLast => self.constraints.step_last.push((name, constraint)), + ConstraintLocation::_StepLast => self.constraints.step_last.push((name, constraint)), ConstraintLocation::NotStepLast => { self.constraints.not_step_last.push((name, constraint)) } diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/add_words.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/add_words.rs index ee947a7d86..da330056bc 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/add_words.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget/add_words.rs @@ -135,7 +135,7 @@ impl Ok(()) } - pub(crate) fn addends(&self) -> &[Word32Cell] { + pub(crate) fn _addends(&self) -> &[Word32Cell] { &self.addends } @@ -179,7 +179,7 @@ mod tests { sum.clone(), ); - assert_eq!(addwords_gadget.addends().len(), N_ADDENDS); + assert_eq!(addwords_gadget._addends().len(), N_ADDENDS); if !CHECK_OVERFLOW { let carry_hi = addwords_gadget.carry().as_ref().unwrap(); cb.require_equal("carry_hi is correct", carry_hi.expr(), CARRY_HI.expr()) diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/constant_division.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/constant_division.rs index 56d5e45432..25d0008d9b 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/constant_division.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget/constant_division.rs @@ -60,8 +60,7 @@ impl ConstantDivisionGadget { self.quotient.expr() } - #[allow(dead_code)] - pub(crate) fn remainder(&self) -> Expression { + pub(crate) fn _remainder(&self) -> Expression { self.remainder.expr() } @@ -123,7 +122,7 @@ mod tests { cb.require_equal( "correct reminder", - constdiv_gadget.remainder(), + constdiv_gadget._remainder(), REMAINDER.expr(), ); diff --git a/zkevm-circuits/src/state_circuit/dev.rs b/zkevm-circuits/src/state_circuit/dev.rs index 6a6babf714..ea80eb73f6 100644 --- a/zkevm-circuits/src/state_circuit/dev.rs +++ b/zkevm-circuits/src/state_circuit/dev.rs @@ -66,36 +66,34 @@ where #[cfg(test)] use halo2_proofs::plonk::{Advice, Column}; -// allow dead code for unconstructed variants -#[allow(dead_code)] #[cfg(test)] #[derive(Hash, Eq, PartialEq, Clone, Debug)] pub(crate) enum AdviceColumn { IsWrite, - Address, + _Address, AddressLimb0, AddressLimb1, - StorageKeyLo, - StorageKeyHi, + _StorageKeyLo, + _StorageKeyHi, StorageKeyLimb0, - StorageKeyLimb1, + _StorageKeyLimb1, ValueLo, ValueHi, ValuePrevLo, ValuePrevHi, RwCounter, RwCounterLimb0, - RwCounterLimb1, + _RwCounterLimb1, Tag, TagBit0, TagBit1, TagBit2, TagBit3, - LimbIndexBit0, // most significant bit + _LimbIndexBit0, // most significant bit LimbIndexBit1, LimbIndexBit2, - LimbIndexBit3, - LimbIndexBit4, // least significant bit + _LimbIndexBit3, + _LimbIndexBit4, // least significant bit InitialValueLo, InitialValueHi, IsZero, // committed_value and value are 0 @@ -109,30 +107,30 @@ impl AdviceColumn { pub(crate) fn value(&self, config: &StateCircuitConfig) -> Column { match self { Self::IsWrite => config.rw_table.is_write, - Self::Address => config.rw_table.address, + Self::_Address => config.rw_table.address, Self::AddressLimb0 => config.sort_keys.address.limbs[0], Self::AddressLimb1 => config.sort_keys.address.limbs[1], - Self::StorageKeyLo => config.rw_table.storage_key.lo(), - Self::StorageKeyHi => config.rw_table.storage_key.hi(), + Self::_StorageKeyLo => config.rw_table.storage_key.lo(), + Self::_StorageKeyHi => config.rw_table.storage_key.hi(), Self::StorageKeyLimb0 => config.sort_keys.storage_key.limbs[0], - Self::StorageKeyLimb1 => config.sort_keys.storage_key.limbs[1], + Self::_StorageKeyLimb1 => config.sort_keys.storage_key.limbs[1], Self::ValueLo => config.rw_table.value.lo(), Self::ValueHi => config.rw_table.value.hi(), Self::ValuePrevLo => config.rw_table.value_prev.lo(), Self::ValuePrevHi => config.rw_table.value_prev.hi(), Self::RwCounter => config.rw_table.rw_counter, Self::RwCounterLimb0 => config.sort_keys.rw_counter.limbs[0], - Self::RwCounterLimb1 => config.sort_keys.rw_counter.limbs[1], + Self::_RwCounterLimb1 => config.sort_keys.rw_counter.limbs[1], Self::Tag => config.rw_table.tag, Self::TagBit0 => config.sort_keys.tag.bits[0], Self::TagBit1 => config.sort_keys.tag.bits[1], Self::TagBit2 => config.sort_keys.tag.bits[2], Self::TagBit3 => config.sort_keys.tag.bits[3], - Self::LimbIndexBit0 => config.lexicographic_ordering.first_different_limb.bits[0], + Self::_LimbIndexBit0 => config.lexicographic_ordering.first_different_limb.bits[0], Self::LimbIndexBit1 => config.lexicographic_ordering.first_different_limb.bits[1], Self::LimbIndexBit2 => config.lexicographic_ordering.first_different_limb.bits[2], - Self::LimbIndexBit3 => config.lexicographic_ordering.first_different_limb.bits[3], - Self::LimbIndexBit4 => config.lexicographic_ordering.first_different_limb.bits[4], + Self::_LimbIndexBit3 => config.lexicographic_ordering.first_different_limb.bits[3], + Self::_LimbIndexBit4 => config.lexicographic_ordering.first_different_limb.bits[4], Self::InitialValueLo => config.initial_value.lo(), Self::InitialValueHi => config.initial_value.hi(), Self::IsZero => config.is_non_exist.is_zero, diff --git a/zkevm-circuits/src/state_circuit/multiple_precision_integer.rs b/zkevm-circuits/src/state_circuit/multiple_precision_integer.rs index 0ea236faa5..89cffa0bee 100644 --- a/zkevm-circuits/src/state_circuit/multiple_precision_integer.rs +++ b/zkevm-circuits/src/state_circuit/multiple_precision_integer.rs @@ -112,7 +112,7 @@ pub struct Chip where T: ToLimbs, { - config: Config, + _config: Config, _marker: PhantomData, } diff --git a/zkevm-circuits/src/tx_circuit/sign_verify.rs b/zkevm-circuits/src/tx_circuit/sign_verify.rs index 2be373ca22..e1c3bd2b4c 100644 --- a/zkevm-circuits/src/tx_circuit/sign_verify.rs +++ b/zkevm-circuits/src/tx_circuit/sign_verify.rs @@ -125,8 +125,7 @@ pub(crate) struct SignVerifyConfig { rlc: Column, // Keccak q_keccak: Selector, - #[allow(dead_code)] // We need keccak_table for test - keccak_table: KeccakTable, + _keccak_table: KeccakTable, } impl SignVerifyConfig { @@ -198,7 +197,7 @@ impl SignVerifyConfig { Self { range_config, main_gate_config, - keccak_table, + _keccak_table: keccak_table, q_rlc_keccak_input, rlc, q_keccak, @@ -262,8 +261,7 @@ impl SignVerifyConfig { #[derive(Clone, Debug)] pub(crate) enum Term { Assigned(Cell, Value), - #[allow(dead_code)] // We need Unassigned for match - Unassigned(Value), + _Unassigned(Value), } impl Term { @@ -274,14 +272,14 @@ impl Term { fn cell(&self) -> Option { match self { Self::Assigned(cell, _) => Some(*cell), - Self::Unassigned(_) => None, + Self::_Unassigned(_) => None, } } fn value(&self) -> Value { match self { Self::Assigned(_, value) => *value, - Self::Unassigned(value) => *value, + Self::_Unassigned(value) => *value, } } } @@ -789,7 +787,7 @@ mod sign_verify_tests { &self.signatures, &challenges, )?; - config.sign_verify.keccak_table.dev_load( + config.sign_verify._keccak_table.dev_load( &mut layouter, &keccak_inputs_sign_verify(&self.signatures), &challenges, diff --git a/zkevm-circuits/src/util/cell_manager.rs b/zkevm-circuits/src/util/cell_manager.rs index 110999eec4..4a0ee703dd 100644 --- a/zkevm-circuits/src/util/cell_manager.rs +++ b/zkevm-circuits/src/util/cell_manager.rs @@ -1,5 +1,3 @@ -// Temporarly allow dead code before the strategy is fully implemented -#![allow(dead_code)] use std::collections::HashMap; use eth_types::Field; @@ -58,9 +56,9 @@ impl CellType { /// Cell is a (column, rotation) pair that has been placed and queried by the Cell Manager. pub struct Cell { pub(crate) expression: Expression, - pub(crate) column_expression: Expression, + pub(crate) _column_expression: Expression, pub(crate) column: Column, - pub(crate) column_idx: usize, + pub(crate) _column_idx: usize, pub(crate) rotation: usize, } @@ -69,14 +67,14 @@ impl Cell { pub fn new( meta: &mut VirtualCells, column: Column, - column_idx: usize, + _column_idx: usize, rotation: usize, ) -> Cell { Cell { expression: meta.query_advice(column, Rotation(rotation as i32)), - column_expression: meta.query_advice(column, Rotation::cur()), + _column_expression: meta.query_advice(column, Rotation::cur()), column, - column_idx, + _column_idx, rotation, } } @@ -217,7 +215,7 @@ impl CellManagerColumns { } /// Returns the number of columns. - pub fn get_width(&self) -> usize { + pub fn _get_width(&self) -> usize { self.columns_list.len() } } @@ -272,8 +270,8 @@ impl> CellManager { } /// Returns the number of columns managed by this Cell Manager. - pub fn get_width(&self) -> usize { - self.columns.get_width() + pub fn _get_width(&self) -> usize { + self.columns._get_width() } /// Returns the statistics about this Cell Manager. diff --git a/zkevm-circuits/src/util/cell_manager_strategy.rs b/zkevm-circuits/src/util/cell_manager_strategy.rs index 5097e7fd83..02a3006043 100644 --- a/zkevm-circuits/src/util/cell_manager_strategy.rs +++ b/zkevm-circuits/src/util/cell_manager_strategy.rs @@ -1,5 +1,3 @@ -// Temporarly allow dead code before the strategy is fully implemented -#![allow(dead_code)] use std::collections::{BTreeMap, HashMap}; use eth_types::Field; @@ -19,7 +17,7 @@ impl CMFixedWidthStrategyDistribution { } } - pub(crate) fn get(&self, cell_type: CellType) -> Option<&Vec>> { + pub(crate) fn _get(&self, cell_type: CellType) -> Option<&Vec>> { self.0.get(&cell_type) } } @@ -192,7 +190,7 @@ pub(crate) struct CMFixedHeigthStrategy { } impl CMFixedHeigthStrategy { - pub(crate) fn new(height: usize, cell_type: CellType) -> CMFixedHeigthStrategy { + pub(crate) fn _new(height: usize, cell_type: CellType) -> CMFixedHeigthStrategy { CMFixedHeigthStrategy { row_width: vec![0; height], cell_type, diff --git a/zkevm-circuits/src/witness/block.rs b/zkevm-circuits/src/witness/block.rs index fcfc578544..bceeb5cd5e 100644 --- a/zkevm-circuits/src/witness/block.rs +++ b/zkevm-circuits/src/witness/block.rs @@ -55,11 +55,10 @@ pub struct Block { } impl Block { - // This function is useful for debug so we allow it as a deadcode - #[allow(dead_code)] /// For each tx, for each step, print the rwc at the beginning of the step, /// and all the rw operations of the step. - pub(crate) fn debug_print_txs_steps_rw_ops(&self) { + /// This function is useful for debug so we allow it as a deadcode + pub(crate) fn _debug_print_txs_steps_rw_ops(&self) { for (tx_idx, tx) in self.txs.iter().enumerate() { println!("tx {}", tx_idx); for step in tx.steps() { From edd9d0ef570572c3d999f6ffb89551b91fd9aa9c Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Fri, 7 Jul 2023 02:02:28 +0800 Subject: [PATCH 13/27] fmt --- zkevm-circuits/src/evm_circuit/util/math_gadget/test_util.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/test_util.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/test_util.rs index 6f186838ce..472658dbbe 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/test_util.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget/test_util.rs @@ -21,9 +21,7 @@ pub(crate) use halo2_proofs::circuit::{Layouter, Value}; use halo2_proofs::{ circuit::SimpleFloorPlanner, dev::MockProver, - plonk::{ - Circuit, ConstraintSystem, Error, FirstPhase, SecondPhase, Selector, ThirdPhase, - }, + plonk::{Circuit, ConstraintSystem, Error, FirstPhase, SecondPhase, Selector, ThirdPhase}, }; pub(crate) const WORD_LOW_MAX: Word = U256([u64::MAX, u64::MAX, 0, 0]); From 14c370116e8082c85433d0ca5a4559382512f4ea Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Fri, 7 Jul 2023 02:06:52 +0800 Subject: [PATCH 14/27] comment --- zkevm-circuits/Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/zkevm-circuits/Cargo.toml b/zkevm-circuits/Cargo.toml index 735facb71b..62d3d1f8fa 100644 --- a/zkevm-circuits/Cargo.toml +++ b/zkevm-circuits/Cargo.toml @@ -51,6 +51,7 @@ serde_json = "1.0.78" default = [] # We export some test circuits for other crates to consume test-circuits = ["eth-types/warn-unimplemented"] +# Test utilities for testool crate to consume test-util = ["dep:mock"] stats = ["eth-types/warn-unimplemented", "dep:cli-table"] From 2a101e8173b001682a031fff800a653f429075f8 Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Fri, 7 Jul 2023 02:09:40 +0800 Subject: [PATCH 15/27] wave goodbye to batched is zero --- .../evm_circuit/util/constraint_builder.rs | 6 - .../src/evm_circuit/util/math_gadget.rs | 2 - .../util/math_gadget/batched_is_zero.rs | 187 ------------------ 3 files changed, 195 deletions(-) delete mode 100644 zkevm-circuits/src/evm_circuit/util/math_gadget/batched_is_zero.rs diff --git a/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs b/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs index cf461fa0d0..185b5658c4 100644 --- a/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs +++ b/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs @@ -485,12 +485,6 @@ impl<'a, F: Field> EVMConstraintBuilder<'a, F> { self.query_cells(cell_type, 1).first().unwrap().clone() } - pub(crate) fn query_bool_with_type(&mut self, cell_type: CellType) -> Cell { - let cell = self.query_cell_with_type(cell_type); - self.require_boolean("Constrain cell to be a bool", cell.expr()); - cell - } - fn query_cells(&mut self, cell_type: CellType, count: usize) -> Vec> { if self.in_next_step { &mut self.next diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget.rs index ca55ff663a..c72c3bf632 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget.rs @@ -4,8 +4,6 @@ use halo2_proofs::plonk::Expression; mod abs_word; mod add_words; -#[allow(dead_code)] // we might want to use batched is zero for something -mod batched_is_zero; mod byte_size; mod cmp_words; mod comparison; diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/batched_is_zero.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/batched_is_zero.rs deleted file mode 100644 index 02c514843a..0000000000 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/batched_is_zero.rs +++ /dev/null @@ -1,187 +0,0 @@ -use crate::{ - evm_circuit::util::{ - constraint_builder::{ConstrainBuilderCommon, EVMConstraintBuilder}, - transpose_val_ret, CachedRegion, Cell, CellType, - }, - util::Expr, -}; -use eth_types::Field; -use halo2_proofs::{ - circuit::Value, - plonk::{Error, Expression}, -}; - -#[derive(Clone, Debug)] -pub struct BatchedIsZeroGadget { - is_zero: Cell, - nonempty_witness: Cell, -} - -impl BatchedIsZeroGadget { - pub(crate) fn construct(cb: &mut EVMConstraintBuilder, values: [Expression; N]) -> Self { - let max_values_phase = values - .iter() - .map(CellType::expr_phase) - .max() - .expect("BatchedIsZeroGadget needs at least one expression"); - - let cell_type = CellType::storage_for_phase(max_values_phase); - let is_zero = cb.query_bool_with_type(cell_type); - let nonempty_witness = cb.query_cell_with_type(cell_type); - - for value in values.iter() { - cb.require_zero( - "is_zero is 0 if there is any non-zero value", - is_zero.expr() * value.clone(), - ); - } - - cb.require_zero( - "is_zero is 1 if values are all zero", - values.iter().fold(1.expr() - is_zero.expr(), |acc, value| { - acc * (1.expr() - value.expr() * nonempty_witness.clone().expr()) - }), - ); - - Self { - is_zero, - nonempty_witness, - } - } - - pub(crate) fn expr(&self) -> Expression { - self.is_zero.expr() - } - - pub(crate) fn assign( - &self, - region: &mut CachedRegion<'_, '_, F>, - offset: usize, - values: [F; N], - ) -> Result { - let is_zero = - if let Some(inverse) = values.iter().find_map(|value| Option::from(value.invert())) { - self.nonempty_witness - .assign(region, offset, Value::known(inverse))?; - F::ZERO - } else { - F::ONE - }; - self.is_zero.assign(region, offset, Value::known(is_zero))?; - - Ok(is_zero) - } - - pub(crate) fn assign_value( - &self, - region: &mut CachedRegion<'_, '_, F>, - offset: usize, - values: [Value; N], - ) -> Result, Error> { - let values: Value<[F; N]> = - Value::>::from_iter(values).map(|vv| vv.try_into().unwrap()); - transpose_val_ret(values.map(|values| self.assign(region, offset, values))) - } -} - -#[cfg(test)] -mod tests { - use super::{super::test_util::*, *}; - use eth_types::*; - use halo2_proofs::{halo2curves::bn256::Fr, plonk::Error}; - - #[derive(Clone)] - /// IsZeroGadgetTestContainer: require(all(cells) == 0) - struct IsZeroGadgetTestContainer { - z_gadget: BatchedIsZeroGadget, - nums: [Cell; N], - } - - impl MathGadgetContainer for IsZeroGadgetTestContainer { - fn configure_gadget_container(cb: &mut EVMConstraintBuilder) -> Self { - let nums = [(); N].map(|_| cb.query_cell()); - let z_gadget = BatchedIsZeroGadget::::construct( - cb, - nums.iter() - .map(|cell| cell.expr()) - .collect::>>() - .try_into() - .unwrap(), - ); - cb.require_equal("Input must be all 0", z_gadget.expr(), 1.expr()); - IsZeroGadgetTestContainer { z_gadget, nums } - } - - fn assign_gadget_container( - &self, - witnesses: &[Word], - region: &mut CachedRegion<'_, '_, F>, - ) -> Result<(), Error> { - let values = witnesses - .iter() - .map(|num| num.to_scalar().unwrap()) - .collect::>(); - let offset = 0; - - for (i, num) in self.nums.iter().enumerate() { - num.assign(region, offset, Value::known(values[i]))?; - } - self.z_gadget - .assign(region, offset, values.try_into().unwrap())?; - - Ok(()) - } - } - - #[test] - fn test_batched_iszero() { - try_test!(IsZeroGadgetTestContainer, [Word::from(0); 5], true); - } - - #[test] - fn test_batched_1_in_array_not_iszero() { - try_test!( - IsZeroGadgetTestContainer, - vec![ - Word::from(0), - Word::from(1), - Word::from(0), - Word::from(0), - Word::from(0), - ], - false - ); - } - - #[test] - fn test_batched_big_array_not_iszero() { - let mut test_nums = vec![Word::from(1)]; - test_nums.extend(vec![Word::from(0); 31]); - try_test!(IsZeroGadgetTestContainer, test_nums, false); - } - - #[test] - fn test_batched_single_cell_iszero() { - try_test!(IsZeroGadgetTestContainer, [Word::from(0)], true); - } - - #[test] - fn test_batched_single_cell_not_iszero() { - try_test!(IsZeroGadgetTestContainer, vec![WORD_LOW_MAX], false); - } - - #[test] - fn test_batched_wordmax_bytes_not_iszero() { - try_test!( - IsZeroGadgetTestContainer, - vec![ - WORD_LOW_MAX, - WORD_LOW_MAX, - WORD_LOW_MAX, - WORD_LOW_MAX, - WORD_LOW_MAX, - ], - false - ); - } -} From 611f0c0e4c28393eb1be652536f42d2077555388 Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Fri, 7 Jul 2023 02:53:40 +0800 Subject: [PATCH 16/27] minimize impact on features flag --- zkevm-circuits/Cargo.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zkevm-circuits/Cargo.toml b/zkevm-circuits/Cargo.toml index 62d3d1f8fa..a499952828 100644 --- a/zkevm-circuits/Cargo.toml +++ b/zkevm-circuits/Cargo.toml @@ -50,11 +50,11 @@ serde_json = "1.0.78" [features] default = [] # We export some test circuits for other crates to consume -test-circuits = ["eth-types/warn-unimplemented"] +test-circuits = [] # Test utilities for testool crate to consume test-util = ["dep:mock"] - -stats = ["eth-types/warn-unimplemented", "dep:cli-table"] +warn-unimplemented = ["eth-types/warn-unimplemented"] +stats = ["warn-unimplemented", "dep:cli-table"] [[bin]] name = "stats" From 478da29a496d8f0325dda0385f352f08c2fe4142 Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Fri, 7 Jul 2023 15:24:19 +0800 Subject: [PATCH 17/27] super circuit test has no exports --- zkevm-circuits/src/super_circuit.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zkevm-circuits/src/super_circuit.rs b/zkevm-circuits/src/super_circuit.rs index 6f769b151e..35c6357aee 100644 --- a/zkevm-circuits/src/super_circuit.rs +++ b/zkevm-circuits/src/super_circuit.rs @@ -50,7 +50,7 @@ //! - [x] Tx Circuit //! - [ ] MPT Circuit -#[cfg(any(feature = "test", test))] +#[cfg(test)] pub(crate) mod test; use crate::{ From 65df70aa6a88683bd0dca79a6d7e1ed0bd0dd20a Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Fri, 7 Jul 2023 15:27:03 +0800 Subject: [PATCH 18/27] update test features --- .github/workflows/test-features.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test-features.yml b/.github/workflows/test-features.yml index eb43f61c97..c22f67eec3 100644 --- a/.github/workflows/test-features.yml +++ b/.github/workflows/test-features.yml @@ -35,8 +35,8 @@ jobs: - zkevm-circuits feature: - default - - test - test-circuits + - test-util - warn-unimplemented steps: - uses: actions/checkout@v2 From ac7f2fd34da58b285a66b93d14f1e2d428accd7e Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Fri, 7 Jul 2023 17:11:27 +0800 Subject: [PATCH 19/27] dummy cols are required in test circuits --- zkevm-circuits/src/util.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/zkevm-circuits/src/util.rs b/zkevm-circuits/src/util.rs index fc86c59101..037d0a9a16 100644 --- a/zkevm-circuits/src/util.rs +++ b/zkevm-circuits/src/util.rs @@ -43,6 +43,10 @@ pub struct Challenges { impl Challenges { /// Construct `Challenges` by allocating challenges in specific phases. pub fn construct(meta: &mut ConstraintSystem) -> Self { + // Dummy columns are required in the test circuits + // In some tests there might be no advice columns before the phase, so Halo2 will panic with + // "No Column is used in phase Phase(1) while allocating a new 'Challenge usable + // after phase Phase(1)'" #[cfg(any(test, feature = "test-circuits"))] let _dummy_cols = [meta.advice_column(), meta.advice_column_in(SecondPhase)]; From 438c617d1f9e4846cdcc8bcc9481ef7084a0f7dd Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Fri, 7 Jul 2023 22:10:16 +0800 Subject: [PATCH 20/27] rm StepLast --- zkevm-circuits/src/evm_circuit/util/constraint_builder.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs b/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs index 185b5658c4..21415874d2 100644 --- a/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs +++ b/zkevm-circuits/src/evm_circuit/util/constraint_builder.rs @@ -276,7 +276,6 @@ impl BaseConstraintBuilder { enum ConstraintLocation { Step, StepFirst, - _StepLast, NotStepLast, } @@ -1450,7 +1449,6 @@ impl<'a, F: Field> EVMConstraintBuilder<'a, F> { match self.constraints_location { ConstraintLocation::Step => self.constraints.step.push((name, constraint)), ConstraintLocation::StepFirst => self.constraints.step_first.push((name, constraint)), - ConstraintLocation::_StepLast => self.constraints.step_last.push((name, constraint)), ConstraintLocation::NotStepLast => { self.constraints.not_step_last.push((name, constraint)) } From 26b3527c028c204a758ab14222ff02e04b6b91d5 Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Mon, 10 Jul 2023 15:18:13 +0800 Subject: [PATCH 21/27] typo fix 'remainder' --- .../src/evm_circuit/util/math_gadget/constant_division.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/constant_division.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/constant_division.rs index 25d0008d9b..e231925e20 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/constant_division.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget/constant_division.rs @@ -121,7 +121,7 @@ mod tests { ConstantDivisionGadget::::construct(cb, a.expr(), DENOMINATOR); cb.require_equal( - "correct reminder", + "correct remainder", constdiv_gadget._remainder(), REMAINDER.expr(), ); From 2868dbe81c0d14f5fbdf76a58ed69a52e1b12bb7 Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Mon, 10 Jul 2023 15:20:31 +0800 Subject: [PATCH 22/27] remove pub(crate) for unused variables --- zkevm-circuits/src/util/cell_manager.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zkevm-circuits/src/util/cell_manager.rs b/zkevm-circuits/src/util/cell_manager.rs index 4a0ee703dd..fc968057fd 100644 --- a/zkevm-circuits/src/util/cell_manager.rs +++ b/zkevm-circuits/src/util/cell_manager.rs @@ -56,9 +56,9 @@ impl CellType { /// Cell is a (column, rotation) pair that has been placed and queried by the Cell Manager. pub struct Cell { pub(crate) expression: Expression, - pub(crate) _column_expression: Expression, + _column_expression: Expression, pub(crate) column: Column, - pub(crate) _column_idx: usize, + _column_idx: usize, pub(crate) rotation: usize, } From 6d229b1d21dc5f32e717110cb6635c83f5af7e96 Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Mon, 10 Jul 2023 15:49:36 +0800 Subject: [PATCH 23/27] uX tables are dead code now --- zkevm-circuits/src/state_circuit.rs | 9 --------- zkevm-circuits/src/state_circuit/dev.rs | 4 +--- 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/zkevm-circuits/src/state_circuit.rs b/zkevm-circuits/src/state_circuit.rs index 6987817e12..ed096760c4 100644 --- a/zkevm-circuits/src/state_circuit.rs +++ b/zkevm-circuits/src/state_circuit.rs @@ -69,12 +69,6 @@ pub struct StateCircuitConfig { lookups: LookupsConfig, // External tables mpt_table: MptTable, - // External U8Table - u8_table: UXTable<8>, - // External U10Table - u10_table: UXTable<10>, - // External U16Table - u16_table: UXTable<16>, _marker: PhantomData, } @@ -174,9 +168,6 @@ impl SubCircuitConfig for StateCircuitConfig { lookups, rw_table, mpt_table, - u8_table, - u10_table, - u16_table, _marker: PhantomData::default(), }; diff --git a/zkevm-circuits/src/state_circuit/dev.rs b/zkevm-circuits/src/state_circuit/dev.rs index ea80eb73f6..796c85cfea 100644 --- a/zkevm-circuits/src/state_circuit/dev.rs +++ b/zkevm-circuits/src/state_circuit/dev.rs @@ -56,9 +56,7 @@ where ) -> Result<(), Error> { let challenges = challenges.values(&mut layouter); config.mpt_table.load(&mut layouter, &self.updates)?; - config.u8_table.load(&mut layouter)?; - config.u10_table.load(&mut layouter)?; - config.u16_table.load(&mut layouter)?; + config.load_aux_tables(&mut layouter)?; self.synthesize_sub(&config, &challenges, &mut layouter) } } From 8740aeb8a0e3cb19870da7f195a7501ff7362e68 Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Mon, 10 Jul 2023 15:59:11 +0800 Subject: [PATCH 24/27] rm keccak dead code --- zkevm-circuits/src/tx_circuit.rs | 5 +---- zkevm-circuits/src/tx_circuit/dev.rs | 10 +++++----- zkevm-circuits/src/tx_circuit/sign_verify.rs | 2 +- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/zkevm-circuits/src/tx_circuit.rs b/zkevm-circuits/src/tx_circuit.rs index 3c2f2e5191..162d00c5c2 100644 --- a/zkevm-circuits/src/tx_circuit.rs +++ b/zkevm-circuits/src/tx_circuit.rs @@ -44,8 +44,6 @@ pub struct TxCircuitConfig { value: Word>, sign_verify: SignVerifyConfig, _marker: PhantomData, - // External tables - keccak_table: KeccakTable, } /// Circuit configuration arguments @@ -77,7 +75,7 @@ impl SubCircuitConfig for TxCircuitConfig { meta.enable_equality(value.lo()); meta.enable_equality(value.hi()); - let sign_verify = SignVerifyConfig::new(meta, keccak_table.clone(), challenges); + let sign_verify = SignVerifyConfig::new(meta, keccak_table, challenges); Self { tx_id, @@ -85,7 +83,6 @@ impl SubCircuitConfig for TxCircuitConfig { index, value, sign_verify, - keccak_table, _marker: PhantomData, } } diff --git a/zkevm-circuits/src/tx_circuit/dev.rs b/zkevm-circuits/src/tx_circuit/dev.rs index 38f210ad53..fa4f4e3288 100644 --- a/zkevm-circuits/src/tx_circuit/dev.rs +++ b/zkevm-circuits/src/tx_circuit/dev.rs @@ -14,7 +14,7 @@ use halo2_proofs::{ use log::error; impl Circuit for TxCircuit { - type Config = (TxCircuitConfig, Challenges); + type Config = (TxCircuitConfig, Challenges, KeccakTable); type FloorPlanner = SimpleFloorPlanner; type Params = (); @@ -33,23 +33,23 @@ impl Circuit for TxCircuit { meta, TxCircuitConfigArgs { tx_table, - keccak_table, + keccak_table: keccak_table.clone(), challenges, }, ) }; - (config, challenges) + (config, challenges, keccak_table) } fn synthesize( &self, - (config, challenges): Self::Config, + (config, challenges, keccak_table): Self::Config, mut layouter: impl Layouter, ) -> Result<(), Error> { let challenges = challenges.values(&mut layouter); - config.keccak_table.dev_load( + keccak_table.dev_load( &mut layouter, &keccak_inputs_tx_circuit(&self.txs[..], self.chain_id).map_err(|e| { error!("keccak_inputs_tx_circuit error: {:?}", e); diff --git a/zkevm-circuits/src/tx_circuit/sign_verify.rs b/zkevm-circuits/src/tx_circuit/sign_verify.rs index e1c3bd2b4c..2e9be76297 100644 --- a/zkevm-circuits/src/tx_circuit/sign_verify.rs +++ b/zkevm-circuits/src/tx_circuit/sign_verify.rs @@ -197,10 +197,10 @@ impl SignVerifyConfig { Self { range_config, main_gate_config, - _keccak_table: keccak_table, q_rlc_keccak_input, rlc, q_keccak, + _keccak_table: keccak_table.clone(), } } From 9710114ce3c9e5d9e323e909e4372dfa8ae37680 Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Mon, 10 Jul 2023 18:36:18 +0800 Subject: [PATCH 25/27] allow dead_code with reasons --- zkevm-circuits/src/evm_circuit/execution.rs | 10 ++++++---- zkevm-circuits/src/evm_circuit/util.rs | 14 +++++++------- .../src/evm_circuit/util/math_gadget/add_words.rs | 8 ++++++-- zkevm-circuits/src/lib.rs | 2 ++ zkevm-circuits/src/util/cell_manager.rs | 8 +++++--- zkevm-circuits/src/util/cell_manager_strategy.rs | 6 ++++-- zkevm-circuits/src/witness/block.rs | 4 ++-- 7 files changed, 32 insertions(+), 20 deletions(-) diff --git a/zkevm-circuits/src/evm_circuit/execution.rs b/zkevm-circuits/src/evm_circuit/execution.rs index 6ee67b15f2..ea159318c0 100644 --- a/zkevm-circuits/src/evm_circuit/execution.rs +++ b/zkevm-circuits/src/evm_circuit/execution.rs @@ -311,8 +311,10 @@ pub struct ExecutionConfig { error_oog_code_store: Box>, error_invalid_jump: Box>, error_invalid_opcode: Box>, - _error_depth: Box>, - _error_contract_address_collision: + #[allow(dead_code, reason = "under active development")] + error_depth: Box>, + #[allow(dead_code, reason = "under active development")] + error_contract_address_collision: Box>, error_invalid_creation_code: Box>, error_return_data_out_of_bound: Box>, @@ -574,8 +576,8 @@ impl ExecutionConfig { error_invalid_jump: configure_gadget!(), error_invalid_opcode: configure_gadget!(), error_write_protection: configure_gadget!(), - _error_depth: configure_gadget!(), - _error_contract_address_collision: configure_gadget!(), + error_depth: configure_gadget!(), + error_contract_address_collision: configure_gadget!(), error_invalid_creation_code: configure_gadget!(), error_return_data_out_of_bound: configure_gadget!(), // step and presets diff --git a/zkevm-circuits/src/evm_circuit/util.rs b/zkevm-circuits/src/evm_circuit/util.rs index 0f65c822df..94cbc890f3 100644 --- a/zkevm-circuits/src/evm_circuit/util.rs +++ b/zkevm-circuits/src/evm_circuit/util.rs @@ -506,7 +506,7 @@ mod tests { .sum::(); assert_eq!( - cm._get(CellType::StoragePhase1).unwrap().len(), + cm.get(CellType::StoragePhase1).unwrap().len(), STEP_WIDTH - N_PHASE2_COLUMNS - N_COPY_COLUMNS @@ -515,27 +515,27 @@ mod tests { - N_U16_LOOKUPS ); assert_eq!( - cm._get(CellType::StoragePhase2).unwrap().len(), + cm.get(CellType::StoragePhase2).unwrap().len(), N_PHASE2_COLUMNS ); assert_eq!( - cm._get(CellType::StoragePermutation).unwrap().len(), + cm.get(CellType::StoragePermutation).unwrap().len(), N_COPY_COLUMNS ); // CellType::Lookup for &(table, count) in LOOKUP_CONFIG { - assert_eq!(cm._get(CellType::Lookup(table)).unwrap().len(), count); + assert_eq!(cm.get(CellType::Lookup(table)).unwrap().len(), count); } assert_eq!( - cm._get(CellType::Lookup(Table::U8)).unwrap().len(), + cm.get(CellType::Lookup(Table::U8)).unwrap().len(), N_U8_LOOKUPS ); if N_U16_LOOKUPS == 0 { - assert!(cm._get(CellType::Lookup(Table::U16)).is_none()); + assert!(cm.get(CellType::Lookup(Table::U16)).is_none()); } else { assert_eq!( - cm._get(CellType::Lookup(Table::U16)).unwrap().len(), + cm.get(CellType::Lookup(Table::U16)).unwrap().len(), N_U16_LOOKUPS ); } diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/add_words.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/add_words.rs index da330056bc..8ad2e86284 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/add_words.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget/add_words.rs @@ -135,7 +135,11 @@ impl Ok(()) } - pub(crate) fn _addends(&self) -> &[Word32Cell] { + #[allow( + dead_code, + reason = "this method is a legit API but is currently only used in the tests" + )] + pub(crate) fn addends(&self) -> &[Word32Cell] { &self.addends } @@ -179,7 +183,7 @@ mod tests { sum.clone(), ); - assert_eq!(addwords_gadget._addends().len(), N_ADDENDS); + assert_eq!(addwords_gadget.addends().len(), N_ADDENDS); if !CHECK_OVERFLOW { let carry_hi = addwords_gadget.carry().as_ref().unwrap(); cb.require_equal("carry_hi is correct", carry_hi.expr(), CARRY_HI.expr()) diff --git a/zkevm-circuits/src/lib.rs b/zkevm-circuits/src/lib.rs index 6beb928d01..f093c5add4 100644 --- a/zkevm-circuits/src/lib.rs +++ b/zkevm-circuits/src/lib.rs @@ -5,6 +5,8 @@ #![allow(incomplete_features)] // Needed by DummyGadget in evm circuit #![feature(adt_const_params)] +// Required for adding reasons in allow(dead_code) +#![feature(lint_reasons)] // Needed by some builder patterns in testing modules. #![cfg_attr(docsrs, feature(doc_cfg))] // We want to have UPPERCASE idents sometimes. diff --git a/zkevm-circuits/src/util/cell_manager.rs b/zkevm-circuits/src/util/cell_manager.rs index fc968057fd..bf3b2a36d6 100644 --- a/zkevm-circuits/src/util/cell_manager.rs +++ b/zkevm-circuits/src/util/cell_manager.rs @@ -214,8 +214,9 @@ impl CellManagerColumns { self.columns_list.clone() } + #[allow(dead_code, reason = "under active development")] /// Returns the number of columns. - pub fn _get_width(&self) -> usize { + pub fn get_width(&self) -> usize { self.columns_list.len() } } @@ -269,9 +270,10 @@ impl> CellManager { self.columns.columns() } + #[allow(dead_code, reason = "under active development")] /// Returns the number of columns managed by this Cell Manager. - pub fn _get_width(&self) -> usize { - self.columns._get_width() + pub fn get_width(&self) -> usize { + self.columns.get_width() } /// Returns the statistics about this Cell Manager. diff --git a/zkevm-circuits/src/util/cell_manager_strategy.rs b/zkevm-circuits/src/util/cell_manager_strategy.rs index 02a3006043..3fdb486df0 100644 --- a/zkevm-circuits/src/util/cell_manager_strategy.rs +++ b/zkevm-circuits/src/util/cell_manager_strategy.rs @@ -17,7 +17,8 @@ impl CMFixedWidthStrategyDistribution { } } - pub(crate) fn _get(&self, cell_type: CellType) -> Option<&Vec>> { + #[allow(dead_code, reason = "this method will be used outside tests")] + pub(crate) fn get(&self, cell_type: CellType) -> Option<&Vec>> { self.0.get(&cell_type) } } @@ -190,7 +191,8 @@ pub(crate) struct CMFixedHeigthStrategy { } impl CMFixedHeigthStrategy { - pub(crate) fn _new(height: usize, cell_type: CellType) -> CMFixedHeigthStrategy { + #[allow(dead_code, reason = "under active development")] + pub(crate) fn new(height: usize, cell_type: CellType) -> CMFixedHeigthStrategy { CMFixedHeigthStrategy { row_width: vec![0; height], cell_type, diff --git a/zkevm-circuits/src/witness/block.rs b/zkevm-circuits/src/witness/block.rs index bceeb5cd5e..f2d93faaf7 100644 --- a/zkevm-circuits/src/witness/block.rs +++ b/zkevm-circuits/src/witness/block.rs @@ -57,8 +57,8 @@ pub struct Block { impl Block { /// For each tx, for each step, print the rwc at the beginning of the step, /// and all the rw operations of the step. - /// This function is useful for debug so we allow it as a deadcode - pub(crate) fn _debug_print_txs_steps_rw_ops(&self) { + #[allow(dead_code, reason = "useful debug function")] + pub(crate) fn debug_print_txs_steps_rw_ops(&self) { for (tx_idx, tx) in self.txs.iter().enumerate() { println!("tx {}", tx_idx); for step in tx.steps() { From bf11d685cd8ba365be7a7057fe164c418ac216cf Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Mon, 10 Jul 2023 19:09:17 +0800 Subject: [PATCH 26/27] state circuit lookup fix --- zkevm-circuits/src/state_circuit/dev.rs | 1 - zkevm-circuits/src/state_circuit/lookups.rs | 3 +++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/zkevm-circuits/src/state_circuit/dev.rs b/zkevm-circuits/src/state_circuit/dev.rs index 796c85cfea..193cf2e52c 100644 --- a/zkevm-circuits/src/state_circuit/dev.rs +++ b/zkevm-circuits/src/state_circuit/dev.rs @@ -56,7 +56,6 @@ where ) -> Result<(), Error> { let challenges = challenges.values(&mut layouter); config.mpt_table.load(&mut layouter, &self.updates)?; - config.load_aux_tables(&mut layouter)?; self.synthesize_sub(&config, &challenges, &mut layouter) } } diff --git a/zkevm-circuits/src/state_circuit/lookups.rs b/zkevm-circuits/src/state_circuit/lookups.rs index 83297636f3..41b45a3fb1 100644 --- a/zkevm-circuits/src/state_circuit/lookups.rs +++ b/zkevm-circuits/src/state_circuit/lookups.rs @@ -88,6 +88,9 @@ impl Chip { } pub fn load(&self, layouter: &mut impl Layouter) -> Result<(), Error> { + self.config.u8_table.load(layouter)?; + self.config.u10_table.load(layouter)?; + self.config.u16_table.load(layouter)?; layouter.assign_region( || "assign call_context_field_tags fixed column", |mut region| { From b2df2f9defe22aa14b7730101d4db7166d4ef9ce Mon Sep 17 00:00:00 2001 From: ChihChengLiang Date: Mon, 10 Jul 2023 19:16:06 +0800 Subject: [PATCH 27/27] fix remainder --- .../src/evm_circuit/util/math_gadget/constant_division.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zkevm-circuits/src/evm_circuit/util/math_gadget/constant_division.rs b/zkevm-circuits/src/evm_circuit/util/math_gadget/constant_division.rs index e231925e20..dff6e51a6b 100644 --- a/zkevm-circuits/src/evm_circuit/util/math_gadget/constant_division.rs +++ b/zkevm-circuits/src/evm_circuit/util/math_gadget/constant_division.rs @@ -59,8 +59,8 @@ impl ConstantDivisionGadget { pub(crate) fn quotient(&self) -> Expression { self.quotient.expr() } - - pub(crate) fn _remainder(&self) -> Expression { + #[allow(dead_code, reason = "remainder is a valid API but only used in tests")] + pub(crate) fn remainder(&self) -> Expression { self.remainder.expr() } @@ -122,7 +122,7 @@ mod tests { cb.require_equal( "correct remainder", - constdiv_gadget._remainder(), + constdiv_gadget.remainder(), REMAINDER.expr(), );