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.

283 lines
8.5 KiB

  1. //! Demonstrates how to use Nova to produce a recursive proof of the correct execution of
  2. //! iterations of the MinRoot function, thereby realizing a Nova-based verifiable delay function (VDF).
  3. //! We execute a configurable number of iterations of the MinRoot function per step of Nova's recursion.
  4. type G1 = pasta_curves::pallas::Point;
  5. type G2 = pasta_curves::vesta::Point;
  6. use ::bellperson::{gadgets::num::AllocatedNum, ConstraintSystem, SynthesisError};
  7. use ff::PrimeField;
  8. use nova_snark::{
  9. traits::{
  10. circuit::{StepCircuit, TrivialTestCircuit},
  11. Group,
  12. },
  13. CompressedSNARK, PublicParams, RecursiveSNARK,
  14. };
  15. use num_bigint::BigUint;
  16. use std::time::Instant;
  17. #[derive(Clone, Debug)]
  18. struct MinRootIteration<F: PrimeField> {
  19. x_i: F,
  20. y_i: F,
  21. x_i_plus_1: F,
  22. y_i_plus_1: F,
  23. }
  24. impl<F: PrimeField> MinRootIteration<F> {
  25. // produces a sample non-deterministic advice, executing one invocation of MinRoot per step
  26. fn new(num_iters: usize, x_0: &F, y_0: &F) -> (Vec<F>, Vec<Self>) {
  27. // although this code is written generically, it is tailored to Pallas' scalar field
  28. // (p - 3 / 5)
  29. let exp = BigUint::parse_bytes(
  30. b"23158417847463239084714197001737581570690445185553317903743794198714690358477",
  31. 10,
  32. )
  33. .unwrap();
  34. let mut res = Vec::new();
  35. let mut x_i = *x_0;
  36. let mut y_i = *y_0;
  37. for _i in 0..num_iters {
  38. let x_i_plus_1 = (x_i + y_i).pow_vartime(exp.to_u64_digits()); // computes the fifth root of x_i + y_i
  39. // sanity check
  40. let sq = x_i_plus_1 * x_i_plus_1;
  41. let quad = sq * sq;
  42. let fifth = quad * x_i_plus_1;
  43. debug_assert_eq!(fifth, x_i + y_i);
  44. let y_i_plus_1 = x_i;
  45. res.push(Self {
  46. x_i,
  47. y_i,
  48. x_i_plus_1,
  49. y_i_plus_1,
  50. });
  51. x_i = x_i_plus_1;
  52. y_i = y_i_plus_1;
  53. }
  54. let z0 = vec![*x_0, *y_0];
  55. (z0, res)
  56. }
  57. }
  58. #[derive(Clone, Debug)]
  59. struct MinRootCircuit<F: PrimeField> {
  60. seq: Vec<MinRootIteration<F>>,
  61. }
  62. impl<F> StepCircuit<F> for MinRootCircuit<F>
  63. where
  64. F: PrimeField,
  65. {
  66. fn arity(&self) -> usize {
  67. 2
  68. }
  69. fn synthesize<CS: ConstraintSystem<F>>(
  70. &self,
  71. cs: &mut CS,
  72. z: &[AllocatedNum<F>],
  73. ) -> Result<Vec<AllocatedNum<F>>, SynthesisError> {
  74. let mut z_out: Result<Vec<AllocatedNum<F>>, SynthesisError> =
  75. Err(SynthesisError::AssignmentMissing);
  76. // use the provided inputs
  77. let x_0 = z[0].clone();
  78. let y_0 = z[1].clone();
  79. // variables to hold running x_i and y_i
  80. let mut x_i = x_0;
  81. let mut y_i = y_0;
  82. for i in 0..self.seq.len() {
  83. // non deterministic advice
  84. let x_i_plus_1 =
  85. AllocatedNum::alloc(cs.namespace(|| format!("x_i_plus_1_iter_{}", i)), || {
  86. Ok(self.seq[i].x_i_plus_1)
  87. })?;
  88. // check the following conditions hold:
  89. // (i) x_i_plus_1 = (x_i + y_i)^{1/5}, which can be more easily checked with x_i_plus_1^5 = x_i + y_i
  90. // (ii) y_i_plus_1 = x_i
  91. // (1) constraints for condition (i) are below
  92. // (2) constraints for condition (ii) is avoided because we just used x_i wherever y_i_plus_1 is used
  93. let x_i_plus_1_sq =
  94. x_i_plus_1.square(cs.namespace(|| format!("x_i_plus_1_sq_iter_{}", i)))?;
  95. let x_i_plus_1_quad =
  96. x_i_plus_1_sq.square(cs.namespace(|| format!("x_i_plus_1_quad_{}", i)))?;
  97. cs.enforce(
  98. || format!("x_i_plus_1_quad * x_i_plus_1 = x_i + y_i_iter_{}", i),
  99. |lc| lc + x_i_plus_1_quad.get_variable(),
  100. |lc| lc + x_i_plus_1.get_variable(),
  101. |lc| lc + x_i.get_variable() + y_i.get_variable(),
  102. );
  103. if i == self.seq.len() - 1 {
  104. z_out = Ok(vec![x_i_plus_1.clone(), x_i.clone()]);
  105. }
  106. // update x_i and y_i for the next iteration
  107. y_i = x_i;
  108. x_i = x_i_plus_1;
  109. }
  110. z_out
  111. }
  112. fn output(&self, z: &[F]) -> Vec<F> {
  113. // sanity check
  114. debug_assert_eq!(z[0], self.seq[0].x_i);
  115. debug_assert_eq!(z[1], self.seq[0].y_i);
  116. // compute output using advice
  117. vec![
  118. self.seq[self.seq.len() - 1].x_i_plus_1,
  119. self.seq[self.seq.len() - 1].y_i_plus_1,
  120. ]
  121. }
  122. }
  123. fn main() {
  124. println!("Nova-based VDF with MinRoot delay function");
  125. println!("=========================================================");
  126. let num_steps = 10;
  127. for num_iters_per_step in [1024, 2048, 4096, 8192, 16384, 32768, 65535] {
  128. // number of iterations of MinRoot per Nova's recursive step
  129. let circuit_primary = MinRootCircuit {
  130. seq: vec![
  131. MinRootIteration {
  132. x_i: <G1 as Group>::Scalar::zero(),
  133. y_i: <G1 as Group>::Scalar::zero(),
  134. x_i_plus_1: <G1 as Group>::Scalar::zero(),
  135. y_i_plus_1: <G1 as Group>::Scalar::zero(),
  136. };
  137. num_iters_per_step
  138. ],
  139. };
  140. let circuit_secondary = TrivialTestCircuit::default();
  141. println!(
  142. "Proving {} iterations of MinRoot per step",
  143. num_iters_per_step
  144. );
  145. // produce public parameters
  146. println!("Producing public parameters...");
  147. let pp = PublicParams::<
  148. G1,
  149. G2,
  150. MinRootCircuit<<G1 as Group>::Scalar>,
  151. TrivialTestCircuit<<G2 as Group>::Scalar>,
  152. >::setup(circuit_primary, circuit_secondary.clone());
  153. println!(
  154. "Number of constraints per step (primary circuit): {}",
  155. pp.num_constraints().0
  156. );
  157. println!(
  158. "Number of constraints per step (secondary circuit): {}",
  159. pp.num_constraints().1
  160. );
  161. println!(
  162. "Number of variables per step (primary circuit): {}",
  163. pp.num_variables().0
  164. );
  165. println!(
  166. "Number of variables per step (secondary circuit): {}",
  167. pp.num_variables().1
  168. );
  169. // produce non-deterministic advice
  170. let (z0_primary, minroot_iterations) = MinRootIteration::new(
  171. num_iters_per_step * num_steps,
  172. &<G1 as Group>::Scalar::zero(),
  173. &<G1 as Group>::Scalar::one(),
  174. );
  175. let minroot_circuits = (0..num_steps)
  176. .map(|i| MinRootCircuit {
  177. seq: (0..num_iters_per_step)
  178. .map(|j| MinRootIteration {
  179. x_i: minroot_iterations[i * num_iters_per_step + j].x_i,
  180. y_i: minroot_iterations[i * num_iters_per_step + j].y_i,
  181. x_i_plus_1: minroot_iterations[i * num_iters_per_step + j].x_i_plus_1,
  182. y_i_plus_1: minroot_iterations[i * num_iters_per_step + j].y_i_plus_1,
  183. })
  184. .collect::<Vec<_>>(),
  185. })
  186. .collect::<Vec<_>>();
  187. let z0_secondary = vec![<G2 as Group>::Scalar::zero()];
  188. type C1 = MinRootCircuit<<G1 as Group>::Scalar>;
  189. type C2 = TrivialTestCircuit<<G2 as Group>::Scalar>;
  190. // produce a recursive SNARK
  191. println!("Generating a RecursiveSNARK...");
  192. let mut recursive_snark: Option<RecursiveSNARK<G1, G2, C1, C2>> = None;
  193. for (i, circuit_primary) in minroot_circuits.iter().take(num_steps).enumerate() {
  194. let start = Instant::now();
  195. let res = RecursiveSNARK::prove_step(
  196. &pp,
  197. recursive_snark,
  198. circuit_primary.clone(),
  199. circuit_secondary.clone(),
  200. z0_primary.clone(),
  201. z0_secondary.clone(),
  202. );
  203. assert!(res.is_ok());
  204. println!(
  205. "RecursiveSNARK::prove_step {}: {:?}, took {:?} ",
  206. i,
  207. res.is_ok(),
  208. start.elapsed()
  209. );
  210. recursive_snark = Some(res.unwrap());
  211. }
  212. assert!(recursive_snark.is_some());
  213. let recursive_snark = recursive_snark.unwrap();
  214. // verify the recursive SNARK
  215. println!("Verifying a RecursiveSNARK...");
  216. let start = Instant::now();
  217. let res = recursive_snark.verify(&pp, num_steps, z0_primary.clone(), z0_secondary.clone());
  218. println!(
  219. "RecursiveSNARK::verify: {:?}, took {:?}",
  220. res.is_ok(),
  221. start.elapsed()
  222. );
  223. assert!(res.is_ok());
  224. // produce a compressed SNARK
  225. println!("Generating a CompressedSNARK using Spartan with IPA-PC...");
  226. let start = Instant::now();
  227. type S1 = nova_snark::spartan_with_ipa_pc::RelaxedR1CSSNARK<G1>;
  228. type S2 = nova_snark::spartan_with_ipa_pc::RelaxedR1CSSNARK<G2>;
  229. let res = CompressedSNARK::<_, _, _, _, S1, S2>::prove(&pp, &recursive_snark);
  230. println!(
  231. "CompressedSNARK::prove: {:?}, took {:?}",
  232. res.is_ok(),
  233. start.elapsed()
  234. );
  235. assert!(res.is_ok());
  236. let compressed_snark = res.unwrap();
  237. // verify the compressed SNARK
  238. println!("Verifying a CompressedSNARK...");
  239. let start = Instant::now();
  240. let res = compressed_snark.verify(&pp, num_steps, z0_primary, z0_secondary);
  241. println!(
  242. "CompressedSNARK::verify: {:?}, took {:?}",
  243. res.is_ok(),
  244. start.elapsed()
  245. );
  246. assert!(res.is_ok());
  247. println!("=========================================================");
  248. }
  249. }