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

Commit

Permalink
refactor global rw_counter to chunkctx_table & code cosmetics
Browse files Browse the repository at this point in the history
  • Loading branch information
hero78119 committed Oct 19, 2023
1 parent de55034 commit 9d05903
Show file tree
Hide file tree
Showing 16 changed files with 162 additions and 73 deletions.
7 changes: 6 additions & 1 deletion bus-mapping/src/circuit_input_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,9 @@ impl CircuitInputBuilder<FixedCParams> {
}

// rwc index start from 1
let total_rws = state.block_ctx.rwc.0 - 1;
let end_rwc = state.block_ctx.rwc.0;
let total_rws = end_rwc - 1;

// We need at least 1 extra Start row
// because total_rws exclude Rw::Start
#[allow(clippy::int_plus_one)]
Expand Down Expand Up @@ -400,6 +402,9 @@ impl CircuitInputBuilder<FixedCParams> {

self.block.block_steps.end_block_not_last = end_block_not_last;
self.block.block_steps.end_block_last = end_block_last;

// set final rwc value to chunkctx
self.chunk_ctx.end_rwc = end_rwc;
}
}

Expand Down
8 changes: 8 additions & 0 deletions bus-mapping/src/circuit_input_builder/chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ pub struct ChunkContext {
pub chunk_index: usize,
/// number of chunks
pub total_chunks: usize,
/// initial rw counter
pub initial_rwc: usize,
/// end rw counter
pub end_rwc: usize,
}

impl Default for ChunkContext {
Expand All @@ -25,6 +29,8 @@ impl ChunkContext {
rwc: RWCounter::new(),
chunk_index,
total_chunks,
initial_rwc: 1, // rw counter start from 1
end_rwc: 0, // end_rwc should be set in later phase
}
}

Expand All @@ -34,6 +40,8 @@ impl ChunkContext {
rwc: RWCounter::new(),
chunk_index: 0,
total_chunks: 1,
initial_rwc: 1, // rw counter start from 1
end_rwc: 0, // end_rwc should be set in later phase
}
}
}
24 changes: 12 additions & 12 deletions gadgets/src/permutation.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
//! Chip that implements permutation fingerprints
//! fingerprints &= \prod_{row_j} \left ( \alpha - \sum_k (\gamma^k \cdot cell_j(k)) \right )
//! power of gamma are defined in columns to trade more columns with less degrees
use std::iter;
#[rustfmt::skip]
// | q_row_non_first | alpha | gamma | fingerprints |
// |-----------------|-----------|-----------|-----------------|
// | 0 | alpha | gamma | fingerprints_0 |
// | 1 | alpha | gamma | fingerprints_1 |
// | 1 | alpha | gamma | fingerprints_2 |
// | q_row_non_first | alpha | gamma | gamma power 2 | ... | fingerprints |
// |-----------------|-----------|-----------|-----------------| |
// | 0 | alpha | gamma | gamma **2 | ... |
// | 1 | alpha | gamma | gamma **2 | ... |
// | 1 | alpha | gamma | gamma **2 | ... |

use std::marker::PhantomData;

