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.

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