arnaucube
arnaucube/sonobePublic Self-hosted repository
sonobe/folding-schemes/src/folding/nova/decider_eth_circuit.rs
folding-schemes/src/folding/nova/decider_eth_circuit.rsRaw
  1/// This file implements the onchain (Ethereum's EVM) decider circuit. For non-ethereum use cases,
  2/// other more efficient approaches can be used.
  3use ark_crypto_primitives::crh::poseidon::constraints::CRHParametersVar;
  4use ark_crypto_primitives::sponge::{poseidon::PoseidonConfig, Absorb};
  5use ark_ec::{CurveGroup, Group};
  6use ark_ff::{BigInteger, PrimeField};
  7use ark_poly::Polynomial;
  8use ark_r1cs_std::{
  9    alloc::{AllocVar, AllocationMode},
 10    boolean::Boolean,
 11    eq::EqGadget,
 12    fields::{fp::FpVar, FieldVar},
 13    groups::GroupOpsBounds,
 14    poly::{domain::Radix2DomainVar, evaluations::univariate::EvaluationsVar},
 15    prelude::CurveVar,
 16    ToConstraintFieldGadget,
 17};
 18use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystemRef, Namespace, SynthesisError};
 19use ark_std::{log2, Zero};
 20use core::{borrow::Borrow, marker::PhantomData};
 21
 22use super::{circuits::ChallengeGadget, nifs::NIFS};
 23use crate::arith::r1cs::R1CS;
 24use crate::commitment::{pedersen::Params as PedersenParams, CommitmentScheme};
 25use crate::folding::circuits::{
 26    nonnative::{
 27        affine::{nonnative_affine_to_field_elements, NonNativeAffineVar},
 28        uint::NonNativeUintVar,
 29    },
 30    CF1, CF2,
 31};
 32use crate::folding::nova::{circuits::CommittedInstanceVar, CommittedInstance, Nova, Witness};
 33use crate::frontend::FCircuit;
 34use crate::transcript::{
 35    poseidon::{PoseidonTranscript, PoseidonTranscriptVar},
 36    Transcript, TranscriptVar,
 37};
 38use crate::utils::{
 39    gadgets::{MatrixGadget, SparseMatrixVar, VectorGadget},
 40    vec::poly_from_vec,
 41};
 42use crate::Error;
 43
 44#[derive(Debug, Clone)]
 45pub struct RelaxedR1CSGadget {}
 46impl RelaxedR1CSGadget {
 47    /// performs the RelaxedR1CS check for native variables (Az∘Bz==uCz+E)
 48    pub fn check_native<F: PrimeField>(
 49        r1cs: R1CSVar<F, F, FpVar<F>>,
 50        E: Vec<FpVar<F>>,
 51        u: FpVar<F>,
 52        z: Vec<FpVar<F>>,
 53    ) -> Result<(), SynthesisError> {
 54        let Az = r1cs.A.mul_vector(&z)?;
 55        let Bz = r1cs.B.mul_vector(&z)?;
 56        let Cz = r1cs.C.mul_vector(&z)?;
 57        let uCzE = Cz.mul_scalar(&u)?.add(&E)?;
 58        let AzBz = Az.hadamard(&Bz)?;
 59        AzBz.enforce_equal(&uCzE)?;
 60        Ok(())
 61    }
 62
 63    /// performs the RelaxedR1CS check for non-native variables (Az∘Bz==uCz+E)
 64    pub fn check_nonnative<F: PrimeField, CF: PrimeField>(
 65        r1cs: R1CSVar<F, CF, NonNativeUintVar<CF>>,
 66        E: Vec<NonNativeUintVar<CF>>,
 67        u: NonNativeUintVar<CF>,
 68        z: Vec<NonNativeUintVar<CF>>,
 69    ) -> Result<(), SynthesisError> {
 70        // First we do addition and multiplication without mod F's order
 71        let Az = r1cs.A.mul_vector(&z)?;
 72        let Bz = r1cs.B.mul_vector(&z)?;
 73        let Cz = r1cs.C.mul_vector(&z)?;
 74        let uCzE = Cz.mul_scalar(&u)?.add(&E)?;
 75        let AzBz = Az.hadamard(&Bz)?;
 76
 77        // Then we compare the results by checking if they are congruent
 78        // modulo the field order
 79        AzBz.into_iter()
 80            .zip(uCzE)
 81            .try_for_each(|(a, b)| a.enforce_congruent::<F>(&b))
 82    }
 83}
 84
 85#[derive(Debug, Clone)]
 86pub struct R1CSVar<F: PrimeField, CF: PrimeField, FV: AllocVar<F, CF>> {
 87    _f: PhantomData<F>,
 88    _cf: PhantomData<CF>,
 89    _fv: PhantomData<FV>,
 90    pub A: SparseMatrixVar<F, CF, FV>,
 91    pub B: SparseMatrixVar<F, CF, FV>,
 92    pub C: SparseMatrixVar<F, CF, FV>,
 93}
 94
 95impl<F, CF, FV> AllocVar<R1CS<F>, CF> for R1CSVar<F, CF, FV>
 96where
 97    F: PrimeField,
 98    CF: PrimeField,
 99    FV: AllocVar<F, CF>,
