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.

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