spartan2 0.2.0

High-speed zkSNARKs without trusted setup
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! This module implements the sum-check protocol used in the Spartan SNARK.
//!
//! The sum-check protocol allows a prover to convince a verifier that a claimed sum
//! over a multivariate polynomial equals a specific value, without the verifier
//! needing to compute the sum directly.

use crate::{
  errors::SpartanError,
  polys::{
    multilinear::MultilinearPolynomial,
    univariate::{CompressedUniPoly, UniPoly},
  },
  start_span,
  traits::{Engine, transcript::TranscriptEngineTrait},
};
use ff::Field;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::time::Instant;
use tracing::{info, info_span};

/// 4 k elements is a good cut-off on a 16-core machine.
const PAR_THRESHOLD: usize = 4 << 10; // 4096

/// Adaptive parallel-for helper.
/// Falls back to a plain `for` loop when the slice is small **or**
/// we are already inside a Rayon worker, avoiding nested pools.
/// `par_for` – run `map(i)` for `i = 0..len` and fold the
/// results with `reduce`, starting from `identity()`.
///
/// When `len` is small or we’re already on a Rayon thread it executes
/// serially; otherwise it uses `into_par_iter`.
pub fn par_for<R, Map, Red, Id>(len: usize, map: Map, reduce: Red, identity: Id) -> R
where
  R: Send, // result must cross Rayon threads
  Map: Fn(usize) -> R + Sync + Send,
  Red: Fn(R, R) -> R + Sync + Send,
  Id: Fn() -> R + Sync + Send,
{
  // Fast-path for empty ranges
  if len == 0 {
    return identity();
  }

  // Are we *already* running inside a Rayon worker thread?
  let in_rayon_ctx = rayon::current_thread_index().is_some();

  if len < PAR_THRESHOLD || in_rayon_ctx {
    // ---------- serial fallback ----------
    let mut acc = identity();
    for i in 0..len {
      let v = map(i);
      acc = reduce(acc, v);
    }
    acc
  } else {
    // ---------- true parallel path ----------
    (0..len).into_par_iter().map(map).reduce(identity, reduce)
  }
}

/// A proof generated by the sum-check protocol.
///
/// This struct contains the compressed univariate polynomials that constitute
/// the prover's messages in each round of the sum-check protocol.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(bound = "")]
pub struct SumcheckProof<E: Engine> {
  compressed_polys: Vec<CompressedUniPoly<E::Scalar>>,
}

impl<E: Engine> SumcheckProof<E> {
  /// Verifies a sum-check proof.
  ///
  /// # Arguments
  /// * `claim` - The claimed sum that the prover asserts
  /// * `num_rounds` - The number of rounds in the sum-check protocol
  /// * `degree_bound` - The maximum degree of univariate polynomials in each round
  /// * `transcript` - The transcript for the interactive proof
  ///
  /// # Returns
  /// A tuple containing the final evaluation point and the sequence of verifier challenges,
  /// or an error if verification fails.
  pub fn verify(
    &self,
    claim: E::Scalar,
    num_rounds: usize,
    degree_bound: usize,
    transcript: &mut E::TE,
  ) -> Result<(E::Scalar, Vec<E::Scalar>), SpartanError> {
    let (_verify_span, verify_t) = start_span!("sumcheck_verify");
    let mut e = claim;
    let mut r: Vec<E::Scalar> = Vec::new();

    // verify that there is a univariate polynomial for each round
    if self.compressed_polys.len() != num_rounds {
      return Err(SpartanError::InvalidSumcheckProof);
    }

    for i in 0..self.compressed_polys.len() {
      let (_round_span, round_t) = start_span!("sumcheck_verify_round", round = i);
      let poly = self.compressed_polys[i].decompress(&e);

      // verify degree bound
      if poly.degree() != degree_bound {
        return Err(SpartanError::InvalidSumcheckProof);
      }

      // we do not need to check if poly(0) + poly(1) = e, as
      // decompress() call above already ensures that holds
      debug_assert_eq!(poly.eval_at_zero() + poly.eval_at_one(), e);

      // append the prover's message to the transcript
      transcript.absorb(b"p", &poly);

      //derive the verifier's challenge for the next round
      let r_i = transcript.squeeze(b"c")?;

      r.push(r_i);

      // evaluate the claimed degree-ell polynomial at r_i
      e = poly.evaluate(&r_i);

      if round_t.elapsed().as_millis() > 0 {
        info!(elapsed_ms = %round_t.elapsed().as_millis(), "sumcheck_verify_round");
      }
    }

    info!(elapsed_ms = %verify_t.elapsed().as_millis(), "sumcheck_verify");
    Ok((e, r))
  }

