Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
adr1anh committed Sep 25, 2023
1 parent 7285f92 commit 4abf832
Show file tree
Hide file tree
Showing 28 changed files with 2,040 additions and 3,071 deletions.
61 changes: 17 additions & 44 deletions halo2_proofs/examples/folding.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,15 @@
use ff::{BatchInvert, FromUniformBytes};

Check warning on line 1 in halo2_proofs/examples/folding.rs

View workflow job for this annotation

GitHub Actions / Clippy (beta)

unused import: `FromUniformBytes`

warning: unused import: `FromUniformBytes` --> halo2_proofs/examples/folding.rs:1:23 | 1 | use ff::{BatchInvert, FromUniformBytes}; | ^^^^^^^^^^^^^^^^ | = note: `#[warn(unused_imports)]` on by default

Check warning on line 1 in halo2_proofs/examples/folding.rs

View workflow job for this annotation

GitHub Actions / Test on macOS-latest

unused import: `FromUniformBytes`

Check warning on line 1 in halo2_proofs/examples/folding.rs

View workflow job for this annotation

GitHub Actions / Test on ubuntu-latest

unused import: `FromUniformBytes`

Check warning on line 1 in halo2_proofs/examples/folding.rs

View workflow job for this annotation

GitHub Actions / Test on windows-latest

