arnaucube
arnaucube/sonobePublic Self-hosted repository
sonobe/folding-schemes/src/folding/nova/circuits.rs
folding-schemes/src/folding/nova/circuits.rsRaw
  1/// contains [Nova](https://eprint.iacr.org/2021/370.pdf) related circuits
  2use ark_crypto_primitives::crh::{
  3    poseidon::constraints::{CRHGadget, CRHParametersVar},
  4    CRHSchemeGadget,
  5};
  6use ark_crypto_primitives::sponge::{
  7    constraints::CryptographicSpongeVar,
  8    poseidon::{constraints::PoseidonSpongeVar, PoseidonConfig, PoseidonSponge},
  9    Absorb, CryptographicSponge,
 10};
 11use ark_ec::{AffineRepr, CurveGroup, Group};
 12use ark_ff::{Field, PrimeField};
 13use ark_r1cs_std::{
 14    alloc::{AllocVar, AllocationMode},
 15    boolean::Boolean,
 16    eq::EqGadget,
 17    fields::{fp::FpVar, nonnative::NonNativeFieldVar, FieldVar},
 18    groups::GroupOpsBounds,
 19    prelude::CurveVar,
 20    ToBitsGadget, ToConstraintFieldGadget,
 21};
 22use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystemRef, Namespace, SynthesisError};
 23use ark_std::fmt::Debug;
 24use ark_std::{One, Zero};
 25use core::{borrow::Borrow, marker::PhantomData};
 26
 27use super::{
 28    cyclefold::{
 29        CycleFoldChallengeGadget, CycleFoldCommittedInstanceVar, NIFSFullGadget, CF_IO_LEN,
 30    },
 31    CommittedInstance,
 32};
 33use crate::constants::N_BITS_RO;
 34use crate::folding::circuits::nonnative::{point_to_nonnative_limbs, NonNativeAffineVar};
 35use crate::frontend::FCircuit;
 36
 37/// CF1 represents the ConstraintField used for the main Nova circuit which is over E1::Fr, where
 38/// E1 is the main curve where we do the folding.
 39pub type CF1<C> = <<C as CurveGroup>::Affine as AffineRepr>::ScalarField;
 40/// CF2 represents the ConstraintField used for the CycleFold circuit which is over E2::Fr=E1::Fq,
 41/// where E2 is the auxiliary curve (from [CycleFold](https://eprint.iacr.org/2023/1192.pdf)
 42/// approach) where we check the folding of the commitments (elliptic curve points).
 43pub type CF2<C> = <<C as CurveGroup>::BaseField as Field>::BasePrimeField;
 44
 45/// CommittedInstanceVar contains the u, x, cmE and cmW values which are folded on the main Nova
 46/// constraints field (E1::Fr, where E1 is the main curve). The peculiarity is that cmE and cmW are
 47/// represented non-natively over the constraint field.
 48#[derive(Debug, Clone)]
 49pub struct CommittedInstanceVar<C: CurveGroup>
 50where
 51    <C as ark_ec::CurveGroup>::BaseField: ark_ff::PrimeField,
 52{
 53    pub u: FpVar<C::ScalarField>,
 54    pub x: Vec<FpVar<C::ScalarField>>,
 55    pub cmE: NonNativeAffineVar<C>,
 56    pub cmW: NonNativeAffineVar<C>,
 57}
 58
 59impl<C> AllocVar<CommittedInstance<C>, CF1<C>> for CommittedInstanceVar<C>
 60where
 61    C: CurveGroup,
 62    <C as ark_ec::CurveGroup>::BaseField: PrimeField,
 63{
 64    fn new_variable<T: Borrow<CommittedInstance<C>>>(
 65        cs: impl Into<Namespace<CF1<C>>>,
 66        f: impl FnOnce() -> Result<T, SynthesisError>,
 67        mode: AllocationMode,
 68    ) -> Result<Self, SynthesisError> {
 69        f().and_then(|val| {
 70            let cs = cs.into();
 71
 72            let u = FpVar::<C::ScalarField>::new_variable(cs.clone(), || Ok(val.borrow().u), mode)?;
 73            let x: Vec<FpVar<C::ScalarField>> =
 74                Vec::new_variable(cs.clone(), || Ok(val.borrow().x.clone()), mode)?;
 75
 76            let cmE =
 77                NonNativeAffineVar::<C>::new_variable(cs.clone(), || Ok(val.borrow().cmE), mode)?;
 78            let cmW =
 79                NonNativeAffineVar::<C>::new_variable(cs.clone(), || Ok(val.borrow().cmW), mode)?;
 80
 81            Ok(Self { u, x, cmE, cmW })
 82        })
 83    }
 84}
 85
 86impl<C> CommittedInstanceVar<C>
 87where
 88    C: CurveGroup,
 89    <C as Group>::ScalarField: Absorb,
 90    <C as ark_ec::CurveGroup>::BaseField: ark_ff::PrimeField,
 91{
 92    /// hash implements the committed instance hash compatible with the native implementation from
 93    /// CommittedInstance.hash.
 94    /// Returns `H(i, z_0, z_i, U_i)`, where `i` can be `i` but also `i+1`, and `U` is the
 95    /// `CommittedInstance`.
 96    /// Additionally it returns the vector of the field elements from the self parameters, so they
 97    /// can be reused in other gadgets avoiding recalculating (reconstraining) them.
 98    #[allow(clippy::type_complexity)]
 99    pub fn hash(
100        self,
101        crh_params: &CRHParametersVar<CF1<C>>,
102        i: FpVar<CF1<C>>,
103        z_0: Vec<FpVar<CF1<C>>>,
104        z_i: Vec<FpVar<CF1<C>>>,
105    ) -> Result<(FpVar<CF1<C>>, Vec<FpVar<CF1<C>>>), SynthesisError> {
106        let U_vec = [
107            vec![self.u],
108            self.x,
109            self.cmE.x.to_constraint_field()?,
110            self.cmE.y.to_constraint_field()?,
111            self.cmW.x.to_constraint_field()?,
112            self.cmW.y.to_constraint_field()?,
113        ]
114        .concat();
115        let input = [vec![i], z_0, z_i, U_vec.clone()].concat();
116        Ok((
117            CRHGadget::<C::ScalarField>::evaluate(crh_params, &input)?,
118            U_vec,
119        ))
120    }
121}
122
123/// Implements the circuit that does the checks of the Non-Interactive Folding Scheme Verifier
124/// described in section 4 of [Nova](https://eprint.iacr.org/2021/370.pdf), where the cmE & cmW checks are
125/// delegated to the NIFSCycleFoldGadget.
126pub struct NIFSGadget<C: CurveGroup> {
127    _c: PhantomData<C>,
128}
129
130impl<C: CurveGroup> NIFSGadget<C>
131where
132    C: CurveGroup,
133    <C as ark_ec::CurveGroup>::BaseField: ark_ff::PrimeField,
134{
135    /// Implements the constraints for NIFS.V for u and x, since cm(E) and cm(W) are delegated to
136    /// the CycleFold circuit.
137    pub fn verify(
138        r: FpVar<CF1<C>>,
139        ci1: CommittedInstanceVar<C>, // U_i
140        ci2: CommittedInstanceVar<C>, // u_i
141        ci3: CommittedInstanceVar<C>, // U_{i+1}
142    ) -> Result<Boolean<CF1<C>>, SynthesisError> {
143        // ensure that: ci3.u == ci1.u + r * ci2.u
144        let first_check = ci3.u.is_eq(&(ci1.u + r.clone() * ci2.u))?;
145
146        // ensure that: ci3.x == ci1.x + r * ci2.x
147        let x_rlc = ci1
148            .x
149            .iter()
150            .zip(ci2.x)
151            .map(|(a, b)| a + &r * &b)
152            .collect::<Vec<FpVar<CF1<C>>>>();
153        let second_check = x_rlc.is_eq(&ci3.x)?;
154
155        first_check.and(&second_check)
156    }
157}
158
159/// ChallengeGadget computes the RO challenge used for the Nova instances NIFS, it contains a
160/// rust-native and a in-circuit compatible versions.
161pub struct ChallengeGadget<C: CurveGroup> {
162    _c: PhantomData<C>,
163}
164impl<C: CurveGroup> ChallengeGadget<C>
165where
166    C: CurveGroup,
167    <C as CurveGroup>::BaseField: PrimeField,
168    <C as Group>::ScalarField: Absorb,
169{
170    pub fn get_challenge_native(
171        poseidon_config: &PoseidonConfig<C::ScalarField>,
172        U_i: CommittedInstance<C>,
173        u_i: CommittedInstance<C>,
174        cmT: C,
175    ) -> Result<Vec<bool>, SynthesisError> {
176        let (U_cmE_x, U_cmE_y) = point_to_nonnative_limbs::<C>(U_i.cmE)?;
177        let (U_cmW_x, U_cmW_y) = point_to_nonnative_limbs::<C>(U_i.cmW)?;
178        let (u_cmE_x, u_cmE_y) = point_to_nonnative_limbs::<C>(u_i.cmE)?;
179        let (u_cmW_x, u_cmW_y) = point_to_nonnative_limbs::<C>(u_i.cmW)?;
180        let (cmT_x, cmT_y) = point_to_nonnative_limbs::<C>(cmT)?;
181
182        let mut sponge = PoseidonSponge::<C::ScalarField>::new(poseidon_config);
183        let input = vec![
184            vec![U_i.u],
185            U_i.x.clone(),
186            U_cmE_x,
187            U_cmE_y,
188            U_cmW_x,
189            U_cmW_y,
190            vec![u_i.u],
191            u_i.x.clone(),
192            u_cmE_x,
193            u_cmE_y,
194            u_cmW_x,
195            u_cmW_y,
196            cmT_x,
197            cmT_y,
198        ]
199        .concat();
200        sponge.absorb(&input);
201        let bits = sponge.squeeze_bits(N_BITS_RO);
202        Ok(bits)
203    }
204
205    // compatible with the native get_challenge_native
206    pub fn get_challenge_gadget(
207        cs: ConstraintSystemRef<C::ScalarField>,
208        poseidon_config: &PoseidonConfig<C::ScalarField>,
209        U_i_vec: Vec<FpVar<CF1<C>>>, // apready processed input, so we don't have to recompute these values
210        u_i: CommittedInstanceVar<C>,
211        cmT: NonNativeAffineVar<C>,
212    ) -> Result<Vec<Boolean<C::ScalarField>>, SynthesisError> {
213        let mut sponge = PoseidonSpongeVar::<C::ScalarField>::new(cs, poseidon_config);
214
215        let input: Vec<FpVar<C::ScalarField>> = vec![
216            U_i_vec,
217            vec![u_i.u.clone()],
218            u_i.x.clone(),
219            u_i.cmE.x.to_constraint_field()?,
220            u_i.cmE.y.to_constraint_field()?,
221            u_i.cmW.x.to_constraint_field()?,
222            u_i.cmW.y.to_constraint_field()?,
223            cmT.x.to_constraint_field()?,
224            cmT.y.to_constraint_field()?,
225        ]
226        .concat();
227        sponge.absorb(&input)?;
228        let bits = sponge.squeeze_bits(N_BITS_RO)?;
229        Ok(bits)
230    }
231}
232
233/// AugmentedFCircuit implements the F' circuit (augmented F) defined in
234/// [Nova](https://eprint.iacr.org/2021/370.pdf) together with the extra constraints defined in
235/// [CycleFold](https://eprint.iacr.org/2023/1192.pdf).
236#[derive(Debug, Clone)]
237pub struct AugmentedFCircuit<
238    C1: CurveGroup,
239    C2: CurveGroup,
240    GC2: CurveVar<C2, CF2<C2>>,
241    FC: FCircuit<CF1<C1>>,
242> where
243    for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
244{
245    pub _gc2: PhantomData<GC2>,
246    pub poseidon_config: PoseidonConfig<CF1<C1>>,
247    pub i: Option<CF1<C1>>,
248    pub i_usize: Option<usize>,
249    pub z_0: Option<Vec<C1::ScalarField>>,
250    pub z_i: Option<Vec<C1::ScalarField>>,
251    pub u_i: Option<CommittedInstance<C1>>,
252    pub U_i: Option<CommittedInstance<C1>>,
253    pub U_i1: Option<CommittedInstance<C1>>,
254    pub cmT: Option<C1>,
255    pub F: FC,              // F circuit
256    pub x: Option<CF1<C1>>, // public inputs (u_{i+1}.x)
257
258    // cyclefold verifier on C1
259    // Here 'cf1, cf2' are for each of the CycleFold circuits, corresponding to the fold of cmW and
260    // cmE respectively
261    pub cf1_u_i: Option<CommittedInstance<C2>>,  // input
262    pub cf2_u_i: Option<CommittedInstance<C2>>,  // input
263    pub cf_U_i: Option<CommittedInstance<C2>>,   // input
264    pub cf1_U_i1: Option<CommittedInstance<C2>>, // intermediate
265    pub cf_U_i1: Option<CommittedInstance<C2>>,  // output
266    pub cf1_cmT: Option<C2>,
267    pub cf2_cmT: Option<C2>,
268    pub cf1_r_nonnat: Option<C2::ScalarField>,
269    pub cf2_r_nonnat: Option<C2::ScalarField>,
270}
271
272impl<C1: CurveGroup, C2: CurveGroup, GC2: CurveVar<C2, CF2<C2>>, FC: FCircuit<CF1<C1>>>
273    AugmentedFCircuit<C1, C2, GC2, FC>
274where
275    for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
276{
277    pub fn empty(poseidon_config: &PoseidonConfig<CF1<C1>>, F_circuit: FC) -> Self {
278        Self {
279            _gc2: PhantomData,
280            poseidon_config: poseidon_config.clone(),
281            i: None,
282            i_usize: None,
283            z_0: None,
284            z_i: None,
285            u_i: None,
286            U_i: None,
287            U_i1: None,
288            cmT: None,
289            F: F_circuit,
290            x: None,
291            // cyclefold values
292            cf1_u_i: None,
293            cf2_u_i: None,
294            cf_U_i: None,
295            cf1_U_i1: None,
296            cf_U_i1: None,
297            cf1_cmT: None,
298            cf2_cmT: None,
299            cf1_r_nonnat: None,
300            cf2_r_nonnat: None,
301        }
302    }
303}
304
305impl<C1, C2, GC2, FC> ConstraintSynthesizer<CF1<C1>> for AugmentedFCircuit<C1, C2, GC2, FC>
306where
307    C1: CurveGroup,
308    C2: CurveGroup,
309    GC2: CurveVar<C2, CF2<C2>>,
310    FC: FCircuit<CF1<C1>>,
311    <C1 as CurveGroup>::BaseField: PrimeField,
312    <C2 as CurveGroup>::BaseField: PrimeField,
313    <C1 as Group>::ScalarField: Absorb,
314    <C2 as Group>::ScalarField: Absorb,
315    C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
316    for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
317{
318    fn generate_constraints(self, cs: ConstraintSystemRef<CF1<C1>>) -> Result<(), SynthesisError> {
319        let i = FpVar::<CF1<C1>>::new_witness(cs.clone(), || {
320            Ok(self.i.unwrap_or_else(CF1::<C1>::zero))
321        })?;
322        let z_0 = Vec::<FpVar<CF1<C1>>>::new_witness(cs.clone(), || {
323            Ok(self
324                .z_0
325                .unwrap_or(vec![CF1::<C1>::zero(); self.F.state_len()]))
326        })?;
327        let z_i = Vec::<FpVar<CF1<C1>>>::new_witness(cs.clone(), || {
328            Ok(self
329                .z_i
330                .unwrap_or(vec![CF1::<C1>::zero(); self.F.state_len()]))
331        })?;
332
333        let u_dummy_native = CommittedInstance::<C1>::dummy(1);
334        let u_i = CommittedInstanceVar::<C1>::new_witness(cs.clone(), || {
335            Ok(self.u_i.unwrap_or(u_dummy_native.clone()))
336        })?;
337        let U_i = CommittedInstanceVar::<C1>::new_witness(cs.clone(), || {
338            Ok(self.U_i.unwrap_or(u_dummy_native.clone()))
339        })?;
340        let U_i1 = CommittedInstanceVar::<C1>::new_witness(cs.clone(), || {
341            Ok(self.U_i1.unwrap_or(u_dummy_native.clone()))
342        })?;
343        let cmT =
344            NonNativeAffineVar::new_witness(cs.clone(), || Ok(self.cmT.unwrap_or_else(C1::zero)))?;
345        let x =
346            FpVar::<CF1<C1>>::new_input(cs.clone(), || Ok(self.x.unwrap_or_else(CF1::<C1>::zero)))?;
347
348        let crh_params = CRHParametersVar::<C1::ScalarField>::new_constant(
349            cs.clone(),
350            self.poseidon_config.clone(),
351        )?;
352
353        // get z_{i+1} from the F circuit
354        let i_usize = self.i_usize.unwrap_or(0);
355        let z_i1 = self
356            .F
357            .generate_step_constraints(cs.clone(), i_usize, z_i.clone())?;
358
359        let zero = FpVar::<CF1<C1>>::new_constant(cs.clone(), CF1::<C1>::zero())?;
360        let is_not_basecase = i.is_neq(&zero)?;
361
362        // 1. u_i.x == H(i, z_0, z_i, U_i)
363        let (u_i_x, U_i_vec) =
364            U_i.clone()
365                .hash(&crh_params, i.clone(), z_0.clone(), z_i.clone())?;
366
367        // check that h == u_i.x
368        (u_i.x[0]).conditional_enforce_equal(&u_i_x, &is_not_basecase)?;
369
370        // 2. u_i.cmE==cm(0), u_i.u==1
371        let zero_x = NonNativeFieldVar::<C1::BaseField, C1::ScalarField>::new_constant(
372            cs.clone(),
373            C1::BaseField::zero(),
374        )?;
375        let zero_y = NonNativeFieldVar::<C1::BaseField, C1::ScalarField>::new_constant(
376            cs.clone(),
377            C1::BaseField::one(),
378        )?;
379        (u_i.cmE.x.is_eq(&zero_x)?).conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
380        (u_i.cmE.y.is_eq(&zero_y)?).conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
381        (u_i.u.is_one()?).conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
382
383        // 3. nifs.verify, checks that folding u_i & U_i obtains U_{i+1}.
384        // compute r = H(u_i, U_i, cmT)
385        let r_bits = ChallengeGadget::<C1>::get_challenge_gadget(
386            cs.clone(),
387            &self.poseidon_config,
388            U_i_vec,
389            u_i.clone(),
390            cmT.clone(),
391        )?;
392        let r = Boolean::le_bits_to_fp_var(&r_bits)?;
393
394        // Notice that NIFSGadget::verify is not checking the folding of cmE & cmW, since it will
395        // be done on the other curve.
396        let nifs_check = NIFSGadget::<C1>::verify(r, U_i.clone(), u_i.clone(), U_i1.clone())?;
397        nifs_check.conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
398
399        // 4. u_{i+1}.x = H(i+1, z_0, z_i+1, U_{i+1}), this is the output of F'
400        let (u_i1_x, _) = U_i1.clone().hash(
401            &crh_params,
402            i + FpVar::<CF1<C1>>::one(),
403            z_0.clone(),
404            z_i1.clone(),
405        )?;
406
407        u_i1_x.enforce_equal(&x)?;
408
409        // CycleFold part
410        let cf_u_dummy_native = CommittedInstance::<C2>::dummy(CF_IO_LEN);
411        // cf W circuit data
412        let cf1_u_i = CycleFoldCommittedInstanceVar::<C2, GC2>::new_witness(cs.clone(), || {
413            Ok(self.cf1_u_i.unwrap_or_else(|| cf_u_dummy_native.clone()))
414        })?;
415        let cf2_u_i = CycleFoldCommittedInstanceVar::<C2, GC2>::new_witness(cs.clone(), || {
416            Ok(self.cf2_u_i.unwrap_or_else(|| cf_u_dummy_native.clone()))
417        })?;
418        let cf_U_i = CycleFoldCommittedInstanceVar::<C2, GC2>::new_witness(cs.clone(), || {
419            Ok(self.cf_U_i.unwrap_or_else(|| cf_u_dummy_native.clone()))
420        })?;
421        let cf1_U_i1 = CycleFoldCommittedInstanceVar::<C2, GC2>::new_witness(cs.clone(), || {
422            Ok(self.cf1_U_i1.unwrap_or_else(|| cf_u_dummy_native.clone()))
423        })?;
424        let cf_U_i1 = CycleFoldCommittedInstanceVar::<C2, GC2>::new_witness(cs.clone(), || {
425            Ok(self.cf_U_i1.unwrap_or_else(|| cf_u_dummy_native.clone()))
426        })?;
427        let cf1_cmT = GC2::new_witness(cs.clone(), || Ok(self.cf1_cmT.unwrap_or_else(C2::zero)))?;
428        let cf2_cmT = GC2::new_witness(cs.clone(), || Ok(self.cf2_cmT.unwrap_or_else(C2::zero)))?;
429        let cf1_r_nonnat =
430            NonNativeFieldVar::<C1::BaseField, C1::ScalarField>::new_witness(cs.clone(), || {
431                Ok(self.cf1_r_nonnat.unwrap_or_else(C2::ScalarField::zero))
432            })?;
433        let cf2_r_nonnat =
434            NonNativeFieldVar::<C1::BaseField, C1::ScalarField>::new_witness(cs.clone(), || {
435                Ok(self.cf2_r_nonnat.unwrap_or_else(C2::ScalarField::zero))
436            })?;
437
438        let cfW_x: Vec<NonNativeFieldVar<C1::BaseField, C1::ScalarField>> = vec![
439            U_i.cmW.x, U_i.cmW.y, u_i.cmW.x, u_i.cmW.y, U_i1.cmW.x, U_i1.cmW.y,
440        ];
441        let cfE_x: Vec<NonNativeFieldVar<C1::BaseField, C1::ScalarField>> = vec![
442            U_i.cmE.x, U_i.cmE.y, u_i.cmE.x, u_i.cmE.y, U_i1.cmE.x, U_i1.cmE.y,
443        ];
444
445        // ensure that cf1_u & cf2_u have as public inputs the cmW & cmE from main instances U_i,
446        // u_i, U_i+1 coordinates of the commitments
447        cf1_u_i
448            .x
449            .conditional_enforce_equal(&cfW_x, &is_not_basecase)?;
450        cf2_u_i
451            .x
452            .conditional_enforce_equal(&cfE_x, &is_not_basecase)?;
453
454        // cf_r_bits is denoted by rho* in the paper.
455        // assert that cf_r_bits == cf_r_nonnat converted to bits. cf_r_nonnat is just an auxiliary
456        // value used to compute RLC of NonNativeFieldVar values, since we can convert
457        // NonNativeFieldVar into Vec<Boolean>, but not in the other direction.
458        let cf1_r_bits = CycleFoldChallengeGadget::<C2, GC2>::get_challenge_gadget(
459            cs.clone(),
460            &self.poseidon_config,
461            cf_U_i.clone(),
462            cf1_u_i.clone(),
463            cf1_cmT.clone(),
464        )?;
465        let cf1_r_nonnat_bits = cf1_r_nonnat.to_bits_le()?;
466        cf1_r_bits.conditional_enforce_equal(&cf1_r_nonnat_bits[..N_BITS_RO], &is_not_basecase)?;
467        // same for cf2_r:
468        let cf2_r_bits = CycleFoldChallengeGadget::<C2, GC2>::get_challenge_gadget(
469            cs.clone(),
470            &self.poseidon_config,
471            cf1_U_i1.clone(),
472            cf2_u_i.clone(),
473            cf2_cmT.clone(),
474        )?;
475        let cf2_r_nonnat_bits = cf2_r_nonnat.to_bits_le()?;
476        cf2_r_bits.conditional_enforce_equal(&cf2_r_nonnat_bits[..N_BITS_RO], &is_not_basecase)?;
477
478        // check cf_u_i.cmE=0, cf_u_i.u=1
479        (cf1_u_i.cmE.is_zero()?).conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
480        (cf1_u_i.u.is_one()?).conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
481        (cf2_u_i.cmE.is_zero()?).conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
482        (cf2_u_i.u.is_one()?).conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
483
484        // check the fold of all the parameters of the CycleFold instances, where the elliptic
485        // curve points relations are checked natively in Curve1 circuit (this one)
486        let v1 = NIFSFullGadget::<C2, GC2>::verify(
487            cf1_r_bits,
488            cf1_r_nonnat,
489            cf1_cmT,
490            cf_U_i,
491            cf1_u_i,
492            cf1_U_i1.clone(),
493        )?;
494        v1.conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
495        let v2 = NIFSFullGadget::<C2, GC2>::verify(
496            cf2_r_bits,
497            cf2_r_nonnat,
498            cf2_cmT,
499            cf1_U_i1, // the output from NIFS.V(cf1_r, cf_U, cfE_u)
500            cf2_u_i,
501            cf_U_i1,
502        )?;
503        v2.conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
504
505        Ok(())
506    }
507}
508
509#[cfg(test)]
510pub mod tests {
511    use super::*;
512    use ark_bn254::{Fr, G1Projective as Projective};
513    use ark_ff::BigInteger;
514    use ark_r1cs_std::{alloc::AllocVar, R1CSVar};
515    use ark_relations::r1cs::ConstraintSystem;
516    use ark_std::UniformRand;
517
518    use crate::commitment::pedersen::Pedersen;
519    use crate::folding::nova::nifs::tests::prepare_simple_fold_inputs;
520    use crate::folding::nova::nifs::NIFS;
521    use crate::transcript::poseidon::poseidon_test_config;
522
523    #[test]
524    fn test_committed_instance_var() {
525        let mut rng = ark_std::test_rng();
526
527        let ci = CommittedInstance::<Projective> {
528            cmE: Projective::rand(&mut rng),
529            u: Fr::rand(&mut rng),
530            cmW: Projective::rand(&mut rng),
531            x: vec![Fr::rand(&mut rng); 1],
532        };
533
534        let cs = ConstraintSystem::<Fr>::new_ref();
535        let ciVar =
536            CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(ci.clone())).unwrap();
537        assert_eq!(ciVar.u.value().unwrap(), ci.u);
538        assert_eq!(ciVar.x.value().unwrap(), ci.x);
539        // the values cmE and cmW are checked in the CycleFold's circuit
540        // CommittedInstanceInCycleFoldVar in
541        // nova::cyclefold::tests::test_committed_instance_cyclefold_var
542    }
543
544    #[test]
545    fn test_nifs_gadget() {
546        let (_, _, _, _, ci1, _, ci2, _, ci3, _, cmT, _, r_Fr) = prepare_simple_fold_inputs();
547
548        let ci3_verifier = NIFS::<Projective, Pedersen<Projective>>::verify(r_Fr, &ci1, &ci2, &cmT);
549        assert_eq!(ci3_verifier, ci3);
550
551        let cs = ConstraintSystem::<Fr>::new_ref();
552
553        let rVar = FpVar::<Fr>::new_witness(cs.clone(), || Ok(r_Fr)).unwrap();
554        let ci1Var =
555            CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(ci1.clone()))
556                .unwrap();
557        let ci2Var =
558            CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(ci2.clone()))
559                .unwrap();
560        let ci3Var =
561            CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(ci3.clone()))
562                .unwrap();
563
564        let nifs_check = NIFSGadget::<Projective>::verify(
565            rVar.clone(),
566            ci1Var.clone(),
567            ci2Var.clone(),
568            ci3Var.clone(),
569        )
570        .unwrap();
571        nifs_check.enforce_equal(&Boolean::<Fr>::TRUE).unwrap();
572        assert!(cs.is_satisfied().unwrap());
573    }
574
575    #[test]
576    fn test_committed_instance_hash() {
577        let mut rng = ark_std::test_rng();
578        let poseidon_config = poseidon_test_config::<Fr>();
579
580        let i = Fr::from(3_u32);
581        let z_0 = vec![Fr::from(3_u32)];
582        let z_i = vec![Fr::from(3_u32)];
583        let ci = CommittedInstance::<Projective> {
584            cmE: Projective::rand(&mut rng),
585            u: Fr::rand(&mut rng),
586            cmW: Projective::rand(&mut rng),
587            x: vec![Fr::rand(&mut rng); 1],
588        };
589
590        // compute the CommittedInstance hash natively
591        let h = ci
592            .hash(&poseidon_config, i, z_0.clone(), z_i.clone())
593            .unwrap();
594
595        let cs = ConstraintSystem::<Fr>::new_ref();
596
597        let iVar = FpVar::<Fr>::new_witness(cs.clone(), || Ok(i)).unwrap();
598        let z_0Var = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_0.clone())).unwrap();
599        let z_iVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_i.clone())).unwrap();
600        let ciVar =
601            CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(ci.clone())).unwrap();
602
603        let crh_params = CRHParametersVar::<Fr>::new_constant(cs.clone(), poseidon_config).unwrap();
604
605        // compute the CommittedInstance hash in-circuit
606        let (hVar, _) = ciVar.hash(&crh_params, iVar, z_0Var, z_iVar).unwrap();
607        assert!(cs.is_satisfied().unwrap());
608
609        // check that the natively computed and in-circuit computed hashes match
610        assert_eq!(hVar.value().unwrap(), h);
611    }
612
613    // checks that the gadget and native implementations of the challenge computation match
614    #[test]
615    fn test_challenge_gadget() {
616        let mut rng = ark_std::test_rng();
617        let poseidon_config = poseidon_test_config::<Fr>();
618
619        let u_i = CommittedInstance::<Projective> {
620            cmE: Projective::rand(&mut rng),
621            u: Fr::rand(&mut rng),
622            cmW: Projective::rand(&mut rng),
623            x: vec![Fr::rand(&mut rng); 1],
624        };
625        let U_i = CommittedInstance::<Projective> {
626            cmE: Projective::rand(&mut rng),
627            u: Fr::rand(&mut rng),
628            cmW: Projective::rand(&mut rng),
629            x: vec![Fr::rand(&mut rng); 1],
630        };
631        let cmT = Projective::rand(&mut rng);
632
633        // compute the challenge natively
634        let r_bits = ChallengeGadget::<Projective>::get_challenge_native(
635            &poseidon_config,
636            U_i.clone(),
637            u_i.clone(),
638            cmT,
639        )
640        .unwrap();
641        let r = Fr::from_bigint(BigInteger::from_bits_le(&r_bits)).unwrap();
642
643        let cs = ConstraintSystem::<Fr>::new_ref();
644        let u_iVar =
645            CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(u_i.clone()))
646                .unwrap();
647        let U_iVar =
648            CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(U_i.clone()))
649                .unwrap();
650        let cmTVar = NonNativeAffineVar::<Projective>::new_witness(cs.clone(), || Ok(cmT)).unwrap();
651
652        // compute the challenge in-circuit
653        let U_iVar_vec = [
654            vec![U_iVar.u.clone()],
655            U_iVar.x.clone(),
656            U_iVar.cmE.x.to_constraint_field().unwrap(),
657            U_iVar.cmE.y.to_constraint_field().unwrap(),
658            U_iVar.cmW.x.to_constraint_field().unwrap(),
659            U_iVar.cmW.y.to_constraint_field().unwrap(),
660        ]
661        .concat();
662        let r_bitsVar = ChallengeGadget::<Projective>::get_challenge_gadget(
663            cs.clone(),
664            &poseidon_config,
665            U_iVar_vec,
666            u_iVar,
667            cmTVar,
668        )
669        .unwrap();
670        assert!(cs.is_satisfied().unwrap());
671
672        // check that the natively computed and in-circuit computed hashes match
673        let rVar = Boolean::le_bits_to_fp_var(&r_bitsVar).unwrap();
674        assert_eq!(rVar.value().unwrap(), r);
675        assert_eq!(r_bitsVar.value().unwrap(), r_bits);
676    }
677}