sonobe/folding-schemes/src/folding/hypernova/decider_eth_circuit.rs
folding-schemes/src/folding/hypernova/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::sponge::{
4 constraints::CryptographicSpongeVar,
5 poseidon::{constraints::PoseidonSpongeVar, PoseidonConfig, PoseidonSponge},
6 Absorb, CryptographicSponge,
7};
8use ark_ec::{CurveGroup, Group};
9use ark_ff::PrimeField;
10use ark_poly::Polynomial;
11use ark_r1cs_std::{
12 alloc::{AllocVar, AllocationMode},
13 boolean::Boolean,
14 eq::EqGadget,
15 fields::fp::FpVar,
16 groups::GroupOpsBounds,
17 prelude::CurveVar,
18 ToConstraintFieldGadget,
19};
20use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystemRef, Namespace, SynthesisError};
21use ark_std::Zero;
22use core::{borrow::Borrow, marker::PhantomData};
23
24use super::{
25 circuits::{CCCSVar, LCCCSVar, NIMFSGadget, ProofVar as NIMFSProofVar},
26 nimfs::{NIMFSProof, NIMFS},
27 HyperNova, Witness, CCCS, LCCCS,
28};
29use crate::arith::ccs::CCS;
30use crate::arith::r1cs::R1CS;
31use crate::commitment::{pedersen::Params as PedersenParams, CommitmentScheme};
32use crate::folding::circuits::{
33 cyclefold::{CycleFoldCommittedInstance, CycleFoldWitness},
34 CF1, CF2,
35};
36use crate::frontend::FCircuit;
37use crate::transcript::{Transcript, TranscriptVar};
38use crate::utils::{
39 gadgets::{eval_mle, MatrixGadget, SparseMatrixVar},
40 vec::poly_from_vec,
41};
42use crate::Error;
43
44/// In-circuit representation of the Witness associated to the CommittedInstance.
45#[derive(Debug, Clone)]
46pub struct WitnessVar<F: PrimeField> {
47 pub w: Vec<FpVar<F>>,
48 pub r_w: FpVar<F>,
49}
50
51impl<F: PrimeField> AllocVar<Witness<F>, F> for WitnessVar<F> {
52 fn new_variable<T: Borrow<Witness<F>>>(
53 cs: impl Into<Namespace<F>>,
54 f: impl FnOnce() -> Result<T, SynthesisError>,
55 mode: AllocationMode,
56 ) -> Result<Self, SynthesisError> {
57 f().and_then(|val| {
58 let cs = cs.into();
59
60 let w: Vec<FpVar<F>> =
61 Vec::new_variable(cs.clone(), || Ok(val.borrow().w.clone()), mode)?;
62 let r_w = FpVar::<F>::new_variable(cs.clone(), || Ok(val.borrow().r_w), mode)?;
63
64 Ok(Self { w, r_w })
65 })
66 }
67}
68
69/// CCSMatricesVar contains the matrices 'M' of the CCS without the rest of CCS parameters.
70#[derive(Debug, Clone)]
71pub struct CCSMatricesVar<F: PrimeField> {
72 // we only need native representation, so the constraint field==F
73 pub M: Vec<SparseMatrixVar<F, F, FpVar<F>>>,
74}
75
76impl<F> AllocVar<CCS<F>, F> for CCSMatricesVar<F>
77where
78 F: PrimeField,
79{
80 fn new_variable<T: Borrow<CCS<F>>>(
81 cs: impl Into<Namespace<F>>,
82 f: impl FnOnce() -> Result<T, SynthesisError>,
83 _mode: AllocationMode,
84 ) -> Result<Self, SynthesisError> {
85 f().and_then(|val| {
86 let cs = cs.into();
87
88 let M: Vec<SparseMatrixVar<F, F, FpVar<F>>> = val
89 .borrow()
90 .M
91 .iter()
92 .map(|M| SparseMatrixVar::<F, F, FpVar<F>>::new_constant(cs.clone(), M.clone()))
93 .collect::<Result<_, SynthesisError>>()?;
94
95 Ok(Self { M })
96 })
97 }
98}
99
100/// Gadget to check the LCCCS relation both over the native constraint field and over the
101/// non-native constraint field.
102#[derive(Debug, Clone)]
103pub struct LCCCSCheckerGadget {}
104impl LCCCSCheckerGadget {
105 /// performs in-circuit the RelaxedR1CS check for native variables (Az∘Bz==uCz+E)
106 pub fn check<F: PrimeField>(
107 s: usize,
108 ccs_mat: CCSMatricesVar<F>,
109 z: Vec<FpVar<F>>,
110 // LCCCS values
111 r_x: Vec<FpVar<F>>,
112 v: Vec<FpVar<F>>,
113 ) -> Result<(), SynthesisError> {
114 let computed_v: Vec<FpVar<F>> = ccs_mat
115 .M
116 .iter()
117 .map(|M_j| {
118 let Mz = M_j.mul_vector(&z)?;
119 Ok(eval_mle(s, Mz, r_x.clone()))
120 })
121 .collect::<Result<Vec<FpVar<F>>, SynthesisError>>()?;
122
123 (computed_v).enforce_equal(&v)?;
124 Ok(())
125 }
126}
127
128/// Circuit that implements the in-circuit checks needed for the HyperNova's onchain (Ethereum's
129/// EVM) verification.
130#[derive(Clone, Debug)]
131pub struct DeciderEthCircuit<C1, GC1, C2, GC2, CS1, CS2, const H: bool = false>
132where
133 C1: CurveGroup,
134 GC1: CurveVar<C1, CF2<C1>>,
135 C2: CurveGroup,
136 GC2: CurveVar<C2, CF2<C2>>,
137 CS1: CommitmentScheme<C1, H>,
138 CS2: CommitmentScheme<C2, H>,
139{
140 _c1: PhantomData<C1>,
141 _gc1: PhantomData<GC1>,
142 _c2: PhantomData<C2>,
143 _gc2: PhantomData<GC2>,
144 _cs1: PhantomData<CS1>,
145 _cs2: PhantomData<CS2>,
146
147 /// E vector's length of the CycleFold instance witness
148 pub cf_E_len: usize,
149 /// CCS of the Augmented Function circuit
150 pub ccs: CCS<C1::ScalarField>,
151 /// R1CS of the CycleFold circuit
152 pub cf_r1cs: R1CS<C2::ScalarField>,
153 /// CycleFold PedersenParams over C2
154 pub cf_pedersen_params: PedersenParams<C2>,
155 pub poseidon_config: PoseidonConfig<CF1<C1>>,
156 /// public params hash
157 pub pp_hash: Option<C1::ScalarField>,
158 pub i: Option<CF1<C1>>,
159 /// initial state
160 pub z_0: Option<Vec<C1::ScalarField>>,
161 /// current i-th state
162 pub z_i: Option<Vec<C1::ScalarField>>,
163 /// Nova instances
164 pub U_i: Option<LCCCS<C1>>,
165 pub W_i: Option<Witness<C1::ScalarField>>,
166 pub u_i: Option<CCCS<C1>>,
167 pub w_i: Option<Witness<C1::ScalarField>>,
168 pub U_i1: Option<LCCCS<C1>>,
169 pub W_i1: Option<Witness<C1::ScalarField>>,
170 pub nimfs_proof: Option<NIMFSProof<C1>>,
171 // rho is the 'random' value used for the fold of the last 2 instances
172 pub rho: Option<C1::ScalarField>,
173 /// CycleFold running instance
174 pub cf_U_i: Option<CycleFoldCommittedInstance<C2>>,
175 pub cf_W_i: Option<CycleFoldWitness<C2>>,
176
177 /// KZG challenge & eval
178 pub kzg_challenge: Option<C1::ScalarField>,
179 pub eval_W: Option<C1::ScalarField>,
180}
181
182impl<C1, GC1, C2, GC2, CS1, CS2, const H: bool> DeciderEthCircuit<C1, GC1, C2, GC2, CS1, CS2, H>
183where
184 C1: CurveGroup,
185 C2: CurveGroup,
186 GC1: CurveVar<C1, CF2<C1>> + ToConstraintFieldGadget<CF2<C1>>,
187 GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
188 CS1: CommitmentScheme<C1, H>,
189 // enforce that the CS2 is Pedersen commitment scheme, since we're at Ethereum's EVM decider
190 CS2: CommitmentScheme<C2, H, ProverParams = PedersenParams<C2>>,
191 <C1 as Group>::ScalarField: Absorb,
192 <C1 as CurveGroup>::BaseField: PrimeField,
193{
194 /// returns an instance of the DeciderEthCircuit from the given HyperNova struct
195 pub fn from_hypernova<FC: FCircuit<C1::ScalarField>, const MU: usize, const NU: usize>(
196 hn: HyperNova<C1, GC1, C2, GC2, FC, CS1, CS2, MU, NU, H>,
197 ) -> Result<Self, Error> {
198 // compute the U_{i+1}, W_{i+1}, by folding the last running & incoming instances
199 let mut transcript = PoseidonSponge::<C1::ScalarField>::new(&hn.poseidon_config);
200 transcript.absorb(&hn.pp_hash);
201 let (nimfs_proof, U_i1, W_i1, rho) = NIMFS::<C1, PoseidonSponge<C1::ScalarField>>::prove(
202 &mut transcript,
203 &hn.ccs,
204 &[hn.U_i.clone()],
205 &[hn.u_i.clone()],
206 &[hn.W_i.clone()],
207 &[hn.w_i.clone()],
208 )?;
209
210 // compute the KZG challenges used as inputs in the circuit
211 let kzg_challenge =
212 KZGChallengeGadget::<C1>::get_challenge_native(&mut transcript, U_i1.clone())?;
213
214 // get KZG evals
215 let mut W = W_i1.w.clone();
216 W.extend(
217 std::iter::repeat(C1::ScalarField::zero())
218 .take(W_i1.w.len().next_power_of_two() - W_i1.w.len()),
219 );
220 let p_W = poly_from_vec(W.to_vec())?;
221 let eval_W = p_W.evaluate(&kzg_challenge);
222
223 Ok(Self {
224 _c1: PhantomData,
225 _gc1: PhantomData,
226 _c2: PhantomData,
227 _gc2: PhantomData,
228 _cs1: PhantomData,
229 _cs2: PhantomData,
230
231 cf_E_len: hn.cf_W_i.E.len(),
232 ccs: hn.ccs,
233 cf_r1cs: hn.cf_r1cs,
234 cf_pedersen_params: hn.cf_cs_pp,
235 poseidon_config: hn.poseidon_config,
236 pp_hash: Some(hn.pp_hash),
237 i: Some(hn.i),
238 z_0: Some(hn.z_0),
239 z_i: Some(hn.z_i),
240 U_i: Some(hn.U_i),
241 W_i: Some(hn.W_i),
242 u_i: Some(hn.u_i),
243 w_i: Some(hn.w_i),
244 U_i1: Some(U_i1),
245 W_i1: Some(W_i1),
246 nimfs_proof: Some(nimfs_proof),
247 rho: Some(rho),
248 cf_U_i: Some(hn.cf_U_i),
249 cf_W_i: Some(hn.cf_W_i),
250 kzg_challenge: Some(kzg_challenge),
251 eval_W: Some(eval_W),
252 })
253 }
254}
255
256impl<C1, GC1, C2, GC2, CS1, CS2> ConstraintSynthesizer<CF1<C1>>
257 for DeciderEthCircuit<C1, GC1, C2, GC2, CS1, CS2>
258where
259 C1: CurveGroup,
260 C2: CurveGroup,
261 GC1: CurveVar<C1, CF2<C1>>,
262 GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
263 CS1: CommitmentScheme<C1>,
264 CS2: CommitmentScheme<C2>,
265 C1::ScalarField: PrimeField,
266 <C1 as CurveGroup>::BaseField: PrimeField,
267 <C2 as CurveGroup>::BaseField: PrimeField,
268 <C1 as Group>::ScalarField: Absorb,
269 <C2 as Group>::ScalarField: Absorb,
270 C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
271 for<'b> &'b GC2: GroupOpsBounds<'b, C2, GC2>,
272{
273 fn generate_constraints(self, cs: ConstraintSystemRef<CF1<C1>>) -> Result<(), SynthesisError> {
274 let ccs_matrices =
275 CCSMatricesVar::<C1::ScalarField>::new_witness(cs.clone(), || Ok(self.ccs.clone()))?;
276
277 let pp_hash = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
278 Ok(self.pp_hash.unwrap_or_else(CF1::<C1>::zero))
279 })?;
280 let i =
281 FpVar::<CF1<C1>>::new_input(cs.clone(), || Ok(self.i.unwrap_or_else(CF1::<C1>::zero)))?;
282 let z_0 = Vec::<FpVar<CF1<C1>>>::new_input(cs.clone(), || {
283 Ok(self.z_0.unwrap_or(vec![CF1::<C1>::zero()]))
284 })?;
285 let z_i = Vec::<FpVar<CF1<C1>>>::new_input(cs.clone(), || {
286 Ok(self.z_i.unwrap_or(vec![CF1::<C1>::zero()]))
287 })?;
288
289 let U_dummy_native = LCCCS::<C1>::dummy(self.ccs.l, self.ccs.t, self.ccs.s);
290 let u_dummy_native = CCCS::<C1>::dummy(self.ccs.l);
291 let w_dummy_native = Witness::<C1::ScalarField>::new(
292 vec![C1::ScalarField::zero(); self.ccs.n - 3 /* (3=2+1, since u_i.x.len=2) */],
293 );
294
295 let U_i = LCCCSVar::<C1>::new_witness(cs.clone(), || {
296 Ok(self.U_i.unwrap_or(U_dummy_native.clone()))
297 })?;
298 let u_i = CCCSVar::<C1>::new_witness(cs.clone(), || {
299 Ok(self.u_i.unwrap_or(u_dummy_native.clone()))
300 })?;
301 // here (U_i1, W_i1) = NIFS.P( (U_i,W_i), (u_i,w_i))
302 let U_i1 = LCCCSVar::<C1>::new_input(cs.clone(), || {
303 Ok(self.U_i1.unwrap_or(U_dummy_native.clone()))
304 })?;
305 let W_i1 = WitnessVar::<C1::ScalarField>::new_witness(cs.clone(), || {
306 Ok(self.W_i1.unwrap_or(w_dummy_native.clone()))
307 })?;
308 let nimfs_proof_dummy = NIMFSProof::<C1>::dummy(&self.ccs, 1, 1); // mu=1 & nu=1 because the last fold is 2-to-1
309 let nimfs_proof = NIMFSProofVar::<C1>::new_witness(cs.clone(), || {
310 Ok(self.nimfs_proof.unwrap_or(nimfs_proof_dummy))
311 })?;
312
313 // allocate the inputs for the check 6
314 let kzg_challenge = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
315 Ok(self.kzg_challenge.unwrap_or_else(CF1::<C1>::zero))
316 })?;
317 let _eval_W = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
318 Ok(self.eval_W.unwrap_or_else(CF1::<C1>::zero))
319 })?;
320
321 // `sponge` is for digest computation.
322 let sponge = PoseidonSpongeVar::<C1::ScalarField>::new(cs.clone(), &self.poseidon_config);
323 // `transcript` is for challenge generation.
324 let mut transcript = sponge.clone();
325 transcript.absorb(&pp_hash)?;
326
327 // NOTE: we use the same enumeration as in Nova's DeciderEthCircuit described at
328 // https://privacy-scaling-explorations.github.io/sonobe-docs/design/nova-decider-onchain.html
329 // in order to make it easier to reason about.
330
331 // 1. check LCCCS relation of U_{i+1}
332 let z_U1: Vec<FpVar<CF1<C1>>> =
333 [vec![U_i1.u.clone()], U_i1.x.to_vec(), W_i1.w.to_vec()].concat();
334 LCCCSCheckerGadget::check(
335 self.ccs.s,
336 ccs_matrices,
337 z_U1,
338 U_i1.r_x.clone(),
339 U_i1.v.clone(),
340 )?;
341
342 // 3.a u_i.x[0] == H(i, z_0, z_i, U_i)
343 let (u_i_x, _) = U_i.clone().hash(
344 &sponge,
345 pp_hash.clone(),
346 i.clone(),
347 z_0.clone(),
348 z_i.clone(),
349 )?;
350 (u_i.x[0]).enforce_equal(&u_i_x)?;
351
352 #[cfg(feature = "light-test")]
353 log::warn!("[WARNING]: Running with the 'light-test' feature, skipping the big part of the DeciderEthCircuit.\n Only for testing purposes.");
354
355 // The following two checks (and their respective allocations) are disabled for normal
356 // tests since they take several millions of constraints and would take several minutes
357 // (and RAM) to run the test. It is active by default, and not active only when
358 // 'light-test' feature is used.
359 #[cfg(not(feature = "light-test"))]
360 {
361 // imports here instead of at the top of the file, so we avoid having multiple
362 // `#[cfg(not(test))]`
363 use crate::commitment::pedersen::PedersenGadget;
364 use crate::folding::circuits::nonnative::uint::NonNativeUintVar;
365 use crate::folding::nova::decider_eth_circuit::{R1CSVar, RelaxedR1CSGadget};
366 use crate::folding::{
367 circuits::cyclefold::{
368 CycleFoldCommittedInstanceVar, CycleFoldConfig, CycleFoldWitnessVar,
369 },
370 nova::NovaCycleFoldConfig,
371 };
372 use ark_r1cs_std::ToBitsGadget;
373
374 let cf_u_dummy_native =
375 CycleFoldCommittedInstance::<C2>::dummy(NovaCycleFoldConfig::<C1>::IO_LEN);
376 let cf_w_dummy_native = CycleFoldWitness::<C2>::dummy(
377 self.cf_r1cs.A.n_cols - 1 - self.cf_r1cs.l,
378 self.cf_E_len,
379 );
380 let cf_U_i = CycleFoldCommittedInstanceVar::<C2, GC2>::new_witness(cs.clone(), || {
381 Ok(self.cf_U_i.unwrap_or_else(|| cf_u_dummy_native.clone()))
382 })?;
383 let cf_W_i = CycleFoldWitnessVar::<C2>::new_witness(cs.clone(), || {
384 Ok(self.cf_W_i.unwrap_or(cf_w_dummy_native.clone()))
385 })?;
386
387 // 3.b u_i.x[1] == H(cf_U_i)
388 let (cf_u_i_x, _) = cf_U_i.clone().hash(&sponge, pp_hash.clone())?;
389 (u_i.x[1]).enforce_equal(&cf_u_i_x)?;
390
391 // 4. check Pedersen commitments of cf_U_i.{cmE, cmW}
392 let H = GC2::new_constant(cs.clone(), self.cf_pedersen_params.h)?;
393 let G = Vec::<GC2>::new_constant(cs.clone(), self.cf_pedersen_params.generators)?;
394 let cf_W_i_E_bits: Result<Vec<Vec<Boolean<CF1<C1>>>>, SynthesisError> =
395 cf_W_i.E.iter().map(|E_i| E_i.to_bits_le()).collect();
396 let cf_W_i_W_bits: Result<Vec<Vec<Boolean<CF1<C1>>>>, SynthesisError> =
397 cf_W_i.W.iter().map(|W_i| W_i.to_bits_le()).collect();
398
399 let computed_cmE = PedersenGadget::<C2, GC2>::commit(
400 H.clone(),
401 G.clone(),
402 cf_W_i_E_bits?,
403 cf_W_i.rE.to_bits_le()?,
404 )?;
405 cf_U_i.cmE.enforce_equal(&computed_cmE)?;
406 let computed_cmW =
407 PedersenGadget::<C2, GC2>::commit(H, G, cf_W_i_W_bits?, cf_W_i.rW.to_bits_le()?)?;
408 cf_U_i.cmW.enforce_equal(&computed_cmW)?;
409
410 let cf_r1cs =
411 R1CSVar::<C1::BaseField, CF1<C1>, NonNativeUintVar<CF1<C1>>>::new_witness(
412 cs.clone(),
413 || Ok(self.cf_r1cs.clone()),
414 )?;
415
416 // 5. check RelaxedR1CS of cf_U_i
417 let cf_z_U = [vec![cf_U_i.u.clone()], cf_U_i.x.to_vec(), cf_W_i.W.to_vec()].concat();
418 RelaxedR1CSGadget::check_nonnative(cf_r1cs, cf_W_i.E, cf_U_i.u.clone(), cf_z_U)?;
419 }
420
421 // The following steps are in non-increasing order because the `computed_U_i1` is computed
422 // at step 8, and later used at step 6. Notice that in Nova, we compute U_i1 outside of the
423 // circuit, in the smart contract, but here we're computing it in-circuit, and we reuse the
424 // `rho_bits` computed along the way of computing `computed_U_i1` for the later `rho_powers`
425 // check (6.b).
426
427 // Check 7 is temporary disabled due
428 // https://github.com/privacy-scaling-explorations/sonobe/issues/80
429 log::warn!("[WARNING]: issue #80 (https://github.com/privacy-scaling-explorations/sonobe/issues/80) is not resolved yet.");
430 //
431 // 7. check eval_W==p_W(c_W)
432 // let incircuit_eval_W = evaluate_gadget::<CF1<C1>>(W_i1.W, incircuit_c_W)?;
433 // incircuit_eval_W.enforce_equal(&eval_W)?;
434
435 // 8.a verify the NIMFS.V of the final fold, and check that the obtained rho_powers from the
436 // transcript match the one from the public input (so we avoid the onchain logic of the
437 // verifier computing it).
438 // Notice that the NIMFSGadget performs all the logic except of checking the fold of the
439 // instances C parameter, which would require non-native arithmetic, henceforth we perform
440 // that check outside the circuit.
441 let (computed_U_i1, rho_bits) = NIMFSGadget::<C1>::verify(
442 cs.clone(),
443 &self.ccs.clone(),
444 &mut transcript,
445 &[U_i],
446 &[u_i],
447 nimfs_proof,
448 Boolean::TRUE, // enabled
449 )?;
450
451 // 6.a check KZG challenges
452 // Notice that this step is done after the NIMFS.V, to follow the transcript absorbs order
453 // done outside the circuit, where to compute the challenge it needs first to compute the
454 // U_{i+1} through the NIMFS.V
455 let incircuit_challenge =
456 KZGChallengeGadget::<C1>::get_challenge_gadget(&mut transcript, U_i1.clone())?;
457 incircuit_challenge.enforce_equal(&kzg_challenge)?;
458
459 // 6.b check that the obtained U_{i+1} from the NIMFS.V matches the U_{i+1} from the input,
460 // except for the C parameter, which to compute its folding would require non-native logic
461 // in-circuit, and we defer it to outside the circuit.
462 computed_U_i1.u.enforce_equal(&U_i1.u)?;
463 computed_U_i1.r_x.enforce_equal(&U_i1.r_x)?;
464 computed_U_i1.v.enforce_equal(&U_i1.v)?;
465
466 // 8.b check that the in-circuit computed r is equal to the inputted r.
467
468 let rho = Boolean::le_bits_to_fp_var(&rho_bits)?;
469 let external_rho =
470 FpVar::<CF1<C1>>::new_input(cs.clone(), || Ok(self.rho.unwrap_or(CF1::<C1>::zero())))?;
471 rho.enforce_equal(&external_rho)?;
472
473 Ok(())
474 }
475}
476
477/// Gadget that computes the KZG challenges, also offers the rust native implementation compatible
478/// with the gadget.
479pub struct KZGChallengeGadget<C: CurveGroup> {
480 _c: PhantomData<C>,
481}
482#[allow(clippy::type_complexity)]
483impl<C> KZGChallengeGadget<C>
484where
485 C: CurveGroup,
486 C::ScalarField: PrimeField,
487 <C as CurveGroup>::BaseField: PrimeField,
488 C::ScalarField: Absorb,
489{
490 pub fn get_challenge_native<T: Transcript<C::ScalarField>>(
491 transcript: &mut T,
492 U_i: LCCCS<C>,
493 ) -> Result<C::ScalarField, Error> {
494 // compute the KZG challenges, which are computed in-circuit and checked that it matches
495 // the inputted one
496 transcript.absorb_nonnative(&U_i.C);
497 Ok(transcript.get_challenge())
498 }
499 // compatible with the native get_challenge_native
500 pub fn get_challenge_gadget<S: CryptographicSponge, T: TranscriptVar<CF1<C>, S>>(
501 transcript: &mut T,
502 U_i: LCCCSVar<C>,
503 ) -> Result<FpVar<C::ScalarField>, SynthesisError> {
504 transcript.absorb(&U_i.C.to_constraint_field()?)?;
505 transcript.get_challenge()
506 }
507}
508
509#[cfg(test)]
510pub mod tests {
511 use ark_bn254::{constraints::GVar, Fr, G1Projective as Projective};
512 use ark_grumpkin::{constraints::GVar as GVar2, Projective as Projective2};
513 use ark_relations::r1cs::ConstraintSystem;
514 use ark_std::One;
515 use ark_std::{test_rng, UniformRand};
516
517 use super::*;
518 use crate::commitment::pedersen::Pedersen;
519 use crate::folding::nova::PreprocessorParam;
520 use crate::frontend::utils::CubicFCircuit;
521 use crate::transcript::poseidon::poseidon_canonical_config;
522 use crate::FoldingScheme;
523
524 #[test]
525 fn test_lcccs_checker_gadget() {
526 let mut rng = test_rng();
527 let n_rows = 2_u32.pow(5) as usize;
528 let n_cols = 2_u32.pow(5) as usize;
529 let r1cs = R1CS::<Fr>::rand(&mut rng, n_rows, n_cols);
530 let ccs = CCS::from_r1cs(r1cs);
531 let z: Vec<Fr> = (0..n_cols).map(|_| Fr::rand(&mut rng)).collect();
532
533 let (pedersen_params, _) =
534 Pedersen::<Projective>::setup(&mut rng, ccs.n - ccs.l - 1).unwrap();
535
536 let (lcccs, _) = ccs
537 .to_lcccs::<_, Projective, Pedersen<Projective>, false>(&mut rng, &pedersen_params, &z)
538 .unwrap();
539
540 let cs = ConstraintSystem::<Fr>::new_ref();
541
542 // CCS's (sparse) matrices are constants in the circuit
543 let ccs_mat = CCSMatricesVar::<Fr>::new_constant(cs.clone(), ccs.clone()).unwrap();
544 let zVar = Vec::<FpVar<Fr>>::new_input(cs.clone(), || Ok(z)).unwrap();
545 let r_xVar = Vec::<FpVar<Fr>>::new_input(cs.clone(), || Ok(lcccs.r_x)).unwrap();
546 let vVar = Vec::<FpVar<Fr>>::new_input(cs.clone(), || Ok(lcccs.v)).unwrap();
547
548 LCCCSCheckerGadget::check(ccs.s, ccs_mat, zVar, r_xVar, vVar).unwrap();
549
550 assert!(cs.is_satisfied().unwrap());
551 }
552
553 #[test]
554 fn test_decider_circuit() {
555 let mut rng = ark_std::test_rng();
556 let poseidon_config = poseidon_canonical_config::<Fr>();
557
558 let F_circuit = CubicFCircuit::<Fr>::new(()).unwrap();
559 let z_0 = vec![Fr::from(3_u32)];
560
561 const MU: usize = 1;
562 const NU: usize = 1;
563
564 type HN = HyperNova<
565 Projective,
566 GVar,
567 Projective2,
568 GVar2,
569 CubicFCircuit<Fr>,
570 Pedersen<Projective>,
571 Pedersen<Projective2>,
572 MU,
573 NU,
574 false,
575 >;
576 let prep_param = PreprocessorParam::<
577 Projective,
578 Projective2,
579 CubicFCircuit<Fr>,
580 Pedersen<Projective>,
581 Pedersen<Projective2>,
582 false,
583 >::new(poseidon_config, F_circuit);
584 let hn_params = HN::preprocess(&mut rng, &prep_param).unwrap();
585
586 // generate a Nova instance and do a step of it
587 let mut hypernova = HN::init(&hn_params, F_circuit, z_0.clone()).unwrap();
588 hypernova
589 .prove_step(&mut rng, vec![], Some((vec![], vec![])))
590 .unwrap();
591
592 let ivc_v = hypernova.clone();
593 let (running_instance, incoming_instance, cyclefold_instance) = ivc_v.instances();
594 HN::verify(
595 hn_params.1, // HN's verifier_params
596 z_0,
597 ivc_v.z_i,
598 Fr::one(),
599 running_instance,
600 incoming_instance,
601 cyclefold_instance,
602 )
603 .unwrap();
604
605 // load the DeciderEthCircuit from the generated Nova instance
606 let decider_circuit = DeciderEthCircuit::<
607 Projective,
608 GVar,
609 Projective2,
610 GVar2,
611 Pedersen<Projective>,
612 Pedersen<Projective2>,
613 >::from_hypernova(hypernova)
614 .unwrap();
615
616 let cs = ConstraintSystem::<Fr>::new_ref();
617
618 // generate the constraints and check that are satisfied by the inputs
619 decider_circuit.generate_constraints(cs.clone()).unwrap();
620 assert!(cs.is_satisfied().unwrap());
621 dbg!(cs.num_constraints());
622 }
623}