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.

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