  #[inline]
  fn compute_eval_points_quad<F>(
    poly_A: &MultilinearPolynomial<E::Scalar>,
    poly_B: &MultilinearPolynomial<E::Scalar>,
    comb_func: &F,
  ) -> (E::Scalar, E::Scalar)
  where
    F: Fn(&E::Scalar, &E::Scalar) -> E::Scalar + Sync,
  {
    let len = poly_A.Z.len() / 2;

    // Using `par_for` keeps the map-reduce logic identical
    // but avoids Rayon overhead on tiny slices.
    par_for(
      len,
      // map-closure (returned pair is the per-index contribution)
      |i| {
        let a_low = poly_A[i];
        let a_high = poly_A[len + i];
        let b_low = poly_B[i];
        let b_high = poly_B[len + i];

        // eval 0:   A(low)
        let eval0 = comb_func(&a_low, &b_low);

        // eval 2:  −A(low) + 2·A(high)   (same for B)
        let a_bound = a_high + a_high - a_low;
        let b_bound = b_high + b_high - b_low;
        let eval2 = comb_func(&a_bound, &b_bound);

        (eval0, eval2)
      },
      // reduce-closure (pairwise accumulation)
      |mut acc, val| {
        acc.0 += val.0;
        acc.1 += val.1;
        acc
      },
      // identity value
      || (E::Scalar::ZERO, E::Scalar::ZERO),
    )
  }

  /// Generates a sum-check proof for a quadratic combination of two multilinear polynomials.
  ///
  /// # Arguments
  /// * `claim` - The claimed sum over the hypercube
  /// * `num_rounds` - The number of variables/rounds in the sum-check
  /// * `poly_A` - First multilinear polynomial (mutable, will be bound during protocol)
  /// * `poly_B` - Second multilinear polynomial (mutable, will be bound during protocol)  
  /// * `comb_func` - Function that combines evaluations of the two polynomials
  /// * `transcript` - The transcript for generating randomness
  ///
  /// # Returns
  /// A tuple containing the sum-check proof, the sequence of verifier challenges,
  /// and the final evaluations of the polynomials.
  pub fn prove_quad<F>(
    claim: &E::Scalar,
    num_rounds: usize,
    poly_A: &mut MultilinearPolynomial<E::Scalar>,
    poly_B: &mut MultilinearPolynomial<E::Scalar>,
    comb_func: F,
    transcript: &mut E::TE,
  ) -> Result<(Self, Vec<E::Scalar>, Vec<E::Scalar>), SpartanError>
  where
    F: Fn(&E::Scalar, &E::Scalar) -> E::Scalar + Sync,
  {
    let mut r: Vec<E::Scalar> = Vec::new();
    let mut polys: Vec<CompressedUniPoly<E::Scalar>> = Vec::new();
    let mut claim_per_round = *claim;
    for round in 0..num_rounds {
      let (_round_span, round_t) = start_span!("sumcheck_quad_round", round = round);

      let poly = {
        let (_eval_span, eval_t) = start_span!("compute_eval_points_quad");
        let (eval_point_0, eval_point_2) =
          Self::compute_eval_points_quad(poly_A, poly_B, &comb_func);
        if eval_t.elapsed().as_millis() > 0 {
          info!(elapsed_ms = %eval_t.elapsed().as_millis(), "compute_eval_points_quad");
        }

        let evals = vec![eval_point_0, claim_per_round - eval_point_0, eval_point_2];
        UniPoly::from_evals(&evals)?
      };

      // append the prover's message to the transcript
      transcript.absorb(b"p", &poly);

      //derive the verifier's challenge for the next round
      let r_i = transcript.squeeze(b"c")?;
      r.push(r_i);
      polys.push(poly.compress());

      // Set up next round
      claim_per_round = poly.evaluate(&r_i);

      // bind all tables to the verifier's challenge
      let (_bind_span, bind_t) = start_span!("bind_poly_vars_quad");
      rayon::join(
        || poly_A.bind_poly_var_top(&r_i),
        || poly_B.bind_poly_var_top(&r_i),
      );
      info!(elapsed_ms = %bind_t.elapsed().as_millis(), "bind_poly_vars_quad");
      info!(elapsed_ms = %round_t.elapsed().as_millis(), round = round, "sumcheck_quad_round");
    }

    Ok((
      SumcheckProof {
        compressed_polys: polys,
      },
      r,
      vec![poly_A[0], poly_B[0]],
    ))
  }