unused import: `FromUniformBytes`
use halo2_proofs::{
arithmetic::{CurveAffine, Field},
arithmetic::Field,
circuit::{floor_planner::V1, Layouter, Value},
dev::{metadata, FailureLocation, MockProver, VerifyFailure},
plonk::*,
poly::{
poly::{self, commitment::ParamsProver, VerificationStrategy},

Check warning on line 6 in halo2_proofs/examples/folding.rs

View workflow job for this annotation

GitHub Actions / Clippy (beta)

unused import: `VerificationStrategy`

warning: unused import: `VerificationStrategy` --> halo2_proofs/examples/folding.rs:6:44 | 6 | poly::{self, commitment::ParamsProver, VerificationStrategy}, | ^^^^^^^^^^^^^^^^^^^^

Check warning on line 6 in halo2_proofs/examples/folding.rs

View workflow job for this annotation

GitHub Actions / Test on macOS-latest

unused import: `VerificationStrategy`

Check warning on line 6 in halo2_proofs/examples/folding.rs

View workflow job for this annotation

GitHub Actions / Test on windows-latest

unused import: `VerificationStrategy`
protostar::{
self,
commitment::ParamsProver,
ipa::{
commitment::{IPACommitmentScheme, ParamsIPA},
multiopen::{ProverIPA, VerifierIPA},
strategy::AccumulatorStrategy,
},
VerificationStrategy,
},
protostar::{self, decider::create_proof},
transcript::{
Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer,
accumulator::Accumulator,
// decider::create_proof,
},
transcript::{Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer},

Check warning on line 12 in halo2_proofs/examples/folding.rs

View workflow job for this annotation

GitHub Actions / Clippy (beta)

unused import: `TranscriptReadBuffer`

warning: unused import: `TranscriptReadBuffer` --> halo2_proofs/examples/folding.rs:12:46 | 12 | transcript::{Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer}, | ^^^^^^^^^^^^^^^^^^^^

Check warning on line 12 in halo2_proofs/examples/folding.rs

View workflow job for this annotation

GitHub Actions / Test on macOS-latest

unused import: `TranscriptReadBuffer`

Check warning on line 12 in halo2_proofs/examples/folding.rs

View workflow job for this annotation

GitHub Actions / Test on ubuntu-latest

unused import: `TranscriptReadBuffer`

Check warning on line 12 in halo2_proofs/examples/folding.rs

View workflow job for this annotation

GitHub Actions / Test on windows-latest

unused import: `TranscriptReadBuffer`
};
use halo2curves::pasta::pallas;
use rand_core::{OsRng, RngCore};
Expand Down Expand Up @@ -264,7 +256,8 @@ fn main() {

let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]);
let pk = protostar::ProvingKey::new(&params, &circuit1).unwrap();
let mut acc = protostar::prover::create_accumulator(

let acc1 = protostar::prover::create_accumulator(
&params,
&pk,
&circuit1,
Expand All @@ -273,15 +266,17 @@ fn main() {
&mut transcript,
)
.unwrap();
assert!(acc.decide(&params, &pk));

// An accumulator is always valid
assert!(Accumulator::decide(&params, &pk, &acc1));

// Folding an accumulator with itself should yield the same one,
// since (1-X)*acc + X*acc = acc
let acc1 = acc.clone();
acc.fold(&pk, acc1.clone(), &mut transcript);
assert!(acc.decide(&params, &pk));
let acc = Accumulator::fold(&pk, acc1.clone(), acc1.clone(), &mut transcript);
assert_eq!(acc, acc1);

assert!(Accumulator::decide(&params, &pk, &acc));

let acc2 = protostar::prover::create_accumulator(
&params,
&pk,
Expand All @@ -291,31 +286,9 @@ fn main() {
&mut transcript,
)
.unwrap();
acc.fold(&pk, acc2, &mut transcript);
assert!(acc.decide(&params, &pk));

let acc3 = protostar::prover::create_accumulator(
&params,
&pk,
&circuit3,
&[],
&mut rng,
&mut transcript,
)
.unwrap();
acc.fold(&pk, acc3, &mut transcript);

let acc4 = protostar::prover::create_accumulator(
&params,
&pk,
&circuit3,
&[],
&mut rng,
&mut transcript,
)
.unwrap();
acc.fold(&pk, acc4, &mut transcript);
assert!(acc.decide(&params, &pk));
let acc = Accumulator::fold(&pk, acc, acc2, &mut transcript);
assert!(Accumulator::decide(&params, &pk, &acc));

let _ = create_proof::<_, ProverIPA<_>, _, _, _>(&params, &pk, acc, &mut rng, &mut transcript);
// let _ = create_proof::<_, ProverIPA<_>, _, _, _>(&params, &pk, acc, &mut rng, &mut transcript);
}
1 change: 0 additions & 1 deletion halo2_proofs/src/plonk/circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2234,7 +2234,6 @@ impl<F: Field> ConstraintSystem<F> {

/// Compute the degree of the constraint system (the maximum degree of all
/// constraints).
/// TODO(@adr1anh): Folding degree?
pub fn degree(&self) -> usize {
// The permutation argument will serve alongside the gates, so must be
// accounted for.
Expand Down
7 changes: 2 additions & 5 deletions halo2_proofs/src/protostar.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
//! Contains logic for handling halo2 circuits with Protostar

pub mod decider;
mod error_check;
pub mod accumulator;
mod constraints;
mod keygen;
pub mod prover;
mod row_evaluator;
mod transcript;

pub use error_check::Accumulator;
pub use keygen::ProvingKey;
154 changes: 154 additions & 0 deletions halo2_proofs/src/protostar/accumulator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
use std::iter::{self, zip};

use ff::Field;
use group::Curve;
use halo2curves::CurveAffine;
use rand_core::RngCore;

use crate::{
arithmetic::{eval_polynomial, parallelize},
dev::metadata::Gate,
poly::{
commitment::{Blind, Params},
LagrangeCoeff, Polynomial,
},
transcript::{EncodedChallenge, TranscriptWrite},
};

use self::committed::Committed;

use super::{
constraints::{paired::Paired, polynomial::PolynomialRef, Data},
ProvingKey,
};

pub(super) mod advice;
pub(super) mod committed;
pub(super) mod compressed_verifier;
pub(super) mod instance;
pub(super) mod lookup;

/// An `Accumulator` contains the entirety of the IOP transcript,
/// including commitments and verifier challenges.
#[derive(Debug, Clone, PartialEq)]
pub struct Accumulator<C: CurveAffine> {
pub instance: instance::Transcript<C>,
pub advice: advice::Transcript<C>,
pub lookups: Vec<lookup::Transcript<C>>,
pub beta: compressed_verifier::Transcript<C>,

pub ys: Vec<C::Scalar>,

// Error value for all constraints
pub error: C::Scalar,
}

impl<C: CurveAffine> Accumulator<C> {
pub fn fold<E: EncodedChallenge<C>, T: TranscriptWrite<C, E>>(
pk: &ProvingKey<C>,
acc0: Self,
acc1: Self,
transcript: &mut T,
) -> Self {
let paired_data = Paired::<'_, C::Scalar>::new_data(pk, &acc0, &acc1);

let full_constraint = paired_data.full_constraint(pk.cs.gates(), pk.cs.lookups());

let error_poly = Paired::<'_, C::Scalar>::evaluate_compressed_polynomial(
full_constraint,
pk.usable_rows.clone(),
pk.num_rows,
);

for coef in &error_poly {
let _ = transcript.write_scalar(*coef);
}
let alpha = *transcript.squeeze_challenge_scalar::<C::Scalar>();
Self::merge(acc0, acc1, error_poly, alpha)
}

fn merge(acc0: Self, acc1: Self, error_poly: Vec<C::Scalar>, alpha: C::Scalar) -> Self {
let instance = instance::Transcript::merge(alpha, acc0.instance, acc1.instance);
let advice = advice::Transcript::merge(alpha, acc0.advice, acc1.advice);
let lookups = zip(acc0.lookups.into_iter(), acc1.lookups.into_iter())
.map(|(lookup0, lookup1)| lookup::Transcript::merge(alpha, lookup0, lookup1))
.collect();
let beta = compressed_verifier::Transcript::merge(alpha, acc0.beta, acc1.beta);

let ys = zip(acc0.ys.into_iter(), acc1.ys.into_iter())
.map(|(y0, y1)| y0 + alpha * (y1 - y0))
.collect();

let error = eval_polynomial(&error_poly, alpha);

let error0 = eval_polynomial(&error_poly, C::Scalar::ZERO);
let error1 = eval_polynomial(&error_poly, C::Scalar::ONE);

assert_eq!(error0, acc0.error);
assert_eq!(error1, acc1.error);

Self {
instance,
advice,
lookups,
beta,
ys,
error,
}
}

pub fn decide<'params, P: Params<'params, C>>(
params: &P,
pk: &ProvingKey<C>,
acc: &Self,
) -> bool {
let committed_iter: Vec<&Committed<C>> = acc
.instance
.committed
.iter()
.chain(&acc.advice.committed)
.chain([&acc.beta.beta, &acc.beta.beta_shift].into_iter())
.chain(
acc.lookups
.iter()
.flat_map(|lookup| [&lookup.m, &lookup.g, &lookup.h].into_iter()),
)
.collect();

let committed_ok = committed_iter.iter().all(|c| c.decide(params));

let error_vec = Self::error_vector(pk, acc);

let error = error_vec
.iter()
.zip(acc.beta.beta.values.iter())
.fold(C::Scalar::ZERO, |acc, (e, b)| acc + (*e * b));

let error_ok = error == acc.error;

committed_ok && error_ok
}

pub fn error_vector(pk: &ProvingKey<C>, acc: &Self) -> Polynomial<C::Scalar, LagrangeCoeff> {
let lagrange_data = Data::<PolynomialRef<'_, C::Scalar, LagrangeCoeff>>::new(&pk, &acc);

let full_constraint = lagrange_data.full_constraint_no_beta(pk.cs.gates(), pk.cs.lookups());

let mut error = pk.domain.empty_lagrange();
parallelize(&mut error, |value, start| {
for (i, v) in value.iter_mut().enumerate() {
let row_idx = i + start;
*v = full_constraint.evaluate(
&|c| c,
&|challenge| *challenge.value,
&|fixed| fixed.column[fixed.row_idx(row_idx, pk.num_rows)],
&|witness| witness.column[witness.row_idx(row_idx, pk.num_rows)],
&|e| -e,
&|a, b| a + b,
&|a, b| a * b,
);
}
});
error
}
}
Loading

0 comments on commit 4abf832

Please sign in to comment.