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::snark::RelaxedR1CSSNARK<G1, EE1>;
21type S2 = nova_snark::spartan::snark::RelaxedR1CSSNARK<G2, EE2>;
22type C1 = NonTrivialTestCircuit<<G1 as Group>::Scalar>;
23type C2 = TrivialTestCircuit<<G2 as Group>::Scalar>;
24
25// To run these benchmarks, first download `criterion` with `cargo install cargo install cargo-criterion`.
26// Then `cargo criterion --bench compressed-snark`. The results are located in `target/criterion/data/<name-of-benchmark>`.
27// For flamegraphs, run `cargo criterion --bench compressed-snark --features flamegraph -- --profile-time <secs>`.
28// The results are located in `target/criterion/profile/<name-of-benchmark>`.
29cfg_if::cfg_if! {
30 if #[cfg(feature = "flamegraph")] {
31 criterion_group! {
32 name = compressed_snark;
33 config = Criterion::default().warm_up_time(Duration::from_millis(3000)).with_profiler(pprof::criterion::PProfProfiler::new(100, pprof::criterion::Output::Flamegraph(None)));
34 targets = bench_compressed_snark
35 }
36 } else {
37 criterion_group! {
38 name = compressed_snark;
39 config = Criterion::default().warm_up_time(Duration::from_millis(3000));
40 targets = bench_compressed_snark
41 }
42 }
43}
44
45criterion_main!(compressed_snark);
46
47fn bench_compressed_snark(c: &mut Criterion) {
48 let num_samples = 10;
49 let num_cons_verifier_circuit_primary = 9819;
50 // we vary the number of constraints in the step circuit
51 for &num_cons_in_augmented_circuit in
52 [9819, 16384, 32768, 65536, 131072, 262144, 524288, 1048576].iter()
53 {
54 // number of constraints in the step circuit
55 let num_cons = num_cons_in_augmented_circuit - num_cons_verifier_circuit_primary;
56
57 let mut group = c.benchmark_group(format!("CompressedSNARK-StepCircuitSize-{num_cons}"));
58 group.sample_size(num_samples);
59
60 let c_primary = NonTrivialTestCircuit::new(num_cons);
61 let c_secondary = TrivialTestCircuit::default();
62
63 // Produce public parameters
64 let pp = PublicParams::<G1, G2, C1, C2>::setup(c_primary.clone(), c_secondary.clone());
65
66 // Produce prover and verifier keys for CompressedSNARK
67 let (pk, vk) = CompressedSNARK::<_, _, _, _, S1, S2>::setup(&pp).unwrap();
68
69 // produce a recursive SNARK
70 let num_steps = 3;
71 let mut recursive_snark: RecursiveSNARK<G1, G2, C1, C2> = RecursiveSNARK::new(
72 &pp,
73 &c_primary,
74 &c_secondary,
75 vec![<G1 as Group>::Scalar::from(2u64)],
76 vec![<G2 as Group>::Scalar::from(2u64)],
77 );
78
79 for i in 0..num_steps {
80 let res = recursive_snark.prove_step(
81 &pp,
82 &c_primary,
83 &c_secondary,
84 vec![<G1 as Group>::Scalar::from(2u64)],
85 vec![<G2 as Group>::Scalar::from(2u64)],
86 );
87 assert!(res.is_ok());
88
89 // verify the recursive snark at each step of recursion
90 let res = recursive_snark.verify(
91 &pp,
92 i + 1,
93 &[<G1 as Group>::Scalar::from(2u64)],
94 &[<G2 as Group>::Scalar::from(2u64)],
95 );
96 assert!(res.is_ok());
97 }
98
99 // Bench time to produce a compressed SNARK
100 group.bench_function("Prove", |b| {
101 b.iter(|| {
102 assert!(CompressedSNARK::<_, _, _, _, S1, S2>::prove(
103 black_box(&pp),
104 black_box(&pk),
105 black_box(&recursive_snark)
106 )
107 .is_ok());
108 })
109 });
110 let res = CompressedSNARK::<_, _, _, _, S1, S2>::prove(&pp, &pk, &recursive_snark);
111 assert!(res.is_ok());
112 let compressed_snark = res.unwrap();
113
114 // Benchmark the verification time
115 group.bench_function("Verify", |b| {
116 b.iter(|| {
117 assert!(black_box(&compressed_snark)
118 .verify(
119 black_box(&vk),
120 black_box(num_steps),
121 black_box(vec![<G1 as Group>::Scalar::from(2u64)]),
122 black_box(vec![<G2 as Group>::Scalar::from(2u64)]),
123 )
124 .is_ok());
125 })
126 });
127
128 group.finish();
129 }
130}
131
132#[derive(Clone, Debug, Default)]
133struct NonTrivialTestCircuit<F: PrimeField> {
134 num_cons: usize,
135 _p: PhantomData<F>,
136}
137
138impl<F> NonTrivialTestCircuit<F>
139where
140 F: PrimeField,
141{
142 pub fn new(num_cons: usize) -> Self {
143 Self {
144 num_cons,
145 _p: Default::default(),
146 }
147 }
148}
149impl<F> StepCircuit<F> for NonTrivialTestCircuit<F>
150where
151 F: PrimeField,
152{
153 fn arity(&self) -> usize {
154 1
155 }
156
157 fn synthesize<CS: ConstraintSystem<F>>(
158 &self,
159 cs: &mut CS,
160 z: &[AllocatedNum<F>],
161 ) -> Result<Vec<AllocatedNum<F>>, SynthesisError> {
162 // Consider a an equation: `x^2 = y`, where `x` and `y` are respectively the input and output.
163 let mut x = z[0].clone();
164 let mut y = x.clone();
165 for i in 0..self.num_cons {
166 y = x.square(cs.namespace(|| format!("x_sq_{i}")))?;
167 x = y.clone();
168 }
169 Ok(vec![y])
170 }
171
172 fn output(&self, z: &[F]) -> Vec<F> {
173 let mut x = z[0];
174 let mut y = x;
175 for _i in 0..self.num_cons {
176 y = x * x;
177 x = y;
178 }
179 vec![y]
180 }
181}