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