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