arnaucube
arnaucube/NovaPublic Self-hosted repository
Nova/src/spartan/sumcheck.rs
src/spartan/sumcheck.rsRaw
  1#![allow(clippy::too_many_arguments)]
  2#![allow(clippy::type_complexity)]
  3use super::polynomial::MultilinearPolynomial;
  4use crate::errors::NovaError;
  5use crate::traits::{Group, TranscriptEngineTrait, TranscriptReprTrait};
  6use core::marker::PhantomData;
  7use ff::Field;
  8use rayon::prelude::*;
  9use serde::{Deserialize, Serialize};
 10
 11#[derive(Clone, Debug, Serialize, Deserialize)]
 12#[serde(bound = "")]
 13pub(crate) struct SumcheckProof<G: Group> {
 14  compressed_polys: Vec<CompressedUniPoly<G>>,
 15}
 16
 17impl<G: Group> SumcheckProof<G> {
 18  pub fn new(compressed_polys: Vec<CompressedUniPoly<G>>) -> Self {
 19    Self { compressed_polys }
 20  }
 21
 22  pub fn verify(
 23    &self,
 24    claim: G::Scalar,
 25    num_rounds: usize,
 26    degree_bound: usize,
 27    transcript: &mut G::TE,
 28  ) -> Result<(G::Scalar, Vec<G::Scalar>), NovaError> {
 29    let mut e = claim;
 30    let mut r: Vec<G::Scalar> = Vec::new();
 31
 32    // verify that there is a univariate polynomial for each round
 33    if self.compressed_polys.len() != num_rounds {
 34      return Err(NovaError::InvalidSumcheckProof);
 35    }
 36
 37    for i in 0..self.compressed_polys.len() {
 38      let poly = self.compressed_polys[i].decompress(&e);
 39
 40      // verify degree bound
 41      if poly.degree() != degree_bound {
 42        return Err(NovaError::InvalidSumcheckProof);
 43      }
 44
 45      // we do not need to check if poly(0) + poly(1) = e, as
 46      // decompress() call above already ensures that hods
 47      debug_assert_eq!(poly.eval_at_zero() + poly.eval_at_one(), e);
 48
 49      // append the prover's message to the transcript
 50      transcript.absorb(b"p", &poly);
 51
 52      //derive the verifier's challenge for the next round
 53      let r_i = transcript.squeeze(b"c")?;
 54
 55      r.push(r_i);
 56
 57      // evaluate the claimed degree-ell polynomial at r_i
 58      e = poly.evaluate(&r_i);
 59    }
 60
 61    Ok((e, r))
 62  }
 63
 64  pub fn prove_quad<F>(
 65    claim: &G::Scalar,
 66    num_rounds: usize,
 67    poly_A: &mut MultilinearPolynomial<G::Scalar>,
 68    poly_B: &mut MultilinearPolynomial<G::Scalar>,
 69    comb_func: F,
 70    transcript: &mut G::TE,
 71  ) -> Result<(Self, Vec<G::Scalar>, Vec<G::Scalar>), NovaError>
 72  where
 73    F: Fn(&G::Scalar, &G::Scalar) -> G::Scalar + Sync,
 74  {
 75    let mut r: Vec<G::Scalar> = Vec::new();
 76    let mut polys: Vec<CompressedUniPoly<G>> = Vec::new();
 77    let mut claim_per_round = *claim;
 78    for _ in 0..num_rounds {
 79      let poly = {
 80        let len = poly_A.len() / 2;
 81
 82        // Make an iterator returning the contributions to the evaluations
 83        let (eval_point_0, eval_point_2) = (0..len)
 84          .into_par_iter()
 85          .map(|i| {
 86            // eval 0: bound_func is A(low)
 87            let eval_point_0 = comb_func(&poly_A[i], &poly_B[i]);
 88
 89            // eval 2: bound_func is -A(low) + 2*A(high)
 90            let poly_A_bound_point = poly_A[len + i] + poly_A[len + i] - poly_A[i];
 91            let poly_B_bound_point = poly_B[len + i] + poly_B[len + i] - poly_B[i];
 92            let eval_point_2 = comb_func(&poly_A_bound_point, &poly_B_bound_point);
 93            (eval_point_0, eval_point_2)
 94          })
 95          .reduce(
 96            || (G::Scalar::zero(), G::Scalar::zero()),
 97            |a, b| (a.0 + b.0, a.1 + b.1),
 98          );
 99
100        let evals = vec![eval_point_0, claim_per_round - eval_point_0, eval_point_2];
101        UniPoly::from_evals(&evals)
102      };
103
104      // append the prover's message to the transcript
105      transcript.absorb(b"p", &poly);
106
107      //derive the verifier's challenge for the next round
108      let r_i = transcript.squeeze(b"c")?;
109      r.push(r_i);
110      polys.push(poly.compress());
111
112      // Set up next round
113      claim_per_round = poly.evaluate(&r_i);
114
115      // bound all tables to the verifier's challenege
116      poly_A.bound_poly_var_top(&r_i);
117      poly_B.bound_poly_var_top(&r_i);
118    }
119
120    Ok((
121      SumcheckProof {
122        compressed_polys: polys,
123      },
124      r,
125      vec![poly_A[0], poly_B[0]],
126    ))
127  }
128
129  pub fn prove_quad_batch<F>(
130    claim: &G::Scalar,
131    num_rounds: usize,
132    poly_A_vec: &mut Vec<MultilinearPolynomial<G::Scalar>>,
133    poly_B_vec: &mut Vec<MultilinearPolynomial<G::Scalar>>,
134    coeffs: &[G::Scalar],
135    comb_func: F,
136    transcript: &mut G::TE,
137  ) -> Result<(Self, Vec<G::Scalar>, (Vec<G::Scalar>, Vec<G::Scalar>)), NovaError>
138  where
139    F: Fn(&G::Scalar, &G::Scalar) -> G::Scalar,
140  {
141    let mut e = *claim;
142    let mut r: Vec<G::Scalar> = Vec::new();
143    let mut quad_polys: Vec<CompressedUniPoly<G>> = Vec::new();
144
145    for _j in 0..num_rounds {
146      let mut evals: Vec<(G::Scalar, G::Scalar)> = Vec::new();
147
148      for (poly_A, poly_B) in poly_A_vec.iter().zip(poly_B_vec.iter()) {
149        let mut eval_point_0 = G::Scalar::zero();
150        let mut eval_point_2 = G::Scalar::zero();
151
152        let len = poly_A.len() / 2;
153        for i in 0..len {
154          // eval 0: bound_func is A(low)
155          eval_point_0 += comb_func(&poly_A[i], &poly_B[i]);
156
157          // eval 2: bound_func is -A(low) + 2*A(high)
158          let poly_A_bound_point = poly_A[len + i] + poly_A[len + i] - poly_A[i];
159          let poly_B_bound_point = poly_B[len + i] + poly_B[len + i] - poly_B[i];
160          eval_point_2 += comb_func(&poly_A_bound_point, &poly_B_bound_point);
161        }
162
163        evals.push((eval_point_0, eval_point_2));
164      }
165
166      let evals_combined_0 = (0..evals.len())
167        .map(|i| evals[i].0 * coeffs[i])
168        .fold(G::Scalar::zero(), |acc, item| acc + item);
169      let evals_combined_2 = (0..evals.len())
170        .map(|i| evals[i].1 * coeffs[i])
171        .fold(G::Scalar::zero(), |acc, item| acc + item);
172
173      let evals = vec![evals_combined_0, e - evals_combined_0, evals_combined_2];
174      let poly = UniPoly::from_evals(&evals);
175
176      // append the prover's message to the transcript
177      transcript.absorb(b"p", &poly);
178
179      // derive the verifier's challenge for the next round
180      let r_i = transcript.squeeze(b"c")?;
181      r.push(r_i);
182
183      // bound all tables to the verifier's challenege
184      for (poly_A, poly_B) in poly_A_vec.iter_mut().zip(poly_B_vec.iter_mut()) {
185        poly_A.bound_poly_var_top(&r_i);
186        poly_B.bound_poly_var_top(&r_i);
187      }
188
189      e = poly.evaluate(&r_i);
190      quad_polys.push(poly.compress());
191    }
192
193    let poly_A_final = (0..poly_A_vec.len()).map(|i| poly_A_vec[i][0]).collect();
194    let poly_B_final = (0..poly_B_vec.len()).map(|i| poly_B_vec[i][0]).collect();
195    let claims_prod = (poly_A_final, poly_B_final);
196
197    Ok((SumcheckProof::new(quad_polys), r, claims_prod))
198  }
199
200  pub fn prove_cubic_with_additive_term<F>(
201    claim: &G::Scalar,
202    num_rounds: usize,
203    poly_A: &mut MultilinearPolynomial<G::Scalar>,
204    poly_B: &mut MultilinearPolynomial<G::Scalar>,
205    poly_C: &mut MultilinearPolynomial<G::Scalar>,
206    poly_D: &mut MultilinearPolynomial<G::Scalar>,
207    comb_func: F,
208    transcript: &mut G::TE,
209  ) -> Result<(Self, Vec<G::Scalar>, Vec<G::Scalar>), NovaError>
210  where
211    F: Fn(&G::Scalar, &G::Scalar, &G::Scalar, &G::Scalar) -> G::Scalar + Sync,
212  {
213    let mut r: Vec<G::Scalar> = Vec::new();
214    let mut polys: Vec<CompressedUniPoly<G>> = Vec::new();
215    let mut claim_per_round = *claim;
216
217    for _ in 0..num_rounds {
218      let poly = {
219        let len = poly_A.len() / 2;
220
221        // Make an iterator returning the contributions to the evaluations
222        let (eval_point_0, eval_point_2, eval_point_3) = (0..len)
223          .into_par_iter()
224          .map(|i| {
225            // eval 0: bound_func is A(low)
226            let eval_point_0 = comb_func(&poly_A[i], &poly_B[i], &poly_C[i], &poly_D[i]);
227
228            // eval 2: bound_func is -A(low) + 2*A(high)
229            let poly_A_bound_point = poly_A[len + i] + poly_A[len + i] - poly_A[i];
230            let poly_B_bound_point = poly_B[len + i] + poly_B[len + i] - poly_B[i];
231            let poly_C_bound_point = poly_C[len + i] + poly_C[len + i] - poly_C[i];
232            let poly_D_bound_point = poly_D[len + i] + poly_D[len + i] - poly_D[i];
233            let eval_point_2 = comb_func(
234              &poly_A_bound_point,
235              &poly_B_bound_point,
236              &poly_C_bound_point,
237              &poly_D_bound_point,
238            );
239
240            // eval 3: bound_func is -2A(low) + 3A(high); computed incrementally with bound_func applied to eval(2)
241            let poly_A_bound_point = poly_A_bound_point + poly_A[len + i] - poly_A[i];
242            let poly_B_bound_point = poly_B_bound_point + poly_B[len + i] - poly_B[i];
243            let poly_C_bound_point = poly_C_bound_point + poly_C[len + i] - poly_C[i];
244            let poly_D_bound_point = poly_D_bound_point + poly_D[len + i] - poly_D[i];
245            let eval_point_3 = comb_func(
246              &poly_A_bound_point,
247              &poly_B_bound_point,
248              &poly_C_bound_point,
249              &poly_D_bound_point,
250            );
251            (eval_point_0, eval_point_2, eval_point_3)
252          })
253          .reduce(
254            || (G::Scalar::zero(), G::Scalar::zero(), G::Scalar::zero()),
255            |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2),
256          );
257
258        let evals = vec![
259          eval_point_0,
260          claim_per_round - eval_point_0,
261          eval_point_2,
262          eval_point_3,
263        ];
264        UniPoly::from_evals(&evals)
265      };
266
267      // append the prover's message to the transcript
268      transcript.absorb(b"p", &poly);
269
270      //derive the verifier's challenge for the next round
271      let r_i = transcript.squeeze(b"c")?;
272      r.push(r_i);
273      polys.push(poly.compress());
274
275      // Set up next round
276      claim_per_round = poly.evaluate(&r_i);
277
278      // bound all tables to the verifier's challenege
279      poly_A.bound_poly_var_top(&r_i);
280      poly_B.bound_poly_var_top(&r_i);
281      poly_C.bound_poly_var_top(&r_i);
282      poly_D.bound_poly_var_top(&r_i);
283    }
284
285    Ok((
286      SumcheckProof {
287        compressed_polys: polys,
288      },
289      r,
290      vec![poly_A[0], poly_B[0], poly_C[0], poly_D[0]],
291    ))
292  }
293}
294
295// ax^2 + bx + c stored as vec![a,b,c]
296// ax^3 + bx^2 + cx + d stored as vec![a,b,c,d]
297#[derive(Debug)]
298pub struct UniPoly<G: Group> {
299  coeffs: Vec<G::Scalar>,
300}
301
302// ax^2 + bx + c stored as vec![a,c]
303// ax^3 + bx^2 + cx + d stored as vec![a,c,d]
304#[derive(Clone, Debug, Serialize, Deserialize)]
305pub struct CompressedUniPoly<G: Group> {
306  coeffs_except_linear_term: Vec<G::Scalar>,
307  _p: PhantomData<G>,
308}
309
310impl<G: Group> UniPoly<G> {
311  pub fn from_evals(evals: &[G::Scalar]) -> Self {
312    // we only support degree-2 or degree-3 univariate polynomials
313    assert!(evals.len() == 3 || evals.len() == 4);
314    let coeffs = if evals.len() == 3 {
315      // ax^2 + bx + c
316      let two_inv = G::Scalar::from(2).invert().unwrap();
317
318      let c = evals[0];
319      let a = two_inv * (evals[2] - evals[1] - evals[1] + c);
320      let b = evals[1] - c - a;
321      vec![c, b, a]
322    } else {
323      // ax^3 + bx^2 + cx + d
324      let two_inv = G::Scalar::from(2).invert().unwrap();
325      let six_inv = G::Scalar::from(6).invert().unwrap();
326
327      let d = evals[0];
328      let a = six_inv
329        * (evals[3] - evals[2] - evals[2] - evals[2] + evals[1] + evals[1] + evals[1] - evals[0]);
330      let b = two_inv
331        * (evals[0] + evals[0] - evals[1] - evals[1] - evals[1] - evals[1] - evals[1]
332          + evals[2]
333          + evals[2]
334          + evals[2]
335          + evals[2]
336          - evals[3]);
337      let c = evals[1] - d - a - b;
338      vec![d, c, b, a]
339    };
340
341    UniPoly { coeffs }
342  }
343
344  pub fn degree(&self) -> usize {
345    self.coeffs.len() - 1
346  }
347
348  pub fn eval_at_zero(&self) -> G::Scalar {
349    self.coeffs[0]
350  }
351
352  pub fn eval_at_one(&self) -> G::Scalar {
353    (0..self.coeffs.len())
354      .into_par_iter()
355      .map(|i| self.coeffs[i])
356      .reduce(G::Scalar::zero, |a, b| a + b)
357  }
358
359  pub fn evaluate(&self, r: &G::Scalar) -> G::Scalar {
360    let mut eval = self.coeffs[0];
361    let mut power = *r;
362    for coeff in self.coeffs.iter().skip(1) {
363      eval += power * coeff;
364      power *= r;
365    }
366    eval
367  }
368
369  pub fn compress(&self) -> CompressedUniPoly<G> {
370    let coeffs_except_linear_term = [&self.coeffs[0..1], &self.coeffs[2..]].concat();
371    assert_eq!(coeffs_except_linear_term.len() + 1, self.coeffs.len());
372    CompressedUniPoly {
373      coeffs_except_linear_term,
374      _p: Default::default(),
375    }
376  }
377}
378
379impl<G: Group> CompressedUniPoly<G> {
380  // we require eval(0) + eval(1) = hint, so we can solve for the linear term as:
381  // linear_term = hint - 2 * constant_term - deg2 term - deg3 term
382  pub fn decompress(&self, hint: &G::Scalar) -> UniPoly<G> {
383    let mut linear_term =
384      *hint - self.coeffs_except_linear_term[0] - self.coeffs_except_linear_term[0];
385    for i in 1..self.coeffs_except_linear_term.len() {
386      linear_term -= self.coeffs_except_linear_term[i];
387    }
388
389    let mut coeffs: Vec<G::Scalar> = Vec::new();
390    coeffs.extend(vec![&self.coeffs_except_linear_term[0]]);
391    coeffs.extend(vec![&linear_term]);
392    coeffs.extend(self.coeffs_except_linear_term[1..].to_vec());
393    assert_eq!(self.coeffs_except_linear_term.len() + 1, coeffs.len());
394    UniPoly { coeffs }
395  }
396}
397
398impl<G: Group> TranscriptReprTrait<G> for UniPoly<G> {
399  fn to_transcript_bytes(&self) -> Vec<u8> {
400    let coeffs = self.compress().coeffs_except_linear_term;
401    coeffs.as_slice().to_transcript_bytes()
402  }
403}