100{
101    fn new_variable<T: Borrow<R1CS<F>>>(
102        cs: impl Into<Namespace<CF>>,
103        f: impl FnOnce() -> Result<T, SynthesisError>,
104        _mode: AllocationMode,
105    ) -> Result<Self, SynthesisError> {
106        f().and_then(|val| {
107            let cs = cs.into();
108
109            let A = SparseMatrixVar::<F, CF, FV>::new_constant(cs.clone(), &val.borrow().A)?;
110            let B = SparseMatrixVar::<F, CF, FV>::new_constant(cs.clone(), &val.borrow().B)?;
111            let C = SparseMatrixVar::<F, CF, FV>::new_constant(cs.clone(), &val.borrow().C)?;
112
113            Ok(Self {
114                _f: PhantomData,
115                _cf: PhantomData,
116                _fv: PhantomData,
117                A,
118                B,
119                C,
120            })
121        })
122    }
123}
124
125/// In-circuit representation of the Witness associated to the CommittedInstance.
126#[derive(Debug, Clone)]
127pub struct WitnessVar<C: CurveGroup> {
128    pub E: Vec<FpVar<C::ScalarField>>,
129    pub rE: FpVar<C::ScalarField>,
130    pub W: Vec<FpVar<C::ScalarField>>,
131    pub rW: FpVar<C::ScalarField>,
132}
133
134impl<C> AllocVar<Witness<C>, CF1<C>> for WitnessVar<C>
135where
136    C: CurveGroup,
137    <C as ark_ec::CurveGroup>::BaseField: PrimeField,
138{
139    fn new_variable<T: Borrow<Witness<C>>>(
140        cs: impl Into<Namespace<CF1<C>>>,
141        f: impl FnOnce() -> Result<T, SynthesisError>,
142        mode: AllocationMode,
143    ) -> Result<Self, SynthesisError> {
144        f().and_then(|val| {
145            let cs = cs.into();
146
147            let E: Vec<FpVar<C::ScalarField>> =
148                Vec::new_variable(cs.clone(), || Ok(val.borrow().E.clone()), mode)?;
149            let rE =
150                FpVar::<C::ScalarField>::new_variable(cs.clone(), || Ok(val.borrow().rE), mode)?;
151
152            let W: Vec<FpVar<C::ScalarField>> =
153                Vec::new_variable(cs.clone(), || Ok(val.borrow().W.clone()), mode)?;
154            let rW =
155                FpVar::<C::ScalarField>::new_variable(cs.clone(), || Ok(val.borrow().rW), mode)?;
156
157            Ok(Self { E, rE, W, rW })
158        })
159    }
160}
161
162/// In-circuit representation of the Witness associated to the CommittedInstance, but with
163/// non-native representation, since it is used to represent the CycleFold witness.
164#[derive(Debug, Clone)]
165pub struct CycleFoldWitnessVar<C: CurveGroup> {
166    pub E: Vec<NonNativeUintVar<CF2<C>>>,
167    pub rE: NonNativeUintVar<CF2<C>>,
168    pub W: Vec<NonNativeUintVar<CF2<C>>>,
169    pub rW: NonNativeUintVar<CF2<C>>,
170}
171
172impl<C> AllocVar<Witness<C>, CF2<C>> for CycleFoldWitnessVar<C>
173where
174    C: CurveGroup,
175    <C as ark_ec::CurveGroup>::BaseField: PrimeField,
176{
177    fn new_variable<T: Borrow<Witness<C>>>(
178        cs: impl Into<Namespace<CF2<C>>>,
179        f: impl FnOnce() -> Result<T, SynthesisError>,
180        mode: AllocationMode,
181    ) -> Result<Self, SynthesisError> {
182        f().and_then(|val| {
183            let cs = cs.into();
184
185            let E = Vec::new_variable(cs.clone(), || Ok(val.borrow().E.clone()), mode)?;
186            let rE = NonNativeUintVar::new_variable(cs.clone(), || Ok(val.borrow().rE), mode)?;
187
188            let W = Vec::new_variable(cs.clone(), || Ok(val.borrow().W.clone()), mode)?;
189            let rW = NonNativeUintVar::new_variable(cs.clone(), || Ok(val.borrow().rW), mode)?;
190
191            Ok(Self { E, rE, W, rW })
192        })
193    }
194}
195
196/// Circuit that implements the in-circuit checks needed for the onchain (Ethereum's EVM)
197/// verification.
198#[derive(Clone, Debug)]
199pub struct DeciderEthCircuit<C1, GC1, C2, GC2, CS1, CS2>
200where
201    C1: CurveGroup,
202    GC1: CurveVar<C1, CF2<C1>>,
203    C2: CurveGroup,
204    GC2: CurveVar<C2, CF2<C2>>,
205    CS1: CommitmentScheme<C1>,
206    CS2: CommitmentScheme<C2>,
207{
208    _c1: PhantomData<C1>,
209    _gc1: PhantomData<GC1>,
210    _c2: PhantomData<C2>,
211    _gc2: PhantomData<GC2>,
212    _cs1: PhantomData<CS1>,
213    _cs2: PhantomData<CS2>,
214
215    /// E vector's length of the Nova instance witness
216    pub E_len: usize,
217    /// E vector's length of the CycleFold instance witness
218    pub cf_E_len: usize,
219    /// R1CS of the Augmented Function circuit
220    pub r1cs: R1CS<C1::ScalarField>,
221    /// R1CS of the CycleFold circuit
222    pub cf_r1cs: R1CS<C2::ScalarField>,
223    /// CycleFold PedersenParams over C2
224    pub cf_pedersen_params: PedersenParams<C2>,
225    pub poseidon_config: PoseidonConfig<CF1<C1>>,
226    /// public params hash
227    pub pp_hash: Option<C1::ScalarField>,
228    pub i: Option<CF1<C1>>,
229    /// initial state
230    pub z_0: Option<Vec<C1::ScalarField>>,
231    /// current i-th state
232    pub z_i: Option<Vec<C1::ScalarField>>,
233    /// Nova instances
234    pub u_i: Option<CommittedInstance<C1>>,
235    pub w_i: Option<Witness<C1>>,
236    pub U_i: Option<CommittedInstance<C1>>,
237    pub W_i: Option<Witness<C1>>,
238    pub U_i1: Option<CommittedInstance<C1>>,
239    pub W_i1: Option<Witness<C1>>,
240    pub cmT: Option<C1>,
241    pub r: Option<C1::ScalarField>,
242    /// CycleFold running instance
243    pub cf_U_i: Option<CommittedInstance<C2>>,
244    pub cf_W_i: Option<Witness<C2>>,
245
246    /// KZG challenges
247    pub kzg_c_W: Option<C1::ScalarField>,
248    pub kzg_c_E: Option<C1::ScalarField>,
249    pub eval_W: Option<C1::ScalarField>,
250    pub eval_E: Option<C1::ScalarField>,
251}
252impl<C1, GC1, C2, GC2, CS1, CS2> DeciderEthCircuit<C1, GC1, C2, GC2, CS1, CS2>
253where
254    C1: CurveGroup,
255    C2: CurveGroup,
256    GC1: CurveVar<C1, CF2<C1>> + ToConstraintFieldGadget<CF2<C1>>,
257    GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
258    CS1: CommitmentScheme<C1>,
259    // enforce that the CS2 is Pedersen commitment scheme, since we're at Ethereum's EVM decider
260    CS2: CommitmentScheme<C2, ProverParams = PedersenParams<C2>>,
261    <C1 as Group>::ScalarField: Absorb,
262    <C1 as CurveGroup>::BaseField: PrimeField,
263{
264    pub fn from_nova<FC: FCircuit<C1::ScalarField>>(
265        nova: Nova<C1, GC1, C2, GC2, FC, CS1, CS2>,
266    ) -> Result<Self, Error> {
267        // compute the U_{i+1}, W_{i+1}
268        let (T, cmT) = NIFS::<C1, CS1>::compute_cmT(
269            &nova.cs_pp,
270            &nova.r1cs.clone(),
271            &nova.w_i.clone(),
272            &nova.u_i.clone(),
273            &nova.W_i.clone(),
274            &nova.U_i.clone(),
275        )?;
276        let r_bits = ChallengeGadget::<C1>::get_challenge_native(
277            &nova.poseidon_config,
278            nova.pp_hash,
279            nova.U_i.clone(),
280            nova.u_i.clone(),
281            cmT,
282        )?;
283        let r_Fr = C1::ScalarField::from_bigint(BigInteger::from_bits_le(&r_bits))
284            .ok_or(Error::OutOfBounds)?;
285        let (W_i1, U_i1) = NIFS::<C1, CS1>::fold_instances(
286            r_Fr, &nova.W_i, &nova.U_i, &nova.w_i, &nova.u_i, &T, cmT,
287        )?;
288
289        // compute the KZG challenges used as inputs in the circuit
290        let (kzg_challenge_W, kzg_challenge_E) =
291            KZGChallengesGadget::<C1>::get_challenges_native(&nova.poseidon_config, U_i1.clone())?;
292
293        // get KZG evals
294        let mut W = W_i1.W.clone();
295        W.extend(
296            std::iter::repeat(C1::ScalarField::zero())
297                .take(W_i1.W.len().next_power_of_two() - W_i1.W.len()),
298        );
299        let mut E = W_i1.E.clone();
300        E.extend(
301            std::iter::repeat(C1::ScalarField::zero())
302                .take(W_i1.E.len().next_power_of_two() - W_i1.E.len()),
303        );
304        let p_W = poly_from_vec(W.to_vec())?;
305        let eval_W = p_W.evaluate(&kzg_challenge_W);
306        let p_E = poly_from_vec(E.to_vec())?;
307        let eval_E = p_E.evaluate(&kzg_challenge_E);
308
309        Ok(Self {
310            _c1: PhantomData,
311            _gc1: PhantomData,
312            _c2: PhantomData,
313            _gc2: PhantomData,
314            _cs1: PhantomData,
315            _cs2: PhantomData,
316
317            E_len: nova.W_i.E.len(),
318            cf_E_len: nova.cf_W_i.E.len(),
319            r1cs: nova.r1cs,
320            cf_r1cs: nova.cf_r1cs,
321            cf_pedersen_params: nova.cf_cs_pp,
322            poseidon_config: nova.poseidon_config,
323            pp_hash: Some(nova.pp_hash),
324            i: Some(nova.i),
325            z_0: Some(nova.z_0),
326            z_i: Some(nova.z_i),
327            u_i: Some(nova.u_i),
328            w_i: Some(nova.w_i),
329            U_i: Some(nova.U_i),
330            W_i: Some(nova.W_i),
331            U_i1: Some(U_i1),
332            W_i1: Some(W_i1),
333            cmT: Some(cmT),
334            r: Some(r_Fr),
335            cf_U_i: Some(nova.cf_U_i),
336            cf_W_i: Some(nova.cf_W_i),
337            kzg_c_W: Some(kzg_challenge_W),
338            kzg_c_E: Some(kzg_challenge_E),
339            eval_W: Some(eval_W),
340            eval_E: Some(eval_E),
341        })
342    }
343}
344
345impl<C1, GC1, C2, GC2, CS1, CS2> ConstraintSynthesizer<CF1<C1>>
346    for DeciderEthCircuit<C1, GC1, C2, GC2, CS1, CS2>
347where
348    C1: CurveGroup,
349    C2: CurveGroup,
350    GC1: CurveVar<C1, CF2<C1>>,
351    GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
352    CS1: CommitmentScheme<C1>,
353    CS2: CommitmentScheme<C2>,
354    <C1 as CurveGroup>::BaseField: PrimeField,
355    <C2 as CurveGroup>::BaseField: PrimeField,
356    <C1 as Group>::ScalarField: Absorb,
357    <C2 as Group>::ScalarField: Absorb,
358    C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
359    for<'b> &'b GC2: GroupOpsBounds<'b, C2, GC2>,
360{
361    fn generate_constraints(self, cs: ConstraintSystemRef<CF1<C1>>) -> Result<(), SynthesisError> {
362        let r1cs =
363            R1CSVar::<C1::ScalarField, CF1<C1>, FpVar<CF1<C1>>>::new_witness(cs.clone(), || {
364                Ok(self.r1cs.clone())
365            })?;
366
367        let pp_hash = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
368            Ok(self.pp_hash.unwrap_or_else(CF1::<C1>::zero))
369        })?;
370        let i =
371            FpVar::<CF1<C1>>::new_input(cs.clone(), || Ok(self.i.unwrap_or_else(CF1::<C1>::zero)))?;
372        let z_0 = Vec::<FpVar<CF1<C1>>>::new_input(cs.clone(), || {
373            Ok(self.z_0.unwrap_or(vec![CF1::<C1>::zero()]))
374        })?;
375        let z_i = Vec::<FpVar<CF1<C1>>>::new_input(cs.clone(), || {
376            Ok(self.z_i.unwrap_or(vec![CF1::<C1>::zero()]))
377        })?;
378
379        let u_dummy_native = CommittedInstance::<C1>::dummy(2);
380        let w_dummy_native = Witness::<C1>::new(
381            vec![C1::ScalarField::zero(); self.r1cs.A.n_cols - 3 /* (3=2+1, since u_i.x.len=2) */],
382            self.E_len,
383        );
384
385        let u_i = CommittedInstanceVar::<C1>::new_witness(cs.clone(), || {
386            Ok(self.u_i.unwrap_or(u_dummy_native.clone()))
387        })?;
388        let U_i = CommittedInstanceVar::<C1>::new_witness(cs.clone(), || {
389            Ok(self.U_i.unwrap_or(u_dummy_native.clone()))
390        })?;
391        // here (U_i1, W_i1) = NIFS.P( (U_i,W_i), (u_i,w_i))
392        let U_i1 = CommittedInstanceVar::<C1>::new_input(cs.clone(), || {
393            Ok(self.U_i1.unwrap_or(u_dummy_native.clone()))
394        })?;
395        let W_i1 = WitnessVar::<C1>::new_witness(cs.clone(), || {
396            Ok(self.W_i1.unwrap_or(w_dummy_native.clone()))
397        })?;
398
399        // allocate the inputs for the check 6
400        let kzg_c_W = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
401            Ok(self.kzg_c_W.unwrap_or_else(CF1::<C1>::zero))
402        })?;
403        let kzg_c_E = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
404            Ok(self.kzg_c_E.unwrap_or_else(CF1::<C1>::zero))
405        })?;
406        let _eval_W = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
407            Ok(self.eval_W.unwrap_or_else(CF1::<C1>::zero))
408        })?;
409        let _eval_E = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
410            Ok(self.eval_E.unwrap_or_else(CF1::<C1>::zero))
411        })?;
412
413        let crh_params = CRHParametersVar::<C1::ScalarField>::new_constant(
414            cs.clone(),
415            self.poseidon_config.clone(),
416        )?;
417
418        // 1. check RelaxedR1CS of U_{i+1}
419        let z_U1: Vec<FpVar<CF1<C1>>> =
420            [vec![U_i1.u.clone()], U_i1.x.to_vec(), W_i1.W.to_vec()].concat();
421        RelaxedR1CSGadget::check_native(r1cs, W_i1.E.clone(), U_i1.u.clone(), z_U1)?;
422
423        // 2. u_i.cmE==cm(0), u_i.u==1
424        // Here zero is the x & y coordinates of the zero point affine representation.
425        let zero = NonNativeUintVar::new_constant(cs.clone(), C1::BaseField::zero())?;
426        u_i.cmE.x.enforce_equal_unaligned(&zero)?;
427        u_i.cmE.y.enforce_equal_unaligned(&zero)?;
428        (u_i.u.is_one()?).enforce_equal(&Boolean::TRUE)?;
429
430        // 3.a u_i.x[0] == H(i, z_0, z_i, U_i)
431        let (u_i_x, U_i_vec) = U_i.clone().hash(
432            &crh_params,
433            pp_hash.clone(),
434            i.clone(),
435            z_0.clone(),
436            z_i.clone(),
437        )?;
438        (u_i.x[0]).enforce_equal(&u_i_x)?;
439
440        #[cfg(feature = "light-test")]
441        println!("[WARNING]: Running with the 'light-test' feature, skipping the big part of the DeciderEthCircuit.\n           Only for testing purposes.");
442
443        // The following two checks (and their respective allocations) are disabled for normal
444        // tests since they take several millions of constraints and would take several minutes
445        // (and RAM) to run the test. It is active by default, and not active only when
446        // 'light-test' feature is used.
447        #[cfg(not(feature = "light-test"))]
448        {
449            // imports here instead of at the top of the file, so we avoid having multiple
450            // `#[cfg(not(test))]`
451            use crate::commitment::pedersen::PedersenGadget;
452            use crate::folding::circuits::cyclefold::{CycleFoldCommittedInstanceVar, CF_IO_LEN};
453            use ark_r1cs_std::ToBitsGadget;
454
455            let cf_u_dummy_native = CommittedInstance::<C2>::dummy(CF_IO_LEN);
456            let w_dummy_native = Witness::<C2>::new(
457                vec![C2::ScalarField::zero(); self.cf_r1cs.A.n_cols - 1 - self.cf_r1cs.l],
458                self.cf_E_len,
459            );
460            let cf_U_i = CycleFoldCommittedInstanceVar::<C2, GC2>::new_witness(cs.clone(), || {
461                Ok(self.cf_U_i.unwrap_or_else(|| cf_u_dummy_native.clone()))
462            })?;
463            let cf_W_i = CycleFoldWitnessVar::<C2>::new_witness(cs.clone(), || {
464                Ok(self.cf_W_i.unwrap_or(w_dummy_native.clone()))
465            })?;
466
467            // 3.b u_i.x[1] == H(cf_U_i)
468            let (cf_u_i_x, _) = cf_U_i.clone().hash(&crh_params, pp_hash.clone())?;
469            (u_i.x[1]).enforce_equal(&cf_u_i_x)?;
470
471            // 4. check Pedersen commitments of cf_U_i.{cmE, cmW}
472            let H = GC2::new_constant(cs.clone(), self.cf_pedersen_params.h)?;
473            let G = Vec::<GC2>::new_constant(cs.clone(), self.cf_pedersen_params.generators)?;
474            let cf_W_i_E_bits: Result<Vec<Vec<Boolean<CF1<C1>>>>, SynthesisError> =
475                cf_W_i.E.iter().map(|E_i| E_i.to_bits_le()).collect();
476            let cf_W_i_W_bits: Result<Vec<Vec<Boolean<CF1<C1>>>>, SynthesisError> =
477                cf_W_i.W.iter().map(|W_i| W_i.to_bits_le()).collect();
478
479            let computed_cmE = PedersenGadget::<C2, GC2>::commit(
480                H.clone(),
481                G.clone(),
482                cf_W_i_E_bits?,
483                cf_W_i.rE.to_bits_le()?,
484            )?;
485            cf_U_i.cmE.enforce_equal(&computed_cmE)?;
486            let computed_cmW =
487                PedersenGadget::<C2, GC2>::commit(H, G, cf_W_i_W_bits?, cf_W_i.rW.to_bits_le()?)?;
488            cf_U_i.cmW.enforce_equal(&computed_cmW)?;
489
490            let cf_r1cs =
491                R1CSVar::<C1::BaseField, CF1<C1>, NonNativeUintVar<CF1<C1>>>::new_witness(
492                    cs.clone(),
493                    || Ok(self.cf_r1cs.clone()),
494                )?;
495
496            // 5. check RelaxedR1CS of cf_U_i
497            let cf_z_U = [vec![cf_U_i.u.clone()], cf_U_i.x.to_vec(), cf_W_i.W.to_vec()].concat();
498            RelaxedR1CSGadget::check_nonnative(cf_r1cs, cf_W_i.E, cf_U_i.u.clone(), cf_z_U)?;
499        }
500
501        // 6. check KZG challenges
502        let (incircuit_c_W, incircuit_c_E) = KZGChallengesGadget::<C1>::get_challenges_gadget(
503            cs.clone(),
504            &self.poseidon_config,
505            U_i1.clone(),
506        )?;
507        incircuit_c_W.enforce_equal(&kzg_c_W)?;
508        incircuit_c_E.enforce_equal(&kzg_c_E)?;
509
510        // Check 7 is temporary disabled due
511        // https://github.com/privacy-scaling-explorations/sonobe/issues/80
512        //
513        // 7. check eval_W==p_W(c_W) and eval_E==p_E(c_E)
514        // let incircuit_eval_W = evaluate_gadget::<CF1<C1>>(W_i1.W, incircuit_c_W)?;
515        // let incircuit_eval_E = evaluate_gadget::<CF1<C1>>(W_i1.E, incircuit_c_E)?;
516        // incircuit_eval_W.enforce_equal(&eval_W)?;
517        // incircuit_eval_E.enforce_equal(&eval_E)?;
518
519        // 8. compute the NIFS.V challenge and check that matches the one from the public input (so we
520        // avoid the verifier computing it)
521        let cmT =
522            NonNativeAffineVar::new_input(cs.clone(), || Ok(self.cmT.unwrap_or_else(C1::zero)))?;
523        let r_bits = ChallengeGadget::<C1>::get_challenge_gadget(
524            cs.clone(),
525            &self.poseidon_config,
526            pp_hash,
527            U_i_vec,
528            u_i.clone(),
529            cmT.clone(),
530        )?;
531        let r_Fr = Boolean::le_bits_to_fp_var(&r_bits)?;
532        // check that the in-circuit computed r is equal to the inputted r
533        let r =
534            FpVar::<CF1<C1>>::new_input(cs.clone(), || Ok(self.r.unwrap_or_else(CF1::<C1>::zero)))?;
535        r_Fr.enforce_equal(&r)?;
536
537        Ok(())
538    }
539}
540
541/// Interpolates the polynomial from the given vector, and then returns it's evaluation at the
542/// given point.
543#[allow(unused)] // unused while check 7 is disabled
544fn evaluate_gadget<F: PrimeField>(
545    v: Vec<FpVar<F>>,
546    point: FpVar<F>,
547) -> Result<FpVar<F>, SynthesisError> {
548    if !v.len().is_power_of_two() {
549        return Err(SynthesisError::Unsatisfiable);
550    }
551    let n = v.len() as u64;
552    let gen = F::get_root_of_unity(n).unwrap();
553    let domain = Radix2DomainVar::new(gen, log2(v.len()) as u64, FpVar::one()).unwrap();
554
555    let evaluations_var = EvaluationsVar::from_vec_and_domain(v, domain, true);
556    evaluations_var.interpolate_and_evaluate(&point)
557}
558
559/// Gadget that computes the KZG challenges, also offers the rust native implementation compatible
560/// with the gadget.
561pub struct KZGChallengesGadget<C: CurveGroup> {
562    _c: PhantomData<C>,
563}
564#[allow(clippy::type_complexity)]
565impl<C> KZGChallengesGadget<C>
566where
567    C: CurveGroup,
568    C::ScalarField: PrimeField,
569    <C as CurveGroup>::BaseField: PrimeField,
570    C::ScalarField: Absorb,
571{
572    pub fn get_challenges_native(
573        poseidon_config: &PoseidonConfig<C::ScalarField>,
574        U_i: CommittedInstance<C>,
575    ) -> Result<(C::ScalarField, C::ScalarField), Error> {
576        let (cmE_x_limbs, cmE_y_limbs) = nonnative_affine_to_field_elements(U_i.cmE)?;
577        let (cmW_x_limbs, cmW_y_limbs) = nonnative_affine_to_field_elements(U_i.cmW)?;
578
579        let transcript = &mut PoseidonTranscript::<C>::new(poseidon_config);
580        // compute the KZG challenges, which are computed in-circuit and checked that it matches
581        // the inputted one
582        transcript.absorb_vec(&cmW_x_limbs);
583        transcript.absorb_vec(&cmW_y_limbs);
584        let challenge_W = transcript.get_challenge();
585        transcript.absorb_vec(&cmE_x_limbs);
586        transcript.absorb_vec(&cmE_y_limbs);
587        let challenge_E = transcript.get_challenge();
588
589        Ok((challenge_W, challenge_E))
590    }
591    // compatible with the native get_challenges_native
592    pub fn get_challenges_gadget(
593        cs: ConstraintSystemRef<C::ScalarField>,
594        poseidon_config: &PoseidonConfig<C::ScalarField>,
595        U_i: CommittedInstanceVar<C>,
596    ) -> Result<(FpVar<C::ScalarField>, FpVar<C::ScalarField>), SynthesisError> {
597        let mut transcript =
598            PoseidonTranscriptVar::<CF1<C>>::new(cs.clone(), &poseidon_config.clone());
599
600        transcript.absorb_vec(&U_i.cmW.to_constraint_field()?[..])?;
601        let challenge_W = transcript.get_challenge()?;
602
603        transcript.absorb_vec(&U_i.cmE.to_constraint_field()?[..])?;
604        let challenge_E = transcript.get_challenge()?;
605
606        Ok((challenge_W, challenge_E))
607    }
608}
609
610#[cfg(test)]
611pub mod tests {
612    use ark_crypto_primitives::crh::{
613        sha256::{
614            constraints::{Sha256Gadget, UnitVar},
615            Sha256,
616        },
617        CRHScheme, CRHSchemeGadget,
618    };
619    use ark_pallas::{constraints::GVar, Fq, Fr, Projective};
620    use ark_r1cs_std::bits::uint8::UInt8;
621    use ark_relations::r1cs::ConstraintSystem;
622    use ark_std::{One, UniformRand};
623    use ark_vesta::{constraints::GVar as GVar2, Projective as Projective2};
624
625    use super::*;
626    use crate::arith::{
627        r1cs::{
628            tests::{get_test_r1cs, get_test_z},
629            {extract_r1cs, extract_w_x},
630        },
631        Arith,
632    };
633    use crate::commitment::pedersen::Pedersen;
634    use crate::folding::nova::PreprocessorParam;
635    use crate::frontend::tests::{CubicFCircuit, CustomFCircuit, WrapperCircuit};
636    use crate::transcript::poseidon::poseidon_canonical_config;
637    use crate::FoldingScheme;
638
639    #[test]
640    fn test_relaxed_r1cs_small_gadget_handcrafted() {
641        let r1cs: R1CS<Fr> = get_test_r1cs();
642        let rel_r1cs = r1cs.clone().relax();
643        let z = get_test_z(3);
644
645        let cs = ConstraintSystem::<Fr>::new_ref();
646
647        let zVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z)).unwrap();
648        let EVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(rel_r1cs.E)).unwrap();
649        let uVar = FpVar::<Fr>::new_witness(cs.clone(), || Ok(rel_r1cs.u)).unwrap();
650        let r1csVar = R1CSVar::<Fr, Fr, FpVar<Fr>>::new_witness(cs.clone(), || Ok(r1cs)).unwrap();
651
652        RelaxedR1CSGadget::check_native(r1csVar, EVar, uVar, zVar).unwrap();
653        assert!(cs.is_satisfied().unwrap());
654    }
655
656    // gets as input a circuit that implements the ConstraintSynthesizer trait, and that has been
657    // initialized.
658    fn test_relaxed_r1cs_gadget<CS: ConstraintSynthesizer<Fr>>(circuit: CS) {
659        let cs = ConstraintSystem::<Fr>::new_ref();
660
661        circuit.generate_constraints(cs.clone()).unwrap();
662        cs.finalize();
663        assert!(cs.is_satisfied().unwrap());
664
665        let cs = cs.into_inner().unwrap();
666
667        let r1cs = extract_r1cs::<Fr>(&cs);
668        let (w, x) = extract_w_x::<Fr>(&cs);
669        let z = [vec![Fr::one()], x, w].concat();
670        r1cs.check_relation(&z).unwrap();
671
672        let relaxed_r1cs = r1cs.clone().relax();
673        relaxed_r1cs.check_relation(&z).unwrap();
674
675        // set new CS for the circuit that checks the RelaxedR1CS of our original circuit
676        let cs = ConstraintSystem::<Fr>::new_ref();
677        // prepare the inputs for our circuit
678        let zVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z)).unwrap();
679        let EVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(relaxed_r1cs.E)).unwrap();
680        let uVar = FpVar::<Fr>::new_witness(cs.clone(), || Ok(relaxed_r1cs.u)).unwrap();
681        let r1csVar = R1CSVar::<Fr, Fr, FpVar<Fr>>::new_witness(cs.clone(), || Ok(r1cs)).unwrap();
682
683        RelaxedR1CSGadget::check_native(r1csVar, EVar, uVar, zVar).unwrap();
684        assert!(cs.is_satisfied().unwrap());
685    }
686
687    #[test]
688    fn test_relaxed_r1cs_small_gadget_arkworks() {
689        let z_i = vec![Fr::from(3_u32)];
690        let cubic_circuit = CubicFCircuit::<Fr>::new(()).unwrap();
691        let circuit = WrapperCircuit::<Fr, CubicFCircuit<Fr>> {
692            FC: cubic_circuit,
693            z_i: Some(z_i.clone()),
694            z_i1: Some(cubic_circuit.step_native(0, z_i, vec![]).unwrap()),
695        };
696
697        test_relaxed_r1cs_gadget(circuit);
698    }
699
700    struct Sha256TestCircuit<F: PrimeField> {
701        _f: PhantomData<F>,
702        pub x: Vec<u8>,
703        pub y: Vec<u8>,
704    }
705    impl<F: PrimeField> ConstraintSynthesizer<F> for Sha256TestCircuit<F> {
706        fn generate_constraints(self, cs: ConstraintSystemRef<F>) -> Result<(), SynthesisError> {
707            let x = Vec::<UInt8<F>>::new_witness(cs.clone(), || Ok(self.x))?;
708            let y = Vec::<UInt8<F>>::new_input(cs.clone(), || Ok(self.y))?;
709
710            let unitVar = UnitVar::default();
711            let comp_y = <Sha256Gadget<F> as CRHSchemeGadget<Sha256, F>>::evaluate(&unitVar, &x)?;
712            comp_y.0.enforce_equal(&y)?;
713            Ok(())
714        }
715    }
716    #[test]
717    fn test_relaxed_r1cs_medium_gadget_arkworks() {
718        let x = Fr::from(5_u32).into_bigint().to_bytes_le();
719        let y = <Sha256 as CRHScheme>::evaluate(&(), x.clone()).unwrap();
720
721        let circuit = Sha256TestCircuit::<Fr> {
722            _f: PhantomData,
723            x,
724            y,
725        };
726        test_relaxed_r1cs_gadget(circuit);
727    }
728
729    #[test]
730    fn test_relaxed_r1cs_custom_circuit() {
731        let n_constraints = 10_000;
732        let custom_circuit = CustomFCircuit::<Fr>::new(n_constraints).unwrap();
733        let z_i = vec![Fr::from(5_u32)];
734        let circuit = WrapperCircuit::<Fr, CustomFCircuit<Fr>> {
735            FC: custom_circuit,
736            z_i: Some(z_i.clone()),
737            z_i1: Some(custom_circuit.step_native(0, z_i, vec![]).unwrap()),
738        };
739        test_relaxed_r1cs_gadget(circuit);
740    }
741
742    #[test]
743    fn test_relaxed_r1cs_nonnative_circuit() {
744        let cs = ConstraintSystem::<Fq>::new_ref();
745        // in practice we would use CycleFoldCircuit, but is a very big circuit (when computed
746        // non-natively inside the RelaxedR1CS circuit), so in order to have a short test we use a
747        // custom circuit.
748        let custom_circuit = CustomFCircuit::<Fq>::new(10).unwrap();
749        let z_i = vec![Fq::from(5_u32)];
750        let circuit = WrapperCircuit::<Fq, CustomFCircuit<Fq>> {
751            FC: custom_circuit,
752            z_i: Some(z_i.clone()),
753            z_i1: Some(custom_circuit.step_native(0, z_i, vec![]).unwrap()),
754        };
755        circuit.generate_constraints(cs.clone()).unwrap();
756        cs.finalize();
757        let cs = cs.into_inner().unwrap();
758        let r1cs = extract_r1cs::<Fq>(&cs);
759        let (w, x) = extract_w_x::<Fq>(&cs);
760        let z = [vec![Fq::one()], x, w].concat();
761
762        let relaxed_r1cs = r1cs.clone().relax();
763
764        // natively
765        let cs = ConstraintSystem::<Fq>::new_ref();
766        let zVar = Vec::<FpVar<Fq>>::new_witness(cs.clone(), || Ok(z.clone())).unwrap();
767        let EVar =
768            Vec::<FpVar<Fq>>::new_witness(cs.clone(), || Ok(relaxed_r1cs.clone().E)).unwrap();
769        let uVar = FpVar::<Fq>::new_witness(cs.clone(), || Ok(relaxed_r1cs.u)).unwrap();
770        let r1csVar =
771            R1CSVar::<Fq, Fq, FpVar<Fq>>::new_witness(cs.clone(), || Ok(r1cs.clone())).unwrap();
772        RelaxedR1CSGadget::check_native(r1csVar, EVar, uVar, zVar).unwrap();
773
774        // non-natively
775        let cs = ConstraintSystem::<Fr>::new_ref();
776        let zVar = Vec::new_witness(cs.clone(), || Ok(z)).unwrap();
777        let EVar = Vec::new_witness(cs.clone(), || Ok(relaxed_r1cs.E)).unwrap();
778        let uVar = NonNativeUintVar::<Fr>::new_witness(cs.clone(), || Ok(relaxed_r1cs.u)).unwrap();
779        let r1csVar =
780            R1CSVar::<Fq, Fr, NonNativeUintVar<Fr>>::new_witness(cs.clone(), || Ok(r1cs)).unwrap();
781        RelaxedR1CSGadget::check_nonnative(r1csVar, EVar, uVar, zVar).unwrap();
782    }
783
784    #[test]
785    fn test_decider_circuit() {
786        let mut rng = ark_std::test_rng();
787        let poseidon_config = poseidon_canonical_config::<Fr>();
788
789        let F_circuit = CubicFCircuit::<Fr>::new(()).unwrap();
790        let z_0 = vec![Fr::from(3_u32)];
791
792        type N = Nova<
793            Projective,
794            GVar,
795            Projective2,
796            GVar2,
797            CubicFCircuit<Fr>,
798            Pedersen<Projective>,
799            Pedersen<Projective2>,
800        >;
801
802        let prep_param = PreprocessorParam::<
803            Projective,
804            Projective2,
805            CubicFCircuit<Fr>,
806            Pedersen<Projective>,
807            Pedersen<Projective2>,
808        >::new(poseidon_config, F_circuit);
809        let (prover_params, verifier_params) = N::preprocess(&mut rng, &prep_param).unwrap();
810
811        // generate a Nova instance and do a step of it
812        let mut nova = N::init(
813            (prover_params, verifier_params.clone()),
814            F_circuit,
815            z_0.clone(),
816        )
817        .unwrap();
818        nova.prove_step(&mut rng, vec![]).unwrap();
819        let ivc_v = nova.clone();
820        let (running_instance, incoming_instance, cyclefold_instance) = ivc_v.instances();
821        N::verify(
822            verifier_params,
823            z_0,
824            ivc_v.z_i,
825            Fr::one(),
826            running_instance,
827            incoming_instance,
828            cyclefold_instance,
829        )
830        .unwrap();
831
832        // load the DeciderEthCircuit from the generated Nova instance
833        let decider_circuit = DeciderEthCircuit::<
834            Projective,
835            GVar,
836            Projective2,
837            GVar2,
838            Pedersen<Projective>,
839            Pedersen<Projective2>,
840        >::from_nova(nova)
841        .unwrap();
842
843        let cs = ConstraintSystem::<Fr>::new_ref();
844
845        // generate the constraints and check that are satisfied by the inputs
846        decider_circuit.generate_constraints(cs.clone()).unwrap();
847        assert!(cs.is_satisfied().unwrap());
848    }
849
850    // checks that the gadget and native implementations of the challenge computation match
851    #[test]
852    fn test_kzg_challenge_gadget() {
853        let mut rng = ark_std::test_rng();
854        let poseidon_config = poseidon_canonical_config::<Fr>();
855
856        let U_i = CommittedInstance::<Projective> {
857            cmE: Projective::rand(&mut rng),
858            u: Fr::rand(&mut rng),
859            cmW: Projective::rand(&mut rng),
860            x: vec![Fr::rand(&mut rng); 1],
861        };
862
863        // compute the challenge natively
864        let (challenge_W, challenge_E) =
865            KZGChallengesGadget::<Projective>::get_challenges_native(&poseidon_config, U_i.clone())
866                .unwrap();
867
868        let cs = ConstraintSystem::<Fr>::new_ref();
869        let U_iVar =
870            CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(U_i.clone()))
871                .unwrap();
872
873        let (challenge_W_Var, challenge_E_Var) =
874            KZGChallengesGadget::<Projective>::get_challenges_gadget(
875                cs.clone(),
876                &poseidon_config,
877                U_iVar,
878            )
879            .unwrap();
880        assert!(cs.is_satisfied().unwrap());
881
882        // check that the natively computed and in-circuit computed hashes match
883        use ark_r1cs_std::R1CSVar;
884        assert_eq!(challenge_W_Var.value().unwrap(), challenge_W);
885        assert_eq!(challenge_E_Var.value().unwrap(), challenge_E);
886    }
887
888    // The test test_polynomial_interpolation is temporary disabled due
889    // https://github.com/privacy-scaling-explorations/sonobe/issues/80
890    // for n<=11 it will work, but for n>11 it will fail with stack overflow.
891    #[ignore]
892    #[test]
893    fn test_polynomial_interpolation() {
894        let mut rng = ark_std::test_rng();
895        let n = 12;
896        let l = 1 << n;
897
898        let v: Vec<Fr> = std::iter::repeat_with(|| Fr::rand(&mut rng))
899            .take(l)
900            .collect();
901        let challenge = Fr::rand(&mut rng);
902
903        use ark_poly::Polynomial;
904        let polynomial = poly_from_vec(v.to_vec()).unwrap();
905        let eval = polynomial.evaluate(&challenge);
906
907        let cs = ConstraintSystem::<Fr>::new_ref();
908        let vVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(v)).unwrap();
909        let challengeVar = FpVar::<Fr>::new_witness(cs.clone(), || Ok(challenge)).unwrap();
910
911        let evalVar = evaluate_gadget::<Fr>(vVar, challengeVar).unwrap();
912
913        use ark_r1cs_std::R1CSVar;
914        assert_eq!(evalVar.value().unwrap(), eval);
915        assert!(cs.is_satisfied().unwrap());
916    }
917}