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 z_0: Option<Vec<C1::ScalarField>>,
249    pub z_i: Option<Vec<C1::ScalarField>>,
250    pub u_i: Option<CommittedInstance<C1>>,
251    pub U_i: Option<CommittedInstance<C1>>,
252    pub U_i1: Option<CommittedInstance<C1>>,
253    pub cmT: Option<C1>,
254    pub F: FC,              // F circuit
255    pub x: Option<CF1<C1>>, // public inputs (u_{i+1}.x)
256
257    // cyclefold verifier on C1
258    // Here 'cf1, cf2' are for each of the CycleFold circuits, corresponding to the fold of cmW and
259    // cmE respectively
260    pub cf1_u_i: Option<CommittedInstance<C2>>,  // input
261    pub cf2_u_i: Option<CommittedInstance<C2>>,  // input
262    pub cf_U_i: Option<CommittedInstance<C2>>,   // input
263    pub cf1_U_i1: Option<CommittedInstance<C2>>, // intermediate
264    pub cf_U_i1: Option<CommittedInstance<C2>>,  // output
265    pub cf1_cmT: Option<C2>,
266    pub cf2_cmT: Option<C2>,
267    pub cf1_r_nonnat: Option<C2::ScalarField>,
268    pub cf2_r_nonnat: Option<C2::ScalarField>,
269}
270
271impl<C1: CurveGroup, C2: CurveGroup, GC2: CurveVar<C2, CF2<C2>>, FC: FCircuit<CF1<C1>>>
272    AugmentedFCircuit<C1, C2, GC2, FC>
273where
274    for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
275{
276    pub fn empty(poseidon_config: &PoseidonConfig<CF1<C1>>, F_circuit: FC) -> Self {
277        Self {
278            _gc2: PhantomData,
279            poseidon_config: poseidon_config.clone(),
280            i: None,
281            z_0: None,
282            z_i: None,
283            u_i: None,
284            U_i: None,
285            U_i1: None,
286            cmT: None,
287            F: F_circuit,
288            x: None,
289            // cyclefold values
290            cf1_u_i: None,
291            cf2_u_i: None,
292            cf_U_i: None,
293            cf1_U_i1: None,
294            cf_U_i1: None,
295            cf1_cmT: None,
296            cf2_cmT: None,
297            cf1_r_nonnat: None,
298            cf2_r_nonnat: None,
299        }
300    }
301}
302
303impl<C1, C2, GC2, FC> ConstraintSynthesizer<CF1<C1>> for AugmentedFCircuit<C1, C2, GC2, FC>
304where
305    C1: CurveGroup,
306    C2: CurveGroup,
307    GC2: CurveVar<C2, CF2<C2>>,
308    FC: FCircuit<CF1<C1>>,
309    <C1 as CurveGroup>::BaseField: PrimeField,
310    <C2 as CurveGroup>::BaseField: PrimeField,
311    <C1 as Group>::ScalarField: Absorb,
312    <C2 as Group>::ScalarField: Absorb,
313    C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
314    for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
315{
316    fn generate_constraints(self, cs: ConstraintSystemRef<CF1<C1>>) -> Result<(), SynthesisError> {
317        let i = FpVar::<CF1<C1>>::new_witness(cs.clone(), || {
318            Ok(self.i.unwrap_or_else(CF1::<C1>::zero))
319        })?;
320        let z_0 = Vec::<FpVar<CF1<C1>>>::new_witness(cs.clone(), || {
321            Ok(self
322                .z_0
323                .unwrap_or(vec![CF1::<C1>::zero(); self.F.state_len()]))
324        })?;
325        let z_i = Vec::<FpVar<CF1<C1>>>::new_witness(cs.clone(), || {
326            Ok(self
327                .z_i
328                .unwrap_or(vec![CF1::<C1>::zero(); self.F.state_len()]))
329        })?;
330
331        let u_dummy_native = CommittedInstance::<C1>::dummy(1);
332        let u_i = CommittedInstanceVar::<C1>::new_witness(cs.clone(), || {
333            Ok(self.u_i.unwrap_or(u_dummy_native.clone()))
334        })?;
335        let U_i = CommittedInstanceVar::<C1>::new_witness(cs.clone(), || {
336            Ok(self.U_i.unwrap_or(u_dummy_native.clone()))
337        })?;
338        let U_i1 = CommittedInstanceVar::<C1>::new_witness(cs.clone(), || {
339            Ok(self.U_i1.unwrap_or(u_dummy_native.clone()))
340        })?;
341        let cmT =
342            NonNativeAffineVar::new_witness(cs.clone(), || Ok(self.cmT.unwrap_or_else(C1::zero)))?;
343        let x =
344            FpVar::<CF1<C1>>::new_input(cs.clone(), || Ok(self.x.unwrap_or_else(CF1::<C1>::zero)))?;
345
346        let crh_params = CRHParametersVar::<C1::ScalarField>::new_constant(
347            cs.clone(),
348            self.poseidon_config.clone(),
349        )?;
350
351        // get z_{i+1} from the F circuit
352        let z_i1 = self.F.generate_step_constraints(cs.clone(), z_i.clone())?;
353
354        let zero = FpVar::<CF1<C1>>::new_constant(cs.clone(), CF1::<C1>::zero())?;
355        let is_not_basecase = i.is_neq(&zero)?;
356
357        // 1. u_i.x == H(i, z_0, z_i, U_i)
358        let (u_i_x, U_i_vec) =
359            U_i.clone()
360                .hash(&crh_params, i.clone(), z_0.clone(), z_i.clone())?;
361
362        // check that h == u_i.x
363        (u_i.x[0]).conditional_enforce_equal(&u_i_x, &is_not_basecase)?;
364
365        // 2. u_i.cmE==cm(0), u_i.u==1
366        let zero_x = NonNativeFieldVar::<C1::BaseField, C1::ScalarField>::new_constant(
367            cs.clone(),
368            C1::BaseField::zero(),
369        )?;
370        let zero_y = NonNativeFieldVar::<C1::BaseField, C1::ScalarField>::new_constant(
371            cs.clone(),
372            C1::BaseField::one(),
373        )?;
374        (u_i.cmE.x.is_eq(&zero_x)?).conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
375        (u_i.cmE.y.is_eq(&zero_y)?).conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
376        (u_i.u.is_one()?).conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
377
378        // 3. nifs.verify, checks that folding u_i & U_i obtains U_{i+1}.
379        // compute r = H(u_i, U_i, cmT)
380        let r_bits = ChallengeGadget::<C1>::get_challenge_gadget(
381            cs.clone(),
382            &self.poseidon_config,
383            U_i_vec,
384            u_i.clone(),
385            cmT.clone(),
386        )?;
387        let r = Boolean::le_bits_to_fp_var(&r_bits)?;
388
389        // Notice that NIFSGadget::verify is not checking the folding of cmE & cmW, since it will
390        // be done on the other curve.
391        let nifs_check = NIFSGadget::<C1>::verify(r, U_i.clone(), u_i.clone(), U_i1.clone())?;
392        nifs_check.conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
393
394        // 4. u_{i+1}.x = H(i+1, z_0, z_i+1, U_{i+1}), this is the output of F'
395        let (u_i1_x, _) = U_i1.clone().hash(
396            &crh_params,
397            i + FpVar::<CF1<C1>>::one(),
398            z_0.clone(),
399            z_i1.clone(),
400        )?;
401
402        u_i1_x.enforce_equal(&x)?;
403
404        // CycleFold part
405        let cf_u_dummy_native = CommittedInstance::<C2>::dummy(CF_IO_LEN);
406        // cf W circuit data
407        let cf1_u_i = CycleFoldCommittedInstanceVar::<C2, GC2>::new_witness(cs.clone(), || {
408            Ok(self.cf1_u_i.unwrap_or_else(|| cf_u_dummy_native.clone()))
409        })?;
410        let cf2_u_i = CycleFoldCommittedInstanceVar::<C2, GC2>::new_witness(cs.clone(), || {
411            Ok(self.cf2_u_i.unwrap_or_else(|| cf_u_dummy_native.clone()))
412        })?;
413        let cf_U_i = CycleFoldCommittedInstanceVar::<C2, GC2>::new_witness(cs.clone(), || {
414            Ok(self.cf_U_i.unwrap_or_else(|| cf_u_dummy_native.clone()))
415        })?;
416        let cf1_U_i1 = CycleFoldCommittedInstanceVar::<C2, GC2>::new_witness(cs.clone(), || {
417            Ok(self.cf1_U_i1.unwrap_or_else(|| cf_u_dummy_native.clone()))
418        })?;
419        let cf_U_i1 = CycleFoldCommittedInstanceVar::<C2, GC2>::new_witness(cs.clone(), || {
420            Ok(self.cf_U_i1.unwrap_or_else(|| cf_u_dummy_native.clone()))
421        })?;
422        let cf1_cmT = GC2::new_witness(cs.clone(), || Ok(self.cf1_cmT.unwrap_or_else(C2::zero)))?;
423        let cf2_cmT = GC2::new_witness(cs.clone(), || Ok(self.cf2_cmT.unwrap_or_else(C2::zero)))?;
424        let cf1_r_nonnat =
425            NonNativeFieldVar::<C1::BaseField, C1::ScalarField>::new_witness(cs.clone(), || {
426                Ok(self.cf1_r_nonnat.unwrap_or_else(C2::ScalarField::zero))
427            })?;
428        let cf2_r_nonnat =
429            NonNativeFieldVar::<C1::BaseField, C1::ScalarField>::new_witness(cs.clone(), || {
430                Ok(self.cf2_r_nonnat.unwrap_or_else(C2::ScalarField::zero))
431            })?;
432
433        let cfW_x: Vec<NonNativeFieldVar<C1::BaseField, C1::ScalarField>> = vec![
434            U_i.cmW.x, U_i.cmW.y, u_i.cmW.x, u_i.cmW.y, U_i1.cmW.x, U_i1.cmW.y,
435        ];
436        let cfE_x: Vec<NonNativeFieldVar<C1::BaseField, C1::ScalarField>> = vec![
437            U_i.cmE.x, U_i.cmE.y, u_i.cmE.x, u_i.cmE.y, U_i1.cmE.x, U_i1.cmE.y,
438        ];
439
440        // ensure that cf1_u & cf2_u have as public inputs the cmW & cmE from main instances U_i,
441        // u_i, U_i+1 coordinates of the commitments
442        cf1_u_i
443            .x
444            .conditional_enforce_equal(&cfW_x, &is_not_basecase)?;
445        cf2_u_i
446            .x
447            .conditional_enforce_equal(&cfE_x, &is_not_basecase)?;
448
449        // cf_r_bits is denoted by rho* in the paper.
450        // assert that cf_r_bits == cf_r_nonnat converted to bits. cf_r_nonnat is just an auxiliary
451        // value used to compute RLC of NonNativeFieldVar values, since we can convert
452        // NonNativeFieldVar into Vec<Boolean>, but not in the other direction.
453        let cf1_r_bits = CycleFoldChallengeGadget::<C2, GC2>::get_challenge_gadget(
454            cs.clone(),
455            &self.poseidon_config,
456            cf_U_i.clone(),
457            cf1_u_i.clone(),
458            cf1_cmT.clone(),
459        )?;
460        let cf1_r_nonnat_bits = cf1_r_nonnat.to_bits_le()?;
461        cf1_r_bits.conditional_enforce_equal(&cf1_r_nonnat_bits[..N_BITS_RO], &is_not_basecase)?;
462        // same for cf2_r:
463        let cf2_r_bits = CycleFoldChallengeGadget::<C2, GC2>::get_challenge_gadget(
464            cs.clone(),
465            &self.poseidon_config,
466            cf1_U_i1.clone(),
467            cf2_u_i.clone(),
468            cf2_cmT.clone(),
469        )?;
470        let cf2_r_nonnat_bits = cf2_r_nonnat.to_bits_le()?;
471        cf2_r_bits.conditional_enforce_equal(&cf2_r_nonnat_bits[..N_BITS_RO], &is_not_basecase)?;
472
473        // check cf_u_i.cmE=0, cf_u_i.u=1
474        (cf1_u_i.cmE.is_zero()?).conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
475        (cf1_u_i.u.is_one()?).conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
476        (cf2_u_i.cmE.is_zero()?).conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
477        (cf2_u_i.u.is_one()?).conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
478
479        // check the fold of all the parameters of the CycleFold instances, where the elliptic
480        // curve points relations are checked natively in Curve1 circuit (this one)
481        let v1 = NIFSFullGadget::<C2, GC2>::verify(
482            cf1_r_bits,
483            cf1_r_nonnat,
484            cf1_cmT,
485            cf_U_i,
486            cf1_u_i,
487            cf1_U_i1.clone(),
488        )?;
489        v1.conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
490        let v2 = NIFSFullGadget::<C2, GC2>::verify(
491            cf2_r_bits,
492            cf2_r_nonnat,
493            cf2_cmT,
494            cf1_U_i1, // the output from NIFS.V(cf1_r, cf_U, cfE_u)
495            cf2_u_i,
496            cf_U_i1,
497        )?;
498        v2.conditional_enforce_equal(&Boolean::TRUE, &is_not_basecase)?;
499
500        Ok(())
501    }
502}
503
504#[cfg(test)]
505pub mod tests {
506    use super::*;
507    use ark_ff::BigInteger;
508    use ark_pallas::{Fr, Projective};
509    use ark_r1cs_std::{alloc::AllocVar, R1CSVar};
510    use ark_relations::r1cs::ConstraintSystem;
511    use ark_std::UniformRand;
512
513    use crate::commitment::pedersen::Pedersen;
514    use crate::folding::nova::nifs::tests::prepare_simple_fold_inputs;
515    use crate::folding::nova::nifs::NIFS;
516    use crate::transcript::poseidon::poseidon_test_config;
517
518    #[test]
519    fn test_committed_instance_var() {
520        let mut rng = ark_std::test_rng();
521
522        let ci = CommittedInstance::<Projective> {
523            cmE: Projective::rand(&mut rng),
524            u: Fr::rand(&mut rng),
525            cmW: Projective::rand(&mut rng),
526            x: vec![Fr::rand(&mut rng); 1],
527        };
528
529        let cs = ConstraintSystem::<Fr>::new_ref();
530        let ciVar =
531            CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(ci.clone())).unwrap();
532        assert_eq!(ciVar.u.value().unwrap(), ci.u);
533        assert_eq!(ciVar.x.value().unwrap(), ci.x);
534        // the values cmE and cmW are checked in the CycleFold's circuit
535        // CommittedInstanceInCycleFoldVar in
536        // nova::cyclefold::tests::test_committed_instance_cyclefold_var
537    }
538
539    #[test]
540    fn test_nifs_gadget() {
541        let (_, _, _, _, ci1, _, ci2, _, ci3, _, cmT, _, r_Fr) = prepare_simple_fold_inputs();
542
543        let ci3_verifier = NIFS::<Projective, Pedersen<Projective>>::verify(r_Fr, &ci1, &ci2, &cmT);
544        assert_eq!(ci3_verifier, ci3);
545
546        let cs = ConstraintSystem::<Fr>::new_ref();
547
548        let rVar = FpVar::<Fr>::new_witness(cs.clone(), || Ok(r_Fr)).unwrap();
549        let ci1Var =
550            CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(ci1.clone()))
551                .unwrap();
552        let ci2Var =
553            CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(ci2.clone()))
554                .unwrap();
555        let ci3Var =
556            CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(ci3.clone()))
557                .unwrap();
558
559        let nifs_check = NIFSGadget::<Projective>::verify(
560            rVar.clone(),
561            ci1Var.clone(),
562            ci2Var.clone(),
563            ci3Var.clone(),
564        )
565        .unwrap();
566        nifs_check.enforce_equal(&Boolean::<Fr>::TRUE).unwrap();
567        assert!(cs.is_satisfied().unwrap());
568    }
569
570    #[test]
571    fn test_committed_instance_hash() {
572        let mut rng = ark_std::test_rng();
573        let poseidon_config = poseidon_test_config::<Fr>();
574
575        let i = Fr::from(3_u32);
576        let z_0 = vec![Fr::from(3_u32)];
577        let z_i = vec![Fr::from(3_u32)];
578        let ci = CommittedInstance::<Projective> {
579            cmE: Projective::rand(&mut rng),
580            u: Fr::rand(&mut rng),
581            cmW: Projective::rand(&mut rng),
582            x: vec![Fr::rand(&mut rng); 1],
583        };
584
585        // compute the CommittedInstance hash natively
586        let h = ci
587            .hash(&poseidon_config, i, z_0.clone(), z_i.clone())
588            .unwrap();
589
590        let cs = ConstraintSystem::<Fr>::new_ref();
591
592        let iVar = FpVar::<Fr>::new_witness(cs.clone(), || Ok(i)).unwrap();
593        let z_0Var = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_0.clone())).unwrap();
594        let z_iVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_i.clone())).unwrap();
595        let ciVar =
596            CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(ci.clone())).unwrap();
597
598        let crh_params = CRHParametersVar::<Fr>::new_constant(cs.clone(), poseidon_config).unwrap();
599
600        // compute the CommittedInstance hash in-circuit
601        let (hVar, _) = ciVar.hash(&crh_params, iVar, z_0Var, z_iVar).unwrap();
602        assert!(cs.is_satisfied().unwrap());
603
604        // check that the natively computed and in-circuit computed hashes match
605        assert_eq!(hVar.value().unwrap(), h);
606    }
607
608    // checks that the gadget and native implementations of the challenge computation match
609    #[test]
610    fn test_challenge_gadget() {
611        let mut rng = ark_std::test_rng();
612        let poseidon_config = poseidon_test_config::<Fr>();
613
614        let u_i = CommittedInstance::<Projective> {
615            cmE: Projective::rand(&mut rng),
616            u: Fr::rand(&mut rng),
617            cmW: Projective::rand(&mut rng),
618            x: vec![Fr::rand(&mut rng); 1],
619        };
620        let U_i = CommittedInstance::<Projective> {
621            cmE: Projective::rand(&mut rng),
622            u: Fr::rand(&mut rng),
623            cmW: Projective::rand(&mut rng),
624            x: vec![Fr::rand(&mut rng); 1],
625        };
626        let cmT = Projective::rand(&mut rng);
627
628        // compute the challenge natively
629        let r_bits = ChallengeGadget::<Projective>::get_challenge_native(
630            &poseidon_config,
631            U_i.clone(),
632            u_i.clone(),
633            cmT,
634        )
635        .unwrap();
636        let r = Fr::from_bigint(BigInteger::from_bits_le(&r_bits)).unwrap();
637
638        let cs = ConstraintSystem::<Fr>::new_ref();
639        let u_iVar =
640            CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(u_i.clone()))
641                .unwrap();
642        let U_iVar =
643            CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(U_i.clone()))
644                .unwrap();
645        let cmTVar = NonNativeAffineVar::<Projective>::new_witness(cs.clone(), || Ok(cmT)).unwrap();
646
647        // compute the challenge in-circuit
648        let U_iVar_vec = [
649            vec![U_iVar.u.clone()],
650            U_iVar.x.clone(),
651            U_iVar.cmE.x.to_constraint_field().unwrap(),
652            U_iVar.cmE.y.to_constraint_field().unwrap(),
653            U_iVar.cmW.x.to_constraint_field().unwrap(),
654            U_iVar.cmW.y.to_constraint_field().unwrap(),
655        ]
656        .concat();
657        let r_bitsVar = ChallengeGadget::<Projective>::get_challenge_gadget(
658            cs.clone(),
659            &poseidon_config,
660            U_iVar_vec,
661            u_iVar,
662            cmTVar,
663        )
664        .unwrap();
665        assert!(cs.is_satisfied().unwrap());
666
667        // check that the natively computed and in-circuit computed hashes match
668        let rVar = Boolean::le_bits_to_fp_var(&r_bitsVar).unwrap();
669        assert_eq!(rVar.value().unwrap(), r);
670        assert_eq!(r_bitsVar.value().unwrap(), r_bits);
671    }
672}