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_field_to_field_elements, point_to_nonnative_limbs,
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) = point_to_nonnative_limbs::<C>(self.cmE)?;
77 let (cmW_x, cmW_y) = point_to_nonnative_limbs::<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(&std::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: Some(self.u_i.clone()), // = dummy
396 U_i: Some(self.U_i.clone()), // = dummy
397 U_i1: Some(U_i1.clone()),
398 r_nonnat: Some(r_Fq),
399 cmT: Some(cmT),
400 F: self.F.clone(),
401 x: Some(u_i1_x),
402 cf1_u_i: None,
403 cf2_u_i: None,
404 cf_U_i: None,
405 cf1_U_i1: None,
406 cf_U_i1: None,
407 cf1_cmT: None,
408 cf2_cmT: None,
409 cf1_r_nonnat: None,
410 cf2_r_nonnat: None,
411 cf_x: Some(cf_u_i1_x),
412 };
413
414 #[cfg(test)]
415 NIFS::<C1, CS1>::verify_folded_instance(r_Fr, &self.U_i, &self.u_i, &U_i1, &cmT)?;
416 } else {
417 // CycleFold part:
418 // get the vector used as public inputs 'x' in the CycleFold circuit
419 // cyclefold circuit for cmW
420 let cfW_u_i_x = [
421 vec![r_Fq],
422 get_cm_coordinates(&self.U_i.cmW),
423 get_cm_coordinates(&self.u_i.cmW),
424 get_cm_coordinates(&U_i1.cmW),
425 ]
426 .concat();
427 // cyclefold circuit for cmE
428 let cfE_u_i_x = [
429 vec![r_Fq],
430 get_cm_coordinates(&self.U_i.cmE),
431 get_cm_coordinates(&cmT),
432 get_cm_coordinates(&U_i1.cmE),
433 ]
434 .concat();
435
436 let cfW_circuit = CycleFoldCircuit::<C1, GC1> {
437 _gc: PhantomData,
438 r_bits: Some(r_bits.clone()),
439 p1: Some(self.U_i.clone().cmW),
440 p2: Some(self.u_i.clone().cmW),
441 p3: Some(U_i1.clone().cmW),
442 x: Some(cfW_u_i_x.clone()),
443 };
444 let cfE_circuit = CycleFoldCircuit::<C1, GC1> {
445 _gc: PhantomData,
446 r_bits: Some(r_bits.clone()),
447 p1: Some(self.U_i.clone().cmE),
448 p2: Some(cmT),
449 p3: Some(U_i1.clone().cmE),
450 x: Some(cfE_u_i_x.clone()),
451 };
452
453 // fold self.cf_U_i + cfW_U -> folded running with cfW
454 let (_cfW_w_i, cfW_u_i, cfW_W_i1, cfW_U_i1, cfW_cmT, cfW_r1_Fq) = self
455 .fold_cyclefold_circuit(
456 self.cf_W_i.clone(), // CycleFold running instance witness
457 self.cf_U_i.clone(), // CycleFold running instance
458 cfW_u_i_x,
459 cfW_circuit,
460 )?;
461 // fold [the output from folding self.cf_U_i + cfW_U] + cfE_U = folded_running_with_cfW + cfE
462 let (_cfE_w_i, cfE_u_i, cf_W_i1, cf_U_i1, cf_cmT, cf_r2_Fq) =
463 self.fold_cyclefold_circuit(cfW_W_i1, cfW_U_i1.clone(), cfE_u_i_x, cfE_circuit)?;
464
465 cf_u_i1_x = cf_U_i1.hash_cyclefold(&self.poseidon_config)?;
466
467 augmented_F_circuit = AugmentedFCircuit::<C1, C2, GC2, FC> {
468 _gc2: PhantomData,
469 poseidon_config: self.poseidon_config.clone(),
470 i: Some(self.i),
471 i_usize: Some(i_usize),
472 z_0: Some(self.z_0.clone()),
473 z_i: Some(self.z_i.clone()),
474 u_i: Some(self.u_i.clone()),
475 U_i: Some(self.U_i.clone()),
476 U_i1: Some(U_i1.clone()),
477 r_nonnat: Some(r_Fq),
478 cmT: Some(cmT),
479 F: self.F.clone(),
480 x: Some(u_i1_x),
481 // cyclefold values
482 cf1_u_i: Some(cfW_u_i.clone()),
483 cf2_u_i: Some(cfE_u_i.clone()),
484 cf_U_i: Some(self.cf_U_i.clone()),
485 cf1_U_i1: Some(cfW_U_i1.clone()),
486 cf_U_i1: Some(cf_U_i1.clone()),
487 cf1_cmT: Some(cfW_cmT),
488 cf2_cmT: Some(cf_cmT),
489 cf1_r_nonnat: Some(cfW_r1_Fq),
490 cf2_r_nonnat: Some(cf_r2_Fq),
491 cf_x: Some(cf_u_i1_x),
492 };
493
494 self.cf_W_i = cf_W_i1.clone();
495 self.cf_U_i = cf_U_i1.clone();
496
497 #[cfg(test)]
498 {
499 self.cf_r1cs.check_instance_relation(&_cfW_w_i, &cfW_u_i)?;
500 self.cf_r1cs.check_instance_relation(&_cfE_w_i, &cfE_u_i)?;
501 self.cf_r1cs
502 .check_relaxed_instance_relation(&self.cf_W_i, &self.cf_U_i)?;
503 }
504 }
505
506 let cs = ConstraintSystem::<C1::ScalarField>::new_ref();
507
508 augmented_F_circuit.generate_constraints(cs.clone())?;
509
510 #[cfg(test)]
511 assert!(cs.is_satisfied().unwrap());
512
513 let cs = cs.into_inner().ok_or(Error::NoInnerConstraintSystem)?;
514 let (w_i1, x_i1) = extract_w_x::<C1::ScalarField>(&cs);
515 if x_i1[0] != u_i1_x || x_i1[1] != cf_u_i1_x {
516 return Err(Error::NotEqual);
517 }
518
519 #[cfg(test)]
520 if x_i1.len() != 2 {
521 return Err(Error::NotExpectedLength(x_i1.len(), 2));
522 }
523
524 // set values for next iteration
525 self.i += C1::ScalarField::one();
526 self.z_i = z_i1.clone();
527 self.w_i = Witness::<C1>::new(w_i1, self.r1cs.A.n_rows);
528 self.u_i = self.w_i.commit::<CS1>(&self.cs_params, x_i1)?;
529 self.W_i = W_i1.clone();
530 self.U_i = U_i1.clone();
531
532 #[cfg(test)]
533 {
534 self.r1cs.check_instance_relation(&self.w_i, &self.u_i)?;
535 self.r1cs
536 .check_relaxed_instance_relation(&self.W_i, &self.U_i)?;
537 }
538
539 Ok(())
540 }
541
542 fn state(&self) -> Vec<C1::ScalarField> {
543 self.z_i.clone()
544 }
545 fn instances(
546 &self,
547 ) -> (
548 Self::CommittedInstanceWithWitness,
549 Self::CommittedInstanceWithWitness,
550 Self::CFCommittedInstanceWithWitness,
551 ) {
552 (
553 (self.U_i.clone(), self.W_i.clone()),
554 (self.u_i.clone(), self.w_i.clone()),
555 (self.cf_U_i.clone(), self.cf_W_i.clone()),
556 )
557 }
558
559 /// Implements IVC.V of Nova+CycleFold
560 fn verify(
561 vp: Self::VerifierParam,
562 z_0: Vec<C1::ScalarField>, // initial state
563 z_i: Vec<C1::ScalarField>, // last state
564 num_steps: C1::ScalarField,
565 running_instance: Self::CommittedInstanceWithWitness,
566 incoming_instance: Self::CommittedInstanceWithWitness,
567 cyclefold_instance: Self::CFCommittedInstanceWithWitness,
568 ) -> Result<(), Error> {
569 let (U_i, W_i) = running_instance;
570 let (u_i, w_i) = incoming_instance;
571 let (cf_U_i, cf_W_i) = cyclefold_instance;
572
573 if u_i.x.len() != 2 || U_i.x.len() != 2 {
574 return Err(Error::IVCVerificationFail);
575 }
576
577 // check that u_i's output points to the running instance
578 // u_i.X[0] == H(i, z_0, z_i, U_i)
579 let expected_u_i_x = U_i.hash(&vp.poseidon_config, num_steps, z_0, z_i.clone())?;
580 if expected_u_i_x != u_i.x[0] {
581 return Err(Error::IVCVerificationFail);
582 }
583 // u_i.X[1] == H(cf_U_i)
584 let expected_cf_u_i_x = cf_U_i.hash_cyclefold(&vp.poseidon_config)?;
585 if expected_cf_u_i_x != u_i.x[1] {
586 return Err(Error::IVCVerificationFail);
587 }
588
589 // check u_i.cmE==0, u_i.u==1 (=u_i is a un-relaxed instance)
590 if !u_i.cmE.is_zero() || !u_i.u.is_one() {
591 return Err(Error::IVCVerificationFail);
592 }
593
594 // check R1CS satisfiability
595 vp.r1cs.check_instance_relation(&w_i, &u_i)?;
596 // check RelaxedR1CS satisfiability
597 vp.r1cs.check_relaxed_instance_relation(&W_i, &U_i)?;
598
599 // check CycleFold RelaxedR1CS satisfiability
600 vp.cf_r1cs
601 .check_relaxed_instance_relation(&cf_W_i, &cf_U_i)?;
602
603 Ok(())
604 }
605}
606
607impl<C1, GC1, C2, GC2, FC, CS1, CS2> Nova<C1, GC1, C2, GC2, FC, CS1, CS2>
608where
609 C1: CurveGroup,
610 GC1: CurveVar<C1, CF2<C1>> + ToConstraintFieldGadget<CF2<C1>>,
611 C2: CurveGroup,
612 GC2: CurveVar<C2, CF2<C2>>,
613 FC: FCircuit<C1::ScalarField>,
614 CS1: CommitmentScheme<C1>,
615 CS2: CommitmentScheme<C2>,
616 <C2 as CurveGroup>::BaseField: PrimeField,
617 <C1 as Group>::ScalarField: Absorb,
618 <C2 as Group>::ScalarField: Absorb,
619 C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
620{
621 // computes T and cmT for the AugmentedFCircuit
622 fn compute_cmT(&self) -> Result<(Vec<C1::ScalarField>, C1), Error> {
623 NIFS::<C1, CS1>::compute_cmT(
624 &self.cs_params,
625 &self.r1cs,
626 &self.w_i,
627 &self.u_i,
628 &self.W_i,
629 &self.U_i,
630 )
631 }
632 // computes T* and cmT* for the CycleFoldCircuit
633 fn compute_cf_cmT(
634 &self,
635 cf_w_i: &Witness<C2>,
636 cf_u_i: &CommittedInstance<C2>,
637 cf_W_i: &Witness<C2>,
638 cf_U_i: &CommittedInstance<C2>,
639 ) -> Result<(Vec<C2::ScalarField>, C2), Error> {
640 NIFS::<C2, CS2>::compute_cyclefold_cmT(
641 &self.cf_cs_params,
642 &self.cf_r1cs,
643 cf_w_i,
644 cf_u_i,
645 cf_W_i,
646 cf_U_i,
647 )
648 }
649}
650
651impl<C1, GC1, C2, GC2, FC, CS1, CS2> Nova<C1, GC1, C2, GC2, FC, CS1, CS2>
652where
653 C1: CurveGroup,
654 GC1: CurveVar<C1, CF2<C1>> + ToConstraintFieldGadget<CF2<C1>>,
655 C2: CurveGroup,
656 GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
657 FC: FCircuit<C1::ScalarField>,
658 CS1: CommitmentScheme<C1>,
659 CS2: CommitmentScheme<C2>,
660 <C1 as CurveGroup>::BaseField: PrimeField,
661 <C2 as CurveGroup>::BaseField: PrimeField,
662 <C1 as Group>::ScalarField: Absorb,
663 <C2 as Group>::ScalarField: Absorb,
664 C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
665 for<'a> &'a GC1: GroupOpsBounds<'a, C1, GC1>,
666 for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
667{
668 // folds the given cyclefold circuit and its instances
669 #[allow(clippy::type_complexity)]
670 fn fold_cyclefold_circuit(
671 &self,
672 cf_W_i: Witness<C2>, // witness of the running instance
673 cf_U_i: CommittedInstance<C2>, // running instance
674 cf_u_i_x: Vec<C2::ScalarField>,
675 cf_circuit: CycleFoldCircuit<C1, GC1>,
676 ) -> Result<
677 (
678 Witness<C2>,
679 CommittedInstance<C2>, // u_i
680 Witness<C2>, // W_i1
681 CommittedInstance<C2>, // U_i1
682 C2, // cmT
683 C2::ScalarField, // r_Fq
684 ),
685 Error,
686 > {
687 let cs2 = ConstraintSystem::<C1::BaseField>::new_ref();
688 cf_circuit.generate_constraints(cs2.clone())?;
689
690 let cs2 = cs2.into_inner().ok_or(Error::NoInnerConstraintSystem)?;
691 let (cf_w_i, cf_x_i) = extract_w_x::<C1::BaseField>(&cs2);
692 if cf_x_i != cf_u_i_x {
693 return Err(Error::NotEqual);
694 }
695
696 #[cfg(test)]
697 if cf_x_i.len() != CF_IO_LEN {
698 return Err(Error::NotExpectedLength(cf_x_i.len(), CF_IO_LEN));
699 }
700
701 // fold cyclefold instances
702 let cf_w_i = Witness::<C2>::new(cf_w_i.clone(), self.cf_r1cs.A.n_rows);
703 let cf_u_i: CommittedInstance<C2> =
704 cf_w_i.commit::<CS2>(&self.cf_cs_params, cf_x_i.clone())?;
705
706 // compute T* and cmT* for CycleFoldCircuit
707 let (cf_T, cf_cmT) = self.compute_cf_cmT(&cf_w_i, &cf_u_i, &cf_W_i, &cf_U_i)?;
708
709 let cf_r_bits = CycleFoldChallengeGadget::<C2, GC2>::get_challenge_native(
710 &self.poseidon_config,
711 cf_U_i.clone(),
712 cf_u_i.clone(),
713 cf_cmT,
714 )?;
715 let cf_r_Fq = C1::BaseField::from_bigint(BigInteger::from_bits_le(&cf_r_bits))
716 .ok_or(Error::OutOfBounds)?;
717
718 let (cf_W_i1, cf_U_i1) = NIFS::<C2, CS2>::fold_instances(
719 cf_r_Fq, &cf_W_i, &cf_U_i, &cf_w_i, &cf_u_i, &cf_T, cf_cmT,
720 )?;
721 Ok((cf_w_i, cf_u_i, cf_W_i1, cf_U_i1, cf_cmT, cf_r_Fq))
722 }
723}
724
725/// helper method to get the r1cs from the ConstraintSynthesizer
726pub fn get_r1cs_from_cs<F: PrimeField>(
727 circuit: impl ConstraintSynthesizer<F>,
728) -> Result<R1CS<F>, Error> {
729 let cs = ConstraintSystem::<F>::new_ref();
730 circuit.generate_constraints(cs.clone())?;
731 cs.finalize();
732 let cs = cs.into_inner().ok_or(Error::NoInnerConstraintSystem)?;
733 let r1cs = extract_r1cs::<F>(&cs);
734 Ok(r1cs)
735}
736
737/// helper method to get the R1CS for both the AugmentedFCircuit and the CycleFold circuit
738#[allow(clippy::type_complexity)]
739pub fn get_r1cs<C1, GC1, C2, GC2, FC>(
740 poseidon_config: &PoseidonConfig<C1::ScalarField>,
741 F_circuit: FC,
742) -> Result<(R1CS<C1::ScalarField>, R1CS<C2::ScalarField>), Error>
743where
744 C1: CurveGroup,
745 GC1: CurveVar<C1, CF2<C1>> + ToConstraintFieldGadget<CF2<C1>>,
746 C2: CurveGroup,
747 GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
748 FC: FCircuit<C1::ScalarField>,
749 <C1 as CurveGroup>::BaseField: PrimeField,
750 <C2 as CurveGroup>::BaseField: PrimeField,
751 <C1 as Group>::ScalarField: Absorb,
752 <C2 as Group>::ScalarField: Absorb,
753 C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
754 for<'a> &'a GC1: GroupOpsBounds<'a, C1, GC1>,
755 for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
756{
757 let augmented_F_circuit =
758 AugmentedFCircuit::<C1, C2, GC2, FC>::empty(poseidon_config, F_circuit);
759 let cf_circuit = CycleFoldCircuit::<C1, GC1>::empty();
760 let r1cs = get_r1cs_from_cs::<C1::ScalarField>(augmented_F_circuit)?;
761 let cf_r1cs = get_r1cs_from_cs::<C2::ScalarField>(cf_circuit)?;
762 Ok((r1cs, cf_r1cs))
763}
764
765/// helper method to get the pedersen params length for both the AugmentedFCircuit and the
766/// CycleFold circuit
767pub fn get_cs_params_len<C1, GC1, C2, GC2, FC>(
768 poseidon_config: &PoseidonConfig<C1::ScalarField>,
769 F_circuit: FC,
770) -> Result<(usize, usize), Error>
771where
772 C1: CurveGroup,
773 GC1: CurveVar<C1, CF2<C1>> + ToConstraintFieldGadget<CF2<C1>>,
774 C2: CurveGroup,
775 GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
776 FC: FCircuit<C1::ScalarField>,
777 <C1 as CurveGroup>::BaseField: PrimeField,
778 <C2 as CurveGroup>::BaseField: PrimeField,
779 <C1 as Group>::ScalarField: Absorb,
780 <C2 as Group>::ScalarField: Absorb,
781 C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
782 for<'a> &'a GC1: GroupOpsBounds<'a, C1, GC1>,
783 for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
784{
785 let (r1cs, cf_r1cs) = get_r1cs::<C1, GC1, C2, GC2, FC>(poseidon_config, F_circuit)?;
786 Ok((r1cs.A.n_rows, cf_r1cs.A.n_rows))
787}
788
789/// returns the coordinates of a commitment point. This is compatible with the arkworks
790/// GC.to_constraint_field()[..2]
791pub(crate) fn get_cm_coordinates<C: CurveGroup>(cm: &C) -> Vec<C::BaseField> {
792 let zero = (&C::BaseField::zero(), &C::BaseField::zero());
793 let cm = cm.into_affine();
794 let (cm_x, cm_y) = cm.xy().unwrap_or(zero);
795 vec![*cm_x, *cm_y]
796}
797
798#[cfg(test)]
799pub mod tests {
800 use super::*;
801 use crate::commitment::kzg::{ProverKey as KZGProverKey, KZG};
802 use ark_bn254::{constraints::GVar, Bn254, Fr, G1Projective as Projective};
803 use ark_grumpkin::{constraints::GVar as GVar2, Projective as Projective2};
804 use ark_poly_commit::kzg10::VerifierKey as KZGVerifierKey;
805
806 use crate::commitment::pedersen::Pedersen;
807 use crate::frontend::tests::CubicFCircuit;
808 use crate::transcript::poseidon::poseidon_test_config;
809
810 /// This test tests the Nova+CycleFold IVC, and by consequence it is also testing the
811 /// AugmentedFCircuit
812 #[test]
813 fn test_ivc() {
814 let mut rng = ark_std::test_rng();
815 let poseidon_config = poseidon_test_config::<Fr>();
816
817 let F_circuit = CubicFCircuit::<Fr>::new(());
818
819 let (cs_len, cf_cs_len) =
820 get_cs_params_len::<Projective, GVar, Projective2, GVar2, CubicFCircuit<Fr>>(
821 &poseidon_config,
822 F_circuit,
823 )
824 .unwrap();
825 let (kzg_pk, _): (KZGProverKey<Projective>, KZGVerifierKey<Bn254>) =
826 KZG::<Bn254>::setup(&mut rng, cs_len).unwrap();
827 let (pedersen_params, _) = Pedersen::<Projective>::setup(&mut rng, cs_len).unwrap();
828 let (cf_pedersen_params, _) = Pedersen::<Projective2>::setup(&mut rng, cf_cs_len).unwrap();
829
830 // run the test using Pedersen commitments on both sides of the curve cycle
831 test_ivc_opt::<Pedersen<Projective>, Pedersen<Projective2>>(
832 poseidon_config.clone(),
833 pedersen_params,
834 cf_pedersen_params.clone(),
835 F_circuit,
836 );
837 // run the test using KZG for the commitments on the main curve, and Pedersen for the
838 // commitments on the secondary curve
839 test_ivc_opt::<KZG<Bn254>, Pedersen<Projective2>>(
840 poseidon_config,
841 kzg_pk,
842 cf_pedersen_params,
843 F_circuit,
844 );
845 }
846
847 // test_ivc allowing to choose the CommitmentSchemes
848 fn test_ivc_opt<CS1: CommitmentScheme<Projective>, CS2: CommitmentScheme<Projective2>>(
849 poseidon_config: PoseidonConfig<Fr>,
850 cs_params: CS1::ProverParams,
851 cf_cs_params: CS2::ProverParams,
852 F_circuit: CubicFCircuit<Fr>,
853 ) {
854 type NOVA<CS1, CS2> =
855 Nova<Projective, GVar, Projective2, GVar2, CubicFCircuit<Fr>, CS1, CS2>;
856
857 let prover_params = ProverParams::<Projective, Projective2, CS1, CS2> {
858 poseidon_config: poseidon_config.clone(),
859 cs_params,
860 cf_cs_params,
861 };
862
863 let z_0 = vec![Fr::from(3_u32)];
864 let mut nova = NOVA::init(&prover_params, F_circuit, z_0.clone()).unwrap();
865
866 let num_steps: usize = 3;
867 for _ in 0..num_steps {
868 nova.prove_step().unwrap();
869 }
870 assert_eq!(Fr::from(num_steps as u32), nova.i);
871
872 let verifier_params = VerifierParams::<Projective, Projective2> {
873 poseidon_config,
874 r1cs: nova.clone().r1cs,
875 cf_r1cs: nova.clone().cf_r1cs,
876 };
877 let (running_instance, incoming_instance, cyclefold_instance) = nova.instances();
878 NOVA::<CS1, CS2>::verify(
879 verifier_params,
880 z_0,
881 nova.z_i,
882 nova.i,
883 running_instance,
884 incoming_instance,
885 cyclefold_instance,
886 )
887 .unwrap();
888 }
889}