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