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_sum<F>(
130    claim: &G::Scalar,
131    num_rounds: usize,
132    poly_A: &mut MultilinearPolynomial<G::Scalar>,
133    poly_B: &mut MultilinearPolynomial<G::Scalar>,
134    poly_C: &mut MultilinearPolynomial<G::Scalar>,
135    poly_D: &mut MultilinearPolynomial<G::Scalar>,
136    comb_func: F,
137    transcript: &mut G::TE,
138  ) -> Result<(Self, Vec<G::Scalar>, Vec<G::Scalar>), NovaError>
139  where
140    F: Fn(&G::Scalar, &G::Scalar, &G::Scalar, &G::Scalar) -> G::Scalar + Sync,
141  {
142    let mut r: Vec<G::Scalar> = Vec::new();
143    let mut polys: Vec<CompressedUniPoly<G>> = Vec::new();
144    let mut claim_per_round = *claim;
145    for _ in 0..num_rounds {
146      let poly = {
147        let len = poly_A.len() / 2;
148
149        // Make an iterator returning the contributions to the evaluations
150        let (eval_point_0, eval_point_2) = (0..len)
151          .into_par_iter()
152          .map(|i| {
153            // eval 0: bound_func is A(low)
154            let eval_point_0 = comb_func(&poly_A[i], &poly_B[i], &poly_C[i], &poly_D[i]);
155
156            // eval 2: bound_func is -A(low) + 2*A(high)
157            let poly_A_bound_point = poly_A[len + i] + poly_A[len + i] - poly_A[i];
158            let poly_B_bound_point = poly_B[len + i] + poly_B[len + i] - poly_B[i];
159            let poly_C_bound_point = poly_C[len + i] + poly_C[len + i] - poly_C[i];
160            let poly_D_bound_point = poly_D[len + i] + poly_D[len + i] - poly_D[i];
161            let eval_point_2 = comb_func(
162              &poly_A_bound_point,
163              &poly_B_bound_point,
164              &poly_C_bound_point,
165              &poly_D_bound_point,
166            );
167            (eval_point_0, eval_point_2)
168          })
169          .reduce(
170            || (G::Scalar::zero(), G::Scalar::zero()),
171            |a, b| (a.0 + b.0, a.1 + b.1),
172          );
173
174        let evals = vec![eval_point_0, claim_per_round - eval_point_0, eval_point_2];
175        UniPoly::from_evals(&evals)
176      };
177
178      // append the prover's message to the transcript
179      transcript.absorb(b"p", &poly);
180
181      // derive the verifier's challenge for the next round
182      let r_i = transcript.squeeze(b"c")?;
183      r.push(r_i);
184      polys.push(poly.compress());
185
186      // Set up next round
187      claim_per_round = poly.evaluate(&r_i);
188
189      // bound all tables to the verifier's challenege
190      poly_A.bound_poly_var_top(&r_i);
191      poly_B.bound_poly_var_top(&r_i);
192      poly_C.bound_poly_var_top(&r_i);
193      poly_D.bound_poly_var_top(&r_i);
194    }
195
196    Ok((
197      SumcheckProof {
198        compressed_polys: polys,
199      },
200      r,
201      vec![poly_A[0], poly_B[0], poly_C[0], poly_D[0]],
202    ))
203  }
204
205  pub fn prove_cubic_with_additive_term<F>(
206    claim: &G::Scalar,
207    num_rounds: usize,
208    poly_A: &mut MultilinearPolynomial<G::Scalar>,
209    poly_B: &mut MultilinearPolynomial<G::Scalar>,
210    poly_C: &mut MultilinearPolynomial<G::Scalar>,
211    poly_D: &mut MultilinearPolynomial<G::Scalar>,
212    comb_func: F,
213    transcript: &mut G::TE,
214  ) -> Result<(Self, Vec<G::Scalar>, Vec<G::Scalar>), NovaError>
215  where
216    F: Fn(&G::Scalar, &G::Scalar, &G::Scalar, &G::Scalar) -> G::Scalar + Sync,
217  {
218    let mut r: Vec<G::Scalar> = Vec::new();
219    let mut polys: Vec<CompressedUniPoly<G>> = Vec::new();
220    let mut claim_per_round = *claim;
221
222    for _ in 0..num_rounds {
223      let poly = {
224        let len = poly_A.len() / 2;
225
226        // Make an iterator returning the contributions to the evaluations
227        let (eval_point_0, eval_point_2, eval_point_3) = (0..len)
228          .into_par_iter()
229          .map(|i| {
230            // eval 0: bound_func is A(low)
231            let eval_point_0 = comb_func(&poly_A[i], &poly_B[i], &poly_C[i], &poly_D[i]);
232
233            // eval 2: bound_func is -A(low) + 2*A(high)
234            let poly_A_bound_point = poly_A[len + i] + poly_A[len + i] - poly_A[i];
235            let poly_B_bound_point = poly_B[len + i] + poly_B[len + i] - poly_B[i];
236            let poly_C_bound_point = poly_C[len + i] + poly_C[len + i] - poly_C[i];
237            let poly_D_bound_point = poly_D[len + i] + poly_D[len + i] - poly_D[i];
238            let eval_point_2 = comb_func(
239              &poly_A_bound_point,
240              &poly_B_bound_point,
241              &poly_C_bound_point,
242              &poly_D_bound_point,
243            );
244
245            // eval 3: bound_func is -2A(low) + 3A(high); computed incrementally with bound_func applied to eval(2)
246            let poly_A_bound_point = poly_A_bound_point + poly_A[len + i] - poly_A[i];
247            let poly_B_bound_point = poly_B_bound_point + poly_B[len + i] - poly_B[i];
248            let poly_C_bound_point = poly_C_bound_point + poly_C[len + i] - poly_C[i];
249            let poly_D_bound_point = poly_D_bound_point + poly_D[len + i] - poly_D[i];
250            let eval_point_3 = comb_func(
251              &poly_A_bound_point,
252              &poly_B_bound_point,
253              &poly_C_bound_point,
254              &poly_D_bound_point,
255            );
256            (eval_point_0, eval_point_2, eval_point_3)
257          })
258          .reduce(
259            || (G::Scalar::zero(), G::Scalar::zero(), G::Scalar::zero()),
260            |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2),
261          );
262
263        let evals = vec![
264          eval_point_0,
265          claim_per_round - eval_point_0,
266          eval_point_2,
267          eval_point_3,
268        ];
269        UniPoly::from_evals(&evals)
270      };
271
272      // append the prover's message to the transcript
273      transcript.absorb(b"p", &poly);
274
275      //derive the verifier's challenge for the next round
276      let r_i = transcript.squeeze(b"c")?;
277      r.push(r_i);
278      polys.push(poly.compress());
279
280      // Set up next round
281      claim_per_round = poly.evaluate(&r_i);
282
283      // bound all tables to the verifier's challenege
284      poly_A.bound_poly_var_top(&r_i);
285      poly_B.bound_poly_var_top(&r_i);
286      poly_C.bound_poly_var_top(&r_i);
287      poly_D.bound_poly_var_top(&r_i);
288    }
289
290    Ok((
291      SumcheckProof {
292        compressed_polys: polys,
293      },
294      r,
295      vec![poly_A[0], poly_B[0], poly_C[0], poly_D[0]],
296    ))
297  }
298}
299
300// ax^2 + bx + c stored as vec![a,b,c]
301// ax^3 + bx^2 + cx + d stored as vec![a,b,c,d]
302#[derive(Debug)]
303pub struct UniPoly<G: Group> {
304  coeffs: Vec<G::Scalar>,
305}
306
307// ax^2 + bx + c stored as vec![a,c]
308// ax^3 + bx^2 + cx + d stored as vec![a,c,d]
309#[derive(Clone, Debug, Serialize, Deserialize)]
310pub struct CompressedUniPoly<G: Group> {
311  coeffs_except_linear_term: Vec<G::Scalar>,
312  _p: PhantomData<G>,
313}
314
315impl<G: Group> UniPoly<G> {
316  pub fn from_evals(evals: &[G::Scalar]) -> Self {
317    // we only support degree-2 or degree-3 univariate polynomials
318    assert!(evals.len() == 3 || evals.len() == 4);
319    let coeffs = if evals.len() == 3 {
320      // ax^2 + bx + c
321      let two_inv = G::Scalar::from(2).invert().unwrap();
322
323      let c = evals[0];
324      let a = two_inv * (evals[2] - evals[1] - evals[1] + c);
325      let b = evals[1] - c - a;
326      vec![c, b, a]
327    } else {
328      // ax^3 + bx^2 + cx + d
329      let two_inv = G::Scalar::from(2).invert().unwrap();
330      let six_inv = G::Scalar::from(6).invert().unwrap();
331
332      let d = evals[0];
333      let a = six_inv
334        * (evals[3] - evals[2] - evals[2] - evals[2] + evals[1] + evals[1] + evals[1] - evals[0]);
335      let b = two_inv
336        * (evals[0] + evals[0] - evals[1] - evals[1] - evals[1] - evals[1] - evals[1]
337          + evals[2]
338          + evals[2]
339          + evals[2]
340          + evals[2]
341          - evals[3]);
342      let c = evals[1] - d - a - b;
343      vec![d, c, b, a]
344    };
345
346    UniPoly { coeffs }
347  }
348
349  pub fn degree(&self) -> usize {
350    self.coeffs.len() - 1
351  }
352
353  pub fn eval_at_zero(&self) -> G::Scalar {
354    self.coeffs[0]
355  }
356
357  pub fn eval_at_one(&self) -> G::Scalar {
358    (0..self.coeffs.len())
359      .into_par_iter()
360      .map(|i| self.coeffs[i])
361      .reduce(G::Scalar::zero, |a, b| a + b)
362  }
363
364  pub fn evaluate(&self, r: &G::Scalar) -> G::Scalar {
365    let mut eval = self.coeffs[0];
366    let mut power = *r;
367    for coeff in self.coeffs.iter().skip(1) {
368      eval += power * coeff;
369      power *= r;
370    }
371    eval
372  }
373
374  pub fn compress(&self) -> CompressedUniPoly<G> {
375    let coeffs_except_linear_term = [&self.coeffs[0..1], &self.coeffs[2..]].concat();
376    assert_eq!(coeffs_except_linear_term.len() + 1, self.coeffs.len());
377    CompressedUniPoly {
378      coeffs_except_linear_term,
379      _p: Default::default(),
380    }
381  }
382}
383
384impl<G: Group> CompressedUniPoly<G> {
385  // we require eval(0) + eval(1) = hint, so we can solve for the linear term as:
386  // linear_term = hint - 2 * constant_term - deg2 term - deg3 term
387  pub fn decompress(&self, hint: &G::Scalar) -> UniPoly<G> {
388    let mut linear_term =
389      *hint - self.coeffs_except_linear_term[0] - self.coeffs_except_linear_term[0];
390    for i in 1..self.coeffs_except_linear_term.len() {
391      linear_term -= self.coeffs_except_linear_term[i];
392    }
393
394    let mut coeffs: Vec<G::Scalar> = Vec::new();
395    coeffs.extend(vec![&self.coeffs_except_linear_term[0]]);
396    coeffs.extend(vec![&linear_term]);
397    coeffs.extend(self.coeffs_except_linear_term[1..].to_vec());
398    assert_eq!(self.coeffs_except_linear_term.len() + 1, coeffs.len());
399    UniPoly { coeffs }
400  }
401}
402
403impl<G: Group> TranscriptReprTrait<G> for UniPoly<G> {
404  fn to_transcript_bytes(&self) -> Vec<u8> {
405    let coeffs = self.compress().coeffs_except_linear_term;
406    coeffs.as_slice().to_transcript_bytes()
407  }
408}