arnaucube
arnaucube/sonobePublic Self-hosted repository
sonobe/folding-schemes/src/folding/circuits/cyclefold.rs
folding-schemes/src/folding/circuits/cyclefold.rsRaw
  1/// Contains [CycleFold](https://eprint.iacr.org/2023/1192.pdf) related circuits and functions that
  2/// are shared across the different folding schemes
  3use ark_crypto_primitives::sponge::{Absorb, CryptographicSponge};
  4use ark_ec::{AffineRepr, CurveGroup, Group};
  5use ark_ff::{BigInteger, Field, PrimeField};
  6use ark_r1cs_std::{
  7    alloc::{AllocVar, AllocationMode},
  8    boolean::Boolean,
  9    eq::EqGadget,
 10    fields::fp::FpVar,
 11    groups::GroupOpsBounds,
 12    prelude::CurveVar,
 13    ToConstraintFieldGadget,
 14};
 15use ark_relations::r1cs::{
 16    ConstraintSynthesizer, ConstraintSystem, ConstraintSystemRef, Namespace, SynthesisError,
 17};
 18use ark_std::fmt::Debug;
 19use ark_std::rand::RngCore;
 20use ark_std::Zero;
 21use core::{borrow::Borrow, marker::PhantomData};
 22
 23use super::{nonnative::uint::NonNativeUintVar, CF1, CF2};
 24use crate::arith::r1cs::{extract_w_x, R1CS};
 25use crate::commitment::CommitmentScheme;
 26use crate::constants::NOVA_N_BITS_RO;
 27use crate::folding::nova::nifs::NIFS;
 28use crate::transcript::{AbsorbNonNative, AbsorbNonNativeGadget, Transcript, TranscriptVar};
 29use crate::Error;
 30
 31/// Re-export the Nova committed instance as `CycleFoldCommittedInstance` and
 32/// witness as `CycleFoldWitness`, for clarity and consistency
 33pub use crate::folding::nova::{
 34    CommittedInstance as CycleFoldCommittedInstance, Witness as CycleFoldWitness,
 35};
 36
 37/// CycleFoldCommittedInstanceVar is the CycleFold CommittedInstance represented
 38/// in folding verifier circuit
 39#[derive(Debug, Clone)]
 40pub struct CycleFoldCommittedInstanceVar<C: CurveGroup, GC: CurveVar<C, CF2<C>>>
 41where
 42    for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
 43{
 44    pub cmE: GC,
 45    pub u: NonNativeUintVar<CF2<C>>,
 46    pub cmW: GC,
 47    pub x: Vec<NonNativeUintVar<CF2<C>>>,
 48}
 49impl<C, GC> AllocVar<CycleFoldCommittedInstance<C>, CF2<C>> for CycleFoldCommittedInstanceVar<C, GC>
 50where
 51    C: CurveGroup,
 52    GC: CurveVar<C, CF2<C>>,
 53    <C as ark_ec::CurveGroup>::BaseField: ark_ff::PrimeField,
 54    for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
 55{
 56    fn new_variable<T: Borrow<CycleFoldCommittedInstance<C>>>(
 57        cs: impl Into<Namespace<CF2<C>>>,
 58        f: impl FnOnce() -> Result<T, SynthesisError>,
 59        mode: AllocationMode,
 60    ) -> Result<Self, SynthesisError> {
 61        f().and_then(|val| {
 62            let cs = cs.into();
 63
 64            let cmE = GC::new_variable(cs.clone(), || Ok(val.borrow().cmE), mode)?;
 65            let cmW = GC::new_variable(cs.clone(), || Ok(val.borrow().cmW), mode)?;
 66            let u = NonNativeUintVar::new_variable(cs.clone(), || Ok(val.borrow().u), mode)?;
 67            let x = Vec::new_variable(cs.clone(), || Ok(val.borrow().x.clone()), mode)?;
 68
 69            Ok(Self { cmE, u, cmW, x })
 70        })
 71    }
 72}
 73
 74impl<C: CurveGroup> AbsorbNonNative<C::BaseField> for CycleFoldCommittedInstance<C>
 75where
 76    C::BaseField: PrimeField + Absorb,
 77{
 78    // Compatible with the in-circuit `CycleFoldCommittedInstanceVar::to_native_sponge_field_elements`
 79    fn to_native_sponge_field_elements(&self, dest: &mut Vec<C::BaseField>) {
 80        [self.u].to_native_sponge_field_elements(dest);
 81        self.x.to_native_sponge_field_elements(dest);
 82        let (cmE_x, cmE_y) = match self.cmE.into_affine().xy() {
 83            Some((&x, &y)) => (x, y),
 84            None => (C::BaseField::zero(), C::BaseField::zero()),
 85        };
 86        let (cmW_x, cmW_y) = match self.cmW.into_affine().xy() {
 87            Some((&x, &y)) => (x, y),
 88            None => (C::BaseField::zero(), C::BaseField::zero()),
 89        };
 90        cmE_x.to_sponge_field_elements(dest);
 91        cmE_y.to_sponge_field_elements(dest);
 92        cmW_x.to_sponge_field_elements(dest);
 93        cmW_y.to_sponge_field_elements(dest);
 94    }
 95}
 96
 97impl<C, GC> AbsorbNonNativeGadget<C::BaseField> for CycleFoldCommittedInstanceVar<C, GC>
 98where
 99    C: CurveGroup,
