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

Commit

Permalink
Refactor RandomLinearCombination::<F, 32>::random_linear_combine_expr…
Browse files Browse the repository at this point in the history
… to accept challenge instead of powers (#1113)
  • Loading branch information
leolara committed Jan 31, 2023
1 parent 6efb9b8 commit 27a9173
Show file tree
Hide file tree
Showing 17 changed files with 97 additions and 184 deletions.
13 changes: 4 additions & 9 deletions zkevm-circuits/src/bytecode_circuit/bytecode_unroller.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
use crate::{
evm_circuit::util::{
and, constraint_builder::BaseConstraintBuilder, not, or, select, RandomLinearCombination,
},
evm_circuit::util::{and, constraint_builder::BaseConstraintBuilder, not, or, rlc, select},
table::{BytecodeFieldTag, BytecodeTable, DynamicTableColumns, KeccakTable},
util::{Challenges, Expr, SubCircuit, SubCircuitConfig},
witness,
Expand Down Expand Up @@ -449,12 +447,9 @@ impl<F: Field> BytecodeCircuitConfig<F> {
return Err(Error::Synthesis);
}

let code_hash = challenges.evm_word().map(|challenge| {
RandomLinearCombination::<F, 32>::random_linear_combine(
row.code_hash.to_le_bytes(),
challenge,
)
});
let code_hash = challenges
.evm_word()
.map(|challenge| rlc::value(&row.code_hash.to_le_bytes(), challenge));

// Track which byte is an opcode and which is push
// data
Expand Down
6 changes: 2 additions & 4 deletions zkevm-circuits/src/copy_circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use std::marker::PhantomData;

use crate::witness::{Bytecode, RwMap, Transaction};
use crate::{
evm_circuit::util::{constraint_builder::BaseConstraintBuilder, RandomLinearCombination},
evm_circuit::util::{constraint_builder::BaseConstraintBuilder, rlc},
table::{
BytecodeFieldTag, BytecodeTable, CopyTable, LookupTable, RwTable, RwTableTag,
TxContextFieldTag, TxTable,
Expand All @@ -46,9 +46,7 @@ pub fn number_or_hash_to_field<F: Field>(v: &NumberOrHash, challenge: Value<F>)
b.reverse();
b
};
challenge.map(|challenge| {
RandomLinearCombination::random_linear_combine(le_bytes, challenge)
})
challenge.map(|challenge| rlc::value(&le_bytes, challenge))
}
}
}
Expand Down
14 changes: 1 addition & 13 deletions zkevm-circuits/src/evm_circuit/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -421,8 +421,6 @@ impl<F: Field> ExecutionConfig<F> {
let mut stored_expressions_map = HashMap::new();

let step_next = Step::new(meta, advices, MAX_STEP_HEIGHT, true);
let word_powers_of_randomness = challenges.evm_word_powers_of_randomness();
let lookup_powers_of_randomness = challenges.lookup_input_powers_of_randomness();
macro_rules! configure_gadget {
() => {
Self::configure_gadget(
Expand All @@ -434,8 +432,6 @@ impl<F: Field> ExecutionConfig<F> {
q_step_first,
q_step_last,
&challenges,
&word_powers_of_randomness,
&lookup_powers_of_randomness,
&step_curr,
&step_next,
&mut height_map,
Expand Down Expand Up @@ -579,8 +575,6 @@ impl<F: Field> ExecutionConfig<F> {
q_step_first: Selector,
q_step_last: Selector,
challenges: &Challenges<Expression<F>>,
word_powers_of_randomness: &[Expression<F>; 31],
lookup_powers_of_randomness: &[Expression<F>; 12],
step_curr: &Step<F>,
step_next: &Step<F>,
height_map: &mut HashMap<ExecutionState, usize>,
Expand All @@ -593,8 +587,6 @@ impl<F: Field> ExecutionConfig<F> {
step_curr.clone(),
step_next.clone(),
challenges,
word_powers_of_randomness,
lookup_powers_of_randomness,
G::EXECUTION_STATE,
);
G::configure(&mut cb);
Expand All @@ -608,8 +600,6 @@ impl<F: Field> ExecutionConfig<F> {
step_curr.clone(),
step_next.clone(),
challenges,
word_powers_of_randomness,
lookup_powers_of_randomness,
G::EXECUTION_STATE,
);

Expand Down Expand Up @@ -744,8 +734,6 @@ impl<F: Field> ExecutionConfig<F> {
challenges: &Challenges<Expression<F>>,
cell_manager: &CellManager<F>,
) {
let lookup_powers_of_randomness: [Expression<F>; 31] =
challenges.lookup_input_powers_of_randomness();
for column in cell_manager.columns().iter() {
if let CellType::Lookup(table) = column.cell_type {
let name = format!("{:?}", table);
Expand All @@ -763,7 +751,7 @@ impl<F: Field> ExecutionConfig<F> {
.table_exprs(meta);
vec![(
column.expr(),
rlc::expr(&table_expressions, &lookup_powers_of_randomness),
rlc::expr(&table_expressions, challenges.lookup_input()),
)]
});
}
Expand Down
15 changes: 5 additions & 10 deletions zkevm-circuits/src/evm_circuit/execution/signextend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::{
common_gadget::SameContextGadget,
constraint_builder::{ConstraintBuilder, StepStateTransition, Transition::Delta},
math_gadget::{IsEqualGadget, IsZeroGadget},
select, sum, CachedRegion, Cell, Word,
rlc, select, sum, CachedRegion, Cell, Word,
},
witness::{Block, Call, ExecStep, Transaction},
},
Expand All @@ -17,10 +17,7 @@ use crate::{
use array_init::array_init;
use bus_mapping::evm::OpcodeId;
use eth_types::{Field, ToLittleEndian};
use halo2_proofs::{
circuit::Value,
plonk::{Error, Expression},
};
use halo2_proofs::{circuit::Value, plonk::Error};

#[derive(Clone, Debug)]
pub(crate) struct SignextendGadget<F> {
Expand Down Expand Up @@ -111,10 +108,8 @@ impl<F: Field> ExecutionGadget<F> for SignextendGadget<F> {
// enabled need to be changed to the sign byte.
// When a byte was selected all the **following** bytes need to be
// replaced (hence the `selectors[idx - 1]`).
let powers_of_randomness: [Expression<F>; 31] =
cb.challenges().evm_word_powers_of_randomness();
let result = Word::random_linear_combine_expr(
array_init(|idx| {
let result = rlc::expr(
&array_init::<_, _, 32>(|idx| {
if idx == 0 {
value.cells[idx].expr()
} else {
Expand All @@ -125,7 +120,7 @@ impl<F: Field> ExecutionGadget<F> for SignextendGadget<F> {
)
}
}),
&powers_of_randomness,
cb.challenges().evm_word(),
);

// Pop the byte index and the value from the stack, push the result on
Expand Down
61 changes: 31 additions & 30 deletions zkevm-circuits/src/evm_circuit/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ impl<'r, 'b, F: FieldExt> CachedRegion<'r, 'b, F> {
pub fn word_rlc(&self, n: U256) -> Value<F> {
self.challenges
.evm_word()
.map(|r| Word::random_linear_combine(n.to_le_bytes(), r))
.map(|r| rlc::value(&n.to_le_bytes(), r))
}
pub fn empty_hash_rlc(&self) -> Value<F> {
self.word_rlc(U256::from_little_endian(&*EMPTY_HASH_LE))
Expand Down Expand Up @@ -462,23 +462,9 @@ pub(crate) struct RandomLinearCombination<F, const N: usize> {
impl<F: FieldExt, const N: usize> RandomLinearCombination<F, N> {
const N_BYTES: usize = N;

pub(crate) fn random_linear_combine(bytes: [u8; N], randomness: F) -> F {
rlc::value(&bytes, randomness)
}

pub(crate) fn random_linear_combine_expr(
bytes: [Expression<F>; N],
power_of_randomness: &[Expression<F>],
) -> Expression<F> {
rlc::expr(&bytes, power_of_randomness)
}

pub(crate) fn new(cells: [Cell<F>; N], power_of_randomness: &[Expression<F>]) -> Self {
pub(crate) fn new(cells: [Cell<F>; N], randomness: Expression<F>) -> Self {
Self {
expression: Self::random_linear_combine_expr(
cells.clone().map(|cell| cell.expr()),
power_of_randomness,
),
expression: rlc::expr(&cells.clone().map(|cell| cell.expr()), randomness),
cells,
}
}
Expand Down Expand Up @@ -547,30 +533,45 @@ pub(crate) mod from_bytes {
/// Returns the random linear combination of the inputs.
/// Encoding is done as follows: v_0 * R^0 + v_1 * R^1 + ...
pub(crate) mod rlc {
use std::ops::{Add, Mul};

use crate::util::Expr;
use halo2_proofs::{arithmetic::FieldExt, plonk::Expression};

pub(crate) fn expr<F: FieldExt, E: Expr<F>>(
expressions: &[E],
power_of_randomness: &[E],
) -> Expression<F> {
debug_assert!(expressions.len() <= power_of_randomness.len() + 1);

let mut rlc = expressions[0].expr();
for (expression, randomness) in expressions[1..].iter().zip(power_of_randomness.iter()) {
rlc = rlc + expression.expr() * randomness.expr();
pub(crate) fn expr<F: FieldExt, E: Expr<F>>(expressions: &[E], randomness: E) -> Expression<F> {
if !expressions.is_empty() {
generic(expressions.iter().map(|e| e.expr()), randomness.expr())
} else {
0.expr()
}
rlc
}

pub(crate) fn value<'a, F: FieldExt, I>(values: I, randomness: F) -> F
where
I: IntoIterator<Item = &'a u8>,
<I as IntoIterator>::IntoIter: DoubleEndedIterator,
{
values.into_iter().rev().fold(F::zero(), |acc, value| {
acc * randomness + F::from(*value as u64)
})
let values = values
.into_iter()
.map(|v| F::from(*v as u64))
.collect::<Vec<F>>();
if !values.is_empty() {
generic(values, randomness)
} else {
F::zero()
}
}

fn generic<V, I>(values: I, randomness: V) -> V
where
I: IntoIterator<Item = V>,
<I as IntoIterator>::IntoIter: DoubleEndedIterator,
V: Clone + Add<Output = V> + Mul<Output = V>,
{
let mut values = values.into_iter().rev();
let init = values.next().expect("values should not be empty");

values.fold(init, |acc, value| acc * randomness.clone() + value)
}
}

Expand Down
12 changes: 3 additions & 9 deletions zkevm-circuits/src/evm_circuit/util/constraint_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,8 +266,6 @@ pub(crate) struct ConstraintBuilder<'a, F> {
pub(crate) curr: Step<F>,
pub(crate) next: Step<F>,
challenges: &'a Challenges<Expression<F>>,
word_powers_of_randomness: &'a [Expression<F>; 31],
lookup_powers_of_randomness: &'a [Expression<F>; 12],
execution_state: ExecutionState,
constraints: Constraints<F>,
rw_counter_offset: Expression<F>,
Expand All @@ -285,8 +283,6 @@ impl<'a, F: Field> ConstraintBuilder<'a, F> {
curr: Step<F>,
next: Step<F>,
challenges: &'a Challenges<Expression<F>>,
word_powers_of_randomness: &'a [Expression<F>; 31],
lookup_powers_of_randomness: &'a [Expression<F>; 12],
execution_state: ExecutionState,
) -> Self {
Self {
Expand All @@ -309,8 +305,6 @@ impl<'a, F: Field> ConstraintBuilder<'a, F> {
condition: None,
constraints_location: ConstraintLocation::Step,
stored_expressions: Vec::new(),
word_powers_of_randomness,
lookup_powers_of_randomness,
}
}

Expand Down Expand Up @@ -379,7 +373,7 @@ impl<'a, F: Field> ConstraintBuilder<'a, F> {
}

pub(crate) fn query_word_rlc<const N: usize>(&mut self) -> RandomLinearCombination<F, N> {
RandomLinearCombination::<F, N>::new(self.query_bytes(), self.word_powers_of_randomness)
RandomLinearCombination::<F, N>::new(self.query_bytes(), self.challenges.evm_word())
}

pub(crate) fn query_bytes<const N: usize>(&mut self) -> [Cell<F>; N] {
Expand Down Expand Up @@ -423,7 +417,7 @@ impl<'a, F: Field> ConstraintBuilder<'a, F> {
}

pub(crate) fn word_rlc<const N: usize>(&self, bytes: [Expression<F>; N]) -> Expression<F> {
RandomLinearCombination::random_linear_combine_expr(bytes, self.word_powers_of_randomness)
rlc::expr(&bytes, self.challenges.evm_word())
}

pub(crate) fn empty_hash_rlc(&self) -> Expression<F> {
Expand Down Expand Up @@ -1435,7 +1429,7 @@ impl<'a, F: Field> ConstraintBuilder<'a, F> {
};
let compressed_expr = self.split_expression(
"Lookup compression",
rlc::expr(&lookup.input_exprs(), self.lookup_powers_of_randomness),
rlc::expr(&lookup.input_exprs(), self.challenges.lookup_input()),
MAX_DEGREE - IMPLICIT_DEGREE,
);
self.store_expression(name, compressed_expr, CellType::Lookup(lookup.table()));
Expand Down
7 changes: 1 addition & 6 deletions zkevm-circuits/src/evm_circuit/util/math_gadget/test_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,15 +124,10 @@ impl<F: Field, G: MathGadgetContainer<F>> Circuit<F> for UnitTestMathGadgetBaseC

let step_curr = Step::new(meta, advices, 0, false);
let step_next = Step::new(meta, advices, MAX_STEP_HEIGHT, true);
let evm_word_powers_of_randomness = challenges_exprs.evm_word_powers_of_randomness();
let lookup_input_powers_of_randomness =
challenges_exprs.lookup_input_powers_of_randomness();
let mut cb = ConstraintBuilder::new(
step_curr.clone(),
step_next,
&challenges_exprs,
&evm_word_powers_of_randomness,
&lookup_input_powers_of_randomness,
ExecutionState::STOP,
);
let math_gadget_container = G::configure_gadget_container(&mut cb);
Expand All @@ -157,7 +152,7 @@ impl<F: Field, G: MathGadgetContainer<F>> Circuit<F> for UnitTestMathGadgetBaseC
let table_expressions = fixed_table.table_exprs(meta);
vec![(
column.expr(),
rlc::expr(&table_expressions, &lookup_input_powers_of_randomness),
rlc::expr(&table_expressions, challenges_exprs.lookup_input()),
)]
});
}
Expand Down
2 changes: 1 addition & 1 deletion zkevm-circuits/src/state_circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ impl<F: Field> SubCircuitConfig<F> for StateCircuitConfig<F> {
selector,
rw_table.storage_key,
lookups,
power_of_randomness.clone(),
challenges.evm_word(),
);

let initial_value = meta.advice_column_in(SecondPhase);
Expand Down
4 changes: 2 additions & 2 deletions zkevm-circuits/src/state_circuit/random_linear_combination.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ impl<F: Field, const N: usize> Chip<F, N> {
selector: Column<Fixed>,
encoded: Column<Advice>,
lookup: lookups::Config,
power_of_randomness: [Expression<F>; 31],
randomness: Expression<F>,
) -> Config<N> {
let bytes = [0; N].map(|_| meta.advice_column());

Expand All @@ -81,7 +81,7 @@ impl<F: Field, const N: usize> Chip<F, N> {
let selector = meta.query_fixed(selector, Rotation::cur());
let encoded = meta.query_advice(encoded, Rotation::cur());
let bytes = bytes.map(|c| meta.query_advice(c, Rotation::cur()));
vec![selector * (encoded - rlc::expr(&bytes, &power_of_randomness))]
vec![selector * (encoded - rlc::expr(&bytes, randomness))]
});

Config { bytes }
Expand Down
6 changes: 3 additions & 3 deletions zkevm-circuits/src/table.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Table definitions used cross-circuits

use crate::copy_circuit::number_or_hash_to_field;
use crate::evm_circuit::util::{rlc, RandomLinearCombination};
use crate::evm_circuit::util::rlc;
use crate::exp_circuit::{OFFSET_INCREMENT, ROWS_PER_STEP};
use crate::impl_expr;
use crate::util::build_tx_log_address;
Expand Down Expand Up @@ -772,8 +772,8 @@ impl KeccakTable {
keccak.update(input);
let output = keccak.digest();
let output_rlc = challenges.evm_word().map(|challenge| {
RandomLinearCombination::<F, 32>::random_linear_combine(
Word::from_big_endian(output.as_slice()).to_le_bytes(),
rlc::value(
&Word::from_big_endian(output.as_slice()).to_le_bytes(),
challenge,
)
});
Expand Down
7 changes: 1 addition & 6 deletions zkevm-circuits/src/tx_circuit/sign_verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,13 +234,8 @@ impl SignVerifyConfig {
let [rlc, rlc_next] = [Rotation::cur(), Rotation::next()]
.map(|rotation| meta.query_advice(rlc, rotation));
let inputs = [e, d, c, b, a, rlc];
let powers_of_challenge = iter::successors(challenge.clone().into(), |power| {
(challenge.clone() * power.clone()).into()
})
.take(inputs.len() - 1)
.collect_vec();

vec![q_rlc * (rlc_next - rlc::expr(&inputs, &powers_of_challenge))]
vec![q_rlc * (rlc_next - rlc::expr(&inputs, challenge))]
});
}
}
Expand Down
Loading

0 comments on commit 27a9173

Please sign in to comment.