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.

301 lines
9.1 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. let x_i_plus_1_pow_5 = x_i_plus_1_quad.mul(
  115. cs.namespace(|| format!("x_i_plus_1_pow_5_{}", i)),
  116. &x_i_plus_1,
  117. )?;
  118. cs.enforce(
  119. || format!("x_i_plus_1_pow_5 = x_i + y_i_iter_{}", i),
  120. |lc| lc + x_i_plus_1_pow_5.get_variable(),
  121. |lc| lc + CS::one(),
  122. |lc| lc + x_i.get_variable() + y_i.get_variable(),
  123. );
  124. // return hash(x_i_plus_1, y_i_plus_1) since Nova circuits expect a single output
  125. if i == self.seq.len() - 1 {
  126. z_out = poseidon_hash(
  127. cs.namespace(|| "output hash"),
  128. vec![x_i_plus_1, x_i.clone()],
  129. &self.pc,
  130. );
  131. }
  132. }
  133. z_out
  134. }
  135. fn output(&self, z: &F) -> F {
  136. // sanity check
  137. let z_hash =
  138. Poseidon::<F, U2>::new_with_preimage(&[self.seq[0].x_i, self.seq[0].y_i], &self.pc).hash();
  139. debug_assert_eq!(z, &z_hash);
  140. // compute output hash using advice
  141. let iters = self.seq.len();
  142. Poseidon::<F, U2>::new_with_preimage(
  143. &[
  144. self.seq[iters - 1].x_i_plus_1,
  145. self.seq[iters - 1].y_i_plus_1,
  146. ],
  147. &self.pc,
  148. )
  149. .hash()
  150. }
  151. }
  152. fn main() {
  153. let num_steps = 10;
  154. let num_iters_per_step = 10; // number of iterations of MinRoot per Nova's recursive step
  155. let pc = PoseidonConstants::<<G1 as Group>::Scalar, U2>::new_with_strength(Strength::Standard);
  156. let circuit_primary = MinRootCircuit {
  157. seq: vec![
  158. MinRootIteration {
  159. x_i: <G1 as Group>::Scalar::zero(),
  160. y_i: <G1 as Group>::Scalar::zero(),
  161. x_i_plus_1: <G1 as Group>::Scalar::zero(),
  162. y_i_plus_1: <G1 as Group>::Scalar::zero(),
  163. };
  164. num_iters_per_step
  165. ],
  166. pc: pc.clone(),
  167. };
  168. let circuit_secondary = TrivialTestCircuit::default();
  169. println!("Nova-based VDF with MinRoot delay function");
  170. println!("==========================================");
  171. println!(
  172. "Proving {} iterations of MinRoot per step",
  173. num_iters_per_step
  174. );
  175. // produce public parameters
  176. println!("Producing public parameters...");
  177. let pp = PublicParams::<
  178. G1,
  179. G2,
  180. MinRootCircuit<<G1 as Group>::Scalar>,
  181. TrivialTestCircuit<<G2 as Group>::Scalar>,
  182. >::setup(circuit_primary, circuit_secondary.clone());
  183. println!(
  184. "Number of constraints per step (primary circuit): {}",
  185. pp.num_constraints().0
  186. );
  187. println!(
  188. "Number of constraints per step (secondary circuit): {}",
  189. pp.num_constraints().1
  190. );
  191. // produce non-deterministic advice
  192. let (z0_primary, minroot_iterations) = MinRootIteration::new(
  193. num_iters_per_step * num_steps,
  194. &<G1 as Group>::Scalar::zero(),
  195. &<G1 as Group>::Scalar::one(),
  196. &pc,
  197. );
  198. let minroot_circuits = (0..num_steps)
  199. .map(|i| MinRootCircuit {
  200. seq: (0..num_iters_per_step)
  201. .map(|j| MinRootIteration {
  202. x_i: minroot_iterations[i * num_iters_per_step + j].x_i,
  203. y_i: minroot_iterations[i * num_iters_per_step + j].y_i,
  204. x_i_plus_1: minroot_iterations[i * num_iters_per_step + j].x_i_plus_1,
  205. y_i_plus_1: minroot_iterations[i * num_iters_per_step + j].y_i_plus_1,
  206. })
  207. .collect::<Vec<_>>(),
  208. pc: pc.clone(),
  209. })
  210. .collect::<Vec<_>>();
  211. let z0_secondary = <G2 as Group>::Scalar::zero();
  212. type C1 = MinRootCircuit<<G1 as Group>::Scalar>;
  213. type C2 = TrivialTestCircuit<<G2 as Group>::Scalar>;
  214. // produce a recursive SNARK
  215. println!("Generating a RecursiveSNARK...");
  216. let mut recursive_snark: Option<RecursiveSNARK<G1, G2, C1, C2>> = None;
  217. for (i, circuit_primary) in minroot_circuits.iter().take(num_steps).enumerate() {
  218. let start = Instant::now();
  219. let res = RecursiveSNARK::prove_step(
  220. &pp,
  221. recursive_snark,
  222. circuit_primary.clone(),
  223. circuit_secondary.clone(),
  224. z0_primary,
  225. z0_secondary,
  226. );
  227. assert!(res.is_ok());
  228. println!(
  229. "RecursiveSNARK::prove_step {}: {:?}, took {:?} ",
  230. i,
  231. res.is_ok(),
  232. start.elapsed()
  233. );
  234. recursive_snark = Some(res.unwrap());
  235. }
  236. assert!(recursive_snark.is_some());
  237. let recursive_snark = recursive_snark.unwrap();
  238. // verify the recursive SNARK
  239. println!("Verifying a RecursiveSNARK...");
  240. let start = Instant::now();
  241. let res = recursive_snark.verify(&pp, num_steps, z0_primary, z0_secondary);
  242. println!(
  243. "RecursiveSNARK::verify: {:?}, took {:?}",
  244. res.is_ok(),
  245. start.elapsed()
  246. );
  247. assert!(res.is_ok());
  248. // produce a compressed SNARK
  249. println!("Generating a CompressedSNARK using Spartan with IPA-PC...");
  250. let start = Instant::now();
  251. type S1 = nova_snark::spartan_with_ipa_pc::RelaxedR1CSSNARK<G1>;
  252. type S2 = nova_snark::spartan_with_ipa_pc::RelaxedR1CSSNARK<G2>;
  253. let res = CompressedSNARK::<_, _, _, _, S1, S2>::prove(&pp, &recursive_snark);
  254. println!(
  255. "CompressedSNARK::prove: {:?}, took {:?}",
  256. res.is_ok(),
  257. start.elapsed()
  258. );
  259. assert!(res.is_ok());
  260. let compressed_snark = res.unwrap();
  261. // verify the compressed SNARK
  262. println!("Verifying a CompressedSNARK...");
  263. let start = Instant::now();
  264. let res = compressed_snark.verify(&pp, num_steps, z0_primary, z0_secondary);
  265. println!(
  266. "CompressedSNARK::verify: {:?}, took {:?}",
  267. res.is_ok(),
  268. start.elapsed()
  269. );
  270. assert!(res.is_ok());
  271. }