Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement subarray equality check using RLC #189

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions plonky2x/src/frontend/builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,14 @@ impl<L: PlonkParameters<D>, const D: usize> CircuitBuilder<L, D> {
}
}

/// Fails if i1 != true.
pub fn assert_is_true<V: CircuitVariable>(&mut self, i1: V) {
let one = self.api.one();
for t1 in i1.targets().iter() {
self.api.connect(*t1, one);
}
}

/// Returns 1 if i1 == i2 and 0 otherwise as a BoolVariable.
pub fn is_equal<V: CircuitVariable>(&mut self, i1: V, i2: V) -> BoolVariable {
let mut result = self._true();
Expand All @@ -342,6 +350,15 @@ impl<L: PlonkParameters<D>, const D: usize> CircuitBuilder<L, D> {
pub fn to_be_bits<V: EvmVariable>(&mut self, variable: V) -> Vec<BoolVariable> {
variable.to_be_bits(self)
}

/// Takes a slice of bits and returns the number with little-endian bit representation as a Variable.
pub fn le_sum(&mut self, bits: &[BoolVariable]) -> Variable {
let bits = bits
.iter()
.map(|x| BoolTarget::new_unsafe(x.0.0))
.collect_vec();
Variable(self.api.le_sum(bits.into_iter()))
}
}

impl<L: PlonkParameters<D>, const D: usize> Default for CircuitBuilder<L, D> {
Expand Down
244 changes: 220 additions & 24 deletions plonky2x/src/frontend/eth/mpt/rlc.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,46 @@
use std::marker::PhantomData;
use itertools::Itertools;
use plonky2::field::types::Field;
use plonky2::hash::poseidon::PoseidonHash;
use plonky2::iop::challenger::RecursiveChallenger;

use super::generators::SubarrayEqualGenerator;
use crate::prelude::{BoolVariable, ByteVariable, CircuitBuilder, PlonkParameters, Variable};

// Checks that a[a_offset:a_offset+len] = b[b_offset:b_offset+len]
pub fn subarray_equal(a: &[u8], a_offset: usize, b: &[u8], b_offset: usize, len: usize) -> u8 {
for i in 0..len {
if a[a_offset + i] != b[b_offset + i] {
return 0;
impl<L: PlonkParameters<D>, const D: usize> CircuitBuilder<L, D> {
/// Generates a commitment for a subarray using RLC.
fn commit_subarray(
&mut self,
arr: &[ByteVariable],
offset: Variable,
len: Variable,
random_value: Variable,
) -> Variable {
let end_idx = self.add(offset, len);
let mut commitment: Variable = self.zero();
let mut is_within_subarray = self.zero();

let one: Variable = self.one();
let mut current_multiplier = one;
for idx in 0..arr.len() {
let idx_target = self.constant(L::Field::from_canonical_usize(idx));
// is_within_subarray is one if idx is in the range [offset..offset+len].
let is_at_start_idx = self.is_equal(idx_target, offset);
is_within_subarray = self.add(is_within_subarray, is_at_start_idx.0);
let is_at_end_idx = self.is_equal(idx_target, end_idx);
is_within_subarray = self.sub(is_within_subarray, is_at_end_idx.0);

let to_be_multiplied = self.select(BoolVariable(is_within_subarray), random_value, one);
current_multiplier = self.mul(current_multiplier, to_be_multiplied);

let le_value = arr[idx].to_variable(self);
let multiplied_value = self.mul(le_value, current_multiplier);
let random_value_if_in_range = self.mul(is_within_subarray, multiplied_value);
commitment = self.add(commitment, random_value_if_in_range);
}

commitment
}
1
}

impl<L: PlonkParameters<D>, const D: usize> CircuitBuilder<L, D> {
#[allow(unused_variables, dead_code)]
/// Checks subarrays for equality using a random linear combination.
pub fn subarray_equal(
&mut self,
a: &[ByteVariable],
Expand All @@ -23,10 +49,23 @@ impl<L: PlonkParameters<D>, const D: usize> CircuitBuilder<L, D> {
b_offset: Variable,
len: Variable,
) -> BoolVariable {
todo!();
let mut challenger = RecursiveChallenger::<L::Field, PoseidonHash, D>::new(&mut self.api);
let challenger_seed = [a, b]
.concat()
.iter()
.map(|byte| byte.to_variable(self).0)
.collect_vec();

challenger.observe_elements(&challenger_seed);

let challenge = Variable(challenger.get_challenge(&mut self.api));

let commitment_for_a = self.commit_subarray(a, a_offset, len, challenge);
let commitment_for_b = self.commit_subarray(b, b_offset, len, challenge);
self.is_equal(commitment_for_a, commitment_for_b)
}

#[allow(unused_variables, dead_code)]
/// Asserts that subarrays are equal using a random linear combination.
pub fn assert_subarray_equal(
&mut self,
a: &[ByteVariable],
Expand All @@ -35,19 +74,176 @@ impl<L: PlonkParameters<D>, const D: usize> CircuitBuilder<L, D> {
b_offset: Variable,
len: Variable,
) {
// TODO: implement
let generator: SubarrayEqualGenerator<L, D> = SubarrayEqualGenerator {
a: a.to_vec(),
a_offset,
b: b.to_vec(),
b_offset,
len,
_phantom: PhantomData::<L>,
};
self.add_simple_generator(generator);
let subarrays_are_equal = self.subarray_equal(a, a_offset, b, b_offset, len);
self.assert_is_true(subarrays_are_equal);
}
}

#[cfg(test)]
pub(crate) mod tests {
// TODO add a test for subarray_equal
use plonky2::field::types::Field;
use plonky2::plonk::config::{GenericConfig, PoseidonGoldilocksConfig};

use crate::frontend::builder::DefaultBuilder;
use crate::prelude::{ByteVariable, Variable};

impl Default for ByteVariable {
fn default() -> ByteVariable {
unsafe { std::mem::zeroed() }
}
}

#[test]
pub fn test_subarray_equal_should_succeed() {
const D: usize = 2;
type C = PoseidonGoldilocksConfig;
type F = <C as GenericConfig<D>>::F;
let mut builder = DefaultBuilder::new();

const MAX_LEN: usize = 15;
let mut a: [ByteVariable; MAX_LEN] = Default::default();
let mut b: [ByteVariable; MAX_LEN] = Default::default();

for i in 0..MAX_LEN {
a[i] = builder.constant::<ByteVariable>((i + 5) as u8);
}

for i in 0..MAX_LEN {
b[i] = builder.constant::<ByteVariable>(i as u8);
}

let a_offset: Variable = builder.constant(F::ZERO);
let b_offset = builder.constant(F::from_canonical_usize(5));
let len: Variable = builder.constant(F::from_canonical_usize(5));
builder.assert_subarray_equal(&a, a_offset, &b, b_offset, len);

// Build your circuit.
let circuit = builder.build();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you make this use circuit.inputs() and circuit.prove()?


// Write to the circuit input.
let input = circuit.input();

// Generate a proof.
let (proof, output) = circuit.prove(&input);

// Verify proof.
circuit.verify(&proof, &input, &output)
}

#[test]
pub fn test_subarray_equal_diff_len_should_succeed() {
const D: usize = 2;
type C = PoseidonGoldilocksConfig;
type F = <C as GenericConfig<D>>::F;
let mut builder = DefaultBuilder::new();

const LEN_A: usize = 15;
const LEN_B: usize = 10;
let mut a: [ByteVariable; LEN_A] = Default::default();
let mut b: [ByteVariable; LEN_B] = Default::default();

for i in 0..LEN_A {
a[i] = builder.constant::<ByteVariable>((i + 5) as u8);
}

for i in 0..LEN_B {
b[i] = builder.constant::<ByteVariable>(i as u8);
}

let a_offset: Variable = builder.constant(F::ZERO);
let b_offset = builder.constant(F::from_canonical_usize(5));
let len: Variable = builder.constant(F::from_canonical_usize(5));
builder.assert_subarray_equal(&a, a_offset, &b, b_offset, len);

// Build your circuit.
let circuit = builder.build();

// Write to the circuit input.
let input = circuit.input();

// Generate a proof.
let (proof, output) = circuit.prove(&input);

// Verify proof.
circuit.verify(&proof, &input, &output)
}

#[test]
pub fn test_subarray_equal_diff_len_inverse_should_succeed() {
const D: usize = 2;
type C = PoseidonGoldilocksConfig;
type F = <C as GenericConfig<D>>::F;
let mut builder = DefaultBuilder::new();

const LEN_A: usize = 10;
const LEN_B: usize = 15;
let mut a: [ByteVariable; LEN_A] = Default::default();
let mut b: [ByteVariable; LEN_B] = Default::default();

for i in 0..LEN_A {
a[i] = builder.constant::<ByteVariable>((i + 5) as u8);
}

for i in 0..LEN_B {
b[i] = builder.constant::<ByteVariable>(i as u8);
}

let a_offset: Variable = builder.constant(F::ZERO);
let b_offset = builder.constant(F::from_canonical_usize(5));
let len: Variable = builder.constant(F::from_canonical_usize(5));
builder.assert_subarray_equal(&a, a_offset, &b, b_offset, len);

// Build your circuit.
let circuit = builder.build();

// Write to the circuit input.
let input = circuit.input();

// Generate a proof.
let (proof, output) = circuit.prove(&input);

// Verify proof.
circuit.verify(&proof, &input, &output)
}

#[test]
#[should_panic]
pub fn test_subarray_equal_should_fail() {
const D: usize = 2;
type C = PoseidonGoldilocksConfig;
type F = <C as GenericConfig<D>>::F;
let mut builder = DefaultBuilder::new();

const MAX_LEN: usize = 15;
let mut a: [ByteVariable; MAX_LEN] = Default::default();
let mut b: [ByteVariable; MAX_LEN] = Default::default();

for i in 0..MAX_LEN {
a[i] = builder.constant::<ByteVariable>((i + 5) as u8);
}

for i in 0..MAX_LEN {
b[i] = builder.constant::<ByteVariable>(i as u8);
}

// Modify 1 byte here.
b[6] = builder.constant::<ByteVariable>(0);

let a_offset = builder.constant(F::ZERO);
let b_offset = builder.constant(F::from_canonical_usize(5));
let len: Variable = builder.constant(F::from_canonical_usize(5));
builder.assert_subarray_equal(&a, a_offset, &b, b_offset, len);

// Build your circuit.
let circuit = builder.build();

// Write to the circuit input.
let input = circuit.input();

// Generate a proof.
let (proof, output) = circuit.prove(&input);

// Verify proof.
circuit.verify(&proof, &input, &output)
}
}