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.

315 lines
9.6 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. // allocate variables to hold x_0 and y_0
  80. let x_0 = AllocatedNum::alloc(cs.namespace(|| "x_0"), || Ok(self.seq[0].x_i))?;
  81. let y_0 = AllocatedNum::alloc(cs.namespace(|| "y_0"), || Ok(self.seq[0].y_i))?;
  82. // variables to hold running x_i and y_i
  83. let mut x_i = x_0;
  84. let mut y_i = y_0;
  85. for i in 0..self.seq.len() {
  86. // non deterministic advice
  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.clone(), x_i.clone()],
  125. &self.pc,
  126. );
  127. }
  128. // update x_i and y_i for the next iteration
  129. y_i = x_i;
  130. x_i = x_i_plus_1;
  131. }
  132. z_out
  133. }
  134. fn output(&self, z: &F) -> F {
  135. // sanity check
  136. let z_hash =
  137. Poseidon::<F, U2>::new_with_preimage(&[self.seq[0].x_i, self.seq[0].y_i], &self.pc).hash();
  138. debug_assert_eq!(z, &z_hash);
  139. // compute output hash using advice
  140. let iters = self.seq.len();
  141. Poseidon::<F, U2>::new_with_preimage(
  142. &[
  143. self.seq[iters - 1].x_i_plus_1,
  144. self.seq[iters - 1].y_i_plus_1,
  145. ],
  146. &self.pc,
  147. )
  148. .hash()
  149. }
  150. }
  151. fn main() {
  152. println!("Nova-based VDF with MinRoot delay function");
  153. println!("=========================================================");
  154. let num_steps = 10;
  155. for num_iters_per_step in [1024, 2048, 4096, 8192, 16384, 32768, 65535] {
  156. // number of iterations of MinRoot per Nova's recursive step
  157. let pc = PoseidonConstants::<<G1 as Group>::Scalar, U2>::new_with_strength(Strength::Standard);
  158. let circuit_primary = MinRootCircuit {
  159. seq: vec![
  160. MinRootIteration {
  161. x_i: <G1 as Group>::Scalar::zero(),
  162. y_i: <G1 as Group>::Scalar::zero(),
  163. x_i_plus_1: <G1 as Group>::Scalar::zero(),
  164. y_i_plus_1: <G1 as Group>::Scalar::zero(),
  165. };
  166. num_iters_per_step
  167. ],
  168. pc: pc.clone(),
  169. };
  170. let circuit_secondary = TrivialTestCircuit::default();
  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. println!(
  192. "Number of variables per step (primary circuit): {}",
  193. pp.num_variables().0
  194. );
  195. println!(
  196. "Number of variables per step (secondary circuit): {}",
  197. pp.num_variables().1
  198. );
  199. // produce non-deterministic advice
  200. let (z0_primary, minroot_iterations) = MinRootIteration::new(
  201. num_iters_per_step * num_steps,
  202. &<G1 as Group>::Scalar::zero(),
  203. &<G1 as Group>::Scalar::one(),
  204. &pc,
  205. );
  206. let minroot_circuits = (0..num_steps)
  207. .map(|i| MinRootCircuit {
  208. seq: (0..num_iters_per_step)
  209. .map(|j| MinRootIteration {
  210. x_i: minroot_iterations[i * num_iters_per_step + j].x_i,
  211. y_i: minroot_iterations[i * num_iters_per_step + j].y_i,
  212. x_i_plus_1: minroot_iterations[i * num_iters_per_step + j].x_i_plus_1,
  213. y_i_plus_1: minroot_iterations[i * num_iters_per_step + j].y_i_plus_1,
  214. })
  215. .collect::<Vec<_>>(),
  216. pc: pc.clone(),
  217. })
  218. .collect::<Vec<_>>();
  219. let z0_secondary = <G2 as Group>::Scalar::zero();
  220. type C1 = MinRootCircuit<<G1 as Group>::Scalar>;
  221. type C2 = TrivialTestCircuit<<G2 as Group>::Scalar>;
  222. // produce a recursive SNARK
  223. println!("Generating a RecursiveSNARK...");
  224. let mut recursive_snark: Option<RecursiveSNARK<G1, G2, C1, C2>> = None;
  225. for (i, circuit_primary) in minroot_circuits.iter().take(num_steps).enumerate() {
  226. let start = Instant::now();
  227. let res = RecursiveSNARK::prove_step(
  228. &pp,
  229. recursive_snark,
  230. circuit_primary.clone(),
  231. circuit_secondary.clone(),
  232. z0_primary,
  233. z0_secondary,
  234. );
  235. assert!(res.is_ok());
  236. println!(
  237. "RecursiveSNARK::prove_step {}: {:?}, took {:?} ",
  238. i,
  239. res.is_ok(),
  240. start.elapsed()
  241. );
  242. recursive_snark = Some(res.unwrap());
  243. }
  244. assert!(recursive_snark.is_some());
  245. let recursive_snark = recursive_snark.unwrap();
  246. // verify the recursive SNARK
  247. println!("Verifying a RecursiveSNARK...");
  248. let start = Instant::now();
  249. let res = recursive_snark.verify(&pp, num_steps, z0_primary, z0_secondary);
  250. println!(
  251. "RecursiveSNARK::verify: {:?}, took {:?}",
  252. res.is_ok(),
  253. start.elapsed()
  254. );
  255. assert!(res.is_ok());
  256. // produce a compressed SNARK
  257. println!("Generating a CompressedSNARK using Spartan with IPA-PC...");
  258. let start = Instant::now();
  259. type S1 = nova_snark::spartan_with_ipa_pc::RelaxedR1CSSNARK<G1>;
  260. type S2 = nova_snark::spartan_with_ipa_pc::RelaxedR1CSSNARK<G2>;
  261. let res = CompressedSNARK::<_, _, _, _, S1, S2>::prove(&pp, &recursive_snark);
  262. println!(
  263. "CompressedSNARK::prove: {:?}, took {:?}",
  264. res.is_ok(),
  265. start.elapsed()
  266. );
  267. assert!(res.is_ok());
  268. let compressed_snark = res.unwrap();
  269. // verify the compressed SNARK
  270. println!("Verifying a CompressedSNARK...");
  271. let start = Instant::now();
  272. let res = compressed_snark.verify(&pp, num_steps, z0_primary, z0_secondary);
  273. println!(
  274. "CompressedSNARK::verify: {:?}, took {:?}",
  275. res.is_ok(),
  276. start.elapsed()
  277. );
  278. assert!(res.is_ok());
  279. println!("=========================================================");
  280. }
  281. }