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