  #[inline]
  /// Computes evaluation points for a cubic polynomial with additive term.
  ///
  /// This function computes three evaluation points (at 0, 2, and 3) for a univariate
  /// polynomial that represents the sum over a hypercube edge in the sum-check protocol
  /// for a cubic combination of four multilinear polynomials.
  ///
  /// # Arguments
  /// * `poly_A` - First multilinear polynomial
  /// * `poly_B` - Second multilinear polynomial  
  /// * `poly_C` - Third multilinear polynomial
  /// * `poly_D` - Fourth multilinear polynomial
  /// * `comb_func` - Function that combines evaluations of the four polynomials
  ///
  /// # Returns
  /// A tuple containing the evaluations at points 0, 2, and 3.
  pub fn compute_eval_points_cubic_with_additive_term<F>(
    poly_A: &MultilinearPolynomial<E::Scalar>,
    poly_B: &MultilinearPolynomial<E::Scalar>,
    poly_C: &MultilinearPolynomial<E::Scalar>,
    poly_D: &MultilinearPolynomial<E::Scalar>,
    comb_func: &F,
  ) -> (E::Scalar, E::Scalar, E::Scalar)
  where
    F: Fn(&E::Scalar, &E::Scalar, &E::Scalar, &E::Scalar) -> E::Scalar + Sync,
  {
    let len = poly_A.Z.len() / 2;
    par_for(
      len,
      |i| {
        let a_low = poly_A[i];
        let a_high = poly_A[i + len];
        let b_low = poly_B[i];
        let b_high = poly_B[i + len];
        let c_low = poly_C[i];
        let c_high = poly_C[i + len];
        let d_low = poly_D[i];
        let d_high = poly_D[i + len];

        // eval 0: bound_func is A(low)
        let eval_point_0 = comb_func(&a_low, &b_low, &c_low, &d_low);

        // eval 2: bound_func is -A(low) + 2*A(high)
        let poly_A_bound_point = a_high + a_high - a_low;
        let poly_B_bound_point = b_high + b_high - b_low;
        let poly_C_bound_point = c_high + c_high - c_low;
        let poly_D_bound_point = d_high + d_high - d_low;
        let eval_point_2 = comb_func(
          &poly_A_bound_point,
          &poly_B_bound_point,
          &poly_C_bound_point,
          &poly_D_bound_point,
        );

        // eval 3: bound_func is -2A(low) + 3A(high); computed incrementally with bound_func applied to eval(2)
        let poly_A_bound_point = poly_A_bound_point + a_high - a_low;
        let poly_B_bound_point = poly_B_bound_point + b_high - b_low;
        let poly_C_bound_point = poly_C_bound_point + c_high - c_low;
        let poly_D_bound_point = poly_D_bound_point + d_high - d_low;
        let eval_point_3 = comb_func(
          &poly_A_bound_point,
          &poly_B_bound_point,
          &poly_C_bound_point,
          &poly_D_bound_point,
        );
        (eval_point_0, eval_point_2, eval_point_3)
      },
      |mut acc, val| {
        acc.0 += val.0;
        acc.1 += val.1;
        acc.2 += val.2;
        acc
      },
      || (E::Scalar::ZERO, E::Scalar::ZERO, E::Scalar::ZERO),
    )
  }

