arnaucube
arnaucube/sonobePublic Self-hosted repository
sonobe/folding-schemes/src/folding/nova/decider_circuits.rs
folding-schemes/src/folding/nova/decider_circuits.rsRaw
  1/// This file implements the offchain decider circuit. For ethereum use cases, use the
  2/// DeciderEthCircuit.
  3/// More details can be found at the documentation page:
  4/// https://privacy-scaling-explorations.github.io/sonobe-docs/design/nova-decider-offchain.html
  5use ark_crypto_primitives::sponge::{
  6    constraints::CryptographicSpongeVar,
  7    poseidon::{constraints::PoseidonSpongeVar, PoseidonConfig, PoseidonSponge},
  8    Absorb, CryptographicSponge,
  9};
 10use ark_ec::{CurveGroup, Group};
 11use ark_ff::{BigInteger, PrimeField};
 12use ark_poly::Polynomial;
 13use ark_r1cs_std::{
 14    alloc::AllocVar,
 15    boolean::Boolean,
 16    eq::EqGadget,
 17    fields::{fp::FpVar, FieldVar},
 18    groups::GroupOpsBounds,
 19    prelude::CurveVar,
 20    ToConstraintFieldGadget,
 21};
 22use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystemRef, SynthesisError};
 23use ark_std::Zero;
 24use core::marker::PhantomData;
 25
 26use super::{
 27    circuits::{ChallengeGadget, CommittedInstanceVar},
 28    decider_eth_circuit::{
 29        evaluate_gadget, KZGChallengesGadget, R1CSVar, RelaxedR1CSGadget, WitnessVar,
 30    },
 31    nifs::{nova::NIFS, NIFSTrait},
 32    CommittedInstance, Nova, Witness,
 33};
 34use crate::arith::r1cs::R1CS;
 35use crate::commitment::CommitmentScheme;
 36use crate::folding::circuits::{
 37    cyclefold::{
 38        CycleFoldCommittedInstance, CycleFoldCommittedInstanceVar, CycleFoldConfig,
 39        CycleFoldWitness,
 40    },
 41    nonnative::{affine::NonNativeAffineVar, uint::NonNativeUintVar},
 42    CF1, CF2,
 43};
 44use crate::folding::nova::NovaCycleFoldConfig;
 45use crate::folding::traits::{CommittedInstanceVarOps, Dummy};
 46use crate::frontend::FCircuit;
 47use crate::utils::vec::poly_from_vec;
 48use crate::Error;
 49
 50/// Circuit that implements part of the in-circuit checks needed for the offchain verification over
 51/// the Curve2's BaseField (=Curve1's ScalarField).
 52#[derive(Clone, Debug)]
 53pub struct DeciderCircuit1<C1, C2, GC2>
 54where
 55    C1: CurveGroup,
 56    C2: CurveGroup,
 57    GC2: CurveVar<C2, CF2<C2>>,
 58{
 59    _c1: PhantomData<C1>,
 60    _c2: PhantomData<C2>,
 61    _gc2: PhantomData<GC2>,
 62
 63    /// E vector's length of the Nova instance witness
 64    pub E_len: usize,
 65    /// E vector's length of the CycleFold instance witness
 66    pub cf_E_len: usize,
 67    /// R1CS of the Augmented Function circuit
 68    pub r1cs: R1CS<C1::ScalarField>,
 69    pub poseidon_config: PoseidonConfig<CF1<C1>>,
 70    /// public params hash
 71    pub pp_hash: Option<C1::ScalarField>,
 72    pub i: Option<CF1<C1>>,
 73    /// initial state
 74    pub z_0: Option<Vec<C1::ScalarField>>,
 75    /// current i-th state
 76    pub z_i: Option<Vec<C1::ScalarField>>,
 77    /// Nova instances
 78    pub u_i: Option<CommittedInstance<C1>>,
 79    pub w_i: Option<Witness<C1>>,
 80    pub U_i: Option<CommittedInstance<C1>>,
 81    pub W_i: Option<Witness<C1>>,
 82    pub U_i1: Option<CommittedInstance<C1>>,
 83    pub W_i1: Option<Witness<C1>>,
 84    pub cmT: Option<C1>,
 85    pub r: Option<C1::ScalarField>,
 86    /// CycleFold running instance
 87    pub cf_U_i: Option<CycleFoldCommittedInstance<C2>>,
 88
 89    /// Commitment Scheme challenges
 90    pub cs_c_W: Option<C1::ScalarField>,
 91    pub cs_c_E: Option<C1::ScalarField>,
 92    /// Evaluations of the committed polynomials at the challenge
 93    pub eval_W: Option<C1::ScalarField>,
 94    pub eval_E: Option<C1::ScalarField>,
 95}
 96impl<C1, C2, GC2> DeciderCircuit1<C1, C2, GC2>
 97where
 98    C1: CurveGroup,
 99    <C1 as CurveGroup>::BaseField: PrimeField,
