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