  /// Generates a sum-check proof for a cubic combination with additive term of four multilinear polynomials.
  ///
  /// # Arguments
  /// * `claim` - The claimed sum over the hypercube
  /// * `num_rounds` - The number of variables/rounds in the sum-check
  /// * `poly_A` - First multilinear polynomial (mutable, will be bound during protocol)
  /// * `poly_B` - Second multilinear polynomial (mutable, will be bound during protocol)
  /// * `poly_C` - Third multilinear polynomial (mutable, will be bound during protocol)
  /// * `poly_D` - Fourth multilinear polynomial (mutable, will be bound during protocol)
  /// * `comb_func` - Function that combines evaluations of the four polynomials
  /// * `transcript` - The transcript for generating randomness
  ///
  /// # Returns
  /// A tuple containing the sum-check proof, the sequence of verifier challenges,
  /// and the final evaluations of the polynomials.
  #[allow(clippy::too_many_arguments)]
  pub fn prove_cubic_with_additive_term<F>(
    claim: &E::Scalar,
    num_rounds: usize,
    poly_A: &mut MultilinearPolynomial<E::Scalar>,
    poly_B: &mut MultilinearPolynomial<E::Scalar>,
    poly_C: &mut MultilinearPolynomial<E::Scalar>,
    poly_D: &mut MultilinearPolynomial<E::Scalar>,
    comb_func: F,
    transcript: &mut E::TE,
  ) -> Result<(Self, Vec<E::Scalar>, Vec<E::Scalar>), SpartanError>
  where
    F: Fn(&E::Scalar, &E::Scalar, &E::Scalar, &E::Scalar) -> E::Scalar + Sync,
  {
    let mut r: Vec<E::Scalar> = Vec::new();
    let mut polys: Vec<CompressedUniPoly<E::Scalar>> = Vec::new();
    let mut claim_per_round = *claim;

    for round in 0..num_rounds {
      let (_round_span, round_t) = start_span!("sumcheck_round", round = round);

      let poly = {
        // Make an iterator returning the contributions to the evaluations
        let (_eval_span, eval_t) = start_span!("compute_eval_points");
        let (eval_point_0, eval_point_2, eval_point_3) =
          Self::compute_eval_points_cubic_with_additive_term(
            poly_A, poly_B, poly_C, poly_D, &comb_func,
          );
        if eval_t.elapsed().as_millis() > 0 {
          info!(elapsed_ms = %eval_t.elapsed().as_millis(), "compute_eval_points");
        }
        let evals = vec![
          eval_point_0,
          claim_per_round - eval_point_0,
          eval_point_2,
          eval_point_3,
        ];
        UniPoly::from_evals(&evals)?
      };

      // append the prover's message to the transcript
      transcript.absorb(b"p", &poly);

      //derive the verifier's challenge for the next round
      let r_i = transcript.squeeze(b"c")?;
      r.push(r_i);
      polys.push(poly.compress());

      // Set up next round
      claim_per_round = poly.evaluate(&r_i);

      // bound all tables to the verifier's challenge
      let (_bind_span, bind_t) = start_span!("bind_poly_vars");
      rayon::join(
        || {
          rayon::join(
            || poly_A.bind_poly_var_top(&r_i),
            || poly_B.bind_poly_var_top(&r_i),
          )
        },
        || {
          rayon::join(
            || poly_C.bind_poly_var_top(&r_i),
            || poly_D.bind_poly_var_top(&r_i),
          )
        },
      );
      info!(elapsed_ms = %bind_t.elapsed().as_millis(), "bind_poly_vars");
      info!(elapsed_ms = %round_t.elapsed().as_millis(), round = round, "sumcheck_round");
    }

    Ok((
      SumcheckProof {
        compressed_polys: polys,
      },
      r,
      vec![poly_A[0], poly_B[0], poly_C[0], poly_D[0]],
    ))
  }
}