sonobe/folding-schemes/src/folding/nova/mod.rs
folding-schemes/src/folding/nova/mod.rsRaw
1/// Implements the scheme described in [Nova](https://eprint.iacr.org/2021/370.pdf) and
2/// [CycleFold](https://eprint.iacr.org/2023/1192.pdf).
3use ark_crypto_primitives::{
4 crh::{poseidon::CRH, CRHScheme},
5 sponge::{poseidon::PoseidonConfig, Absorb},
6};
7use ark_ec::{AffineRepr, CurveGroup, Group};
8use ark_ff::{BigInteger, PrimeField};
9use ark_r1cs_std::{groups::GroupOpsBounds, prelude::CurveVar};
10use ark_std::fmt::Debug;
11use ark_std::{One, Zero};
12use core::marker::PhantomData;
13
14use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystem};
15
16use crate::ccs::r1cs::{extract_r1cs, extract_w_x, R1CS};
17use crate::commitment::CommitmentProver;
18use crate::folding::circuits::nonnative::point_to_nonnative_limbs;
19use crate::frontend::FCircuit;
20use crate::utils::vec::is_zero_vec;
21use crate::Error;
22use crate::FoldingScheme;
23
24pub mod circuits;
25pub mod cyclefold;
26pub mod decider_eth;
27pub mod decider_eth_circuit;
28pub mod nifs;
29pub mod traits;
30
31use circuits::{AugmentedFCircuit, ChallengeGadget, CF2};
32use cyclefold::{CycleFoldChallengeGadget, CycleFoldCircuit};
33use nifs::NIFS;
34use traits::NovaR1CS;
35
36#[cfg(test)]
37use cyclefold::CF_IO_LEN;
38
39#[derive(Debug, Clone, Eq, PartialEq)]
40pub struct CommittedInstance<C: CurveGroup> {
41 pub cmE: C,
42 pub u: C::ScalarField,
43 pub cmW: C,
44 pub x: Vec<C::ScalarField>,
45}
46
47impl<C: CurveGroup> CommittedInstance<C> {
48 pub fn dummy(io_len: usize) -> Self {
49 Self {
50 cmE: C::zero(),
51 u: C::ScalarField::zero(),
52 cmW: C::zero(),
53 x: vec![C::ScalarField::zero(); io_len],
54 }
55 }
56}
57
58impl<C: CurveGroup> CommittedInstance<C>
59where
60 <C as Group>::ScalarField: Absorb,
61 <C as ark_ec::CurveGroup>::BaseField: ark_ff::PrimeField,
62{
63 /// hash implements the committed instance hash compatible with the gadget implemented in
64 /// nova/circuits.rs::CommittedInstanceVar.hash.
65 /// Returns `H(i, z_0, z_i, U_i)`, where `i` can be `i` but also `i+1`, and `U_i` is the
66 /// `CommittedInstance`.
67 pub fn hash(
68 &self,
69 poseidon_config: &PoseidonConfig<C::ScalarField>,
70 i: C::ScalarField,
71 z_0: Vec<C::ScalarField>,
72 z_i: Vec<C::ScalarField>,
73 ) -> Result<C::ScalarField, Error> {
74 let (cmE_x, cmE_y) = point_to_nonnative_limbs::<C>(self.cmE)?;
75 let (cmW_x, cmW_y) = point_to_nonnative_limbs::<C>(self.cmW)?;
76
77 CRH::<C::ScalarField>::evaluate(
78 poseidon_config,
79 vec![
80 vec![i],
81 z_0,
82 z_i,
83 vec![self.u],
84 self.x.clone(),
85 cmE_x,
86 cmE_y,
87 cmW_x,
88 cmW_y,
89 ]
90 .concat(),
91 )
92 .map_err(|e| Error::Other(e.to_string()))
93 }
94}
95
96#[derive(Debug, Clone, Eq, PartialEq)]
97pub struct Witness<C: CurveGroup> {
98 pub E: Vec<C::ScalarField>,
99 pub rE: C::ScalarField,
100 pub W: Vec<C::ScalarField>,
101 pub rW: C::ScalarField,
102}
103
104impl<C: CurveGroup> Witness<C>
105where
106 <C as Group>::ScalarField: Absorb,
107{
108 pub fn new(w: Vec<C::ScalarField>, e_len: usize) -> Self {
109 // note: at the current version, we don't use the blinding factors and we set them to 0
110 // always.
111 Self {
112 E: vec![C::ScalarField::zero(); e_len],
113 rE: C::ScalarField::zero(),
114 W: w,
115 rW: C::ScalarField::zero(),
116 }
117 }
118 pub fn commit<CP: CommitmentProver<C>>(
119 &self,
120 params: &CP::Params,
121 x: Vec<C::ScalarField>,
122 ) -> Result<CommittedInstance<C>, Error> {
123 let mut cmE = C::zero();
124 if !is_zero_vec::<C::ScalarField>(&self.E) {
125 cmE = CP::commit(params, &self.E, &self.rE)?;
126 }
127 let cmW = CP::commit(params, &self.W, &self.rW)?;
128 Ok(CommittedInstance {
129 cmE,
130 u: C::ScalarField::one(),
131 cmW,
132 x,
133 })
134 }
135}
136
137#[derive(Debug, Clone)]
138pub struct ProverParams<C1, C2, CP1, CP2>
139where
140 C1: CurveGroup,
141 C2: CurveGroup,
142 CP1: CommitmentProver<C1>,
143 CP2: CommitmentProver<C2>,
144{
145 pub poseidon_config: PoseidonConfig<C1::ScalarField>,
146 pub cm_params: CP1::Params,
147 pub cf_cm_params: CP2::Params,
148}
149
150#[derive(Debug, Clone)]
151pub struct VerifierParams<C1: CurveGroup, C2: CurveGroup> {
152 pub poseidon_config: PoseidonConfig<C1::ScalarField>,
153 pub r1cs: R1CS<C1::ScalarField>,
154 pub cf_r1cs: R1CS<C2::ScalarField>,
155}
156
157/// Implements Nova+CycleFold's IVC, described in [Nova](https://eprint.iacr.org/2021/370.pdf) and
158/// [CycleFold](https://eprint.iacr.org/2023/1192.pdf), following the FoldingScheme trait
159#[derive(Clone, Debug)]
160pub struct Nova<C1, GC1, C2, GC2, FC, CP1, CP2>
161where
162 C1: CurveGroup,
163 GC1: CurveVar<C1, CF2<C1>>,
164 C2: CurveGroup,
165 GC2: CurveVar<C2, CF2<C2>>,
166 FC: FCircuit<C1::ScalarField>,
167 CP1: CommitmentProver<C1>,
168 CP2: CommitmentProver<C2>,
169{
170 _gc1: PhantomData<GC1>,
171 _c2: PhantomData<C2>,
172 _gc2: PhantomData<GC2>,
173 /// R1CS of the Augmented Function circuit
174 pub r1cs: R1CS<C1::ScalarField>,
175 /// R1CS of the CycleFold circuit
176 pub cf_r1cs: R1CS<C2::ScalarField>,
177 pub poseidon_config: PoseidonConfig<C1::ScalarField>,
178 /// CommitmentProver::Params over C1
179 pub cm_params: CP1::Params,
180 /// CycleFold CommitmentProver::Params, over C2
181 pub cf_cm_params: CP2::Params,
182 /// F circuit, the circuit that is being folded
183 pub F: FC,
184 pub i: C1::ScalarField,
185 /// initial state
186 pub z_0: Vec<C1::ScalarField>,
187 /// current i-th state
188 pub z_i: Vec<C1::ScalarField>,
189 /// Nova instances
190 pub w_i: Witness<C1>,
191 pub u_i: CommittedInstance<C1>,
192 pub W_i: Witness<C1>,
193 pub U_i: CommittedInstance<C1>,
194
195 /// CycleFold running instance
196 pub cf_W_i: Witness<C2>,
197 pub cf_U_i: CommittedInstance<C2>,
198}
199
200impl<C1, GC1, C2, GC2, FC, CP1, CP2> FoldingScheme<C1, C2, FC>
201 for Nova<C1, GC1, C2, GC2, FC, CP1, CP2>
202where
203 C1: CurveGroup,
204 GC1: CurveVar<C1, CF2<C1>>,
205 C2: CurveGroup,
206 GC2: CurveVar<C2, CF2<C2>>,
207 FC: FCircuit<C1::ScalarField>,
208 CP1: CommitmentProver<C1>,
209 CP2: CommitmentProver<C2>,
210 <C1 as CurveGroup>::BaseField: PrimeField,
211 <C2 as CurveGroup>::BaseField: PrimeField,
212 <C1 as Group>::ScalarField: Absorb,
213 <C2 as Group>::ScalarField: Absorb,
214 C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
215 for<'a> &'a GC1: GroupOpsBounds<'a, C1, GC1>,
216 for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
217{
218 type PreprocessorParam = (Self::ProverParam, FC);
219 type ProverParam = ProverParams<C1, C2, CP1, CP2>;
220 type VerifierParam = VerifierParams<C1, C2>;
221 type CommittedInstanceWithWitness = (CommittedInstance<C1>, Witness<C1>);
222 type CFCommittedInstanceWithWitness = (CommittedInstance<C2>, Witness<C2>);
223
224 fn preprocess(
225 prep_param: &Self::PreprocessorParam,
226 ) -> Result<(Self::ProverParam, Self::VerifierParam), Error> {
227 let (prover_params, F_circuit) = prep_param;
228
229 let (r1cs, cf_r1cs) =
230 get_r1cs::<C1, GC1, C2, GC2, FC>(&prover_params.poseidon_config, F_circuit.clone())?;
231
232 let verifier_params = VerifierParams::<C1, C2> {
233 poseidon_config: prover_params.poseidon_config.clone(),
234 r1cs,
235 cf_r1cs,
236 };
237 Ok((prover_params.clone(), verifier_params))
238 }
239
240 /// Initializes the Nova+CycleFold's IVC for the given parameters and initial state `z_0`.
241 fn init(pp: &Self::ProverParam, F: FC, z_0: Vec<C1::ScalarField>) -> Result<Self, Error> {
242 // prepare the circuit to obtain its R1CS
243 let cs = ConstraintSystem::<C1::ScalarField>::new_ref();
244 let cs2 = ConstraintSystem::<C1::BaseField>::new_ref();
245
246 let augmented_F_circuit =
247 AugmentedFCircuit::<C1, C2, GC2, FC>::empty(&pp.poseidon_config, F.clone());
248 let cf_circuit = CycleFoldCircuit::<C1, GC1>::empty();
249
250 augmented_F_circuit.generate_constraints(cs.clone())?;
251 cs.finalize();
252 let cs = cs.into_inner().ok_or(Error::NoInnerConstraintSystem)?;
253 let r1cs = extract_r1cs::<C1::ScalarField>(&cs);
254
255 cf_circuit.generate_constraints(cs2.clone())?;
256 cs2.finalize();
257 let cs2 = cs2.into_inner().ok_or(Error::NoInnerConstraintSystem)?;
258 let cf_r1cs = extract_r1cs::<C1::BaseField>(&cs2);
259
260 // setup the dummy instances
261 let (w_dummy, u_dummy) = r1cs.dummy_instance();
262 let (cf_w_dummy, cf_u_dummy) = cf_r1cs.dummy_instance();
263
264 // W_dummy=W_0 is a 'dummy witness', all zeroes, but with the size corresponding to the
265 // R1CS that we're working with.
266 Ok(Self {
267 _gc1: PhantomData,
268 _c2: PhantomData,
269 _gc2: PhantomData,
270 r1cs,
271 cf_r1cs,
272 poseidon_config: pp.poseidon_config.clone(),
273 cm_params: pp.cm_params.clone(),
274 cf_cm_params: pp.cf_cm_params.clone(),
275 F,
276 i: C1::ScalarField::zero(),
277 z_0: z_0.clone(),
278 z_i: z_0,
279 w_i: w_dummy.clone(),
280 u_i: u_dummy.clone(),
281 W_i: w_dummy,
282 U_i: u_dummy,
283 // cyclefold running instance
284 cf_W_i: cf_w_dummy.clone(),
285 cf_U_i: cf_u_dummy.clone(),
286 })
287 }
288
289 /// Implements IVC.P of Nova+CycleFold
290 fn prove_step(&mut self) -> Result<(), Error> {
291 let augmented_F_circuit: AugmentedFCircuit<C1, C2, GC2, FC>;
292 let cfW_circuit: CycleFoldCircuit<C1, GC1>;
293 let cfE_circuit: CycleFoldCircuit<C1, GC1>;
294
295 if self.i > C1::ScalarField::from_le_bytes_mod_order(&std::usize::MAX.to_le_bytes()) {
296 return Err(Error::MaxStep);
297 }
298 let mut i_bytes: [u8; 8] = [0; 8];
299 i_bytes.copy_from_slice(&self.i.into_bigint().to_bytes_le()[..8]);
300 let i_usize: usize = usize::from_le_bytes(i_bytes);
301
302 let z_i1 = self.F.step_native(i_usize, self.z_i.clone())?;
303
304 // compute T and cmT for AugmentedFCircuit
305 let (T, cmT) = self.compute_cmT()?;
306
307 // r_bits is the r used to the RLC of the F' instances
308 let r_bits = ChallengeGadget::<C1>::get_challenge_native(
309 &self.poseidon_config,
310 self.U_i.clone(),
311 self.u_i.clone(),
312 cmT,
313 )?;
314 let r_Fr = C1::ScalarField::from_bigint(BigInteger::from_bits_le(&r_bits))
315 .ok_or(Error::OutOfBounds)?;
316
317 // fold Nova instances
318 let (W_i1, U_i1): (Witness<C1>, CommittedInstance<C1>) = NIFS::<C1, CP1>::fold_instances(
319 r_Fr, &self.W_i, &self.U_i, &self.w_i, &self.u_i, &T, cmT,
320 )?;
321
322 // folded instance output (public input, x)
323 // u_{i+1}.x = H(i+1, z_0, z_{i+1}, U_{i+1})
324 let u_i1_x = U_i1.hash(
325 &self.poseidon_config,
326 self.i + C1::ScalarField::one(),
327 self.z_0.clone(),
328 z_i1.clone(),
329 )?;
330
331 if self.i == C1::ScalarField::zero() {
332 // base case
333 augmented_F_circuit = AugmentedFCircuit::<C1, C2, GC2, FC> {
334 _gc2: PhantomData,
335 poseidon_config: self.poseidon_config.clone(),
336 i: Some(C1::ScalarField::zero()), // = i=0
337 i_usize: Some(0),
338 z_0: Some(self.z_0.clone()), // = z_i
339 z_i: Some(self.z_i.clone()),
340 u_i: Some(self.u_i.clone()), // = dummy
341 U_i: Some(self.U_i.clone()), // = dummy
342 U_i1: Some(U_i1.clone()),
343 cmT: Some(cmT),
344 F: self.F.clone(),
345 x: Some(u_i1_x),
346 cf1_u_i: None,
347 cf2_u_i: None,
348 cf_U_i: None,
349 cf1_U_i1: None,
350 cf_U_i1: None,
351 cf1_cmT: None,
352 cf2_cmT: None,
353 cf1_r_nonnat: None,
354 cf2_r_nonnat: None,
355 };
356
357 #[cfg(test)]
358 NIFS::<C1, CP1>::verify_folded_instance(r_Fr, &self.U_i, &self.u_i, &U_i1, &cmT)?;
359 } else {
360 // CycleFold part:
361 // get the vector used as public inputs 'x' in the CycleFold circuit
362 // cyclefold circuit for cmW
363 let cfW_u_i_x = [
364 get_cm_coordinates(&self.U_i.cmW),
365 get_cm_coordinates(&self.u_i.cmW),
366 get_cm_coordinates(&U_i1.cmW),
367 ]
368 .concat();
369 // cyclefold circuit for cmE
370 let cfE_u_i_x = [
371 get_cm_coordinates(&self.U_i.cmE),
372 get_cm_coordinates(&self.u_i.cmE),
373 get_cm_coordinates(&U_i1.cmE),
374 ]
375 .concat();
376
377 cfW_circuit = CycleFoldCircuit::<C1, GC1> {
378 _gc: PhantomData,
379 r_bits: Some(r_bits.clone()),
380 p1: Some(self.U_i.clone().cmW),
381 p2: Some(self.u_i.clone().cmW),
382 p3: Some(U_i1.clone().cmW),
383 x: Some(cfW_u_i_x.clone()),
384 };
385 cfE_circuit = CycleFoldCircuit::<C1, GC1> {
386 _gc: PhantomData,
387 r_bits: Some(r_bits.clone()),
388 p1: Some(self.U_i.clone().cmE),
389 p2: Some(cmT),
390 p3: Some(U_i1.clone().cmE),
391 x: Some(cfE_u_i_x.clone()),
392 };
393
394 // fold self.cf_U_i + cfW_U -> folded running with cfW
395 let (_cfW_w_i, cfW_u_i, cfW_W_i1, cfW_U_i1, cfW_cmT, cfW_r1_Fq) = self
396 .fold_cyclefold_circuit(
397 self.cf_W_i.clone(), // CycleFold running instance witness
398 self.cf_U_i.clone(), // CycleFold running instance
399 cfW_u_i_x,
400 cfW_circuit,
401 )?;
402 // fold [the output from folding self.cf_U_i + cfW_U] + cfE_U = folded_running_with_cfW + cfE
403 let (_cfE_w_i, cfE_u_i, cf_W_i1, cf_U_i1, cf_cmT, cf_r2_Fq) =
404 self.fold_cyclefold_circuit(cfW_W_i1, cfW_U_i1.clone(), cfE_u_i_x, cfE_circuit)?;
405
406 augmented_F_circuit = AugmentedFCircuit::<C1, C2, GC2, FC> {
407 _gc2: PhantomData,
408 poseidon_config: self.poseidon_config.clone(),
409 i: Some(self.i),
410 i_usize: Some(i_usize),
411 z_0: Some(self.z_0.clone()),
412 z_i: Some(self.z_i.clone()),
413 u_i: Some(self.u_i.clone()),
414 U_i: Some(self.U_i.clone()),
415 U_i1: Some(U_i1.clone()),
416 cmT: Some(cmT),
417 F: self.F.clone(),
418 x: Some(u_i1_x),
419 // cyclefold values
420 cf1_u_i: Some(cfW_u_i.clone()),
421 cf2_u_i: Some(cfE_u_i.clone()),
422 cf_U_i: Some(self.cf_U_i.clone()),
423 cf1_U_i1: Some(cfW_U_i1.clone()),
424 cf_U_i1: Some(cf_U_i1.clone()),
425 cf1_cmT: Some(cfW_cmT),
426 cf2_cmT: Some(cf_cmT),
427 cf1_r_nonnat: Some(cfW_r1_Fq),
428 cf2_r_nonnat: Some(cf_r2_Fq),
429 };
430
431 self.cf_W_i = cf_W_i1.clone();
432 self.cf_U_i = cf_U_i1.clone();
433
434 #[cfg(test)]
435 {
436 self.cf_r1cs.check_instance_relation(&_cfW_w_i, &cfW_u_i)?;
437 self.cf_r1cs.check_instance_relation(&_cfE_w_i, &cfE_u_i)?;
438 self.cf_r1cs
439 .check_relaxed_instance_relation(&self.cf_W_i, &self.cf_U_i)?;
440 }
441 }
442
443 let cs = ConstraintSystem::<C1::ScalarField>::new_ref();
444
445 augmented_F_circuit.generate_constraints(cs.clone())?;
446
447 let cs = cs.into_inner().ok_or(Error::NoInnerConstraintSystem)?;
448 let (w_i1, x_i1) = extract_w_x::<C1::ScalarField>(&cs);
449 if x_i1[0] != u_i1_x {
450 return Err(Error::NotEqual);
451 }
452
453 #[cfg(test)]
454 if x_i1.len() != 1 {
455 return Err(Error::NotExpectedLength(x_i1.len(), 1));
456 }
457
458 // set values for next iteration
459 self.i += C1::ScalarField::one();
460 self.z_i = z_i1.clone();
461 self.w_i = Witness::<C1>::new(w_i1, self.r1cs.A.n_rows);
462 self.u_i = self.w_i.commit::<CP1>(&self.cm_params, vec![u_i1_x])?;
463 self.W_i = W_i1.clone();
464 self.U_i = U_i1.clone();
465
466 #[cfg(test)]
467 {
468 self.r1cs.check_instance_relation(&self.w_i, &self.u_i)?;
469 self.r1cs
470 .check_relaxed_instance_relation(&self.W_i, &self.U_i)?;
471 }
472
473 Ok(())
474 }
475
476 fn state(&self) -> Vec<C1::ScalarField> {
477 self.z_i.clone()
478 }
479 fn instances(
480 &self,
481 ) -> (
482 Self::CommittedInstanceWithWitness,
483 Self::CommittedInstanceWithWitness,
484 Self::CFCommittedInstanceWithWitness,
485 ) {
486 (
487 (self.U_i.clone(), self.W_i.clone()),
488 (self.u_i.clone(), self.w_i.clone()),
489 (self.cf_U_i.clone(), self.cf_W_i.clone()),
490 )
491 }
492
493 /// Implements IVC.V of Nova+CycleFold
494 fn verify(
495 vp: Self::VerifierParam,
496 z_0: Vec<C1::ScalarField>, // initial state
497 z_i: Vec<C1::ScalarField>, // last state
498 num_steps: C1::ScalarField,
499 running_instance: Self::CommittedInstanceWithWitness,
500 incoming_instance: Self::CommittedInstanceWithWitness,
501 cyclefold_instance: Self::CFCommittedInstanceWithWitness,
502 ) -> Result<(), Error> {
503 let (U_i, W_i) = running_instance;
504 let (u_i, w_i) = incoming_instance;
505 let (cf_U_i, cf_W_i) = cyclefold_instance;
506
507 if u_i.x.len() != 1 || U_i.x.len() != 1 {
508 return Err(Error::IVCVerificationFail);
509 }
510
511 // check that u_i's output points to the running instance
512 // u_i.X == H(i, z_0, z_i, U_i)
513 let expected_u_i_x = U_i.hash(&vp.poseidon_config, num_steps, z_0, z_i.clone())?;
514 if expected_u_i_x != u_i.x[0] {
515 return Err(Error::IVCVerificationFail);
516 }
517
518 // check u_i.cmE==0, u_i.u==1 (=u_i is a un-relaxed instance)
519 if !u_i.cmE.is_zero() || !u_i.u.is_one() {
520 return Err(Error::IVCVerificationFail);
521 }
522
523 // check R1CS satisfiability
524 vp.r1cs.check_instance_relation(&w_i, &u_i)?;
525 // check RelaxedR1CS satisfiability
526 vp.r1cs.check_relaxed_instance_relation(&W_i, &U_i)?;
527
528 // check CycleFold RelaxedR1CS satisfiability
529 vp.cf_r1cs
530 .check_relaxed_instance_relation(&cf_W_i, &cf_U_i)?;
531
532 Ok(())
533 }
534}
535
536impl<C1, GC1, C2, GC2, FC, CP1, CP2> Nova<C1, GC1, C2, GC2, FC, CP1, CP2>
537where
538 C1: CurveGroup,
539 GC1: CurveVar<C1, CF2<C1>>,
540 C2: CurveGroup,
541 GC2: CurveVar<C2, CF2<C2>>,
542 FC: FCircuit<C1::ScalarField>,
543 CP1: CommitmentProver<C1>,
544 CP2: CommitmentProver<C2>,
545 <C2 as CurveGroup>::BaseField: PrimeField,
546 <C1 as Group>::ScalarField: Absorb,
547 <C2 as Group>::ScalarField: Absorb,
548 C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
549{
550 // computes T and cmT for the AugmentedFCircuit
551 fn compute_cmT(&self) -> Result<(Vec<C1::ScalarField>, C1), Error> {
552 NIFS::<C1, CP1>::compute_cmT(
553 &self.cm_params,
554 &self.r1cs,
555 &self.w_i,
556 &self.u_i,
557 &self.W_i,
558 &self.U_i,
559 )
560 }
561 // computes T* and cmT* for the CycleFoldCircuit
562 fn compute_cf_cmT(
563 &self,
564 cf_w_i: &Witness<C2>,
565 cf_u_i: &CommittedInstance<C2>,
566 cf_W_i: &Witness<C2>,
567 cf_U_i: &CommittedInstance<C2>,
568 ) -> Result<(Vec<C2::ScalarField>, C2), Error> {
569 NIFS::<C2, CP2>::compute_cyclefold_cmT(
570 &self.cf_cm_params,
571 &self.cf_r1cs,
572 cf_w_i,
573 cf_u_i,
574 cf_W_i,
575 cf_U_i,
576 )
577 }
578}
579
580impl<C1, GC1, C2, GC2, FC, CP1, CP2> Nova<C1, GC1, C2, GC2, FC, CP1, CP2>
581where
582 C1: CurveGroup,
583 GC1: CurveVar<C1, CF2<C1>>,
584 C2: CurveGroup,
585 GC2: CurveVar<C2, CF2<C2>>,
586 FC: FCircuit<C1::ScalarField>,
587 CP1: CommitmentProver<C1>,
588 CP2: CommitmentProver<C2>,
589 <C1 as CurveGroup>::BaseField: PrimeField,
590 <C2 as CurveGroup>::BaseField: PrimeField,
591 <C1 as Group>::ScalarField: Absorb,
592 <C2 as Group>::ScalarField: Absorb,
593 C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
594 for<'a> &'a GC1: GroupOpsBounds<'a, C1, GC1>,
595 for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
596{
597 // folds the given cyclefold circuit and its instances
598 #[allow(clippy::type_complexity)]
599 fn fold_cyclefold_circuit(
600 &self,
601 cf_W_i: Witness<C2>, // witness of the running instance
602 cf_U_i: CommittedInstance<C2>, // running instance
603 cf_u_i_x: Vec<C2::ScalarField>,
604 cf_circuit: CycleFoldCircuit<C1, GC1>,
605 ) -> Result<
606 (
607 Witness<C2>,
608 CommittedInstance<C2>, // u_i
609 Witness<C2>, // W_i1
610 CommittedInstance<C2>, // U_i1
611 C2, // cmT
612 C2::ScalarField, // r_Fq
613 ),
614 Error,
615 > {
616 let cs2 = ConstraintSystem::<C1::BaseField>::new_ref();
617 cf_circuit.generate_constraints(cs2.clone())?;
618
619 let cs2 = cs2.into_inner().ok_or(Error::NoInnerConstraintSystem)?;
620 let (cf_w_i, cf_x_i) = extract_w_x::<C1::BaseField>(&cs2);
621 if cf_x_i != cf_u_i_x {
622 return Err(Error::NotEqual);
623 }
624
625 #[cfg(test)]
626 if cf_x_i.len() != CF_IO_LEN {
627 return Err(Error::NotExpectedLength(cf_x_i.len(), CF_IO_LEN));
628 }
629
630 // fold cyclefold instances
631 let cf_w_i = Witness::<C2>::new(cf_w_i.clone(), self.cf_r1cs.A.n_rows);
632 let cf_u_i: CommittedInstance<C2> =
633 cf_w_i.commit::<CP2>(&self.cf_cm_params, cf_x_i.clone())?;
634
635 // compute T* and cmT* for CycleFoldCircuit
636 let (cf_T, cf_cmT) = self.compute_cf_cmT(&cf_w_i, &cf_u_i, &cf_W_i, &cf_U_i)?;
637
638 let cf_r_bits = CycleFoldChallengeGadget::<C2, GC2>::get_challenge_native(
639 &self.poseidon_config,
640 cf_U_i.clone(),
641 cf_u_i.clone(),
642 cf_cmT,
643 )?;
644 let cf_r_Fq = C1::BaseField::from_bigint(BigInteger::from_bits_le(&cf_r_bits))
645 .ok_or(Error::OutOfBounds)?;
646
647 let (cf_W_i1, cf_U_i1) = NIFS::<C2, CP2>::fold_instances(
648 cf_r_Fq, &cf_W_i, &cf_U_i, &cf_w_i, &cf_u_i, &cf_T, cf_cmT,
649 )?;
650 Ok((cf_w_i, cf_u_i, cf_W_i1, cf_U_i1, cf_cmT, cf_r_Fq))
651 }
652}
653
654/// helper method to get the r1cs from the ConstraintSynthesizer
655pub fn get_r1cs_from_cs<F: PrimeField>(
656 circuit: impl ConstraintSynthesizer<F>,
657) -> Result<R1CS<F>, Error> {
658 let cs = ConstraintSystem::<F>::new_ref();
659 circuit.generate_constraints(cs.clone())?;
660 cs.finalize();
661 let cs = cs.into_inner().ok_or(Error::NoInnerConstraintSystem)?;
662 let r1cs = extract_r1cs::<F>(&cs);
663 Ok(r1cs)
664}
665
666/// helper method to get the R1CS for both the AugmentedFCircuit and the CycleFold circuit
667#[allow(clippy::type_complexity)]
668pub fn get_r1cs<C1, GC1, C2, GC2, FC>(
669 poseidon_config: &PoseidonConfig<C1::ScalarField>,
670 F_circuit: FC,
671) -> Result<(R1CS<C1::ScalarField>, R1CS<C2::ScalarField>), Error>
672where
673 C1: CurveGroup,
674 GC1: CurveVar<C1, CF2<C1>>,
675 C2: CurveGroup,
676 GC2: CurveVar<C2, CF2<C2>>,
677 FC: FCircuit<C1::ScalarField>,
678 <C1 as CurveGroup>::BaseField: PrimeField,
679 <C2 as CurveGroup>::BaseField: PrimeField,
680 <C1 as Group>::ScalarField: Absorb,
681 <C2 as Group>::ScalarField: Absorb,
682 C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
683 for<'a> &'a GC1: GroupOpsBounds<'a, C1, GC1>,
684 for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
685{
686 let augmented_F_circuit =
687 AugmentedFCircuit::<C1, C2, GC2, FC>::empty(poseidon_config, F_circuit);
688 let cf_circuit = CycleFoldCircuit::<C1, GC1>::empty();
689 let r1cs = get_r1cs_from_cs::<C1::ScalarField>(augmented_F_circuit)?;
690 let cf_r1cs = get_r1cs_from_cs::<C2::ScalarField>(cf_circuit)?;
691 Ok((r1cs, cf_r1cs))
692}
693
694/// helper method to get the pedersen params length for both the AugmentedFCircuit and the
695/// CycleFold circuit
696pub fn get_pedersen_params_len<C1, GC1, C2, GC2, FC>(
697 poseidon_config: &PoseidonConfig<C1::ScalarField>,
698 F_circuit: FC,
699) -> Result<(usize, usize), Error>
700where
701 C1: CurveGroup,
702 GC1: CurveVar<C1, CF2<C1>>,
703 C2: CurveGroup,
704 GC2: CurveVar<C2, CF2<C2>>,
705 FC: FCircuit<C1::ScalarField>,
706 <C1 as CurveGroup>::BaseField: PrimeField,
707 <C2 as CurveGroup>::BaseField: PrimeField,
708 <C1 as Group>::ScalarField: Absorb,
709 <C2 as Group>::ScalarField: Absorb,
710 C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
711 for<'a> &'a GC1: GroupOpsBounds<'a, C1, GC1>,
712 for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
713{
714 let (r1cs, cf_r1cs) = get_r1cs::<C1, GC1, C2, GC2, FC>(poseidon_config, F_circuit)?;
715 Ok((r1cs.A.n_rows, cf_r1cs.A.n_rows))
716}
717
718pub(crate) fn get_cm_coordinates<C: CurveGroup>(cm: &C) -> Vec<C::BaseField> {
719 let zero = (&C::BaseField::zero(), &C::BaseField::one());
720 let cm = cm.into_affine();
721 let (cm_x, cm_y) = cm.xy().unwrap_or(zero);
722 vec![*cm_x, *cm_y]
723}
724
725#[cfg(test)]
726pub mod tests {
727 use super::*;
728 use ark_pallas::{constraints::GVar, Fr, Projective};
729 use ark_vesta::{constraints::GVar as GVar2, Projective as Projective2};
730
731 use crate::commitment::pedersen::Pedersen;
732 use crate::frontend::tests::CubicFCircuit;
733 use crate::transcript::poseidon::poseidon_test_config;
734
735 /// This test tests the Nova+CycleFold IVC, and by consequence it is also testing the
736 /// AugmentedFCircuit
737 #[test]
738 fn test_ivc() {
739 type NOVA = Nova<
740 Projective,
741 GVar,
742 Projective2,
743 GVar2,
744 CubicFCircuit<Fr>,
745 Pedersen<Projective>,
746 Pedersen<Projective2>,
747 >;
748
749 let mut rng = ark_std::test_rng();
750 let poseidon_config = poseidon_test_config::<Fr>();
751
752 let F_circuit = CubicFCircuit::<Fr>::new(());
753 let z_0 = vec![Fr::from(3_u32)];
754
755 let (cm_len, cf_cm_len) =
756 get_pedersen_params_len::<Projective, GVar, Projective2, GVar2, CubicFCircuit<Fr>>(
757 &poseidon_config,
758 F_circuit,
759 )
760 .unwrap();
761 let pedersen_params = Pedersen::<Projective>::new_params(&mut rng, cm_len);
762 let cf_pedersen_params = Pedersen::<Projective2>::new_params(&mut rng, cf_cm_len);
763
764 let prover_params =
765 ProverParams::<Projective, Projective2, Pedersen<Projective>, Pedersen<Projective2>> {
766 poseidon_config: poseidon_config.clone(),
767 cm_params: pedersen_params,
768 cf_cm_params: cf_pedersen_params,
769 };
770
771 let mut nova = NOVA::init(&prover_params, F_circuit, z_0.clone()).unwrap();
772
773 let num_steps: usize = 3;
774 for _ in 0..num_steps {
775 nova.prove_step().unwrap();
776 }
777 assert_eq!(Fr::from(num_steps as u32), nova.i);
778
779 let verifier_params = VerifierParams::<Projective, Projective2> {
780 poseidon_config,
781 r1cs: nova.clone().r1cs,
782 cf_r1cs: nova.clone().cf_r1cs,
783 };
784 let (running_instance, incoming_instance, cyclefold_instance) = nova.instances();
785 NOVA::verify(
786 verifier_params,
787 z_0,
788 nova.z_i,
789 nova.i,
790 running_instance,
791 incoming_instance,
792 cyclefold_instance,
793 )
794 .unwrap();
795 }
796}