From cfc3dfa38dc64088f55590efdf6255838ace0512 Mon Sep 17 00:00:00 2001 From: Skalman Date: Thu, 26 Sep 2024 09:26:58 -0400 Subject: [PATCH] Do cargo fmt --- common/src/domain.rs | 52 ++++++---- common/src/gadgets/booleanity.rs | 15 +-- common/src/gadgets/cond_add.rs | 50 +++++----- common/src/gadgets/fixed_cells.rs | 20 ++-- common/src/gadgets/inner_prod.rs | 20 ++-- common/src/gadgets/mod.rs | 6 +- common/src/gadgets/sw_cond_add.rs | 136 ++++++++++---------------- common/src/gadgets/te_cond_add.rs | 153 ++++++++++++------------------ common/src/lib.rs | 24 ++--- common/src/piop.rs | 9 +- common/src/prover.rs | 24 ++--- common/src/test_helpers.rs | 19 ++-- common/src/transcript.rs | 12 ++- common/src/verifier.rs | 63 +++++++----- ring/src/lib.rs | 86 ++++++++++++----- ring/src/piop/mod.rs | 66 ++++++++----- ring/src/piop/params.rs | 24 ++--- ring/src/piop/prover.rs | 71 ++++++++------ ring/src/piop/verifier.rs | 39 +++++--- ring/src/ring.rs | 66 ++++++++----- ring/src/ring_prover.rs | 37 +++++--- ring/src/ring_verifier.rs | 42 +++++--- 22 files changed, 557 insertions(+), 477 deletions(-) diff --git a/common/src/domain.rs b/common/src/domain.rs index 28e71ec..9a7ff58 100644 --- a/common/src/domain.rs +++ b/common/src/domain.rs @@ -1,6 +1,8 @@ use ark_ff::{batch_inversion, FftField, Zero}; -use ark_poly::{DenseUVPolynomial, EvaluationDomain, Evaluations, GeneralEvaluationDomain, Polynomial}; use ark_poly::univariate::DensePolynomial; +use ark_poly::{ + DenseUVPolynomial, EvaluationDomain, Evaluations, GeneralEvaluationDomain, Polynomial, +}; use ark_std::{vec, vec::Vec}; use crate::FieldColumn; @@ -16,8 +18,10 @@ struct Domains { impl Domains { fn new(n: usize) -> Self { - let x1 = GeneralEvaluationDomain::::new(n).unwrap_or_else(|| panic!("No domain of size {}", n)); - let x4 = GeneralEvaluationDomain::::new(4 * n).unwrap_or_else(|| panic!("No domain of size {}", 4 * n)); + let x1 = GeneralEvaluationDomain::::new(n) + .unwrap_or_else(|| panic!("No domain of size {}", n)); + let x4 = GeneralEvaluationDomain::::new(4 * n) + .unwrap_or_else(|| panic!("No domain of size {}", 4 * n)); Self { x1, x4 } } @@ -26,7 +30,12 @@ impl Domains { let evals = Evaluations::from_vec_and_domain(evals, self.x1); let poly = evals.interpolate_by_ref(); let evals_4x = poly.evaluate_over_domain_by_ref(self.x4); - FieldColumn { len, poly, evals, evals_4x } + FieldColumn { + len, + poly, + evals, + evals_4x, + } } fn column_from_poly(&self, poly: DensePolynomial, len: usize) -> FieldColumn { @@ -34,7 +43,12 @@ impl Domains { let evals_4x = self.amplify(&poly); let evals = evals_4x.evals.iter().step_by(4).cloned().collect(); let evals = Evaluations::from_vec_and_domain(evals, self.x1); - FieldColumn { len, poly, evals, evals_4x } + FieldColumn { + len, + poly, + evals, + evals_4x, + } } // Amplifies the number of the evaluations of the polynomial so it can be multiplied in linear time. @@ -81,13 +95,12 @@ impl Domain { } } - pub(crate) fn divide_by_vanishing_poly<>( - &self, - poly: &DensePolynomial, - ) -> DensePolynomial { + pub(crate) fn divide_by_vanishing_poly(&self, poly: &DensePolynomial) -> DensePolynomial { let (quotient, remainder) = if self.hiding { let exclude_zk_rows = poly * self.zk_rows_vanishing_poly.as_ref().unwrap(); - exclude_zk_rows.divide_by_vanishing_poly(self.domains.x1).unwrap() //TODO error-handling + exclude_zk_rows + .divide_by_vanishing_poly(self.domains.x1) + .unwrap() //TODO error-handling } else { poly.divide_by_vanishing_poly(self.domains.x1).unwrap() //TODO error-handling }; @@ -100,7 +113,9 @@ impl Domain { assert!(len <= self.capacity); if self.hiding && hidden { evals.resize(self.capacity, F::zero()); - evals.resize_with(self.domains.x1.size(), || F::rand(&mut getrandom_or_panic::getrandom_or_panic())); + evals.resize_with(self.domains.x1.size(), || { + F::rand(&mut getrandom_or_panic::getrandom_or_panic()) + }); } else { evals.resize(self.domains.x1.size(), F::zero()); } @@ -132,7 +147,10 @@ fn l_i(i: usize, n: usize) -> Vec { } // (x - w^i) -fn vanishes_on_row(i: usize, domain: GeneralEvaluationDomain) -> DensePolynomial { +fn vanishes_on_row( + i: usize, + domain: GeneralEvaluationDomain, +) -> DensePolynomial { assert!(i < domain.size()); let w = domain.group_gen(); let wi = w.pow(&[i as u64]); @@ -202,10 +220,7 @@ impl EvaluatedDomain { } } - pub(crate) fn divide_by_vanishing_poly_in_zeta<>( - &self, - poly_in_zeta: F, - ) -> F { + pub(crate) fn divide_by_vanishing_poly_in_zeta(&self, poly_in_zeta: F) -> F { poly_in_zeta * self.vanishing_polynomial_inv } @@ -232,7 +247,10 @@ mod tests { let domain_eval = EvaluatedDomain::new(domain.domain(), z, hiding); assert_eq!(domain.l_first.poly.evaluate(&z), domain_eval.l_first); assert_eq!(domain.l_last.poly.evaluate(&z), domain_eval.l_last); - assert_eq!(domain.not_last_row.poly.evaluate(&z), domain_eval.not_last_row); + assert_eq!( + domain.not_last_row.poly.evaluate(&z), + domain_eval.not_last_row + ); } #[test] diff --git a/common/src/gadgets/booleanity.rs b/common/src/gadgets/booleanity.rs index d897d17..46820e2 100644 --- a/common/src/gadgets/booleanity.rs +++ b/common/src/gadgets/booleanity.rs @@ -1,11 +1,11 @@ use ark_ff::{FftField, Field, Zero}; -use ark_poly::{Evaluations, GeneralEvaluationDomain}; use ark_poly::univariate::DensePolynomial; +use ark_poly::{Evaluations, GeneralEvaluationDomain}; use ark_std::{vec, vec::Vec}; -use crate::{Column, const_evals, FieldColumn}; use crate::domain::Domain; use crate::gadgets::VerifierGadget; +use crate::{const_evals, Column, FieldColumn}; #[derive(Clone)] pub struct BitColumn { @@ -13,10 +13,10 @@ pub struct BitColumn { pub col: FieldColumn, } - impl BitColumn { pub fn init(bits: Vec, domain: &Domain) -> Self { - let bits_as_field_elements = bits.iter() + let bits_as_field_elements = bits + .iter() .map(|&b| if b { F::one() } else { F::zero() }) .collect(); let col = domain.private_column(bits_as_field_elements); @@ -24,7 +24,6 @@ impl BitColumn { } } - impl Column for BitColumn { fn domain(&self) -> GeneralEvaluationDomain { self.col.domain() @@ -39,12 +38,10 @@ impl Column for BitColumn { } } - pub struct Booleanity { bits: BitColumn, } - impl<'a, F: FftField> Booleanity { pub fn init(bits: BitColumn) -> Self { Self { bits } @@ -63,15 +60,13 @@ impl<'a, F: FftField> Booleanity { } } - pub struct BooleanityValues { pub bits: F, } - impl VerifierGadget for BooleanityValues { fn evaluate_constraints_main(&self) -> Vec { let c = self.bits * (F::one() - self.bits); vec![c] } -} \ No newline at end of file +} diff --git a/common/src/gadgets/cond_add.rs b/common/src/gadgets/cond_add.rs index d429a2d..a8e3371 100644 --- a/common/src/gadgets/cond_add.rs +++ b/common/src/gadgets/cond_add.rs @@ -1,27 +1,24 @@ -use ark_ec::{AffineRepr}; -use ark_ff::{FftField, Field}; -use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; -use ark_std::{vec::Vec}; -use crate::{Column, FieldColumn}; use crate::domain::Domain; use crate::gadgets::booleanity::BitColumn; +use crate::{Column, FieldColumn}; +use ark_ec::AffineRepr; +use ark_ff::{FftField, Field}; +use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; +use ark_std::vec::Vec; // A vec of affine points from the prime-order subgroup of the curve whose base field enables FFTs, // and its convenience representation as columns of coordinates over the curve's base field. #[derive(Clone, CanonicalSerialize, CanonicalDeserialize)] -pub struct AffineColumn> { - pub (super) points: Vec

, +pub struct AffineColumn> { + pub(super) points: Vec

, pub xs: FieldColumn, pub ys: FieldColumn, } -impl> AffineColumn { - +impl> AffineColumn { fn column(points: Vec

, domain: &Domain, hidden: bool) -> Self { assert!(points.iter().all(|p| !p.is_zero())); - let (xs, ys) = points.iter() - .map(|p| p.xy().unwrap()) - .unzip(); + let (xs, ys) = points.iter().map(|p| p.xy().unwrap()).unzip(); let xs = domain.column(xs, hidden); let ys = domain.column(ys, hidden); Self { points, xs, ys } @@ -39,33 +36,30 @@ impl> AffineColumn { } } -pub trait CondAdd where +pub trait CondAdd +where F: FftField, - AffinePoint: AffineRepr, - + AffinePoint: AffineRepr, { type CondAddValT: CondAddValues; - fn init(bitmask: BitColumn, - points: AffineColumn, - seed: AffinePoint, - domain: &Domain) -> Self; - + fn init( + bitmask: BitColumn, + points: AffineColumn, + seed: AffinePoint, + domain: &Domain, + ) -> Self; + fn evaluate_assignment(&self, z: &F) -> Self::CondAddValT; fn get_acc(&self) -> AffineColumn; fn get_result(&self) -> AffinePoint; } pub trait CondAddValues - where F: Field +where + F: Field, { fn acc_coeffs_1(&self) -> (F, F); fn acc_coeffs_2(&self) -> (F, F); - fn init( - bitmask: F, - points: (F, F), - not_last: F, - acc: (F, F), - )-> Self; - + fn init(bitmask: F, points: (F, F), not_last: F, acc: (F, F)) -> Self; } diff --git a/common/src/gadgets/fixed_cells.rs b/common/src/gadgets/fixed_cells.rs index 11c1d46..c895055 100644 --- a/common/src/gadgets/fixed_cells.rs +++ b/common/src/gadgets/fixed_cells.rs @@ -1,11 +1,11 @@ use ark_ff::{FftField, Field, Zero}; -use ark_poly::Evaluations; use ark_poly::univariate::DensePolynomial; +use ark_poly::Evaluations; use ark_std::{vec, vec::Vec}; -use crate::{Column, const_evals, FieldColumn}; use crate::domain::Domain; use crate::gadgets::VerifierGadget; +use crate::{const_evals, Column, FieldColumn}; pub struct FixedCells { col: FieldColumn, @@ -15,7 +15,6 @@ pub struct FixedCells { l_last: FieldColumn, } - pub struct FixedCellsValues { pub col: F, pub col_first: F, @@ -24,7 +23,6 @@ pub struct FixedCellsValues { pub l_last: F, } - impl FixedCells { pub fn init(col: FieldColumn, domain: &Domain) -> Self { assert_eq!(col.len, domain.capacity); @@ -32,7 +30,13 @@ impl FixedCells { let col_last = col.evals.evals[domain.capacity - 1]; let l_first = domain.l_first.clone(); let l_last = domain.l_last.clone(); - Self { col, col_first, col_last, l_first, l_last } + Self { + col, + col_first, + col_last, + l_first, + l_last, + } } pub fn constraints(&self) -> Vec> { @@ -52,10 +56,10 @@ impl FixedCells { } } - impl VerifierGadget for FixedCellsValues { fn evaluate_constraints_main(&self) -> Vec { - let c = (self.col - self.col_first) * self.l_first + (self.col - self.col_last) * self.l_last; + let c = + (self.col - self.col_first) * self.l_first + (self.col - self.col_last) * self.l_last; vec![c] } -} \ No newline at end of file +} diff --git a/common/src/gadgets/inner_prod.rs b/common/src/gadgets/inner_prod.rs index 0ddd2b0..3d1000b 100644 --- a/common/src/gadgets/inner_prod.rs +++ b/common/src/gadgets/inner_prod.rs @@ -1,11 +1,11 @@ use ark_ff::{FftField, Field}; -use ark_poly::{Evaluations, GeneralEvaluationDomain}; use ark_poly::univariate::DensePolynomial; +use ark_poly::{Evaluations, GeneralEvaluationDomain}; use ark_std::{vec, vec::Vec}; -use crate::{Column, FieldColumn}; use crate::domain::Domain; use crate::gadgets::{ProverGadget, VerifierGadget}; +use crate::{Column, FieldColumn}; pub struct InnerProd { a: FieldColumn, @@ -21,7 +21,6 @@ pub struct InnerProdValues { pub acc: F, } - impl InnerProd { pub fn init(a: FieldColumn, b: FieldColumn, domain: &Domain) -> Self { assert_eq!(a.len, domain.capacity - 1); // last element is not constrained @@ -30,7 +29,12 @@ impl InnerProd { let mut acc = vec![F::zero()]; acc.extend(inner_prods); let acc = domain.private_column(acc); - Self { a, b, not_last: domain.not_last_row.clone(), acc } + Self { + a, + b, + not_last: domain.not_last_row.clone(), + acc, + } } /// Returns a[0]b[0], a[0]b[0] + a[1]b[1], ..., a[0]b[0] + a[1]b[1] + ... + a[n-1]b[n-1] @@ -71,7 +75,6 @@ impl ProverGadget for InnerProd { } } - impl VerifierGadget for InnerProdValues { fn evaluate_constraints_main(&self) -> Vec { let c = (-self.acc - self.a * self.b) * self.not_last; @@ -79,7 +82,6 @@ impl VerifierGadget for InnerProdValues { } } - #[cfg(test)] mod tests { use ark_ed_on_bls12_381_bandersnatch::Fq; @@ -94,9 +96,7 @@ mod tests { fn inner_prod(a: &[F], b: &[F]) -> F { assert_eq!(a.len(), b.len()); - a.iter().zip(b) - .map(|(a, b)| *a * b) - .sum() + a.iter().zip(b).map(|(a, b)| *a * b).sum() } fn _test_inner_prod_gadget(hiding: bool) { @@ -130,4 +130,4 @@ mod tests { _test_inner_prod_gadget(false); _test_inner_prod_gadget(true); } -} \ No newline at end of file +} diff --git a/common/src/gadgets/mod.rs b/common/src/gadgets/mod.rs index b610e80..c056e0f 100644 --- a/common/src/gadgets/mod.rs +++ b/common/src/gadgets/mod.rs @@ -1,15 +1,15 @@ use ark_ff::{FftField, Field}; -use ark_poly::{Evaluations, GeneralEvaluationDomain}; use ark_poly::univariate::DensePolynomial; +use ark_poly::{Evaluations, GeneralEvaluationDomain}; use ark_std::vec::Vec; pub mod booleanity; // pub mod inner_prod_pub; pub mod cond_add; -pub mod sw_cond_add; -pub mod te_cond_add; pub mod fixed_cells; pub mod inner_prod; +pub mod sw_cond_add; +pub mod te_cond_add; pub trait ProverGadget { // Columns populated by the gadget. diff --git a/common/src/gadgets/sw_cond_add.rs b/common/src/gadgets/sw_cond_add.rs index f47168a..2acf8ae 100644 --- a/common/src/gadgets/sw_cond_add.rs +++ b/common/src/gadgets/sw_cond_add.rs @@ -1,24 +1,24 @@ -use ark_ec::{AffineRepr, CurveGroup}; use ark_ec::short_weierstrass::{Affine, SWCurveConfig}; +use ark_ec::{AffineRepr, CurveGroup}; use ark_ff::{FftField, Field}; -use ark_poly::{Evaluations, GeneralEvaluationDomain}; use ark_poly::univariate::DensePolynomial; +use ark_poly::{Evaluations, GeneralEvaluationDomain}; use ark_std::{vec, vec::Vec}; -use crate::{Column, FieldColumn, const_evals}; use crate::domain::Domain; -use crate::gadgets::{ProverGadget, VerifierGadget}; use crate::gadgets::booleanity::BitColumn; use crate::gadgets::cond_add::{AffineColumn, CondAdd, CondAddValues}; +use crate::gadgets::{ProverGadget, VerifierGadget}; +use crate::{const_evals, Column, FieldColumn}; // Conditional affine addition: // if the bit is set for a point, add the point to the acc and store, // otherwise copy the acc value -pub struct SwCondAdd> { - pub(super)bitmask: BitColumn, - pub(super)points: AffineColumn, +pub struct SwCondAdd> { + pub(super) bitmask: BitColumn, + pub(super) points: AffineColumn, // The polynomial `X - w^{n-1}` in the Lagrange basis - pub(super)not_last: FieldColumn, + pub(super) not_last: FieldColumn, // Accumulates the (conditional) rolling sum of the points pub acc: AffineColumn, pub result: P, @@ -31,24 +31,28 @@ pub struct SwCondAddValues { pub acc: (F, F), } -impl CondAdd > for SwCondAdd> where +impl CondAdd> for SwCondAdd> +where F: FftField, - Curve: SWCurveConfig, + Curve: SWCurveConfig, { - type CondAddValT = SwCondAddValues; // Populates the acc column starting from the supplied seed (as 0 doesn't have an affine SW representation). // As the SW addition formula used is not complete, the seed must be selected in a way that would prevent // exceptional cases (doublings or adding the opposite point). // The last point of the input column is ignored, as adding it would made the acc column overflow due the initial point. - fn init(bitmask: BitColumn, - points: AffineColumn>, - seed: Affine, - domain: &Domain) -> Self { + fn init( + bitmask: BitColumn, + points: AffineColumn>, + seed: Affine, + domain: &Domain, + ) -> Self { assert_eq!(bitmask.bits.len(), domain.capacity - 1); assert_eq!(points.points.len(), domain.capacity - 1); let not_last = domain.not_last_row.clone(); - let acc = bitmask.bits.iter() + let acc = bitmask + .bits + .iter() .zip(points.points.iter()) .scan(seed, |acc, (&b, point)| { if b { @@ -56,15 +60,19 @@ impl CondAdd > for SwCondAdd> where } Some(*acc) }); - let acc: Vec<_> = ark_std::iter::once(seed) - .chain(acc) - .collect(); + let acc: Vec<_> = ark_std::iter::once(seed).chain(acc).collect(); let init_plus_result = acc.last().unwrap(); let result = init_plus_result.into_group() - seed.into_group(); let result = result.into_affine(); let acc = AffineColumn::private_column(acc, domain); - Self { bitmask, points, acc, not_last, result } + Self { + bitmask, + points, + acc, + not_last, + result, + } } fn evaluate_assignment(&self, z: &F) -> SwCondAddValues { @@ -83,14 +91,12 @@ impl CondAdd > for SwCondAdd> where fn get_result(&self) -> Affine { self.result.clone() } - } - impl ProverGadget for SwCondAdd> - where - F: FftField, - Curve: SWCurveConfig, +where + F: FftField, + Curve: SWCurveConfig, { fn witness_columns(&self) -> Vec> { vec![self.acc.xs.poly.clone(), self.acc.ys.poly.clone()] @@ -104,42 +110,12 @@ impl ProverGadget for SwCondAdd> let (x2, y2) = (&self.points.xs.evals_4x, &self.points.ys.evals_4x); let (x3, y3) = (&self.acc.xs.shifted_4x(), &self.acc.ys.shifted_4x()); - let mut c1 = - &( - b * - &( - &( - &( - &(x1 - x2) * &(x1 - x2) - ) * - &( - &(x1 + x2) + x3 - ) - ) - - &( - &(y2 - y1) * &(y2 - y1) - ) - ) - ) + - &( - &(one - b) * &(y3 - y1) - ); + let mut c1 = &(b * &(&(&(&(x1 - x2) * &(x1 - x2)) * &(&(x1 + x2) + x3)) + - &(&(y2 - y1) * &(y2 - y1)))) + + &(&(one - b) * &(y3 - y1)); - let mut c2 = - &( - b * - &( - &( - &(x1 - x2) * &(y3 + y1) - ) - - &( - &(y2 - y1) * &(x3 - x1) - ) - ) - ) + - &( - &(one - b) * &(x3 - x1) - ); + let mut c2 = &(b * &(&(&(x1 - x2) * &(y3 + y1)) - &(&(y2 - y1) * &(x3 - x1)))) + + &(&(one - b) * &(x3 - x1)); let not_last = &self.not_last.evals_4x; c1 *= not_last; @@ -167,7 +143,6 @@ impl ProverGadget for SwCondAdd> } } - impl VerifierGadget for SwCondAddValues { fn evaluate_constraints_main(&self) -> Vec { let b = self.bitmask; @@ -175,17 +150,11 @@ impl VerifierGadget for SwCondAddValues { let (x2, y2) = self.points; let (x3, y3) = (F::zero(), F::zero()); - let mut c1 = - b * ( - (x1 - x2) * (x1 - x2) * (x1 + x2 + x3) - - (y2 - y1) * (y2 - y1) - ) + (F::one() - b) * (y3 - y1); + let mut c1 = b * ((x1 - x2) * (x1 - x2) * (x1 + x2 + x3) - (y2 - y1) * (y2 - y1)) + + (F::one() - b) * (y3 - y1); let mut c2 = - b * ( - (x1 - x2) * (y3 + y1) - - (y2 - y1) * (x3 - x1) - ) + (F::one() - b) * (x3 - x1); + b * ((x1 - x2) * (y3 + y1) - (y2 - y1) * (x3 - x1)) + (F::one() - b) * (x3 - x1); c1 *= self.not_last; c2 *= self.not_last; @@ -194,14 +163,8 @@ impl VerifierGadget for SwCondAddValues { } } - impl CondAddValues for SwCondAddValues { - fn init( - bitmask: F, - points: (F, F), - not_last: F, - acc: (F, F), - )-> Self { + fn init(bitmask: F, points: (F, F), not_last: F, acc: (F, F)) -> Self { SwCondAddValues:: { bitmask, points, @@ -239,19 +202,20 @@ impl CondAddValues for SwCondAddValues { } } - #[cfg(test)] mod tests { - use ark_ed_on_bls12_381_bandersnatch::{SWAffine, Fq}; + use ark_ed_on_bls12_381_bandersnatch::{Fq, SWAffine}; use ark_poly::Polynomial; use ark_std::test_rng; - use crate::test_helpers::*; use crate::test_helpers::cond_sum; + use crate::test_helpers::*; use super::*; - fn _test_sw_cond_add_gadget(hiding: bool) -> (Domain, SwCondAdd, Vec>) { + fn _test_sw_cond_add_gadget( + hiding: bool, + ) -> (Domain, SwCondAdd, Vec>) { let rng = &mut test_rng(); let log_n = 10; @@ -279,11 +243,9 @@ mod tests { domain.divide_by_vanishing_poly(&c1); domain.divide_by_vanishing_poly(&c2); - return (domain, gadget, cs,) - + return (domain, gadget, cs); } - #[test] fn test_sw_cond_add_gadget() { _test_sw_cond_add_gadget(false); @@ -301,12 +263,10 @@ mod tests { let linearized_evaluation = gadget.constraints_linearized(&random_point); for i in 0..2 { - - let result = linearized_evaluation[i].evaluate(&(random_point*domain.omega())) + vals.evaluate_constraints_main()[i]; + let result = linearized_evaluation[i].evaluate(&(random_point * domain.omega())) + + vals.evaluate_constraints_main()[i]; let constrain_poly = constrains[i].interpolate_by_ref(); assert_eq!(constrain_poly.evaluate(&random_point), result); } - } - } diff --git a/common/src/gadgets/te_cond_add.rs b/common/src/gadgets/te_cond_add.rs index 1d71d70..f6f3adb 100644 --- a/common/src/gadgets/te_cond_add.rs +++ b/common/src/gadgets/te_cond_add.rs @@ -1,31 +1,31 @@ +use ark_ec::twisted_edwards::{Affine, TECurveConfig}; use ark_ec::{AffineRepr, CurveGroup}; -use ark_ec::twisted_edwards::{Affine,TECurveConfig}; use ark_ff::{FftField, Field}; -use ark_poly::{Evaluations, GeneralEvaluationDomain}; use ark_poly::univariate::DensePolynomial; +use ark_poly::{Evaluations, GeneralEvaluationDomain}; use ark_std::{vec, vec::Vec}; use core::marker::PhantomData; -use crate::{Column, FieldColumn, const_evals}; use crate::domain::Domain; -use crate::gadgets::{ProverGadget, VerifierGadget}; use crate::gadgets::booleanity::BitColumn; use crate::gadgets::cond_add::{AffineColumn, CondAdd, CondAddValues}; +use crate::gadgets::{ProverGadget, VerifierGadget}; +use crate::{const_evals, Column, FieldColumn}; // Conditional affine addition: // if the bit is set for a point, add the point to the acc and store, // otherwise copy the acc value -pub struct TeCondAdd> { - pub(super)bitmask: BitColumn, - pub(super)points: AffineColumn, +pub struct TeCondAdd> { + pub(super) bitmask: BitColumn, + pub(super) points: AffineColumn, // The polynomial `X - w^{n-1}` in the Lagrange basis - pub(super)not_last: FieldColumn, + pub(super) not_last: FieldColumn, // Accumulates the (conditional) rolling sum of the points pub acc: AffineColumn, pub result: P, } -pub struct TeCondAddValues> { +pub struct TeCondAddValues> { pub bitmask: F, pub points: (F, F), pub not_last: F, @@ -33,23 +33,28 @@ pub struct TeCondAddValues> { pub _curve: PhantomData, } -impl CondAdd> for TeCondAdd> where +impl CondAdd> for TeCondAdd> +where F: FftField, - Curve: TECurveConfig, + Curve: TECurveConfig, { type CondAddValT = TeCondAddValues; // Populates the acc column starting from the supplied seed (as 0 doesn't work with the addition formula). // As the TE addition formula used is not complete, the seed must be selected in a way that would prevent // exceptional cases (doublings or adding the opposite point). // The last point of the input column is ignored, as adding it would made the acc column overflow due the initial point. - fn init(bitmask: BitColumn, - points: AffineColumn>, - seed: Affine, - domain: &Domain) -> Self { + fn init( + bitmask: BitColumn, + points: AffineColumn>, + seed: Affine, + domain: &Domain, + ) -> Self { assert_eq!(bitmask.bits.len(), domain.capacity - 1); assert_eq!(points.points.len(), domain.capacity - 1); let not_last = domain.not_last_row.clone(); - let acc = bitmask.bits.iter() + let acc = bitmask + .bits + .iter() .zip(points.points.iter()) .scan(seed, |acc, (&b, point)| { if b { @@ -57,15 +62,19 @@ impl CondAdd> for TeCondAdd> where } Some(*acc) }); - let acc: Vec<_> = ark_std::iter::once(seed) - .chain(acc) - .collect(); + let acc: Vec<_> = ark_std::iter::once(seed).chain(acc).collect(); let init_plus_result = acc.last().unwrap(); let result = init_plus_result.into_group() - seed.into_group(); let result = result.into_affine(); let acc = AffineColumn::private_column(acc, domain); - Self { bitmask, points, acc, not_last, result } + Self { + bitmask, + points, + acc, + not_last, + result, + } } fn evaluate_assignment(&self, z: &F) -> TeCondAddValues { @@ -85,13 +94,12 @@ impl CondAdd> for TeCondAdd> where fn get_result(&self) -> Affine { self.result.clone() } - } impl ProverGadget for TeCondAdd> - where - F: FftField, - Curve: TECurveConfig, +where + F: FftField, + Curve: TECurveConfig, { fn witness_columns(&self) -> Vec> { vec![self.acc.xs.poly.clone(), self.acc.ys.poly.clone()] @@ -107,46 +115,12 @@ impl ProverGadget for TeCondAdd> let (x3, y3) = (&self.acc.xs.shifted_4x(), &self.acc.ys.shifted_4x()); //b (x_3 (y_1 y_2 + ax_1 x_2) - x_1 y_1 - y_2 x_2) + (1 - b) (x_3 - x_1) = 0 - let mut c1 = - &( - b * - &( - &( - x3 * - &( - &(y1 * y2) + - - &(te_a_coeff * - - &(x1 * x2) - ) - - ) - ) - - - - &( - &(x1 * y1) + &(y2* x2) - ) - ) - ) + - &( - &(one - b) * &(x3 - x1) - ); + let mut c1 = &(b * &(&(x3 * &(&(y1 * y2) + &(te_a_coeff * &(x1 * x2)))) + - &(&(x1 * y1) + &(y2 * x2)))) + + &(&(one - b) * &(x3 - x1)); //b (y_3 (x_1 y_2 - x_2 y_1) - x_1 y_1 + x_2 y_2) + (1 - b) (y_3 - y_1) = 0 - let mut c2 = - &( - b * - &( &(y3 * - &( - &(x1 * y2) - &(x2 * y1))) - - &(&(x1 * y1) - &(x2 * y2)) - ) - ) - + - &( - &(one - b) * &(y3 - y1) - ); + let mut c2 = &(b * &(&(y3 * &(&(x1 * y2) - &(x2 * y1))) - &(&(x1 * y1) - &(x2 * y2)))) + + &(&(one - b) * &(y3 - y1)); let not_last = &self.not_last.evals_4x; c1 *= not_last; @@ -175,7 +149,9 @@ impl ProverGadget for TeCondAdd> } } -impl> VerifierGadget for TeCondAddValues { +impl> VerifierGadget + for TeCondAddValues +{ fn evaluate_constraints_main(&self) -> Vec { let b = self.bitmask; let (x1, y1) = self.acc; @@ -183,18 +159,12 @@ impl> VerifierGadget for TeCondAd let (x3, y3) = (F::zero(), F::zero()); //b (x_3 (y_1 y_2 + ax_1 x_2) - x_1 y_1 - y_2 x_2) + (1 - b) (x_3 - x_1) = 0 - let mut c1 = - b * ( - x3 * (y1*y2 + Curve::COEFF_A * x1 * x2) - - (x1*y1 + x2*y2) - ) + (F::one() - b) * (x3 - x1); + let mut c1 = b * (x3 * (y1 * y2 + Curve::COEFF_A * x1 * x2) - (x1 * y1 + x2 * y2)) + + (F::one() - b) * (x3 - x1); //b (y_3 (x_1 y_2 - x_2 y_1) - x_1 y_1 + x_2 y_2) + (1 - b) (y_3 - y_1) = 0 let mut c2 = - b * ( - y3 * (x1*y2 - x2*y1) - - (x1*y1 - x2*y2) - ) + (F::one() - b) * (y3 - y1); + b * (y3 * (x1 * y2 - x2 * y1) - (x1 * y1 - x2 * y2)) + (F::one() - b) * (y3 - y1); c1 *= self.not_last; c2 *= self.not_last; @@ -203,19 +173,14 @@ impl> VerifierGadget for TeCondAd } } -impl> CondAddValues for TeCondAddValues { - fn init( - bitmask: F, - points: (F, F), - not_last: F, - acc: (F, F), - )-> Self { +impl> CondAddValues for TeCondAddValues { + fn init(bitmask: F, points: (F, F), not_last: F, acc: (F, F)) -> Self { TeCondAddValues:: { bitmask, points, not_last, acc, - _curve : PhantomData, + _curve: PhantomData, } } fn acc_coeffs_1(&self) -> (F, F) { @@ -223,7 +188,7 @@ impl> CondAddValues for TeCondAdd let (x1, y1) = self.acc; let (x2, y2) = self.points; - let mut c_acc_x = b * (y1*y2 + Curve::COEFF_A * x1*x2) + F::one() - b; + let mut c_acc_x = b * (y1 * y2 + Curve::COEFF_A * x1 * x2) + F::one() - b; let mut c_acc_y = F::zero(); c_acc_x *= self.not_last; @@ -238,7 +203,7 @@ impl> CondAddValues for TeCondAdd let (x2, y2) = self.points; let mut c_acc_x = F::zero(); - let mut c_acc_y = b * (x1*y2 - x2*y1) + F::one() - b; + let mut c_acc_y = b * (x1 * y2 - x2 * y1) + F::one() - b; c_acc_x *= self.not_last; c_acc_y *= self.not_last; @@ -247,19 +212,24 @@ impl> CondAddValues for TeCondAdd } } - #[cfg(test)] mod tests { - use ark_ed_on_bls12_381_bandersnatch::{Fq, EdwardsAffine}; + use ark_ed_on_bls12_381_bandersnatch::{EdwardsAffine, Fq}; use ark_poly::Polynomial; use ark_std::test_rng; - use crate::test_helpers::*; use crate::test_helpers::cond_sum; + use crate::test_helpers::*; use super::*; - fn _test_te_cond_add_gadget(hiding: bool) -> (Domain, TeCondAdd, Vec>){ + fn _test_te_cond_add_gadget( + hiding: bool, + ) -> ( + Domain, + TeCondAdd, + Vec>, + ) { let rng = &mut test_rng(); let log_n = 10; @@ -287,7 +257,7 @@ mod tests { domain.divide_by_vanishing_poly(&c1); domain.divide_by_vanishing_poly(&c2); - return (domain, gadget, cs,) + return (domain, gadget, cs); } #[test] @@ -298,7 +268,6 @@ mod tests { #[test] fn test_linearized_constrain() { - let (domain, gadget, constrains) = _test_te_cond_add_gadget(false); let rng = &mut test_rng(); @@ -308,12 +277,10 @@ mod tests { let linearized_evaluation = gadget.constraints_linearized(&random_point); for i in 0..2 { - - let result = linearized_evaluation[i].evaluate(&(random_point*domain.omega())) + vals.evaluate_constraints_main()[i]; + let result = linearized_evaluation[i].evaluate(&(random_point * domain.omega())) + + vals.evaluate_constraints_main()[i]; let constrain_poly = constrains[i].interpolate_by_ref(); assert_eq!(constrain_poly.evaluate(&random_point), result); } - } - } diff --git a/common/src/lib.rs b/common/src/lib.rs index c75d8e2..00ffa38 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -1,19 +1,19 @@ #![cfg_attr(not(feature = "std"), no_std)] use ark_ff::{FftField, PrimeField}; -use ark_poly::{EvaluationDomain, Evaluations, GeneralEvaluationDomain, Polynomial}; use ark_poly::univariate::DensePolynomial; +use ark_poly::{EvaluationDomain, Evaluations, GeneralEvaluationDomain, Polynomial}; use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; use ark_std::{vec, vec::Vec}; use fflonk::pcs::{Commitment, PCS}; +pub mod domain; pub mod gadgets; -pub mod test_helpers; pub mod piop; pub mod prover; -pub mod verifier; +pub mod test_helpers; pub mod transcript; -pub mod domain; +pub mod verifier; pub trait Column { fn domain(&self) -> GeneralEvaluationDomain; @@ -66,22 +66,24 @@ pub fn const_evals(c: F, domain: GeneralEvaluationDomain) -> Eva Evaluations::from_vec_and_domain(vec![c; domain.size()], domain) } - pub trait ColumnsEvaluated: CanonicalSerialize + CanonicalDeserialize { fn to_vec(self) -> Vec; } -pub trait ColumnsCommited>: CanonicalSerialize + CanonicalDeserialize { +pub trait ColumnsCommited>: + CanonicalSerialize + CanonicalDeserialize +{ fn to_vec(self) -> Vec; } #[derive(Clone, CanonicalSerialize, CanonicalDeserialize)] pub struct Proof - where - F: PrimeField, - CS: PCS, - Commitments: ColumnsCommited, - Evaluations: ColumnsEvaluated, { +where + F: PrimeField, + CS: PCS, + Commitments: ColumnsCommited, + Evaluations: ColumnsEvaluated, +{ pub column_commitments: Commitments, pub columns_at_zeta: Evaluations, pub quotient_commitment: CS::C, diff --git a/common/src/piop.rs b/common/src/piop.rs index f6b1690..1ca41c2 100644 --- a/common/src/piop.rs +++ b/common/src/piop.rs @@ -1,12 +1,12 @@ use ark_ff::PrimeField; -use ark_poly::Evaluations; use ark_poly::univariate::DensePolynomial; +use ark_poly::Evaluations; use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; use ark_std::vec::Vec; use fflonk::pcs::Commitment; -use crate::{ColumnsCommited, ColumnsEvaluated}; use crate::domain::{Domain, EvaluatedDomain}; +use crate::{ColumnsCommited, ColumnsEvaluated}; pub trait ProverPiop> { type Commitments: ColumnsCommited; @@ -14,7 +14,10 @@ pub trait ProverPiop> { type Instance: CanonicalSerialize + CanonicalDeserialize; // Commitments to the column polynomials excluding the precommitted columns. - fn committed_columns) -> C>(&self, commit: Fun) -> Self::Commitments; + fn committed_columns) -> C>( + &self, + commit: Fun, + ) -> Self::Commitments; // All the column polynomials (including precommitted columns) fn columns(&self) -> Vec>; diff --git a/common/src/prover.rs b/common/src/prover.rs index 23e9fd5..91d4823 100644 --- a/common/src/prover.rs +++ b/common/src/prover.rs @@ -6,8 +6,8 @@ use fflonk::aggregation::single::aggregate_polys; use fflonk::pcs::PCS; use crate::piop::ProverPiop; -use crate::Proof; use crate::transcript::Transcript; +use crate::Proof; pub struct PlonkProver, T: Transcript> { // Polynomial commitment scheme committer's key. @@ -18,9 +18,11 @@ pub struct PlonkProver, T: Transcript> { } impl, T: Transcript> PlonkProver { - pub fn init(pcs_ck: CS::CK, - verifier_key: impl CanonicalSerialize, //TODO: a type, - empty_transcript: T) -> Self { + pub fn init( + pcs_ck: CS::CK, + verifier_key: impl CanonicalSerialize, //TODO: a type, + empty_transcript: T, + ) -> Self { let mut transcript_prelude = empty_transcript; transcript_prelude._add_serializable(b"vk", &verifier_key); @@ -31,7 +33,8 @@ impl, T: Transcript> PlonkProver { } pub fn prove

(&self, piop: P) -> Proof - where P: ProverPiop + where + P: ProverPiop, { let mut transcript = self.transcript_prelude.clone(); transcript.add_instance(&piop.result()); @@ -65,7 +68,6 @@ impl, T: Transcript> PlonkProver { let lin_at_zeta_omega = lin.evaluate(&zeta_omega); transcript.add_evaluations(&columns_at_zeta, &lin_at_zeta_omega); - let polys_at_zeta = [columns_to_open, vec![quotient_poly]].concat(); let nus = transcript.get_kzg_aggregation_challenges(polys_at_zeta.len()); let agg_at_zeta = aggregate_polys(&polys_at_zeta, &nus); @@ -80,15 +82,15 @@ impl, T: Transcript> PlonkProver { agg_at_zeta_proof, lin_at_zeta_omega_proof, } - } fn aggregate_evaluations(polys: &[Evaluations], coeffs: &[F]) -> Evaluations { assert_eq!(coeffs.len(), polys.len()); - polys.iter().zip(coeffs.iter()) + polys + .iter() + .zip(coeffs.iter()) .map(|(p, &c)| p * c) - .reduce(|acc, p| &acc + &p).unwrap() + .reduce(|acc, p| &acc + &p) + .unwrap() } } - - diff --git a/common/src/test_helpers.rs b/common/src/test_helpers.rs index 1e69955..8f65736 100644 --- a/common/src/test_helpers.rs +++ b/common/src/test_helpers.rs @@ -1,23 +1,24 @@ use ark_ec::{AffineRepr, CurveGroup}; use ark_std::rand::Rng; -use ark_std::UniformRand; use ark_std::vec::Vec; +use ark_std::UniformRand; pub fn random_bitvec(n: usize, density: f64, rng: &mut R) -> Vec { - (0..n) - .map(|_| rng.gen_bool(density)) - .collect() + (0..n).map(|_| rng.gen_bool(density)).collect() } pub fn random_vec(n: usize, rng: &mut R) -> Vec { - (0..n) - .map(|_| X::rand(rng)) - .collect() + (0..n).map(|_| X::rand(rng)).collect() } -pub fn cond_sum

(bitmask: &[bool], points: &[P]) -> P where P: AffineRepr { +pub fn cond_sum

(bitmask: &[bool], points: &[P]) -> P +where + P: AffineRepr, +{ assert_eq!(bitmask.len(), points.len()); - bitmask.iter().zip(points.iter()) + bitmask + .iter() + .zip(points.iter()) .map(|(&b, &p)| if b { p } else { P::zero() }) .sum::() .into_affine() diff --git a/common/src/transcript.rs b/common/src/transcript.rs index 04851d2..a213c8f 100644 --- a/common/src/transcript.rs +++ b/common/src/transcript.rs @@ -1,15 +1,19 @@ use ark_ff::PrimeField; use ark_poly::GeneralEvaluationDomain; use ark_serialize::CanonicalSerialize; -use ark_std::{vec, vec::Vec}; use ark_std::rand::SeedableRng; -use fflonk::pcs::{PCS, PcsParams}; +use ark_std::{vec, vec::Vec}; +use fflonk::pcs::{PcsParams, PCS}; use rand_chacha::ChaCha20Rng; use crate::{ColumnsCommited, ColumnsEvaluated}; pub trait Transcript>: Clone { - fn add_protocol_params(&mut self, domain: &GeneralEvaluationDomain, pcs_raw_vk: &::RVK) { + fn add_protocol_params( + &mut self, + domain: &GeneralEvaluationDomain, + pcs_raw_vk: &::RVK, + ) { self._add_serializable(b"domain", domain); self._add_serializable(b"pcs_raw_vk", pcs_raw_vk); } @@ -84,4 +88,4 @@ impl> Transcript for merlin::Transcript { self.challenge_bytes(b"transcript_rng", &mut buf); ChaCha20Rng::from_seed(buf) } -} \ No newline at end of file +} diff --git a/common/src/verifier.rs b/common/src/verifier.rs index 0c4d8f9..096c285 100644 --- a/common/src/verifier.rs +++ b/common/src/verifier.rs @@ -1,13 +1,13 @@ use ark_ff::{Field, PrimeField}; use ark_serialize::CanonicalSerialize; -use ark_std::{vec, vec::Vec}; use ark_std::rand::Rng; -use fflonk::pcs::{Commitment, PCS, PcsParams}; +use ark_std::{vec, vec::Vec}; +use fflonk::pcs::{Commitment, PcsParams, PCS}; use rand_chacha::ChaCha20Rng; -use crate::{ColumnsCommited, ColumnsEvaluated, Proof}; use crate::piop::VerifierPiop; use crate::transcript::Transcript; +use crate::{ColumnsCommited, ColumnsEvaluated, Proof}; pub struct PlonkVerifier, T: Transcript> { // Polynomial commitment scheme verifier's key. @@ -18,9 +18,11 @@ pub struct PlonkVerifier, T: Transcript> { } impl, T: Transcript> PlonkVerifier { - pub fn init(pcs_vk: ::VK, - verifier_key: &impl CanonicalSerialize, - empty_transcript: T) -> Self { + pub fn init( + pcs_vk: ::VK, + verifier_key: &impl CanonicalSerialize, + empty_transcript: T, + ) -> Self { let mut transcript_prelude = empty_transcript; transcript_prelude._add_serializable(b"vk", verifier_key); @@ -37,35 +39,53 @@ impl, T: Transcript> PlonkVerifier { challenges: Challenges, rng: &mut R, ) -> bool - where - Piop: VerifierPiop, - Commitments: ColumnsCommited, - Evaluations: ColumnsEvaluated, + where + Piop: VerifierPiop, + Commitments: ColumnsCommited, + Evaluations: ColumnsEvaluated, { - let eval: F = piop.evaluate_constraints_main().iter().zip(challenges.alphas.iter()).map(|(c, alpha)| *alpha * c).sum(); + let eval: F = piop + .evaluate_constraints_main() + .iter() + .zip(challenges.alphas.iter()) + .map(|(c, alpha)| *alpha * c) + .sum(); let zeta = challenges.zeta; let domain_evaluated = piop.domain_evaluated(); - let q_zeta = domain_evaluated.divide_by_vanishing_poly_in_zeta(eval + proof.lin_at_zeta_omega); + let q_zeta = + domain_evaluated.divide_by_vanishing_poly_in_zeta(eval + proof.lin_at_zeta_omega); let mut columns = [ piop.precommitted_columns(), proof.column_commitments.to_vec(), - ].concat(); + ] + .concat(); columns.push(proof.quotient_commitment.clone()); let mut columns_at_zeta = proof.columns_at_zeta.to_vec(); columns_at_zeta.push(q_zeta); let cl = CS::C::combine(&challenges.nus, &columns); - let agg_y = columns_at_zeta.into_iter().zip(challenges.nus.iter()).map(|(y, r)| y * r).sum(); + let agg_y = columns_at_zeta + .into_iter() + .zip(challenges.nus.iter()) + .map(|(y, r)| y * r) + .sum(); let lin_pices = piop.constraint_polynomials_linearized_commitments(); let lin_comm = CS::C::combine(&challenges.alphas[..3], &lin_pices); let zeta_omega = zeta * domain_evaluated.omega(); - CS::batch_verify(&self.pcs_vk, vec![cl, lin_comm], vec![challenges.zeta, zeta_omega], vec![agg_y, proof.lin_at_zeta_omega], vec![proof.agg_at_zeta_proof, proof.lin_at_zeta_omega_proof], rng) + CS::batch_verify( + &self.pcs_vk, + vec![cl, lin_comm], + vec![challenges.zeta, zeta_omega], + vec![agg_y, proof.lin_at_zeta_omega], + vec![proof.agg_at_zeta_proof, proof.lin_at_zeta_omega_proof], + rng, + ) } pub fn restore_challenges( @@ -75,9 +95,9 @@ impl, T: Transcript> PlonkVerifier { n_polys: usize, n_constraints: usize, ) -> (Challenges, ChaCha20Rng) - where - Commitments: ColumnsCommited, - Evaluations: ColumnsEvaluated, + where + Commitments: ColumnsCommited, + Evaluations: ColumnsEvaluated, { let mut transcript = self.transcript_prelude.clone(); transcript.add_instance(instance); @@ -89,11 +109,7 @@ impl, T: Transcript> PlonkVerifier { let zeta = transcript.get_evaluation_point(); transcript.add_evaluations(&proof.columns_at_zeta, &proof.lin_at_zeta_omega); let nus = transcript.get_kzg_aggregation_challenges(n_polys); - let challenges = Challenges { - alphas, - zeta, - nus, - }; + let challenges = Challenges { alphas, zeta, nus }; (challenges, transcript.to_rng()) } @@ -104,4 +120,3 @@ pub struct Challenges { pub zeta: F, pub nus: Vec, } - diff --git a/ring/src/lib.rs b/ring/src/lib.rs index f92caa7..21e5b2d 100644 --- a/ring/src/lib.rs +++ b/ring/src/lib.rs @@ -1,8 +1,8 @@ #![cfg_attr(not(feature = "std"), no_std)] -use ark_ec::AffineRepr; use ark_ec::short_weierstrass::{Affine, SWCurveConfig}; -use ark_ff::{One, Zero, Field}; +use ark_ec::AffineRepr; +use ark_ff::{Field, One, Zero}; use ark_std::rand; use fflonk::pcs::PCS; @@ -10,8 +10,8 @@ pub use common::domain::Domain; use common::Proof; pub use piop::index; +pub use crate::piop::{params::PiopParams, FixedColumnsCommitted, ProverKey, VerifierKey}; use crate::piop::{RingCommitments, RingEvaluations}; -pub use crate::piop::{params::PiopParams, ProverKey, VerifierKey, FixedColumnsCommitted}; mod piop; pub mod ring; @@ -38,11 +38,12 @@ pub fn find_complement_point() -> Affine { } } -pub fn find_random_point>() -> P { +pub fn find_random_point>() -> P { let mut x: u8 = 0; loop { let p = P::from_random_bytes(&[x]); - if p.is_some() && !p.unwrap().is_zero(){// && !p.unwrap().is_in_correct_subgroup_assuming_on_curve() { + if p.is_some() && !p.unwrap().is_zero() { + // && !p.unwrap().is_in_correct_subgroup_assuming_on_curve() { return p.unwrap().clear_cofactor(); } x = x + 1; @@ -51,8 +52,8 @@ pub fn find_random_point>() -> P { // TODO: switch to better hash to curve when available pub fn hash_to_curve(message: &[u8]) -> A { - use blake2::Digest; use ark_std::rand::SeedableRng; + use blake2::Digest; let seed = blake2::Blake2s::digest(message); let rng = &mut rand::rngs::StdRng::from_seed(seed.into()); @@ -63,29 +64,35 @@ pub fn hash_to_curve(message: &[u8]) -> A { mod tests { use ark_bls12_381::Bls12_381; use ark_ec::CurveGroup; - use ark_ed_on_bls12_381_bandersnatch::{BandersnatchConfig, Fq, Fr, SWAffine, EdwardsAffine}; + use ark_ed_on_bls12_381_bandersnatch::{BandersnatchConfig, EdwardsAffine, Fq, Fr, SWAffine}; use ark_ff::MontFp; - use ark_std::{end_timer, start_timer, test_rng, UniformRand}; use ark_std::rand::Rng; + use ark_std::{end_timer, start_timer, test_rng, UniformRand}; use fflonk::pcs::kzg::KZG; use merlin::Transcript; use common::test_helpers::random_vec; - use common::gadgets::sw_cond_add::{SwCondAdd}; - use common::gadgets::te_cond_add::{TeCondAdd}; - use common::gadgets::cond_add::CondAdd; - use common::gadgets::ProverGadget; use crate::piop::FixedColumnsCommitted; use crate::ring::{Ring, RingBuilderKey}; use crate::ring_prover::RingProver; use crate::ring_verifier::RingVerifier; + use common::gadgets::cond_add::CondAdd; + use common::gadgets::sw_cond_add::SwCondAdd; + use common::gadgets::te_cond_add::TeCondAdd; + use common::gadgets::ProverGadget; use common::gadgets::VerifierGadget; use super::*; - fn _test_ring_proof, P: AffineRepr, CondAddT: CondAdd + ProverGadget>(domain_size: usize) - where CondAddT::CondAddValT : VerifierGadget + fn _test_ring_proof< + CS: PCS, + P: AffineRepr, + CondAddT: CondAdd + ProverGadget, + >( + domain_size: usize, + ) where + CondAddT::CondAddValT: VerifierGadget, { let rng = &mut test_rng(); @@ -102,19 +109,26 @@ mod tests { // PROOF generation let secret = Fr::rand(rng); // prover's secret scalar let result = piop_params.h.mul(secret) + pk; - let ring_prover = RingProver::init(prover_key, piop_params.clone(), k, Transcript::new(b"ring-vrf-test")); + let ring_prover = RingProver::init( + prover_key, + piop_params.clone(), + k, + Transcript::new(b"ring-vrf-test"), + ); let t_prove = start_timer!(|| "Prove"); let proof = ring_prover.prove::(secret); end_timer!(t_prove); - let ring_verifier = RingVerifier::init(verifier_key, piop_params, Transcript::new(b"ring-vrf-test")); + let ring_verifier = + RingVerifier::init(verifier_key, piop_params, Transcript::new(b"ring-vrf-test")); let t_verify = start_timer!(|| "Verify"); - let res = ring_verifier.verify_ring_proof::(proof, result.into_affine()); + let res = + ring_verifier.verify_ring_proof::(proof, result.into_affine()); end_timer!(t_verify); assert!(res); } - fn _test_lagrangian_commitment>() { + fn _test_lagrangian_commitment>() { let rng = &mut test_rng(); let domain_size = 2usize.pow(9); @@ -126,15 +140,21 @@ mod tests { let keyset_size: usize = rng.gen_range(0..max_keyset_size); let pks = random_vec::(keyset_size, rng); - let (_, verifier_key) = index::<_, KZG::, _>(&pcs_params, &piop_params, &pks); + let (_, verifier_key) = index::<_, KZG, _>(&pcs_params, &piop_params, &pks); let ring = Ring::<_, Bls12_381, _>::with_keys(&piop_params, &pks, &ring_builder_key); let fixed_columns_committed = FixedColumnsCommitted::from_ring(&ring); - assert_eq!(fixed_columns_committed, verifier_key.fixed_columns_committed); + assert_eq!( + fixed_columns_committed, + verifier_key.fixed_columns_committed + ); } - fn setup, P: AffineRepr>(rng: &mut R, domain_size: usize) -> (CS::Params, PiopParams) { + fn setup, P: AffineRepr>( + rng: &mut R, + domain_size: usize, + ) -> (CS::Params, PiopParams) { let setup_degree = 3 * domain_size; let pcs_params = CS::setup(setup_degree, rng); @@ -161,7 +181,15 @@ mod tests { let p = find_complement_point::(); assert!(p.is_on_curve()); assert!(!p.is_in_correct_subgroup_assuming_on_curve()); - assert_eq!(p, SWAffine::new_unchecked(MontFp!("0"), MontFp!("11982629110561008531870698410380659621661946968466267969586599013782997959645"))) + assert_eq!( + p, + SWAffine::new_unchecked( + MontFp!("0"), + MontFp!( + "11982629110561008531870698410380659621661946968466267969586599013782997959645" + ) + ) + ) } #[test] @@ -171,16 +199,24 @@ mod tests { #[test] fn test_ring_proof_kzg_te() { - _test_ring_proof::, EdwardsAffine, TeCondAdd>(2usize.pow(10)); + _test_ring_proof::, EdwardsAffine, TeCondAdd>( + 2usize.pow(10), + ); } #[test] fn test_ring_proof_id_sw() { - _test_ring_proof::>(2usize.pow(10)); + _test_ring_proof::>( + 2usize.pow(10), + ); } #[test] fn test_ring_proof_id_te() { - _test_ring_proof::>(2usize.pow(10)); + _test_ring_proof::< + fflonk::pcs::IdentityCommitment, + EdwardsAffine, + TeCondAdd, + >(2usize.pow(10)); } } diff --git a/ring/src/piop/mod.rs b/ring/src/piop/mod.rs index f5a7a56..f43c3f3 100644 --- a/ring/src/piop/mod.rs +++ b/ring/src/piop/mod.rs @@ -1,43 +1,47 @@ -use ark_ec::AffineRepr; use ark_ec::pairing::Pairing; +use ark_ec::AffineRepr; use ark_ff::PrimeField; use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; -use ark_std::{vec, vec::Vec}; use ark_std::marker::PhantomData; -use fflonk::pcs::{Commitment, PCS, PcsParams}; +use ark_std::{vec, vec::Vec}; use fflonk::pcs::kzg::commitment::KzgCommitment; -use fflonk::pcs::kzg::KZG; use fflonk::pcs::kzg::params::RawKzgVerifierKey; +use fflonk::pcs::kzg::KZG; +use fflonk::pcs::{Commitment, PcsParams, PCS}; -use common::{Column, ColumnsCommited, ColumnsEvaluated, FieldColumn}; use common::gadgets::cond_add::AffineColumn; +use common::{Column, ColumnsCommited, ColumnsEvaluated, FieldColumn}; pub(crate) use prover::PiopProver; pub(crate) use verifier::PiopVerifier; -use crate::PiopParams; use crate::ring::Ring; +use crate::PiopParams; +pub mod params; mod prover; mod verifier; -pub mod params; // Workaround while waiting for https://github.com/arkworks-rs/algebra/pull/837 // to be on [crates.io](https://crates.io/crates/ark-serialize) (allegedly ark-serialize 0.4.3 ) mod ark_serialize_837 { - use ark_serialize::{CanonicalDeserialize, CanonicalSerialize, Compress, Validate, Valid, SerializationError, Read}; + use ark_serialize::{ + CanonicalDeserialize, CanonicalSerialize, Compress, Read, SerializationError, Valid, + Validate, + }; #[derive(Clone, CanonicalSerialize)] #[repr(transparent)] pub struct ArrayWrap(pub [T; N]); - impl Valid for ArrayWrap - { + impl Valid for ArrayWrap { fn check(&self) -> Result<(), SerializationError> { self.0.check() } } - impl CanonicalDeserialize for ArrayWrap { + impl CanonicalDeserialize + for ArrayWrap + { fn deserialize_with_mode( mut reader: R, compress: Compress, @@ -45,7 +49,11 @@ mod ark_serialize_837 { ) -> Result { let mut array = arrayvec::ArrayVec::::new(); for _ in 0..N { - array.push(T::deserialize_with_mode(&mut reader, compress, Validate::No)?); + array.push(T::deserialize_with_mode( + &mut reader, + compress, + Validate::No, + )?); } if let ark_serialize::Validate::Yes = validate { T::batch_check(array.iter())? @@ -54,7 +62,9 @@ mod ark_serialize_837 { } } - impl core::ops::Deref for ArrayWrap { + impl core::ops::Deref + for ArrayWrap + { type Target = [T; N]; fn deref(&self) -> &Self::Target { @@ -125,7 +135,7 @@ impl ColumnsEvaluated for RingEvaluations { // Columns commitment to which the verifier knows (or trusts). #[derive(Clone, CanonicalSerialize, CanonicalDeserialize)] -pub struct FixedColumns> { +pub struct FixedColumns> { // Public keys of the ring participants in order, // followed by the powers-of-2 multiples of the second Pedersen base. // pk_1, ..., pk_n, H, 2H, 4H, ..., 2^sH @@ -156,7 +166,7 @@ impl> FixedColumnsCommitted { } impl FixedColumnsCommitted> { - pub fn from_ring>( + pub fn from_ring>( ring: &Ring, ) -> Self { let cx = KzgCommitment(ring.cx); @@ -169,19 +179,23 @@ impl FixedColumnsCommitted> { } } -impl> FixedColumns { +impl> FixedColumns { fn commit>(&self, ck: &CS::CK) -> FixedColumnsCommitted { let points = [ CS::commit(ck, self.points.xs.as_poly()), CS::commit(ck, self.points.ys.as_poly()), ]; let ring_selector = CS::commit(ck, self.ring_selector.as_poly()); - FixedColumnsCommitted { points, ring_selector, phantom: Default::default() } + FixedColumnsCommitted { + points, + ring_selector, + phantom: Default::default(), + } } } #[derive(CanonicalSerialize, CanonicalDeserialize)] -pub struct ProverKey, P: AffineRepr> { +pub struct ProverKey, P: AffineRepr> { pub(crate) pcs_ck: CS::CK, pub(crate) fixed_columns: FixedColumns, pub(crate) verifier_key: VerifierKey, // used in the Fiat-Shamir transform @@ -195,7 +209,7 @@ pub struct VerifierKey> { } impl VerifierKey> { - pub fn from_ring_and_kzg_vk>( + pub fn from_ring_and_kzg_vk>( ring: &Ring, kzg_vk: RawKzgVerifierKey, ) -> Self { @@ -217,8 +231,7 @@ impl VerifierKey> { } } - -pub fn index, P: AffineRepr,>( +pub fn index, P: AffineRepr>( pcs_params: &CS::Params, piop_params: &PiopParams, keys: &[P], @@ -231,7 +244,14 @@ pub fn index, P: AffineRepr,>( pcs_raw_vk: pcs_raw_vk.clone(), fixed_columns_committed: fixed_columns_committed.clone(), }; - let prover_key = ProverKey { pcs_ck, fixed_columns, verifier_key }; - let verifier_key = VerifierKey { pcs_raw_vk, fixed_columns_committed }; + let prover_key = ProverKey { + pcs_ck, + fixed_columns, + verifier_key, + }; + let verifier_key = VerifierKey { + pcs_raw_vk, + fixed_columns_committed, + }; (prover_key, verifier_key) } diff --git a/ring/src/piop/params.rs b/ring/src/piop/params.rs index 2cceeae..7cf2b8a 100644 --- a/ring/src/piop/params.rs +++ b/ring/src/piop/params.rs @@ -8,7 +8,7 @@ use common::gadgets::cond_add::AffineColumn; use crate::piop::FixedColumns; #[derive(Clone)] -pub struct PiopParams> { +pub struct PiopParams> { // Domain over which the piop is represented. pub(crate) domain: Domain, @@ -29,7 +29,7 @@ pub struct PiopParams> { pub(crate) padding_point: P, } -impl> PiopParams { +impl> PiopParams { pub fn setup(domain: Domain, h: P, seed: P) -> Self { let padding_point = crate::hash_to_curve::

(b"w3f/ring-proof/common/padding"); let scalar_bitlen = P::ScalarField::MODULUS_BIT_SIZE as usize; @@ -49,18 +49,17 @@ impl> PiopParams { let ring_selector = self.keyset_part_selector(); let ring_selector = self.domain.public_column(ring_selector); let points = self.points_column(&keys); - FixedColumns { points, ring_selector } + FixedColumns { + points, + ring_selector, + } } pub fn points_column(&self, keys: &[P]) -> AffineColumn { assert!(keys.len() <= self.keyset_part_size); let padding_len = self.keyset_part_size - keys.len(); let padding = vec![self.padding_point; padding_len]; - let points = [ - keys, - &padding, - &self.power_of_2_multiples_of_h(), - ].concat(); + let points = [keys, &padding, &self.power_of_2_multiples_of_h()].concat(); assert_eq!(points.len(), self.domain.capacity - 1); AffineColumn::public_column(points, &self.domain) } @@ -85,15 +84,16 @@ impl> PiopParams { pub fn keyset_part_selector(&self) -> Vec { [ vec![F::one(); self.keyset_part_size], - vec![F::zero(); self.scalar_bitlen] - ].concat() + vec![F::zero(); self.scalar_bitlen], + ] + .concat() } } #[cfg(test)] mod tests { - use ark_ed_on_bls12_381_bandersnatch::{Fq, Fr, SWAffine, EdwardsAffine}; use ark_ec::AffineRepr; + use ark_ed_on_bls12_381_bandersnatch::{EdwardsAffine, Fq, Fr, SWAffine}; use ark_std::{test_rng, UniformRand}; use common::domain::Domain; @@ -101,7 +101,7 @@ mod tests { use crate::piop::params::PiopParams; - fn _test_powers_of_h>() { + fn _test_powers_of_h>() { let rng = &mut test_rng(); let h = P::rand(rng); let seed = P::rand(rng); diff --git a/ring/src/piop/prover.rs b/ring/src/piop/prover.rs index b1fb487..ab14a7a 100644 --- a/ring/src/piop/prover.rs +++ b/ring/src/piop/prover.rs @@ -1,27 +1,27 @@ -use ark_ec::{AffineRepr}; +use ark_ec::AffineRepr; use ark_ff::PrimeField; -use ark_poly::Evaluations; use ark_poly::univariate::DensePolynomial; +use ark_poly::Evaluations; use ark_std::marker::PhantomData; use ark_std::{vec, vec::Vec}; use fflonk::pcs::Commitment; -use common::{Column, FieldColumn}; use common::domain::Domain; use common::gadgets::booleanity::{BitColumn, Booleanity}; +use common::gadgets::cond_add::{AffineColumn, CondAdd}; use common::gadgets::fixed_cells::FixedCells; use common::gadgets::inner_prod::InnerProd; use common::gadgets::ProverGadget; -use common::gadgets::cond_add::{AffineColumn, CondAdd}; use common::piop::ProverPiop; +use common::{Column, FieldColumn}; -use crate::piop::{RingCommitments, RingEvaluations}; -use crate::piop::FixedColumns; use crate::piop::params::PiopParams; +use crate::piop::FixedColumns; +use crate::piop::{RingCommitments, RingEvaluations}; // The 'table': columns representing the execution trace of the computation // and the constraints -- polynomials that vanish on every 2 consecutive rows. -pub struct PiopProver, CondAddT: CondAdd> { +pub struct PiopProver, CondAddT: CondAdd> { domain: Domain, // Fixed (public input) columns: points: AffineColumn, @@ -37,14 +37,20 @@ pub struct PiopProver, CondAddT: CondA cond_add_acc_y: FixedCells, } -impl, CondAddT: CondAdd> PiopProver +impl, CondAddT: CondAdd> + PiopProver { - pub fn build(params: &PiopParams, - fixed_columns: FixedColumns, - prover_index_in_keys: usize, - secret: P::ScalarField) -> Self { + pub fn build( + params: &PiopParams, + fixed_columns: FixedColumns, + prover_index_in_keys: usize, + secret: P::ScalarField, + ) -> Self { let domain = params.domain.clone(); - let FixedColumns { points, ring_selector } = fixed_columns; + let FixedColumns { + points, + ring_selector, + } = fixed_columns; let bits = Self::bits_column(¶ms, prover_index_in_keys, secret); let inner_prod = InnerProd::init(ring_selector.clone(), bits.col.clone(), &domain); let cond_add = CondAddT::init(bits.clone(), points.clone(), params.seed, &domain); @@ -67,36 +73,39 @@ impl, CondAddT: CondAdd> PiopPro } } - fn bits_column(params: &PiopParams, index_in_keys: usize, secret: P::ScalarField) -> BitColumn { + fn bits_column( + params: &PiopParams, + index_in_keys: usize, + secret: P::ScalarField, + ) -> BitColumn { let mut keyset_part = vec![false; params.keyset_part_size]; keyset_part[index_in_keys] = true; let scalar_part = params.scalar_part(secret); - let bits = [ - keyset_part, - scalar_part - ].concat(); + let bits = [keyset_part, scalar_part].concat(); assert_eq!(bits.len(), params.domain.capacity - 1); BitColumn::init(bits, ¶ms.domain) } } impl ProverPiop for PiopProver - where - F: PrimeField, - C: Commitment, - P: AffineRepr, +where + F: PrimeField, + C: Commitment, + P: AffineRepr, CondAddT: CondAdd + ProverGadget, - { type Commitments = RingCommitments; type Evaluations = RingEvaluations; type Instance = P; - fn committed_columns) -> C>(&self, commit: Fun) -> Self::Commitments { + fn committed_columns) -> C>( + &self, + commit: Fun, + ) -> Self::Commitments { let bits = commit(self.bits.as_poly()); let cond_add_acc = super::ArrayWrap([ commit(self.cond_add.get_acc().xs.as_poly()), - commit(self.cond_add.get_acc().ys.as_poly()) + commit(self.cond_add.get_acc().ys.as_poly()), ]); let inn_prod_acc = commit(self.inner_prod.acc.as_poly()); Self::Commitments { @@ -122,10 +131,8 @@ impl ProverPiop for PiopProver } fn columns_evaluated(&self, zeta: &F) -> Self::Evaluations { - let points = super::ArrayWrap([ - self.points.xs.evaluate(zeta), - self.points.ys.evaluate(zeta), - ]); + let points = + super::ArrayWrap([self.points.xs.evaluate(zeta), self.points.ys.evaluate(zeta)]); let ring_selector = self.ring_selector.evaluate(zeta); let bits = self.bits.evaluate(zeta); let inn_prod_acc = self.inner_prod.acc.evaluate(zeta); @@ -150,7 +157,8 @@ impl ProverPiop for PiopProver self.cond_add_acc_x.constraints(), self.cond_add_acc_y.constraints(), self.inner_prod_acc.constraints(), - ].concat() + ] + .concat() } fn constraints_lin(&self, zeta: &F) -> Vec> { @@ -161,7 +169,8 @@ impl ProverPiop for PiopProver self.cond_add_acc_x.constraints_linearized(zeta), self.cond_add_acc_y.constraints_linearized(zeta), self.inner_prod_acc.constraints_linearized(zeta), - ].concat() + ] + .concat() } fn domain(&self) -> &Domain { diff --git a/ring/src/piop/verifier.rs b/ring/src/piop/verifier.rs index f41c3c0..fc746e4 100644 --- a/ring/src/piop/verifier.rs +++ b/ring/src/piop/verifier.rs @@ -4,17 +4,16 @@ use fflonk::pcs::Commitment; use common::domain::EvaluatedDomain; use common::gadgets::booleanity::BooleanityValues; +use common::gadgets::cond_add::CondAddValues; use common::gadgets::fixed_cells::FixedCellsValues; use common::gadgets::inner_prod::InnerProdValues; -use common::gadgets::cond_add::CondAddValues; use common::gadgets::VerifierGadget; use common::piop::VerifierPiop; use crate::piop::{FixedColumnsCommitted, RingCommitments}; use crate::RingEvaluations; -pub struct PiopVerifier, CondAddValuesT: CondAddValues - > { +pub struct PiopVerifier, CondAddValuesT: CondAddValues> { domain_evals: EvaluatedDomain, fixed_columns_committed: FixedColumnsCommitted, witness_columns_committed: RingCommitments, @@ -27,7 +26,9 @@ pub struct PiopVerifier, CondAddValuesT: CondAdd cond_add_acc_y: FixedCellsValues, } -impl, CondAddValuesT: CondAddValues> PiopVerifier { +impl, CondAddValuesT: CondAddValues> + PiopVerifier +{ pub fn init( domain_evals: EvaluatedDomain, fixed_columns_committed: FixedColumnsCommitted, @@ -36,11 +37,17 @@ impl, CondAddValuesT: CondAddValues> PiopVeri init: (F, F), result: (F, F), ) -> Self { - let cond_add = CondAddValuesT::init ( + let cond_add = CondAddValuesT::init( all_columns_evaluated.bits, - (all_columns_evaluated.points[0], all_columns_evaluated.points[1]), + ( + all_columns_evaluated.points[0], + all_columns_evaluated.points[1], + ), domain_evals.not_last_row, - (all_columns_evaluated.cond_add_acc[0], all_columns_evaluated.cond_add_acc[1]), + ( + all_columns_evaluated.cond_add_acc[0], + all_columns_evaluated.cond_add_acc[1], + ), ); let inner_prod = InnerProdValues { @@ -92,7 +99,9 @@ impl, CondAddValuesT: CondAddValues> PiopVeri } } -impl, CondAddValuesT: CondAddValues + VerifierGadget> VerifierPiop for PiopVerifier { +impl, CondAddValuesT: CondAddValues + VerifierGadget> + VerifierPiop for PiopVerifier +{ const N_CONSTRAINTS: usize = 7; const N_COLUMNS: usize = 7; @@ -108,11 +117,15 @@ impl, CondAddValuesT: CondAddValues + Verifie self.cond_add_acc_x.evaluate_constraints_main(), self.cond_add_acc_y.evaluate_constraints_main(), self.inner_prod_acc.evaluate_constraints_main(), - ].concat() + ] + .concat() } fn constraint_polynomials_linearized_commitments(&self) -> Vec { - let inner_prod_acc = self.witness_columns_committed.inn_prod_acc.mul(self.inner_prod.not_last); + let inner_prod_acc = self + .witness_columns_committed + .inn_prod_acc + .mul(self.inner_prod.not_last); let acc_x = &self.witness_columns_committed.cond_add_acc[0]; let acc_y = &self.witness_columns_committed.cond_add_acc[1]; @@ -122,11 +135,7 @@ impl, CondAddValuesT: CondAddValues + Verifie let (c_acc_x, c_acc_y) = self.cond_add.acc_coeffs_2(); let c2_lin = acc_x.mul(c_acc_x) + acc_y.mul(c_acc_y); - vec![ - inner_prod_acc, - c1_lin, - c2_lin, - ] + vec![inner_prod_acc, c1_lin, c2_lin] } fn domain_evaluated(&self) -> &EvaluatedDomain { diff --git a/ring/src/ring.rs b/ring/src/ring.rs index 5236abe..bd339bd 100644 --- a/ring/src/ring.rs +++ b/ring/src/ring.rs @@ -1,5 +1,5 @@ -use ark_ec::{AffineRepr, CurveGroup, VariableBaseMSM}; use ark_ec::pairing::Pairing; +use ark_ec::{AffineRepr, CurveGroup, VariableBaseMSM}; use ark_ff::PrimeField; use ark_poly::EvaluationDomain; use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; @@ -36,7 +36,11 @@ const IDLE_ROWS: usize = ZK_ROWS + 1; // `VrfCurveConfig` -- inner curve, the curve used by the VRF, in SW form. We instantiate it with Bandersnatch. // `F` shared scalar field of the outer and the base field of the inner curves. #[derive(Clone, PartialEq, Eq, CanonicalSerialize, CanonicalDeserialize)] -pub struct Ring, VrfAffineT: AffineRepr> { +pub struct Ring< + F: PrimeField, + KzgCurve: Pairing, + VrfAffineT: AffineRepr, +> { // KZG commitments to the coordinates of the vector described above pub cx: KzgCurve::G1Affine, pub cy: KzgCurve::G1Affine, @@ -50,13 +54,21 @@ pub struct Ring, VrfAffineT: Aff pub padding_point: VrfAffineT, } -impl, VrfAffineT: AffineRepr> fmt::Debug for Ring { +impl, VrfAffineT: AffineRepr> + fmt::Debug for Ring +{ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Ring(curr_keys={}, max_keys{})", self.curr_keys, self.max_keys) + write!( + f, + "Ring(curr_keys={}, max_keys{})", + self.curr_keys, self.max_keys + ) } } -impl, VrfAffineT: AffineRepr> Ring { +impl, VrfAffineT: AffineRepr> + Ring +{ // Builds the commitment to the vector // `padding, ..., padding, H, 2H, ..., 2^(s-1)H, 0, 0, 0, 0`. // We compute it as a sum of commitments of 2 vectors: @@ -77,7 +89,8 @@ impl, VrfAffineT: AffineRepr, Vec) = powers_of_h.iter() + let (mut xs, mut ys): (Vec, Vec) = powers_of_h + .iter() .map(|p| p.xy().unwrap()) .map(|(&x, &y)| (x - padding_x, y - padding_y)) .unzip(); @@ -115,7 +128,8 @@ impl, VrfAffineT: AffineRepr, Vec) = keys.iter() + let (xs, ys): (Vec, Vec) = keys + .iter() .map(|p| p.xy().unwrap()) .map(|(&x, &y)| (x - padding_x, y - padding_y)) .unzip(); @@ -151,7 +165,8 @@ impl, VrfAffineT: AffineRepr, Vec) = keys.iter() + let (xs, ys): (Vec, Vec) = keys + .iter() .chain(&powers_of_h) .map(|p| p.xy().unwrap()) .map(|(&x, &y)| (x - padding_x, y - padding_y)) @@ -164,11 +179,14 @@ impl, VrfAffineT: AffineRepr(); + let selector_inv = srs.lis_in_g1[piop_params.keyset_part_size..] + .iter() + .sum::(); let selector = srs.g1 - selector_inv; let (cx, cy, selector) = { @@ -197,7 +215,8 @@ impl, VrfAffineT: AffineRepr Self { - let max_keys = domain_size - (VrfAffineT::ScalarField::MODULUS_BIT_SIZE as usize + IDLE_ROWS); + let max_keys = + domain_size - (VrfAffineT::ScalarField::MODULUS_BIT_SIZE as usize + IDLE_ROWS); Self { cx, cy, @@ -210,14 +229,14 @@ impl, VrfAffineT: AffineRepr> { +pub struct RingBuilderKey> { // Lagrangian SRS pub lis_in_g1: Vec, // generator used in the SRS pub g1: KzgCurve::G1, } -impl> RingBuilderKey { +impl> RingBuilderKey { pub fn from_srs(srs: &URS, domain_size: usize) -> Self { let g1 = srs.powers_in_g1[0].into_group(); let ck = srs.ck_with_lagrangian(domain_size); @@ -229,24 +248,24 @@ impl> RingBuilderKey = Ring; - fn _test_ring_mgmt>() { + fn _test_ring_mgmt>() { let rng = &mut test_rng(); let domain_size = 1 << 9; @@ -286,7 +305,7 @@ mod tests { _test_ring_mgmt::(); } - fn _test_empty_rings>() { + fn _test_empty_rings>() { let rng = &mut test_rng(); let domain_size = 1 << 9; @@ -304,7 +323,6 @@ mod tests { let ring = TestRing::

::empty(&piop_params, srs, ring_builder_key.g1); let same_ring = TestRing::with_keys(&piop_params, &[], &ring_builder_key); assert_eq!(ring, same_ring); - } #[test] @@ -317,9 +335,13 @@ mod tests { _test_empty_rings::(); } - - fn get_monomial_commitment(pcs_params: &URS, piop_params: &PiopParams, keys: &[SWAffine]) -> (G1Affine, G1Affine) { - let (_, verifier_key) = crate::piop::index::<_, KZG::, _>(pcs_params, piop_params, keys); + fn get_monomial_commitment( + pcs_params: &URS, + piop_params: &PiopParams, + keys: &[SWAffine], + ) -> (G1Affine, G1Affine) { + let (_, verifier_key) = + crate::piop::index::<_, KZG, _>(pcs_params, piop_params, keys); let [monimial_cx, monimial_cy] = verifier_key.fixed_columns_committed.points; (monimial_cx.0, monimial_cy.0) } diff --git a/ring/src/ring_prover.rs b/ring/src/ring_prover.rs index cddda60..fb663e9 100644 --- a/ring/src/ring_prover.rs +++ b/ring/src/ring_prover.rs @@ -1,30 +1,34 @@ -use ark_ec::{AffineRepr}; +use ark_ec::AffineRepr; use ark_ff::PrimeField; use fflonk::pcs::PCS; -use common::prover::PlonkProver; -use common::gadgets::cond_add::{CondAdd}; +use common::gadgets::cond_add::CondAdd; use common::gadgets::ProverGadget; +use common::prover::PlonkProver; -use crate::piop::{FixedColumns, PiopProver, ProverKey}; use crate::piop::params::PiopParams; +use crate::piop::{FixedColumns, PiopProver, ProverKey}; use crate::RingProof; -pub struct RingProver, P: AffineRepr> { +pub struct RingProver, P: AffineRepr> { piop_params: PiopParams, fixed_columns: FixedColumns, k: usize, plonk_prover: PlonkProver, } - -impl, P: AffineRepr,> RingProver { - pub fn init(prover_key: ProverKey, - piop_params: PiopParams, - k: usize, - empty_transcript: merlin::Transcript, +impl, P: AffineRepr> RingProver { + pub fn init( + prover_key: ProverKey, + piop_params: PiopParams, + k: usize, + empty_transcript: merlin::Transcript, ) -> Self { - let ProverKey { pcs_ck, fixed_columns, verifier_key } = prover_key; + let ProverKey { + pcs_ck, + fixed_columns, + verifier_key, + } = prover_key; let plonk_prover = PlonkProver::init(pcs_ck, verifier_key, empty_transcript); @@ -36,8 +40,12 @@ impl, P: AffineRepr,> RingProver + ProverGadget>(&self, t: P::ScalarField) -> RingProof { - let piop : PiopProver:: = PiopProver::build(&self.piop_params, self.fixed_columns.clone(), self.k, t); + pub fn prove + ProverGadget>( + &self, + t: P::ScalarField, + ) -> RingProof { + let piop: PiopProver = + PiopProver::build(&self.piop_params, self.fixed_columns.clone(), self.k, t); self.plonk_prover.prove(piop) } @@ -45,4 +53,3 @@ impl, P: AffineRepr,> RingProver, P: AffineRepr> { +pub struct RingVerifier, P: AffineRepr> { piop_params: PiopParams, fixed_columns_committed: FixedColumnsCommitted, plonk_verifier: PlonkVerifier, } -impl, P: AffineRepr> RingVerifier { - pub fn init(verifier_key: VerifierKey, - piop_params: PiopParams, - empty_transcript: merlin::Transcript, +impl, P: AffineRepr> RingVerifier { + pub fn init( + verifier_key: VerifierKey, + piop_params: PiopParams, + empty_transcript: merlin::Transcript, ) -> Self { let pcs_vk = verifier_key.pcs_raw_vk.prepare(); let plonk_verifier = PlonkVerifier::init(pcs_vk, &verifier_key, empty_transcript); @@ -33,7 +34,11 @@ impl, P: AffineRepr> RingVerifier + VerifierGadget>(&self, proof: RingProof, result: P) -> bool { + pub fn verify_ring_proof + VerifierGadget>( + &self, + proof: RingProof, + result: P, + ) -> bool { let (challenges, mut rng) = self.plonk_verifier.restore_challenges( &result, &proof, @@ -43,7 +48,11 @@ impl, P: AffineRepr> RingVerifier>::C, CondAddValuesT> = PiopVerifier::init( domain_eval, @@ -51,14 +60,17 @@ impl, P: AffineRepr> RingVerifier &PiopParams { &self.piop_params } } -