100    GC: CurveVar<C, CF2<C>> + ToConstraintFieldGadget<CF2<C>>,
101    <C as ark_ec::CurveGroup>::BaseField: ark_ff::PrimeField + Absorb,
102    for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
103{
104    /// Extracts the underlying field elements from `CycleFoldCommittedInstanceVar`, in the order
105    /// of `u`, `x`, `cmE.x`, `cmE.y`, `cmW.x`, `cmW.y`, `cmE.is_inf || cmW.is_inf` (|| is for
106    /// concat).
107    fn to_native_sponge_field_elements(&self) -> Result<Vec<FpVar<CF2<C>>>, SynthesisError> {
108        let mut cmE_elems = self.cmE.to_constraint_field()?;
109        let mut cmW_elems = self.cmW.to_constraint_field()?;
110
111        // See `transcript/poseidon.rs: TranscriptVar::absorb_point` for details
112        // why the last element is unnecessary.
113        cmE_elems.pop();
114        cmW_elems.pop();
115
116        Ok([
117            self.u.to_native_sponge_field_elements()?,
118            self.x
119                .iter()
120                .map(|i| i.to_native_sponge_field_elements())
121                .collect::<Result<Vec<_>, _>>()?
122                .concat(),
123            cmE_elems,
124            cmW_elems,
125        ]
126        .concat())
127    }
128}
129
130impl<C: CurveGroup> CycleFoldCommittedInstance<C>
131where
132    <C as ark_ec::CurveGroup>::BaseField: ark_ff::PrimeField + Absorb,
133{
134    /// hash_cyclefold implements the committed instance hash compatible with the
135    /// in-circuit implementation `CycleFoldCommittedInstanceVar::hash`.
136    /// Returns `H(U_i)`, where `U_i` is a `CycleFoldCommittedInstance`.
137    pub fn hash_cyclefold<T: Transcript<C::BaseField>>(
138        &self,
139        sponge: &T,
140        pp_hash: C::BaseField, // public params hash
141    ) -> C::BaseField {
142        let mut sponge = sponge.clone();
143        sponge.absorb(&pp_hash);
144        sponge.absorb_nonnative(self);
145        sponge.squeeze_field_elements(1)[0]
146    }
147}
148
149impl<C, GC> CycleFoldCommittedInstanceVar<C, GC>
150where
151    C: CurveGroup,
152    GC: CurveVar<C, CF2<C>> + ToConstraintFieldGadget<CF2<C>>,
153    <C as ark_ec::CurveGroup>::BaseField: ark_ff::PrimeField + Absorb,
154    for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
155{
156    /// hash implements the committed instance hash compatible with the native
157    /// implementation `CycleFoldCommittedInstance::hash_cyclefold`.
158    /// Returns `H(U_i)`, where `U` is a `CycleFoldCommittedInstanceVar`.
159    ///
160    /// Additionally it returns the vector of the field elements from the self
161    /// parameters, so they can be reused in other gadgets without recalculating
162    /// (reconstraining) them.
163    #[allow(clippy::type_complexity)]
164    pub fn hash<S: CryptographicSponge, T: TranscriptVar<CF2<C>, S>>(
165        self,
166        sponge: &T,
167        pp_hash: FpVar<CF2<C>>, // public params hash
168    ) -> Result<(FpVar<CF2<C>>, Vec<FpVar<CF2<C>>>), SynthesisError> {
169        let mut sponge = sponge.clone();
170        let U_vec = self.to_native_sponge_field_elements()?;
171        sponge.absorb(&pp_hash)?;
172        sponge.absorb(&U_vec)?;
173        Ok((sponge.squeeze_field_elements(1)?.pop().unwrap(), U_vec))
174    }
175}
176
177/// CommittedInstanceInCycleFoldVar represents the Nova CommittedInstance in the CycleFold circuit,
178/// where the commitments to E and W (cmW and cmW) from the CommittedInstance on the E2,
179/// represented as native points, which are folded on the auxiliary curve constraints field (E2::Fr
180/// = E1::Fq).
181#[derive(Debug, Clone)]
182pub struct CommittedInstanceInCycleFoldVar<C: CurveGroup, GC: CurveVar<C, CF2<C>>>
183where
184    for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
185{
186    _c: PhantomData<C>,
187    pub cmE: GC,
188    pub cmW: GC,
189}
190
191impl<C, GC> AllocVar<CycleFoldCommittedInstance<C>, CF2<C>>
192    for CommittedInstanceInCycleFoldVar<C, GC>
193where
194    C: CurveGroup,
195    GC: CurveVar<C, CF2<C>>,
196    for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
197{
198    fn new_variable<T: Borrow<CycleFoldCommittedInstance<C>>>(
199        cs: impl Into<Namespace<CF2<C>>>,
200        f: impl FnOnce() -> Result<T, SynthesisError>,
201        mode: AllocationMode,
202    ) -> Result<Self, SynthesisError> {
203        f().and_then(|val| {
204            let cs = cs.into();
205
206            let cmE = GC::new_variable(cs.clone(), || Ok(val.borrow().cmE), mode)?;
207            let cmW = GC::new_variable(cs.clone(), || Ok(val.borrow().cmW), mode)?;
208
209            Ok(Self {
210                _c: PhantomData,
211                cmE,
212                cmW,
213            })
214        })
215    }
216}
217
218/// In-circuit representation of the Witness associated to the CommittedInstance, but with
219/// non-native representation, since it is used to represent the CycleFold witness. This struct is
220/// used in the Decider circuit.
221#[derive(Debug, Clone)]
222pub struct CycleFoldWitnessVar<C: CurveGroup> {
223    pub E: Vec<NonNativeUintVar<CF2<C>>>,
224    pub rE: NonNativeUintVar<CF2<C>>,
225    pub W: Vec<NonNativeUintVar<CF2<C>>>,
226    pub rW: NonNativeUintVar<CF2<C>>,
227}
228
229impl<C> AllocVar<CycleFoldWitness<C>, CF2<C>> for CycleFoldWitnessVar<C>
230where
231    C: CurveGroup,
232    <C as ark_ec::CurveGroup>::BaseField: PrimeField,
233{
234    fn new_variable<T: Borrow<CycleFoldWitness<C>>>(
235        cs: impl Into<Namespace<CF2<C>>>,
236        f: impl FnOnce() -> Result<T, SynthesisError>,
237        mode: AllocationMode,
238    ) -> Result<Self, SynthesisError> {
239        f().and_then(|val| {
240            let cs = cs.into();
241
242            let E = Vec::new_variable(cs.clone(), || Ok(val.borrow().E.clone()), mode)?;
243            let rE = NonNativeUintVar::new_variable(cs.clone(), || Ok(val.borrow().rE), mode)?;
244
245            let W = Vec::new_variable(cs.clone(), || Ok(val.borrow().W.clone()), mode)?;
246            let rW = NonNativeUintVar::new_variable(cs.clone(), || Ok(val.borrow().rW), mode)?;
247
248            Ok(Self { E, rE, W, rW })
249        })
250    }
251}
252
253/// This is the gadget used in the AugmentedFCircuit to verify the CycleFold instances folding,
254/// which checks the correct RLC of u,x,cmE,cmW (hence the name containing 'Full', since it checks
255/// all the RLC values, not only the native ones). It assumes that ci2.cmE=0, ci2.u=1.
256pub struct NIFSFullGadget<C: CurveGroup, GC: CurveVar<C, CF2<C>>> {
257    _c: PhantomData<C>,
258    _gc: PhantomData<GC>,
259}
260
261impl<C: CurveGroup, GC: CurveVar<C, CF2<C>>> NIFSFullGadget<C, GC>
262where
263    C: CurveGroup,
264    GC: CurveVar<C, CF2<C>>,
265    <C as ark_ec::CurveGroup>::BaseField: ark_ff::PrimeField,
266    for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
267{
268    pub fn fold_committed_instance(
269        r_bits: Vec<Boolean<CF2<C>>>,
270        cmT: GC,
271        ci1: CycleFoldCommittedInstanceVar<C, GC>,
272        // ci2 is assumed to be always with cmE=0, u=1 (checks done previous to this method)
273        ci2: CycleFoldCommittedInstanceVar<C, GC>,
274    ) -> Result<CycleFoldCommittedInstanceVar<C, GC>, SynthesisError> {
275        // r_nonnat is equal to r_bits just that in a different format
276        let r_nonnat = {
277            let mut bits = r_bits.clone();
278            bits.resize(CF1::<C>::MODULUS_BIT_SIZE as usize, Boolean::FALSE);
279            NonNativeUintVar::from(&bits)
280        };
281        Ok(CycleFoldCommittedInstanceVar {
282            cmE: cmT.scalar_mul_le(r_bits.iter())? + ci1.cmE,
283            cmW: ci1.cmW + ci2.cmW.scalar_mul_le(r_bits.iter())?,
284            u: ci1.u.add_no_align(&r_nonnat).modulo::<CF1<C>>()?,
285            x: ci1
286                .x
287                .iter()
288                .zip(ci2.x)
289                .map(|(a, b)| {
290                    a.add_no_align(&r_nonnat.mul_no_align(&b)?)
291                        .modulo::<CF1<C>>()
292                })
293                .collect::<Result<Vec<_>, _>>()?,
294        })
295    }
296
297    pub fn verify(
298        // assumes that r_bits is equal to r_nonnat just that in a different format
299        r_bits: Vec<Boolean<CF2<C>>>,
300        cmT: GC,
301        ci1: CycleFoldCommittedInstanceVar<C, GC>,
302        // ci2 is assumed to be always with cmE=0, u=1 (checks done previous to this method)
303        ci2: CycleFoldCommittedInstanceVar<C, GC>,
304        ci3: CycleFoldCommittedInstanceVar<C, GC>,
305    ) -> Result<(), SynthesisError> {
306        let ci = Self::fold_committed_instance(r_bits, cmT, ci1, ci2)?;
307
308        ci.cmE.enforce_equal(&ci3.cmE)?;
309        ci.u.enforce_equal_unaligned(&ci3.u)?;
310        ci.cmW.enforce_equal(&ci3.cmW)?;
311        for (x, y) in ci.x.iter().zip(ci3.x.iter()) {
312            x.enforce_equal_unaligned(y)?;
313        }
314
315        Ok(())
316    }
317}
318
319/// CycleFoldChallengeGadget computes the RO challenge used for the CycleFold instances NIFS, it contains a
320/// rust-native and a in-circuit compatible versions.
321pub struct CycleFoldChallengeGadget<C: CurveGroup, GC: CurveVar<C, CF2<C>>> {
322    _c: PhantomData<C>, // Nova's Curve2, the one used for the CycleFold circuit
323    _gc: PhantomData<GC>,
324}
325impl<C, GC> CycleFoldChallengeGadget<C, GC>
326where
327    C: CurveGroup,
328    GC: CurveVar<C, CF2<C>> + ToConstraintFieldGadget<CF2<C>>,
329    <C as CurveGroup>::BaseField: PrimeField,
330    <C as CurveGroup>::BaseField: Absorb,
331    for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
332{
333    pub fn get_challenge_native<T: Transcript<C::BaseField>>(
334        transcript: &mut T,
335        pp_hash: C::BaseField, // public params hash
336        U_i: CycleFoldCommittedInstance<C>,
337        u_i: CycleFoldCommittedInstance<C>,
338        cmT: C,
339    ) -> Vec<bool> {
340        transcript.absorb(&pp_hash);
341        transcript.absorb_nonnative(&U_i);
342        transcript.absorb_nonnative(&u_i);
343        transcript.absorb_point(&cmT);
344        transcript.squeeze_bits(NOVA_N_BITS_RO)
345    }
346
347    // compatible with the native get_challenge_native
348    pub fn get_challenge_gadget<S: CryptographicSponge, T: TranscriptVar<C::BaseField, S>>(
349        transcript: &mut T,
350        pp_hash: FpVar<C::BaseField>, // public params hash
351        U_i_vec: Vec<FpVar<C::BaseField>>,
352        u_i: CycleFoldCommittedInstanceVar<C, GC>,
353        cmT: GC,
354    ) -> Result<Vec<Boolean<C::BaseField>>, SynthesisError> {
355        transcript.absorb(&pp_hash)?;
356        transcript.absorb(&U_i_vec)?;
357        transcript.absorb_nonnative(&u_i)?;
358        transcript.absorb_point(&cmT)?;
359        transcript.squeeze_bits(NOVA_N_BITS_RO)
360    }
361}
362
363pub trait CycleFoldConfig {
364    /// `N_INPUT_POINTS` specifies the number of input points that are folded in
365    /// [`CycleFoldCircuit`] via random linear combinations.
366    const N_INPUT_POINTS: usize;
367    /// `RANDOMNESS_BIT_LENGTH` is the (maximum) bit length of randomness `r`.
368    const RANDOMNESS_BIT_LENGTH: usize;
369    /// `FIELD_CAPACITY` is the maximum number of bits that can be stored in a
370    /// field element.
371    ///
372    /// E.g., given a randomness `r` with `RANDOMNESS_BIT_LENGTH` bits, we need
373    /// `RANDOMNESS_BIT_LENGTH / FIELD_CAPACITY` field elements to represent `r`
374    /// compactly in-circuit.
375    const FIELD_CAPACITY: usize = CF2::<Self::C>::MODULUS_BIT_SIZE as usize - 1;
376
377    /// Public inputs length for the CycleFoldCircuit.
378    /// * For Nova this is: `|[r, p1.x,y, p2.x,y, p3.x,y]|`
379    /// * In general, `|[r, (p_i.x,y)*n_points, p_folded.x,y]|`.
380    ///
381    /// Thus, `IO_LEN` is:
382    /// `RANDOMNESS_BIT_LENGTH / FIELD_CAPACITY  + 2 * N_INPUT_POINTS + 2`
383    const IO_LEN: usize = {
384        Self::RANDOMNESS_BIT_LENGTH.div_ceil(Self::FIELD_CAPACITY) + 2 * Self::N_INPUT_POINTS + 2
385    };
386
387    type F: Field;
388    type C: CurveGroup<BaseField = Self::F>;
389}
390
391/// CycleFoldCircuit contains the constraints that check the correct fold of the committed
392/// instances from Curve1. Namely, it checks the random linear combinations of the elliptic curve
393/// (Curve1) points of u_i, U_i leading to U_{i+1}
394#[derive(Debug, Clone)]
395pub struct CycleFoldCircuit<CFG: CycleFoldConfig, GC: CurveVar<CFG::C, CFG::F>> {
396    pub _gc: PhantomData<GC>,
397    /// r_bits is the bit representation of the r whose powers are used in the
398    /// random-linear-combination inside the CycleFoldCircuit
399    pub r_bits: Option<Vec<bool>>,
400    /// points to be folded in the CycleFoldCircuit
401    pub points: Option<Vec<CFG::C>>,
402    /// public inputs (cf_u_{i+1}.x)
403    pub x: Option<Vec<CFG::F>>,
404}
405
406impl<CFG: CycleFoldConfig, GC: CurveVar<CFG::C, CFG::F>> CycleFoldCircuit<CFG, GC> {
407    /// n_points indicates the number of points being folded in the CycleFoldCircuit
408    pub fn empty() -> Self {
409        Self {
410            _gc: PhantomData,
411            r_bits: None,
412            points: None,
413            x: None,
414        }
415    }
416}
417
418impl<CFG: CycleFoldConfig, GC: CurveVar<CFG::C, CFG::F>> ConstraintSynthesizer<CFG::F>
419    for CycleFoldCircuit<CFG, GC>
420where
421    GC: ToConstraintFieldGadget<CFG::F>,
422    CFG::F: PrimeField,
423    for<'a> &'a GC: GroupOpsBounds<'a, CFG::C, GC>,
424{
425    fn generate_constraints(self, cs: ConstraintSystemRef<CFG::F>) -> Result<(), SynthesisError> {
426        let r_bits = Vec::<Boolean<CFG::F>>::new_witness(cs.clone(), || {
427            Ok(self
428                .r_bits
429                .unwrap_or(vec![false; CFG::RANDOMNESS_BIT_LENGTH]))
430        })?;
431        let points = Vec::<GC>::new_witness(cs.clone(), || {
432            Ok(self
433                .points
434                .unwrap_or(vec![CFG::C::zero(); CFG::N_INPUT_POINTS]))
435        })?;
436
437        #[cfg(test)]
438        {
439            assert_eq!(CFG::N_INPUT_POINTS, points.len());
440            assert_eq!(CFG::RANDOMNESS_BIT_LENGTH, r_bits.len());
441        }
442
443        // Fold the original points of the instances natively in CycleFold.
444        // In Nova,
445        // - for the cmW we're computing: U_i1.cmW = U_i.cmW + r * u_i.cmW
446        // - for the cmE we're computing: U_i1.cmE = U_i.cmE + r * cmT + r^2 * u_i.cmE, where u_i.cmE
447        // is assumed to be 0, so, U_i1.cmE = U_i.cmE + r * cmT
448        // We want to compute
449        // P_folded = p_0 + r * P_1 + r^2 * P_2 + r^3 * P_3 + ... + r^{n-2} * P_{n-2} + r^{n-1} * P_{n-1}
450        // so in order to do it more efficiently (less constraints) we do
451        // P_folded = (((P_{n-1} * r + P_{n-2}) * r + P_{n-3})... ) * r + P_0
452        let mut p_folded: GC = points[CFG::N_INPUT_POINTS - 1].clone();
453        for i in (0..CFG::N_INPUT_POINTS - 1).rev() {
454            p_folded = p_folded.scalar_mul_le(r_bits.iter())? + points[i].clone();
455        }
456
457        let x = Vec::<FpVar<CFG::F>>::new_input(cs.clone(), || {
458            Ok(self.x.unwrap_or(vec![CFG::F::zero(); CFG::IO_LEN]))
459        })?;
460        #[cfg(test)]
461        assert_eq!(x.len(), CFG::IO_LEN); // non-constrained sanity check
462
463        // Check that the points coordinates are placed as the public input x:
464        // In Nova, this is: x == [r, p1, p2, p3] (wheere p3 is the p_folded).
465        // In multifolding schemes such as HyperNova, this is:
466        // computed_x = [r, p_0, p_1, p_2, ..., p_n, p_folded],
467        // where each p_i is in fact p_i.to_constraint_field()
468        let r_fp = Boolean::le_bits_to_fp_var(&r_bits)?;
469        let points_aux: Vec<FpVar<CFG::F>> = points
470            .iter()
471            .map(|p_i| Ok(p_i.to_constraint_field()?[..2].to_vec()))
472            .collect::<Result<Vec<_>, SynthesisError>>()?
473            .into_iter()
474            .flatten()
475            .collect();
476
477        let computed_x: Vec<FpVar<CFG::F>> = [
478            vec![r_fp],
479            points_aux,
480            p_folded.to_constraint_field()?[..2].to_vec(),
481        ]
482        .concat();
483        computed_x.enforce_equal(&x)?;
484
485        Ok(())
486    }
487}
488
489/// Folds the given cyclefold circuit and its instances. This method is abstracted from any folding
490/// scheme struct because it is used both by Nova & HyperNova's CycleFold.
491#[allow(clippy::type_complexity)]
492#[allow(clippy::too_many_arguments)]
493pub fn fold_cyclefold_circuit<CFG, C1, GC1, C2, GC2, CS2, const H: bool>(
494    transcript: &mut impl Transcript<C1::ScalarField>,
495    cf_r1cs: R1CS<C2::ScalarField>,
496    cf_cs_params: CS2::ProverParams,
497    pp_hash: C1::ScalarField,               // public params hash
498    cf_W_i: CycleFoldWitness<C2>,           // witness of the running instance
499    cf_U_i: CycleFoldCommittedInstance<C2>, // running instance
500    cf_u_i_x: Vec<C2::ScalarField>,
501    cf_circuit: CycleFoldCircuit<CFG, GC1>,
502    mut rng: impl RngCore,
503) -> Result<
504    (
505        CycleFoldWitness<C2>,
506        CycleFoldCommittedInstance<C2>, // u_i
507        CycleFoldWitness<C2>,           // W_i1
508        CycleFoldCommittedInstance<C2>, // U_i1
509        C2,                             // cmT
510        C2::ScalarField,                // r_Fq
511    ),
512    Error,
513>
514where
515    CFG: CycleFoldConfig<C = C1, F = CF2<C1>>,
516    C1: CurveGroup,
517    GC1: CurveVar<C1, CF2<C1>> + ToConstraintFieldGadget<CF2<C1>>,
518    C2: CurveGroup,
519    GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
520    CS2: CommitmentScheme<C2, H>,
521    <C1 as CurveGroup>::BaseField: PrimeField,
522    <C2 as CurveGroup>::BaseField: PrimeField,
523    <C1 as Group>::ScalarField: Absorb,
524    <C2 as Group>::ScalarField: Absorb,
525    C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
526    for<'a> &'a GC1: GroupOpsBounds<'a, C1, GC1>,
527    for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
528{
529    let cs2 = ConstraintSystem::<C1::BaseField>::new_ref();
530    cf_circuit.generate_constraints(cs2.clone())?;
531
532    let cs2 = cs2.into_inner().ok_or(Error::NoInnerConstraintSystem)?;
533    let (cf_w_i, cf_x_i) = extract_w_x::<C1::BaseField>(&cs2);
534    if cf_x_i != cf_u_i_x {
535        return Err(Error::NotEqual);
536    }
537
538    #[cfg(test)]
539    assert_eq!(cf_x_i.len(), CFG::IO_LEN);
540
541    // fold cyclefold instances
542    let cf_w_i = CycleFoldWitness::<C2>::new::<H>(cf_w_i.clone(), cf_r1cs.A.n_rows, &mut rng);
543    let cf_u_i: CycleFoldCommittedInstance<C2> =
544        cf_w_i.commit::<CS2, H>(&cf_cs_params, cf_x_i.clone())?;
545
546    // compute T* and cmT* for CycleFoldCircuit
547    let (cf_T, cf_cmT) = NIFS::<C2, CS2, H>::compute_cyclefold_cmT(
548        &cf_cs_params,
549        &cf_r1cs,
550        &cf_w_i,
551        &cf_u_i,
552        &cf_W_i,
553        &cf_U_i,
554    )?;
555
556    let cf_r_bits = CycleFoldChallengeGadget::<C2, GC2>::get_challenge_native(
557        transcript,
558        pp_hash,
559        cf_U_i.clone(),
560        cf_u_i.clone(),
561        cf_cmT,
562    );
563    let cf_r_Fq = C1::BaseField::from_bigint(BigInteger::from_bits_le(&cf_r_bits))
564        .expect("cf_r_bits out of bounds");
565
566    let (cf_W_i1, cf_U_i1) = NIFS::<C2, CS2, H>::fold_instances(
567        cf_r_Fq, &cf_W_i, &cf_U_i, &cf_w_i, &cf_u_i, &cf_T, cf_cmT,
568    )?;
569    Ok((cf_w_i, cf_u_i, cf_W_i1, cf_U_i1, cf_cmT, cf_r_Fq))
570}
571
572#[cfg(test)]
573pub mod tests {
574    use ark_bn254::{constraints::GVar, Fq, Fr, G1Projective as Projective};
575    use ark_crypto_primitives::sponge::{
576        constraints::CryptographicSpongeVar,
577        poseidon::{constraints::PoseidonSpongeVar, PoseidonSponge},
578    };
579    use ark_r1cs_std::R1CSVar;
580    use ark_std::UniformRand;
581
582    use super::*;
583    use crate::folding::nova::nifs::tests::prepare_simple_fold_inputs;
584    use crate::transcript::poseidon::poseidon_canonical_config;
585    use crate::utils::get_cm_coordinates;
586
587    struct TestCycleFoldConfig<C: CurveGroup, const N: usize> {
588        _c: PhantomData<C>,
589    }
590
591    impl<C: CurveGroup, const N: usize> CycleFoldConfig for TestCycleFoldConfig<C, N> {
592        const RANDOMNESS_BIT_LENGTH: usize = NOVA_N_BITS_RO;
593        const N_INPUT_POINTS: usize = N;
594        type C = C;
595        type F = C::BaseField;
596    }
597
598    #[test]
599    fn test_committed_instance_cyclefold_var() {
600        let mut rng = ark_std::test_rng();
601
602        let ci = CycleFoldCommittedInstance::<Projective> {
603            cmE: Projective::rand(&mut rng),
604            u: Fr::rand(&mut rng),
605            cmW: Projective::rand(&mut rng),
606            x: vec![Fr::rand(&mut rng); 1],
607        };
608
609        // check the instantiation of the CycleFold side:
610        let cs = ConstraintSystem::<Fq>::new_ref();
611        let ciVar =
612            CommittedInstanceInCycleFoldVar::<Projective, GVar>::new_witness(cs.clone(), || {
613                Ok(ci.clone())
614            })
615            .unwrap();
616        assert_eq!(ciVar.cmE.value().unwrap(), ci.cmE);
617        assert_eq!(ciVar.cmW.value().unwrap(), ci.cmW);
618    }
619
620    #[test]
621    fn test_CycleFoldCircuit_n_points_constraints() {
622        const n: usize = 16;
623        let mut rng = ark_std::test_rng();
624
625        // points to random-linear-combine
626        let points: Vec<Projective> = std::iter::repeat_with(|| Projective::rand(&mut rng))
627            .take(n)
628            .collect();
629
630        use std::ops::Mul;
631        let rho_raw = Fq::rand(&mut rng);
632        let rho_bits = rho_raw.into_bigint().to_bits_le()[..NOVA_N_BITS_RO].to_vec();
633        let rho_Fq = Fq::from_bigint(BigInteger::from_bits_le(&rho_bits)).unwrap();
634        let rho_Fr = Fr::from_bigint(BigInteger::from_bits_le(&rho_bits)).unwrap();
635        let mut res = Projective::zero();
636        use ark_std::One;
637        let mut rho_i = Fr::one();
638        for point_i in points.iter() {
639            res += point_i.mul(rho_i);
640            rho_i *= rho_Fr;
641        }
642
643        // cs is the Constraint System on the Curve Cycle auxiliary curve constraints field
644        // (E1::Fq=E2::Fr)
645        let cs = ConstraintSystem::<Fq>::new_ref();
646
647        let x: Vec<Fq> = [
648            vec![rho_Fq],
649            points.iter().flat_map(get_cm_coordinates).collect(),
650            get_cm_coordinates(&res),
651        ]
652        .concat();
653        let cf_circuit = CycleFoldCircuit::<TestCycleFoldConfig<Projective, n>, GVar> {
654            _gc: PhantomData,
655            r_bits: Some(rho_bits),
656            points: Some(points),
657            x: Some(x.clone()),
658        };
659        cf_circuit.generate_constraints(cs.clone()).unwrap();
660        assert!(cs.is_satisfied().unwrap());
661    }
662
663    #[test]
664    fn test_nifs_full_gadget() {
665        let (_, _, _, _, ci1, _, ci2, _, ci3, _, cmT, r_bits, _) = prepare_simple_fold_inputs();
666
667        let cs = ConstraintSystem::<Fq>::new_ref();
668
669        let r_bitsVar = Vec::<Boolean<Fq>>::new_witness(cs.clone(), || Ok(r_bits)).unwrap();
670
671        let ci1Var =
672            CycleFoldCommittedInstanceVar::<Projective, GVar>::new_witness(cs.clone(), || {
673                Ok(ci1.clone())
674            })
675            .unwrap();
676        let ci2Var =
677            CycleFoldCommittedInstanceVar::<Projective, GVar>::new_witness(cs.clone(), || {
678                Ok(ci2.clone())
679            })
680            .unwrap();
681        let ci3Var =
682            CycleFoldCommittedInstanceVar::<Projective, GVar>::new_witness(cs.clone(), || {
683                Ok(ci3.clone())
684            })
685            .unwrap();
686        let cmTVar = GVar::new_witness(cs.clone(), || Ok(cmT)).unwrap();
687
688        NIFSFullGadget::<Projective, GVar>::verify(r_bitsVar, cmTVar, ci1Var, ci2Var, ci3Var)
689            .unwrap();
690        assert!(cs.is_satisfied().unwrap());
691    }
692
693    #[test]
694    fn test_cyclefold_challenge_gadget() {
695        let mut rng = ark_std::test_rng();
696        let poseidon_config = poseidon_canonical_config::<Fq>();
697        let mut transcript = PoseidonSponge::<Fq>::new(&poseidon_config);
698
699        let u_i = CycleFoldCommittedInstance::<Projective> {
700            cmE: Projective::zero(), // zero on purpose, so we test also the zero point case
701            u: Fr::zero(),
702            cmW: Projective::rand(&mut rng),
703            x: std::iter::repeat_with(|| Fr::rand(&mut rng))
704                .take(TestCycleFoldConfig::<Projective, 2>::IO_LEN)
705                .collect(),
706        };
707        let U_i = CycleFoldCommittedInstance::<Projective> {
708            cmE: Projective::rand(&mut rng),
709            u: Fr::rand(&mut rng),
710            cmW: Projective::rand(&mut rng),
711            x: std::iter::repeat_with(|| Fr::rand(&mut rng))
712                .take(TestCycleFoldConfig::<Projective, 2>::IO_LEN)
713                .collect(),
714        };
715        let cmT = Projective::rand(&mut rng);
716
717        // compute the challenge natively
718        let pp_hash = Fq::from(42u32); // only for test
719        let r_bits = CycleFoldChallengeGadget::<Projective, GVar>::get_challenge_native(
720            &mut transcript,
721            pp_hash,
722            U_i.clone(),
723            u_i.clone(),
724            cmT,
725        );
726
727        let cs = ConstraintSystem::<Fq>::new_ref();
728        let u_iVar =
729            CycleFoldCommittedInstanceVar::<Projective, GVar>::new_witness(cs.clone(), || {
730                Ok(u_i.clone())
731            })
732            .unwrap();
733        let U_iVar =
734            CycleFoldCommittedInstanceVar::<Projective, GVar>::new_witness(cs.clone(), || {
735                Ok(U_i.clone())
736            })
737            .unwrap();
738        let cmTVar = GVar::new_witness(cs.clone(), || Ok(cmT)).unwrap();
739        let mut transcript_var =
740            PoseidonSpongeVar::<Fq>::new(ConstraintSystem::<Fq>::new_ref(), &poseidon_config);
741
742        let pp_hashVar = FpVar::<Fq>::new_witness(cs.clone(), || Ok(pp_hash)).unwrap();
743        let r_bitsVar = CycleFoldChallengeGadget::<Projective, GVar>::get_challenge_gadget(
744            &mut transcript_var,
745            pp_hashVar,
746            U_iVar.to_native_sponge_field_elements().unwrap(),
747            u_iVar,
748            cmTVar,
749        )
750        .unwrap();
751        assert!(cs.is_satisfied().unwrap());
752
753        // check that the natively computed and in-circuit computed hashes match
754        let rVar = Boolean::le_bits_to_fp_var(&r_bitsVar).unwrap();
755        let r = Fq::from_bigint(BigInteger::from_bits_le(&r_bits)).unwrap();
756        assert_eq!(rVar.value().unwrap(), r);
757        assert_eq!(r_bitsVar.value().unwrap(), r_bits);
758    }
759
760    #[test]
761    fn test_cyclefold_hash_gadget() {
762        let mut rng = ark_std::test_rng();
763        let poseidon_config = poseidon_canonical_config::<Fq>();
764        let sponge = PoseidonSponge::<Fq>::new(&poseidon_config);
765
766        let U_i = CycleFoldCommittedInstance::<Projective> {
767            cmE: Projective::rand(&mut rng),
768            u: Fr::rand(&mut rng),
769            cmW: Projective::rand(&mut rng),
770            x: std::iter::repeat_with(|| Fr::rand(&mut rng))
771                .take(TestCycleFoldConfig::<Projective, 2>::IO_LEN)
772                .collect(),
773        };
774        let pp_hash = Fq::from(42u32); // only for test
775        let h = U_i.hash_cyclefold(&sponge, pp_hash);
776
777        let cs = ConstraintSystem::<Fq>::new_ref();
778        let U_iVar =
779            CycleFoldCommittedInstanceVar::<Projective, GVar>::new_witness(cs.clone(), || {
780                Ok(U_i.clone())
781            })
782            .unwrap();
783        let pp_hashVar = FpVar::<Fq>::new_witness(cs.clone(), || Ok(pp_hash)).unwrap();
784        let (hVar, _) = U_iVar
785            .hash(
786                &PoseidonSpongeVar::new(cs.clone(), &poseidon_config),
787                pp_hashVar,
788            )
789            .unwrap();
790        hVar.enforce_equal(&FpVar::new_witness(cs.clone(), || Ok(h)).unwrap())
791            .unwrap();
792        assert!(cs.is_satisfied().unwrap());
793    }
794}