arnaucube
arnaucube/NovaPublic Self-hosted repository
Nova/benches/compressed-snark.rs
benches/compressed-snark.rsRaw
  1#![allow(non_snake_case)]
  2
  3use bellperson::{gadgets::num::AllocatedNum, ConstraintSystem, SynthesisError};
  4use core::marker::PhantomData;
  5use criterion::*;
  6use ff::PrimeField;
  7use nova_snark::{
  8  traits::{
  9    circuit::{StepCircuit, TrivialTestCircuit},
 10    Group,
 11  },
 12  CompressedSNARK, PublicParams, RecursiveSNARK,
 13};
 14use std::time::Duration;
 15
 16type G1 = pasta_curves::pallas::Point;
 17type G2 = pasta_curves::vesta::Point;
 18type EE1 = nova_snark::provider::ipa_pc::EvaluationEngine<G1>;
 19type EE2 = nova_snark::provider::ipa_pc::EvaluationEngine<G2>;
 20type S1 = nova_snark::spartan::RelaxedR1CSSNARK<G1, EE1>;
 21type S2 = nova_snark::spartan::RelaxedR1CSSNARK<G2, EE2>;
 22type C1 = NonTrivialTestCircuit<<G1 as Group>::Scalar>;
 23type C2 = TrivialTestCircuit<<G2 as Group>::Scalar>;
 24
 25criterion_group! {
 26name = compressed_snark;
 27config = Criterion::default().warm_up_time(Duration::from_millis(3000));
 28targets = bench_compressed_snark
 29}
 30
 31criterion_main!(compressed_snark);
 32
 33fn bench_compressed_snark(c: &mut Criterion) {
 34  let num_samples = 10;
 35  let num_cons_verifier_circuit_primary = 9819;
 36  // we vary the number of constraints in the step circuit
 37  for &num_cons_in_augmented_circuit in
 38    [9819, 16384, 32768, 65536, 131072, 262144, 524288, 1048576].iter()
 39  {
 40    // number of constraints in the step circuit
 41    let num_cons = num_cons_in_augmented_circuit - num_cons_verifier_circuit_primary;
 42
 43    let mut group = c.benchmark_group(format!("CompressedSNARK-StepCircuitSize-{num_cons}"));
 44    group.sample_size(num_samples);
 45
 46    // Produce public parameters
 47    let pp = PublicParams::<G1, G2, C1, C2>::setup(
 48      NonTrivialTestCircuit::new(num_cons),
 49      TrivialTestCircuit::default(),
 50    );
 51
 52    // Produce prover and verifier keys for CompressedSNARK
 53    let (pk, vk) = CompressedSNARK::<_, _, _, _, S1, S2>::setup(&pp);
 54
 55    // produce a recursive SNARK
 56    let num_steps = 3;
 57    let mut recursive_snark: Option<RecursiveSNARK<G1, G2, C1, C2>> = None;
 58
 59    for i in 0..num_steps {
 60      let res = RecursiveSNARK::prove_step(
 61        &pp,
 62        recursive_snark,
 63        NonTrivialTestCircuit::new(num_cons),
 64        TrivialTestCircuit::default(),
 65        vec![<G1 as Group>::Scalar::from(2u64)],
 66        vec![<G2 as Group>::Scalar::from(2u64)],
 67      );
 68      assert!(res.is_ok());
 69      let recursive_snark_unwrapped = res.unwrap();
 70
 71      // verify the recursive snark at each step of recursion
 72      let res = recursive_snark_unwrapped.verify(
 73        &pp,
 74        i + 1,
 75        vec![<G1 as Group>::Scalar::from(2u64)],
 76        vec![<G2 as Group>::Scalar::from(2u64)],
 77      );
 78      assert!(res.is_ok());
 79
 80      // set the running variable for the next iteration
 81      recursive_snark = Some(recursive_snark_unwrapped);
 82    }
 83
 84    // Bench time to produce a compressed SNARK
 85    let recursive_snark = recursive_snark.unwrap();
 86    group.bench_function("Prove", |b| {
 87      b.iter(|| {
 88        assert!(CompressedSNARK::<_, _, _, _, S1, S2>::prove(
 89          black_box(&pp),
 90          black_box(&pk),
 91          black_box(&recursive_snark)
 92        )
 93        .is_ok());
 94      })
 95    });
 96    let res = CompressedSNARK::<_, _, _, _, S1, S2>::prove(&pp, &pk, &recursive_snark);
 97    assert!(res.is_ok());
 98    let compressed_snark = res.unwrap();
 99
100    // Benchmark the verification time
101    group.bench_function("Verify", |b| {
102      b.iter(|| {
103        assert!(black_box(&compressed_snark)
104          .verify(
105            black_box(&vk),
106            black_box(num_steps),
107            black_box(vec![<G1 as Group>::Scalar::from(2u64)]),
108            black_box(vec![<G2 as Group>::Scalar::from(2u64)]),
109          )
110          .is_ok());
111      })
112    });
113
114    group.finish();
115  }
116}
117
118#[derive(Clone, Debug, Default)]
119struct NonTrivialTestCircuit<F: PrimeField> {
120  num_cons: usize,
121  _p: PhantomData<F>,
122}
123
124impl<F> NonTrivialTestCircuit<F>
125where
126  F: PrimeField,
127{
128  pub fn new(num_cons: usize) -> Self {
129    Self {
130      num_cons,
131      _p: Default::default(),
132    }
133  }
134}
135impl<F> StepCircuit<F> for NonTrivialTestCircuit<F>
136where
137  F: PrimeField,
138{
139  fn arity(&self) -> usize {
140    1
141  }
142
143  fn synthesize<CS: ConstraintSystem<F>>(
144    &self,
145    cs: &mut CS,
146    z: &[AllocatedNum<F>],
147  ) -> Result<Vec<AllocatedNum<F>>, SynthesisError> {
148    // Consider a an equation: `x^2 = y`, where `x` and `y` are respectively the input and output.
149    let mut x = z[0].clone();
150    let mut y = x.clone();
151    for i in 0..self.num_cons {
152      y = x.square(cs.namespace(|| format!("x_sq_{i}")))?;
153      x = y.clone();
154    }
155    Ok(vec![y])
156  }
157
158  fn output(&self, z: &[F]) -> Vec<F> {
159    let mut x = z[0];
160    let mut y = x;
161    for _i in 0..self.num_cons {
162      y = x * x;
163      x = y;
164    }
165    vec![y]
166  }
167}