100    <C1 as Group>::ScalarField: Absorb,
101    C2: CurveGroup,
102    GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
103    for<'b> &'b GC2: GroupOpsBounds<'b, C2, GC2>,
104{
105    pub fn from_nova<GC1, CS1, CS2, const H: bool, FC: FCircuit<C1::ScalarField>>(
106        nova: Nova<C1, GC1, C2, GC2, FC, CS1, CS2, H>,
107    ) -> Result<Self, Error>
108    where
109        C2: CurveGroup,
110        GC1: CurveVar<C1, CF2<C1>> + ToConstraintFieldGadget<CF2<C1>>,
111        GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
112        CS1: CommitmentScheme<C1, H>,
113        CS2: CommitmentScheme<C2, H>,
114    {
115        let mut transcript = PoseidonSponge::<C1::ScalarField>::new(&nova.poseidon_config);
116        // pp_hash is absorbed to transcript at the NIFS::prove call
117
118        // compute the U_{i+1}, W_{i+1}
119        let (W_i1, U_i1, cmT, r_bits) = NIFS::<C1, CS1, PoseidonSponge<C1::ScalarField>, H>::prove(
120            &nova.cs_pp,
121            &nova.r1cs.clone(),
122            &mut transcript,
123            nova.pp_hash,
124            &nova.W_i,
125            &nova.U_i,
126            &nova.w_i,
127            &nova.u_i,
128        )?;
129        let r_Fr = C1::ScalarField::from_bigint(BigInteger::from_bits_le(&r_bits))
130            .ok_or(Error::OutOfBounds)?;
131
132        // compute the commitment scheme challenges used as inputs in the circuit
133        let (cs_challenge_W, cs_challenge_E) =
134            KZGChallengesGadget::<C1>::get_challenges_native(&mut transcript, U_i1.clone());
135
136        // get evals of the committed polys at the challenges
137        let mut W = W_i1.W.clone();
138        W.extend(
139            std::iter::repeat(C1::ScalarField::zero())
140                .take(W_i1.W.len().next_power_of_two() - W_i1.W.len()),
141        );
142        let mut E = W_i1.E.clone();
143        E.extend(
144            std::iter::repeat(C1::ScalarField::zero())
145                .take(W_i1.E.len().next_power_of_two() - W_i1.E.len()),
146        );
147        let p_W = poly_from_vec(W.to_vec())?;
148        let eval_W = p_W.evaluate(&cs_challenge_W);
149        let p_E = poly_from_vec(E.to_vec())?;
150        let eval_E = p_E.evaluate(&cs_challenge_E);
151
152        Ok(Self {
153            _c1: PhantomData,
154            _c2: PhantomData,
155            _gc2: PhantomData,
156
157            E_len: nova.W_i.E.len(),
158            cf_E_len: nova.cf_W_i.E.len(),
159            r1cs: nova.r1cs,
160            poseidon_config: nova.poseidon_config,
161            pp_hash: Some(nova.pp_hash),
162            i: Some(nova.i),
163            z_0: Some(nova.z_0),
164            z_i: Some(nova.z_i),
165            u_i: Some(nova.u_i),
166            w_i: Some(nova.w_i),
167            U_i: Some(nova.U_i),
168            W_i: Some(nova.W_i),
169            U_i1: Some(U_i1),
170            W_i1: Some(W_i1),
171            cmT: Some(cmT),
172            r: Some(r_Fr),
173            cf_U_i: Some(nova.cf_U_i),
174            cs_c_W: Some(cs_challenge_W),
175            cs_c_E: Some(cs_challenge_E),
176            eval_W: Some(eval_W),
177            eval_E: Some(eval_E),
178        })
179    }
180}
181
182impl<C1, C2, GC2> ConstraintSynthesizer<CF1<C1>> for DeciderCircuit1<C1, C2, GC2>
183where
184    C1: CurveGroup,
185    <C1 as CurveGroup>::BaseField: PrimeField,
186    <C1 as Group>::ScalarField: Absorb,
187    C2: CurveGroup,
188    <C2 as CurveGroup>::BaseField: PrimeField,
189    <C2 as Group>::ScalarField: Absorb,
190    C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
191    GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
192    for<'b> &'b GC2: GroupOpsBounds<'b, C2, GC2>,
193{
194    fn generate_constraints(self, cs: ConstraintSystemRef<CF1<C1>>) -> Result<(), SynthesisError> {
195        let r1cs =
196            R1CSVar::<C1::ScalarField, CF1<C1>, FpVar<CF1<C1>>>::new_witness(cs.clone(), || {
197                Ok(self.r1cs.clone())
198            })?;
199
200        let pp_hash = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
201            Ok(self.pp_hash.unwrap_or_else(CF1::<C1>::zero))
202        })?;
203        let i =
204            FpVar::<CF1<C1>>::new_input(cs.clone(), || Ok(self.i.unwrap_or_else(CF1::<C1>::zero)))?;
205        let z_0 = Vec::<FpVar<CF1<C1>>>::new_input(cs.clone(), || {
206            Ok(self.z_0.unwrap_or(vec![CF1::<C1>::zero()]))
207        })?;
208        let z_i = Vec::<FpVar<CF1<C1>>>::new_input(cs.clone(), || {
209            Ok(self.z_i.unwrap_or(vec![CF1::<C1>::zero()]))
210        })?;
211
212        let u_dummy_native = CommittedInstance::<C1>::dummy(&self.r1cs);
213        let w_dummy_native = Witness::<C1>::dummy(&self.r1cs);
214
215        let u_i = CommittedInstanceVar::<C1>::new_witness(cs.clone(), || {
216            Ok(self.u_i.unwrap_or(u_dummy_native.clone()))
217        })?;
218        let U_i = CommittedInstanceVar::<C1>::new_witness(cs.clone(), || {
219            Ok(self.U_i.unwrap_or(u_dummy_native.clone()))
220        })?;
221        // here (U_i1, W_i1) = NIFS.P( (U_i,W_i), (u_i,w_i))
222        let U_i1 = CommittedInstanceVar::<C1>::new_input(cs.clone(), || {
223            Ok(self.U_i1.unwrap_or(u_dummy_native.clone()))
224        })?;
225        let W_i1 = WitnessVar::<C1>::new_witness(cs.clone(), || {
226            Ok(self.W_i1.unwrap_or(w_dummy_native.clone()))
227        })?;
228
229        // allocate the inputs for the check 6
230        let cs_c_W = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
231            Ok(self.cs_c_W.unwrap_or_else(CF1::<C1>::zero))
232        })?;
233        let cs_c_E = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
234            Ok(self.cs_c_E.unwrap_or_else(CF1::<C1>::zero))
235        })?;
236        let eval_W = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
237            Ok(self.eval_W.unwrap_or_else(CF1::<C1>::zero))
238        })?;
239        let eval_E = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
240            Ok(self.eval_E.unwrap_or_else(CF1::<C1>::zero))
241        })?;
242
243        // `sponge` is for digest computation.
244        let sponge = PoseidonSpongeVar::<C1::ScalarField>::new(cs.clone(), &self.poseidon_config);
245        // `transcript` is for challenge generation.
246        let mut transcript = sponge.clone();
247        // notice that the `pp_hash` is absorbed inside the ChallengeGadget::get_challenge_gadget call
248
249        // 2. u_i.cmE==cm(0), u_i.u==1
250        // Here zero is the x & y coordinates of the zero point affine representation.
251        let zero = NonNativeUintVar::new_constant(cs.clone(), C1::BaseField::zero())?;
252        u_i.cmE.x.enforce_equal_unaligned(&zero)?;
253        u_i.cmE.y.enforce_equal_unaligned(&zero)?;
254        (u_i.u.is_one()?).enforce_equal(&Boolean::TRUE)?;
255
256        // 3.a u_i.x[0] == H(i, z_0, z_i, U_i)
257        let (u_i_x, U_i_vec) = U_i.clone().hash(&sponge, &pp_hash, &i, &z_0, &z_i)?;
258        (u_i.x[0]).enforce_equal(&u_i_x)?;
259
260        // 3.b u_i.x[1] == H(cf_U_i)
261        let cf_u_dummy_native =
262            CycleFoldCommittedInstance::<C2>::dummy(NovaCycleFoldConfig::<C1>::IO_LEN);
263        let cf_U_i = CycleFoldCommittedInstanceVar::<C2, GC2>::new_input(cs.clone(), || {
264            Ok(self.cf_U_i.unwrap_or_else(|| cf_u_dummy_native.clone()))
265        })?;
266        let (cf_u_i_x, _) = cf_U_i.clone().hash(&sponge, pp_hash.clone())?;
267        (u_i.x[1]).enforce_equal(&cf_u_i_x)?;
268
269        // 4. check RelaxedR1CS of U_{i+1}
270        let z_U1: Vec<FpVar<CF1<C1>>> =
271            [vec![U_i1.u.clone()], U_i1.x.to_vec(), W_i1.W.to_vec()].concat();
272        RelaxedR1CSGadget::check_native(r1cs, W_i1.E.clone(), U_i1.u.clone(), z_U1)?;
273
274        // 1.1.a, 5.1 compute NIFS.V and Commitment Scheme challenges.
275        // We need to ensure the order of challenge generation is the same as
276        // the native counterpart, so we first compute the challenges here and
277        // do the actual checks later.
278        let cmT =
279            NonNativeAffineVar::new_input(cs.clone(), || Ok(self.cmT.unwrap_or_else(C1::zero)))?;
280        let r_bits = ChallengeGadget::<C1, CommittedInstance<C1>>::get_challenge_gadget(
281            &mut transcript,
282            pp_hash,
283            U_i_vec,
284            u_i.clone(),
285            Some(cmT.clone()),
286        )?;
287        // 5.1.
288        let (incircuit_c_W, incircuit_c_E) =
289            KZGChallengesGadget::<C1>::get_challenges_gadget(&mut transcript, U_i1.clone())?;
290        incircuit_c_W.enforce_equal(&cs_c_W)?;
291        incircuit_c_E.enforce_equal(&cs_c_E)?;
292
293        // 5.2. check eval_W==p_W(c_W) and eval_E==p_E(c_E)
294        let incircuit_eval_W = evaluate_gadget::<CF1<C1>>(W_i1.W, incircuit_c_W)?;
295        let incircuit_eval_E = evaluate_gadget::<CF1<C1>>(W_i1.E, incircuit_c_E)?;
296        incircuit_eval_W.enforce_equal(&eval_W)?;
297        incircuit_eval_E.enforce_equal(&eval_E)?;
298
299        // 1.1.b check that the NIFS.V challenge matches the one from the public input (so we avoid
300        //   the verifier computing it)
301        let r_Fr = Boolean::le_bits_to_fp_var(&r_bits)?;
302        // check that the in-circuit computed r is equal to the inputted r
303        let r =
304            FpVar::<CF1<C1>>::new_input(cs.clone(), || Ok(self.r.unwrap_or_else(CF1::<C1>::zero)))?;
305        r_Fr.enforce_equal(&r)?;
306
307        Ok(())
308    }
309}
310
311/// Circuit that implements part of the in-circuit checks needed for the offchain verification over
312/// the Curve1's BaseField (=Curve2's ScalarField).
313#[derive(Clone, Debug)]
314pub struct DeciderCircuit2<C1, GC1, C2>
315where
316    C1: CurveGroup,
317    C2: CurveGroup,
318{
319    _c1: PhantomData<C1>,
320    _gc1: PhantomData<GC1>,
321    _c2: PhantomData<C2>,
322
323    /// E vector's length of the CycleFold instance witness
324    pub cf_E_len: usize,
325    /// R1CS of the CycleFold circuit
326    pub cf_r1cs: R1CS<C2::ScalarField>,
327    pub poseidon_config: PoseidonConfig<CF1<C2>>,
328    /// public params hash
329    pub pp_hash: Option<C2::ScalarField>,
330
331    /// CycleFold running instance. Notice that here we use Nova's CommittedInstance (instead of
332    /// CycleFoldCommittedInstance), since we are over C2::Fr, so that the CycleFold instances can
333    /// be computed natively
334    pub cf_U_i: Option<CommittedInstance<C2>>,
335    pub cf_W_i: Option<CycleFoldWitness<C2>>,
336    /// Commitment Scheme challenges
337    pub cs_c_W: Option<C2::ScalarField>,
338    pub cs_c_E: Option<C2::ScalarField>,
339    /// Evaluations of the committed polynomials at the challenge
340    pub eval_W: Option<C2::ScalarField>,
341    pub eval_E: Option<C2::ScalarField>,
342}
343impl<C1, GC1, C2> DeciderCircuit2<C1, GC1, C2>
344where
345    C1: CurveGroup,
346    C2: CurveGroup,
347    <C1 as CurveGroup>::BaseField: PrimeField,
348    <C1 as Group>::ScalarField: Absorb,
349    <C2 as CurveGroup>::BaseField: PrimeField,
350    <C2 as Group>::ScalarField: Absorb,
351    GC1: CurveVar<C1, CF2<C1>> + ToConstraintFieldGadget<CF2<C1>>,
352{
353    pub fn from_nova<GC2, CS1, CS2, const H: bool, FC: FCircuit<C1::ScalarField>>(
354        nova: Nova<C1, GC1, C2, GC2, FC, CS1, CS2, H>,
355    ) -> Result<Self, Error>
356    where
357        GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
358        CS1: CommitmentScheme<C1, H>,
359        CS2: CommitmentScheme<C2, H>,
360    {
361        // compute the Commitment Scheme challenges of the CycleFold instance commitments, used as
362        // inputs in the circuit
363        let poseidon_config =
364            crate::transcript::poseidon::poseidon_canonical_config::<C2::ScalarField>();
365        let mut transcript = PoseidonSponge::<C2::ScalarField>::new(&poseidon_config);
366        let pp_hash_Fq =
367            C2::ScalarField::from_le_bytes_mod_order(&nova.pp_hash.into_bigint().to_bytes_le());
368        transcript.absorb(&pp_hash_Fq);
369
370        let (cs_challenge_W, cs_challenge_E) =
371            KZGChallengesGadget::<C2>::get_challenges_native(&mut transcript, nova.cf_U_i.clone());
372
373        // get evals of the committed polynomials at the challenge
374        let mut W = nova.cf_W_i.W.clone();
375        W.extend(
376            std::iter::repeat(C2::ScalarField::zero())
377                .take(nova.cf_W_i.W.len().next_power_of_two() - nova.cf_W_i.W.len()),
378        );
379        let mut E = nova.cf_W_i.E.clone();
380        E.extend(
381            std::iter::repeat(C2::ScalarField::zero())
382                .take(nova.cf_W_i.E.len().next_power_of_two() - nova.cf_W_i.E.len()),
383        );
384        let p_W = poly_from_vec(W.to_vec())?;
385        let eval_W = p_W.evaluate(&cs_challenge_W);
386        let p_E = poly_from_vec(E.to_vec())?;
387        let eval_E = p_E.evaluate(&cs_challenge_E);
388
389        Ok(Self {
390            _c1: PhantomData,
391            _gc1: PhantomData,
392            _c2: PhantomData,
393
394            cf_E_len: nova.cf_W_i.E.len(),
395            cf_r1cs: nova.cf_r1cs,
396            poseidon_config,
397            pp_hash: Some(pp_hash_Fq),
398
399            cf_U_i: Some(nova.cf_U_i),
400            cf_W_i: Some(nova.cf_W_i),
401
402            // CycleFold instance commitments challenges
403            cs_c_W: Some(cs_challenge_W),
404            cs_c_E: Some(cs_challenge_E),
405            eval_W: Some(eval_W),
406            eval_E: Some(eval_E),
407        })
408    }
409}
410
411impl<C1, GC1, C2> ConstraintSynthesizer<CF1<C2>> for DeciderCircuit2<C1, GC1, C2>
412where
413    C1: CurveGroup,
414    C2: CurveGroup,
415    <C1 as CurveGroup>::BaseField: PrimeField,
416    <C2 as CurveGroup>::BaseField: PrimeField,
417    <C1 as Group>::ScalarField: Absorb,
418    <C2 as Group>::ScalarField: Absorb,
419    C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
420    GC1: CurveVar<C1, CF2<C1>> + ToConstraintFieldGadget<CF2<C1>>,
421    for<'a> &'a GC1: GroupOpsBounds<'a, C1, GC1>,
422{
423    fn generate_constraints(self, cs: ConstraintSystemRef<CF1<C2>>) -> Result<(), SynthesisError> {
424        let pp_hash = FpVar::<CF1<C2>>::new_input(cs.clone(), || {
425            Ok(self.pp_hash.unwrap_or_else(CF1::<C2>::zero))
426        })?;
427
428        let cf_u_dummy_native = CommittedInstance::<C2>::dummy(&self.cf_r1cs);
429        let w_dummy_native = Witness::<C2>::dummy(&self.cf_r1cs);
430        let cf_U_i = CommittedInstanceVar::<C2>::new_input(cs.clone(), || {
431            Ok(self.cf_U_i.unwrap_or_else(|| cf_u_dummy_native.clone()))
432        })?;
433        let cf_W_i = WitnessVar::<C2>::new_witness(cs.clone(), || {
434            Ok(self.cf_W_i.unwrap_or(w_dummy_native.clone()))
435        })?;
436
437        let cf_r1cs =
438            R1CSVar::<C2::ScalarField, CF1<C2>, FpVar<CF1<C2>>>::new_witness(cs.clone(), || {
439                Ok(self.cf_r1cs.clone())
440            })?;
441
442        // 6. check RelaxedR1CS of cf_U_i
443        let cf_z_U = [vec![cf_U_i.u.clone()], cf_U_i.x.to_vec(), cf_W_i.W.to_vec()].concat();
444        RelaxedR1CSGadget::check_native(cf_r1cs, cf_W_i.E.clone(), cf_U_i.u.clone(), cf_z_U)?;
445
446        // `transcript` is for challenge generation.
447        let mut transcript =
448            PoseidonSpongeVar::<C2::ScalarField>::new(cs.clone(), &self.poseidon_config);
449        transcript.absorb(&pp_hash)?;
450
451        // allocate the inputs for the check 7.1
452        let cs_c_W = FpVar::<CF1<C2>>::new_input(cs.clone(), || {
453            Ok(self.cs_c_W.unwrap_or_else(CF1::<C2>::zero))
454        })?;
455        let cs_c_E = FpVar::<CF1<C2>>::new_input(cs.clone(), || {
456            Ok(self.cs_c_E.unwrap_or_else(CF1::<C2>::zero))
457        })?;
458        // allocate the inputs for the check 7.2
459        let eval_W = FpVar::<CF1<C2>>::new_input(cs.clone(), || {
460            Ok(self.eval_W.unwrap_or_else(CF1::<C2>::zero))
461        })?;
462        let eval_E = FpVar::<CF1<C2>>::new_input(cs.clone(), || {
463            Ok(self.eval_E.unwrap_or_else(CF1::<C2>::zero))
464        })?;
465
466        // 7.1. check the commitment scheme challenges correct computation
467        let (incircuit_c_W, incircuit_c_E) =
468            KZGChallengesGadget::<C2>::get_challenges_gadget(&mut transcript, cf_U_i.clone())?;
469        incircuit_c_W.enforce_equal(&cs_c_W)?;
470        incircuit_c_E.enforce_equal(&cs_c_E)?;
471
472        // 7.2. check eval_W==p_W(c_W) and eval_E==p_E(c_E)
473        let incircuit_eval_W = evaluate_gadget::<CF1<C2>>(cf_W_i.W, incircuit_c_W)?;
474        let incircuit_eval_E = evaluate_gadget::<CF1<C2>>(cf_W_i.E, incircuit_c_E)?;
475        incircuit_eval_W.enforce_equal(&eval_W)?;
476        incircuit_eval_E.enforce_equal(&eval_E)?;
477
478        Ok(())
479    }
480}
481
482#[cfg(test)]
483pub mod tests {
484    use ark_pallas::{constraints::GVar, Fq, Fr, Projective};
485    use ark_relations::r1cs::ConstraintSystem;
486    use ark_vesta::{constraints::GVar as GVar2, Projective as Projective2};
487
488    use super::*;
489    use crate::commitment::pedersen::Pedersen;
490    use crate::folding::nova::PreprocessorParam;
491    use crate::frontend::utils::CubicFCircuit;
492    use crate::transcript::poseidon::poseidon_canonical_config;
493    use crate::FoldingScheme;
494
495    #[test]
496    fn test_decider_circuits() {
497        let mut rng = ark_std::test_rng();
498        let poseidon_config = poseidon_canonical_config::<Fr>();
499
500        let F_circuit = CubicFCircuit::<Fr>::new(()).unwrap();
501        let z_0 = vec![Fr::from(3_u32)];
502
503        type N = Nova<
504            Projective,
505            GVar,
506            Projective2,
507            GVar2,
508            CubicFCircuit<Fr>,
509            Pedersen<Projective>,
510            Pedersen<Projective2>,
511            false,
512        >;
513
514        let prep_param = PreprocessorParam::<
515            Projective,
516            Projective2,
517            CubicFCircuit<Fr>,
518            Pedersen<Projective>,
519            Pedersen<Projective2>,
520            false,
521        >::new(poseidon_config, F_circuit);
522        let nova_params = N::preprocess(&mut rng, &prep_param).unwrap();
523
524        // generate a Nova instance and do a step of it
525        let mut nova = N::init(&nova_params, F_circuit, z_0.clone()).unwrap();
526        nova.prove_step(&mut rng, vec![], None).unwrap();
527        // verify the IVC
528        let ivc_proof = nova.ivc_proof();
529        N::verify(nova_params.1, ivc_proof).unwrap();
530
531        // load the DeciderCircuit 1 & 2 from the Nova instance
532        let decider_circuit1 =
533            DeciderCircuit1::<Projective, Projective2, GVar2>::from_nova(nova.clone()).unwrap();
534        let decider_circuit2 =
535            DeciderCircuit2::<Projective, GVar, Projective2>::from_nova(nova).unwrap();
536
537        // generate the constraints of both circuits and check that are satisfied by the inputs
538        let cs1 = ConstraintSystem::<Fr>::new_ref();
539        decider_circuit1.generate_constraints(cs1.clone()).unwrap();
540        assert!(cs1.is_satisfied().unwrap());
541        let cs2 = ConstraintSystem::<Fq>::new_ref();
542        decider_circuit2.generate_constraints(cs2.clone()).unwrap();
543        assert!(cs2.is_satisfied().unwrap());
544    }
545}