You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

272 lines
8.3 KiB

[refactorings] Leftovers (pot-pourri?) (#184) * test: compute_path * refactor: path computation - Improve path concatenation by utilizing built-in `join` method * refactor: replace `PartialEq` with derived instance - Derive `PartialEq` for `SatisfyingAssignment` struct - Remove redundant manual implementation of `PartialEq` Cargo-expand generates: ``` #[automatically_derived] impl<G: ::core::cmp::PartialEq + Group> ::core::cmp::PartialEq for SatisfyingAssignment<G> where G::Scalar: PrimeField, G::Scalar: ::core::cmp::PartialEq, G::Scalar: ::core::cmp::PartialEq, G::Scalar: ::core::cmp::PartialEq, G::Scalar: ::core::cmp::PartialEq, G::Scalar: ::core::cmp::PartialEq, { #[inline] fn eq(&self, other: &SatisfyingAssignment<G>) -> bool { self.a_aux_density == other.a_aux_density && self.b_input_density == other.b_input_density && self.b_aux_density == other.b_aux_density && self.a == other.a && self.b == other.b && self.c == other.c && self.input_assignment == other.input_assignment && self.aux_assignment == other.aux_assignment } } ``` * refactor: avoid default for PhantomData Unit type * refactor: replace fold with sum where applicable - Simplify code by replacing `fold` with `sum` in various instances * refactor: decompression method in sumcheck.rs * refactor: test functions to use slice instead of vector conversion * refactor: use more references in functions - Update parameter types to use references instead of owned values in various functions that do not need them - Replace cloning instances with references
1 year ago
  1. #![allow(non_snake_case)]
  2. use bellperson::{gadgets::num::AllocatedNum, ConstraintSystem, SynthesisError};
  3. use core::marker::PhantomData;
  4. use criterion::*;
  5. use ff::PrimeField;
  6. use nova_snark::{
  7. traits::{
  8. circuit::{StepCircuit, TrivialTestCircuit},
  9. Group,
  10. },
  11. CompressedSNARK, PublicParams, RecursiveSNARK,
  12. };
  13. use std::time::Duration;
  14. type G1 = pasta_curves::pallas::Point;
  15. type G2 = pasta_curves::vesta::Point;
  16. type EE1 = nova_snark::provider::ipa_pc::EvaluationEngine<G1>;
  17. type EE2 = nova_snark::provider::ipa_pc::EvaluationEngine<G2>;
  18. // SNARKs without computational commitments
  19. type S1 = nova_snark::spartan::snark::RelaxedR1CSSNARK<G1, EE1>;
  20. type S2 = nova_snark::spartan::snark::RelaxedR1CSSNARK<G2, EE2>;
  21. // SNARKs with computational commitments
  22. type SS1 = nova_snark::spartan::ppsnark::RelaxedR1CSSNARK<G1, EE1>;
  23. type SS2 = nova_snark::spartan::ppsnark::RelaxedR1CSSNARK<G2, EE2>;
  24. type C1 = NonTrivialTestCircuit<<G1 as Group>::Scalar>;
  25. type C2 = TrivialTestCircuit<<G2 as Group>::Scalar>;
  26. // To run these benchmarks, first download `criterion` with `cargo install cargo install cargo-criterion`.
  27. // Then `cargo criterion --bench compressed-snark`. The results are located in `target/criterion/data/<name-of-benchmark>`.
  28. // For flamegraphs, run `cargo criterion --bench compressed-snark --features flamegraph -- --profile-time <secs>`.
  29. // The results are located in `target/criterion/profile/<name-of-benchmark>`.
  30. cfg_if::cfg_if! {
  31. if #[cfg(feature = "flamegraph")] {
  32. criterion_group! {
  33. name = compressed_snark;
  34. config = Criterion::default().warm_up_time(Duration::from_millis(3000)).with_profiler(pprof::criterion::PProfProfiler::new(100, pprof::criterion::Output::Flamegraph(None)));
  35. targets = bench_compressed_snark, bench_compressed_snark_with_computational_commitments
  36. }
  37. } else {
  38. criterion_group! {
  39. name = compressed_snark;
  40. config = Criterion::default().warm_up_time(Duration::from_millis(3000));
  41. targets = bench_compressed_snark, bench_compressed_snark_with_computational_commitments
  42. }
  43. }
  44. }
  45. criterion_main!(compressed_snark);
  46. fn bench_compressed_snark(c: &mut Criterion) {
  47. let num_samples = 10;
  48. let num_cons_verifier_circuit_primary = 9819;
  49. // we vary the number of constraints in the step circuit
  50. for &num_cons_in_augmented_circuit in
  51. [9819, 16384, 32768, 65536, 131072, 262144, 524288, 1048576].iter()
  52. {
  53. // number of constraints in the step circuit
  54. let num_cons = num_cons_in_augmented_circuit - num_cons_verifier_circuit_primary;
  55. let mut group = c.benchmark_group(format!("CompressedSNARK-StepCircuitSize-{num_cons}"));
  56. group.sample_size(num_samples);
  57. let c_primary = NonTrivialTestCircuit::new(num_cons);
  58. let c_secondary = TrivialTestCircuit::default();
  59. // Produce public parameters
  60. let pp = PublicParams::<G1, G2, C1, C2>::setup(c_primary.clone(), c_secondary.clone());
  61. // Produce prover and verifier keys for CompressedSNARK
  62. let (pk, vk) = CompressedSNARK::<_, _, _, _, S1, S2>::setup(&pp).unwrap();
  63. // produce a recursive SNARK
  64. let num_steps = 3;
  65. let mut recursive_snark: RecursiveSNARK<G1, G2, C1, C2> = RecursiveSNARK::new(
  66. &pp,
  67. &c_primary,
  68. &c_secondary,
  69. vec![<G1 as Group>::Scalar::from(2u64)],
  70. vec![<G2 as Group>::Scalar::from(2u64)],
  71. );
  72. for i in 0..num_steps {
  73. let res = recursive_snark.prove_step(
  74. &pp,
  75. &c_primary,
  76. &c_secondary,
  77. vec![<G1 as Group>::Scalar::from(2u64)],
  78. vec![<G2 as Group>::Scalar::from(2u64)],
  79. );
  80. assert!(res.is_ok());
  81. // verify the recursive snark at each step of recursion
  82. let res = recursive_snark.verify(
  83. &pp,
  84. i + 1,
  85. &[<G1 as Group>::Scalar::from(2u64)],
  86. &[<G2 as Group>::Scalar::from(2u64)],
  87. );
  88. assert!(res.is_ok());
  89. }
  90. // Bench time to produce a compressed SNARK
  91. group.bench_function("Prove", |b| {
  92. b.iter(|| {
  93. assert!(CompressedSNARK::<_, _, _, _, S1, S2>::prove(
  94. black_box(&pp),
  95. black_box(&pk),
  96. black_box(&recursive_snark)
  97. )
  98. .is_ok());
  99. })
  100. });
  101. let res = CompressedSNARK::<_, _, _, _, S1, S2>::prove(&pp, &pk, &recursive_snark);
  102. assert!(res.is_ok());
  103. let compressed_snark = res.unwrap();
  104. // Benchmark the verification time
  105. group.bench_function("Verify", |b| {
  106. b.iter(|| {
  107. assert!(black_box(&compressed_snark)
  108. .verify(
  109. black_box(&vk),
  110. black_box(num_steps),
  111. black_box(vec![<G1 as Group>::Scalar::from(2u64)]),
  112. black_box(vec![<G2 as Group>::Scalar::from(2u64)]),
  113. )
  114. .is_ok());
  115. })
  116. });
  117. group.finish();
  118. }
  119. }
  120. fn bench_compressed_snark_with_computational_commitments(c: &mut Criterion) {
  121. let num_samples = 10;
  122. let num_cons_verifier_circuit_primary = 9819;
  123. // we vary the number of constraints in the step circuit
  124. for &num_cons_in_augmented_circuit in [9819, 16384, 32768, 65536, 131072, 262144].iter() {
  125. // number of constraints in the step circuit
  126. let num_cons = num_cons_in_augmented_circuit - num_cons_verifier_circuit_primary;
  127. let mut group = c.benchmark_group(format!(
  128. "CompressedSNARK-Commitments-StepCircuitSize-{num_cons}"
  129. ));
  130. group
  131. .sampling_mode(SamplingMode::Flat)
  132. .sample_size(num_samples);
  133. let c_primary = NonTrivialTestCircuit::new(num_cons);
  134. let c_secondary = TrivialTestCircuit::default();
  135. // Produce public parameters
  136. let pp = PublicParams::<G1, G2, C1, C2>::setup(c_primary.clone(), c_secondary.clone());
  137. // Produce prover and verifier keys for CompressedSNARK
  138. let (pk, vk) = CompressedSNARK::<_, _, _, _, SS1, SS2>::setup(&pp).unwrap();
  139. // produce a recursive SNARK
  140. let num_steps = 3;
  141. let mut recursive_snark: RecursiveSNARK<G1, G2, C1, C2> = RecursiveSNARK::new(
  142. &pp,
  143. &c_primary,
  144. &c_secondary,
  145. vec![<G1 as Group>::Scalar::from(2u64)],
  146. vec![<G2 as Group>::Scalar::from(2u64)],
  147. );
  148. for i in 0..num_steps {
  149. let res = recursive_snark.prove_step(
  150. &pp,
  151. &c_primary,
  152. &c_secondary,
  153. vec![<G1 as Group>::Scalar::from(2u64)],
  154. vec![<G2 as Group>::Scalar::from(2u64)],
  155. );
  156. assert!(res.is_ok());
  157. // verify the recursive snark at each step of recursion
  158. let res = recursive_snark.verify(
  159. &pp,
  160. i + 1,
  161. &[<G1 as Group>::Scalar::from(2u64)],
  162. &[<G2 as Group>::Scalar::from(2u64)],
  163. );
  164. assert!(res.is_ok());
  165. }
  166. // Bench time to produce a compressed SNARK
  167. group.bench_function("Prove", |b| {
  168. b.iter(|| {
  169. assert!(CompressedSNARK::<_, _, _, _, SS1, SS2>::prove(
  170. black_box(&pp),
  171. black_box(&pk),
  172. black_box(&recursive_snark)
  173. )
  174. .is_ok());
  175. })
  176. });
  177. let res = CompressedSNARK::<_, _, _, _, SS1, SS2>::prove(&pp, &pk, &recursive_snark);
  178. assert!(res.is_ok());
  179. let compressed_snark = res.unwrap();
  180. // Benchmark the verification time
  181. group.bench_function("Verify", |b| {
  182. b.iter(|| {
  183. assert!(black_box(&compressed_snark)
  184. .verify(
  185. black_box(&vk),
  186. black_box(num_steps),
  187. black_box(vec![<G1 as Group>::Scalar::from(2u64)]),
  188. black_box(vec![<G2 as Group>::Scalar::from(2u64)]),
  189. )
  190. .is_ok());
  191. })
  192. });
  193. group.finish();
  194. }
  195. }
  196. #[derive(Clone, Debug, Default)]
  197. struct NonTrivialTestCircuit<F: PrimeField> {
  198. num_cons: usize,
  199. _p: PhantomData<F>,
  200. }
  201. impl<F> NonTrivialTestCircuit<F>
  202. where
  203. F: PrimeField,
  204. {
  205. pub fn new(num_cons: usize) -> Self {
  206. Self {
  207. num_cons,
  208. _p: Default::default(),
  209. }
  210. }
  211. }
  212. impl<F> StepCircuit<F> for NonTrivialTestCircuit<F>
  213. where
  214. F: PrimeField,
  215. {
  216. fn arity(&self) -> usize {
  217. 1
  218. }
  219. fn synthesize<CS: ConstraintSystem<F>>(
  220. &self,
  221. cs: &mut CS,
  222. z: &[AllocatedNum<F>],
  223. ) -> Result<Vec<AllocatedNum<F>>, SynthesisError> {
  224. // Consider a an equation: `x^2 = y`, where `x` and `y` are respectively the input and output.
  225. let mut x = z[0].clone();
  226. let mut y = x.clone();
  227. for i in 0..self.num_cons {
  228. y = x.square(cs.namespace(|| format!("x_sq_{i}")))?;
  229. x = y.clone();
  230. }
  231. Ok(vec![y])
  232. }
  233. fn output(&self, z: &[F]) -> Vec<F> {
  234. let mut x = z[0];
  235. let mut y = x;
  236. for _i in 0..self.num_cons {
  237. y = x * x;
  238. x = y;
  239. }
  240. vec![y]
  241. }
  242. }