snarkvm_algorithms/polycommit/sonic_pc/
mod.rs

1// Copyright 2024 Aleo Network Foundation
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use crate::{
17    AlgebraicSponge,
18    fft::DensePolynomial,
19    msm::variable_base::VariableBase,
20    polycommit::{PCError, kzg10, optional_rng::OptionalRng},
21    srs::{UniversalProver, UniversalVerifier},
22};
23use hashbrown::HashMap;
24use itertools::Itertools;
25use snarkvm_curves::traits::{AffineCurve, PairingCurve, PairingEngine, ProjectiveCurve};
26use snarkvm_fields::{One, Zero};
27
28use anyhow::{Result, bail, ensure};
29use core::{convert::TryInto, marker::PhantomData, ops::Mul};
30use rand_core::{RngCore, SeedableRng};
31use std::{
32    borrow::Borrow,
33    collections::{BTreeMap, BTreeSet},
34};
35
36mod data_structures;
37pub use data_structures::*;
38
39mod polynomial;
40pub use polynomial::*;
41
42/// Polynomial commitment based on [\[KZG10\]][kzg], with degree enforcement and
43/// batching taken from [[MBKM19, “Sonic”]][sonic] (more precisely, their
44/// counterparts in [[Gabizon19, “AuroraLight”]][al] that avoid negative G1 powers).
45/// The (optional) hiding property of the commitment scheme follows the approach
46/// described in [[CHMMVW20, “Marlin”]][marlin].
47///
48/// [kzg]: http://cacr.uwaterloo.ca/techreports/2010/cacr2010-10.pdf
49/// [sonic]: https://eprint.iacr.org/2019/099
50/// [al]: https://eprint.iacr.org/2019/601
51/// [marlin]: https://eprint.iacr.org/2019/1047
52#[derive(Clone, Debug)]
53pub struct SonicKZG10<E: PairingEngine, S: AlgebraicSponge<E::Fq, 2>> {
54    _engine: PhantomData<(E, S)>,
55}
56
57impl<E: PairingEngine, S: AlgebraicSponge<E::Fq, 2>> SonicKZG10<E, S> {
58    pub fn load_srs(max_degree: usize) -> Result<UniversalParams<E>, PCError> {
59        kzg10::KZG10::load_srs(max_degree).map_err(Into::into)
60    }
61
62    pub fn trim(
63        pp: &UniversalParams<E>,
64        supported_degree: usize,
65        supported_lagrange_sizes: impl IntoIterator<Item = usize>,
66        supported_hiding_bound: usize,
67        enforced_degree_bounds: Option<&[usize]>,
68    ) -> Result<(CommitterKey<E>, UniversalVerifier<E>)> {
69        let trim_time = start_timer!(|| "Trimming public parameters");
70        let max_degree = pp.max_degree();
71
72        let enforced_degree_bounds = enforced_degree_bounds.map(|bounds| {
73            let mut v = bounds.to_vec();
74            v.sort_unstable();
75            v.dedup();
76            v
77        });
78
79        let (shifted_powers_of_beta_g, shifted_powers_of_beta_times_gamma_g) = if let Some(enforced_degree_bounds) =
80            enforced_degree_bounds.as_ref()
81        {
82            if enforced_degree_bounds.is_empty() {
83                (None, None)
84            } else {
85                let highest_enforced_degree_bound = *enforced_degree_bounds.last().unwrap();
86                if highest_enforced_degree_bound > supported_degree {
87                    bail!(
88                        "The highest enforced degree bound {highest_enforced_degree_bound} is larger than the supported degree {supported_degree}"
89                    );
90                }
91
92                let lowest_shift_degree = max_degree - highest_enforced_degree_bound;
93
94                let shifted_ck_time = start_timer!(|| format!(
95                    "Constructing `shifted_powers_of_beta_g` of size {}",
96                    max_degree - lowest_shift_degree + 1
97                ));
98
99                let shifted_powers_of_beta_g = pp.powers_of_beta_g(lowest_shift_degree, pp.max_degree() + 1)?;
100                let mut shifted_powers_of_beta_times_gamma_g = BTreeMap::new();
101                // Also add degree 0.
102                for degree_bound in enforced_degree_bounds {
103                    let shift_degree = max_degree - degree_bound;
104                    // We have an additional degree in `powers_of_beta_times_gamma_g` beyond `powers_of_beta_g`.
105                    let powers_for_degree_bound = pp
106                        .powers_of_beta_times_gamma_g()
107                        .range(shift_degree..max_degree.min(shift_degree + supported_hiding_bound) + 2)
108                        .map(|(_k, v)| *v)
109                        .collect();
110                    shifted_powers_of_beta_times_gamma_g.insert(*degree_bound, powers_for_degree_bound);
111                }
112
113                end_timer!(shifted_ck_time);
114
115                (Some(shifted_powers_of_beta_g), Some(shifted_powers_of_beta_times_gamma_g))
116            }
117        } else {
118            (None, None)
119        };
120
121        let powers_of_beta_g = pp.powers_of_beta_g(0, supported_degree + 1)?;
122        let powers_of_beta_times_gamma_g = pp
123            .powers_of_beta_times_gamma_g()
124            .range(0..=(supported_hiding_bound + 1))
125            .map(|(_k, v)| *v)
126            .collect::<Vec<_>>();
127        if powers_of_beta_times_gamma_g.len() != supported_hiding_bound + 2 {
128            return Err(
129                PCError::HidingBoundToolarge { hiding_poly_degree: supported_hiding_bound, num_powers: 0 }.into()
130            );
131        }
132
133        let mut lagrange_bases_at_beta_g = BTreeMap::new();
134        for size in supported_lagrange_sizes {
135            let lagrange_time = start_timer!(|| format!("Constructing `lagrange_bases` of size {size}"));
136            if !size.is_power_of_two() {
137                bail!("The Lagrange basis size ({size}) is not a power of two")
138            }
139            if size > pp.max_degree() + 1 {
140                bail!("The Lagrange basis size ({size}) is larger than the supported degree ({})", pp.max_degree() + 1)
141            }
142            let domain = crate::fft::EvaluationDomain::new(size).unwrap();
143            let lagrange_basis_at_beta_g = pp.lagrange_basis(domain)?;
144            assert!(lagrange_basis_at_beta_g.len().is_power_of_two());
145            lagrange_bases_at_beta_g.insert(domain.size(), lagrange_basis_at_beta_g);
146            end_timer!(lagrange_time);
147        }
148
149        let ck = CommitterKey {
150            powers_of_beta_g,
151            lagrange_bases_at_beta_g,
152            powers_of_beta_times_gamma_g,
153            shifted_powers_of_beta_g,
154            shifted_powers_of_beta_times_gamma_g,
155            enforced_degree_bounds,
156        };
157
158        let vk = pp.to_universal_verifier()?;
159
160        end_timer!(trim_time);
161        Ok((ck, vk))
162    }
163
164    /// Outputs commitments to `polynomials`.
165    ///
166    /// If `polynomials[i].is_hiding()`, then the `i`-th commitment is hiding
167    /// up to `polynomials.hiding_bound()` queries.
168    ///
169    /// `rng` should not be `None` if `polynomials[i].is_hiding() == true` for any `i`.
170    ///
171    /// If for some `i`, `polynomials[i].is_hiding() == false`, then the
172    /// corresponding randomness is `Randomness<E>::empty()`.
173    ///
174    /// If for some `i`, `polynomials[i].degree_bound().is_some()`, then that
175    /// polynomial will have the corresponding degree bound enforced.
176    #[allow(clippy::format_push_string)]
177    pub fn commit<'b>(
178        universal_prover: &UniversalProver<E>,
179        ck: &CommitterUnionKey<E>,
180        polynomials: impl IntoIterator<Item = LabeledPolynomialWithBasis<'b, E::Fr>>,
181        rng: Option<&mut dyn RngCore>,
182    ) -> Result<(Vec<LabeledCommitment<Commitment<E>>>, Vec<Randomness<E>>), PCError> {
183        let rng = &mut OptionalRng(rng);
184        let commit_time = start_timer!(|| "Committing to polynomials");
185
186        let mut pool = snarkvm_utilities::ExecutionPool::<Result<_, _>>::new();
187        for p in polynomials {
188            let seed = rng.0.as_mut().map(|r| {
189                let mut seed = [0u8; 32];
190                r.fill_bytes(&mut seed);
191                seed
192            });
193
194            kzg10::KZG10::<E>::check_degrees_and_bounds(
195                universal_prover.max_degree,
196                ck.enforced_degree_bounds.as_deref(),
197                p.clone(),
198            )?;
199            let degree_bound = p.degree_bound();
200            let hiding_bound = p.hiding_bound();
201            let label = p.label().to_string();
202
203            pool.add_job(move || {
204                let mut rng = seed.map(rand::rngs::StdRng::from_seed);
205                add_to_trace!(|| "PC::Commit", || format!(
206                    "Polynomial {} of degree {}, degree bound {:?}, and hiding bound {:?}",
207                    label,
208                    p.degree(),
209                    degree_bound,
210                    hiding_bound,
211                ));
212
213                let (comm, rand) = {
214                    let rng_ref = rng.as_mut().map(|s| s as _);
215                    match p.polynomial {
216                        PolynomialWithBasis::Lagrange { evaluations } => {
217                            let domain = crate::fft::EvaluationDomain::new(evaluations.evaluations.len()).unwrap();
218                            let lagrange_basis = ck
219                                .lagrange_basis(domain)
220                                .ok_or(PCError::UnsupportedLagrangeBasisSize(domain.size()))?;
221                            assert!(domain.size().is_power_of_two());
222                            assert!(lagrange_basis.size().is_power_of_two());
223                            kzg10::KZG10::commit_lagrange(
224                                &lagrange_basis,
225                                &evaluations.evaluations,
226                                hiding_bound,
227                                rng_ref,
228                            )?
229                        }
230                        PolynomialWithBasis::Monomial { polynomial, degree_bound } => {
231                            let powers = if let Some(degree_bound) = degree_bound {
232                                ck.shifted_powers_of_beta_g(degree_bound).unwrap()
233                            } else {
234                                ck.powers()
235                            };
236
237                            kzg10::KZG10::commit(&powers, &polynomial, hiding_bound, rng_ref)?
238                        }
239                    }
240                };
241
242                Ok((LabeledCommitment::new(label.to_string(), comm, degree_bound), rand))
243            });
244        }
245        let results: Vec<Result<_, PCError>> = pool.execute_all();
246
247        let mut labeled_comms = Vec::with_capacity(results.len());
248        let mut randomness = Vec::with_capacity(results.len());
249        for result in results {
250            let (comm, rand) = result?;
251            labeled_comms.push(comm);
252            randomness.push(rand);
253        }
254
255        end_timer!(commit_time);
256        Ok((labeled_comms, randomness))
257    }
258
259    pub fn combine_for_open<'a>(
260        universal_prover: &UniversalProver<E>,
261        ck: &CommitterUnionKey<E>,
262        labeled_polynomials: impl ExactSizeIterator<Item = &'a LabeledPolynomial<E::Fr>>,
263        rands: impl ExactSizeIterator<Item = &'a Randomness<E>>,
264        fs_rng: &mut S,
265    ) -> Result<(DensePolynomial<E::Fr>, Randomness<E>)>
266    where
267        Randomness<E>: 'a,
268        Commitment<E>: 'a,
269    {
270        ensure!(labeled_polynomials.len() == rands.len());
271        let mut to_combine = Vec::with_capacity(labeled_polynomials.len());
272
273        for (p, r) in labeled_polynomials.zip_eq(rands) {
274            let enforced_degree_bounds: Option<&[usize]> = ck.enforced_degree_bounds.as_deref();
275
276            kzg10::KZG10::<E>::check_degrees_and_bounds(universal_prover.max_degree, enforced_degree_bounds, p)?;
277            let challenge = fs_rng.squeeze_short_nonnative_field_element::<E::Fr>();
278            to_combine.push((challenge, p.polynomial().to_dense(), r));
279        }
280
281        Ok(Self::combine_polynomials(to_combine))
282    }
283
284    /// On input a list of labeled polynomials and a query set, `open` outputs a proof of evaluation
285    /// of the polynomials at the points in the query set.
286    pub fn batch_open<'a>(
287        universal_prover: &UniversalProver<E>,
288        ck: &CommitterUnionKey<E>,
289        labeled_polynomials: impl ExactSizeIterator<Item = &'a LabeledPolynomial<E::Fr>>,
290        query_set: &QuerySet<E::Fr>,
291        rands: impl ExactSizeIterator<Item = &'a Randomness<E>>,
292        fs_rng: &mut S,
293    ) -> Result<BatchProof<E>>
294    where
295        Randomness<E>: 'a,
296        Commitment<E>: 'a,
297    {
298        ensure!(labeled_polynomials.len() == rands.len());
299        let poly_rand: HashMap<_, _> =
300            labeled_polynomials.into_iter().zip_eq(rands).map(|(poly, r)| (poly.label(), (poly, r))).collect();
301
302        let open_time = start_timer!(|| format!(
303            "Opening {} polynomials at query set of size {}",
304            poly_rand.len(),
305            query_set.len(),
306        ));
307
308        let mut query_to_labels_map = BTreeMap::new();
309
310        for (label, (point_name, point)) in query_set.iter() {
311            let labels = query_to_labels_map.entry(point_name).or_insert((point, BTreeSet::new()));
312            labels.1.insert(label);
313        }
314
315        let mut pool = snarkvm_utilities::ExecutionPool::<_>::with_capacity(query_to_labels_map.len());
316        for (_point_name, (&query, labels)) in query_to_labels_map.into_iter() {
317            let mut query_polys = Vec::with_capacity(labels.len());
318            let mut query_rands = Vec::with_capacity(labels.len());
319
320            for label in labels {
321                let (polynomial, rand) =
322                    poly_rand.get(label as &str).ok_or(PCError::MissingPolynomial { label: label.to_string() })?;
323
324                query_polys.push(*polynomial);
325                query_rands.push(*rand);
326            }
327            let (polynomial, rand) =
328                Self::combine_for_open(universal_prover, ck, query_polys.into_iter(), query_rands.into_iter(), fs_rng)?;
329            let _randomizer = fs_rng.squeeze_short_nonnative_field_element::<E::Fr>();
330
331            pool.add_job(move || {
332                let proof_time = start_timer!(|| "Creating proof");
333                let proof = kzg10::KZG10::open(&ck.powers(), &polynomial, query, &rand);
334                end_timer!(proof_time);
335                proof
336            });
337        }
338        let batch_proof = pool.execute_all().into_iter().collect::<Result<_, _>>().map(BatchProof).map_err(Into::into);
339        end_timer!(open_time);
340
341        batch_proof
342    }
343
344    pub fn batch_check<'a>(
345        vk: &UniversalVerifier<E>,
346        commitments: impl IntoIterator<Item = &'a LabeledCommitment<Commitment<E>>>,
347        query_set: &QuerySet<E::Fr>,
348        values: &Evaluations<E::Fr>,
349        proof: &BatchProof<E>,
350        fs_rng: &mut S,
351    ) -> Result<bool>
352    where
353        Commitment<E>: 'a,
354    {
355        let commitments: BTreeMap<_, _> = commitments.into_iter().map(|c| (c.label().to_owned(), c)).collect();
356        let batch_check_time = start_timer!(|| format!(
357            "Checking {} commitments at query set of size {}",
358            commitments.len(),
359            query_set.len(),
360        ));
361        let mut query_to_labels_map = BTreeMap::new();
362
363        for (label, (point_name, point)) in query_set.iter() {
364            let labels = query_to_labels_map.entry(point_name).or_insert((point, BTreeSet::new()));
365            labels.1.insert(label);
366        }
367
368        assert_eq!(proof.0.len(), query_to_labels_map.len());
369
370        let mut randomizer = E::Fr::one();
371
372        let mut combined_comms = BTreeMap::new();
373        let mut combined_witness = E::G1Projective::zero();
374        let mut combined_adjusted_witness = E::G1Projective::zero();
375
376        ensure!(query_to_labels_map.len() == proof.0.len());
377        for ((_query_name, (query, labels)), p) in query_to_labels_map.into_iter().zip_eq(&proof.0) {
378            let mut comms_to_combine: Vec<&'_ LabeledCommitment<_>> = Vec::new();
379            let mut values_to_combine = Vec::new();
380            for label in labels.into_iter() {
381                let commitment =
382                    commitments.get(label).ok_or(PCError::MissingPolynomial { label: label.to_string() })?;
383
384                let v_i = values
385                    .get(&(label.clone(), *query))
386                    .ok_or(PCError::MissingEvaluation { label: label.to_string() })?;
387
388                comms_to_combine.push(commitment);
389                values_to_combine.push(*v_i);
390            }
391
392            Self::accumulate_elems(
393                &mut combined_comms,
394                &mut combined_witness,
395                &mut combined_adjusted_witness,
396                vk,
397                comms_to_combine.into_iter(),
398                *query,
399                values_to_combine.into_iter(),
400                p,
401                Some(randomizer),
402                fs_rng,
403            )?;
404
405            randomizer = fs_rng.squeeze_short_nonnative_field_element::<E::Fr>();
406        }
407
408        let result = Self::check_elems(vk, combined_comms, combined_witness, combined_adjusted_witness);
409        end_timer!(batch_check_time);
410        result.map_err(Into::into)
411    }
412
413    pub fn open_combinations<'a>(
414        universal_prover: &UniversalProver<E>,
415        ck: &CommitterUnionKey<E>,
416        linear_combinations: impl IntoIterator<Item = &'a LinearCombination<E::Fr>>,
417        polynomials: impl IntoIterator<Item = LabeledPolynomial<E::Fr>>,
418        rands: impl IntoIterator<Item = &'a Randomness<E>>,
419        query_set: &QuerySet<E::Fr>,
420        fs_rng: &mut S,
421    ) -> Result<BatchLCProof<E>>
422    where
423        Randomness<E>: 'a,
424        Commitment<E>: 'a,
425    {
426        let label_map =
427            polynomials.into_iter().zip_eq(rands).map(|(p, r)| (p.to_label(), (p, r))).collect::<BTreeMap<_, _>>();
428
429        let mut lc_polynomials = Vec::new();
430        let mut lc_randomness = Vec::new();
431        let mut lc_info = Vec::new();
432
433        for lc in linear_combinations {
434            let lc_label = lc.label().to_string();
435            let mut poly = DensePolynomial::zero();
436            let mut randomness = Randomness::empty();
437            let mut degree_bound = None;
438            let mut hiding_bound = None;
439
440            let num_polys = lc.len();
441            // We filter out l.is_one() entries because those constants are not committed to and used directly by the verifier.
442            for (coeff, label) in lc.iter().filter(|(_, l)| !l.is_one()) {
443                let label: &String = label.try_into().expect("cannot be one!");
444                let (cur_poly, cur_rand) =
445                    label_map.get(label as &str).ok_or(PCError::MissingPolynomial { label: label.to_string() })?;
446                if let Some(cur_degree_bound) = cur_poly.degree_bound() {
447                    if num_polys != 1 {
448                        bail!(PCError::EquationHasDegreeBounds(lc_label));
449                    }
450                    assert!(coeff.is_one(), "Coefficient must be one for degree-bounded equations");
451                    if let Some(old_degree_bound) = degree_bound {
452                        assert_eq!(old_degree_bound, cur_degree_bound)
453                    } else {
454                        degree_bound = cur_poly.degree_bound();
455                    }
456                }
457                // Some(_) > None, always.
458                hiding_bound = core::cmp::max(hiding_bound, cur_poly.hiding_bound());
459                poly += (*coeff, cur_poly.polynomial());
460                randomness += (*coeff, *cur_rand);
461            }
462
463            let lc_poly = LabeledPolynomial::new(lc_label.clone(), poly, degree_bound, hiding_bound);
464            lc_polynomials.push(lc_poly);
465            lc_randomness.push(randomness);
466            lc_info.push((lc_label, degree_bound));
467        }
468
469        let proof =
470            Self::batch_open(universal_prover, ck, lc_polynomials.iter(), query_set, lc_randomness.iter(), fs_rng)?;
471
472        Ok(BatchLCProof { proof })
473    }
474
475    /// Checks that `values` are the true evaluations at `query_set` of the polynomials
476    /// committed in `labeled_commitments`.
477    pub fn check_combinations<'a>(
478        vk: &UniversalVerifier<E>,
479        linear_combinations: impl IntoIterator<Item = &'a LinearCombination<E::Fr>>,
480        commitments: impl IntoIterator<Item = &'a LabeledCommitment<Commitment<E>>>,
481        query_set: &QuerySet<E::Fr>,
482        evaluations: &Evaluations<E::Fr>,
483        proof: &BatchLCProof<E>,
484        fs_rng: &mut S,
485    ) -> Result<bool>
486    where
487        Commitment<E>: 'a,
488    {
489        let BatchLCProof { proof } = proof;
490        let label_comm_map = commitments.into_iter().map(|c| (c.label(), c)).collect::<BTreeMap<_, _>>();
491
492        let mut lc_commitments = Vec::new();
493        let mut lc_info = Vec::new();
494        let mut evaluations = evaluations.clone();
495
496        let lc_processing_time = start_timer!(|| "Combining commitments");
497        for lc in linear_combinations {
498            let lc_label = lc.label().to_string();
499            let num_polys = lc.len();
500
501            let mut degree_bound = None;
502            let mut coeffs_and_comms = Vec::new();
503
504            for (coeff, label) in lc.iter() {
505                if label.is_one() {
506                    for ((label, _), ref mut eval) in evaluations.iter_mut() {
507                        if label == &lc_label {
508                            **eval -= coeff;
509                        }
510                    }
511                } else {
512                    let label: &String = label.try_into().unwrap();
513                    let &cur_comm = label_comm_map
514                        .get(label as &str)
515                        .ok_or(PCError::MissingPolynomial { label: label.to_string() })?;
516
517                    if cur_comm.degree_bound().is_some() {
518                        if num_polys != 1 || !coeff.is_one() {
519                            bail!(PCError::EquationHasDegreeBounds(lc_label));
520                        }
521                        degree_bound = cur_comm.degree_bound();
522                    }
523                    coeffs_and_comms.push((*coeff, cur_comm.commitment()));
524                }
525            }
526            let lc_time = start_timer!(|| format!("Combining {num_polys} commitments for {lc_label}"));
527            lc_commitments.push(Self::combine_commitments(coeffs_and_comms));
528            end_timer!(lc_time);
529            lc_info.push((lc_label, degree_bound));
530        }
531        end_timer!(lc_processing_time);
532
533        let combined_comms_norm_time = start_timer!(|| "Normalizing commitments");
534        let comms = Self::normalize_commitments(lc_commitments);
535        ensure!(lc_info.len() == comms.len());
536        let lc_commitments = lc_info
537            .into_iter()
538            .zip_eq(comms)
539            .map(|((label, d), c)| LabeledCommitment::new(label, c, d))
540            .collect::<Vec<_>>();
541        end_timer!(combined_comms_norm_time);
542
543        Self::batch_check(vk, &lc_commitments, query_set, &evaluations, proof, fs_rng)
544    }
545}
546
547impl<E: PairingEngine, S: AlgebraicSponge<E::Fq, 2>> SonicKZG10<E, S> {
548    fn combine_polynomials<'a, B: Borrow<DensePolynomial<E::Fr>>>(
549        coeffs_polys_rands: impl IntoIterator<Item = (E::Fr, B, &'a Randomness<E>)>,
550    ) -> (DensePolynomial<E::Fr>, Randomness<E>) {
551        let mut combined_poly = DensePolynomial::zero();
552        let mut combined_rand = Randomness::empty();
553        for (coeff, poly, rand) in coeffs_polys_rands {
554            let poly = poly.borrow();
555            if coeff.is_one() {
556                combined_poly += poly;
557                combined_rand += rand;
558            } else {
559                combined_poly += (coeff, poly);
560                combined_rand += (coeff, rand);
561            }
562        }
563        (combined_poly, combined_rand)
564    }
565
566    /// MSM for `commitments` and `coeffs`
567    fn combine_commitments<'a>(
568        coeffs_and_comms: impl IntoIterator<Item = (E::Fr, &'a Commitment<E>)>,
569    ) -> E::G1Projective {
570        let (scalars, bases): (Vec<_>, Vec<_>) = coeffs_and_comms.into_iter().map(|(f, c)| (f.into(), c.0)).unzip();
571        VariableBase::msm(&bases, &scalars)
572    }
573
574    fn normalize_commitments(commitments: Vec<E::G1Projective>) -> impl ExactSizeIterator<Item = Commitment<E>> {
575        let comms = E::G1Projective::batch_normalization_into_affine(commitments);
576        comms.into_iter().map(|c| kzg10::KZGCommitment(c))
577    }
578}
579
580impl<E: PairingEngine, S: AlgebraicSponge<E::Fq, 2>> SonicKZG10<E, S> {
581    #[allow(clippy::too_many_arguments)]
582    fn accumulate_elems<'a>(
583        combined_comms: &mut BTreeMap<Option<usize>, E::G1Projective>,
584        combined_witness: &mut E::G1Projective,
585        combined_adjusted_witness: &mut E::G1Projective,
586        vk: &UniversalVerifier<E>,
587        commitments: impl ExactSizeIterator<Item = &'a LabeledCommitment<Commitment<E>>>,
588        point: E::Fr,
589        values: impl ExactSizeIterator<Item = E::Fr>,
590        proof: &kzg10::KZGProof<E>,
591        randomizer: Option<E::Fr>,
592        fs_rng: &mut S,
593    ) -> Result<()> {
594        let acc_time = start_timer!(|| "Accumulating elements");
595        // Keeps track of running combination of values
596        let mut combined_values = E::Fr::zero();
597
598        // Iterates through all of the commitments and accumulates common degree_bound elements in a BTreeMap
599        ensure!(commitments.len() == values.len());
600        for (labeled_comm, value) in commitments.into_iter().zip_eq(values) {
601            let acc_timer = start_timer!(|| format!("Accumulating {}", labeled_comm.label()));
602            let curr_challenge = fs_rng.squeeze_short_nonnative_field_element::<E::Fr>();
603
604            combined_values += &(value * curr_challenge);
605
606            let comm = labeled_comm.commitment();
607            let degree_bound = labeled_comm.degree_bound();
608
609            // Applying opening challenge and randomness (used in batch_checking)
610            let coeff = randomizer.unwrap_or_else(E::Fr::one) * curr_challenge;
611            let comm_with_challenge: E::G1Projective = comm.0.mul(coeff);
612
613            // Accumulate values in the BTreeMap
614            *combined_comms.entry(degree_bound).or_insert_with(E::G1Projective::zero) += &comm_with_challenge;
615            end_timer!(acc_timer);
616        }
617
618        // Push expected results into list of elems. Power will be the negative of the expected power
619        let mut bases = vec![vk.vk.g, -proof.w];
620        let mut coeffs = vec![combined_values, point];
621        if let Some(random_v) = proof.random_v {
622            bases.push(vk.vk.gamma_g);
623            coeffs.push(random_v);
624        }
625        *combined_witness += if let Some(randomizer) = randomizer {
626            coeffs.iter_mut().for_each(|c| *c *= randomizer);
627            proof.w.mul(randomizer)
628        } else {
629            proof.w.to_projective()
630        };
631        let coeffs = coeffs.into_iter().map(|c| c.into()).collect::<Vec<_>>();
632        *combined_adjusted_witness += VariableBase::msm(&bases, &coeffs);
633        end_timer!(acc_time);
634        Ok(())
635    }
636
637    fn check_elems(
638        vk: &UniversalVerifier<E>,
639        combined_comms: BTreeMap<Option<usize>, E::G1Projective>,
640        combined_witness: E::G1Projective,
641        combined_adjusted_witness: E::G1Projective,
642    ) -> Result<bool> {
643        let check_time = start_timer!(|| "Checking elems");
644        let mut g1_projective_elems = Vec::with_capacity(combined_comms.len() + 2);
645        let mut g2_prepared_elems = Vec::with_capacity(combined_comms.len() + 2);
646
647        for (degree_bound, comm) in combined_comms.into_iter() {
648            let shift_power = if let Some(degree_bound) = degree_bound {
649                // Find the appropriate prepared shift for the degree bound.
650                vk.prepared_negative_powers_of_beta_h
651                    .get(&degree_bound)
652                    .cloned()
653                    .ok_or(PCError::UnsupportedDegreeBound(degree_bound))?
654            } else {
655                vk.vk.prepared_h.clone()
656            };
657
658            g1_projective_elems.push(comm);
659            g2_prepared_elems.push(shift_power);
660        }
661
662        g1_projective_elems.push(-combined_adjusted_witness);
663        g2_prepared_elems.push(vk.vk.prepared_h.clone());
664
665        g1_projective_elems.push(-combined_witness);
666        g2_prepared_elems.push(vk.vk.prepared_beta_h.clone());
667
668        let g1_prepared_elems_iter = E::G1Projective::batch_normalization_into_affine(g1_projective_elems)
669            .into_iter()
670            .map(|a| a.prepare())
671            .collect::<Vec<_>>();
672
673        ensure!(g1_prepared_elems_iter.len() == g2_prepared_elems.len());
674        let g1_g2_prepared = g1_prepared_elems_iter.iter().zip_eq(g2_prepared_elems.iter());
675        let is_one: bool = E::product_of_pairings(g1_g2_prepared).is_one();
676        end_timer!(check_time);
677        Ok(is_one)
678    }
679}
680
681#[cfg(test)]
682mod tests {
683    #![allow(non_camel_case_types)]
684
685    use super::{CommitterKey, SonicKZG10};
686    use crate::{crypto_hash::PoseidonSponge, polycommit::test_templates::*};
687    use snarkvm_curves::bls12_377::{Bls12_377, Fq};
688    use snarkvm_utilities::{FromBytes, ToBytes, rand::TestRng};
689
690    use rand::distributions::Distribution;
691
692    type Sponge = PoseidonSponge<Fq, 2, 1>;
693    type PC_Bls12_377 = SonicKZG10<Bls12_377, Sponge>;
694
695    #[test]
696    fn test_committer_key_serialization() {
697        let rng = &mut TestRng::default();
698        let max_degree = rand::distributions::Uniform::from(8..=64).sample(rng);
699        let supported_degree = rand::distributions::Uniform::from(1..=max_degree).sample(rng);
700
701        let lagrange_size = |d: usize| if d.is_power_of_two() { d } else { d.next_power_of_two() >> 1 };
702
703        let pp = PC_Bls12_377::load_srs(max_degree).unwrap();
704
705        let (ck, _vk) = PC_Bls12_377::trim(&pp, supported_degree, [lagrange_size(supported_degree)], 0, None).unwrap();
706
707        let ck_bytes = ck.to_bytes_le().unwrap();
708        let ck_recovered: CommitterKey<Bls12_377> = FromBytes::read_le(&ck_bytes[..]).unwrap();
709        let ck_recovered_bytes = ck_recovered.to_bytes_le().unwrap();
710
711        assert_eq!(&ck_bytes, &ck_recovered_bytes);
712    }
713
714    #[test]
715    fn test_single_poly() {
716        single_poly_test::<Bls12_377, Sponge>().expect("test failed for bls12-377");
717    }
718
719    #[test]
720    fn test_quadratic_poly_degree_bound_multiple_queries() {
721        quadratic_poly_degree_bound_multiple_queries_test::<Bls12_377, Sponge>().expect("test failed for bls12-377");
722    }
723
724    #[test]
725    fn test_linear_poly_degree_bound() {
726        linear_poly_degree_bound_test::<Bls12_377, Sponge>().expect("test failed for bls12-377");
727    }
728
729    #[test]
730    fn test_single_poly_degree_bound() {
731        single_poly_degree_bound_test::<Bls12_377, Sponge>().expect("test failed for bls12-377");
732    }
733
734    #[test]
735    fn test_single_poly_degree_bound_multiple_queries() {
736        single_poly_degree_bound_multiple_queries_test::<Bls12_377, Sponge>().expect("test failed for bls12-377");
737    }
738
739    #[test]
740    fn test_two_polys_degree_bound_single_query() {
741        two_polys_degree_bound_single_query_test::<Bls12_377, Sponge>().expect("test failed for bls12-377");
742    }
743
744    #[test]
745    fn test_full_end_to_end() {
746        full_end_to_end_test::<Bls12_377, Sponge>().expect("test failed for bls12-377");
747        println!("Finished bls12-377");
748    }
749
750    #[test]
751    fn test_single_equation() {
752        single_equation_test::<Bls12_377, Sponge>().expect("test failed for bls12-377");
753        println!("Finished bls12-377");
754    }
755
756    #[test]
757    fn test_two_equation() {
758        two_equation_test::<Bls12_377, Sponge>().expect("test failed for bls12-377");
759        println!("Finished bls12-377");
760    }
761
762    #[test]
763    fn test_two_equation_degree_bound() {
764        two_equation_degree_bound_test::<Bls12_377, Sponge>().expect("test failed for bls12-377");
765        println!("Finished bls12-377");
766    }
767
768    #[test]
769    fn test_full_end_to_end_equation() {
770        full_end_to_end_equation_test::<Bls12_377, Sponge>().expect("test failed for bls12-377");
771        println!("Finished bls12-377");
772    }
773
774    #[test]
775    #[should_panic]
776    fn test_bad_degree_bound() {
777        bad_degree_bound_test::<Bls12_377, Sponge>().expect("test failed for bls12-377");
778        println!("Finished bls12-377");
779    }
780
781    #[test]
782    fn test_lagrange_commitment() {
783        crate::polycommit::test_templates::lagrange_test_template::<Bls12_377, Sponge>()
784            .expect("test failed for bls12-377");
785        println!("Finished bls12-377");
786    }
787}