Expand Down Expand Up @@ -50,8 +51,9 @@ impl<F: Field> PermutationChipConfig<F> {
gamma: Value<F>,
acc_fingerprints_prev: Value<F>,
col_values: &[Vec<Value<F>>],
prefix: &'static str,
) -> Result<PermutationAssignedCells<F>, Error> {
self.annotate_columns_in_region(region, "state_circuit");
self.annotate_columns_in_region(region, prefix);

// get accumulated fingerprints of each row
let fingerprints =
Expand Down Expand Up @@ -174,7 +176,7 @@ impl<F: Field> PermutationChip<F> {
let row_fingerprints = meta.advice_column();
let alpha = meta.advice_column();

// trade more column to reduce degree of power of gamma
// trade more columns with less degrees
let power_of_gamma = (0..cols.len() - 1)
.map(|_| meta.advice_column())
.collect::<Vec<Column<Advice>>>(); // first element is gamma**1
Expand Down Expand Up @@ -294,11 +296,9 @@ pub fn get_permutation_fingerprints<F: Field>(
let tmp = row
.iter()
.zip_eq(power_of_gamma.iter())
.map(|(a, b)| a.zip(*b).map(|(a, b)| a * b))
.fold(Value::known(F::ZERO), |prev, cur| {
prev.zip(cur).map(|(a, b)| a + b)
});
alpha.zip(tmp).map(|(alpha, tmp)| alpha - tmp)
.map(|(a, b)| *a * b)
.fold(Value::known(F::ZERO), |prev, cur| prev + cur);
alpha - tmp
})
.enumerate()
.for_each(|(i, value)| {
Expand Down
32 changes: 27 additions & 5 deletions zkevm-circuits/src/evm_circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,13 @@ impl<F: Field> SubCircuitConfig<F> for EvmCircuitConfig<F> {
}
}

type AssignedChunkContextCell<F> = (AssignedCell<F, F>, AssignedCell<F, F>, AssignedCell<F, F>);
type AssignedChunkContextCell<F> = (
AssignedCell<F, F>,
AssignedCell<F, F>,
AssignedCell<F, F>,
AssignedCell<F, F>,
AssignedCell<F, F>,
);

impl<F: Field> EvmCircuitConfig<F> {
/// Load fixed table
Expand Down Expand Up @@ -285,8 +291,13 @@ impl<F: Field> EvmCircuitConfig<F> {
chunk_context: &ChunkContext,
max_offset_index: usize,
) -> Result<AssignedChunkContextCell<F>, Error> {
let (chunk_index_cell, chunk_index_next_cell, total_chunk_cell) =
self.chunkctx_table.load(layouter, chunk_context)?;
let (
chunk_index_cell,
chunk_index_next_cell,
total_chunk_cell,
initial_rwc_cell,
end_rwc_cell,
) = self.chunkctx_table.load(layouter, chunk_context)?;

let is_first_chunk = IsZeroChip::construct(self.is_first_chunk.clone());
let is_last_chunk = IsZeroChip::construct(self.is_last_chunk.clone());
Expand Down Expand Up @@ -333,7 +344,13 @@ impl<F: Field> EvmCircuitConfig<F> {
Ok(())
},
)?;
Ok((chunk_index_cell, chunk_index_next_cell, total_chunk_cell))
Ok((
chunk_index_cell,
chunk_index_next_cell,
total_chunk_cell,
initial_rwc_cell,
end_rwc_cell,
))
}
}

Expand Down Expand Up @@ -440,7 +457,7 @@ impl<F: Field> SubCircuit<F> for EvmCircuit<F> {

let max_offset_index = config.execution.assign_block(layouter, block, challenges)?;

let (prev_chunk_index, next_chunk_index_next, total_chunks) =
let (prev_chunk_index, next_chunk_index_next, total_chunks, initial_rwc, end_rwc) =
config.assign_chunk_context(layouter, &block.chunk_context, max_offset_index)?;

let (rw_rows_padding, _) = RwMap::table_assignments_padding(
Expand Down Expand Up @@ -476,6 +493,7 @@ impl<F: Field> SubCircuit<F> for EvmCircuit<F> {
Value::known(block.permu_gamma),
Value::known(block.permu_chronological_rwtable_prev_continuous_fingerprint),
&rw_rows_padding.to2dvec(),
"evm circuit",
)?;
Ok(permutation_cells)
},
Expand All @@ -493,6 +511,7 @@ impl<F: Field> SubCircuit<F> for EvmCircuit<F> {
prev_continuous_fingerprint_cell,
prev_chunk_index,
total_chunks.clone(),
initial_rwc,
]]
.iter()
.flatten()
Expand All @@ -504,6 +523,7 @@ impl<F: Field> SubCircuit<F> for EvmCircuit<F> {
next_continuous_fingerprint_cell,
next_chunk_index_next,
total_chunks,
end_rwc,
]]
.iter()
.flatten()
Expand All @@ -528,11 +548,13 @@ impl<F: Field> SubCircuit<F> for EvmCircuit<F> {
block.permu_chronological_rwtable_prev_continuous_fingerprint,
F::from(rw_table_chunked_index as u64),
F::from(rw_table_total_chunks as u64),
F::from(block.chunk_context.initial_rwc as u64),
],
vec![
block.permu_chronological_rwtable_next_continuous_fingerprint,
F::from(rw_table_chunked_index as u64) + F::ONE,
F::from(rw_table_total_chunks as u64),
F::from(block.chunk_context.end_rwc as u64),
],
vec![block.permu_alpha, block.permu_gamma],
]
Expand Down
27 changes: 10 additions & 17 deletions zkevm-circuits/src/evm_circuit/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use bus_mapping::operation::Target;
use eth_types::{evm_unimplemented, Field};
use gadgets::{is_zero::IsZeroConfig, util::not};
use halo2_proofs::{
circuit::{AssignedCell, Layouter, Region, Value},
circuit::{Layouter, Region, Value},
plonk::{
Advice, Column, ConstraintSystem, Error, Expression, FirstPhase, Fixed, SecondPhase,
Selector, ThirdPhase, VirtualCells,
Expand Down Expand Up @@ -801,9 +801,9 @@ impl<F: Field> ExecutionConfig<F> {
],
),
(
"EndChunk can only transit to EndChunk or EndBlock",
"EndChunk can only transit to EndChunk",
ExecutionState::EndChunk,
vec![ExecutionState::EndChunk, ExecutionState::EndBlock],
vec![ExecutionState::EndChunk],
),
(
"EndBlock can only transit to EndBlock",
Expand Down Expand Up @@ -835,9 +835,9 @@ impl<F: Field> ExecutionConfig<F> {
vec![ExecutionState::EndTx, ExecutionState::EndBlock],
),
(
"Only EndChunk or BeginChunk can transit to BeginChunk",
"Only BeginChunk can transit to BeginChunk",
ExecutionState::BeginChunk,
vec![ExecutionState::EndChunk, ExecutionState::BeginChunk],
vec![ExecutionState::BeginChunk],
),
])
.filter(move |(_, _, from)| !from.contains(&execution_state))
Expand Down Expand Up @@ -998,7 +998,6 @@ impl<F: Field> ExecutionConfig<F> {

let evm_rows = block.circuits_params.max_evm_rows;
let no_padding = evm_rows == 0;
let mut rw_counter_assigned_cells: Vec<AssignedCell<F, F>> = vec![];

// part1: assign real steps
loop {
Expand All @@ -1010,7 +1009,7 @@ impl<F: Field> ExecutionConfig<F> {
let height = step.execution_state().get_step_height();

// Assign the step witness
let rw_counter_cell = self.assign_exec_step(
self.assign_exec_step(
&mut region,
offset,
block,
Expand All @@ -1023,11 +1022,6 @@ impl<F: Field> ExecutionConfig<F> {
assign_pass,
)?;

// for copy constraints in offset 0
if offset == 0 {
rw_counter_assigned_cells.push(rw_counter_cell);
}

// q_step logic
self.assign_q_step(&mut region, offset, height)?;

Expand Down Expand Up @@ -1232,7 +1226,7 @@ impl<F: Field> ExecutionConfig<F> {
next: Option<(&Transaction, &Call, &ExecStep)>,
challenges: &Challenges<Value<F>>,
assign_pass: usize,
) -> Result<AssignedCell<F, F>, Error> {
) -> Result<(), Error> {
if !matches!(step.execution_state(), ExecutionState::EndBlock) {
log::trace!(
"assign_exec_step offset: {} state {:?} step: {:?} call: {:?}",
Expand Down Expand Up @@ -1297,9 +1291,8 @@ impl<F: Field> ExecutionConfig<F> {
is_next: bool,
// Layouter assignment pass
assign_pass: usize,
) -> Result<AssignedCell<F, F>, Error> {
let rw_counter_assigned_cell = self
.step
) -> Result<(), Error> {
self.step
.assign_exec_step(region, offset, block, call, step)?;

macro_rules! assign_exec_step {
Expand Down Expand Up @@ -1471,7 +1464,7 @@ impl<F: Field> ExecutionConfig<F> {
}
}
}
Ok(rw_counter_assigned_cell)
Ok(())
}

fn assign_stored_expressions(
Expand Down
5 changes: 4 additions & 1 deletion zkevm-circuits/src/evm_circuit/execution/begin_chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ impl<F: Field> ExecutionGadget<F> for BeginChunkGadget<F> {
const EXECUTION_STATE: ExecutionState = ExecutionState::BeginChunk;

fn configure(cb: &mut EVMConstraintBuilder<F>) -> Self {
// State transition
// constraint rwc at step first
cb.step_first_constraint_rwc();

// state lookup
cb.step_state_lookup(0.expr());
let step_state_transition = StepStateTransition::same();
cb.require_step_state_transition(step_state_transition);
Expand Down
3 changes: 3 additions & 0 deletions zkevm-circuits/src/evm_circuit/execution/begin_tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ impl<F: Field> ExecutionGadget<F> for BeginTxGadget<F> {
const EXECUTION_STATE: ExecutionState = ExecutionState::BeginTx;

fn configure(cb: &mut EVMConstraintBuilder<F>) -> Self {
// constraint rwc at step first
cb.step_first_constraint_rwc();

// Use rw_counter of the step which triggers next call as its call_id.
let call_id = cb.curr.state.rw_counter.clone();

Expand Down
2 changes: 1 addition & 1 deletion zkevm-circuits/src/evm_circuit/execution/end_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use gadgets::util::select;
use halo2_proofs::{circuit::Value, plonk::Error};

/// current SRS size < 2^30 so use 4 bytes (2^32) in LtGadet should be enough
const MAX_RW_BYTES: usize = u32::BITS as usize / 4;
const MAX_RW_BYTES: usize = u32::BITS as usize / 8;

#[derive(Clone, Debug)]
pub(crate) struct EndBlockGadget<F> {
Expand Down
16 changes: 13 additions & 3 deletions zkevm-circuits/src/evm_circuit/execution/end_chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,19 @@ impl<F: Field> ExecutionGadget<F> for EndChunkGadget<F> {

fn configure(cb: &mut EVMConstraintBuilder<F>) -> Self {
// State transition
cb.step_state_lookup(1.expr());
let step_state_transition = StepStateTransition::same();
cb.require_step_state_transition(step_state_transition);
cb.not_step_last(|cb| {
// Propagate all the way down.
cb.require_step_state_transition(StepStateTransition::same());
});

cb.step_last(|cb| {
cb.step_state_lookup(1.expr());
});

cb.step_last_constraint_rwc();

// TODO constraint Rw::Padding are append consecutively to avoid malicious insert

Self {
_marker: PhantomData {},
}
Expand Down
13 changes: 6 additions & 7 deletions zkevm-circuits/src/evm_circuit/step.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use bus_mapping::{
};
use eth_types::{evm_unimplemented, Field, ToWord};
use halo2_proofs::{
circuit::{AssignedCell, Value},
circuit::Value,
plonk::{Advice, Column, ConstraintSystem, Error, Expression},
};
use std::{fmt::Display, iter};
Expand Down Expand Up @@ -761,14 +761,13 @@ impl<F: Field> Step<F> {
_block: &Block<F>,
call: &Call,
step: &ExecStep,
) -> Result<AssignedCell<F, F>, Error> {
) -> Result<(), Error> {
self.state
.execution_state
.assign(region, offset, step.execution_state() as usize)?;
let rw_counter_assigned_cell =
self.state
.rw_counter
.assign(region, offset, Value::known(F::from(step.rwc.into())))?;
self.state
.rw_counter
.assign(region, offset, Value::known(F::from(step.rwc.into())))?;
self.state.inner_rw_counter.assign(
region,
offset,
Expand Down Expand Up @@ -812,6 +811,6 @@ impl<F: Field> Step<F> {
self.state
.log_id
.assign(region, offset, Value::known(F::from(step.log_id as u64)))?;
Ok(rw_counter_assigned_cell)
Ok(())
}
}
Loading

0 comments on commit 9d05903

Please sign in to comment.