arnaucube
arnaucube/sonobePublic Self-hosted repository
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::CommitmentScheme;
 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<CS: CommitmentScheme<C>>(
119        &self,
120        params: &CS::ProverParams,
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 = CS::commit(params, &self.E, &self.rE)?;
126        }
127        let cmW = CS::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, CS1, CS2>
139where
140    C1: CurveGroup,
141    C2: CurveGroup,
142    CS1: CommitmentScheme<C1>,
143    CS2: CommitmentScheme<C2>,
144{
145    pub poseidon_config: PoseidonConfig<C1::ScalarField>,
146    pub cs_params: CS1::ProverParams,
147    pub cf_cs_params: CS2::ProverParams,
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, CS1, CS2>
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    CS1: CommitmentScheme<C1>,
168    CS2: CommitmentScheme<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    /// CommitmentScheme::ProverParams over C1
179    pub cs_params: CS1::ProverParams,
180    /// CycleFold CommitmentScheme::ProverParams, over C2
181    pub cf_cs_params: CS2::ProverParams,
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, CS1, CS2> FoldingScheme<C1, C2, FC>
201    for Nova<C1, GC1, C2, GC2, FC, CS1, CS2>
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    CS1: CommitmentScheme<C1>,
209    CS2: CommitmentScheme<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, CS1, CS2>;
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            cs_params: pp.cs_params.clone(),
274            cf_cs_params: pp.cf_cs_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, CS1>::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, CS1>::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        #[cfg(test)]
448        assert!(cs.is_satisfied().unwrap());
449
450        let cs = cs.into_inner().ok_or(Error::NoInnerConstraintSystem)?;
451        let (w_i1, x_i1) = extract_w_x::<C1::ScalarField>(&cs);
452        if x_i1[0] != u_i1_x {
453            return Err(Error::NotEqual);
454        }
455
456        #[cfg(test)]
457        if x_i1.len() != 1 {
458            return Err(Error::NotExpectedLength(x_i1.len(), 1));
459        }
460
461        // set values for next iteration
462        self.i += C1::ScalarField::one();
463        self.z_i = z_i1.clone();
464        self.w_i = Witness::<C1>::new(w_i1, self.r1cs.A.n_rows);
465        self.u_i = self.w_i.commit::<CS1>(&self.cs_params, vec![u_i1_x])?;
466        self.W_i = W_i1.clone();
467        self.U_i = U_i1.clone();
468
469        #[cfg(test)]
470        {
471            self.r1cs.check_instance_relation(&self.w_i, &self.u_i)?;
472            self.r1cs
473                .check_relaxed_instance_relation(&self.W_i, &self.U_i)?;
474        }
475
476        Ok(())
477    }
478
479    fn state(&self) -> Vec<C1::ScalarField> {
480        self.z_i.clone()
481    }
482    fn instances(
483        &self,
484    ) -> (
485        Self::CommittedInstanceWithWitness,
486        Self::CommittedInstanceWithWitness,
487        Self::CFCommittedInstanceWithWitness,
488    ) {
489        (
490            (self.U_i.clone(), self.W_i.clone()),
491            (self.u_i.clone(), self.w_i.clone()),
492            (self.cf_U_i.clone(), self.cf_W_i.clone()),
493        )
494    }
495
496    /// Implements IVC.V of Nova+CycleFold
497    fn verify(
498        vp: Self::VerifierParam,
499        z_0: Vec<C1::ScalarField>, // initial state
500        z_i: Vec<C1::ScalarField>, // last state
501        num_steps: C1::ScalarField,
502        running_instance: Self::CommittedInstanceWithWitness,
503        incoming_instance: Self::CommittedInstanceWithWitness,
504        cyclefold_instance: Self::CFCommittedInstanceWithWitness,
505    ) -> Result<(), Error> {
506        let (U_i, W_i) = running_instance;
507        let (u_i, w_i) = incoming_instance;
508        let (cf_U_i, cf_W_i) = cyclefold_instance;
509
510        if u_i.x.len() != 1 || U_i.x.len() != 1 {
511            return Err(Error::IVCVerificationFail);
512        }
513
514        // check that u_i's output points to the running instance
515        // u_i.X == H(i, z_0, z_i, U_i)
516        let expected_u_i_x = U_i.hash(&vp.poseidon_config, num_steps, z_0, z_i.clone())?;
517        if expected_u_i_x != u_i.x[0] {
518            return Err(Error::IVCVerificationFail);
519        }
520
521        // check u_i.cmE==0, u_i.u==1 (=u_i is a un-relaxed instance)
522        if !u_i.cmE.is_zero() || !u_i.u.is_one() {
523            return Err(Error::IVCVerificationFail);
524        }
525
526        // check R1CS satisfiability
527        vp.r1cs.check_instance_relation(&w_i, &u_i)?;
528        // check RelaxedR1CS satisfiability
529        vp.r1cs.check_relaxed_instance_relation(&W_i, &U_i)?;
530
531        // check CycleFold RelaxedR1CS satisfiability
532        vp.cf_r1cs
533            .check_relaxed_instance_relation(&cf_W_i, &cf_U_i)?;
534
535        Ok(())
536    }
537}
538
539impl<C1, GC1, C2, GC2, FC, CS1, CS2> Nova<C1, GC1, C2, GC2, FC, CS1, CS2>
540where
541    C1: CurveGroup,
542    GC1: CurveVar<C1, CF2<C1>>,
543    C2: CurveGroup,
544    GC2: CurveVar<C2, CF2<C2>>,
545    FC: FCircuit<C1::ScalarField>,
546    CS1: CommitmentScheme<C1>,
547    CS2: CommitmentScheme<C2>,
548    <C2 as CurveGroup>::BaseField: PrimeField,
549    <C1 as Group>::ScalarField: Absorb,
550    <C2 as Group>::ScalarField: Absorb,
551    C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
552{
553    // computes T and cmT for the AugmentedFCircuit
554    fn compute_cmT(&self) -> Result<(Vec<C1::ScalarField>, C1), Error> {
555        NIFS::<C1, CS1>::compute_cmT(
556            &self.cs_params,
557            &self.r1cs,
558            &self.w_i,
559            &self.u_i,
560            &self.W_i,
561            &self.U_i,
562        )
563    }
564    // computes T* and cmT* for the CycleFoldCircuit
565    fn compute_cf_cmT(
566        &self,
567        cf_w_i: &Witness<C2>,
568        cf_u_i: &CommittedInstance<C2>,
569        cf_W_i: &Witness<C2>,
570        cf_U_i: &CommittedInstance<C2>,
571    ) -> Result<(Vec<C2::ScalarField>, C2), Error> {
572        NIFS::<C2, CS2>::compute_cyclefold_cmT(
573            &self.cf_cs_params,
574            &self.cf_r1cs,
575            cf_w_i,
576            cf_u_i,
577            cf_W_i,
578            cf_U_i,
579        )
580    }
581}
582
583impl<C1, GC1, C2, GC2, FC, CS1, CS2> Nova<C1, GC1, C2, GC2, FC, CS1, CS2>
584where
585    C1: CurveGroup,
586    GC1: CurveVar<C1, CF2<C1>>,
587    C2: CurveGroup,
588    GC2: CurveVar<C2, CF2<C2>>,
589    FC: FCircuit<C1::ScalarField>,
590    CS1: CommitmentScheme<C1>,
591    CS2: CommitmentScheme<C2>,
592    <C1 as CurveGroup>::BaseField: PrimeField,
593    <C2 as CurveGroup>::BaseField: PrimeField,
594    <C1 as Group>::ScalarField: Absorb,
595    <C2 as Group>::ScalarField: Absorb,
596    C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
597    for<'a> &'a GC1: GroupOpsBounds<'a, C1, GC1>,
598    for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
599{
600    // folds the given cyclefold circuit and its instances
601    #[allow(clippy::type_complexity)]
602    fn fold_cyclefold_circuit(
603        &self,
604        cf_W_i: Witness<C2>,           // witness of the running instance
605        cf_U_i: CommittedInstance<C2>, // running instance
606        cf_u_i_x: Vec<C2::ScalarField>,
607        cf_circuit: CycleFoldCircuit<C1, GC1>,
608    ) -> Result<
609        (
610            Witness<C2>,
611            CommittedInstance<C2>, // u_i
612            Witness<C2>,           // W_i1
613            CommittedInstance<C2>, // U_i1
614            C2,                    // cmT
615            C2::ScalarField,       // r_Fq
616        ),
617        Error,
618    > {
619        let cs2 = ConstraintSystem::<C1::BaseField>::new_ref();
620        cf_circuit.generate_constraints(cs2.clone())?;
621
622        let cs2 = cs2.into_inner().ok_or(Error::NoInnerConstraintSystem)?;
623        let (cf_w_i, cf_x_i) = extract_w_x::<C1::BaseField>(&cs2);
624        if cf_x_i != cf_u_i_x {
625            return Err(Error::NotEqual);
626        }
627
628        #[cfg(test)]
629        if cf_x_i.len() != CF_IO_LEN {
630            return Err(Error::NotExpectedLength(cf_x_i.len(), CF_IO_LEN));
631        }
632
633        // fold cyclefold instances
634        let cf_w_i = Witness::<C2>::new(cf_w_i.clone(), self.cf_r1cs.A.n_rows);
635        let cf_u_i: CommittedInstance<C2> =
636            cf_w_i.commit::<CS2>(&self.cf_cs_params, cf_x_i.clone())?;
637
638        // compute T* and cmT* for CycleFoldCircuit
639        let (cf_T, cf_cmT) = self.compute_cf_cmT(&cf_w_i, &cf_u_i, &cf_W_i, &cf_U_i)?;
640
641        let cf_r_bits = CycleFoldChallengeGadget::<C2, GC2>::get_challenge_native(
642            &self.poseidon_config,
643            cf_U_i.clone(),
644            cf_u_i.clone(),
645            cf_cmT,
646        )?;
647        let cf_r_Fq = C1::BaseField::from_bigint(BigInteger::from_bits_le(&cf_r_bits))
648            .ok_or(Error::OutOfBounds)?;
649
650        let (cf_W_i1, cf_U_i1) = NIFS::<C2, CS2>::fold_instances(
651            cf_r_Fq, &cf_W_i, &cf_U_i, &cf_w_i, &cf_u_i, &cf_T, cf_cmT,
652        )?;
653        Ok((cf_w_i, cf_u_i, cf_W_i1, cf_U_i1, cf_cmT, cf_r_Fq))
654    }
655}
656
657/// helper method to get the r1cs from the ConstraintSynthesizer
658pub fn get_r1cs_from_cs<F: PrimeField>(
659    circuit: impl ConstraintSynthesizer<F>,
660) -> Result<R1CS<F>, Error> {
661    let cs = ConstraintSystem::<F>::new_ref();
662    circuit.generate_constraints(cs.clone())?;
663    cs.finalize();
664    let cs = cs.into_inner().ok_or(Error::NoInnerConstraintSystem)?;
665    let r1cs = extract_r1cs::<F>(&cs);
666    Ok(r1cs)
667}
668
669/// helper method to get the R1CS for both the AugmentedFCircuit and the CycleFold circuit
670#[allow(clippy::type_complexity)]
671pub fn get_r1cs<C1, GC1, C2, GC2, FC>(
672    poseidon_config: &PoseidonConfig<C1::ScalarField>,
673    F_circuit: FC,
674) -> Result<(R1CS<C1::ScalarField>, R1CS<C2::ScalarField>), Error>
675where
676    C1: CurveGroup,
677    GC1: CurveVar<C1, CF2<C1>>,
678    C2: CurveGroup,
679    GC2: CurveVar<C2, CF2<C2>>,
680    FC: FCircuit<C1::ScalarField>,
681    <C1 as CurveGroup>::BaseField: PrimeField,
682    <C2 as CurveGroup>::BaseField: PrimeField,
683    <C1 as Group>::ScalarField: Absorb,
684    <C2 as Group>::ScalarField: Absorb,
685    C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
686    for<'a> &'a GC1: GroupOpsBounds<'a, C1, GC1>,
687    for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
688{
689    let augmented_F_circuit =
690        AugmentedFCircuit::<C1, C2, GC2, FC>::empty(poseidon_config, F_circuit);
691    let cf_circuit = CycleFoldCircuit::<C1, GC1>::empty();
692    let r1cs = get_r1cs_from_cs::<C1::ScalarField>(augmented_F_circuit)?;
693    let cf_r1cs = get_r1cs_from_cs::<C2::ScalarField>(cf_circuit)?;
694    Ok((r1cs, cf_r1cs))
695}
696
697/// helper method to get the pedersen params length for both the AugmentedFCircuit and the
698/// CycleFold circuit
699pub fn get_cs_params_len<C1, GC1, C2, GC2, FC>(
700    poseidon_config: &PoseidonConfig<C1::ScalarField>,
701    F_circuit: FC,
702) -> Result<(usize, usize), Error>
703where
704    C1: CurveGroup,
705    GC1: CurveVar<C1, CF2<C1>>,
706    C2: CurveGroup,
707    GC2: CurveVar<C2, CF2<C2>>,
708    FC: FCircuit<C1::ScalarField>,
709    <C1 as CurveGroup>::BaseField: PrimeField,
710    <C2 as CurveGroup>::BaseField: PrimeField,
711    <C1 as Group>::ScalarField: Absorb,
712    <C2 as Group>::ScalarField: Absorb,
713    C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
714    for<'a> &'a GC1: GroupOpsBounds<'a, C1, GC1>,
715    for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
716{
717    let (r1cs, cf_r1cs) = get_r1cs::<C1, GC1, C2, GC2, FC>(poseidon_config, F_circuit)?;
718    Ok((r1cs.A.n_rows, cf_r1cs.A.n_rows))
719}
720
721/// returns the coordinates of a commitment point
722pub(crate) fn get_cm_coordinates<C: CurveGroup>(cm: &C) -> Vec<C::BaseField> {
723    let zero = (&C::BaseField::zero(), &C::BaseField::one());
724    let cm = cm.into_affine();
725    let (cm_x, cm_y) = cm.xy().unwrap_or(zero);
726    vec![*cm_x, *cm_y]
727}
728
729#[cfg(test)]
730pub mod tests {
731    use super::*;
732    use crate::commitment::kzg::{ProverKey as KZGProverKey, KZG};
733    use ark_bn254::{constraints::GVar, Bn254, Fr, G1Projective as Projective};
734    use ark_grumpkin::{constraints::GVar as GVar2, Projective as Projective2};
735    use ark_poly_commit::kzg10::VerifierKey as KZGVerifierKey;
736
737    use crate::commitment::pedersen::Pedersen;
738    use crate::frontend::tests::CubicFCircuit;
739    use crate::transcript::poseidon::poseidon_test_config;
740
741    /// This test tests the Nova+CycleFold IVC, and by consequence it is also testing the
742    /// AugmentedFCircuit
743    #[test]
744    fn test_ivc() {
745        let mut rng = ark_std::test_rng();
746        let poseidon_config = poseidon_test_config::<Fr>();
747
748        let F_circuit = CubicFCircuit::<Fr>::new(());
749
750        let (cs_len, cf_cs_len) =
751            get_cs_params_len::<Projective, GVar, Projective2, GVar2, CubicFCircuit<Fr>>(
752                &poseidon_config,
753                F_circuit,
754            )
755            .unwrap();
756        let (kzg_pk, _): (KZGProverKey<Projective>, KZGVerifierKey<Bn254>) =
757            KZG::<Bn254>::setup(&mut rng, cs_len).unwrap();
758        let (pedersen_params, _) = Pedersen::<Projective>::setup(&mut rng, cs_len).unwrap();
759        let (cf_pedersen_params, _) = Pedersen::<Projective2>::setup(&mut rng, cf_cs_len).unwrap();
760
761        // run the test using Pedersen commitments on both sides of the curve cycle
762        test_ivc_opt::<Pedersen<Projective>, Pedersen<Projective2>>(
763            poseidon_config.clone(),
764            pedersen_params,
765            cf_pedersen_params.clone(),
766            F_circuit,
767        );
768        // run the test using KZG for the commitments on the main curve, and Pedersen for the
769        // commitments on the secondary curve
770        test_ivc_opt::<KZG<Bn254>, Pedersen<Projective2>>(
771            poseidon_config,
772            kzg_pk,
773            cf_pedersen_params,
774            F_circuit,
775        );
776    }
777
778    // test_ivc allowing to choose the CommitmentSchemes
779    fn test_ivc_opt<CS1: CommitmentScheme<Projective>, CS2: CommitmentScheme<Projective2>>(
780        poseidon_config: PoseidonConfig<Fr>,
781        cs_params: CS1::ProverParams,
782        cf_cs_params: CS2::ProverParams,
783        F_circuit: CubicFCircuit<Fr>,
784    ) {
785        type NOVA<CS1, CS2> =
786            Nova<Projective, GVar, Projective2, GVar2, CubicFCircuit<Fr>, CS1, CS2>;
787
788        let prover_params = ProverParams::<Projective, Projective2, CS1, CS2> {
789            poseidon_config: poseidon_config.clone(),
790            cs_params,
791            cf_cs_params,
792        };
793
794        let z_0 = vec![Fr::from(3_u32)];
795        let mut nova = NOVA::init(&prover_params, F_circuit, z_0.clone()).unwrap();
796
797        let num_steps: usize = 3;
798        for _ in 0..num_steps {
799            nova.prove_step().unwrap();
800        }
801        assert_eq!(Fr::from(num_steps as u32), nova.i);
802
803        let verifier_params = VerifierParams::<Projective, Projective2> {
804            poseidon_config,
805            r1cs: nova.clone().r1cs,
806            cf_r1cs: nova.clone().cf_r1cs,
807        };
808        let (running_instance, incoming_instance, cyclefold_instance) = nova.instances();
809        NOVA::<CS1, CS2>::verify(
810            verifier_params,
811            z_0,
812            nova.z_i,
813            nova.i,
814            running_instance,
815            incoming_instance,
816            cyclefold_instance,
817        )
818        .unwrap();
819    }
820}