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

Commit

Permalink
Runtime config (#1728)
Browse files Browse the repository at this point in the history
### Description

We add an initial structure for runtime config. In this PR, we plan to
add only the invalid tx configuration for the starter.

### Issue Link

#1636 

### Type of change

New feature (non-breaking change which adds functionality)


### Decision

- Allow Geth to take invalid tx. The config doesn't affect geth util


### TODO

- [x] Fix invalid tx test
- [ ] Add tx validity check. (Will continue #1740)
  • Loading branch information
ChihChengLiang authored Jan 31, 2024
1 parent 7f35654 commit fc4964c
Show file tree
Hide file tree
Showing 15 changed files with 300 additions and 103 deletions.
72 changes: 69 additions & 3 deletions bus-mapping/src/circuit_input_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,43 @@ use std::{
pub use transaction::{Transaction, TransactionContext};
pub use withdrawal::{Withdrawal, WithdrawalContext};

/// Runtime Config
///
/// Default to mainnet block
#[derive(Debug, Clone, Copy)]
pub struct FeatureConfig {
/// Zero difficulty
pub zero_difficulty: bool,
/// Free first transaction
pub free_first_tx: bool,
/// Enable EIP1559
pub enable_eip1559: bool,
/// Allow invalid transactions to be included in a block
///
/// Transactions with mismatched nonce, insufficient gas limit, or insufficient balance
/// shouldn't be included in a mainnet block. However, rollup developers might want to
/// include invalid tx in the L2 block to support forced exit feature.
pub invalid_tx: bool,
}

impl Default for FeatureConfig {
fn default() -> Self {
Self {
zero_difficulty: true,
free_first_tx: false,
enable_eip1559: true,
invalid_tx: false,
}
}
}

impl FeatureConfig {
/// Check if we are mainnet config
pub fn is_mainnet(&self) -> bool {
self.zero_difficulty && !self.free_first_tx && self.enable_eip1559 && !self.invalid_tx
}
}

/// Circuit Setup Parameters
#[derive(Debug, Clone, Copy)]
pub struct FixedCParams {
Expand Down Expand Up @@ -150,18 +187,27 @@ pub struct CircuitInputBuilder<C: CircuitsParams> {
pub circuits_params: C,
/// Block Context
pub block_ctx: BlockContext,
/// Feature config
pub feature_config: FeatureConfig,
}

impl<'a, C: CircuitsParams> CircuitInputBuilder<C> {
/// Create a new CircuitInputBuilder from the given `eth_block` and
/// `constants`.
pub fn new(sdb: StateDB, code_db: CodeDB, block: Block, params: C) -> Self {
pub fn new(
sdb: StateDB,
code_db: CodeDB,
block: Block,
params: C,
feature_config: FeatureConfig,
) -> Self {
Self {
sdb,
code_db,
block,
circuits_params: params,
block_ctx: BlockContext::new(),
feature_config,
}
}

Expand Down Expand Up @@ -273,13 +319,15 @@ impl<'a, C: CircuitsParams> CircuitInputBuilder<C> {
let end_tx_step =
gen_associated_steps(&mut self.state_ref(&mut tx, &mut tx_ctx), ExecState::EndTx)?;
tx.steps_mut().push(end_tx_step);
} else {
} else if self.feature_config.invalid_tx {
// Generate InvalidTx step
let invalid_tx_step = gen_associated_steps(
&mut self.state_ref(&mut tx, &mut tx_ctx),
ExecState::InvalidTx,
)?;
tx.steps_mut().push(invalid_tx_step);
} else {
panic!("invalid tx support not enabled")
}

self.sdb.commit_tx();
Expand Down Expand Up @@ -457,6 +505,7 @@ impl CircuitInputBuilder<DynamicCParams> {
block: self.block,
circuits_params: c_params,
block_ctx: self.block_ctx,
feature_config: self.feature_config,
};

cib.set_end_block(c_params.max_rws)?;
Expand Down Expand Up @@ -567,6 +616,7 @@ pub struct BuilderClient<P: JsonRpcClient> {
cli: GethClient<P>,
chain_id: Word,
circuits_params: FixedCParams,
feature_config: FeatureConfig,
}

/// Get State Accesses from TxExecTraces
Expand Down Expand Up @@ -624,12 +674,22 @@ pub fn build_state_code_db(
impl<P: JsonRpcClient> BuilderClient<P> {
/// Create a new BuilderClient
pub async fn new(client: GethClient<P>, circuits_params: FixedCParams) -> Result<Self, Error> {
Self::new_with_features(client, circuits_params, FeatureConfig::default()).await
}

/// Create a new BuilderClient
pub async fn new_with_features(
client: GethClient<P>,
circuits_params: FixedCParams,
feature_config: FeatureConfig,
) -> Result<Self, Error> {
let chain_id = client.get_chain_id().await?;

Ok(Self {
cli: client,
chain_id: chain_id.into(),
circuits_params,
feature_config,
})
}

Expand Down Expand Up @@ -741,7 +801,13 @@ impl<P: JsonRpcClient> BuilderClient<P> {
prev_state_root: Word,
) -> Result<CircuitInputBuilder<FixedCParams>, Error> {
let block = Block::new(self.chain_id, history_hashes, prev_state_root, eth_block)?;
let mut builder = CircuitInputBuilder::new(sdb, code_db, block, self.circuits_params);
let mut builder = CircuitInputBuilder::new(
sdb,
code_db,
block,
self.circuits_params,
self.feature_config,
);
builder.handle_block(eth_block, geth_traces)?;
Ok(builder)
}
Expand Down
11 changes: 10 additions & 1 deletion bus-mapping/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use crate::{
circuit_input_builder::{
get_state_accesses, Block, CircuitInputBuilder, CircuitsParams, DynamicCParams,
FixedCParams,
FeatureConfig, FixedCParams,
},
state_db::{self, CodeDB, StateDB},
};
Expand Down Expand Up @@ -34,6 +34,14 @@ impl<C: CircuitsParams> BlockData<C> {
/// Generate a new CircuitInputBuilder initialized with the context of the
/// BlockData.
pub fn new_circuit_input_builder(&self) -> CircuitInputBuilder<C> {
self.new_circuit_input_builder_with_feature(FeatureConfig::default())
}
/// Generate a new CircuitInputBuilder initialized with the context of the
/// BlockData.
pub fn new_circuit_input_builder_with_feature(
&self,
feature_config: FeatureConfig,
) -> CircuitInputBuilder<C> {
CircuitInputBuilder::new(
self.sdb.clone(),
self.code_db.clone(),
Expand All @@ -45,6 +53,7 @@ impl<C: CircuitsParams> BlockData<C> {
)
.unwrap(),
self.circuits_params,
feature_config,
)
}

Expand Down
3 changes: 2 additions & 1 deletion zkevm-circuits/src/bin/stats/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use bus_mapping::circuit_input_builder::FeatureConfig;
use cli_table::{print_stdout, Cell, Style, Table};
use eth_types::{bytecode, evm_types::OpcodeId, ToWord};
use halo2_proofs::{
Expand Down Expand Up @@ -113,7 +114,7 @@ fn copy_states_stats() {
/// cell consumers of each EVM Cell type.
fn get_exec_steps_occupancy() {
let mut meta = ConstraintSystem::<Fr>::default();
let circuit = EvmCircuit::configure(&mut meta);
let circuit = EvmCircuit::configure_with_params(&mut meta, FeatureConfig::default());

let report = circuit.0.execution.instrument().clone().analyze();
macro_rules! gen_report {
Expand Down
46 changes: 39 additions & 7 deletions zkevm-circuits/src/evm_circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use crate::{
},
util::{Challenges, SubCircuit, SubCircuitConfig},
};
use bus_mapping::evm::OpcodeId;
use bus_mapping::{circuit_input_builder::FeatureConfig, evm::OpcodeId};
use eth_types::Field;
use execution::ExecutionConfig;
use itertools::Itertools;
Expand Down Expand Up @@ -74,6 +74,8 @@ pub struct EvmCircuitConfigArgs<F: Field> {
pub u8_table: UXTable<8>,
/// U16Table
pub u16_table: UXTable<16>,
/// Feature config
pub feature_config: FeatureConfig,
}

impl<F: Field> SubCircuitConfig<F> for EvmCircuitConfig<F> {
Expand All @@ -93,6 +95,7 @@ impl<F: Field> SubCircuitConfig<F> for EvmCircuitConfig<F> {
exp_table,
u8_table,
u16_table,
feature_config,
}: Self::ConfigArgs,
) -> Self {
let fixed_table = [(); 4].map(|_| meta.fixed_column());
Expand All @@ -109,6 +112,7 @@ impl<F: Field> SubCircuitConfig<F> for EvmCircuitConfig<F> {
&copy_table,
&keccak_table,
&exp_table,
feature_config,
));

u8_table.annotate_columns(meta);
Expand Down Expand Up @@ -310,7 +314,8 @@ pub(crate) mod cached {
/// Circuit configuration. These values are calculated just once.
static ref CACHE: Cache = {
let mut meta = ConstraintSystem::<Fr>::default();
let config = EvmCircuit::<Fr>::configure(&mut meta);
// Cached EVM circuit is configured with Mainnet FeatureConfig
let config = EvmCircuit::<Fr>::configure_with_params(&mut meta, FeatureConfig::default());
Cache { cs: meta, config }
};
}
Expand Down Expand Up @@ -356,13 +361,21 @@ pub(crate) mod cached {
impl<F: Field> Circuit<F> for EvmCircuit<F> {
type Config = (EvmCircuitConfig<F>, Challenges);
type FloorPlanner = SimpleFloorPlanner;
type Params = ();
type Params = FeatureConfig;

fn without_witnesses(&self) -> Self {
Self::default()
}

fn configure(meta: &mut ConstraintSystem<F>) -> Self::Config {
/// Try to get the [`FeatureConfig`] from the block or fallback to default
fn params(&self) -> Self::Params {
self.block
.as_ref()
.map(|block| block.feature_config)
.unwrap_or_default()
}

fn configure_with_params(meta: &mut ConstraintSystem<F>, params: Self::Params) -> Self::Config {
let tx_table = TxTable::construct(meta);
let rw_table = RwTable::construct(meta);
let bytecode_table = BytecodeTable::construct(meta);
Expand Down Expand Up @@ -390,12 +403,17 @@ impl<F: Field> Circuit<F> for EvmCircuit<F> {
exp_table,
u8_table,
u16_table,
feature_config: params,
},
),
challenges,
)
}

fn configure(_meta: &mut ConstraintSystem<F>) -> Self::Config {
unreachable!();
}

fn synthesize(
&self,
config: Self::Config,
Expand Down Expand Up @@ -443,7 +461,10 @@ mod evm_circuit_stats {
util::{unusable_rows, SubCircuit},
witness::block_convert,
};
use bus_mapping::{circuit_input_builder::FixedCParams, mock::BlockData};
use bus_mapping::{
circuit_input_builder::{FeatureConfig, FixedCParams},
mock::BlockData,
};

use eth_types::{bytecode, geth_types::GethData};
use halo2_proofs::{self, dev::MockProver, halo2curves::bn256::Fr};
Expand All @@ -455,9 +476,20 @@ mod evm_circuit_stats {

#[test]
fn evm_circuit_unusable_rows() {
let computed = EvmCircuit::<Fr>::unusable_rows();
let mainnet_config = FeatureConfig::default();
let invalid_tx_config = FeatureConfig {
invalid_tx: true,
..Default::default()
};

assert_eq!(
computed,
unusable_rows::<Fr, EvmCircuit::<Fr>>(mainnet_config),
);
assert_eq!(
EvmCircuit::<Fr>::unusable_rows(),
unusable_rows::<Fr, EvmCircuit::<Fr>>(()),
computed,
unusable_rows::<Fr, EvmCircuit::<Fr>>(invalid_tx_config),
)
}

Expand Down
Loading

0 comments on commit fc4964c

Please sign in to comment.