From 407acb91acf5318ccbc1970c02b738afe7057d5c Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Thu, 26 Oct 2023 10:34:58 +0200 Subject: [PATCH 01/20] Add the trait bounds --- poly-commit/src/lib.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/poly-commit/src/lib.rs b/poly-commit/src/lib.rs index 8413a1af..8413277f 100644 --- a/poly-commit/src/lib.rs +++ b/poly-commit/src/lib.rs @@ -156,6 +156,8 @@ pub trait PolynomialCommitment, S: Cryptographic type VerifierKey: PCVerifierKey; /// The commitment to a polynomial. type Commitment: PCCommitment + Default; + /// The state of committer + type CommitterState: Default + CanonicalSerialize + CanonicalDeserialize; /// The commitment randomness. type Randomness: PCRandomness; /// The evaluation proof for a single point. From cb65aef6a0b58fdd7134d0f3fbad6cc0495da648 Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Wed, 1 Nov 2023 14:21:48 +0100 Subject: [PATCH 02/20] Add `CommitmentState` --- README.md | 5 ++- poly-commit/src/data_structures.rs | 3 ++ poly-commit/src/ipa_pc/mod.rs | 8 +++- poly-commit/src/kzg10/data_structures.rs | 5 +++ poly-commit/src/lib.rs | 37 ++++++++++++++----- poly-commit/src/marlin/marlin_pc/mod.rs | 14 ++++++- poly-commit/src/marlin/marlin_pst13_pc/mod.rs | 12 +++++- poly-commit/src/marlin/mod.rs | 1 + poly-commit/src/sonic_pc/mod.rs | 13 ++++++- 9 files changed, 81 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index bdedd6bb..70661333 100644 --- a/README.md +++ b/README.md @@ -128,13 +128,13 @@ let (ck, vk) = PCS::trim(&pp, degree, 2, Some(&[degree])).unwrap(); // 3. PolynomialCommitment::commit // The prover commits to the polynomial using their committer key `ck`. -let (comms, rands) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); +let (comms, states, rands) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); let challenge_generator: ChallengeGenerator<::ScalarField, Sponge_Bls12_377> = ChallengeGenerator::new_univariate(&mut test_sponge); // 4a. PolynomialCommitment::open // Opening proof at a single point. -let proof_single = PCS::open(&ck, [&labeled_poly], &comms, &point_1, &mut (challenge_generator.clone()), &rands, None).unwrap(); +let proof_single = PCS::open(&ck, [&labeled_poly], &comms, &point_1, &mut (challenge_generator.clone()), &states, &rands, None).unwrap(); // 5a. PolynomialCommitment::check // Verifying the proof at a single point, given the commitment, the point, the claimed evaluation, and the proof. @@ -156,6 +156,7 @@ let proof_batched = PCS::batch_open( &comms, &query_set, &mut (challenge_generator.clone()), + &states, &rands, Some(rng), ).unwrap(); diff --git a/poly-commit/src/data_structures.rs b/poly-commit/src/data_structures.rs index 4a5eec21..9735d002 100644 --- a/poly-commit/src/data_structures.rs +++ b/poly-commit/src/data_structures.rs @@ -63,6 +63,9 @@ pub trait PCCommitment: Clone + CanonicalSerialize + CanonicalDeserialize { fn has_degree_bound(&self) -> bool; } +/// Defines the auxiliary data of the commitment +pub trait PCCommitmentState: Clone + Default + CanonicalSerialize + CanonicalDeserialize {} + /// Defines the minimal interface of prepared commitments for any polynomial /// commitment scheme. pub trait PCPreparedCommitment: Clone { diff --git a/poly-commit/src/ipa_pc/mod.rs b/poly-commit/src/ipa_pc/mod.rs index 25752d78..800ad480 100644 --- a/poly-commit/src/ipa_pc/mod.rs +++ b/poly-commit/src/ipa_pc/mod.rs @@ -1,3 +1,4 @@ +use crate::kzg10::CommitmentState; use crate::{BTreeMap, BTreeSet, String, ToString, Vec, CHALLENGE_SIZE}; use crate::{BatchLCProof, DenseUVPolynomial, Error, Evaluations, QuerySet}; use crate::{LabeledCommitment, LabeledPolynomial, LinearCombination}; @@ -347,6 +348,7 @@ where type CommitterKey = CommitterKey; type VerifierKey = VerifierKey; type Commitment = Commitment; + type CommitmentState = CommitmentState; type Randomness = Randomness; type Proof = Proof; type BatchProof = Vec; @@ -418,6 +420,7 @@ where ) -> Result< ( Vec>, + Vec, Vec, ), Self::Error, @@ -480,7 +483,7 @@ where } end_timer!(commit_time); - Ok((comms, rands)) + Ok((comms, vec![CommitmentState {}; rands.len()], rands)) } fn open<'a>( @@ -489,6 +492,7 @@ where commitments: impl IntoIterator>, point: &'a P::Point, opening_challenges: &mut ChallengeGenerator, + _states: impl IntoIterator, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result @@ -877,6 +881,7 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, + _states: impl IntoIterator, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> @@ -972,6 +977,7 @@ where lc_commitments.iter(), &query_set, opening_challenges, + &vec![CommitmentState {}; lc_randomness.len()], lc_randomness.iter(), rng, )?; diff --git a/poly-commit/src/kzg10/data_structures.rs b/poly-commit/src/kzg10/data_structures.rs index 60626e70..d44efecb 100644 --- a/poly-commit/src/kzg10/data_structures.rs +++ b/poly-commit/src/kzg10/data_structures.rs @@ -329,6 +329,11 @@ pub struct Commitment( pub E::G1Affine, ); +/// The auxiliary data for KZG commitment is empty. +#[derive(Clone, Default, CanonicalSerialize, CanonicalDeserialize)] +pub struct CommitmentState {} +impl PCCommitmentState for CommitmentState {} + impl PCCommitment for Commitment { #[inline] fn empty() -> Self { diff --git a/poly-commit/src/lib.rs b/poly-commit/src/lib.rs index 8413277f..499802d7 100644 --- a/poly-commit/src/lib.rs +++ b/poly-commit/src/lib.rs @@ -157,7 +157,7 @@ pub trait PolynomialCommitment, S: Cryptographic /// The commitment to a polynomial. type Commitment: PCCommitment + Default; /// The state of committer - type CommitterState: Default + CanonicalSerialize + CanonicalDeserialize; + type CommitmentState: PCCommitmentState; /// The commitment randomness. type Randomness: PCRandomness; /// The evaluation proof for a single point. @@ -205,6 +205,7 @@ pub trait PolynomialCommitment, S: Cryptographic ) -> Result< ( Vec>, + Vec, Vec, ), Self::Error, @@ -219,12 +220,14 @@ pub trait PolynomialCommitment, S: Cryptographic commitments: impl IntoIterator>, point: &'a P::Point, challenge_generator: &mut ChallengeGenerator, + states: impl IntoIterator, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result where P: 'a, Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a; /// check but with individual challenges @@ -255,12 +258,14 @@ pub trait PolynomialCommitment, S: Cryptographic commitments: impl IntoIterator>, query_set: &QuerySet, challenge_generator: &mut ChallengeGenerator, + states: impl IntoIterator, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result where P: 'a, Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, { // The default implementation achieves proceeds by rearranging the queries in @@ -268,11 +273,12 @@ pub trait PolynomialCommitment, S: Cryptographic // the same point, then opening their commitments simultaneously with a // single call to `open` (per point) let rng = &mut crate::optional_rng::OptionalRng(rng); - let poly_rand_comm: BTreeMap<_, _> = labeled_polynomials + let poly_rand_st_comm: BTreeMap<_, _> = labeled_polynomials .into_iter() + .zip(states) .zip(rands) .zip(commitments.into_iter()) - .map(|((poly, r), comm)| (poly.label(), (poly, r, comm))) + .map(|(((poly, st), r), comm)| (poly.label(), (poly, r, st, comm))) .collect(); let open_time = start_timer!(|| format!( @@ -301,19 +307,23 @@ pub trait PolynomialCommitment, S: Cryptographic for (_point_label, (point, labels)) in query_to_labels_map.into_iter() { let mut query_polys: Vec<&'a LabeledPolynomial<_, _>> = Vec::new(); let mut query_rands: Vec<&'a Self::Randomness> = Vec::new(); + let mut query_states: Vec<&'a Self::CommitmentState> = Vec::new(); let mut query_comms: Vec<&'a LabeledCommitment> = Vec::new(); // Constructing matching vectors with the polynomial, commitment // randomness and actual commitment for each polynomial being // queried at `point` for label in labels { - let (polynomial, rand, comm) = - poly_rand_comm.get(label).ok_or(Error::MissingPolynomial { - label: label.to_string(), - })?; + let (polynomial, rand, state, comm) = + poly_rand_st_comm + .get(label) + .ok_or(Error::MissingPolynomial { + label: label.to_string(), + })?; query_polys.push(polynomial); query_rands.push(rand); + query_states.push(state); query_comms.push(comm); } @@ -327,6 +337,7 @@ pub trait PolynomialCommitment, S: Cryptographic query_comms, &point, challenge_generator, + query_states, query_rands, Some(rng), )?; @@ -440,11 +451,13 @@ pub trait PolynomialCommitment, S: Cryptographic commitments: impl IntoIterator>, query_set: &QuerySet, challenge_generator: &mut ChallengeGenerator, + states: impl IntoIterator, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> where Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, P: 'a, { @@ -466,6 +479,7 @@ pub trait PolynomialCommitment, S: Cryptographic commitments, &poly_query_set, challenge_generator, + states, rands, rng, )?; @@ -717,7 +731,7 @@ pub mod tests { )?; println!("Trimmed"); - let (comms, rands) = PC::commit(&ck, &polynomials, Some(rng))?; + let (comms, states, rands) = PC::commit(&ck, &polynomials, Some(rng))?; let mut query_set = QuerySet::new(); let mut values = Evaluations::new(); @@ -735,6 +749,7 @@ pub mod tests { &comms, &query_set, &mut (challenge_gen.clone()), + &states, &rands, Some(rng), )?; @@ -850,7 +865,7 @@ pub mod tests { )?; println!("Trimmed"); - let (comms, rands) = PC::commit(&ck, &polynomials, Some(rng))?; + let (comms, states, rands) = PC::commit(&ck, &polynomials, Some(rng))?; // Construct query set let mut query_set = QuerySet::new(); @@ -871,6 +886,7 @@ pub mod tests { &comms, &query_set, &mut (challenge_gen.clone()), + &states, &rands, Some(rng), )?; @@ -998,7 +1014,7 @@ pub mod tests { )?; println!("Trimmed"); - let (comms, rands) = PC::commit(&ck, &polynomials, Some(rng))?; + let (comms, states, rands) = PC::commit(&ck, &polynomials, Some(rng))?; // Let's construct our equations let mut linear_combinations = Vec::new(); @@ -1050,6 +1066,7 @@ pub mod tests { &comms, &query_set, &mut (challenge_gen.clone()), + &states, &rands, Some(rng), )?; diff --git a/poly-commit/src/marlin/marlin_pc/mod.rs b/poly-commit/src/marlin/marlin_pc/mod.rs index 39c4e362..c10c8680 100644 --- a/poly-commit/src/marlin/marlin_pc/mod.rs +++ b/poly-commit/src/marlin/marlin_pc/mod.rs @@ -1,3 +1,4 @@ +use crate::kzg10::CommitmentState; use crate::{kzg10, marlin::Marlin, PCCommitterKey, CHALLENGE_SIZE}; use crate::{BTreeMap, BTreeSet, ToString, Vec}; use crate::{BatchLCProof, Error, Evaluations, QuerySet}; @@ -66,6 +67,7 @@ where type CommitterKey = CommitterKey; type VerifierKey = VerifierKey; type Commitment = Commitment; + type CommitmentState = CommitmentState; type Randomness = Randomness; type Proof = kzg10::Proof; type BatchProof = Vec; @@ -180,6 +182,7 @@ where ) -> Result< ( Vec>, + Vec, Vec, ), Self::Error, @@ -242,7 +245,11 @@ where end_timer!(commit_time); } end_timer!(commit_time); - Ok((commitments, randomness)) + Ok(( + commitments, + vec![CommitmentState {}; randomness.len()], + randomness, + )) } /// On input a polynomial `p` and a point `point`, outputs a proof for the same. @@ -252,6 +259,7 @@ where _commitments: impl IntoIterator>, point: &'a P::Point, opening_challenges: &mut ChallengeGenerator, + _states: impl IntoIterator, rands: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result @@ -408,6 +416,7 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, + _states: impl IntoIterator, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> @@ -463,12 +472,14 @@ where commitments: impl IntoIterator>>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, + _states: impl IntoIterator, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result>, Error> where P: 'a, Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, { let rng = &mut crate::optional_rng::OptionalRng(rng); @@ -518,6 +529,7 @@ where query_comms, point, opening_challenges, + &vec![CommitmentState {}; query_rands.len()], query_rands, Some(rng), )?; diff --git a/poly-commit/src/marlin/marlin_pst13_pc/mod.rs b/poly-commit/src/marlin/marlin_pst13_pc/mod.rs index ac47c2a7..2ab5d543 100644 --- a/poly-commit/src/marlin/marlin_pst13_pc/mod.rs +++ b/poly-commit/src/marlin/marlin_pst13_pc/mod.rs @@ -1,5 +1,5 @@ use crate::{ - kzg10, + kzg10::{self, CommitmentState}, marlin::{marlin_pc, Marlin}, CHALLENGE_SIZE, }; @@ -151,6 +151,7 @@ where type CommitterKey = CommitterKey; type VerifierKey = VerifierKey; type Commitment = marlin_pc::Commitment; + type CommitmentState = CommitmentState; type Randomness = Randomness; type Proof = Proof; type BatchProof = Vec; @@ -343,6 +344,7 @@ where ) -> Result< ( Vec>, + Vec, Vec, ), Self::Error, @@ -431,7 +433,11 @@ where end_timer!(commit_time); } end_timer!(commit_time); - Ok((commitments, randomness)) + Ok(( + commitments, + vec![CommitmentState {}; randomness.len()], + randomness, + )) } /// On input a polynomial `p` and a point `point`, outputs a proof for the same. @@ -441,6 +447,7 @@ where _commitments: impl IntoIterator>, point: &P::Point, opening_challenges: &mut ChallengeGenerator, + _states: impl IntoIterator, rands: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result @@ -661,6 +668,7 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, + _states: impl IntoIterator, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> diff --git a/poly-commit/src/marlin/mod.rs b/poly-commit/src/marlin/mod.rs index 4bd4fe27..4f9e424e 100644 --- a/poly-commit/src/marlin/mod.rs +++ b/poly-commit/src/marlin/mod.rs @@ -309,6 +309,7 @@ where lc_commitments.iter(), &query_set, opening_challenges, + &vec![PC::CommitmentState::default(); lc_randomness.len()], lc_randomness.iter(), rng, )?; diff --git a/poly-commit/src/sonic_pc/mod.rs b/poly-commit/src/sonic_pc/mod.rs index b989b323..a00fb5f3 100644 --- a/poly-commit/src/sonic_pc/mod.rs +++ b/poly-commit/src/sonic_pc/mod.rs @@ -1,3 +1,4 @@ +use crate::kzg10::CommitmentState; use crate::{kzg10, PCCommitterKey, CHALLENGE_SIZE}; use crate::{BTreeMap, BTreeSet, String, ToString, Vec}; use crate::{BatchLCProof, DenseUVPolynomial, Error, Evaluations, QuerySet}; @@ -146,6 +147,7 @@ where type CommitterKey = CommitterKey; type VerifierKey = VerifierKey; type Commitment = Commitment; + type CommitmentState = CommitmentState; type Randomness = Randomness; type Proof = kzg10::Proof; type BatchProof = Vec; @@ -281,6 +283,7 @@ where ) -> Result< ( Vec>, + Vec, Vec, ), Self::Error, @@ -337,7 +340,11 @@ where } end_timer!(commit_time); - Ok((labeled_comms, randomness)) + Ok(( + labeled_comms, + vec![CommitmentState {}; randomness.len()], + randomness, + )) } fn open<'a>( @@ -346,6 +353,7 @@ where _commitments: impl IntoIterator>, point: &'a P::Point, opening_challenges: &mut ChallengeGenerator, + _states: impl IntoIterator, rands: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result @@ -503,11 +511,13 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, + _states: impl IntoIterator, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> where Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, P: 'a, { @@ -582,6 +592,7 @@ where lc_commitments.iter(), &query_set, opening_challenges, + &vec![CommitmentState {}; lc_randomness.len()], lc_randomness.iter(), rng, )?; From 85c8915e40fda979ef3af3fdddf77956230cbbdd Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Wed, 1 Nov 2023 14:41:37 +0100 Subject: [PATCH 03/20] Update benches for the new type --- bench-templates/src/lib.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/bench-templates/src/lib.rs b/bench-templates/src/lib.rs index 1594ee7c..a9ca68ea 100644 --- a/bench-templates/src/lib.rs +++ b/bench-templates/src/lib.rs @@ -69,7 +69,7 @@ pub fn commit< LabeledPolynomial::new("test".to_string(), rand_poly(num_vars, rng), None, None); let start = Instant::now(); - let (_, _) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); + let (_, _, _) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); start.elapsed() } @@ -91,7 +91,7 @@ pub fn commitment_size< let labeled_poly = LabeledPolynomial::new("test".to_string(), rand_poly(num_vars, rng), None, None); - let (coms, _) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); + let (coms, _, _) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); coms[0].commitment().serialized_size(Compress::No) } @@ -114,7 +114,7 @@ where let labeled_poly = LabeledPolynomial::new("test".to_string(), rand_poly(num_vars, rng), None, None); - let (coms, randomness) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); + let (coms, states, randomness) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); let point = P::Point::rand(rng); let start = Instant::now(); @@ -124,6 +124,7 @@ where &coms, &point, &mut ChallengeGenerator::new_univariate(&mut test_sponge()), + &states, &randomness, Some(rng), ) @@ -148,7 +149,7 @@ where let labeled_poly = LabeledPolynomial::new("test".to_string(), rand_poly(num_vars, rng), None, None); - let (coms, randomness) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); + let (coms, states, randomness) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); let point = P::Point::rand(rng); let proofs = PCS::open( @@ -157,6 +158,7 @@ where &coms, &point, &mut ChallengeGenerator::new_univariate(&mut test_sponge()), + &states, &randomness, Some(rng), ) @@ -185,7 +187,7 @@ where let labeled_poly = LabeledPolynomial::new("test".to_string(), rand_poly(num_vars, rng), None, None); - let (coms, randomness) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); + let (coms, states, randomness) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); let point = P::Point::rand(rng); let claimed_eval = labeled_poly.evaluate(&point); let proof = PCS::open( @@ -194,6 +196,7 @@ where &coms, &point, &mut ChallengeGenerator::new_univariate(&mut test_sponge()), + &states, &randomness, Some(rng), ) From 4ee97d46041e1d6fdb2e9d107f1b636c1d60225b Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Wed, 1 Nov 2023 14:59:43 +0100 Subject: [PATCH 04/20] Fix the name of local variable --- poly-commit/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/poly-commit/src/lib.rs b/poly-commit/src/lib.rs index 499802d7..cbd0a588 100644 --- a/poly-commit/src/lib.rs +++ b/poly-commit/src/lib.rs @@ -283,7 +283,7 @@ pub trait PolynomialCommitment, S: Cryptographic let open_time = start_timer!(|| format!( "Opening {} polynomials at query set of size {}", - poly_rand_comm.len(), + poly_rand_st_comm.len(), query_set.len(), )); From fb68290e35ff8f088f3003fc935cc8484e3396bb Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Mon, 13 Nov 2023 10:43:05 +0100 Subject: [PATCH 05/20] Merge `PCCommitmentState` with `PCRandomness` --- bench-templates/src/lib.rs | 13 +++---- poly-commit/src/data_structures.rs | 9 ++--- poly-commit/src/ipa_pc/data_structures.rs | 2 +- poly-commit/src/ipa_pc/mod.rs | 20 ++++------ poly-commit/src/kzg10/data_structures.rs | 7 +--- poly-commit/src/kzg10/mod.rs | 2 +- poly-commit/src/lib.rs | 39 +++++-------------- .../src/marlin/marlin_pc/data_structures.rs | 6 +-- poly-commit/src/marlin/marlin_pc/mod.rs | 30 +++++--------- .../marlin/marlin_pst13_pc/data_structures.rs | 4 +- poly-commit/src/marlin/marlin_pst13_pc/mod.rs | 24 ++++-------- poly-commit/src/marlin/mod.rs | 9 ++--- poly-commit/src/sonic_pc/mod.rs | 27 ++++--------- 13 files changed, 62 insertions(+), 130 deletions(-) diff --git a/bench-templates/src/lib.rs b/bench-templates/src/lib.rs index a9ca68ea..ba212e3e 100644 --- a/bench-templates/src/lib.rs +++ b/bench-templates/src/lib.rs @@ -69,7 +69,7 @@ pub fn commit< LabeledPolynomial::new("test".to_string(), rand_poly(num_vars, rng), None, None); let start = Instant::now(); - let (_, _, _) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); + let (_, _) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); start.elapsed() } @@ -91,7 +91,7 @@ pub fn commitment_size< let labeled_poly = LabeledPolynomial::new("test".to_string(), rand_poly(num_vars, rng), None, None); - let (coms, _, _) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); + let (coms, _) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); coms[0].commitment().serialized_size(Compress::No) } @@ -114,7 +114,7 @@ where let labeled_poly = LabeledPolynomial::new("test".to_string(), rand_poly(num_vars, rng), None, None); - let (coms, states, randomness) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); + let (coms, states) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); let point = P::Point::rand(rng); let start = Instant::now(); @@ -125,7 +125,6 @@ where &point, &mut ChallengeGenerator::new_univariate(&mut test_sponge()), &states, - &randomness, Some(rng), ) .unwrap(); @@ -149,7 +148,7 @@ where let labeled_poly = LabeledPolynomial::new("test".to_string(), rand_poly(num_vars, rng), None, None); - let (coms, states, randomness) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); + let (coms, states) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); let point = P::Point::rand(rng); let proofs = PCS::open( @@ -159,7 +158,6 @@ where &point, &mut ChallengeGenerator::new_univariate(&mut test_sponge()), &states, - &randomness, Some(rng), ) .unwrap(); @@ -187,7 +185,7 @@ where let labeled_poly = LabeledPolynomial::new("test".to_string(), rand_poly(num_vars, rng), None, None); - let (coms, states, randomness) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); + let (coms, states) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); let point = P::Point::rand(rng); let claimed_eval = labeled_poly.evaluate(&point); let proof = PCS::open( @@ -197,7 +195,6 @@ where &point, &mut ChallengeGenerator::new_univariate(&mut test_sponge()), &states, - &randomness, Some(rng), ) .unwrap(); diff --git a/poly-commit/src/data_structures.rs b/poly-commit/src/data_structures.rs index 9735d002..b4854f9a 100644 --- a/poly-commit/src/data_structures.rs +++ b/poly-commit/src/data_structures.rs @@ -63,9 +63,6 @@ pub trait PCCommitment: Clone + CanonicalSerialize + CanonicalDeserialize { fn has_degree_bound(&self) -> bool; } -/// Defines the auxiliary data of the commitment -pub trait PCCommitmentState: Clone + Default + CanonicalSerialize + CanonicalDeserialize {} - /// Defines the minimal interface of prepared commitments for any polynomial /// commitment scheme. pub trait PCPreparedCommitment: Clone { @@ -73,9 +70,9 @@ pub trait PCPreparedCommitment: Clone { fn prepare(comm: &UNPREPARED) -> Self; } -/// Defines the minimal interface of commitment randomness for any polynomial -/// commitment scheme. -pub trait PCRandomness: Clone + CanonicalSerialize + CanonicalDeserialize { +/// Defines the minimal interface of commitment state for any polynomial +/// commitment scheme. It might be randomness etc. +pub trait PCCommitmentState: Clone + CanonicalSerialize + CanonicalDeserialize { /// Outputs empty randomness that does not hide the commitment. fn empty() -> Self; diff --git a/poly-commit/src/ipa_pc/data_structures.rs b/poly-commit/src/ipa_pc/data_structures.rs index 7ba56c95..a2cca4d1 100644 --- a/poly-commit/src/ipa_pc/data_structures.rs +++ b/poly-commit/src/ipa_pc/data_structures.rs @@ -146,7 +146,7 @@ pub struct Randomness { pub shifted_rand: Option, } -impl PCRandomness for Randomness { +impl PCCommitmentState for Randomness { fn empty() -> Self { Self { rand: G::ScalarField::zero(), diff --git a/poly-commit/src/ipa_pc/mod.rs b/poly-commit/src/ipa_pc/mod.rs index 800ad480..d5472d9b 100644 --- a/poly-commit/src/ipa_pc/mod.rs +++ b/poly-commit/src/ipa_pc/mod.rs @@ -1,8 +1,7 @@ -use crate::kzg10::CommitmentState; use crate::{BTreeMap, BTreeSet, String, ToString, Vec, CHALLENGE_SIZE}; use crate::{BatchLCProof, DenseUVPolynomial, Error, Evaluations, QuerySet}; use crate::{LabeledCommitment, LabeledPolynomial, LinearCombination}; -use crate::{PCCommitterKey, PCRandomness, PCUniversalParams, PolynomialCommitment}; +use crate::{PCCommitmentState, PCCommitterKey, PCUniversalParams, PolynomialCommitment}; use ark_ec::{AffineRepr, CurveGroup, VariableBaseMSM}; use ark_ff::{Field, One, PrimeField, UniformRand, Zero}; @@ -348,8 +347,7 @@ where type CommitterKey = CommitterKey; type VerifierKey = VerifierKey; type Commitment = Commitment; - type CommitmentState = CommitmentState; - type Randomness = Randomness; + type CommitmentState = Randomness; type Proof = Proof; type BatchProof = Vec; type Error = Error; @@ -421,7 +419,6 @@ where ( Vec>, Vec, - Vec, ), Self::Error, > @@ -483,7 +480,7 @@ where } end_timer!(commit_time); - Ok((comms, vec![CommitmentState {}; rands.len()], rands)) + Ok((comms, rands)) } fn open<'a>( @@ -492,13 +489,12 @@ where commitments: impl IntoIterator>, point: &'a P::Point, opening_challenges: &mut ChallengeGenerator, - _states: impl IntoIterator, - rands: impl IntoIterator, + rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result where Self::Commitment: 'a, - Self::Randomness: 'a, + Self::CommitmentState: 'a, P: 'a, { let mut combined_polynomial = P::zero(); @@ -881,12 +877,11 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, - _states: impl IntoIterator, - rands: impl IntoIterator, + rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> where - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, P: 'a, { @@ -977,7 +972,6 @@ where lc_commitments.iter(), &query_set, opening_challenges, - &vec![CommitmentState {}; lc_randomness.len()], lc_randomness.iter(), rng, )?; diff --git a/poly-commit/src/kzg10/data_structures.rs b/poly-commit/src/kzg10/data_structures.rs index d44efecb..8ae4191a 100644 --- a/poly-commit/src/kzg10/data_structures.rs +++ b/poly-commit/src/kzg10/data_structures.rs @@ -329,11 +329,6 @@ pub struct Commitment( pub E::G1Affine, ); -/// The auxiliary data for KZG commitment is empty. -#[derive(Clone, Default, CanonicalSerialize, CanonicalDeserialize)] -pub struct CommitmentState {} -impl PCCommitmentState for CommitmentState {} - impl PCCommitment for Commitment { #[inline] fn empty() -> Self { @@ -425,7 +420,7 @@ impl> Randomness { } } -impl> PCRandomness for Randomness { +impl> PCCommitmentState for Randomness { fn empty() -> Self { Self { blinding_polynomial: P::zero(), diff --git a/poly-commit/src/kzg10/mod.rs b/poly-commit/src/kzg10/mod.rs index a6ea5752..d4bc9d74 100644 --- a/poly-commit/src/kzg10/mod.rs +++ b/poly-commit/src/kzg10/mod.rs @@ -5,7 +5,7 @@ //! proposed by Kate, Zaverucha, and Goldberg ([KZG10](http://cacr.uwaterloo.ca/techreports/2010/cacr2010-10.pdf)). //! This construction achieves extractability in the algebraic group model (AGM). -use crate::{BTreeMap, Error, LabeledPolynomial, PCRandomness, ToString, Vec}; +use crate::{BTreeMap, Error, LabeledPolynomial, PCCommitmentState, ToString, Vec}; use ark_ec::AffineRepr; use ark_ec::{pairing::Pairing, CurveGroup}; use ark_ec::{scalar_mul::fixed_base::FixedBase, VariableBaseMSM}; diff --git a/poly-commit/src/lib.rs b/poly-commit/src/lib.rs index cbd0a588..48c87625 100644 --- a/poly-commit/src/lib.rs +++ b/poly-commit/src/lib.rs @@ -156,10 +156,8 @@ pub trait PolynomialCommitment, S: Cryptographic type VerifierKey: PCVerifierKey; /// The commitment to a polynomial. type Commitment: PCCommitment + Default; - /// The state of committer + /// The state of commitment type CommitmentState: PCCommitmentState; - /// The commitment randomness. - type Randomness: PCRandomness; /// The evaluation proof for a single point. type Proof: Clone; /// The evaluation proof for a query set. @@ -206,7 +204,6 @@ pub trait PolynomialCommitment, S: Cryptographic ( Vec>, Vec, - Vec, ), Self::Error, > @@ -221,12 +218,10 @@ pub trait PolynomialCommitment, S: Cryptographic point: &'a P::Point, challenge_generator: &mut ChallengeGenerator, states: impl IntoIterator, - rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result where P: 'a, - Self::Randomness: 'a, Self::CommitmentState: 'a, Self::Commitment: 'a; @@ -259,12 +254,10 @@ pub trait PolynomialCommitment, S: Cryptographic query_set: &QuerySet, challenge_generator: &mut ChallengeGenerator, states: impl IntoIterator, - rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result where P: 'a, - Self::Randomness: 'a, Self::CommitmentState: 'a, Self::Commitment: 'a, { @@ -273,12 +266,11 @@ pub trait PolynomialCommitment, S: Cryptographic // the same point, then opening their commitments simultaneously with a // single call to `open` (per point) let rng = &mut crate::optional_rng::OptionalRng(rng); - let poly_rand_st_comm: BTreeMap<_, _> = labeled_polynomials + let poly_st_comm: BTreeMap<_, _> = labeled_polynomials .into_iter() .zip(states) - .zip(rands) .zip(commitments.into_iter()) - .map(|(((poly, st), r), comm)| (poly.label(), (poly, r, st, comm))) + .map(|((poly, st), comm)| (poly.label(), (poly, st, comm))) .collect(); let open_time = start_timer!(|| format!( @@ -306,7 +298,6 @@ pub trait PolynomialCommitment, S: Cryptographic let mut proofs = Vec::new(); for (_point_label, (point, labels)) in query_to_labels_map.into_iter() { let mut query_polys: Vec<&'a LabeledPolynomial<_, _>> = Vec::new(); - let mut query_rands: Vec<&'a Self::Randomness> = Vec::new(); let mut query_states: Vec<&'a Self::CommitmentState> = Vec::new(); let mut query_comms: Vec<&'a LabeledCommitment> = Vec::new(); @@ -314,15 +305,12 @@ pub trait PolynomialCommitment, S: Cryptographic // randomness and actual commitment for each polynomial being // queried at `point` for label in labels { - let (polynomial, rand, state, comm) = - poly_rand_st_comm - .get(label) - .ok_or(Error::MissingPolynomial { - label: label.to_string(), - })?; + let (polynomial, state, comm) = + poly_st_comm.get(label).ok_or(Error::MissingPolynomial { + label: label.to_string(), + })?; query_polys.push(polynomial); - query_rands.push(rand); query_states.push(state); query_comms.push(comm); } @@ -338,7 +326,6 @@ pub trait PolynomialCommitment, S: Cryptographic &point, challenge_generator, query_states, - query_rands, Some(rng), )?; @@ -452,11 +439,9 @@ pub trait PolynomialCommitment, S: Cryptographic query_set: &QuerySet, challenge_generator: &mut ChallengeGenerator, states: impl IntoIterator, - rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> where - Self::Randomness: 'a, Self::CommitmentState: 'a, Self::Commitment: 'a, P: 'a, @@ -480,7 +465,6 @@ pub trait PolynomialCommitment, S: Cryptographic &poly_query_set, challenge_generator, states, - rands, rng, )?; Ok(BatchLCProof { @@ -731,7 +715,7 @@ pub mod tests { )?; println!("Trimmed"); - let (comms, states, rands) = PC::commit(&ck, &polynomials, Some(rng))?; + let (comms, states) = PC::commit(&ck, &polynomials, Some(rng))?; let mut query_set = QuerySet::new(); let mut values = Evaluations::new(); @@ -750,7 +734,6 @@ pub mod tests { &query_set, &mut (challenge_gen.clone()), &states, - &rands, Some(rng), )?; let result = PC::batch_check( @@ -865,7 +848,7 @@ pub mod tests { )?; println!("Trimmed"); - let (comms, states, rands) = PC::commit(&ck, &polynomials, Some(rng))?; + let (comms, states) = PC::commit(&ck, &polynomials, Some(rng))?; // Construct query set let mut query_set = QuerySet::new(); @@ -887,7 +870,6 @@ pub mod tests { &query_set, &mut (challenge_gen.clone()), &states, - &rands, Some(rng), )?; let result = PC::batch_check( @@ -1014,7 +996,7 @@ pub mod tests { )?; println!("Trimmed"); - let (comms, states, rands) = PC::commit(&ck, &polynomials, Some(rng))?; + let (comms, states) = PC::commit(&ck, &polynomials, Some(rng))?; // Let's construct our equations let mut linear_combinations = Vec::new(); @@ -1067,7 +1049,6 @@ pub mod tests { &query_set, &mut (challenge_gen.clone()), &states, - &rands, Some(rng), )?; println!("Generated proof"); diff --git a/poly-commit/src/marlin/marlin_pc/data_structures.rs b/poly-commit/src/marlin/marlin_pc/data_structures.rs index 2b09e03a..5d1cdffb 100644 --- a/poly-commit/src/marlin/marlin_pc/data_structures.rs +++ b/poly-commit/src/marlin/marlin_pc/data_structures.rs @@ -1,6 +1,6 @@ use crate::{ - DenseUVPolynomial, PCCommitment, PCCommitterKey, PCPreparedCommitment, PCPreparedVerifierKey, - PCRandomness, PCVerifierKey, Vec, + DenseUVPolynomial, PCCommitment, PCCommitmentState, PCCommitterKey, PCPreparedCommitment, + PCPreparedVerifierKey, PCVerifierKey, Vec, }; use ark_ec::pairing::Pairing; use ark_ec::AdditiveGroup; @@ -360,7 +360,7 @@ impl<'a, F: PrimeField, P: DenseUVPolynomial> AddAssign<(F, &'a Randomness> PCRandomness for Randomness { +impl> PCCommitmentState for Randomness { fn empty() -> Self { Self { rand: kzg10::Randomness::empty(), diff --git a/poly-commit/src/marlin/marlin_pc/mod.rs b/poly-commit/src/marlin/marlin_pc/mod.rs index c10c8680..e69c7392 100644 --- a/poly-commit/src/marlin/marlin_pc/mod.rs +++ b/poly-commit/src/marlin/marlin_pc/mod.rs @@ -1,9 +1,8 @@ -use crate::kzg10::CommitmentState; use crate::{kzg10, marlin::Marlin, PCCommitterKey, CHALLENGE_SIZE}; use crate::{BTreeMap, BTreeSet, ToString, Vec}; use crate::{BatchLCProof, Error, Evaluations, QuerySet}; use crate::{LabeledCommitment, LabeledPolynomial, LinearCombination}; -use crate::{PCRandomness, PCUniversalParams, PolynomialCommitment}; +use crate::{PCCommitmentState, PCUniversalParams, PolynomialCommitment}; use ark_ec::pairing::Pairing; use ark_ec::AffineRepr; use ark_ec::CurveGroup; @@ -67,8 +66,7 @@ where type CommitterKey = CommitterKey; type VerifierKey = VerifierKey; type Commitment = Commitment; - type CommitmentState = CommitmentState; - type Randomness = Randomness; + type CommitmentState = Randomness; type Proof = kzg10::Proof; type BatchProof = Vec; type Error = Error; @@ -183,7 +181,6 @@ where ( Vec>, Vec, - Vec, ), Self::Error, > @@ -245,11 +242,7 @@ where end_timer!(commit_time); } end_timer!(commit_time); - Ok(( - commitments, - vec![CommitmentState {}; randomness.len()], - randomness, - )) + Ok((commitments, randomness)) } /// On input a polynomial `p` and a point `point`, outputs a proof for the same. @@ -259,13 +252,12 @@ where _commitments: impl IntoIterator>, point: &'a P::Point, opening_challenges: &mut ChallengeGenerator, - _states: impl IntoIterator, - rands: impl IntoIterator, + rands: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result where P: 'a, - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, { let mut p = P::zero(); @@ -416,13 +408,12 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, - _states: impl IntoIterator, - rands: impl IntoIterator, + rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> where P: 'a, - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, { Marlin::::open_combinations( @@ -472,13 +463,11 @@ where commitments: impl IntoIterator>>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, - _states: impl IntoIterator, - rands: impl IntoIterator, + rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result>, Error> where P: 'a, - Self::Randomness: 'a, Self::CommitmentState: 'a, Self::Commitment: 'a, { @@ -508,7 +497,7 @@ where let mut proofs = Vec::new(); for (_point_label, (point, labels)) in query_to_labels_map.into_iter() { let mut query_polys: Vec<&'a LabeledPolynomial<_, _>> = Vec::new(); - let mut query_rands: Vec<&'a Self::Randomness> = Vec::new(); + let mut query_rands: Vec<&'a Self::CommitmentState> = Vec::new(); let mut query_comms: Vec<&'a LabeledCommitment> = Vec::new(); for label in labels { @@ -529,7 +518,6 @@ where query_comms, point, opening_challenges, - &vec![CommitmentState {}; query_rands.len()], query_rands, Some(rng), )?; diff --git a/poly-commit/src/marlin/marlin_pst13_pc/data_structures.rs b/poly-commit/src/marlin/marlin_pst13_pc/data_structures.rs index 8ccf300b..2e6b73cf 100644 --- a/poly-commit/src/marlin/marlin_pst13_pc/data_structures.rs +++ b/poly-commit/src/marlin/marlin_pst13_pc/data_structures.rs @@ -1,6 +1,6 @@ use crate::{BTreeMap, Vec}; use crate::{ - PCCommitterKey, PCPreparedVerifierKey, PCRandomness, PCUniversalParams, PCVerifierKey, + PCCommitmentState, PCCommitterKey, PCPreparedVerifierKey, PCUniversalParams, PCVerifierKey, }; use ark_ec::pairing::Pairing; use ark_poly::DenseMVPolynomial; @@ -362,7 +362,7 @@ where } } -impl PCRandomness for Randomness +impl PCCommitmentState for Randomness where E: Pairing, P: DenseMVPolynomial, diff --git a/poly-commit/src/marlin/marlin_pst13_pc/mod.rs b/poly-commit/src/marlin/marlin_pst13_pc/mod.rs index 2ab5d543..45265370 100644 --- a/poly-commit/src/marlin/marlin_pst13_pc/mod.rs +++ b/poly-commit/src/marlin/marlin_pst13_pc/mod.rs @@ -1,11 +1,11 @@ use crate::{ - kzg10::{self, CommitmentState}, + kzg10, marlin::{marlin_pc, Marlin}, CHALLENGE_SIZE, }; use crate::{BatchLCProof, Error, Evaluations, QuerySet}; use crate::{LabeledCommitment, LabeledPolynomial, LinearCombination}; -use crate::{PCRandomness, PCUniversalParams, PolynomialCommitment}; +use crate::{PCCommitmentState, PCUniversalParams, PolynomialCommitment}; use crate::{ToString, Vec}; use ark_ec::AffineRepr; use ark_ec::{pairing::Pairing, scalar_mul::fixed_base::FixedBase, CurveGroup, VariableBaseMSM}; @@ -151,8 +151,7 @@ where type CommitterKey = CommitterKey; type VerifierKey = VerifierKey; type Commitment = marlin_pc::Commitment; - type CommitmentState = CommitmentState; - type Randomness = Randomness; + type CommitmentState = Randomness; type Proof = Proof; type BatchProof = Vec; type Error = Error; @@ -345,7 +344,6 @@ where ( Vec>, Vec, - Vec, ), Self::Error, > @@ -433,11 +431,7 @@ where end_timer!(commit_time); } end_timer!(commit_time); - Ok(( - commitments, - vec![CommitmentState {}; randomness.len()], - randomness, - )) + Ok((commitments, randomness)) } /// On input a polynomial `p` and a point `point`, outputs a proof for the same. @@ -447,13 +441,12 @@ where _commitments: impl IntoIterator>, point: &P::Point, opening_challenges: &mut ChallengeGenerator, - _states: impl IntoIterator, - rands: impl IntoIterator, + rands: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result where P: 'a, - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, { // Compute random linear combinations of committed polynomials and randomness @@ -668,13 +661,12 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, - _states: impl IntoIterator, - rands: impl IntoIterator, + rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> where P: 'a, - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, { Marlin::::open_combinations( diff --git a/poly-commit/src/marlin/mod.rs b/poly-commit/src/marlin/mod.rs index 4f9e424e..1558486d 100644 --- a/poly-commit/src/marlin/mod.rs +++ b/poly-commit/src/marlin/mod.rs @@ -3,7 +3,7 @@ use crate::{kzg10, Error}; use crate::{BTreeMap, BTreeSet, Debug, RngCore, String, ToString, Vec}; use crate::{BatchLCProof, LabeledPolynomial, LinearCombination}; use crate::{Evaluations, LabeledCommitment, QuerySet}; -use crate::{PCRandomness, Polynomial, PolynomialCommitment}; +use crate::{PCCommitmentState, Polynomial, PolynomialCommitment}; use ark_crypto_primitives::sponge::CryptographicSponge; use ark_ec::pairing::Pairing; use ark_ec::AffineRepr; @@ -228,7 +228,7 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, - rands: impl IntoIterator, + rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Error> where @@ -241,7 +241,7 @@ where Commitment = marlin_pc::Commitment, Error = Error, >, - PC::Randomness: 'a + AddAssign<(E::ScalarField, &'a PC::Randomness)>, + PC::CommitmentState: 'a + AddAssign<(E::ScalarField, &'a PC::CommitmentState)>, PC::Commitment: 'a, { let label_map = polynomials @@ -262,7 +262,7 @@ where let mut degree_bound = None; let mut hiding_bound = None; - let mut randomness = PC::Randomness::empty(); + let mut randomness = PC::CommitmentState::empty(); let mut coeffs_and_comms = Vec::new(); let num_polys = lc.len(); @@ -309,7 +309,6 @@ where lc_commitments.iter(), &query_set, opening_challenges, - &vec![PC::CommitmentState::default(); lc_randomness.len()], lc_randomness.iter(), rng, )?; diff --git a/poly-commit/src/sonic_pc/mod.rs b/poly-commit/src/sonic_pc/mod.rs index a00fb5f3..e495463a 100644 --- a/poly-commit/src/sonic_pc/mod.rs +++ b/poly-commit/src/sonic_pc/mod.rs @@ -1,9 +1,8 @@ -use crate::kzg10::CommitmentState; use crate::{kzg10, PCCommitterKey, CHALLENGE_SIZE}; use crate::{BTreeMap, BTreeSet, String, ToString, Vec}; use crate::{BatchLCProof, DenseUVPolynomial, Error, Evaluations, QuerySet}; use crate::{LabeledCommitment, LabeledPolynomial, LinearCombination}; -use crate::{PCRandomness, PCUniversalParams, PolynomialCommitment}; +use crate::{PCCommitmentState, PCUniversalParams, PolynomialCommitment}; use ark_ec::AffineRepr; use ark_ec::CurveGroup; @@ -147,8 +146,7 @@ where type CommitterKey = CommitterKey; type VerifierKey = VerifierKey; type Commitment = Commitment; - type CommitmentState = CommitmentState; - type Randomness = Randomness; + type CommitmentState = Randomness; type Proof = kzg10::Proof; type BatchProof = Vec; type Error = Error; @@ -284,7 +282,6 @@ where ( Vec>, Vec, - Vec, ), Self::Error, > @@ -294,7 +291,7 @@ where let rng = &mut crate::optional_rng::OptionalRng(rng); let commit_time = start_timer!(|| "Committing to polynomials"); let mut labeled_comms: Vec> = Vec::new(); - let mut randomness: Vec = Vec::new(); + let mut randomness: Vec = Vec::new(); for labeled_polynomial in polynomials { let enforced_degree_bounds: Option<&[usize]> = ck @@ -340,11 +337,7 @@ where } end_timer!(commit_time); - Ok(( - labeled_comms, - vec![CommitmentState {}; randomness.len()], - randomness, - )) + Ok((labeled_comms, randomness)) } fn open<'a>( @@ -353,12 +346,11 @@ where _commitments: impl IntoIterator>, point: &'a P::Point, opening_challenges: &mut ChallengeGenerator, - _states: impl IntoIterator, - rands: impl IntoIterator, + rands: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result where - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, P: 'a, { @@ -511,12 +503,10 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, - _states: impl IntoIterator, - rands: impl IntoIterator, + rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> where - Self::Randomness: 'a, Self::CommitmentState: 'a, Self::Commitment: 'a, P: 'a, @@ -538,7 +528,7 @@ where let mut poly = P::zero(); let mut degree_bound = None; let mut hiding_bound = None; - let mut randomness = Self::Randomness::empty(); + let mut randomness = Self::CommitmentState::empty(); let mut comm = E::G1::zero(); let num_polys = lc.len(); @@ -592,7 +582,6 @@ where lc_commitments.iter(), &query_set, opening_challenges, - &vec![CommitmentState {}; lc_randomness.len()], lc_randomness.iter(), rng, )?; From 14573b38f0ec08fa2a08dd1a0a6680bb81151cde Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Mon, 13 Nov 2023 10:47:24 +0100 Subject: [PATCH 06/20] Update `README.md` --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 70661333..1d7db95f 100644 --- a/README.md +++ b/README.md @@ -128,13 +128,13 @@ let (ck, vk) = PCS::trim(&pp, degree, 2, Some(&[degree])).unwrap(); // 3. PolynomialCommitment::commit // The prover commits to the polynomial using their committer key `ck`. -let (comms, states, rands) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); +let (comms, states) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); let challenge_generator: ChallengeGenerator<::ScalarField, Sponge_Bls12_377> = ChallengeGenerator::new_univariate(&mut test_sponge); // 4a. PolynomialCommitment::open // Opening proof at a single point. -let proof_single = PCS::open(&ck, [&labeled_poly], &comms, &point_1, &mut (challenge_generator.clone()), &states, &rands, None).unwrap(); +let proof_single = PCS::open(&ck, [&labeled_poly], &comms, &point_1, &mut (challenge_generator.clone()), &states, None).unwrap(); // 5a. PolynomialCommitment::check // Verifying the proof at a single point, given the commitment, the point, the claimed evaluation, and the proof. @@ -157,7 +157,6 @@ let proof_batched = PCS::batch_open( &query_set, &mut (challenge_generator.clone()), &states, - &rands, Some(rng), ).unwrap(); From 5a5993eb7b25b2e22336d30cc58c21d9eb06ccf4 Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Mon, 13 Nov 2023 10:51:30 +0100 Subject: [PATCH 07/20] Fix a bug --- poly-commit/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/poly-commit/src/lib.rs b/poly-commit/src/lib.rs index 48c87625..2798d204 100644 --- a/poly-commit/src/lib.rs +++ b/poly-commit/src/lib.rs @@ -275,7 +275,7 @@ pub trait PolynomialCommitment, S: Cryptographic let open_time = start_timer!(|| format!( "Opening {} polynomials at query set of size {}", - poly_rand_st_comm.len(), + poly_st_comm.len(), query_set.len(), )); From b9fa84345d65f26f4c86952dd77d3ae7442cf51f Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Tue, 14 Nov 2023 14:35:45 +0100 Subject: [PATCH 08/20] Change `Randomness` to `CommitmentState` --- poly-commit/src/hyrax/data_structures.rs | 4 ++-- poly-commit/src/hyrax/mod.rs | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/poly-commit/src/hyrax/data_structures.rs b/poly-commit/src/hyrax/data_structures.rs index fbdd69a9..15ac4d8c 100644 --- a/poly-commit/src/hyrax/data_structures.rs +++ b/poly-commit/src/hyrax/data_structures.rs @@ -3,7 +3,7 @@ use ark_ff::PrimeField; use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; use ark_std::{rand::RngCore, vec::Vec}; -use crate::{PCCommitment, PCCommitterKey, PCRandomness, PCUniversalParams, PCVerifierKey}; +use crate::{PCCommitment, PCCommitterKey, PCCommitmentState, PCUniversalParams, PCVerifierKey}; /// `UniversalParams` amounts to a Pederson commitment key of sufficient length #[derive(Derivative, CanonicalSerialize, CanonicalDeserialize)] @@ -79,7 +79,7 @@ pub(crate) type HyraxRandomness = Vec; /// A vector of scalars, each of which multiplies the distinguished group /// element in the Pederson commitment key for a different commitment -impl PCRandomness for HyraxRandomness { +impl PCCommitmentState for HyraxRandomness { fn empty() -> Self { unimplemented!() } diff --git a/poly-commit/src/hyrax/mod.rs b/poly-commit/src/hyrax/mod.rs index 67937470..5988cf0b 100644 --- a/poly-commit/src/hyrax/mod.rs +++ b/poly-commit/src/hyrax/mod.rs @@ -128,7 +128,7 @@ impl> type CommitterKey = HyraxCommitterKey; type VerifierKey = HyraxVerifierKey; type Commitment = HyraxCommitment; - type Randomness = HyraxRandomness; + type CommitmentState = HyraxRandomness; type Proof = Vec>; type BatchProof = Vec; type Error = Error; @@ -222,7 +222,7 @@ impl> ) -> Result< ( Vec>, - Vec, + Vec, ), Self::Error, > @@ -305,12 +305,12 @@ impl> G::ScalarField, PoseidonSponge, >, - rands: impl IntoIterator, + rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result where Self::Commitment: 'a, - Self::Randomness: 'a, + Self::CommitmentState: 'a, P: 'a, { let n = point.len(); From 69b5402ad68164d870362adcbaa95a216d0edc19 Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Wed, 15 Nov 2023 15:36:49 +0100 Subject: [PATCH 09/20] Maybe `empty` not return `Self` --- poly-commit/src/data_structures.rs | 8 +++++--- poly-commit/src/ipa_pc/data_structures.rs | 1 + poly-commit/src/kzg10/data_structures.rs | 1 + .../src/marlin/marlin_pc/data_structures.rs | 1 + .../marlin/marlin_pst13_pc/data_structures.rs | 1 + poly-commit/src/marlin/mod.rs | 18 ++++++++++-------- 6 files changed, 19 insertions(+), 11 deletions(-) diff --git a/poly-commit/src/data_structures.rs b/poly-commit/src/data_structures.rs index b4854f9a..e3da52ed 100644 --- a/poly-commit/src/data_structures.rs +++ b/poly-commit/src/data_structures.rs @@ -73,8 +73,11 @@ pub trait PCPreparedCommitment: Clone { /// Defines the minimal interface of commitment state for any polynomial /// commitment scheme. It might be randomness etc. pub trait PCCommitmentState: Clone + CanonicalSerialize + CanonicalDeserialize { + /// blah + type Randomness: Clone + CanonicalSerialize + CanonicalDeserialize; + /// Outputs empty randomness that does not hide the commitment. - fn empty() -> Self; + fn empty() -> Self::Randomness; /// Samples randomness for commitments; /// `num_queries` specifies the number of queries that the commitment will be opened at. @@ -86,9 +89,8 @@ pub trait PCCommitmentState: Clone + CanonicalSerialize + CanonicalDeserialize { has_degree_bound: bool, num_vars: Option, rng: &mut R, - ) -> Self; + ) -> Self::Randomness; } - /// A proof of satisfaction of linear combinations. #[derive(Clone, CanonicalSerialize, CanonicalDeserialize)] pub struct BatchLCProof { diff --git a/poly-commit/src/ipa_pc/data_structures.rs b/poly-commit/src/ipa_pc/data_structures.rs index a2cca4d1..84fcb7f2 100644 --- a/poly-commit/src/ipa_pc/data_structures.rs +++ b/poly-commit/src/ipa_pc/data_structures.rs @@ -147,6 +147,7 @@ pub struct Randomness { } impl PCCommitmentState for Randomness { + type Randomness = Self; fn empty() -> Self { Self { rand: G::ScalarField::zero(), diff --git a/poly-commit/src/kzg10/data_structures.rs b/poly-commit/src/kzg10/data_structures.rs index 8ae4191a..d648f19f 100644 --- a/poly-commit/src/kzg10/data_structures.rs +++ b/poly-commit/src/kzg10/data_structures.rs @@ -421,6 +421,7 @@ impl> Randomness { } impl> PCCommitmentState for Randomness { + type Randomness = Self; fn empty() -> Self { Self { blinding_polynomial: P::zero(), diff --git a/poly-commit/src/marlin/marlin_pc/data_structures.rs b/poly-commit/src/marlin/marlin_pc/data_structures.rs index 5d1cdffb..203e3201 100644 --- a/poly-commit/src/marlin/marlin_pc/data_structures.rs +++ b/poly-commit/src/marlin/marlin_pc/data_structures.rs @@ -361,6 +361,7 @@ impl<'a, F: PrimeField, P: DenseUVPolynomial> AddAssign<(F, &'a Randomness> PCCommitmentState for Randomness { + type Randomness = Self; fn empty() -> Self { Self { rand: kzg10::Randomness::empty(), diff --git a/poly-commit/src/marlin/marlin_pst13_pc/data_structures.rs b/poly-commit/src/marlin/marlin_pst13_pc/data_structures.rs index 2e6b73cf..9cc8d73b 100644 --- a/poly-commit/src/marlin/marlin_pst13_pc/data_structures.rs +++ b/poly-commit/src/marlin/marlin_pst13_pc/data_structures.rs @@ -368,6 +368,7 @@ where P: DenseMVPolynomial, P::Point: Index, { + type Randomness = Self; fn empty() -> Self { Self { blinding_polynomial: P::zero(), diff --git a/poly-commit/src/marlin/mod.rs b/poly-commit/src/marlin/mod.rs index 1558486d..6468d57d 100644 --- a/poly-commit/src/marlin/mod.rs +++ b/poly-commit/src/marlin/mod.rs @@ -228,7 +228,7 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Error> where @@ -241,18 +241,20 @@ where Commitment = marlin_pc::Commitment, Error = Error, >, - PC::CommitmentState: 'a + AddAssign<(E::ScalarField, &'a PC::CommitmentState)>, + PC::CommitmentState: 'a, + ::Randomness: + 'a + AddAssign<(E::ScalarField, &'a PC::CommitmentState)>, PC::Commitment: 'a, { let label_map = polynomials .into_iter() - .zip(rands) + .zip(states) .zip(commitments) .map(|((p, r), c)| (p.label(), (p, r, c))) .collect::>(); let mut lc_polynomials = Vec::new(); - let mut lc_randomness = Vec::new(); + let mut lc_states: Vec = Vec::new(); let mut lc_commitments = Vec::new(); let mut lc_info = Vec::new(); @@ -268,7 +270,7 @@ where let num_polys = lc.len(); for (coeff, label) in lc.iter().filter(|(_, l)| !l.is_one()) { let label: &String = label.try_into().expect("cannot be one!"); - let &(cur_poly, cur_rand, cur_comm) = + let &(cur_poly, cur_state, cur_comm) = label_map.get(label).ok_or(Error::MissingPolynomial { label: label.to_string(), })?; @@ -284,14 +286,14 @@ where // Some(_) > None, always. hiding_bound = core::cmp::max(hiding_bound, cur_poly.hiding_bound()); poly += (*coeff, cur_poly.polynomial()); - randomness += (*coeff, cur_rand); + randomness += (*coeff, cur_state); coeffs_and_comms.push((*coeff, cur_comm.commitment())); } let lc_poly = LabeledPolynomial::new(lc_label.clone(), poly, degree_bound, hiding_bound); lc_polynomials.push(lc_poly); - lc_randomness.push(randomness); + lc_states.push(randomness); lc_commitments.push(Self::combine_commitments(coeffs_and_comms)); lc_info.push((lc_label, degree_bound)); } @@ -309,7 +311,7 @@ where lc_commitments.iter(), &query_set, opening_challenges, - lc_randomness.iter(), + lc_states.iter(), rng, )?; From 1aa03a95e7c2caa5463c6bbddbf61a4c548fb3d6 Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Wed, 15 Nov 2023 15:42:29 +0100 Subject: [PATCH 10/20] Make `empty` return `Self` --- poly-commit/src/data_structures.rs | 2 +- poly-commit/src/marlin/mod.rs | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/poly-commit/src/data_structures.rs b/poly-commit/src/data_structures.rs index e3da52ed..402cbc06 100644 --- a/poly-commit/src/data_structures.rs +++ b/poly-commit/src/data_structures.rs @@ -77,7 +77,7 @@ pub trait PCCommitmentState: Clone + CanonicalSerialize + CanonicalDeserialize { type Randomness: Clone + CanonicalSerialize + CanonicalDeserialize; /// Outputs empty randomness that does not hide the commitment. - fn empty() -> Self::Randomness; + fn empty() -> Self; /// Samples randomness for commitments; /// `num_queries` specifies the number of queries that the commitment will be opened at. diff --git a/poly-commit/src/marlin/mod.rs b/poly-commit/src/marlin/mod.rs index 6468d57d..e0b026d2 100644 --- a/poly-commit/src/marlin/mod.rs +++ b/poly-commit/src/marlin/mod.rs @@ -241,9 +241,7 @@ where Commitment = marlin_pc::Commitment, Error = Error, >, - PC::CommitmentState: 'a, - ::Randomness: - 'a + AddAssign<(E::ScalarField, &'a PC::CommitmentState)>, + PC::CommitmentState: 'a + AddAssign<(E::ScalarField, &'a PC::CommitmentState)>, PC::Commitment: 'a, { let label_map = polynomials From c9032c125013211a06272840d92a9005fa2913e8 Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Wed, 15 Nov 2023 16:04:06 +0100 Subject: [PATCH 11/20] Rename `rand` to `state` --- poly-commit/src/ipa_pc/mod.rs | 36 +++++++++---------- poly-commit/src/marlin/marlin_pc/mod.rs | 26 +++++++------- poly-commit/src/marlin/marlin_pst13_pc/mod.rs | 10 +++--- poly-commit/src/sonic_pc/mod.rs | 24 ++++++------- 4 files changed, 48 insertions(+), 48 deletions(-) diff --git a/poly-commit/src/ipa_pc/mod.rs b/poly-commit/src/ipa_pc/mod.rs index d5472d9b..26234f1e 100644 --- a/poly-commit/src/ipa_pc/mod.rs +++ b/poly-commit/src/ipa_pc/mod.rs @@ -427,7 +427,7 @@ where { let rng = &mut crate::optional_rng::OptionalRng(rng); let mut comms = Vec::new(); - let mut rands = Vec::new(); + let mut states = Vec::new(); let commit_time = start_timer!(|| "Committing to polynomials"); for labeled_polynomial in polynomials { @@ -446,7 +446,7 @@ where hiding_bound, )); - let randomness = if let Some(h) = hiding_bound { + let state = if let Some(h) = hiding_bound { Randomness::rand(h, degree_bound.is_some(), None, rng) } else { Randomness::empty() @@ -456,7 +456,7 @@ where &ck.comm_key[..(polynomial.degree() + 1)], &polynomial.coeffs(), Some(ck.s), - Some(randomness.rand), + Some(state.rand), ) .into(); @@ -465,7 +465,7 @@ where &ck.comm_key[(ck.supported_degree() - d)..], &polynomial.coeffs(), Some(ck.s), - randomness.shifted_rand, + state.shifted_rand, ) .into() }); @@ -474,13 +474,13 @@ where let labeled_comm = LabeledCommitment::new(label.to_string(), commitment, degree_bound); comms.push(labeled_comm); - rands.push(randomness); + states.push(state); end_timer!(commit_time); } end_timer!(commit_time); - Ok((comms, rands)) + Ok((comms, states)) } fn open<'a>( @@ -489,7 +489,7 @@ where commitments: impl IntoIterator>, point: &'a P::Point, opening_challenges: &mut ChallengeGenerator, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result where @@ -504,15 +504,15 @@ where let mut has_hiding = false; let polys_iter = labeled_polynomials.into_iter(); - let rands_iter = rands.into_iter(); + let states_iter = states.into_iter(); let comms_iter = commitments.into_iter(); let combine_time = start_timer!(|| "Combining polynomials, randomness, and commitments."); let mut cur_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); - for (labeled_polynomial, (labeled_commitment, randomness)) in - polys_iter.zip(comms_iter.zip(rands_iter)) + for (labeled_polynomial, (labeled_commitment, state)) in + polys_iter.zip(comms_iter.zip(states_iter)) { let label = labeled_polynomial.label(); assert_eq!(labeled_polynomial.label(), labeled_commitment.label()); @@ -528,7 +528,7 @@ where if hiding_bound.is_some() { has_hiding = true; - combined_rand += &(cur_challenge * &randomness.rand); + combined_rand += &(cur_challenge * &state.rand); } cur_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); @@ -554,7 +554,7 @@ where combined_commitment_proj += &commitment.shifted_comm.unwrap().mul(cur_challenge); if hiding_bound.is_some() { - let shifted_rand = randomness.shifted_rand; + let shifted_rand = state.shifted_rand; assert!( shifted_rand.is_some(), "shifted_rand.is_none() for {}", @@ -877,7 +877,7 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> where @@ -887,13 +887,13 @@ where { let label_poly_map = polynomials .into_iter() - .zip(rands) + .zip(states) .zip(commitments) - .map(|((p, r), c)| (p.label(), (p, r, c))) + .map(|((p, s), c)| (p.label(), (p, s, c))) .collect::>(); let mut lc_polynomials = Vec::new(); - let mut lc_randomness = Vec::new(); + let mut lc_states = Vec::new(); let mut lc_commitments = Vec::new(); let mut lc_info = Vec::new(); @@ -951,7 +951,7 @@ where let lc_poly = LabeledPolynomial::new(lc_label.clone(), poly, degree_bound, hiding_bound); lc_polynomials.push(lc_poly); - lc_randomness.push(Randomness { + lc_states.push(Randomness { rand: combined_rand, shifted_rand: combined_shifted_rand, }); @@ -972,7 +972,7 @@ where lc_commitments.iter(), &query_set, opening_challenges, - lc_randomness.iter(), + lc_states.iter(), rng, )?; Ok(BatchLCProof { proof, evals: None }) diff --git a/poly-commit/src/marlin/marlin_pc/mod.rs b/poly-commit/src/marlin/marlin_pc/mod.rs index e69c7392..1b45bff7 100644 --- a/poly-commit/src/marlin/marlin_pc/mod.rs +++ b/poly-commit/src/marlin/marlin_pc/mod.rs @@ -191,7 +191,7 @@ where let commit_time = start_timer!(|| "Committing to polynomials"); let mut commitments = Vec::new(); - let mut randomness = Vec::new(); + let mut states = Vec::new(); for p in polynomials { let label = p.label(); @@ -232,17 +232,17 @@ where }; let comm = Commitment { comm, shifted_comm }; - let rand = Randomness { rand, shifted_rand }; + let state = Randomness { rand, shifted_rand }; commitments.push(LabeledCommitment::new( label.to_string(), comm, degree_bound, )); - randomness.push(rand); + states.push(state); end_timer!(commit_time); } end_timer!(commit_time); - Ok((commitments, randomness)) + Ok((commitments, states)) } /// On input a polynomial `p` and a point `point`, outputs a proof for the same. @@ -252,7 +252,7 @@ where _commitments: impl IntoIterator>, point: &'a P::Point, opening_challenges: &mut ChallengeGenerator, - rands: impl IntoIterator, + states: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result where @@ -267,7 +267,7 @@ where let mut shifted_r_witness = P::zero(); let mut enforce_degree_bound = false; - for (polynomial, rand) in labeled_polynomials.into_iter().zip(rands) { + for (polynomial, rand) in labeled_polynomials.into_iter().zip(states) { let degree_bound = polynomial.degree_bound(); assert_eq!(degree_bound.is_some(), rand.shifted_rand.is_some()); @@ -408,7 +408,7 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> where @@ -423,7 +423,7 @@ where commitments, query_set, opening_challenges, - rands, + states, rng, ) } @@ -463,7 +463,7 @@ where commitments: impl IntoIterator>>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result>, Error> where @@ -474,7 +474,7 @@ where let rng = &mut crate::optional_rng::OptionalRng(rng); let poly_rand_comm: BTreeMap<_, _> = labeled_polynomials .into_iter() - .zip(rands) + .zip(states) .zip(commitments.into_iter()) .map(|((poly, r), comm)| (poly.label(), (poly, r, comm))) .collect(); @@ -497,7 +497,7 @@ where let mut proofs = Vec::new(); for (_point_label, (point, labels)) in query_to_labels_map.into_iter() { let mut query_polys: Vec<&'a LabeledPolynomial<_, _>> = Vec::new(); - let mut query_rands: Vec<&'a Self::CommitmentState> = Vec::new(); + let mut query_states: Vec<&'a Self::CommitmentState> = Vec::new(); let mut query_comms: Vec<&'a LabeledCommitment> = Vec::new(); for label in labels { @@ -507,7 +507,7 @@ where })?; query_polys.push(polynomial); - query_rands.push(rand); + query_states.push(rand); query_comms.push(comm); } @@ -518,7 +518,7 @@ where query_comms, point, opening_challenges, - query_rands, + query_states, Some(rng), )?; diff --git a/poly-commit/src/marlin/marlin_pst13_pc/mod.rs b/poly-commit/src/marlin/marlin_pst13_pc/mod.rs index 45265370..93d5c0c6 100644 --- a/poly-commit/src/marlin/marlin_pst13_pc/mod.rs +++ b/poly-commit/src/marlin/marlin_pst13_pc/mod.rs @@ -441,7 +441,7 @@ where _commitments: impl IntoIterator>, point: &P::Point, opening_challenges: &mut ChallengeGenerator, - rands: impl IntoIterator, + states: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result where @@ -452,14 +452,14 @@ where // Compute random linear combinations of committed polynomials and randomness let mut p = P::zero(); let mut r = Randomness::empty(); - for (polynomial, rand) in labeled_polynomials.into_iter().zip(rands) { + for (polynomial, state) in labeled_polynomials.into_iter().zip(states) { Self::check_degrees_and_bounds(ck.supported_degree, &polynomial)?; // compute challenge^j and challenge^{j+1}. let challenge_j = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); p += (challenge_j, polynomial.polynomial()); - r += (challenge_j, rand); + r += (challenge_j, state); } let open_time = start_timer!(|| format!("Opening polynomial of degree {}", p.degree())); @@ -661,7 +661,7 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> where @@ -676,7 +676,7 @@ where commitments, query_set, opening_challenges, - rands, + states, rng, ) } diff --git a/poly-commit/src/sonic_pc/mod.rs b/poly-commit/src/sonic_pc/mod.rs index e495463a..b1d7f28b 100644 --- a/poly-commit/src/sonic_pc/mod.rs +++ b/poly-commit/src/sonic_pc/mod.rs @@ -346,7 +346,7 @@ where _commitments: impl IntoIterator>, point: &'a P::Point, opening_challenges: &mut ChallengeGenerator, - rands: impl IntoIterator, + states: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result where @@ -359,7 +359,7 @@ where let mut curr_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); - for (polynomial, rand) in labeled_polynomials.into_iter().zip(rands) { + for (polynomial, state) in labeled_polynomials.into_iter().zip(states) { let enforced_degree_bounds: Option<&[usize]> = ck .enforced_degree_bounds .as_ref() @@ -373,7 +373,7 @@ where )?; combined_polynomial += (curr_challenge, polynomial.polynomial()); - combined_rand += (curr_challenge, rand); + combined_rand += (curr_challenge, state); curr_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); } @@ -503,7 +503,7 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, opening_challenges: &mut ChallengeGenerator, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> where @@ -513,13 +513,13 @@ where { let label_map = polynomials .into_iter() - .zip(rands) + .zip(states) .zip(commitments) - .map(|((p, r), c)| (p.label(), (p, r, c))) + .map(|((p, s), c)| (p.label(), (p, s, c))) .collect::>(); let mut lc_polynomials = Vec::new(); - let mut lc_randomness = Vec::new(); + let mut lc_states = Vec::new(); let mut lc_commitments = Vec::new(); let mut lc_info = Vec::new(); @@ -528,13 +528,13 @@ where let mut poly = P::zero(); let mut degree_bound = None; let mut hiding_bound = None; - let mut randomness = Self::CommitmentState::empty(); + let mut state = Self::CommitmentState::empty(); let mut comm = E::G1::zero(); let num_polys = lc.len(); for (coeff, label) in lc.iter().filter(|(_, l)| !l.is_one()) { let label: &String = label.try_into().expect("cannot be one!"); - let &(cur_poly, cur_rand, curr_comm) = + let &(cur_poly, cur_state, curr_comm) = label_map.get(label).ok_or(Error::MissingPolynomial { label: label.to_string(), })?; @@ -553,14 +553,14 @@ where // Some(_) > None, always. hiding_bound = core::cmp::max(hiding_bound, cur_poly.hiding_bound()); poly += (*coeff, cur_poly.polynomial()); - randomness += (*coeff, cur_rand); + state += (*coeff, cur_state); comm += &curr_comm.commitment().0.mul(*coeff); } let lc_poly = LabeledPolynomial::new(lc_label.clone(), poly, degree_bound, hiding_bound); lc_polynomials.push(lc_poly); - lc_randomness.push(randomness); + lc_states.push(state); lc_commitments.push(comm); lc_info.push((lc_label, degree_bound)); } @@ -582,7 +582,7 @@ where lc_commitments.iter(), &query_set, opening_challenges, - lc_randomness.iter(), + lc_states.iter(), rng, )?; Ok(BatchLCProof { proof, evals: None }) From 8803c52f886d841bcbffda1418d7d17017c8147c Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Wed, 15 Nov 2023 16:28:46 +0100 Subject: [PATCH 12/20] Partially integrate the new design into Hyrax --- poly-commit/src/hyrax/data_structures.rs | 22 +++++++++++++++++++--- poly-commit/src/hyrax/mod.rs | 14 ++++++++------ 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/poly-commit/src/hyrax/data_structures.rs b/poly-commit/src/hyrax/data_structures.rs index 15ac4d8c..da311c29 100644 --- a/poly-commit/src/hyrax/data_structures.rs +++ b/poly-commit/src/hyrax/data_structures.rs @@ -3,7 +3,7 @@ use ark_ff::PrimeField; use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; use ark_std::{rand::RngCore, vec::Vec}; -use crate::{PCCommitment, PCCommitterKey, PCCommitmentState, PCUniversalParams, PCVerifierKey}; +use crate::{PCCommitment, PCCommitmentState, PCCommitterKey, PCUniversalParams, PCVerifierKey}; /// `UniversalParams` amounts to a Pederson commitment key of sufficient length #[derive(Derivative, CanonicalSerialize, CanonicalDeserialize)] @@ -77,9 +77,25 @@ impl PCCommitment for HyraxCommitment { pub(crate) type HyraxRandomness = Vec; +/// Hyrax Commitment State blah blah blah blah +/// blah blah blah blah +/// blah blah blah blah +/// blah blah blah blah +#[derive(Derivative, CanonicalSerialize, CanonicalDeserialize)] +#[derivative(Default(bound = ""), Clone(bound = ""), Debug(bound = ""))] +pub struct HyraxCommitmentState +where + F: PrimeField, +{ + /// blah blah blah blah + /// blah blah blah blah + pub randomness: HyraxRandomness, +} + /// A vector of scalars, each of which multiplies the distinguished group /// element in the Pederson commitment key for a different commitment -impl PCCommitmentState for HyraxRandomness { +impl PCCommitmentState for HyraxCommitmentState { + type Randomness = HyraxRandomness; fn empty() -> Self { unimplemented!() } @@ -89,7 +105,7 @@ impl PCCommitmentState for HyraxRandomness { _has_degree_bound: bool, _num_vars: Option, rng: &mut R, - ) -> Self { + ) -> Self::Randomness { (0..num_queries).map(|_| F::rand(rng)).collect() } } diff --git a/poly-commit/src/hyrax/mod.rs b/poly-commit/src/hyrax/mod.rs index 5988cf0b..efc2e002 100644 --- a/poly-commit/src/hyrax/mod.rs +++ b/poly-commit/src/hyrax/mod.rs @@ -128,7 +128,7 @@ impl> type CommitterKey = HyraxCommitterKey; type VerifierKey = HyraxVerifierKey; type Commitment = HyraxCommitment; - type CommitmentState = HyraxRandomness; + type CommitmentState = HyraxCommitmentState; type Proof = Vec>; type BatchProof = Vec; type Error = Error; @@ -230,7 +230,7 @@ impl> P: 'a, { let mut coms = Vec::new(); - let mut rands = Vec::new(); + let mut states = Vec::new(); #[cfg(not(feature = "parallel"))] let rng_inner = rng.expect("Committing to polynomials requires a random generator"); @@ -270,10 +270,12 @@ impl> let l_comm = LabeledCommitment::new(label.to_string(), com, Some(1)); coms.push(l_comm); - rands.push(com_rands); + states.push(HyraxCommitmentState { + randomness: com_rands, + }); } - Ok((coms, rands)) + Ok((coms, states)) } /// Opens a list of polynomial commitments at a desired point. This @@ -339,7 +341,7 @@ impl> let rng_inner = rng.expect("Opening polynomials requires randomness"); - for (l_poly, (l_com, randomness)) in labeled_polynomials + for (l_poly, (l_com, state)) in labeled_polynomials .into_iter() .zip(commitments.into_iter().zip(rands.into_iter())) { @@ -382,7 +384,7 @@ impl> // t_prime coincides witht he Pedersen commitment to lt with the // randomnes r_lt computed here let r_lt = cfg_iter!(l) - .zip(cfg_iter!(randomness)) + .zip(cfg_iter!(state.randomness)) .map(|(l, r)| *l * r) .sum::(); From 2ac0e33985be71b07b1dca35a48268d71449a6a3 Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Wed, 15 Nov 2023 17:04:47 +0100 Subject: [PATCH 13/20] Update Hyrax with the shared state --- poly-commit/src/hyrax/data_structures.rs | 10 ++++++---- poly-commit/src/hyrax/mod.rs | 8 ++++---- poly-commit/src/utils.rs | 5 +++-- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/poly-commit/src/hyrax/data_structures.rs b/poly-commit/src/hyrax/data_structures.rs index da311c29..aa58b7cf 100644 --- a/poly-commit/src/hyrax/data_structures.rs +++ b/poly-commit/src/hyrax/data_structures.rs @@ -3,7 +3,10 @@ use ark_ff::PrimeField; use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; use ark_std::{rand::RngCore, vec::Vec}; -use crate::{PCCommitment, PCCommitmentState, PCCommitterKey, PCUniversalParams, PCVerifierKey}; +use crate::{ + utils::Matrix, PCCommitment, PCCommitmentState, PCCommitterKey, PCUniversalParams, + PCVerifierKey, +}; /// `UniversalParams` amounts to a Pederson commitment key of sufficient length #[derive(Derivative, CanonicalSerialize, CanonicalDeserialize)] @@ -87,9 +90,8 @@ pub struct HyraxCommitmentState where F: PrimeField, { - /// blah blah blah blah - /// blah blah blah blah - pub randomness: HyraxRandomness, + pub(crate) randomness: HyraxRandomness, + pub(crate) mat: Matrix, } /// A vector of scalars, each of which multiplies the distinguished group diff --git a/poly-commit/src/hyrax/mod.rs b/poly-commit/src/hyrax/mod.rs index efc2e002..e169b91c 100644 --- a/poly-commit/src/hyrax/mod.rs +++ b/poly-commit/src/hyrax/mod.rs @@ -272,6 +272,7 @@ impl> coms.push(l_comm); states.push(HyraxCommitmentState { randomness: com_rands, + mat: Matrix::new_from_rows(m), }); } @@ -307,7 +308,7 @@ impl> G::ScalarField, PoseidonSponge, >, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result where @@ -343,7 +344,7 @@ impl> for (l_poly, (l_com, state)) in labeled_polynomials .into_iter() - .zip(commitments.into_iter().zip(rands.into_iter())) + .zip(commitments.into_iter().zip(states.into_iter())) { let label = l_poly.label(); if label != l_com.label() { @@ -376,8 +377,7 @@ impl> transcript.append_serializable_element(b"point", point)?; // Commiting to the matrix formed by the polynomial coefficients - let t_aux = flat_to_matrix_column_major(&poly.to_evaluations(), dim, dim); - let t = Matrix::new_from_rows(t_aux); + let t = &state.mat; let lt = t.row_mul(&l); diff --git a/poly-commit/src/utils.rs b/poly-commit/src/utils.rs index 7c4a0575..4a2ffeb4 100644 --- a/poly-commit/src/utils.rs +++ b/poly-commit/src/utils.rs @@ -7,7 +7,7 @@ use rayon::{ }; use ark_ff::{Field, PrimeField}; -use ark_serialize::CanonicalSerialize; +use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; use ark_std::vec::Vec; use merlin::Transcript; @@ -31,7 +31,8 @@ pub(crate) fn ceil_div(x: usize, y: usize) -> usize { (x + y - 1) / y } -#[derive(Debug)] +#[derive(Derivative, CanonicalSerialize, CanonicalDeserialize)] +#[derivative(Default(bound = ""), Clone(bound = ""), Debug(bound = ""))] pub(crate) struct Matrix { pub(crate) n: usize, pub(crate) m: usize, From ae5d8f4a9c930456d731fdf1951fe09cb247b079 Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Tue, 9 Jan 2024 23:52:56 +0100 Subject: [PATCH 14/20] Rename nonnative to emulated, as in `r1cs-std` (#137) * Rename nonnative to emulated, as in `r1cs-std` * Run `fmt` * Temporarily change `Cargo.toml` * Revert `Cargo.toml` * Refactor `FoldedPolynomialStream` partially --- poly-commit/src/constraints.rs | 20 +++++++++---------- .../src/streaming_kzg/data_structures.rs | 9 ++++----- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/poly-commit/src/constraints.rs b/poly-commit/src/constraints.rs index e6fb5d4f..1300509a 100644 --- a/poly-commit/src/constraints.rs +++ b/poly-commit/src/constraints.rs @@ -5,7 +5,7 @@ use crate::{ use ark_crypto_primitives::sponge::CryptographicSponge; use ark_ff::PrimeField; use ark_poly::Polynomial; -use ark_r1cs_std::fields::nonnative::NonNativeFieldVar; +use ark_r1cs_std::fields::emulated_fp::EmulatedFpVar; use ark_r1cs_std::{fields::fp::FpVar, prelude::*}; use ark_relations::r1cs::{ConstraintSystemRef, Namespace, Result as R1CSResult, SynthesisError}; use ark_std::{borrow::Borrow, cmp::Eq, cmp::PartialEq, hash::Hash, marker::Sized}; @@ -24,8 +24,8 @@ pub enum LinearCombinationCoeffVar), + /// Other coefficient, represented as a "emulated" field element. + Var(EmulatedFpVar), } /// An allocated version of `LinearCombination`. @@ -60,7 +60,7 @@ impl let (f, lc_term) = term; let fg = - NonNativeFieldVar::new_variable(ark_relations::ns!(cs, "term"), || Ok(f), mode) + EmulatedFpVar::new_variable(ark_relations::ns!(cs, "term"), || Ok(f), mode) .unwrap(); (LinearCombinationCoeffVar::Var(fg), lc_term.clone()) @@ -79,12 +79,12 @@ impl pub struct PCCheckRandomDataVar { /// Opening challenges. /// The prover and the verifier MUST use the same opening challenges. - pub opening_challenges: Vec>, + pub opening_challenges: Vec>, /// Bit representations of the opening challenges. pub opening_challenges_bits: Vec>>, /// Batching random numbers. /// The verifier can choose these numbers freely, as long as they are random. - pub batching_rands: Vec>, + pub batching_rands: Vec>, /// Bit representations of the batching random numbers. pub batching_rands_bits: Vec>>, } @@ -172,7 +172,7 @@ pub struct LabeledPointVar { /// MUST be a unique identifier in a query set. pub name: String, /// The point value. - pub value: NonNativeFieldVar, + pub value: EmulatedFpVar, } /// An allocated version of `QuerySet`. @@ -184,7 +184,7 @@ pub struct QuerySetVar( /// An allocated version of `Evaluations`. #[derive(Clone)] pub struct EvaluationsVar( - pub HashMap, NonNativeFieldVar>, + pub HashMap, EmulatedFpVar>, ); impl EvaluationsVar { @@ -192,8 +192,8 @@ impl EvaluationsVar, - ) -> Result, SynthesisError> { + point: &EmulatedFpVar, + ) -> Result, SynthesisError> { let key = LabeledPointVar:: { name: String::from(lc_string), value: point.clone(), diff --git a/poly-commit/src/streaming_kzg/data_structures.rs b/poly-commit/src/streaming_kzg/data_structures.rs index 5923a40e..0dc68e87 100644 --- a/poly-commit/src/streaming_kzg/data_structures.rs +++ b/poly-commit/src/streaming_kzg/data_structures.rs @@ -140,7 +140,7 @@ where /// Stream implementation of foleded polynomial. #[derive(Clone, Copy)] -pub struct FoldedPolynomialStream<'a, F, S>(FoldedPolynomialTree<'a, F, S>, usize); +pub struct FoldedPolynomialStream<'a, F, S>(FoldedPolynomialTree<'a, F, S>); /// Iterator implementation of foleded polynomial. pub struct FoldedPolynomialStreamIter<'a, F, I> { challenges: &'a [F], @@ -157,8 +157,7 @@ where /// Initialize a new folded polynomial stream. pub fn new(coefficients: &'a S, challenges: &'a [F]) -> Self { let tree = FoldedPolynomialTree::new(coefficients, challenges); - let len = challenges.len(); - Self(tree, len) + Self(tree) } } @@ -240,7 +239,7 @@ fn test_folded_polynomial() { let challenges = vec![F::one(), two]; let coefficients_stream = coefficients.as_slice(); let foldstream = FoldedPolynomialTree::new(&coefficients_stream, challenges.as_slice()); - let fold_stream = FoldedPolynomialStream(foldstream, 2); + let fold_stream = FoldedPolynomialStream(foldstream); assert_eq!(fold_stream.len(), 1); assert_eq!( fold_stream.iter().next(), @@ -252,7 +251,7 @@ fn test_folded_polynomial() { let challenges = vec![F::one(); 4]; let coefficients_stream = coefficients.as_slice(); let foldstream = FoldedPolynomialTree::new(&coefficients_stream, challenges.as_slice()); - let fold_stream = FoldedPolynomialStream(foldstream, 4).iter(); + let fold_stream = FoldedPolynomialStream(foldstream).iter(); assert_eq!(fold_stream.last(), Some(coefficients.iter().sum())); } From 3291693ebd5edb1ea5b1a8e85d0f12a889da503e Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Sun, 14 Jan 2024 23:01:08 +0100 Subject: [PATCH 15/20] Substitute `ChallengeGenerator` by the generic sponge (#139) * Rename nonnative to emulated, as in `r1cs-std` * Run `fmt` * Temporarily change `Cargo.toml` * Substitute `ChallengeGenerator` with the generic sponge * Run `fmt` * Remove the extra file * Update modules * Delete the unnecessary loop * Revert `Cargo.toml` * Refactor `FoldedPolynomialStream` partially * Update README * Make the diff more readable * Bring the whitespace back * Make diff more readable, 2 --- README.md | 12 ++-- bench-templates/src/lib.rs | 10 +-- poly-commit/src/challenge.rs | 61 ----------------- poly-commit/src/ipa_pc/mod.rs | 43 +++++------- poly-commit/src/lib.rs | 68 +++++++------------ poly-commit/src/marlin/marlin_pc/mod.rs | 27 ++++---- poly-commit/src/marlin/marlin_pst13_pc/mod.rs | 21 +++--- poly-commit/src/marlin/mod.rs | 21 +++--- poly-commit/src/sonic_pc/mod.rs | 29 ++++---- 9 files changed, 100 insertions(+), 192 deletions(-) delete mode 100644 poly-commit/src/challenge.rs diff --git a/README.md b/README.md index bdedd6bb..833b2892 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ This trait defines the interface for a polynomial commitment scheme. It is recom // In this example, we will commit to a single polynomial, open it first at one point, and then batched at two points, and finally verify the proofs. // We will use the KZG10 polynomial commitment scheme, following the approach from Marlin. -use ark_poly_commit::{Polynomial, marlin_pc::MarlinKZG10, LabeledPolynomial, PolynomialCommitment, QuerySet, Evaluations, challenge::ChallengeGenerator}; +use ark_poly_commit::{Polynomial, marlin_pc::MarlinKZG10, LabeledPolynomial, PolynomialCommitment, QuerySet, Evaluations}; use ark_bls12_377::Bls12_377; use ark_crypto_primitives::sponge::poseidon::{PoseidonSponge, PoseidonConfig}; use ark_crypto_primitives::sponge::CryptographicSponge; @@ -130,15 +130,13 @@ let (ck, vk) = PCS::trim(&pp, degree, 2, Some(&[degree])).unwrap(); // The prover commits to the polynomial using their committer key `ck`. let (comms, rands) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); -let challenge_generator: ChallengeGenerator<::ScalarField, Sponge_Bls12_377> = ChallengeGenerator::new_univariate(&mut test_sponge); - // 4a. PolynomialCommitment::open // Opening proof at a single point. -let proof_single = PCS::open(&ck, [&labeled_poly], &comms, &point_1, &mut (challenge_generator.clone()), &rands, None).unwrap(); +let proof_single = PCS::open(&ck, [&labeled_poly], &comms, &point_1, &mut (test_sponge.clone()), &rands, None).unwrap(); // 5a. PolynomialCommitment::check // Verifying the proof at a single point, given the commitment, the point, the claimed evaluation, and the proof. -assert!(PCS::check(&vk, &comms, &point_1, [secret_poly.evaluate(&point_1)], &proof_single, &mut (challenge_generator.clone()), Some(rng)).unwrap()); +assert!(PCS::check(&vk, &comms, &point_1, [secret_poly.evaluate(&point_1)], &proof_single, &mut (test_sponge.clone()), Some(rng)).unwrap()); let mut query_set = QuerySet::new(); let mut values = Evaluations::new(); @@ -155,7 +153,7 @@ let proof_batched = PCS::batch_open( [&labeled_poly], &comms, &query_set, - &mut (challenge_generator.clone()), + &mut (test_sponge.clone()), &rands, Some(rng), ).unwrap(); @@ -167,7 +165,7 @@ assert!(PCS::batch_check( &query_set, &values, &proof_batched, - &mut (challenge_generator.clone()), + &mut (test_sponge.clone()), rng, ).unwrap()); ``` diff --git a/bench-templates/src/lib.rs b/bench-templates/src/lib.rs index 1594ee7c..6fc2e8bd 100644 --- a/bench-templates/src/lib.rs +++ b/bench-templates/src/lib.rs @@ -11,7 +11,7 @@ use rand_chacha::{rand_core::SeedableRng, ChaCha20Rng}; use core::time::Duration; use std::time::Instant; -use ark_poly_commit::{challenge::ChallengeGenerator, LabeledPolynomial, PolynomialCommitment}; +use ark_poly_commit::{LabeledPolynomial, PolynomialCommitment}; pub use criterion::*; pub use paste::paste; @@ -123,7 +123,7 @@ where [&labeled_poly], &coms, &point, - &mut ChallengeGenerator::new_univariate(&mut test_sponge()), + &mut test_sponge(), &randomness, Some(rng), ) @@ -156,7 +156,7 @@ where [&labeled_poly], &coms, &point, - &mut ChallengeGenerator::new_univariate(&mut test_sponge()), + &mut test_sponge(), &randomness, Some(rng), ) @@ -193,7 +193,7 @@ where [&labeled_poly], &coms, &point, - &mut ChallengeGenerator::new_univariate(&mut test_sponge()), + &mut test_sponge(), &randomness, Some(rng), ) @@ -206,7 +206,7 @@ where &point, [claimed_eval], &proof, - &mut ChallengeGenerator::new_univariate(&mut test_sponge()), + &mut test_sponge(), None, ) .unwrap(); diff --git a/poly-commit/src/challenge.rs b/poly-commit/src/challenge.rs deleted file mode 100644 index 23b3c9d1..00000000 --- a/poly-commit/src/challenge.rs +++ /dev/null @@ -1,61 +0,0 @@ -use ark_crypto_primitives::sponge::{CryptographicSponge, FieldElementSize}; -use ark_ff::PrimeField; - -/// `ChallengeGenerator` generates opening challenges using multivariate or univariate strategy. -/// For multivariate strategy, each challenge is freshly squeezed from a sponge. -/// For univariate strategy, each challenge is a power of one squeezed element from sponge. -/// -/// Note that mutable reference cannot be cloned. -#[derive(Clone)] -pub enum ChallengeGenerator { - /// Each challenge is freshly squeezed from a sponge. - Multivariate(S), - /// Each challenge is a power of one squeezed element from sponge. - /// - /// `Univariate(generator, next_element)` - Univariate(F, F), -} - -impl ChallengeGenerator { - /// Returns a challenge generator with multivariate strategy. Each challenge is freshly squeezed - /// from a sponge. - pub fn new_multivariate(sponge: S) -> Self { - Self::Multivariate(sponge) - } - - /// Returns a challenge generator with univariate strategy. Each challenge is a power of one - /// squeezed element from sponge. - pub fn new_univariate(sponge: &mut S) -> Self { - let gen = sponge.squeeze_field_elements(1)[0]; - Self::Univariate(gen, gen) - } - - /// Returns a challenge of size `size`. - /// * If `self == Self::Multivariate(...)`, then this squeezes out a challenge of size `size`. - /// * If `self == Self::Univariate(...)`, then this ignores the `size` argument and simply squeezes out - /// the next field element. - pub fn try_next_challenge_of_size(&mut self, size: FieldElementSize) -> F { - match self { - // multivariate (full) - Self::Multivariate(sponge) => sponge.squeeze_field_elements_with_sizes(&[size])[0], - // univariate - Self::Univariate(gen, next) => { - let result = next.clone(); - *next *= *gen; - result - } - } - } - /// Returns the next challenge generated. - pub fn next_challenge(&mut self) -> F { - self.try_next_challenge_of_size(FieldElementSize::Full) - } - - /// Returns the sponge state if `self` is multivariate. Returns `None` otherwise. - pub fn into_sponge(self) -> Option { - match self { - Self::Multivariate(s) => Some(s), - _ => None, - } - } -} diff --git a/poly-commit/src/ipa_pc/mod.rs b/poly-commit/src/ipa_pc/mod.rs index 25752d78..652a54c0 100644 --- a/poly-commit/src/ipa_pc/mod.rs +++ b/poly-commit/src/ipa_pc/mod.rs @@ -15,7 +15,6 @@ pub use data_structures::*; #[cfg(feature = "parallel")] use rayon::prelude::*; -use crate::challenge::ChallengeGenerator; use ark_crypto_primitives::sponge::CryptographicSponge; use digest::Digest; @@ -105,7 +104,7 @@ where point: G::ScalarField, values: impl IntoIterator, proof: &Proof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, ) -> Option> { let check_time = start_timer!(|| "Succinct checking"); @@ -117,7 +116,8 @@ where let mut combined_commitment_proj = G::Group::zero(); let mut combined_v = G::ScalarField::zero(); - let mut cur_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + let mut cur_challenge: G::ScalarField = + sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; let labeled_commitments = commitments.into_iter(); let values = values.into_iter(); @@ -126,7 +126,7 @@ where let commitment = labeled_commitment.commitment(); combined_v += &(cur_challenge * &value); combined_commitment_proj += &labeled_commitment.commitment().comm.mul(cur_challenge); - cur_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + cur_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; let degree_bound = labeled_commitment.degree_bound(); assert_eq!(degree_bound.is_some(), commitment.shifted_comm.is_some()); @@ -137,7 +137,7 @@ where combined_commitment_proj += &commitment.shifted_comm.unwrap().mul(cur_challenge); } - cur_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + cur_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; } let mut combined_commitment = combined_commitment_proj.into_affine(); @@ -488,7 +488,7 @@ where labeled_polynomials: impl IntoIterator>, commitments: impl IntoIterator>, point: &'a P::Point, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result @@ -509,7 +509,7 @@ where let combine_time = start_timer!(|| "Combining polynomials, randomness, and commitments."); - let mut cur_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + let mut cur_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; for (labeled_polynomial, (labeled_commitment, randomness)) in polys_iter.zip(comms_iter.zip(rands_iter)) @@ -531,7 +531,7 @@ where combined_rand += &(cur_challenge * &randomness.rand); } - cur_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + cur_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; let has_degree_bound = degree_bound.is_some(); @@ -564,7 +564,7 @@ where } } - cur_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + cur_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; } end_timer!(combine_time); @@ -739,7 +739,7 @@ where point: &'a P::Point, values: impl IntoIterator, proof: &Self::Proof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, _rng: Option<&mut dyn RngCore>, ) -> Result where @@ -762,8 +762,7 @@ where )); } - let check_poly = - Self::succinct_check(vk, commitments, *point, values, proof, opening_challenges); + let check_poly = Self::succinct_check(vk, commitments, *point, values, proof, sponge); if check_poly.is_none() { return Ok(false); @@ -790,7 +789,7 @@ where query_set: &QuerySet, values: &Evaluations, proof: &Self::BatchProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -833,14 +832,8 @@ where vals.push(*v_i); } - let check_poly = Self::succinct_check( - vk, - comms.into_iter(), - *point, - vals.into_iter(), - p, - opening_challenges, - ); + let check_poly = + Self::succinct_check(vk, comms.into_iter(), *point, vals.into_iter(), p, sponge); if check_poly.is_none() { return Ok(false); @@ -876,7 +869,7 @@ where polynomials: impl IntoIterator>, commitments: impl IntoIterator>, query_set: &QuerySet, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> @@ -971,7 +964,7 @@ where lc_polynomials.iter(), lc_commitments.iter(), &query_set, - opening_challenges, + sponge, lc_randomness.iter(), rng, )?; @@ -987,7 +980,7 @@ where eqn_query_set: &QuerySet, eqn_evaluations: &Evaluations, proof: &BatchLCProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -1060,7 +1053,7 @@ where &eqn_query_set, &evaluations, proof, - opening_challenges, + sponge, rng, ) } diff --git a/poly-commit/src/lib.rs b/poly-commit/src/lib.rs index 8413a1af..23245476 100644 --- a/poly-commit/src/lib.rs +++ b/poly-commit/src/lib.rs @@ -9,7 +9,7 @@ #![deny(renamed_and_removed_lints, stable_features, unused_allocation)] #![deny(unused_comparisons, bare_trait_objects, unused_must_use)] #![forbid(unsafe_code)] -#![doc = include_str!("../README.md")] +#![doc = include_str!("../../README.md")] #[allow(unused)] #[macro_use] @@ -98,8 +98,6 @@ pub mod sonic_pc; /// [pcdas]: https://eprint.iacr.org/2020/499 pub mod ipa_pc; -/// Defines the challenge strategies and challenge generator. -pub mod challenge; /// A multilinear polynomial commitment scheme that converts n-variate multilinear polynomial into /// n quotient UV polynomial. This scheme is based on hardness of the discrete logarithm /// in prime-order groups. Construction is detailed in [[XZZPD19]][xzzpd19] and [[ZGKPP18]][zgkpp18] @@ -108,7 +106,6 @@ pub mod challenge; /// [zgkpp]: https://ieeexplore.ieee.org/document/8418645 pub mod multilinear_pc; -use crate::challenge::ChallengeGenerator; use ark_crypto_primitives::sponge::{CryptographicSponge, FieldElementSize}; /// Multivariate polynomial commitment based on the construction in /// [[PST13]][pst] with batching and (optional) hiding property inspired @@ -216,7 +213,7 @@ pub trait PolynomialCommitment, S: Cryptographic labeled_polynomials: impl IntoIterator>, commitments: impl IntoIterator>, point: &'a P::Point, - challenge_generator: &mut ChallengeGenerator, + sponge: &mut S, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result @@ -232,7 +229,7 @@ pub trait PolynomialCommitment, S: Cryptographic point: &'a P::Point, values: impl IntoIterator, proof: &Self::Proof, - challenge_generator: &mut ChallengeGenerator, + sponge: &mut S, rng: Option<&mut dyn RngCore>, ) -> Result where @@ -252,7 +249,7 @@ pub trait PolynomialCommitment, S: Cryptographic labeled_polynomials: impl IntoIterator>, commitments: impl IntoIterator>, query_set: &QuerySet, - challenge_generator: &mut ChallengeGenerator, + sponge: &mut S, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result @@ -324,7 +321,7 @@ pub trait PolynomialCommitment, S: Cryptographic query_polys, query_comms, &point, - challenge_generator, + sponge, query_rands, Some(rng), )?; @@ -357,7 +354,7 @@ pub trait PolynomialCommitment, S: Cryptographic query_set: &QuerySet, evaluations: &Evaluations, proof: &Self::BatchProof, - challenge_generator: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -415,15 +412,7 @@ pub trait PolynomialCommitment, S: Cryptographic // Verify all proofs referring to the current point simultaneously // with a single call to `check` - result &= Self::check( - vk, - comms, - &point, - values, - &proof, - challenge_generator, - Some(rng), - )?; + result &= Self::check(vk, comms, &point, values, &proof, sponge, Some(rng))?; end_timer!(proof_time); } Ok(result) @@ -437,7 +426,7 @@ pub trait PolynomialCommitment, S: Cryptographic polynomials: impl IntoIterator>, commitments: impl IntoIterator>, query_set: &QuerySet, - challenge_generator: &mut ChallengeGenerator, + sponge: &mut S, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> @@ -463,7 +452,7 @@ pub trait PolynomialCommitment, S: Cryptographic polynomials, commitments, &poly_query_set, - challenge_generator, + sponge, rands, rng, )?; @@ -482,7 +471,7 @@ pub trait PolynomialCommitment, S: Cryptographic eqn_query_set: &QuerySet, eqn_evaluations: &Evaluations, proof: &BatchLCProof, - challenge_generator: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -553,7 +542,7 @@ pub trait PolynomialCommitment, S: Cryptographic &poly_query_set, &poly_evals, proof, - challenge_generator, + sponge, rng, )?; if !pc_result { @@ -665,12 +654,9 @@ pub mod tests { PC: PolynomialCommitment, S: CryptographicSponge, { - let challenge_generators = vec![ - ChallengeGenerator::new_multivariate(sponge()), - ChallengeGenerator::new_univariate(&mut sponge()), - ]; + let sponge = sponge(); - for challenge_gen in challenge_generators { + for __ in 0..1 { let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); let max_degree = 100; let pp = PC::setup(max_degree, None, rng)?; @@ -732,7 +718,7 @@ pub mod tests { &polynomials, &comms, &query_set, - &mut (challenge_gen.clone()), + &mut (sponge.clone()), &rands, Some(rng), )?; @@ -742,7 +728,7 @@ pub mod tests { &query_set, &values, &proof, - &mut (challenge_gen.clone()), + &mut (sponge.clone()), rng, )?; assert!(result, "proof was incorrect, Query set: {:#?}", query_set); @@ -773,12 +759,9 @@ pub mod tests { sponge, } = info; - let challenge_gens = vec![ - ChallengeGenerator::new_multivariate(sponge()), - ChallengeGenerator::new_univariate(&mut sponge()), - ]; + let sponge = sponge(); - for challenge_gen in challenge_gens { + for _ in 0..1 { let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); // If testing multivariate polynomials, make the max degree lower let max_degree = match num_vars { @@ -787,7 +770,7 @@ pub mod tests { }; let pp = PC::setup(max_degree, num_vars, rng)?; - for _ in 0..num_iters { + for __ in 0..num_iters { let supported_degree = supported_degree.unwrap_or(Uniform::from(1..=max_degree).sample(rng)); assert!( @@ -868,7 +851,7 @@ pub mod tests { &polynomials, &comms, &query_set, - &mut (challenge_gen.clone()), + &mut (sponge.clone()), &rands, Some(rng), )?; @@ -878,7 +861,7 @@ pub mod tests { &query_set, &values, &proof, - &mut (challenge_gen.clone()), + &mut (sponge.clone()), rng, )?; if !result { @@ -918,12 +901,9 @@ pub mod tests { sponge, } = info; - let challenge_gens = vec![ - ChallengeGenerator::new_multivariate(sponge()), - ChallengeGenerator::new_univariate(&mut sponge()), - ]; + let sponge = sponge(); - for challenge_gen in challenge_gens { + for __ in 0..1 { let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); // If testing multivariate polynomials, make the max degree lower let max_degree = match num_vars { @@ -1047,7 +1027,7 @@ pub mod tests { &polynomials, &comms, &query_set, - &mut (challenge_gen.clone()), + &mut (sponge.clone()), &rands, Some(rng), )?; @@ -1059,7 +1039,7 @@ pub mod tests { &query_set, &values, &proof, - &mut (challenge_gen.clone()), + &mut (sponge.clone()), rng, )?; if !result { diff --git a/poly-commit/src/marlin/marlin_pc/mod.rs b/poly-commit/src/marlin/marlin_pc/mod.rs index 39c4e362..622e12bd 100644 --- a/poly-commit/src/marlin/marlin_pc/mod.rs +++ b/poly-commit/src/marlin/marlin_pc/mod.rs @@ -12,7 +12,6 @@ use ark_std::rand::RngCore; use ark_std::{marker::PhantomData, ops::Div, vec}; mod data_structures; -use crate::challenge::ChallengeGenerator; use ark_crypto_primitives::sponge::CryptographicSponge; pub use data_structures::*; @@ -251,7 +250,7 @@ where labeled_polynomials: impl IntoIterator>, _commitments: impl IntoIterator>, point: &'a P::Point, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rands: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result @@ -283,7 +282,7 @@ where )?; // compute next challenges challenge^j and challenge^{j+1}. - let challenge_j = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + let challenge_j = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; assert_eq!(degree_bound.is_some(), rand.shifted_rand.is_some()); @@ -299,7 +298,7 @@ where *point, &shifted_rand, )?; - let challenge_j_1 = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + let challenge_j_1 = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; let shifted_witness = shift_polynomial(ck, &witness, degree_bound); @@ -347,7 +346,7 @@ where point: &'a P::Point, values: impl IntoIterator, proof: &Self::Proof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, _rng: Option<&mut dyn RngCore>, ) -> Result where @@ -358,7 +357,7 @@ where Marlin::::accumulate_commitments_and_values( commitments, values, - opening_challenges, + sponge, Some(vk), )?; let combined_comm = kzg10::Commitment(combined_comm.into()); @@ -373,7 +372,7 @@ where query_set: &QuerySet, values: &Evaluations, proof: &Self::BatchProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -384,7 +383,7 @@ where commitments, query_set, values, - opening_challenges, + sponge, Some(vk), )?; assert_eq!(proof.len(), combined_queries.len()); @@ -407,7 +406,7 @@ where polynomials: impl IntoIterator>, commitments: impl IntoIterator>, query_set: &QuerySet, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> @@ -422,7 +421,7 @@ where polynomials, commitments, query_set, - opening_challenges, + sponge, rands, rng, ) @@ -437,7 +436,7 @@ where query_set: &QuerySet, evaluations: &Evaluations, proof: &BatchLCProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -450,7 +449,7 @@ where query_set, evaluations, proof, - opening_challenges, + sponge, rng, ) } @@ -462,7 +461,7 @@ where labeled_polynomials: impl IntoIterator>, commitments: impl IntoIterator>>, query_set: &QuerySet, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result>, Error> @@ -517,7 +516,7 @@ where query_polys, query_comms, point, - opening_challenges, + sponge, query_rands, Some(rng), )?; diff --git a/poly-commit/src/marlin/marlin_pst13_pc/mod.rs b/poly-commit/src/marlin/marlin_pst13_pc/mod.rs index ac47c2a7..14b48052 100644 --- a/poly-commit/src/marlin/marlin_pst13_pc/mod.rs +++ b/poly-commit/src/marlin/marlin_pst13_pc/mod.rs @@ -20,7 +20,6 @@ pub use data_structures::*; mod combinations; use combinations::*; -use crate::challenge::ChallengeGenerator; use ark_crypto_primitives::sponge::CryptographicSponge; #[cfg(feature = "parallel")] use rayon::prelude::*; @@ -440,7 +439,7 @@ where labeled_polynomials: impl IntoIterator>, _commitments: impl IntoIterator>, point: &P::Point, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rands: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result @@ -456,7 +455,7 @@ where Self::check_degrees_and_bounds(ck.supported_degree, &polynomial)?; // compute challenge^j and challenge^{j+1}. - let challenge_j = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + let challenge_j = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; p += (challenge_j, polynomial.polynomial()); r += (challenge_j, rand); @@ -538,7 +537,7 @@ where point: &'a P::Point, values: impl IntoIterator, proof: &Self::Proof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, _rng: Option<&mut dyn RngCore>, ) -> Result where @@ -550,7 +549,7 @@ where Marlin::::accumulate_commitments_and_values( commitments, values, - opening_challenges, + sponge, None, )?; // Compute both sides of the pairing equation @@ -582,7 +581,7 @@ where query_set: &QuerySet, values: &Evaluations, proof: &Self::BatchProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -593,7 +592,7 @@ where commitments, query_set, values, - opening_challenges, + sponge, None, )?; let check_time = @@ -660,7 +659,7 @@ where polynomials: impl IntoIterator>, commitments: impl IntoIterator>, query_set: &QuerySet, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> @@ -675,7 +674,7 @@ where polynomials, commitments, query_set, - opening_challenges, + sponge, rands, rng, ) @@ -690,7 +689,7 @@ where eqn_query_set: &QuerySet, eqn_evaluations: &Evaluations, proof: &BatchLCProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -703,7 +702,7 @@ where eqn_query_set, eqn_evaluations, proof, - opening_challenges, + sponge, rng, ) } diff --git a/poly-commit/src/marlin/mod.rs b/poly-commit/src/marlin/mod.rs index 4bd4fe27..4b4b9eed 100644 --- a/poly-commit/src/marlin/mod.rs +++ b/poly-commit/src/marlin/mod.rs @@ -1,4 +1,4 @@ -use crate::{challenge::ChallengeGenerator, CHALLENGE_SIZE}; +use crate::CHALLENGE_SIZE; use crate::{kzg10, Error}; use crate::{BTreeMap, BTreeSet, Debug, RngCore, String, ToString, Vec}; use crate::{BatchLCProof, LabeledPolynomial, LinearCombination}; @@ -110,7 +110,7 @@ where fn accumulate_commitments_and_values<'a>( commitments: impl IntoIterator>>, values: impl IntoIterator, - challenge_gen: &mut ChallengeGenerator, + sponge: &mut S, vk: Option<&marlin_pc::VerifierKey>, ) -> Result<(E::G1, E::ScalarField), Error> { let acc_time = start_timer!(|| "Accumulating commitments and values"); @@ -121,13 +121,14 @@ where let commitment = labeled_commitment.commitment(); assert_eq!(degree_bound.is_some(), commitment.shifted_comm.is_some()); - let challenge_i = challenge_gen.try_next_challenge_of_size(CHALLENGE_SIZE); + let challenge_i = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; combined_comm += &commitment.comm.0.mul(challenge_i); combined_value += &(value * &challenge_i); if let Some(degree_bound) = degree_bound { - let challenge_i_1 = challenge_gen.try_next_challenge_of_size(CHALLENGE_SIZE); + let challenge_i_1: E::ScalarField = + sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; let shifted_comm = commitment.shifted_comm.as_ref().unwrap().0.into_group(); @@ -152,7 +153,7 @@ where commitments: impl IntoIterator>>, query_set: &QuerySet, evaluations: &Evaluations, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, vk: Option<&marlin_pc::VerifierKey>, ) -> Result<(Vec>, Vec, Vec), Error> where @@ -199,7 +200,7 @@ where let (c, v) = Self::accumulate_commitments_and_values( comms_to_combine, values_to_combine, - opening_challenges, + sponge, vk, )?; end_timer!(lc_time); @@ -227,7 +228,7 @@ where polynomials: impl IntoIterator>, commitments: impl IntoIterator>, query_set: &QuerySet, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Error> @@ -308,7 +309,7 @@ where lc_polynomials.iter(), lc_commitments.iter(), &query_set, - opening_challenges, + sponge, lc_randomness.iter(), rng, )?; @@ -323,7 +324,7 @@ where query_set: &QuerySet, evaluations: &Evaluations, proof: &BatchLCProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -404,7 +405,7 @@ where &query_set, &evaluations, proof, - opening_challenges, + sponge, rng, ) } diff --git a/poly-commit/src/sonic_pc/mod.rs b/poly-commit/src/sonic_pc/mod.rs index b989b323..196fad21 100644 --- a/poly-commit/src/sonic_pc/mod.rs +++ b/poly-commit/src/sonic_pc/mod.rs @@ -12,7 +12,6 @@ use ark_std::rand::RngCore; use ark_std::{convert::TryInto, marker::PhantomData, ops::Div, ops::Mul, vec}; mod data_structures; -use crate::challenge::ChallengeGenerator; use ark_crypto_primitives::sponge::CryptographicSponge; pub use data_structures::*; @@ -47,12 +46,12 @@ where point: P::Point, values: impl IntoIterator, proof: &kzg10::Proof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, randomizer: Option, ) { let acc_time = start_timer!(|| "Accumulating elements"); - let mut curr_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + let mut curr_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; // Keeps track of running combination of values let mut combined_values = E::ScalarField::zero(); @@ -73,7 +72,7 @@ where // Accumulate values in the BTreeMap *combined_comms.entry(degree_bound).or_insert(E::G1::zero()) += &comm_with_challenge; - curr_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + curr_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; } // Push expected results into list of elems. Power will be the negative of the expected power @@ -345,7 +344,7 @@ where labeled_polynomials: impl IntoIterator>, _commitments: impl IntoIterator>, point: &'a P::Point, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rands: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result @@ -357,7 +356,7 @@ where let mut combined_polynomial = P::zero(); let mut combined_rand = kzg10::Randomness::empty(); - let mut curr_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + let mut curr_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; for (polynomial, rand) in labeled_polynomials.into_iter().zip(rands) { let enforced_degree_bounds: Option<&[usize]> = ck @@ -374,7 +373,7 @@ where combined_polynomial += (curr_challenge, polynomial.polynomial()); combined_rand += (curr_challenge, rand); - curr_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + curr_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; } let proof_time = start_timer!(|| "Creating proof for polynomials"); @@ -390,7 +389,7 @@ where point: &'a P::Point, values: impl IntoIterator, proof: &Self::Proof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, _rng: Option<&mut dyn RngCore>, ) -> Result where @@ -410,7 +409,7 @@ where *point, values, proof, - opening_challenges, + sponge, None, ); @@ -430,7 +429,7 @@ where query_set: &QuerySet, values: &Evaluations, proof: &Self::BatchProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -481,7 +480,7 @@ where *point, values_to_combine.into_iter(), p, - opening_challenges, + sponge, Some(randomizer), ); @@ -502,7 +501,7 @@ where polynomials: impl IntoIterator>, commitments: impl IntoIterator>, query_set: &QuerySet, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rands: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> @@ -581,7 +580,7 @@ where lc_polynomials.iter(), lc_commitments.iter(), &query_set, - opening_challenges, + sponge, lc_randomness.iter(), rng, )?; @@ -597,7 +596,7 @@ where eqn_query_set: &QuerySet, eqn_evaluations: &Evaluations, proof: &BatchLCProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -666,7 +665,7 @@ where &eqn_query_set, &evaluations, proof, - opening_challenges, + sponge, rng, ) } From 36dcf5e7c313b616661738f5e5eb6f947cc897ff Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Mon, 15 Jan 2024 19:52:47 +0100 Subject: [PATCH 16/20] Fix according to breaking changes in `ark-ec` (#141) * Fix for KZG10 * Fix the breaking changes in `ark-ec` * Remove the extra loop * Fix the loop range * re-use the preprocessing table * also re-use the preprocessing table for multilinear_pc --------- Co-authored-by: mmagician --- poly-commit/src/kzg10/mod.rs | 47 +- poly-commit/src/lib.rs | 632 +++++++++--------- poly-commit/src/marlin/marlin_pst13_pc/mod.rs | 32 +- poly-commit/src/multilinear_pc/mod.rs | 48 +- poly-commit/src/streaming_kzg/time.rs | 10 +- 5 files changed, 354 insertions(+), 415 deletions(-) diff --git a/poly-commit/src/kzg10/mod.rs b/poly-commit/src/kzg10/mod.rs index a6ea5752..47089685 100644 --- a/poly-commit/src/kzg10/mod.rs +++ b/poly-commit/src/kzg10/mod.rs @@ -8,7 +8,7 @@ use crate::{BTreeMap, Error, LabeledPolynomial, PCRandomness, ToString, Vec}; use ark_ec::AffineRepr; use ark_ec::{pairing::Pairing, CurveGroup}; -use ark_ec::{scalar_mul::fixed_base::FixedBase, VariableBaseMSM}; +use ark_ec::{scalar_mul::ScalarMul, VariableBaseMSM}; use ark_ff::{One, PrimeField, UniformRand, Zero}; use ark_poly::DenseUVPolynomial; use ark_std::{format, marker::PhantomData, ops::Div, ops::Mul, vec}; @@ -66,36 +66,27 @@ where let gamma_g = E::G1::rand(rng); let h = E::G2::rand(rng); + // powers_of_beta = [1, b, ..., b^(max_degree + 1)], len = max_degree + 2 let mut powers_of_beta = vec![E::ScalarField::one()]; - let mut cur = beta; - for _ in 0..max_degree { + for _ in 0..=max_degree { powers_of_beta.push(cur); cur *= β } - let window_size = FixedBase::get_mul_window_size(max_degree + 1); - - let scalar_bits = E::ScalarField::MODULUS_BIT_SIZE as usize; let g_time = start_timer!(|| "Generating powers of G"); - let g_table = FixedBase::get_window_table(scalar_bits, window_size, g); - let powers_of_g = - FixedBase::msm::(scalar_bits, window_size, &g_table, &powers_of_beta); + let powers_of_g = g.batch_mul(&powers_of_beta[0..max_degree + 1]); end_timer!(g_time); - let gamma_g_time = start_timer!(|| "Generating powers of gamma * G"); - let gamma_g_table = FixedBase::get_window_table(scalar_bits, window_size, gamma_g); - let mut powers_of_gamma_g = - FixedBase::msm::(scalar_bits, window_size, &gamma_g_table, &powers_of_beta); - // Add an additional power of gamma_g, because we want to be able to support - // up to D queries. - powers_of_gamma_g.push(powers_of_gamma_g.last().unwrap().mul(&beta)); - end_timer!(gamma_g_time); - let powers_of_g = E::G1::normalize_batch(&powers_of_g); - let powers_of_gamma_g = E::G1::normalize_batch(&powers_of_gamma_g) + // Use the entire `powers_of_beta`, since we want to be able to support + // up to D queries. + let gamma_g_time = start_timer!(|| "Generating powers of gamma * G"); + let powers_of_gamma_g = gamma_g + .batch_mul(&powers_of_beta) .into_iter() .enumerate() .collect(); + end_timer!(gamma_g_time); let neg_powers_of_h_time = start_timer!(|| "Generating negative powers of h in G2"); let neg_powers_of_h = if produce_g2_powers { @@ -106,20 +97,10 @@ where cur /= β } - let neg_h_table = FixedBase::get_window_table(scalar_bits, window_size, h); - let neg_powers_of_h = FixedBase::msm::( - scalar_bits, - window_size, - &neg_h_table, - &neg_powers_of_beta, - ); - - let affines = E::G2::normalize_batch(&neg_powers_of_h); - let mut affines_map = BTreeMap::new(); - affines.into_iter().enumerate().for_each(|(i, a)| { - affines_map.insert(i, a); - }); - affines_map + h.batch_mul(&neg_powers_of_beta) + .into_iter() + .enumerate() + .collect() } else { BTreeMap::new() }; diff --git a/poly-commit/src/lib.rs b/poly-commit/src/lib.rs index 23245476..599db692 100644 --- a/poly-commit/src/lib.rs +++ b/poly-commit/src/lib.rs @@ -656,83 +656,81 @@ pub mod tests { { let sponge = sponge(); - for __ in 0..1 { - let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); - let max_degree = 100; - let pp = PC::setup(max_degree, None, rng)?; - for _ in 0..10 { - let supported_degree = Uniform::from(1..=max_degree).sample(rng); - assert!( - max_degree >= supported_degree, - "max_degree < supported_degree" - ); - - let mut labels = Vec::new(); - let mut polynomials = Vec::new(); - let mut degree_bounds = Vec::new(); - - for i in 0..10 { - let label = format!("Test{}", i); - labels.push(label.clone()); - let degree_bound = 1usize; - let hiding_bound = Some(1); - degree_bounds.push(degree_bound); - - polynomials.push(LabeledPolynomial::new( - label, - rand_poly(supported_degree, None, rng), - Some(degree_bound), - hiding_bound, - )); - } + let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); + let max_degree = 100; + let pp = PC::setup(max_degree, None, rng)?; + for _ in 0..10 { + let supported_degree = Uniform::from(1..=max_degree).sample(rng); + assert!( + max_degree >= supported_degree, + "max_degree < supported_degree" + ); + + let mut labels = Vec::new(); + let mut polynomials = Vec::new(); + let mut degree_bounds = Vec::new(); + + for i in 0..10 { + let label = format!("Test{}", i); + labels.push(label.clone()); + let degree_bound = 1usize; + let hiding_bound = Some(1); + degree_bounds.push(degree_bound); + + polynomials.push(LabeledPolynomial::new( + label, + rand_poly(supported_degree, None, rng), + Some(degree_bound), + hiding_bound, + )); + } - let supported_hiding_bound = polynomials - .iter() - .map(|p| p.hiding_bound().unwrap_or(0)) - .max() - .unwrap_or(0); - println!("supported degree: {:?}", supported_degree); - println!("supported hiding bound: {:?}", supported_hiding_bound); - let (ck, vk) = PC::trim( - &pp, - supported_degree, - supported_hiding_bound, - Some(degree_bounds.as_slice()), - )?; - println!("Trimmed"); + let supported_hiding_bound = polynomials + .iter() + .map(|p| p.hiding_bound().unwrap_or(0)) + .max() + .unwrap_or(0); + println!("supported degree: {:?}", supported_degree); + println!("supported hiding bound: {:?}", supported_hiding_bound); + let (ck, vk) = PC::trim( + &pp, + supported_degree, + supported_hiding_bound, + Some(degree_bounds.as_slice()), + )?; + println!("Trimmed"); - let (comms, rands) = PC::commit(&ck, &polynomials, Some(rng))?; + let (comms, rands) = PC::commit(&ck, &polynomials, Some(rng))?; - let mut query_set = QuerySet::new(); - let mut values = Evaluations::new(); - let point = rand_point(None, rng); - for (i, label) in labels.iter().enumerate() { - query_set.insert((label.clone(), (format!("{}", i), point.clone()))); - let value = polynomials[i].evaluate(&point); - values.insert((label.clone(), point.clone()), value); - } - println!("Generated query set"); - - let proof = PC::batch_open( - &ck, - &polynomials, - &comms, - &query_set, - &mut (sponge.clone()), - &rands, - Some(rng), - )?; - let result = PC::batch_check( - &vk, - &comms, - &query_set, - &values, - &proof, - &mut (sponge.clone()), - rng, - )?; - assert!(result, "proof was incorrect, Query set: {:#?}", query_set); + let mut query_set = QuerySet::new(); + let mut values = Evaluations::new(); + let point = rand_point(None, rng); + for (i, label) in labels.iter().enumerate() { + query_set.insert((label.clone(), (format!("{}", i), point.clone()))); + let value = polynomials[i].evaluate(&point); + values.insert((label.clone(), point.clone()), value); } + println!("Generated query set"); + + let proof = PC::batch_open( + &ck, + &polynomials, + &comms, + &query_set, + &mut (sponge.clone()), + &rands, + Some(rng), + )?; + let result = PC::batch_check( + &vk, + &comms, + &query_set, + &values, + &proof, + &mut (sponge.clone()), + rng, + )?; + assert!(result, "proof was incorrect, Query set: {:#?}", query_set); } Ok(()) @@ -761,122 +759,121 @@ pub mod tests { let sponge = sponge(); - for _ in 0..1 { - let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); - // If testing multivariate polynomials, make the max degree lower - let max_degree = match num_vars { - Some(_) => max_degree.unwrap_or(Uniform::from(2..=10).sample(rng)), - None => max_degree.unwrap_or(Uniform::from(2..=64).sample(rng)), + let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); + // If testing multivariate polynomials, make the max degree lower + let max_degree = match num_vars { + Some(_) => max_degree.unwrap_or(Uniform::from(2..=10).sample(rng)), + None => max_degree.unwrap_or(Uniform::from(2..=64).sample(rng)), + }; + let pp = PC::setup(max_degree, num_vars, rng)?; + + for _ in 0..num_iters { + let supported_degree = + supported_degree.unwrap_or(Uniform::from(1..=max_degree).sample(rng)); + assert!( + max_degree >= supported_degree, + "max_degree < supported_degree" + ); + let mut polynomials: Vec> = Vec::new(); + let mut degree_bounds = if enforce_degree_bounds { + Some(Vec::new()) + } else { + None }; - let pp = PC::setup(max_degree, num_vars, rng)?; - - for __ in 0..num_iters { - let supported_degree = - supported_degree.unwrap_or(Uniform::from(1..=max_degree).sample(rng)); - assert!( - max_degree >= supported_degree, - "max_degree < supported_degree" - ); - let mut polynomials: Vec> = Vec::new(); - let mut degree_bounds = if enforce_degree_bounds { - Some(Vec::new()) + + let mut labels = Vec::new(); + println!("Sampled supported degree"); + + // Generate polynomials + let num_points_in_query_set = Uniform::from(1..=max_num_queries).sample(rng); + for i in 0..num_polynomials { + let label = format!("Test{}", i); + labels.push(label.clone()); + let degree = Uniform::from(1..=supported_degree).sample(rng); + let degree_bound = if let Some(degree_bounds) = &mut degree_bounds { + let range = Uniform::from(degree..=supported_degree); + let degree_bound = range.sample(rng); + degree_bounds.push(degree_bound); + Some(degree_bound) } else { None }; - let mut labels = Vec::new(); - println!("Sampled supported degree"); - - // Generate polynomials - let num_points_in_query_set = Uniform::from(1..=max_num_queries).sample(rng); - for i in 0..num_polynomials { - let label = format!("Test{}", i); - labels.push(label.clone()); - let degree = Uniform::from(1..=supported_degree).sample(rng); - let degree_bound = if let Some(degree_bounds) = &mut degree_bounds { - let range = Uniform::from(degree..=supported_degree); - let degree_bound = range.sample(rng); - degree_bounds.push(degree_bound); - Some(degree_bound) - } else { - None - }; - - let hiding_bound = if num_points_in_query_set >= degree { - Some(degree) - } else { - Some(num_points_in_query_set) - }; + let hiding_bound = if num_points_in_query_set >= degree { + Some(degree) + } else { + Some(num_points_in_query_set) + }; - polynomials.push(LabeledPolynomial::new( - label, - rand_poly(degree, num_vars, rng).into(), - degree_bound, - hiding_bound, - )) - } - let supported_hiding_bound = polynomials - .iter() - .map(|p| p.hiding_bound().unwrap_or(0)) - .max() - .unwrap_or(0); - println!("supported degree: {:?}", supported_degree); - println!("supported hiding bound: {:?}", supported_hiding_bound); - println!("num_points_in_query_set: {:?}", num_points_in_query_set); - let (ck, vk) = PC::trim( - &pp, - supported_degree, - supported_hiding_bound, - degree_bounds.as_ref().map(|s| s.as_slice()), - )?; - println!("Trimmed"); + polynomials.push(LabeledPolynomial::new( + label, + rand_poly(degree, num_vars, rng).into(), + degree_bound, + hiding_bound, + )) + } + let supported_hiding_bound = polynomials + .iter() + .map(|p| p.hiding_bound().unwrap_or(0)) + .max() + .unwrap_or(0); + println!("supported degree: {:?}", supported_degree); + println!("supported hiding bound: {:?}", supported_hiding_bound); + println!("num_points_in_query_set: {:?}", num_points_in_query_set); + let (ck, vk) = PC::trim( + &pp, + supported_degree, + supported_hiding_bound, + degree_bounds.as_ref().map(|s| s.as_slice()), + )?; + println!("Trimmed"); - let (comms, rands) = PC::commit(&ck, &polynomials, Some(rng))?; + let (comms, rands) = PC::commit(&ck, &polynomials, Some(rng))?; - // Construct query set - let mut query_set = QuerySet::new(); - let mut values = Evaluations::new(); - for _ in 0..num_points_in_query_set { - let point = rand_point(num_vars, rng); - for (i, label) in labels.iter().enumerate() { - query_set.insert((label.clone(), (format!("{}", i), point.clone()))); - let value = polynomials[i].evaluate(&point); - values.insert((label.clone(), point.clone()), value); - } + // Construct query set + let mut query_set = QuerySet::new(); + let mut values = Evaluations::new(); + for _ in 0..num_points_in_query_set { + let point = rand_point(num_vars, rng); + for (i, label) in labels.iter().enumerate() { + query_set.insert((label.clone(), (format!("{}", i), point.clone()))); + let value = polynomials[i].evaluate(&point); + values.insert((label.clone(), point.clone()), value); } - println!("Generated query set"); - - let proof = PC::batch_open( - &ck, - &polynomials, - &comms, - &query_set, - &mut (sponge.clone()), - &rands, - Some(rng), - )?; - let result = PC::batch_check( - &vk, - &comms, - &query_set, - &values, - &proof, - &mut (sponge.clone()), - rng, - )?; - if !result { - println!( - "Failed with {} polynomials, num_points_in_query_set: {:?}", - num_polynomials, num_points_in_query_set - ); - println!("Degree of polynomials:",); - for poly in polynomials { - println!("Degree: {:?}", poly.degree()); - } + } + println!("Generated query set"); + + let proof = PC::batch_open( + &ck, + &polynomials, + &comms, + &query_set, + &mut (sponge.clone()), + &rands, + Some(rng), + )?; + let result = PC::batch_check( + &vk, + &comms, + &query_set, + &values, + &proof, + &mut (sponge.clone()), + rng, + )?; + if !result { + println!( + "Failed with {} polynomials, num_points_in_query_set: {:?}", + num_polynomials, num_points_in_query_set + ); + println!("Degree of polynomials:",); + for poly in polynomials { + println!("Degree: {:?}", poly.degree()); } - assert!(result, "proof was incorrect, Query set: {:#?}", query_set); } + assert!(result, "proof was incorrect, Query set: {:#?}", query_set); } + Ok(()) } @@ -903,162 +900,161 @@ pub mod tests { let sponge = sponge(); - for __ in 0..1 { - let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); - // If testing multivariate polynomials, make the max degree lower - let max_degree = match num_vars { - Some(_) => max_degree.unwrap_or(Uniform::from(2..=10).sample(rng)), - None => max_degree.unwrap_or(Uniform::from(2..=64).sample(rng)), + let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); + // If testing multivariate polynomials, make the max degree lower + let max_degree = match num_vars { + Some(_) => max_degree.unwrap_or(Uniform::from(2..=10).sample(rng)), + None => max_degree.unwrap_or(Uniform::from(2..=64).sample(rng)), + }; + let pp = PC::setup(max_degree, num_vars, rng)?; + + for _ in 0..num_iters { + let supported_degree = + supported_degree.unwrap_or(Uniform::from(1..=max_degree).sample(rng)); + assert!( + max_degree >= supported_degree, + "max_degree < supported_degree" + ); + let mut polynomials = Vec::new(); + let mut degree_bounds = if enforce_degree_bounds { + Some(Vec::new()) + } else { + None }; - let pp = PC::setup(max_degree, num_vars, rng)?; - - for _ in 0..num_iters { - let supported_degree = - supported_degree.unwrap_or(Uniform::from(1..=max_degree).sample(rng)); - assert!( - max_degree >= supported_degree, - "max_degree < supported_degree" - ); - let mut polynomials = Vec::new(); - let mut degree_bounds = if enforce_degree_bounds { - Some(Vec::new()) + + let mut labels = Vec::new(); + println!("Sampled supported degree"); + + // Generate polynomials + let num_points_in_query_set = Uniform::from(1..=max_num_queries).sample(rng); + for i in 0..num_polynomials { + let label = format!("Test{}", i); + labels.push(label.clone()); + let degree = Uniform::from(1..=supported_degree).sample(rng); + let degree_bound = if let Some(degree_bounds) = &mut degree_bounds { + if rng.gen() { + let range = Uniform::from(degree..=supported_degree); + let degree_bound = range.sample(rng); + degree_bounds.push(degree_bound); + Some(degree_bound) + } else { + None + } } else { None }; - let mut labels = Vec::new(); - println!("Sampled supported degree"); - - // Generate polynomials - let num_points_in_query_set = Uniform::from(1..=max_num_queries).sample(rng); - for i in 0..num_polynomials { - let label = format!("Test{}", i); - labels.push(label.clone()); - let degree = Uniform::from(1..=supported_degree).sample(rng); - let degree_bound = if let Some(degree_bounds) = &mut degree_bounds { - if rng.gen() { - let range = Uniform::from(degree..=supported_degree); - let degree_bound = range.sample(rng); - degree_bounds.push(degree_bound); - Some(degree_bound) + let hiding_bound = if num_points_in_query_set >= degree { + Some(degree) + } else { + Some(num_points_in_query_set) + }; + println!("Hiding bound: {:?}", hiding_bound); + + polynomials.push(LabeledPolynomial::new( + label, + rand_poly(degree, num_vars, rng), + degree_bound, + hiding_bound, + )) + } + println!("supported degree: {:?}", supported_degree); + println!("num_points_in_query_set: {:?}", num_points_in_query_set); + println!("{:?}", degree_bounds); + println!("{}", num_polynomials); + println!("{}", enforce_degree_bounds); + + let (ck, vk) = PC::trim( + &pp, + supported_degree, + supported_degree, + degree_bounds.as_ref().map(|s| s.as_slice()), + )?; + println!("Trimmed"); + + let (comms, rands) = PC::commit(&ck, &polynomials, Some(rng))?; + + // Let's construct our equations + let mut linear_combinations = Vec::new(); + let mut query_set = QuerySet::new(); + let mut values = Evaluations::new(); + for i in 0..num_points_in_query_set { + let point = rand_point(num_vars, rng); + for j in 0..num_equations.unwrap() { + let label = format!("query {} eqn {}", i, j); + let mut lc = LinearCombination::empty(label.clone()); + + let mut value = F::zero(); + let should_have_degree_bounds: bool = rng.gen(); + for (k, label) in labels.iter().enumerate() { + if should_have_degree_bounds { + value += &polynomials[k].evaluate(&point); + lc.push((F::one(), label.to_string().into())); + break; } else { - None - } - } else { - None - }; - - let hiding_bound = if num_points_in_query_set >= degree { - Some(degree) - } else { - Some(num_points_in_query_set) - }; - println!("Hiding bound: {:?}", hiding_bound); - - polynomials.push(LabeledPolynomial::new( - label, - rand_poly(degree, num_vars, rng), - degree_bound, - hiding_bound, - )) - } - println!("supported degree: {:?}", supported_degree); - println!("num_points_in_query_set: {:?}", num_points_in_query_set); - println!("{:?}", degree_bounds); - println!("{}", num_polynomials); - println!("{}", enforce_degree_bounds); - - let (ck, vk) = PC::trim( - &pp, - supported_degree, - supported_degree, - degree_bounds.as_ref().map(|s| s.as_slice()), - )?; - println!("Trimmed"); - - let (comms, rands) = PC::commit(&ck, &polynomials, Some(rng))?; - - // Let's construct our equations - let mut linear_combinations = Vec::new(); - let mut query_set = QuerySet::new(); - let mut values = Evaluations::new(); - for i in 0..num_points_in_query_set { - let point = rand_point(num_vars, rng); - for j in 0..num_equations.unwrap() { - let label = format!("query {} eqn {}", i, j); - let mut lc = LinearCombination::empty(label.clone()); - - let mut value = F::zero(); - let should_have_degree_bounds: bool = rng.gen(); - for (k, label) in labels.iter().enumerate() { - if should_have_degree_bounds { - value += &polynomials[k].evaluate(&point); - lc.push((F::one(), label.to_string().into())); - break; + let poly = &polynomials[k]; + if poly.degree_bound().is_some() { + continue; } else { - let poly = &polynomials[k]; - if poly.degree_bound().is_some() { - continue; - } else { - assert!(poly.degree_bound().is_none()); - let coeff = F::rand(rng); - value += &(coeff * poly.evaluate(&point)); - lc.push((coeff, label.to_string().into())); - } + assert!(poly.degree_bound().is_none()); + let coeff = F::rand(rng); + value += &(coeff * poly.evaluate(&point)); + lc.push((coeff, label.to_string().into())); } } - values.insert((label.clone(), point.clone()), value); - if !lc.is_empty() { - linear_combinations.push(lc); - // Insert query - query_set.insert((label.clone(), (format!("{}", i), point.clone()))); - } } - } - if linear_combinations.is_empty() { - continue; - } - println!("Generated query set"); - println!("Linear combinations: {:?}", linear_combinations); - - let proof = PC::open_combinations( - &ck, - &linear_combinations, - &polynomials, - &comms, - &query_set, - &mut (sponge.clone()), - &rands, - Some(rng), - )?; - println!("Generated proof"); - let result = PC::check_combinations( - &vk, - &linear_combinations, - &comms, - &query_set, - &values, - &proof, - &mut (sponge.clone()), - rng, - )?; - if !result { - println!( - "Failed with {} polynomials, num_points_in_query_set: {:?}", - num_polynomials, num_points_in_query_set - ); - println!("Degree of polynomials:",); - for poly in polynomials { - println!("Degree: {:?}", poly.degree()); + values.insert((label.clone(), point.clone()), value); + if !lc.is_empty() { + linear_combinations.push(lc); + // Insert query + query_set.insert((label.clone(), (format!("{}", i), point.clone()))); } } - assert!( - result, - "proof was incorrect, equations: {:#?}", - linear_combinations + } + if linear_combinations.is_empty() { + continue; + } + println!("Generated query set"); + println!("Linear combinations: {:?}", linear_combinations); + + let proof = PC::open_combinations( + &ck, + &linear_combinations, + &polynomials, + &comms, + &query_set, + &mut (sponge.clone()), + &rands, + Some(rng), + )?; + println!("Generated proof"); + let result = PC::check_combinations( + &vk, + &linear_combinations, + &comms, + &query_set, + &values, + &proof, + &mut (sponge.clone()), + rng, + )?; + if !result { + println!( + "Failed with {} polynomials, num_points_in_query_set: {:?}", + num_polynomials, num_points_in_query_set ); + println!("Degree of polynomials:",); + for poly in polynomials { + println!("Degree: {:?}", poly.degree()); + } } + assert!( + result, + "proof was incorrect, equations: {:#?}", + linear_combinations + ); } + Ok(()) } diff --git a/poly-commit/src/marlin/marlin_pst13_pc/mod.rs b/poly-commit/src/marlin/marlin_pst13_pc/mod.rs index 14b48052..96855bd4 100644 --- a/poly-commit/src/marlin/marlin_pst13_pc/mod.rs +++ b/poly-commit/src/marlin/marlin_pst13_pc/mod.rs @@ -8,7 +8,11 @@ use crate::{LabeledCommitment, LabeledPolynomial, LinearCombination}; use crate::{PCRandomness, PCUniversalParams, PolynomialCommitment}; use crate::{ToString, Vec}; use ark_ec::AffineRepr; -use ark_ec::{pairing::Pairing, scalar_mul::fixed_base::FixedBase, CurveGroup, VariableBaseMSM}; +use ark_ec::{ + pairing::Pairing, + scalar_mul::{BatchMulPreprocessing, ScalarMul}, + CurveGroup, VariableBaseMSM, +}; use ark_ff::{One, PrimeField, UniformRand, Zero}; use ark_poly::{multivariate::Term, DenseMVPolynomial}; use ark_std::rand::RngCore; @@ -210,47 +214,33 @@ where }) .unzip(); - let scalar_bits = E::ScalarField::MODULUS_BIT_SIZE as usize; let g_time = start_timer!(|| "Generating powers of G"); - let window_size = FixedBase::get_mul_window_size(max_degree + 1); - let g_table = FixedBase::get_window_table(scalar_bits, window_size, g); - let mut powers_of_g = - FixedBase::msm::(scalar_bits, window_size, &g_table, &powers_of_beta); - powers_of_g.push(g); + let mut powers_of_g = g.batch_mul(&powers_of_beta); + powers_of_g.push(g.into_affine()); powers_of_beta_terms.push(P::Term::new(vec![])); end_timer!(g_time); let gamma_g_time = start_timer!(|| "Generating powers of gamma * G"); - let window_size = FixedBase::get_mul_window_size(max_degree + 2); - let gamma_g_table = FixedBase::get_window_table(scalar_bits, window_size, gamma_g); // Each element `i` of `powers_of_gamma_g` is a vector of length `max_degree+1` // containing `betas[i]^j \gamma G` for `j` from 1 to `max_degree+1` to support // up to `max_degree` queries let mut powers_of_gamma_g = vec![Vec::new(); num_vars]; + let gamma_g_table = BatchMulPreprocessing::new(gamma_g, max_degree + 1); + ark_std::cfg_iter_mut!(powers_of_gamma_g) .enumerate() .for_each(|(i, v)| { - let mut powers_of_beta = Vec::with_capacity(max_degree); + let mut powers_of_beta = Vec::with_capacity(max_degree + 1); let mut cur = E::ScalarField::one(); for _ in 0..=max_degree { cur *= &betas[i]; powers_of_beta.push(cur); } - *v = FixedBase::msm::( - scalar_bits, - window_size, - &gamma_g_table, - &powers_of_beta, - ); + *v = gamma_g.batch_mul_with_preprocessing(&powers_of_beta, &gamma_g_table); }); end_timer!(gamma_g_time); - let powers_of_g = E::G1::normalize_batch(&powers_of_g); let gamma_g = gamma_g.into_affine(); - let powers_of_gamma_g = powers_of_gamma_g - .into_iter() - .map(|v| E::G1::normalize_batch(&v)) - .collect(); let beta_h: Vec<_> = betas.iter().map(|b| h.mul(b).into_affine()).collect(); let h = h.into_affine(); let prepared_h = h.into(); diff --git a/poly-commit/src/multilinear_pc/mod.rs b/poly-commit/src/multilinear_pc/mod.rs index bd5d3e53..94ea74cc 100644 --- a/poly-commit/src/multilinear_pc/mod.rs +++ b/poly-commit/src/multilinear_pc/mod.rs @@ -1,9 +1,10 @@ use crate::multilinear_pc::data_structures::{ Commitment, CommitterKey, Proof, UniversalParams, VerifierKey, }; +use ark_ec::scalar_mul::BatchMulPreprocessing; use ark_ec::AffineRepr; use ark_ec::{pairing::Pairing, CurveGroup}; -use ark_ec::{scalar_mul::fixed_base::FixedBase, VariableBaseMSM}; +use ark_ec::{scalar_mul::ScalarMul, VariableBaseMSM}; use ark_ff::{Field, PrimeField}; use ark_ff::{One, Zero}; use ark_poly::{DenseMultilinearExtension, MultilinearExtension}; @@ -27,14 +28,11 @@ impl MultilinearPC { /// setup pub fn setup(num_vars: usize, rng: &mut R) -> UniversalParams { assert!(num_vars > 0, "constant polynomial not supported"); - let g: E::G1 = E::G1::rand(rng); - let h: E::G2 = E::G2::rand(rng); - let g = g.into_affine(); - let h = h.into_affine(); + let g = E::G1::rand(rng); + let h = E::G2::rand(rng); let mut powers_of_g = Vec::new(); let mut powers_of_h = Vec::new(); let t: Vec<_> = (0..num_vars).map(|_| E::ScalarField::rand(rng)).collect(); - let scalar_bits = E::ScalarField::MODULUS_BIT_SIZE as usize; let mut eq: LinkedList> = LinkedList::from_iter(eq_extension(&t).into_iter()); @@ -54,29 +52,15 @@ impl MultilinearPC { } let mut pp_powers = Vec::new(); - let mut total_scalars = 0; for i in 0..num_vars { let eq = eq_arr.pop_front().unwrap(); let pp_k_powers = (0..(1 << (num_vars - i))).map(|x| eq[x]); pp_powers.extend(pp_k_powers); - total_scalars += 1 << (num_vars - i); } - let window_size = FixedBase::get_mul_window_size(total_scalars); - let g_table = FixedBase::get_window_table(scalar_bits, window_size, g.into_group()); - let h_table = FixedBase::get_window_table(scalar_bits, window_size, h.into_group()); - - let pp_g = E::G1::normalize_batch(&FixedBase::msm( - scalar_bits, - window_size, - &g_table, - &pp_powers, - )); - let pp_h = E::G2::normalize_batch(&FixedBase::msm( - scalar_bits, - window_size, - &h_table, - &pp_powers, - )); + + let g_table = BatchMulPreprocessing::new(g, num_vars); + let pp_g = g.batch_mul_with_preprocessing(&pp_powers, &g_table); + let pp_h = h.batch_mul(&pp_powers); let mut start = 0; for i in 0..num_vars { let size = 1 << (num_vars - i); @@ -89,18 +73,14 @@ impl MultilinearPC { // uncomment to measure the time for calculating vp // let vp_generation_timer = start_timer!(|| "VP generation"); - let g_mask = { - let window_size = FixedBase::get_mul_window_size(num_vars); - let g_table = FixedBase::get_window_table(scalar_bits, window_size, g.into_group()); - E::G1::normalize_batch(&FixedBase::msm(scalar_bits, window_size, &g_table, &t)) - }; + let g_mask = g.batch_mul_with_preprocessing(&t, &g_table); // end_timer!(vp_generation_timer); UniversalParams { num_vars, - g, + g: g.into_affine(), g_mask, - h, + h: h.into_affine(), powers_of_g, powers_of_h, } @@ -199,11 +179,7 @@ impl MultilinearPC { ) -> bool { let left = E::pairing(commitment.g_product.into_group() - &vk.g.mul(value), vk.h); - let scalar_size = E::ScalarField::MODULUS_BIT_SIZE as usize; - let window_size = FixedBase::get_mul_window_size(vk.nv); - - let g_table = FixedBase::get_window_table(scalar_size, window_size, vk.g.into_group()); - let g_mul: Vec = FixedBase::msm(scalar_size, window_size, &g_table, point); + let g_mul = vk.g.into_group().batch_mul(point); let pairing_lefts: Vec<_> = (0..vk.nv) .map(|i| vk.g_mask_random[i].into_group() - &g_mul[i]) diff --git a/poly-commit/src/streaming_kzg/time.rs b/poly-commit/src/streaming_kzg/time.rs index 8c7fa2f8..b8d52093 100644 --- a/poly-commit/src/streaming_kzg/time.rs +++ b/poly-commit/src/streaming_kzg/time.rs @@ -1,9 +1,9 @@ //! An impementation of a time-efficient version of Kate et al's polynomial commitment, //! with optimization from [\[BDFG20\]](https://eprint.iacr.org/2020/081.pdf). use ark_ec::pairing::Pairing; -use ark_ec::scalar_mul::fixed_base::FixedBase; +use ark_ec::scalar_mul::ScalarMul; use ark_ec::CurveGroup; -use ark_ff::{PrimeField, Zero}; +use ark_ff::Zero; use ark_poly::{univariate::DensePolynomial, DenseUVPolynomial}; use ark_std::{borrow::Borrow, ops::Div, ops::Mul, rand::RngCore, vec::Vec, UniformRand}; @@ -50,11 +50,7 @@ impl CommitterKey { let powers_of_tau = powers(tau, max_degree + 1); let g = E::G1::rand(rng); - let window_size = FixedBase::get_mul_window_size(max_degree + 1); - let scalar_bits = E::ScalarField::MODULUS_BIT_SIZE as usize; - let g_table = FixedBase::get_window_table(scalar_bits, window_size, g); - let powers_of_g_proj = FixedBase::msm(scalar_bits, window_size, &g_table, &powers_of_tau); - let powers_of_g = E::G1::normalize_batch(&powers_of_g_proj); + let powers_of_g = g.batch_mul(&powers_of_tau); let g2 = E::G2::rand(rng).into_affine(); let powers_of_g2 = powers_of_tau From f6a0c13bf44d7d1776f238bc9afabeab3c5a9511 Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Tue, 16 Jan 2024 03:17:30 +0100 Subject: [PATCH 17/20] Auxiliary opening data (#134) * Add the trait bounds * Add `CommitmentState` * Update benches for the new type * Fix the name of local variable * Merge `PCCommitmentState` with `PCRandomness` * Update `README.md` * Fix a bug * Put `Randomness` in `CommitmentState` * Add a comment * Remove the extra loop * Update the comment for `CommitmentState` Co-authored-by: Marcin * cargo fmt --------- Co-authored-by: Marcin --- README.md | 6 +-- bench-templates/src/lib.rs | 12 ++--- poly-commit/src/data_structures.rs | 12 +++-- poly-commit/src/ipa_pc/data_structures.rs | 3 +- poly-commit/src/ipa_pc/mod.rs | 46 +++++++++---------- poly-commit/src/kzg10/data_structures.rs | 3 +- poly-commit/src/kzg10/mod.rs | 2 +- poly-commit/src/lib.rs | 41 +++++++++-------- .../src/marlin/marlin_pc/data_structures.rs | 7 +-- poly-commit/src/marlin/marlin_pc/mod.rs | 38 +++++++-------- .../marlin/marlin_pst13_pc/data_structures.rs | 5 +- poly-commit/src/marlin/marlin_pst13_pc/mod.rs | 20 ++++---- poly-commit/src/marlin/mod.rs | 20 ++++---- poly-commit/src/sonic_pc/mod.rs | 36 +++++++-------- 14 files changed, 130 insertions(+), 121 deletions(-) diff --git a/README.md b/README.md index 833b2892..82c3e9a6 100644 --- a/README.md +++ b/README.md @@ -128,11 +128,11 @@ let (ck, vk) = PCS::trim(&pp, degree, 2, Some(&[degree])).unwrap(); // 3. PolynomialCommitment::commit // The prover commits to the polynomial using their committer key `ck`. -let (comms, rands) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); +let (comms, states) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); // 4a. PolynomialCommitment::open // Opening proof at a single point. -let proof_single = PCS::open(&ck, [&labeled_poly], &comms, &point_1, &mut (test_sponge.clone()), &rands, None).unwrap(); +let proof_single = PCS::open(&ck, [&labeled_poly], &comms, &point_1, &mut (test_sponge.clone()), &states, None).unwrap(); // 5a. PolynomialCommitment::check // Verifying the proof at a single point, given the commitment, the point, the claimed evaluation, and the proof. @@ -154,7 +154,7 @@ let proof_batched = PCS::batch_open( &comms, &query_set, &mut (test_sponge.clone()), - &rands, + &states, Some(rng), ).unwrap(); diff --git a/bench-templates/src/lib.rs b/bench-templates/src/lib.rs index 6fc2e8bd..9451c313 100644 --- a/bench-templates/src/lib.rs +++ b/bench-templates/src/lib.rs @@ -114,7 +114,7 @@ where let labeled_poly = LabeledPolynomial::new("test".to_string(), rand_poly(num_vars, rng), None, None); - let (coms, randomness) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); + let (coms, states) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); let point = P::Point::rand(rng); let start = Instant::now(); @@ -124,7 +124,7 @@ where &coms, &point, &mut test_sponge(), - &randomness, + &states, Some(rng), ) .unwrap(); @@ -148,7 +148,7 @@ where let labeled_poly = LabeledPolynomial::new("test".to_string(), rand_poly(num_vars, rng), None, None); - let (coms, randomness) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); + let (coms, states) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); let point = P::Point::rand(rng); let proofs = PCS::open( @@ -157,7 +157,7 @@ where &coms, &point, &mut test_sponge(), - &randomness, + &states, Some(rng), ) .unwrap(); @@ -185,7 +185,7 @@ where let labeled_poly = LabeledPolynomial::new("test".to_string(), rand_poly(num_vars, rng), None, None); - let (coms, randomness) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); + let (coms, states) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); let point = P::Point::rand(rng); let claimed_eval = labeled_poly.evaluate(&point); let proof = PCS::open( @@ -194,7 +194,7 @@ where &coms, &point, &mut test_sponge(), - &randomness, + &states, Some(rng), ) .unwrap(); diff --git a/poly-commit/src/data_structures.rs b/poly-commit/src/data_structures.rs index 4a5eec21..2b942ee1 100644 --- a/poly-commit/src/data_structures.rs +++ b/poly-commit/src/data_structures.rs @@ -70,9 +70,12 @@ pub trait PCPreparedCommitment: Clone { fn prepare(comm: &UNPREPARED) -> Self; } -/// Defines the minimal interface of commitment randomness for any polynomial -/// commitment scheme. -pub trait PCRandomness: Clone + CanonicalSerialize + CanonicalDeserialize { +/// Defines the minimal interface of commitment state for any polynomial +/// commitment scheme. It might be randomness etc. +pub trait PCCommitmentState: Clone + CanonicalSerialize + CanonicalDeserialize { + /// This is the type of `Randomness` that the `rand` method returns + type Randomness: Clone + CanonicalSerialize + CanonicalDeserialize; + /// Outputs empty randomness that does not hide the commitment. fn empty() -> Self; @@ -86,9 +89,8 @@ pub trait PCRandomness: Clone + CanonicalSerialize + CanonicalDeserialize { has_degree_bound: bool, num_vars: Option, rng: &mut R, - ) -> Self; + ) -> Self::Randomness; } - /// A proof of satisfaction of linear combinations. #[derive(Clone, CanonicalSerialize, CanonicalDeserialize)] pub struct BatchLCProof { diff --git a/poly-commit/src/ipa_pc/data_structures.rs b/poly-commit/src/ipa_pc/data_structures.rs index 7ba56c95..84fcb7f2 100644 --- a/poly-commit/src/ipa_pc/data_structures.rs +++ b/poly-commit/src/ipa_pc/data_structures.rs @@ -146,7 +146,8 @@ pub struct Randomness { pub shifted_rand: Option, } -impl PCRandomness for Randomness { +impl PCCommitmentState for Randomness { + type Randomness = Self; fn empty() -> Self { Self { rand: G::ScalarField::zero(), diff --git a/poly-commit/src/ipa_pc/mod.rs b/poly-commit/src/ipa_pc/mod.rs index 652a54c0..43a40852 100644 --- a/poly-commit/src/ipa_pc/mod.rs +++ b/poly-commit/src/ipa_pc/mod.rs @@ -1,7 +1,7 @@ use crate::{BTreeMap, BTreeSet, String, ToString, Vec, CHALLENGE_SIZE}; use crate::{BatchLCProof, DenseUVPolynomial, Error, Evaluations, QuerySet}; use crate::{LabeledCommitment, LabeledPolynomial, LinearCombination}; -use crate::{PCCommitterKey, PCRandomness, PCUniversalParams, PolynomialCommitment}; +use crate::{PCCommitmentState, PCCommitterKey, PCUniversalParams, PolynomialCommitment}; use ark_ec::{AffineRepr, CurveGroup, VariableBaseMSM}; use ark_ff::{Field, One, PrimeField, UniformRand, Zero}; @@ -347,7 +347,7 @@ where type CommitterKey = CommitterKey; type VerifierKey = VerifierKey; type Commitment = Commitment; - type Randomness = Randomness; + type CommitmentState = Randomness; type Proof = Proof; type BatchProof = Vec; type Error = Error; @@ -418,7 +418,7 @@ where ) -> Result< ( Vec>, - Vec, + Vec, ), Self::Error, > @@ -427,7 +427,7 @@ where { let rng = &mut crate::optional_rng::OptionalRng(rng); let mut comms = Vec::new(); - let mut rands = Vec::new(); + let mut states = Vec::new(); let commit_time = start_timer!(|| "Committing to polynomials"); for labeled_polynomial in polynomials { @@ -446,7 +446,7 @@ where hiding_bound, )); - let randomness = if let Some(h) = hiding_bound { + let state = if let Some(h) = hiding_bound { Randomness::rand(h, degree_bound.is_some(), None, rng) } else { Randomness::empty() @@ -456,7 +456,7 @@ where &ck.comm_key[..(polynomial.degree() + 1)], &polynomial.coeffs(), Some(ck.s), - Some(randomness.rand), + Some(state.rand), ) .into(); @@ -465,7 +465,7 @@ where &ck.comm_key[(ck.supported_degree() - d)..], &polynomial.coeffs(), Some(ck.s), - randomness.shifted_rand, + state.shifted_rand, ) .into() }); @@ -474,13 +474,13 @@ where let labeled_comm = LabeledCommitment::new(label.to_string(), commitment, degree_bound); comms.push(labeled_comm); - rands.push(randomness); + states.push(state); end_timer!(commit_time); } end_timer!(commit_time); - Ok((comms, rands)) + Ok((comms, states)) } fn open<'a>( @@ -489,12 +489,12 @@ where commitments: impl IntoIterator>, point: &'a P::Point, sponge: &mut S, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result where Self::Commitment: 'a, - Self::Randomness: 'a, + Self::CommitmentState: 'a, P: 'a, { let mut combined_polynomial = P::zero(); @@ -504,15 +504,15 @@ where let mut has_hiding = false; let polys_iter = labeled_polynomials.into_iter(); - let rands_iter = rands.into_iter(); + let states_iter = states.into_iter(); let comms_iter = commitments.into_iter(); let combine_time = start_timer!(|| "Combining polynomials, randomness, and commitments."); let mut cur_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; - for (labeled_polynomial, (labeled_commitment, randomness)) in - polys_iter.zip(comms_iter.zip(rands_iter)) + for (labeled_polynomial, (labeled_commitment, state)) in + polys_iter.zip(comms_iter.zip(states_iter)) { let label = labeled_polynomial.label(); assert_eq!(labeled_polynomial.label(), labeled_commitment.label()); @@ -528,7 +528,7 @@ where if hiding_bound.is_some() { has_hiding = true; - combined_rand += &(cur_challenge * &randomness.rand); + combined_rand += &(cur_challenge * &state.rand); } cur_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; @@ -554,7 +554,7 @@ where combined_commitment_proj += &commitment.shifted_comm.unwrap().mul(cur_challenge); if hiding_bound.is_some() { - let shifted_rand = randomness.shifted_rand; + let shifted_rand = state.shifted_rand; assert!( shifted_rand.is_some(), "shifted_rand.is_none() for {}", @@ -870,23 +870,23 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, sponge: &mut S, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> where - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, P: 'a, { let label_poly_map = polynomials .into_iter() - .zip(rands) + .zip(states) .zip(commitments) - .map(|((p, r), c)| (p.label(), (p, r, c))) + .map(|((p, s), c)| (p.label(), (p, s, c))) .collect::>(); let mut lc_polynomials = Vec::new(); - let mut lc_randomness = Vec::new(); + let mut lc_states = Vec::new(); let mut lc_commitments = Vec::new(); let mut lc_info = Vec::new(); @@ -944,7 +944,7 @@ where let lc_poly = LabeledPolynomial::new(lc_label.clone(), poly, degree_bound, hiding_bound); lc_polynomials.push(lc_poly); - lc_randomness.push(Randomness { + lc_states.push(Randomness { rand: combined_rand, shifted_rand: combined_shifted_rand, }); @@ -965,7 +965,7 @@ where lc_commitments.iter(), &query_set, sponge, - lc_randomness.iter(), + lc_states.iter(), rng, )?; Ok(BatchLCProof { proof, evals: None }) diff --git a/poly-commit/src/kzg10/data_structures.rs b/poly-commit/src/kzg10/data_structures.rs index 60626e70..d648f19f 100644 --- a/poly-commit/src/kzg10/data_structures.rs +++ b/poly-commit/src/kzg10/data_structures.rs @@ -420,7 +420,8 @@ impl> Randomness { } } -impl> PCRandomness for Randomness { +impl> PCCommitmentState for Randomness { + type Randomness = Self; fn empty() -> Self { Self { blinding_polynomial: P::zero(), diff --git a/poly-commit/src/kzg10/mod.rs b/poly-commit/src/kzg10/mod.rs index 47089685..508db2cb 100644 --- a/poly-commit/src/kzg10/mod.rs +++ b/poly-commit/src/kzg10/mod.rs @@ -5,7 +5,7 @@ //! proposed by Kate, Zaverucha, and Goldberg ([KZG10](http://cacr.uwaterloo.ca/techreports/2010/cacr2010-10.pdf)). //! This construction achieves extractability in the algebraic group model (AGM). -use crate::{BTreeMap, Error, LabeledPolynomial, PCRandomness, ToString, Vec}; +use crate::{BTreeMap, Error, LabeledPolynomial, PCCommitmentState, ToString, Vec}; use ark_ec::AffineRepr; use ark_ec::{pairing::Pairing, CurveGroup}; use ark_ec::{scalar_mul::ScalarMul, VariableBaseMSM}; diff --git a/poly-commit/src/lib.rs b/poly-commit/src/lib.rs index 599db692..8ebb9710 100644 --- a/poly-commit/src/lib.rs +++ b/poly-commit/src/lib.rs @@ -153,8 +153,11 @@ pub trait PolynomialCommitment, S: Cryptographic type VerifierKey: PCVerifierKey; /// The commitment to a polynomial. type Commitment: PCCommitment + Default; - /// The commitment randomness. - type Randomness: PCRandomness; + /// Auxiliary state of the commitment, output by the `commit` phase. + /// It contains information that can be reused by the committer + /// during the `open` phase, such as the commitment randomness. + /// Not to be shared with the verifier. + type CommitmentState: PCCommitmentState; /// The evaluation proof for a single point. type Proof: Clone; /// The evaluation proof for a query set. @@ -200,7 +203,7 @@ pub trait PolynomialCommitment, S: Cryptographic ) -> Result< ( Vec>, - Vec, + Vec, ), Self::Error, > @@ -214,12 +217,12 @@ pub trait PolynomialCommitment, S: Cryptographic commitments: impl IntoIterator>, point: &'a P::Point, sponge: &mut S, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result where P: 'a, - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a; /// check but with individual challenges @@ -250,12 +253,12 @@ pub trait PolynomialCommitment, S: Cryptographic commitments: impl IntoIterator>, query_set: &QuerySet, sponge: &mut S, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result where P: 'a, - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, { // The default implementation achieves proceeds by rearranging the queries in @@ -263,16 +266,16 @@ pub trait PolynomialCommitment, S: Cryptographic // the same point, then opening their commitments simultaneously with a // single call to `open` (per point) let rng = &mut crate::optional_rng::OptionalRng(rng); - let poly_rand_comm: BTreeMap<_, _> = labeled_polynomials + let poly_st_comm: BTreeMap<_, _> = labeled_polynomials .into_iter() - .zip(rands) + .zip(states) .zip(commitments.into_iter()) - .map(|((poly, r), comm)| (poly.label(), (poly, r, comm))) + .map(|((poly, st), comm)| (poly.label(), (poly, st, comm))) .collect(); let open_time = start_timer!(|| format!( "Opening {} polynomials at query set of size {}", - poly_rand_comm.len(), + poly_st_comm.len(), query_set.len(), )); @@ -295,20 +298,20 @@ pub trait PolynomialCommitment, S: Cryptographic let mut proofs = Vec::new(); for (_point_label, (point, labels)) in query_to_labels_map.into_iter() { let mut query_polys: Vec<&'a LabeledPolynomial<_, _>> = Vec::new(); - let mut query_rands: Vec<&'a Self::Randomness> = Vec::new(); + let mut query_states: Vec<&'a Self::CommitmentState> = Vec::new(); let mut query_comms: Vec<&'a LabeledCommitment> = Vec::new(); // Constructing matching vectors with the polynomial, commitment // randomness and actual commitment for each polynomial being // queried at `point` for label in labels { - let (polynomial, rand, comm) = - poly_rand_comm.get(label).ok_or(Error::MissingPolynomial { + let (polynomial, state, comm) = + poly_st_comm.get(label).ok_or(Error::MissingPolynomial { label: label.to_string(), })?; query_polys.push(polynomial); - query_rands.push(rand); + query_states.push(state); query_comms.push(comm); } @@ -322,7 +325,7 @@ pub trait PolynomialCommitment, S: Cryptographic query_comms, &point, sponge, - query_rands, + query_states, Some(rng), )?; @@ -427,11 +430,11 @@ pub trait PolynomialCommitment, S: Cryptographic commitments: impl IntoIterator>, query_set: &QuerySet, sponge: &mut S, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> where - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, P: 'a, { @@ -453,7 +456,7 @@ pub trait PolynomialCommitment, S: Cryptographic commitments, &poly_query_set, sponge, - rands, + states, rng, )?; Ok(BatchLCProof { diff --git a/poly-commit/src/marlin/marlin_pc/data_structures.rs b/poly-commit/src/marlin/marlin_pc/data_structures.rs index 2b09e03a..203e3201 100644 --- a/poly-commit/src/marlin/marlin_pc/data_structures.rs +++ b/poly-commit/src/marlin/marlin_pc/data_structures.rs @@ -1,6 +1,6 @@ use crate::{ - DenseUVPolynomial, PCCommitment, PCCommitterKey, PCPreparedCommitment, PCPreparedVerifierKey, - PCRandomness, PCVerifierKey, Vec, + DenseUVPolynomial, PCCommitment, PCCommitmentState, PCCommitterKey, PCPreparedCommitment, + PCPreparedVerifierKey, PCVerifierKey, Vec, }; use ark_ec::pairing::Pairing; use ark_ec::AdditiveGroup; @@ -360,7 +360,8 @@ impl<'a, F: PrimeField, P: DenseUVPolynomial> AddAssign<(F, &'a Randomness> PCRandomness for Randomness { +impl> PCCommitmentState for Randomness { + type Randomness = Self; fn empty() -> Self { Self { rand: kzg10::Randomness::empty(), diff --git a/poly-commit/src/marlin/marlin_pc/mod.rs b/poly-commit/src/marlin/marlin_pc/mod.rs index 622e12bd..7fbfba07 100644 --- a/poly-commit/src/marlin/marlin_pc/mod.rs +++ b/poly-commit/src/marlin/marlin_pc/mod.rs @@ -2,7 +2,7 @@ use crate::{kzg10, marlin::Marlin, PCCommitterKey, CHALLENGE_SIZE}; use crate::{BTreeMap, BTreeSet, ToString, Vec}; use crate::{BatchLCProof, Error, Evaluations, QuerySet}; use crate::{LabeledCommitment, LabeledPolynomial, LinearCombination}; -use crate::{PCRandomness, PCUniversalParams, PolynomialCommitment}; +use crate::{PCCommitmentState, PCUniversalParams, PolynomialCommitment}; use ark_ec::pairing::Pairing; use ark_ec::AffineRepr; use ark_ec::CurveGroup; @@ -65,7 +65,7 @@ where type CommitterKey = CommitterKey; type VerifierKey = VerifierKey; type Commitment = Commitment; - type Randomness = Randomness; + type CommitmentState = Randomness; type Proof = kzg10::Proof; type BatchProof = Vec; type Error = Error; @@ -179,7 +179,7 @@ where ) -> Result< ( Vec>, - Vec, + Vec, ), Self::Error, > @@ -190,7 +190,7 @@ where let commit_time = start_timer!(|| "Committing to polynomials"); let mut commitments = Vec::new(); - let mut randomness = Vec::new(); + let mut states = Vec::new(); for p in polynomials { let label = p.label(); @@ -231,17 +231,17 @@ where }; let comm = Commitment { comm, shifted_comm }; - let rand = Randomness { rand, shifted_rand }; + let state = Randomness { rand, shifted_rand }; commitments.push(LabeledCommitment::new( label.to_string(), comm, degree_bound, )); - randomness.push(rand); + states.push(state); end_timer!(commit_time); } end_timer!(commit_time); - Ok((commitments, randomness)) + Ok((commitments, states)) } /// On input a polynomial `p` and a point `point`, outputs a proof for the same. @@ -251,12 +251,12 @@ where _commitments: impl IntoIterator>, point: &'a P::Point, sponge: &mut S, - rands: impl IntoIterator, + states: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result where P: 'a, - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, { let mut p = P::zero(); @@ -266,7 +266,7 @@ where let mut shifted_r_witness = P::zero(); let mut enforce_degree_bound = false; - for (polynomial, rand) in labeled_polynomials.into_iter().zip(rands) { + for (polynomial, rand) in labeled_polynomials.into_iter().zip(states) { let degree_bound = polynomial.degree_bound(); assert_eq!(degree_bound.is_some(), rand.shifted_rand.is_some()); @@ -407,12 +407,12 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, sponge: &mut S, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> where P: 'a, - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, { Marlin::::open_combinations( @@ -422,7 +422,7 @@ where commitments, query_set, sponge, - rands, + states, rng, ) } @@ -462,18 +462,18 @@ where commitments: impl IntoIterator>>, query_set: &QuerySet, sponge: &mut S, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result>, Error> where P: 'a, - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, { let rng = &mut crate::optional_rng::OptionalRng(rng); let poly_rand_comm: BTreeMap<_, _> = labeled_polynomials .into_iter() - .zip(rands) + .zip(states) .zip(commitments.into_iter()) .map(|((poly, r), comm)| (poly.label(), (poly, r, comm))) .collect(); @@ -496,7 +496,7 @@ where let mut proofs = Vec::new(); for (_point_label, (point, labels)) in query_to_labels_map.into_iter() { let mut query_polys: Vec<&'a LabeledPolynomial<_, _>> = Vec::new(); - let mut query_rands: Vec<&'a Self::Randomness> = Vec::new(); + let mut query_states: Vec<&'a Self::CommitmentState> = Vec::new(); let mut query_comms: Vec<&'a LabeledCommitment> = Vec::new(); for label in labels { @@ -506,7 +506,7 @@ where })?; query_polys.push(polynomial); - query_rands.push(rand); + query_states.push(rand); query_comms.push(comm); } @@ -517,7 +517,7 @@ where query_comms, point, sponge, - query_rands, + query_states, Some(rng), )?; diff --git a/poly-commit/src/marlin/marlin_pst13_pc/data_structures.rs b/poly-commit/src/marlin/marlin_pst13_pc/data_structures.rs index 8ccf300b..9cc8d73b 100644 --- a/poly-commit/src/marlin/marlin_pst13_pc/data_structures.rs +++ b/poly-commit/src/marlin/marlin_pst13_pc/data_structures.rs @@ -1,6 +1,6 @@ use crate::{BTreeMap, Vec}; use crate::{ - PCCommitterKey, PCPreparedVerifierKey, PCRandomness, PCUniversalParams, PCVerifierKey, + PCCommitmentState, PCCommitterKey, PCPreparedVerifierKey, PCUniversalParams, PCVerifierKey, }; use ark_ec::pairing::Pairing; use ark_poly::DenseMVPolynomial; @@ -362,12 +362,13 @@ where } } -impl PCRandomness for Randomness +impl PCCommitmentState for Randomness where E: Pairing, P: DenseMVPolynomial, P::Point: Index, { + type Randomness = Self; fn empty() -> Self { Self { blinding_polynomial: P::zero(), diff --git a/poly-commit/src/marlin/marlin_pst13_pc/mod.rs b/poly-commit/src/marlin/marlin_pst13_pc/mod.rs index 96855bd4..a825a9b5 100644 --- a/poly-commit/src/marlin/marlin_pst13_pc/mod.rs +++ b/poly-commit/src/marlin/marlin_pst13_pc/mod.rs @@ -5,7 +5,7 @@ use crate::{ }; use crate::{BatchLCProof, Error, Evaluations, QuerySet}; use crate::{LabeledCommitment, LabeledPolynomial, LinearCombination}; -use crate::{PCRandomness, PCUniversalParams, PolynomialCommitment}; +use crate::{PCCommitmentState, PCUniversalParams, PolynomialCommitment}; use crate::{ToString, Vec}; use ark_ec::AffineRepr; use ark_ec::{ @@ -154,7 +154,7 @@ where type CommitterKey = CommitterKey; type VerifierKey = VerifierKey; type Commitment = marlin_pc::Commitment; - type Randomness = Randomness; + type CommitmentState = Randomness; type Proof = Proof; type BatchProof = Vec; type Error = Error; @@ -332,7 +332,7 @@ where ) -> Result< ( Vec>, - Vec, + Vec, ), Self::Error, > @@ -430,25 +430,25 @@ where _commitments: impl IntoIterator>, point: &P::Point, sponge: &mut S, - rands: impl IntoIterator, + states: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result where P: 'a, - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, { // Compute random linear combinations of committed polynomials and randomness let mut p = P::zero(); let mut r = Randomness::empty(); - for (polynomial, rand) in labeled_polynomials.into_iter().zip(rands) { + for (polynomial, state) in labeled_polynomials.into_iter().zip(states) { Self::check_degrees_and_bounds(ck.supported_degree, &polynomial)?; // compute challenge^j and challenge^{j+1}. let challenge_j = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; p += (challenge_j, polynomial.polynomial()); - r += (challenge_j, rand); + r += (challenge_j, state); } let open_time = start_timer!(|| format!("Opening polynomial of degree {}", p.degree())); @@ -650,12 +650,12 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, sponge: &mut S, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> where P: 'a, - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, { Marlin::::open_combinations( @@ -665,7 +665,7 @@ where commitments, query_set, sponge, - rands, + states, rng, ) } diff --git a/poly-commit/src/marlin/mod.rs b/poly-commit/src/marlin/mod.rs index 4b4b9eed..d7e7f5a1 100644 --- a/poly-commit/src/marlin/mod.rs +++ b/poly-commit/src/marlin/mod.rs @@ -3,7 +3,7 @@ use crate::{kzg10, Error}; use crate::{BTreeMap, BTreeSet, Debug, RngCore, String, ToString, Vec}; use crate::{BatchLCProof, LabeledPolynomial, LinearCombination}; use crate::{Evaluations, LabeledCommitment, QuerySet}; -use crate::{PCRandomness, Polynomial, PolynomialCommitment}; +use crate::{PCCommitmentState, Polynomial, PolynomialCommitment}; use ark_crypto_primitives::sponge::CryptographicSponge; use ark_ec::pairing::Pairing; use ark_ec::AffineRepr; @@ -229,7 +229,7 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, sponge: &mut S, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Error> where @@ -242,18 +242,18 @@ where Commitment = marlin_pc::Commitment, Error = Error, >, - PC::Randomness: 'a + AddAssign<(E::ScalarField, &'a PC::Randomness)>, + PC::CommitmentState: 'a + AddAssign<(E::ScalarField, &'a PC::CommitmentState)>, PC::Commitment: 'a, { let label_map = polynomials .into_iter() - .zip(rands) + .zip(states) .zip(commitments) .map(|((p, r), c)| (p.label(), (p, r, c))) .collect::>(); let mut lc_polynomials = Vec::new(); - let mut lc_randomness = Vec::new(); + let mut lc_states: Vec = Vec::new(); let mut lc_commitments = Vec::new(); let mut lc_info = Vec::new(); @@ -263,13 +263,13 @@ where let mut degree_bound = None; let mut hiding_bound = None; - let mut randomness = PC::Randomness::empty(); + let mut randomness = PC::CommitmentState::empty(); let mut coeffs_and_comms = Vec::new(); let num_polys = lc.len(); for (coeff, label) in lc.iter().filter(|(_, l)| !l.is_one()) { let label: &String = label.try_into().expect("cannot be one!"); - let &(cur_poly, cur_rand, cur_comm) = + let &(cur_poly, cur_state, cur_comm) = label_map.get(label).ok_or(Error::MissingPolynomial { label: label.to_string(), })?; @@ -285,14 +285,14 @@ where // Some(_) > None, always. hiding_bound = core::cmp::max(hiding_bound, cur_poly.hiding_bound()); poly += (*coeff, cur_poly.polynomial()); - randomness += (*coeff, cur_rand); + randomness += (*coeff, cur_state); coeffs_and_comms.push((*coeff, cur_comm.commitment())); } let lc_poly = LabeledPolynomial::new(lc_label.clone(), poly, degree_bound, hiding_bound); lc_polynomials.push(lc_poly); - lc_randomness.push(randomness); + lc_states.push(randomness); lc_commitments.push(Self::combine_commitments(coeffs_and_comms)); lc_info.push((lc_label, degree_bound)); } @@ -310,7 +310,7 @@ where lc_commitments.iter(), &query_set, sponge, - lc_randomness.iter(), + lc_states.iter(), rng, )?; diff --git a/poly-commit/src/sonic_pc/mod.rs b/poly-commit/src/sonic_pc/mod.rs index 196fad21..caf9b79c 100644 --- a/poly-commit/src/sonic_pc/mod.rs +++ b/poly-commit/src/sonic_pc/mod.rs @@ -2,7 +2,7 @@ use crate::{kzg10, PCCommitterKey, CHALLENGE_SIZE}; use crate::{BTreeMap, BTreeSet, String, ToString, Vec}; use crate::{BatchLCProof, DenseUVPolynomial, Error, Evaluations, QuerySet}; use crate::{LabeledCommitment, LabeledPolynomial, LinearCombination}; -use crate::{PCRandomness, PCUniversalParams, PolynomialCommitment}; +use crate::{PCCommitmentState, PCUniversalParams, PolynomialCommitment}; use ark_ec::AffineRepr; use ark_ec::CurveGroup; @@ -145,7 +145,7 @@ where type CommitterKey = CommitterKey; type VerifierKey = VerifierKey; type Commitment = Commitment; - type Randomness = Randomness; + type CommitmentState = Randomness; type Proof = kzg10::Proof; type BatchProof = Vec; type Error = Error; @@ -280,7 +280,7 @@ where ) -> Result< ( Vec>, - Vec, + Vec, ), Self::Error, > @@ -290,7 +290,7 @@ where let rng = &mut crate::optional_rng::OptionalRng(rng); let commit_time = start_timer!(|| "Committing to polynomials"); let mut labeled_comms: Vec> = Vec::new(); - let mut randomness: Vec = Vec::new(); + let mut randomness: Vec = Vec::new(); for labeled_polynomial in polynomials { let enforced_degree_bounds: Option<&[usize]> = ck @@ -345,11 +345,11 @@ where _commitments: impl IntoIterator>, point: &'a P::Point, sponge: &mut S, - rands: impl IntoIterator, + states: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result where - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, P: 'a, { @@ -358,7 +358,7 @@ where let mut curr_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; - for (polynomial, rand) in labeled_polynomials.into_iter().zip(rands) { + for (polynomial, state) in labeled_polynomials.into_iter().zip(states) { let enforced_degree_bounds: Option<&[usize]> = ck .enforced_degree_bounds .as_ref() @@ -372,7 +372,7 @@ where )?; combined_polynomial += (curr_challenge, polynomial.polynomial()); - combined_rand += (curr_challenge, rand); + combined_rand += (curr_challenge, state); curr_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; } @@ -502,23 +502,23 @@ where commitments: impl IntoIterator>, query_set: &QuerySet, sponge: &mut S, - rands: impl IntoIterator, + states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> where - Self::Randomness: 'a, + Self::CommitmentState: 'a, Self::Commitment: 'a, P: 'a, { let label_map = polynomials .into_iter() - .zip(rands) + .zip(states) .zip(commitments) - .map(|((p, r), c)| (p.label(), (p, r, c))) + .map(|((p, s), c)| (p.label(), (p, s, c))) .collect::>(); let mut lc_polynomials = Vec::new(); - let mut lc_randomness = Vec::new(); + let mut lc_states = Vec::new(); let mut lc_commitments = Vec::new(); let mut lc_info = Vec::new(); @@ -527,13 +527,13 @@ where let mut poly = P::zero(); let mut degree_bound = None; let mut hiding_bound = None; - let mut randomness = Self::Randomness::empty(); + let mut state = Self::CommitmentState::empty(); let mut comm = E::G1::zero(); let num_polys = lc.len(); for (coeff, label) in lc.iter().filter(|(_, l)| !l.is_one()) { let label: &String = label.try_into().expect("cannot be one!"); - let &(cur_poly, cur_rand, curr_comm) = + let &(cur_poly, cur_state, curr_comm) = label_map.get(label).ok_or(Error::MissingPolynomial { label: label.to_string(), })?; @@ -552,14 +552,14 @@ where // Some(_) > None, always. hiding_bound = core::cmp::max(hiding_bound, cur_poly.hiding_bound()); poly += (*coeff, cur_poly.polynomial()); - randomness += (*coeff, cur_rand); + state += (*coeff, cur_state); comm += &curr_comm.commitment().0.mul(*coeff); } let lc_poly = LabeledPolynomial::new(lc_label.clone(), poly, degree_bound, hiding_bound); lc_polynomials.push(lc_poly); - lc_randomness.push(randomness); + lc_states.push(state); lc_commitments.push(comm); lc_info.push((lc_label, degree_bound)); } @@ -581,7 +581,7 @@ where lc_commitments.iter(), &query_set, sponge, - lc_randomness.iter(), + lc_states.iter(), rng, )?; Ok(BatchLCProof { proof, evals: None }) From 12f5529c9ca609d07dd4683fcd1e196bc375eb0d Mon Sep 17 00:00:00 2001 From: Marcin Date: Wed, 17 Jan 2024 05:43:54 +0100 Subject: [PATCH 18/20] `batch_mul_with_preprocessing` no longer takes `self` as argument (#142) * batch_mul_with_preprocessing no longer takes `self` as argument * Apply suggestions from code review Co-authored-by: Pratyush Mishra * fix variable name --------- Co-authored-by: Pratyush Mishra --- poly-commit/src/marlin/marlin_pst13_pc/mod.rs | 2 +- poly-commit/src/multilinear_pc/mod.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/poly-commit/src/marlin/marlin_pst13_pc/mod.rs b/poly-commit/src/marlin/marlin_pst13_pc/mod.rs index a825a9b5..eee026d7 100644 --- a/poly-commit/src/marlin/marlin_pst13_pc/mod.rs +++ b/poly-commit/src/marlin/marlin_pst13_pc/mod.rs @@ -236,7 +236,7 @@ where cur *= &betas[i]; powers_of_beta.push(cur); } - *v = gamma_g.batch_mul_with_preprocessing(&powers_of_beta, &gamma_g_table); + *v = gamma_g_table.batch_mul(&powers_of_beta); }); end_timer!(gamma_g_time); diff --git a/poly-commit/src/multilinear_pc/mod.rs b/poly-commit/src/multilinear_pc/mod.rs index 94ea74cc..cff20eb5 100644 --- a/poly-commit/src/multilinear_pc/mod.rs +++ b/poly-commit/src/multilinear_pc/mod.rs @@ -59,7 +59,7 @@ impl MultilinearPC { } let g_table = BatchMulPreprocessing::new(g, num_vars); - let pp_g = g.batch_mul_with_preprocessing(&pp_powers, &g_table); + let pp_g = g_table.batch_mul(&pp_powers); let pp_h = h.batch_mul(&pp_powers); let mut start = 0; for i in 0..num_vars { @@ -73,7 +73,7 @@ impl MultilinearPC { // uncomment to measure the time for calculating vp // let vp_generation_timer = start_timer!(|| "VP generation"); - let g_mask = g.batch_mul_with_preprocessing(&t, &g_table); + let g_mask = g_table.batch_mul(&t); // end_timer!(vp_generation_timer); UniversalParams { From 428ded7e1ed0defc0d486885c975c488471f65da Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Thu, 18 Jan 2024 11:45:07 +0100 Subject: [PATCH 19/20] Remove ChallengeGenerator for Ligero (#56) * Squash and merge `delete-chalgen` onto here * Fix for `ChallengeGenerator` * Delete `IOPTranscript` for Hyrax (#55) * Use the sponge generic and rearrange `use`s * Use sponge instead of `IOPTransript` * Fix benches --- README.md | 12 +- bench-templates/src/lib.rs | 10 +- poly-commit/benches/hyrax_times.rs | 3 +- poly-commit/src/challenge.rs | 61 ---------- poly-commit/src/constraints.rs | 20 ++-- poly-commit/src/hyrax/mod.rs | 107 ++++++++---------- poly-commit/src/hyrax/tests.rs | 82 +++++++------- poly-commit/src/ipa_pc/mod.rs | 43 +++---- poly-commit/src/lib.rs | 68 ++++------- poly-commit/src/marlin/marlin_pc/mod.rs | 27 +++-- poly-commit/src/marlin/marlin_pst13_pc/mod.rs | 21 ++-- poly-commit/src/marlin/mod.rs | 21 ++-- poly-commit/src/sonic_pc/mod.rs | 29 +++-- .../src/streaming_kzg/data_structures.rs | 9 +- poly-commit/src/utils.rs | 73 +----------- 15 files changed, 204 insertions(+), 382 deletions(-) delete mode 100644 poly-commit/src/challenge.rs diff --git a/README.md b/README.md index 4c2dc28f..64c2ea2f 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ This trait defines the interface for a polynomial commitment scheme. It is recom // In this example, we will commit to a single polynomial, open it first at one point, and then batched at two points, and finally verify the proofs. // We will use the KZG10 polynomial commitment scheme, following the approach from Marlin. -use ark_poly_commit::{Polynomial, marlin_pc::MarlinKZG10, LabeledPolynomial, PolynomialCommitment, QuerySet, Evaluations, challenge::ChallengeGenerator}; +use ark_poly_commit::{Polynomial, marlin_pc::MarlinKZG10, LabeledPolynomial, PolynomialCommitment, QuerySet, Evaluations}; use ark_bls12_377::Bls12_377; use ark_crypto_primitives::sponge::poseidon::{PoseidonSponge, PoseidonConfig}; use ark_crypto_primitives::sponge::CryptographicSponge; @@ -130,15 +130,13 @@ let (ck, vk) = PCS::trim(&pp, degree, 2, Some(&[degree])).unwrap(); // The prover commits to the polynomial using their committer key `ck`. let (comms, states) = PCS::commit(&ck, [&labeled_poly], Some(rng)).unwrap(); -let challenge_generator: ChallengeGenerator<::ScalarField, Sponge_Bls12_377> = ChallengeGenerator::new_univariate(&mut test_sponge); - // 4a. PolynomialCommitment::open // Opening proof at a single point. -let proof_single = PCS::open(&ck, [&labeled_poly], &comms, &point_1, &mut (challenge_generator.clone()), &states, None).unwrap(); +let proof_single = PCS::open(&ck, [&labeled_poly], &comms, &point_1, &mut (test_sponge.clone()), &states, None).unwrap(); // 5a. PolynomialCommitment::check // Verifying the proof at a single point, given the commitment, the point, the claimed evaluation, and the proof. -assert!(PCS::check(&vk, &comms, &point_1, [secret_poly.evaluate(&point_1)], &proof_single, &mut (challenge_generator.clone()), Some(rng)).unwrap()); +assert!(PCS::check(&vk, &comms, &point_1, [secret_poly.evaluate(&point_1)], &proof_single, &mut (test_sponge.clone()), Some(rng)).unwrap()); let mut query_set = QuerySet::new(); let mut values = Evaluations::new(); @@ -155,7 +153,7 @@ let proof_batched = PCS::batch_open( [&labeled_poly], &comms, &query_set, - &mut (challenge_generator.clone()), + &mut (test_sponge.clone()), &states, Some(rng), ).unwrap(); @@ -167,7 +165,7 @@ assert!(PCS::batch_check( &query_set, &values, &proof_batched, - &mut (challenge_generator.clone()), + &mut (test_sponge.clone()), rng, ).unwrap()); ``` diff --git a/bench-templates/src/lib.rs b/bench-templates/src/lib.rs index a284d100..8a656589 100644 --- a/bench-templates/src/lib.rs +++ b/bench-templates/src/lib.rs @@ -11,7 +11,7 @@ use rand_chacha::{rand_core::SeedableRng, ChaCha20Rng}; use core::time::Duration; use std::time::Instant; -use ark_poly_commit::{challenge::ChallengeGenerator, LabeledPolynomial, PolynomialCommitment}; +use ark_poly_commit::{LabeledPolynomial, PolynomialCommitment}; pub use criterion::*; pub use paste::paste; @@ -132,7 +132,7 @@ where [&labeled_poly], &coms, &point, - &mut ChallengeGenerator::new_univariate(&mut test_sponge()), + &mut test_sponge(), &states, Some(rng), ) @@ -165,7 +165,7 @@ where [&labeled_poly], &coms, &point, - &mut ChallengeGenerator::new_univariate(&mut test_sponge()), + &mut test_sponge(), &states, Some(rng), ) @@ -202,7 +202,7 @@ where [&labeled_poly], &coms, &point, - &mut ChallengeGenerator::new_univariate(&mut test_sponge()), + &mut test_sponge(), &states, Some(rng), ) @@ -215,7 +215,7 @@ where &point, [claimed_eval], &proof, - &mut ChallengeGenerator::new_univariate(&mut test_sponge()), + &mut test_sponge(), None, ) .unwrap(); diff --git a/poly-commit/benches/hyrax_times.rs b/poly-commit/benches/hyrax_times.rs index 7f579cab..c76753df 100644 --- a/poly-commit/benches/hyrax_times.rs +++ b/poly-commit/benches/hyrax_times.rs @@ -1,3 +1,4 @@ +use ark_crypto_primitives::sponge::poseidon::PoseidonSponge; use ark_pcs_bench_templates::*; use ark_poly::{DenseMultilinearExtension, MultilinearExtension}; @@ -8,7 +9,7 @@ use ark_poly_commit::hyrax::HyraxPC; use rand_chacha::ChaCha20Rng; // Hyrax PCS over BN254 -type Hyrax254 = HyraxPC>; +type Hyrax254 = HyraxPC, PoseidonSponge>; fn rand_poly_hyrax( num_vars: usize, diff --git a/poly-commit/src/challenge.rs b/poly-commit/src/challenge.rs deleted file mode 100644 index 23b3c9d1..00000000 --- a/poly-commit/src/challenge.rs +++ /dev/null @@ -1,61 +0,0 @@ -use ark_crypto_primitives::sponge::{CryptographicSponge, FieldElementSize}; -use ark_ff::PrimeField; - -/// `ChallengeGenerator` generates opening challenges using multivariate or univariate strategy. -/// For multivariate strategy, each challenge is freshly squeezed from a sponge. -/// For univariate strategy, each challenge is a power of one squeezed element from sponge. -/// -/// Note that mutable reference cannot be cloned. -#[derive(Clone)] -pub enum ChallengeGenerator { - /// Each challenge is freshly squeezed from a sponge. - Multivariate(S), - /// Each challenge is a power of one squeezed element from sponge. - /// - /// `Univariate(generator, next_element)` - Univariate(F, F), -} - -impl ChallengeGenerator { - /// Returns a challenge generator with multivariate strategy. Each challenge is freshly squeezed - /// from a sponge. - pub fn new_multivariate(sponge: S) -> Self { - Self::Multivariate(sponge) - } - - /// Returns a challenge generator with univariate strategy. Each challenge is a power of one - /// squeezed element from sponge. - pub fn new_univariate(sponge: &mut S) -> Self { - let gen = sponge.squeeze_field_elements(1)[0]; - Self::Univariate(gen, gen) - } - - /// Returns a challenge of size `size`. - /// * If `self == Self::Multivariate(...)`, then this squeezes out a challenge of size `size`. - /// * If `self == Self::Univariate(...)`, then this ignores the `size` argument and simply squeezes out - /// the next field element. - pub fn try_next_challenge_of_size(&mut self, size: FieldElementSize) -> F { - match self { - // multivariate (full) - Self::Multivariate(sponge) => sponge.squeeze_field_elements_with_sizes(&[size])[0], - // univariate - Self::Univariate(gen, next) => { - let result = next.clone(); - *next *= *gen; - result - } - } - } - /// Returns the next challenge generated. - pub fn next_challenge(&mut self) -> F { - self.try_next_challenge_of_size(FieldElementSize::Full) - } - - /// Returns the sponge state if `self` is multivariate. Returns `None` otherwise. - pub fn into_sponge(self) -> Option { - match self { - Self::Multivariate(s) => Some(s), - _ => None, - } - } -} diff --git a/poly-commit/src/constraints.rs b/poly-commit/src/constraints.rs index e6fb5d4f..1300509a 100644 --- a/poly-commit/src/constraints.rs +++ b/poly-commit/src/constraints.rs @@ -5,7 +5,7 @@ use crate::{ use ark_crypto_primitives::sponge::CryptographicSponge; use ark_ff::PrimeField; use ark_poly::Polynomial; -use ark_r1cs_std::fields::nonnative::NonNativeFieldVar; +use ark_r1cs_std::fields::emulated_fp::EmulatedFpVar; use ark_r1cs_std::{fields::fp::FpVar, prelude::*}; use ark_relations::r1cs::{ConstraintSystemRef, Namespace, Result as R1CSResult, SynthesisError}; use ark_std::{borrow::Borrow, cmp::Eq, cmp::PartialEq, hash::Hash, marker::Sized}; @@ -24,8 +24,8 @@ pub enum LinearCombinationCoeffVar), + /// Other coefficient, represented as a "emulated" field element. + Var(EmulatedFpVar), } /// An allocated version of `LinearCombination`. @@ -60,7 +60,7 @@ impl let (f, lc_term) = term; let fg = - NonNativeFieldVar::new_variable(ark_relations::ns!(cs, "term"), || Ok(f), mode) + EmulatedFpVar::new_variable(ark_relations::ns!(cs, "term"), || Ok(f), mode) .unwrap(); (LinearCombinationCoeffVar::Var(fg), lc_term.clone()) @@ -79,12 +79,12 @@ impl pub struct PCCheckRandomDataVar { /// Opening challenges. /// The prover and the verifier MUST use the same opening challenges. - pub opening_challenges: Vec>, + pub opening_challenges: Vec>, /// Bit representations of the opening challenges. pub opening_challenges_bits: Vec>>, /// Batching random numbers. /// The verifier can choose these numbers freely, as long as they are random. - pub batching_rands: Vec>, + pub batching_rands: Vec>, /// Bit representations of the batching random numbers. pub batching_rands_bits: Vec>>, } @@ -172,7 +172,7 @@ pub struct LabeledPointVar { /// MUST be a unique identifier in a query set. pub name: String, /// The point value. - pub value: NonNativeFieldVar, + pub value: EmulatedFpVar, } /// An allocated version of `QuerySet`. @@ -184,7 +184,7 @@ pub struct QuerySetVar( /// An allocated version of `Evaluations`. #[derive(Clone)] pub struct EvaluationsVar( - pub HashMap, NonNativeFieldVar>, + pub HashMap, EmulatedFpVar>, ); impl EvaluationsVar { @@ -192,8 +192,8 @@ impl EvaluationsVar, - ) -> Result, SynthesisError> { + point: &EmulatedFpVar, + ) -> Result, SynthesisError> { let key = LabeledPointVar:: { name: String::from(lc_string), value: point.clone(), diff --git a/poly-commit/src/hyrax/mod.rs b/poly-commit/src/hyrax/mod.rs index e169b91c..d5536137 100644 --- a/poly-commit/src/hyrax/mod.rs +++ b/poly-commit/src/hyrax/mod.rs @@ -1,30 +1,26 @@ -mod data_structures; -mod utils; -pub use data_structures::*; - -#[cfg(test)] -mod tests; - -use ark_crypto_primitives::sponge::poseidon::PoseidonSponge; +use crate::hyrax::utils::tensor_prime; +use crate::to_bytes; +use crate::utils::{inner_product, scalar_by_vector, vector_sum, Matrix}; +use crate::{ + hyrax::utils::flat_to_matrix_column_major, Error, LabeledCommitment, LabeledPolynomial, + PolynomialCommitment, +}; +use ark_crypto_primitives::sponge::{Absorb, CryptographicSponge}; use ark_ec::{AffineRepr, CurveGroup, VariableBaseMSM}; use ark_ff::PrimeField; use ark_poly::MultilinearExtension; -use ark_std::{rand::RngCore, string::ToString, vec::Vec, UniformRand}; +use ark_std::{marker::PhantomData, rand::RngCore, string::ToString, vec::Vec, UniformRand}; use blake2::Blake2s256; -use core::marker::PhantomData; use digest::Digest; #[cfg(feature = "parallel")] use rayon::prelude::*; -use crate::hyrax::utils::tensor_prime; -use crate::utils::{inner_product, scalar_by_vector, vector_sum, IOPTranscript, Matrix}; - -use crate::{ - challenge::ChallengeGenerator, hyrax::utils::flat_to_matrix_column_major, Error, - LabeledCommitment, LabeledPolynomial, PolynomialCommitment, -}; - +mod data_structures; +pub use data_structures::*; +#[cfg(test)] +mod tests; +mod utils; /// String of bytes used to seed the randomness during the setup function. /// Note that the latter should never be used in production environments. pub const PROTOCOL_NAME: &'static [u8] = b"Hyrax protocol"; @@ -70,11 +66,18 @@ pub struct HyraxPC< G: AffineRepr, // A polynomial type representing multilinear polynomials P: MultilinearExtension, + // The sponge used in the protocol as random oracle + S: CryptographicSponge, > { - _phantom: PhantomData<(G, P)>, + _phantom: PhantomData<(G, P, S)>, } -impl> HyraxPC { +impl HyraxPC +where + G: AffineRepr, + P: MultilinearExtension, + S: CryptographicSponge, +{ /// Pedersen commitment to a vector of scalars as described in appendix A.1 /// of the reference article. /// The caller must either directly pass hiding exponent `r` inside Some, @@ -116,13 +119,12 @@ impl> HyraxPC { } } -impl> - PolynomialCommitment< - G::ScalarField, - P, - // Dummy sponge - required by the trait, not used in this implementation - PoseidonSponge, - > for HyraxPC +impl PolynomialCommitment for HyraxPC +where + G: AffineRepr, + G::ScalarField: Absorb, + P: MultilinearExtension, + S: CryptographicSponge, { type UniversalParams = HyraxUniversalParams; type CommitterKey = HyraxCommitterKey; @@ -295,19 +297,12 @@ impl> /// polynomial. /// - The number of variables of a polynomial doesn't match that of the /// point. - /// - /// # Disregarded arguments - /// - `opening_challenges` fn open<'a>( ck: &Self::CommitterKey, labeled_polynomials: impl IntoIterator>, commitments: impl IntoIterator>, point: &'a P::Point, - // Not used and not generic on the cryptographic sponge S - _opening_challenges: &mut ChallengeGenerator< - G::ScalarField, - PoseidonSponge, - >, + sponge: &mut S, states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result @@ -364,17 +359,14 @@ impl> }); } - // Initialising the transcript - let mut transcript: IOPTranscript = IOPTranscript::new(b"transcript"); - // Absorbing public parameters - transcript.append_serializable_element(b"public parameters", ck)?; + sponge.absorb(&to_bytes!(ck).map_err(|_| Error::TranscriptError)?); // Absorbing the commitment to the polynomial - transcript.append_serializable_element(b"commitment", &com.row_coms)?; + sponge.absorb(&to_bytes!(&com.row_coms).map_err(|_| Error::TranscriptError)?); // Absorbing the point - transcript.append_serializable_element(b"point", point)?; + sponge.absorb(point); // Commiting to the matrix formed by the polynomial coefficients let t = &state.mat; @@ -408,15 +400,15 @@ impl> let (com_b, r_b) = Self::pedersen_commit(ck, &[b], None, Some(rng_inner)); // Absorbing the commitment to the evaluation - transcript.append_serializable_element(b"com_eval", &com_eval)?; + sponge.absorb(&to_bytes!(&com_eval).map_err(|_| Error::TranscriptError)?); // Absorbing the two auxiliary commitments - transcript.append_serializable_element(b"com_d", &com_d)?; - transcript.append_serializable_element(b"com_b", &com_b)?; + sponge.absorb(&to_bytes!(&com_d).map_err(|_| Error::TranscriptError)?); + sponge.absorb(&to_bytes!(&com_b).map_err(|_| Error::TranscriptError)?); // Receive the random challenge c from the verifier, i.e. squeeze // it from the transcript. - let c = transcript.get_and_append_challenge(b"c").unwrap(); + let c = sponge.squeeze_field_elements(1)[0]; let z = vector_sum(&d, &scalar_by_vector(c, <)); let z_d = c * r_lt + r_d; @@ -444,7 +436,6 @@ impl> /// point (specifically, commitment length should be 2^(point-length/2)). /// /// # Disregarded arguments - /// - `opening_challenges` /// - `rng` fn check<'a>( vk: &Self::VerifierKey, @@ -452,11 +443,7 @@ impl> point: &'a P::Point, _values: impl IntoIterator, proof: &Self::Proof, - // Not used and not generic on the cryptographic sponge S - _opening_challenges: &mut ChallengeGenerator< - G::ScalarField, - PoseidonSponge, - >, + sponge: &mut S, _rng: Option<&mut dyn RngCore>, ) -> Result where @@ -508,29 +495,25 @@ impl> .collect::>(); let t_prime: G = ::msm_bigint(row_coms, &l_bigint).into(); - // Construct transcript and squeeze the challenge c from it - - let mut transcript: IOPTranscript = IOPTranscript::new(b"transcript"); - // Absorbing public parameters - transcript.append_serializable_element(b"public parameters", vk)?; + sponge.absorb(&to_bytes!(vk).map_err(|_| Error::TranscriptError)?); // Absorbing the commitment to the polynomial - transcript.append_serializable_element(b"commitment", row_coms)?; + sponge.absorb(&to_bytes!(row_coms).map_err(|_| Error::TranscriptError)?); // Absorbing the point - transcript.append_serializable_element(b"point", point)?; + sponge.absorb(point); // Absorbing the commitment to the evaluation - transcript.append_serializable_element(b"com_eval", com_eval)?; + sponge.absorb(&to_bytes!(com_eval).map_err(|_| Error::TranscriptError)?); // Absorbing the two auxiliary commitments - transcript.append_serializable_element(b"com_d", com_d)?; - transcript.append_serializable_element(b"com_b", com_b)?; + sponge.absorb(&to_bytes!(com_d).map_err(|_| Error::TranscriptError)?); + sponge.absorb(&to_bytes!(com_b).map_err(|_| Error::TranscriptError)?); // Receive the random challenge c from the verifier, i.e. squeeze // it from the transcript. - let c = transcript.get_and_append_challenge(b"c").unwrap(); + let c: G::ScalarField = sponge.squeeze_field_elements(1)[0]; // First check let com_z_zd = Self::pedersen_commit(vk, z, Some(*z_d), None).0; diff --git a/poly-commit/src/hyrax/tests.rs b/poly-commit/src/hyrax/tests.rs index f471b49f..713dd7f3 100644 --- a/poly-commit/src/hyrax/tests.rs +++ b/poly-commit/src/hyrax/tests.rs @@ -1,3 +1,7 @@ +use crate::hyrax::HyraxPC; +use crate::tests::*; +use crate::utils::test_sponge; +use crate::{LabeledPolynomial, PolynomialCommitment}; use ark_bls12_377::G1Affine; use ark_crypto_primitives::sponge::poseidon::PoseidonSponge; use ark_ec::AffineRepr; @@ -7,24 +11,16 @@ use ark_poly::{DenseMultilinearExtension, MultilinearExtension}; use ark_std::test_rng; use rand_chacha::{rand_core::SeedableRng, ChaCha20Rng}; -use crate::challenge::ChallengeGenerator; -use crate::hyrax::HyraxPC; - -use crate::utils::test_sponge; -use crate::{LabeledPolynomial, PolynomialCommitment}; - -use crate::tests::*; - // The test structure is largely taken from the multilinear_ligero module // inside this crate // ****************** types ****************** -type Fr = ::ScalarField; -type Hyrax381 = HyraxPC>; - type Fq = ::ScalarField; -type Hyrax377 = HyraxPC>; +type Hyrax377 = HyraxPC, PoseidonSponge>; + +type Fr = ::ScalarField; +type Hyrax381 = HyraxPC, PoseidonSponge>; // ******** auxiliary test functions ******** @@ -84,15 +80,13 @@ fn test_hyrax_construction() { // Dummy argument let mut test_sponge = test_sponge::(); - let mut challenge_generator: ChallengeGenerator> = - ChallengeGenerator::new_univariate(&mut test_sponge); let proof = Hyrax381::open( &ck, &[l_poly], &c, &point, - &mut (challenge_generator.clone()), + &mut (test_sponge.clone()), &rands, Some(chacha), ) @@ -104,7 +98,7 @@ fn test_hyrax_construction() { &point, [value], &proof, - &mut challenge_generator, + &mut test_sponge, Some(chacha), ) .unwrap()); @@ -112,35 +106,35 @@ fn test_hyrax_construction() { #[test] fn hyrax_single_poly_test() { - single_poly_test::<_, _, Hyrax381, _>( + single_poly_test::<_, _, Hyrax377, _>( Some(10), - rand_poly::, - rand_point::, + rand_poly, + rand_point, poseidon_sponge_for_test, ) - .expect("test failed for bls12-381"); - single_poly_test::<_, _, Hyrax377, _>( + .expect("test failed for bls12-377"); + single_poly_test::<_, _, Hyrax381, _>( Some(10), - rand_poly::, - rand_point::, + rand_poly, + rand_point, poseidon_sponge_for_test, ) - .expect("test failed for bls12-377"); + .expect("test failed for bls12-381"); } #[test] fn hyrax_constant_poly_test() { single_poly_test::<_, _, Hyrax377, _>( Some(0), - constant_poly::, - rand_point::, + constant_poly, + rand_point, poseidon_sponge_for_test, ) .expect("test failed for bls12-377"); single_poly_test::<_, _, Hyrax381, _>( Some(0), - constant_poly::, - rand_point::, + constant_poly, + rand_point, poseidon_sponge_for_test, ) .expect("test failed for bls12-381"); @@ -150,15 +144,15 @@ fn hyrax_constant_poly_test() { fn hyrax_full_end_to_end_test() { full_end_to_end_test::<_, _, Hyrax377, _>( Some(8), - rand_poly::, - rand_point::, + rand_poly, + rand_point, poseidon_sponge_for_test, ) .expect("test failed for bls12-377"); full_end_to_end_test::<_, _, Hyrax381, _>( Some(10), - rand_poly::, - rand_point::, + rand_poly, + rand_point, poseidon_sponge_for_test, ) .expect("test failed for bls12-381"); @@ -168,15 +162,15 @@ fn hyrax_full_end_to_end_test() { fn hyrax_single_equation_test() { single_equation_test::<_, _, Hyrax377, _>( Some(6), - rand_poly::, - rand_point::, + rand_poly, + rand_point, poseidon_sponge_for_test, ) .expect("test failed for bls12-377"); single_equation_test::<_, _, Hyrax381, _>( Some(6), - rand_poly::, - rand_point::, + rand_poly, + rand_point, poseidon_sponge_for_test, ) .expect("test failed for bls12-381"); @@ -186,15 +180,15 @@ fn hyrax_single_equation_test() { fn hyrax_two_equation_test() { two_equation_test::<_, _, Hyrax377, _>( Some(10), - rand_poly::, - rand_point::, + rand_poly, + rand_point, poseidon_sponge_for_test, ) .expect("test failed for bls12-377"); two_equation_test::<_, _, Hyrax381, _>( Some(10), - rand_poly::, - rand_point::, + rand_poly, + rand_point, poseidon_sponge_for_test, ) .expect("test failed for bls12-381"); @@ -204,15 +198,15 @@ fn hyrax_two_equation_test() { fn hyrax_full_end_to_end_equation_test() { full_end_to_end_equation_test::<_, _, Hyrax377, _>( Some(8), - rand_poly::, - rand_point::, + rand_poly, + rand_point, poseidon_sponge_for_test, ) .expect("test failed for bls12-377"); full_end_to_end_equation_test::<_, _, Hyrax381, _>( Some(8), - rand_poly::, - rand_point::, + rand_poly, + rand_point, poseidon_sponge_for_test, ) .expect("test failed for bls12-381"); diff --git a/poly-commit/src/ipa_pc/mod.rs b/poly-commit/src/ipa_pc/mod.rs index 26234f1e..43a40852 100644 --- a/poly-commit/src/ipa_pc/mod.rs +++ b/poly-commit/src/ipa_pc/mod.rs @@ -15,7 +15,6 @@ pub use data_structures::*; #[cfg(feature = "parallel")] use rayon::prelude::*; -use crate::challenge::ChallengeGenerator; use ark_crypto_primitives::sponge::CryptographicSponge; use digest::Digest; @@ -105,7 +104,7 @@ where point: G::ScalarField, values: impl IntoIterator, proof: &Proof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, ) -> Option> { let check_time = start_timer!(|| "Succinct checking"); @@ -117,7 +116,8 @@ where let mut combined_commitment_proj = G::Group::zero(); let mut combined_v = G::ScalarField::zero(); - let mut cur_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + let mut cur_challenge: G::ScalarField = + sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; let labeled_commitments = commitments.into_iter(); let values = values.into_iter(); @@ -126,7 +126,7 @@ where let commitment = labeled_commitment.commitment(); combined_v += &(cur_challenge * &value); combined_commitment_proj += &labeled_commitment.commitment().comm.mul(cur_challenge); - cur_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + cur_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; let degree_bound = labeled_commitment.degree_bound(); assert_eq!(degree_bound.is_some(), commitment.shifted_comm.is_some()); @@ -137,7 +137,7 @@ where combined_commitment_proj += &commitment.shifted_comm.unwrap().mul(cur_challenge); } - cur_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + cur_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; } let mut combined_commitment = combined_commitment_proj.into_affine(); @@ -488,7 +488,7 @@ where labeled_polynomials: impl IntoIterator>, commitments: impl IntoIterator>, point: &'a P::Point, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result @@ -509,7 +509,7 @@ where let combine_time = start_timer!(|| "Combining polynomials, randomness, and commitments."); - let mut cur_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + let mut cur_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; for (labeled_polynomial, (labeled_commitment, state)) in polys_iter.zip(comms_iter.zip(states_iter)) @@ -531,7 +531,7 @@ where combined_rand += &(cur_challenge * &state.rand); } - cur_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + cur_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; let has_degree_bound = degree_bound.is_some(); @@ -564,7 +564,7 @@ where } } - cur_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + cur_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; } end_timer!(combine_time); @@ -739,7 +739,7 @@ where point: &'a P::Point, values: impl IntoIterator, proof: &Self::Proof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, _rng: Option<&mut dyn RngCore>, ) -> Result where @@ -762,8 +762,7 @@ where )); } - let check_poly = - Self::succinct_check(vk, commitments, *point, values, proof, opening_challenges); + let check_poly = Self::succinct_check(vk, commitments, *point, values, proof, sponge); if check_poly.is_none() { return Ok(false); @@ -790,7 +789,7 @@ where query_set: &QuerySet, values: &Evaluations, proof: &Self::BatchProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -833,14 +832,8 @@ where vals.push(*v_i); } - let check_poly = Self::succinct_check( - vk, - comms.into_iter(), - *point, - vals.into_iter(), - p, - opening_challenges, - ); + let check_poly = + Self::succinct_check(vk, comms.into_iter(), *point, vals.into_iter(), p, sponge); if check_poly.is_none() { return Ok(false); @@ -876,7 +869,7 @@ where polynomials: impl IntoIterator>, commitments: impl IntoIterator>, query_set: &QuerySet, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> @@ -971,7 +964,7 @@ where lc_polynomials.iter(), lc_commitments.iter(), &query_set, - opening_challenges, + sponge, lc_states.iter(), rng, )?; @@ -987,7 +980,7 @@ where eqn_query_set: &QuerySet, eqn_evaluations: &Evaluations, proof: &BatchLCProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -1060,7 +1053,7 @@ where &eqn_query_set, &evaluations, proof, - opening_challenges, + sponge, rng, ) } diff --git a/poly-commit/src/lib.rs b/poly-commit/src/lib.rs index 93fc801f..1c277dd5 100644 --- a/poly-commit/src/lib.rs +++ b/poly-commit/src/lib.rs @@ -9,7 +9,7 @@ #![deny(renamed_and_removed_lints, stable_features, unused_allocation)] #![deny(unused_comparisons, bare_trait_objects, unused_must_use)] #![forbid(unsafe_code)] -#![doc = include_str!("../README.md")] +#![doc = include_str!("../../README.md")] #[allow(unused)] #[macro_use] @@ -101,8 +101,6 @@ pub mod sonic_pc; /// [pcdas]: https://eprint.iacr.org/2020/499 pub mod ipa_pc; -/// Defines the challenge strategies and challenge generator. -pub mod challenge; /// A multilinear polynomial commitment scheme that converts n-variate multilinear polynomial into /// n quotient UV polynomial. This scheme is based on hardness of the discrete logarithm /// in prime-order groups. Construction is detailed in [[XZZPD19]][xzzpd19] and [[ZGKPP18]][zgkpp18] @@ -111,7 +109,6 @@ pub mod challenge; /// [zgkpp]: https://ieeexplore.ieee.org/document/8418645 pub mod multilinear_pc; -use crate::challenge::ChallengeGenerator; use ark_crypto_primitives::sponge::{CryptographicSponge, FieldElementSize}; /// Multivariate polynomial commitment based on the construction in /// [[PST13]][pst] with batching and (optional) hiding property inspired @@ -229,7 +226,7 @@ pub trait PolynomialCommitment, S: Cryptographic labeled_polynomials: impl IntoIterator>, commitments: impl IntoIterator>, point: &'a P::Point, - challenge_generator: &mut ChallengeGenerator, + sponge: &mut S, states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result @@ -245,7 +242,7 @@ pub trait PolynomialCommitment, S: Cryptographic point: &'a P::Point, values: impl IntoIterator, proof: &Self::Proof, - challenge_generator: &mut ChallengeGenerator, + sponge: &mut S, rng: Option<&mut dyn RngCore>, ) -> Result where @@ -265,7 +262,7 @@ pub trait PolynomialCommitment, S: Cryptographic labeled_polynomials: impl IntoIterator>, commitments: impl IntoIterator>, query_set: &QuerySet, - challenge_generator: &mut ChallengeGenerator, + sponge: &mut S, states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result @@ -337,7 +334,7 @@ pub trait PolynomialCommitment, S: Cryptographic query_polys, query_comms, &point, - challenge_generator, + sponge, query_states, Some(rng), )?; @@ -370,7 +367,7 @@ pub trait PolynomialCommitment, S: Cryptographic query_set: &QuerySet, evaluations: &Evaluations, proof: &Self::BatchProof, - challenge_generator: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -428,15 +425,7 @@ pub trait PolynomialCommitment, S: Cryptographic // Verify all proofs referring to the current point simultaneously // with a single call to `check` - result &= Self::check( - vk, - comms, - &point, - values, - &proof, - challenge_generator, - Some(rng), - )?; + result &= Self::check(vk, comms, &point, values, &proof, sponge, Some(rng))?; end_timer!(proof_time); } Ok(result) @@ -450,7 +439,7 @@ pub trait PolynomialCommitment, S: Cryptographic polynomials: impl IntoIterator>, commitments: impl IntoIterator>, query_set: &QuerySet, - challenge_generator: &mut ChallengeGenerator, + sponge: &mut S, states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> @@ -476,7 +465,7 @@ pub trait PolynomialCommitment, S: Cryptographic polynomials, commitments, &poly_query_set, - challenge_generator, + sponge, states, rng, )?; @@ -495,7 +484,7 @@ pub trait PolynomialCommitment, S: Cryptographic eqn_query_set: &QuerySet, eqn_evaluations: &Evaluations, proof: &BatchLCProof, - challenge_generator: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -566,7 +555,7 @@ pub trait PolynomialCommitment, S: Cryptographic &poly_query_set, &poly_evals, proof, - challenge_generator, + sponge, rng, )?; if !pc_result { @@ -678,12 +667,9 @@ pub mod tests { PC: PolynomialCommitment, S: CryptographicSponge, { - let challenge_generators = vec![ - ChallengeGenerator::new_multivariate(sponge()), - ChallengeGenerator::new_univariate(&mut sponge()), - ]; + let sponge = sponge(); - for challenge_gen in challenge_generators { + for __ in 0..1 { let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); let max_degree = 100; let pp = PC::setup(max_degree, None, rng)?; @@ -745,7 +731,7 @@ pub mod tests { &polynomials, &comms, &query_set, - &mut (challenge_gen.clone()), + &mut (sponge.clone()), &states, Some(rng), )?; @@ -755,7 +741,7 @@ pub mod tests { &query_set, &values, &proof, - &mut (challenge_gen.clone()), + &mut (sponge.clone()), rng, )?; assert!(result, "proof was incorrect, Query set: {:#?}", query_set); @@ -786,12 +772,9 @@ pub mod tests { sponge, } = info; - let challenge_gens = vec![ - ChallengeGenerator::new_multivariate(sponge()), - ChallengeGenerator::new_univariate(&mut sponge()), - ]; + let sponge = sponge(); - for challenge_gen in challenge_gens { + for _ in 0..1 { let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); // If testing multivariate polynomials, make the max degree lower let max_degree = match num_vars { @@ -800,7 +783,7 @@ pub mod tests { }; let pp = PC::setup(max_degree, num_vars, rng)?; - for _ in 0..num_iters { + for __ in 0..num_iters { let supported_degree = supported_degree.unwrap_or(Uniform::from(1..=max_degree).sample(rng)); assert!( @@ -881,7 +864,7 @@ pub mod tests { &polynomials, &comms, &query_set, - &mut (challenge_gen.clone()), + &mut (sponge.clone()), &states, Some(rng), )?; @@ -891,7 +874,7 @@ pub mod tests { &query_set, &values, &proof, - &mut (challenge_gen.clone()), + &mut (sponge.clone()), rng, )?; if !result { @@ -931,12 +914,9 @@ pub mod tests { sponge, } = info; - let challenge_gens = vec![ - ChallengeGenerator::new_multivariate(sponge()), - ChallengeGenerator::new_univariate(&mut sponge()), - ]; + let sponge = sponge(); - for challenge_gen in challenge_gens { + for __ in 0..1 { let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); // If testing multivariate polynomials, make the max degree lower let max_degree = match num_vars { @@ -1060,7 +1040,7 @@ pub mod tests { &polynomials, &comms, &query_set, - &mut (challenge_gen.clone()), + &mut (sponge.clone()), &states, Some(rng), )?; @@ -1072,7 +1052,7 @@ pub mod tests { &query_set, &values, &proof, - &mut (challenge_gen.clone()), + &mut (sponge.clone()), rng, )?; if !result { diff --git a/poly-commit/src/marlin/marlin_pc/mod.rs b/poly-commit/src/marlin/marlin_pc/mod.rs index 1b45bff7..7fbfba07 100644 --- a/poly-commit/src/marlin/marlin_pc/mod.rs +++ b/poly-commit/src/marlin/marlin_pc/mod.rs @@ -12,7 +12,6 @@ use ark_std::rand::RngCore; use ark_std::{marker::PhantomData, ops::Div, vec}; mod data_structures; -use crate::challenge::ChallengeGenerator; use ark_crypto_primitives::sponge::CryptographicSponge; pub use data_structures::*; @@ -251,7 +250,7 @@ where labeled_polynomials: impl IntoIterator>, _commitments: impl IntoIterator>, point: &'a P::Point, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, states: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result @@ -283,7 +282,7 @@ where )?; // compute next challenges challenge^j and challenge^{j+1}. - let challenge_j = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + let challenge_j = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; assert_eq!(degree_bound.is_some(), rand.shifted_rand.is_some()); @@ -299,7 +298,7 @@ where *point, &shifted_rand, )?; - let challenge_j_1 = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + let challenge_j_1 = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; let shifted_witness = shift_polynomial(ck, &witness, degree_bound); @@ -347,7 +346,7 @@ where point: &'a P::Point, values: impl IntoIterator, proof: &Self::Proof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, _rng: Option<&mut dyn RngCore>, ) -> Result where @@ -358,7 +357,7 @@ where Marlin::::accumulate_commitments_and_values( commitments, values, - opening_challenges, + sponge, Some(vk), )?; let combined_comm = kzg10::Commitment(combined_comm.into()); @@ -373,7 +372,7 @@ where query_set: &QuerySet, values: &Evaluations, proof: &Self::BatchProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -384,7 +383,7 @@ where commitments, query_set, values, - opening_challenges, + sponge, Some(vk), )?; assert_eq!(proof.len(), combined_queries.len()); @@ -407,7 +406,7 @@ where polynomials: impl IntoIterator>, commitments: impl IntoIterator>, query_set: &QuerySet, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> @@ -422,7 +421,7 @@ where polynomials, commitments, query_set, - opening_challenges, + sponge, states, rng, ) @@ -437,7 +436,7 @@ where query_set: &QuerySet, evaluations: &Evaluations, proof: &BatchLCProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -450,7 +449,7 @@ where query_set, evaluations, proof, - opening_challenges, + sponge, rng, ) } @@ -462,7 +461,7 @@ where labeled_polynomials: impl IntoIterator>, commitments: impl IntoIterator>>, query_set: &QuerySet, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result>, Error> @@ -517,7 +516,7 @@ where query_polys, query_comms, point, - opening_challenges, + sponge, query_states, Some(rng), )?; diff --git a/poly-commit/src/marlin/marlin_pst13_pc/mod.rs b/poly-commit/src/marlin/marlin_pst13_pc/mod.rs index 93d5c0c6..a72d9199 100644 --- a/poly-commit/src/marlin/marlin_pst13_pc/mod.rs +++ b/poly-commit/src/marlin/marlin_pst13_pc/mod.rs @@ -20,7 +20,6 @@ pub use data_structures::*; mod combinations; use combinations::*; -use crate::challenge::ChallengeGenerator; use ark_crypto_primitives::sponge::CryptographicSponge; #[cfg(feature = "parallel")] use rayon::prelude::*; @@ -440,7 +439,7 @@ where labeled_polynomials: impl IntoIterator>, _commitments: impl IntoIterator>, point: &P::Point, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, states: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result @@ -456,7 +455,7 @@ where Self::check_degrees_and_bounds(ck.supported_degree, &polynomial)?; // compute challenge^j and challenge^{j+1}. - let challenge_j = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + let challenge_j = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; p += (challenge_j, polynomial.polynomial()); r += (challenge_j, state); @@ -538,7 +537,7 @@ where point: &'a P::Point, values: impl IntoIterator, proof: &Self::Proof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, _rng: Option<&mut dyn RngCore>, ) -> Result where @@ -550,7 +549,7 @@ where Marlin::::accumulate_commitments_and_values( commitments, values, - opening_challenges, + sponge, None, )?; // Compute both sides of the pairing equation @@ -582,7 +581,7 @@ where query_set: &QuerySet, values: &Evaluations, proof: &Self::BatchProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -593,7 +592,7 @@ where commitments, query_set, values, - opening_challenges, + sponge, None, )?; let check_time = @@ -660,7 +659,7 @@ where polynomials: impl IntoIterator>, commitments: impl IntoIterator>, query_set: &QuerySet, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> @@ -675,7 +674,7 @@ where polynomials, commitments, query_set, - opening_challenges, + sponge, states, rng, ) @@ -690,7 +689,7 @@ where eqn_query_set: &QuerySet, eqn_evaluations: &Evaluations, proof: &BatchLCProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -703,7 +702,7 @@ where eqn_query_set, eqn_evaluations, proof, - opening_challenges, + sponge, rng, ) } diff --git a/poly-commit/src/marlin/mod.rs b/poly-commit/src/marlin/mod.rs index e0b026d2..d7e7f5a1 100644 --- a/poly-commit/src/marlin/mod.rs +++ b/poly-commit/src/marlin/mod.rs @@ -1,4 +1,4 @@ -use crate::{challenge::ChallengeGenerator, CHALLENGE_SIZE}; +use crate::CHALLENGE_SIZE; use crate::{kzg10, Error}; use crate::{BTreeMap, BTreeSet, Debug, RngCore, String, ToString, Vec}; use crate::{BatchLCProof, LabeledPolynomial, LinearCombination}; @@ -110,7 +110,7 @@ where fn accumulate_commitments_and_values<'a>( commitments: impl IntoIterator>>, values: impl IntoIterator, - challenge_gen: &mut ChallengeGenerator, + sponge: &mut S, vk: Option<&marlin_pc::VerifierKey>, ) -> Result<(E::G1, E::ScalarField), Error> { let acc_time = start_timer!(|| "Accumulating commitments and values"); @@ -121,13 +121,14 @@ where let commitment = labeled_commitment.commitment(); assert_eq!(degree_bound.is_some(), commitment.shifted_comm.is_some()); - let challenge_i = challenge_gen.try_next_challenge_of_size(CHALLENGE_SIZE); + let challenge_i = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; combined_comm += &commitment.comm.0.mul(challenge_i); combined_value += &(value * &challenge_i); if let Some(degree_bound) = degree_bound { - let challenge_i_1 = challenge_gen.try_next_challenge_of_size(CHALLENGE_SIZE); + let challenge_i_1: E::ScalarField = + sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; let shifted_comm = commitment.shifted_comm.as_ref().unwrap().0.into_group(); @@ -152,7 +153,7 @@ where commitments: impl IntoIterator>>, query_set: &QuerySet, evaluations: &Evaluations, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, vk: Option<&marlin_pc::VerifierKey>, ) -> Result<(Vec>, Vec, Vec), Error> where @@ -199,7 +200,7 @@ where let (c, v) = Self::accumulate_commitments_and_values( comms_to_combine, values_to_combine, - opening_challenges, + sponge, vk, )?; end_timer!(lc_time); @@ -227,7 +228,7 @@ where polynomials: impl IntoIterator>, commitments: impl IntoIterator>, query_set: &QuerySet, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Error> @@ -308,7 +309,7 @@ where lc_polynomials.iter(), lc_commitments.iter(), &query_set, - opening_challenges, + sponge, lc_states.iter(), rng, )?; @@ -323,7 +324,7 @@ where query_set: &QuerySet, evaluations: &Evaluations, proof: &BatchLCProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -404,7 +405,7 @@ where &query_set, &evaluations, proof, - opening_challenges, + sponge, rng, ) } diff --git a/poly-commit/src/sonic_pc/mod.rs b/poly-commit/src/sonic_pc/mod.rs index b1d7f28b..caf9b79c 100644 --- a/poly-commit/src/sonic_pc/mod.rs +++ b/poly-commit/src/sonic_pc/mod.rs @@ -12,7 +12,6 @@ use ark_std::rand::RngCore; use ark_std::{convert::TryInto, marker::PhantomData, ops::Div, ops::Mul, vec}; mod data_structures; -use crate::challenge::ChallengeGenerator; use ark_crypto_primitives::sponge::CryptographicSponge; pub use data_structures::*; @@ -47,12 +46,12 @@ where point: P::Point, values: impl IntoIterator, proof: &kzg10::Proof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, randomizer: Option, ) { let acc_time = start_timer!(|| "Accumulating elements"); - let mut curr_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + let mut curr_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; // Keeps track of running combination of values let mut combined_values = E::ScalarField::zero(); @@ -73,7 +72,7 @@ where // Accumulate values in the BTreeMap *combined_comms.entry(degree_bound).or_insert(E::G1::zero()) += &comm_with_challenge; - curr_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + curr_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; } // Push expected results into list of elems. Power will be the negative of the expected power @@ -345,7 +344,7 @@ where labeled_polynomials: impl IntoIterator>, _commitments: impl IntoIterator>, point: &'a P::Point, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, states: impl IntoIterator, _rng: Option<&mut dyn RngCore>, ) -> Result @@ -357,7 +356,7 @@ where let mut combined_polynomial = P::zero(); let mut combined_rand = kzg10::Randomness::empty(); - let mut curr_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + let mut curr_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; for (polynomial, state) in labeled_polynomials.into_iter().zip(states) { let enforced_degree_bounds: Option<&[usize]> = ck @@ -374,7 +373,7 @@ where combined_polynomial += (curr_challenge, polynomial.polynomial()); combined_rand += (curr_challenge, state); - curr_challenge = opening_challenges.try_next_challenge_of_size(CHALLENGE_SIZE); + curr_challenge = sponge.squeeze_field_elements_with_sizes(&[CHALLENGE_SIZE])[0]; } let proof_time = start_timer!(|| "Creating proof for polynomials"); @@ -390,7 +389,7 @@ where point: &'a P::Point, values: impl IntoIterator, proof: &Self::Proof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, _rng: Option<&mut dyn RngCore>, ) -> Result where @@ -410,7 +409,7 @@ where *point, values, proof, - opening_challenges, + sponge, None, ); @@ -430,7 +429,7 @@ where query_set: &QuerySet, values: &Evaluations, proof: &Self::BatchProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -481,7 +480,7 @@ where *point, values_to_combine.into_iter(), p, - opening_challenges, + sponge, Some(randomizer), ); @@ -502,7 +501,7 @@ where polynomials: impl IntoIterator>, commitments: impl IntoIterator>, query_set: &QuerySet, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, states: impl IntoIterator, rng: Option<&mut dyn RngCore>, ) -> Result, Self::Error> @@ -581,7 +580,7 @@ where lc_polynomials.iter(), lc_commitments.iter(), &query_set, - opening_challenges, + sponge, lc_states.iter(), rng, )?; @@ -597,7 +596,7 @@ where eqn_query_set: &QuerySet, eqn_evaluations: &Evaluations, proof: &BatchLCProof, - opening_challenges: &mut ChallengeGenerator, + sponge: &mut S, rng: &mut R, ) -> Result where @@ -666,7 +665,7 @@ where &eqn_query_set, &evaluations, proof, - opening_challenges, + sponge, rng, ) } diff --git a/poly-commit/src/streaming_kzg/data_structures.rs b/poly-commit/src/streaming_kzg/data_structures.rs index 7adaf005..c8b19c83 100644 --- a/poly-commit/src/streaming_kzg/data_structures.rs +++ b/poly-commit/src/streaming_kzg/data_structures.rs @@ -141,7 +141,7 @@ where /// Stream implementation of foleded polynomial. #[derive(Clone, Copy)] -pub struct FoldedPolynomialStream<'a, F, S>(FoldedPolynomialTree<'a, F, S>, usize); +pub struct FoldedPolynomialStream<'a, F, S>(FoldedPolynomialTree<'a, F, S>); /// Iterator implementation of foleded polynomial. pub struct FoldedPolynomialStreamIter<'a, F, I> { challenges: &'a [F], @@ -158,8 +158,7 @@ where /// Initialize a new folded polynomial stream. pub fn new(coefficients: &'a S, challenges: &'a [F]) -> Self { let tree = FoldedPolynomialTree::new(coefficients, challenges); - let len = challenges.len(); - Self(tree, len) + Self(tree) } } @@ -241,7 +240,7 @@ fn test_folded_polynomial() { let challenges = vec![F::one(), two]; let coefficients_stream = coefficients.as_slice(); let foldstream = FoldedPolynomialTree::new(&coefficients_stream, challenges.as_slice()); - let fold_stream = FoldedPolynomialStream(foldstream, 2); + let fold_stream = FoldedPolynomialStream(foldstream); assert_eq!(fold_stream.len(), 1); assert_eq!( fold_stream.iter().next(), @@ -253,7 +252,7 @@ fn test_folded_polynomial() { let challenges = vec![F::one(); 4]; let coefficients_stream = coefficients.as_slice(); let foldstream = FoldedPolynomialTree::new(&coefficients_stream, challenges.as_slice()); - let fold_stream = FoldedPolynomialStream(foldstream, 4).iter(); + let fold_stream = FoldedPolynomialStream(foldstream).iter(); assert_eq!(fold_stream.last(), Some(coefficients.iter().sum())); } diff --git a/poly-commit/src/utils.rs b/poly-commit/src/utils.rs index 4a2ffeb4..f06ebf96 100644 --- a/poly-commit/src/utils.rs +++ b/poly-commit/src/utils.rs @@ -1,4 +1,6 @@ -use core::marker::PhantomData; +use ark_ff::Field; +use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; +use ark_std::vec::Vec; #[cfg(feature = "parallel")] use rayon::{ @@ -6,13 +8,6 @@ use rayon::{ prelude::IndexedParallelIterator, }; -use ark_ff::{Field, PrimeField}; -use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; -use ark_std::vec::Vec; -use merlin::Transcript; - -use crate::Error; - /// Takes as input a struct, and converts them to a series of bytes. All traits /// that implement `CanonicalSerialize` can be automatically converted to bytes /// in this manner. @@ -109,69 +104,11 @@ pub(crate) fn vector_sum(v1: &[F], v2: &[F]) -> Vec { .collect() } -/// The following struct is taken from jellyfish repository. Once they change -/// their dependency on `crypto-primitive`, we use their crate instead of -/// a copy-paste. We needed the newer `crypto-primitive` for serializing. -#[derive(Clone)] -pub(crate) struct IOPTranscript { - transcript: Transcript, - is_empty: bool, - #[doc(hidden)] - phantom: PhantomData, -} - -// TODO: merge this with jf_plonk::transcript -impl IOPTranscript { - /// Create a new IOP transcript. - pub(crate) fn new(label: &'static [u8]) -> Self { - Self { - transcript: Transcript::new(label), - is_empty: true, - phantom: PhantomData, - } - } - - /// Append the message to the transcript. - pub(crate) fn append_message(&mut self, label: &'static [u8], msg: &[u8]) -> Result<(), Error> { - self.transcript.append_message(label, msg); - self.is_empty = false; - Ok(()) - } - - /// Append the message to the transcript. - pub(crate) fn append_serializable_element( - &mut self, - label: &'static [u8], - group_elem: &S, - ) -> Result<(), Error> { - self.append_message( - label, - &to_bytes!(group_elem).map_err(|_| Error::TranscriptError)?, - ) - } - - /// Generate the challenge from the current transcript - /// and append it to the transcript. - /// - /// The output field element is statistical uniform as long - /// as the field has a size less than 2^384. - pub(crate) fn get_and_append_challenge(&mut self, label: &'static [u8]) -> Result { - // we need to reject when transcript is empty - if self.is_empty { - return Err(Error::TranscriptError); - } - - let mut buf = [0u8; 64]; - self.transcript.challenge_bytes(label, &mut buf); - let challenge = F::from_le_bytes_mod_order(&buf); - self.append_serializable_element(label, &challenge)?; - Ok(challenge) - } -} - // TODO: replace by https://github.com/arkworks-rs/crypto-primitives/issues/112. #[cfg(test)] use ark_crypto_primitives::sponge::poseidon::PoseidonSponge; +#[cfg(test)] +use ark_ff::PrimeField; #[cfg(test)] pub(crate) fn test_sponge() -> PoseidonSponge { From 83b8c7d73f3b440d27ffc8b4184cf3b22150ddac Mon Sep 17 00:00:00 2001 From: Hossein Moghaddas Date: Wed, 17 Jan 2024 10:37:30 +0100 Subject: [PATCH 20/20] Remove the extra loop --- poly-commit/src/lib.rs | 630 ++++++++++++++++++++--------------------- 1 file changed, 312 insertions(+), 318 deletions(-) diff --git a/poly-commit/src/lib.rs b/poly-commit/src/lib.rs index 1c277dd5..4b0bf59d 100644 --- a/poly-commit/src/lib.rs +++ b/poly-commit/src/lib.rs @@ -669,83 +669,81 @@ pub mod tests { { let sponge = sponge(); - for __ in 0..1 { - let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); - let max_degree = 100; - let pp = PC::setup(max_degree, None, rng)?; - for _ in 0..10 { - let supported_degree = Uniform::from(1..=max_degree).sample(rng); - assert!( - max_degree >= supported_degree, - "max_degree < supported_degree" - ); - - let mut labels = Vec::new(); - let mut polynomials = Vec::new(); - let mut degree_bounds = Vec::new(); - - for i in 0..10 { - let label = format!("Test{}", i); - labels.push(label.clone()); - let degree_bound = 1usize; - let hiding_bound = Some(1); - degree_bounds.push(degree_bound); - - polynomials.push(LabeledPolynomial::new( - label, - rand_poly(supported_degree, None, rng), - Some(degree_bound), - hiding_bound, - )); - } + let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); + let max_degree = 100; + let pp = PC::setup(max_degree, None, rng)?; + for _ in 0..10 { + let supported_degree = Uniform::from(1..=max_degree).sample(rng); + assert!( + max_degree >= supported_degree, + "max_degree < supported_degree" + ); + + let mut labels = Vec::new(); + let mut polynomials = Vec::new(); + let mut degree_bounds = Vec::new(); + + for i in 0..10 { + let label = format!("Test{}", i); + labels.push(label.clone()); + let degree_bound = 1usize; + let hiding_bound = Some(1); + degree_bounds.push(degree_bound); + + polynomials.push(LabeledPolynomial::new( + label, + rand_poly(supported_degree, None, rng), + Some(degree_bound), + hiding_bound, + )); + } - let supported_hiding_bound = polynomials - .iter() - .map(|p| p.hiding_bound().unwrap_or(0)) - .max() - .unwrap_or(0); - println!("supported degree: {:?}", supported_degree); - println!("supported hiding bound: {:?}", supported_hiding_bound); - let (ck, vk) = PC::trim( - &pp, - supported_degree, - supported_hiding_bound, - Some(degree_bounds.as_slice()), - )?; - println!("Trimmed"); + let supported_hiding_bound = polynomials + .iter() + .map(|p| p.hiding_bound().unwrap_or(0)) + .max() + .unwrap_or(0); + println!("supported degree: {:?}", supported_degree); + println!("supported hiding bound: {:?}", supported_hiding_bound); + let (ck, vk) = PC::trim( + &pp, + supported_degree, + supported_hiding_bound, + Some(degree_bounds.as_slice()), + )?; + println!("Trimmed"); - let (comms, states) = PC::commit(&ck, &polynomials, Some(rng))?; + let (comms, states) = PC::commit(&ck, &polynomials, Some(rng))?; - let mut query_set = QuerySet::new(); - let mut values = Evaluations::new(); - let point = rand_point(None, rng); - for (i, label) in labels.iter().enumerate() { - query_set.insert((label.clone(), (format!("{}", i), point.clone()))); - let value = polynomials[i].evaluate(&point); - values.insert((label.clone(), point.clone()), value); - } - println!("Generated query set"); - - let proof = PC::batch_open( - &ck, - &polynomials, - &comms, - &query_set, - &mut (sponge.clone()), - &states, - Some(rng), - )?; - let result = PC::batch_check( - &vk, - &comms, - &query_set, - &values, - &proof, - &mut (sponge.clone()), - rng, - )?; - assert!(result, "proof was incorrect, Query set: {:#?}", query_set); + let mut query_set = QuerySet::new(); + let mut values = Evaluations::new(); + let point = rand_point(None, rng); + for (i, label) in labels.iter().enumerate() { + query_set.insert((label.clone(), (format!("{}", i), point.clone()))); + let value = polynomials[i].evaluate(&point); + values.insert((label.clone(), point.clone()), value); } + println!("Generated query set"); + + let proof = PC::batch_open( + &ck, + &polynomials, + &comms, + &query_set, + &mut (sponge.clone()), + &states, + Some(rng), + )?; + let result = PC::batch_check( + &vk, + &comms, + &query_set, + &values, + &proof, + &mut (sponge.clone()), + rng, + )?; + assert!(result, "proof was incorrect, Query set: {:#?}", query_set); } Ok(()) @@ -774,121 +772,119 @@ pub mod tests { let sponge = sponge(); - for _ in 0..1 { - let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); - // If testing multivariate polynomials, make the max degree lower - let max_degree = match num_vars { - Some(_) => max_degree.unwrap_or(Uniform::from(2..=10).sample(rng)), - None => max_degree.unwrap_or(Uniform::from(2..=64).sample(rng)), + let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); + // If testing multivariate polynomials, make the max degree lower + let max_degree = match num_vars { + Some(_) => max_degree.unwrap_or(Uniform::from(2..=10).sample(rng)), + None => max_degree.unwrap_or(Uniform::from(2..=64).sample(rng)), + }; + let pp = PC::setup(max_degree, num_vars, rng)?; + + for _ in 0..num_iters { + let supported_degree = + supported_degree.unwrap_or(Uniform::from(1..=max_degree).sample(rng)); + assert!( + max_degree >= supported_degree, + "max_degree < supported_degree" + ); + let mut polynomials: Vec> = Vec::new(); + let mut degree_bounds = if enforce_degree_bounds { + Some(Vec::new()) + } else { + None }; - let pp = PC::setup(max_degree, num_vars, rng)?; - - for __ in 0..num_iters { - let supported_degree = - supported_degree.unwrap_or(Uniform::from(1..=max_degree).sample(rng)); - assert!( - max_degree >= supported_degree, - "max_degree < supported_degree" - ); - let mut polynomials: Vec> = Vec::new(); - let mut degree_bounds = if enforce_degree_bounds { - Some(Vec::new()) + + let mut labels = Vec::new(); + println!("Sampled supported degree"); + + // Generate polynomials + let num_points_in_query_set = Uniform::from(1..=max_num_queries).sample(rng); + for i in 0..num_polynomials { + let label = format!("Test{}", i); + labels.push(label.clone()); + let degree = Uniform::from(1..=supported_degree).sample(rng); + let degree_bound = if let Some(degree_bounds) = &mut degree_bounds { + let range = Uniform::from(degree..=supported_degree); + let degree_bound = range.sample(rng); + degree_bounds.push(degree_bound); + Some(degree_bound) } else { None }; - let mut labels = Vec::new(); - println!("Sampled supported degree"); - - // Generate polynomials - let num_points_in_query_set = Uniform::from(1..=max_num_queries).sample(rng); - for i in 0..num_polynomials { - let label = format!("Test{}", i); - labels.push(label.clone()); - let degree = Uniform::from(1..=supported_degree).sample(rng); - let degree_bound = if let Some(degree_bounds) = &mut degree_bounds { - let range = Uniform::from(degree..=supported_degree); - let degree_bound = range.sample(rng); - degree_bounds.push(degree_bound); - Some(degree_bound) - } else { - None - }; - - let hiding_bound = if num_points_in_query_set >= degree { - Some(degree) - } else { - Some(num_points_in_query_set) - }; + let hiding_bound = if num_points_in_query_set >= degree { + Some(degree) + } else { + Some(num_points_in_query_set) + }; - polynomials.push(LabeledPolynomial::new( - label, - rand_poly(degree, num_vars, rng).into(), - degree_bound, - hiding_bound, - )) - } - let supported_hiding_bound = polynomials - .iter() - .map(|p| p.hiding_bound().unwrap_or(0)) - .max() - .unwrap_or(0); - println!("supported degree: {:?}", supported_degree); - println!("supported hiding bound: {:?}", supported_hiding_bound); - println!("num_points_in_query_set: {:?}", num_points_in_query_set); - let (ck, vk) = PC::trim( - &pp, - supported_degree, - supported_hiding_bound, - degree_bounds.as_ref().map(|s| s.as_slice()), - )?; - println!("Trimmed"); + polynomials.push(LabeledPolynomial::new( + label, + rand_poly(degree, num_vars, rng).into(), + degree_bound, + hiding_bound, + )) + } + let supported_hiding_bound = polynomials + .iter() + .map(|p| p.hiding_bound().unwrap_or(0)) + .max() + .unwrap_or(0); + println!("supported degree: {:?}", supported_degree); + println!("supported hiding bound: {:?}", supported_hiding_bound); + println!("num_points_in_query_set: {:?}", num_points_in_query_set); + let (ck, vk) = PC::trim( + &pp, + supported_degree, + supported_hiding_bound, + degree_bounds.as_ref().map(|s| s.as_slice()), + )?; + println!("Trimmed"); - let (comms, states) = PC::commit(&ck, &polynomials, Some(rng))?; + let (comms, states) = PC::commit(&ck, &polynomials, Some(rng))?; - // Construct query set - let mut query_set = QuerySet::new(); - let mut values = Evaluations::new(); - for _ in 0..num_points_in_query_set { - let point = rand_point(num_vars, rng); - for (i, label) in labels.iter().enumerate() { - query_set.insert((label.clone(), (format!("{}", i), point.clone()))); - let value = polynomials[i].evaluate(&point); - values.insert((label.clone(), point.clone()), value); - } + // Construct query set + let mut query_set = QuerySet::new(); + let mut values = Evaluations::new(); + for _ in 0..num_points_in_query_set { + let point = rand_point(num_vars, rng); + for (i, label) in labels.iter().enumerate() { + query_set.insert((label.clone(), (format!("{}", i), point.clone()))); + let value = polynomials[i].evaluate(&point); + values.insert((label.clone(), point.clone()), value); } - println!("Generated query set"); - - let proof = PC::batch_open( - &ck, - &polynomials, - &comms, - &query_set, - &mut (sponge.clone()), - &states, - Some(rng), - )?; - let result = PC::batch_check( - &vk, - &comms, - &query_set, - &values, - &proof, - &mut (sponge.clone()), - rng, - )?; - if !result { - println!( - "Failed with {} polynomials, num_points_in_query_set: {:?}", - num_polynomials, num_points_in_query_set - ); - println!("Degree of polynomials:",); - for poly in polynomials { - println!("Degree: {:?}", poly.degree()); - } + } + println!("Generated query set"); + + let proof = PC::batch_open( + &ck, + &polynomials, + &comms, + &query_set, + &mut (sponge.clone()), + &states, + Some(rng), + )?; + let result = PC::batch_check( + &vk, + &comms, + &query_set, + &values, + &proof, + &mut (sponge.clone()), + rng, + )?; + if !result { + println!( + "Failed with {} polynomials, num_points_in_query_set: {:?}", + num_polynomials, num_points_in_query_set + ); + println!("Degree of polynomials:",); + for poly in polynomials { + println!("Degree: {:?}", poly.degree()); } - assert!(result, "proof was incorrect, Query set: {:#?}", query_set); } + assert!(result, "proof was incorrect, Query set: {:#?}", query_set); } Ok(()) } @@ -916,161 +912,159 @@ pub mod tests { let sponge = sponge(); - for __ in 0..1 { - let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); - // If testing multivariate polynomials, make the max degree lower - let max_degree = match num_vars { - Some(_) => max_degree.unwrap_or(Uniform::from(2..=10).sample(rng)), - None => max_degree.unwrap_or(Uniform::from(2..=64).sample(rng)), + let rng = &mut ChaCha20Rng::from_rng(test_rng()).unwrap(); + // If testing multivariate polynomials, make the max degree lower + let max_degree = match num_vars { + Some(_) => max_degree.unwrap_or(Uniform::from(2..=10).sample(rng)), + None => max_degree.unwrap_or(Uniform::from(2..=64).sample(rng)), + }; + let pp = PC::setup(max_degree, num_vars, rng)?; + + for _ in 0..num_iters { + let supported_degree = + supported_degree.unwrap_or(Uniform::from(1..=max_degree).sample(rng)); + assert!( + max_degree >= supported_degree, + "max_degree < supported_degree" + ); + let mut polynomials = Vec::new(); + let mut degree_bounds = if enforce_degree_bounds { + Some(Vec::new()) + } else { + None }; - let pp = PC::setup(max_degree, num_vars, rng)?; - - for _ in 0..num_iters { - let supported_degree = - supported_degree.unwrap_or(Uniform::from(1..=max_degree).sample(rng)); - assert!( - max_degree >= supported_degree, - "max_degree < supported_degree" - ); - let mut polynomials = Vec::new(); - let mut degree_bounds = if enforce_degree_bounds { - Some(Vec::new()) + + let mut labels = Vec::new(); + println!("Sampled supported degree"); + + // Generate polynomials + let num_points_in_query_set = Uniform::from(1..=max_num_queries).sample(rng); + for i in 0..num_polynomials { + let label = format!("Test{}", i); + labels.push(label.clone()); + let degree = Uniform::from(1..=supported_degree).sample(rng); + let degree_bound = if let Some(degree_bounds) = &mut degree_bounds { + if rng.gen() { + let range = Uniform::from(degree..=supported_degree); + let degree_bound = range.sample(rng); + degree_bounds.push(degree_bound); + Some(degree_bound) + } else { + None + } } else { None }; - let mut labels = Vec::new(); - println!("Sampled supported degree"); - - // Generate polynomials - let num_points_in_query_set = Uniform::from(1..=max_num_queries).sample(rng); - for i in 0..num_polynomials { - let label = format!("Test{}", i); - labels.push(label.clone()); - let degree = Uniform::from(1..=supported_degree).sample(rng); - let degree_bound = if let Some(degree_bounds) = &mut degree_bounds { - if rng.gen() { - let range = Uniform::from(degree..=supported_degree); - let degree_bound = range.sample(rng); - degree_bounds.push(degree_bound); - Some(degree_bound) + let hiding_bound = if num_points_in_query_set >= degree { + Some(degree) + } else { + Some(num_points_in_query_set) + }; + println!("Hiding bound: {:?}", hiding_bound); + + polynomials.push(LabeledPolynomial::new( + label, + rand_poly(degree, num_vars, rng), + degree_bound, + hiding_bound, + )) + } + println!("supported degree: {:?}", supported_degree); + println!("num_points_in_query_set: {:?}", num_points_in_query_set); + println!("{:?}", degree_bounds); + println!("{}", num_polynomials); + println!("{}", enforce_degree_bounds); + + let (ck, vk) = PC::trim( + &pp, + supported_degree, + supported_degree, + degree_bounds.as_ref().map(|s| s.as_slice()), + )?; + println!("Trimmed"); + + let (comms, states) = PC::commit(&ck, &polynomials, Some(rng))?; + + // Let's construct our equations + let mut linear_combinations = Vec::new(); + let mut query_set = QuerySet::new(); + let mut values = Evaluations::new(); + for i in 0..num_points_in_query_set { + let point = rand_point(num_vars, rng); + for j in 0..num_equations.unwrap() { + let label = format!("query {} eqn {}", i, j); + let mut lc = LinearCombination::empty(label.clone()); + + let mut value = F::zero(); + let should_have_degree_bounds: bool = rng.gen(); + for (k, label) in labels.iter().enumerate() { + if should_have_degree_bounds { + value += &polynomials[k].evaluate(&point); + lc.push((F::one(), label.to_string().into())); + break; } else { - None - } - } else { - None - }; - - let hiding_bound = if num_points_in_query_set >= degree { - Some(degree) - } else { - Some(num_points_in_query_set) - }; - println!("Hiding bound: {:?}", hiding_bound); - - polynomials.push(LabeledPolynomial::new( - label, - rand_poly(degree, num_vars, rng), - degree_bound, - hiding_bound, - )) - } - println!("supported degree: {:?}", supported_degree); - println!("num_points_in_query_set: {:?}", num_points_in_query_set); - println!("{:?}", degree_bounds); - println!("{}", num_polynomials); - println!("{}", enforce_degree_bounds); - - let (ck, vk) = PC::trim( - &pp, - supported_degree, - supported_degree, - degree_bounds.as_ref().map(|s| s.as_slice()), - )?; - println!("Trimmed"); - - let (comms, states) = PC::commit(&ck, &polynomials, Some(rng))?; - - // Let's construct our equations - let mut linear_combinations = Vec::new(); - let mut query_set = QuerySet::new(); - let mut values = Evaluations::new(); - for i in 0..num_points_in_query_set { - let point = rand_point(num_vars, rng); - for j in 0..num_equations.unwrap() { - let label = format!("query {} eqn {}", i, j); - let mut lc = LinearCombination::empty(label.clone()); - - let mut value = F::zero(); - let should_have_degree_bounds: bool = rng.gen(); - for (k, label) in labels.iter().enumerate() { - if should_have_degree_bounds { - value += &polynomials[k].evaluate(&point); - lc.push((F::one(), label.to_string().into())); - break; + let poly = &polynomials[k]; + if poly.degree_bound().is_some() { + continue; } else { - let poly = &polynomials[k]; - if poly.degree_bound().is_some() { - continue; - } else { - assert!(poly.degree_bound().is_none()); - let coeff = F::rand(rng); - value += &(coeff * poly.evaluate(&point)); - lc.push((coeff, label.to_string().into())); - } + assert!(poly.degree_bound().is_none()); + let coeff = F::rand(rng); + value += &(coeff * poly.evaluate(&point)); + lc.push((coeff, label.to_string().into())); } } - values.insert((label.clone(), point.clone()), value); - if !lc.is_empty() { - linear_combinations.push(lc); - // Insert query - query_set.insert((label.clone(), (format!("{}", i), point.clone()))); - } } - } - if linear_combinations.is_empty() { - continue; - } - println!("Generated query set"); - println!("Linear combinations: {:?}", linear_combinations); - - let proof = PC::open_combinations( - &ck, - &linear_combinations, - &polynomials, - &comms, - &query_set, - &mut (sponge.clone()), - &states, - Some(rng), - )?; - println!("Generated proof"); - let result = PC::check_combinations( - &vk, - &linear_combinations, - &comms, - &query_set, - &values, - &proof, - &mut (sponge.clone()), - rng, - )?; - if !result { - println!( - "Failed with {} polynomials, num_points_in_query_set: {:?}", - num_polynomials, num_points_in_query_set - ); - println!("Degree of polynomials:",); - for poly in polynomials { - println!("Degree: {:?}", poly.degree()); + values.insert((label.clone(), point.clone()), value); + if !lc.is_empty() { + linear_combinations.push(lc); + // Insert query + query_set.insert((label.clone(), (format!("{}", i), point.clone()))); } } - assert!( - result, - "proof was incorrect, equations: {:#?}", - linear_combinations + } + if linear_combinations.is_empty() { + continue; + } + println!("Generated query set"); + println!("Linear combinations: {:?}", linear_combinations); + + let proof = PC::open_combinations( + &ck, + &linear_combinations, + &polynomials, + &comms, + &query_set, + &mut (sponge.clone()), + &states, + Some(rng), + )?; + println!("Generated proof"); + let result = PC::check_combinations( + &vk, + &linear_combinations, + &comms, + &query_set, + &values, + &proof, + &mut (sponge.clone()), + rng, + )?; + if !result { + println!( + "Failed with {} polynomials, num_points_in_query_set: {:?}", + num_polynomials, num_points_in_query_set ); + println!("Degree of polynomials:",); + for poly in polynomials { + println!("Degree: {:?}", poly.degree()); + } } + assert!( + result, + "proof was incorrect, equations: {:#?}", + linear_combinations + ); } Ok(()) }