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::commitment::{pedersen::Params as PedersenParams, CommitmentScheme};
30use crate::folding::circuits::{
31 cyclefold::{CycleFoldCommittedInstance, CycleFoldWitness},
32 CF1, CF2,
33};
34use crate::frontend::FCircuit;
35use crate::transcript::{Transcript, TranscriptVar};
36use crate::utils::{
37 gadgets::{eval_mle, MatrixGadget, SparseMatrixVar},
38 vec::poly_from_vec,
39};
40use crate::Error;
41use crate::{arith::ccs::CCS, folding::traits::CommittedInstanceVarOps};
42use crate::{arith::r1cs::R1CS, folding::traits::WitnessVarOps};
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
69impl<F: PrimeField> WitnessVarOps<F> for WitnessVar<F> {
70 fn get_openings(&self) -> Vec<(&[FpVar<F>], FpVar<F>)> {
71 vec![(&self.w, self.r_w.clone())]
72 }
73}
74
75/// CCSMatricesVar contains the matrices 'M' of the CCS without the rest of CCS parameters.
76#[derive(Debug, Clone)]
77pub struct CCSMatricesVar<F: PrimeField> {
78 // we only need native representation, so the constraint field==F
79 pub M: Vec<SparseMatrixVar<F, F, FpVar<F>>>,
80}
81
82impl<F> AllocVar<CCS<F>, F> for CCSMatricesVar<F>
83where
84 F: PrimeField,
85{
86 fn new_variable<T: Borrow<CCS<F>>>(
87 cs: impl Into<Namespace<F>>,
88 f: impl FnOnce() -> Result<T, SynthesisError>,
89 _mode: AllocationMode,
90 ) -> Result<Self, SynthesisError> {
91 f().and_then(|val| {
92 let cs = cs.into();
93
94 let M: Vec<SparseMatrixVar<F, F, FpVar<F>>> = val
95 .borrow()
96 .M
97 .iter()
98 .map(|M| SparseMatrixVar::<F, F, FpVar<F>>::new_constant(cs.clone(), M.clone()))
99 .collect::<Result<_, SynthesisError>>()?;
100
101 Ok(Self { M })
102 })
103 }
104}
105
106/// Gadget to check the LCCCS relation both over the native constraint field and over the
107/// non-native constraint field.
108#[derive(Debug, Clone)]
109pub struct LCCCSCheckerGadget {}
110impl LCCCSCheckerGadget {
111 /// performs in-circuit the RelaxedR1CS check for native variables (Az∘Bz==uCz+E)
112 pub fn check<F: PrimeField>(
113 s: usize,
114 ccs_mat: CCSMatricesVar<F>,
115 z: Vec<FpVar<F>>,
116 // LCCCS values
117 r_x: Vec<FpVar<F>>,
118 v: Vec<FpVar<F>>,
119 ) -> Result<(), SynthesisError> {
120 let computed_v: Vec<FpVar<F>> = ccs_mat
121 .M
122 .iter()
123 .map(|M_j| {
124 let Mz = M_j.mul_vector(&z)?;
125 Ok(eval_mle(s, Mz, r_x.clone()))
126 })
127 .collect::<Result<Vec<FpVar<F>>, SynthesisError>>()?;
128
129 (computed_v).enforce_equal(&v)?;
130 Ok(())
131 }
132}
133
134/// Circuit that implements the in-circuit checks needed for the HyperNova's onchain (Ethereum's
135/// EVM) verification.
136#[derive(Clone, Debug)]
137pub struct DeciderEthCircuit<C1, GC1, C2, GC2, CS1, CS2, const H: bool = false>
138where
139 C1: CurveGroup,
140 GC1: CurveVar<C1, CF2<C1>>,
141 C2: CurveGroup,
142 GC2: CurveVar<C2, CF2<C2>>,
143 CS1: CommitmentScheme<C1, H>,
144 CS2: CommitmentScheme<C2, H>,
145{
146 _c1: PhantomData<C1>,
147 _gc1: PhantomData<GC1>,
148 _c2: PhantomData<C2>,
149 _gc2: PhantomData<GC2>,
150 _cs1: PhantomData<CS1>,
151 _cs2: PhantomData<CS2>,
152
153 /// E vector's length of the CycleFold instance witness
154 pub cf_E_len: usize,
155 /// CCS of the Augmented Function circuit
156 pub ccs: CCS<C1::ScalarField>,
157 /// R1CS of the CycleFold circuit
158 pub cf_r1cs: R1CS<C2::ScalarField>,
159 /// CycleFold PedersenParams over C2
160 pub cf_pedersen_params: PedersenParams<C2>,
161 pub poseidon_config: PoseidonConfig<CF1<C1>>,
162 /// public params hash
163 pub pp_hash: Option<C1::ScalarField>,
164 pub i: Option<CF1<C1>>,
165 /// initial state
166 pub z_0: Option<Vec<C1::ScalarField>>,
167 /// current i-th state
168 pub z_i: Option<Vec<C1::ScalarField>>,
169 /// Nova instances
170 pub U_i: Option<LCCCS<C1>>,
171 pub W_i: Option<Witness<C1::ScalarField>>,
172 pub u_i: Option<CCCS<C1>>,
173 pub w_i: Option<Witness<C1::ScalarField>>,
174 pub U_i1: Option<LCCCS<C1>>,
175 pub W_i1: Option<Witness<C1::ScalarField>>,
176 pub nimfs_proof: Option<NIMFSProof<C1>>,
177 // rho is the 'random' value used for the fold of the last 2 instances
178 pub rho: Option<C1::ScalarField>,
179 /// CycleFold running instance
180 pub cf_U_i: Option<CycleFoldCommittedInstance<C2>>,
181 pub cf_W_i: Option<CycleFoldWitness<C2>>,
182
183 /// KZG challenge & eval
184 pub kzg_challenge: Option<C1::ScalarField>,
185 pub eval_W: Option<C1::ScalarField>,
186}
187
188impl<C1, GC1, C2, GC2, CS1, CS2, const H: bool> DeciderEthCircuit<C1, GC1, C2, GC2, CS1, CS2, H>
189where
190 C1: CurveGroup,
191 C2: CurveGroup,
192 GC1: CurveVar<C1, CF2<C1>> + ToConstraintFieldGadget<CF2<C1>>,
193 GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
194 CS1: CommitmentScheme<C1, H>,
195 // enforce that the CS2 is Pedersen commitment scheme, since we're at Ethereum's EVM decider
196 CS2: CommitmentScheme<C2, H, ProverParams = PedersenParams<C2>>,
197 <C1 as Group>::ScalarField: Absorb,
198 <C1 as CurveGroup>::BaseField: PrimeField,
199{
200 /// returns an instance of the DeciderEthCircuit from the given HyperNova struct
201 pub fn from_hypernova<FC: FCircuit<C1::ScalarField>, const MU: usize, const NU: usize>(
202 hn: HyperNova<C1, GC1, C2, GC2, FC, CS1, CS2, MU, NU, H>,
203 ) -> Result<Self, Error> {
204 // compute the U_{i+1}, W_{i+1}, by folding the last running & incoming instances
205 let mut transcript = PoseidonSponge::<C1::ScalarField>::new(&hn.poseidon_config);
206 transcript.absorb(&hn.pp_hash);
207 let (nimfs_proof, U_i1, W_i1, rho) = NIMFS::<C1, PoseidonSponge<C1::ScalarField>>::prove(
208 &mut transcript,
209 &hn.ccs,
210 &[hn.U_i.clone()],
211 &[hn.u_i.clone()],
212 &[hn.W_i.clone()],
213 &[hn.w_i.clone()],
214 )?;
215
216 // compute the KZG challenges used as inputs in the circuit
217 let kzg_challenge =
218 KZGChallengeGadget::<C1>::get_challenge_native(&mut transcript, U_i1.clone())?;
219
220 // get KZG evals
221 let mut W = W_i1.w.clone();
222 W.extend(
223 std::iter::repeat(C1::ScalarField::zero())
224 .take(W_i1.w.len().next_power_of_two() - W_i1.w.len()),
225 );
226 let p_W = poly_from_vec(W.to_vec())?;
227 let eval_W = p_W.evaluate(&kzg_challenge);
228
229 Ok(Self {
230 _c1: PhantomData,
231 _gc1: PhantomData,
232 _c2: PhantomData,
233 _gc2: PhantomData,
234 _cs1: PhantomData,
235 _cs2: PhantomData,
236
237 cf_E_len: hn.cf_W_i.E.len(),
238 ccs: hn.ccs,
239 cf_r1cs: hn.cf_r1cs,
240 cf_pedersen_params: hn.cf_cs_pp,
241 poseidon_config: hn.poseidon_config,
242 pp_hash: Some(hn.pp_hash),
243 i: Some(hn.i),
244 z_0: Some(hn.z_0),
245 z_i: Some(hn.z_i),
246 U_i: Some(hn.U_i),
247 W_i: Some(hn.W_i),
248 u_i: Some(hn.u_i),
249 w_i: Some(hn.w_i),
250 U_i1: Some(U_i1),
251 W_i1: Some(W_i1),
252 nimfs_proof: Some(nimfs_proof),
253 rho: Some(rho),
254 cf_U_i: Some(hn.cf_U_i),
255 cf_W_i: Some(hn.cf_W_i),
256 kzg_challenge: Some(kzg_challenge),
257 eval_W: Some(eval_W),
258 })
259 }
260}
261
262impl<C1, GC1, C2, GC2, CS1, CS2> ConstraintSynthesizer<CF1<C1>>
263 for DeciderEthCircuit<C1, GC1, C2, GC2, CS1, CS2>
264where
265 C1: CurveGroup,
266 C2: CurveGroup,
267 GC1: CurveVar<C1, CF2<C1>>,
268 GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
269 CS1: CommitmentScheme<C1>,
270 CS2: CommitmentScheme<C2>,
271 C1::ScalarField: PrimeField,
272 <C1 as CurveGroup>::BaseField: PrimeField,
273 <C2 as CurveGroup>::BaseField: PrimeField,
274 <C1 as Group>::ScalarField: Absorb,
275 <C2 as Group>::ScalarField: Absorb,
276 C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
277 for<'b> &'b GC2: GroupOpsBounds<'b, C2, GC2>,
278{
279 fn generate_constraints(self, cs: ConstraintSystemRef<CF1<C1>>) -> Result<(), SynthesisError> {
280 let ccs_matrices =
281 CCSMatricesVar::<C1::ScalarField>::new_witness(cs.clone(), || Ok(self.ccs.clone()))?;
282
283 let pp_hash = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
284 Ok(self.pp_hash.unwrap_or_else(CF1::<C1>::zero))
285 })?;
286 let i =
287 FpVar::<CF1<C1>>::new_input(cs.clone(), || Ok(self.i.unwrap_or_else(CF1::<C1>::zero)))?;
288 let z_0 = Vec::<FpVar<CF1<C1>>>::new_input(cs.clone(), || {
289 Ok(self.z_0.unwrap_or(vec![CF1::<C1>::zero()]))
290 })?;
291 let z_i = Vec::<FpVar<CF1<C1>>>::new_input(cs.clone(), || {
292 Ok(self.z_i.unwrap_or(vec![CF1::<C1>::zero()]))
293 })?;
294
295 let U_dummy_native = LCCCS::<C1>::dummy(self.ccs.l, self.ccs.t, self.ccs.s);
296 let u_dummy_native = CCCS::<C1>::dummy(self.ccs.l);
297 let w_dummy_native = Witness::<C1::ScalarField>::new(
298 vec![C1::ScalarField::zero(); self.ccs.n - 3 /* (3=2+1, since u_i.x.len=2) */],
299 );
300
301 let U_i = LCCCSVar::<C1>::new_witness(cs.clone(), || {
302 Ok(self.U_i.unwrap_or(U_dummy_native.clone()))
303 })?;
304 let u_i = CCCSVar::<C1>::new_witness(cs.clone(), || {
305 Ok(self.u_i.unwrap_or(u_dummy_native.clone()))
306 })?;
307 // here (U_i1, W_i1) = NIFS.P( (U_i,W_i), (u_i,w_i))
308 let U_i1 = LCCCSVar::<C1>::new_input(cs.clone(), || {
309 Ok(self.U_i1.unwrap_or(U_dummy_native.clone()))
310 })?;
311 let W_i1 = WitnessVar::<C1::ScalarField>::new_witness(cs.clone(), || {
312 Ok(self.W_i1.unwrap_or(w_dummy_native.clone()))
313 })?;
314 let nimfs_proof_dummy = NIMFSProof::<C1>::dummy(&self.ccs, 1, 1); // mu=1 & nu=1 because the last fold is 2-to-1
315 let nimfs_proof = NIMFSProofVar::<C1>::new_witness(cs.clone(), || {
316 Ok(self.nimfs_proof.unwrap_or(nimfs_proof_dummy))
317 })?;
318
319 // allocate the inputs for the check 6
320 let kzg_challenge = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
321 Ok(self.kzg_challenge.unwrap_or_else(CF1::<C1>::zero))
322 })?;
323 let _eval_W = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
324 Ok(self.eval_W.unwrap_or_else(CF1::<C1>::zero))
325 })?;
326
327 // `sponge` is for digest computation.
328 let sponge = PoseidonSpongeVar::<C1::ScalarField>::new(cs.clone(), &self.poseidon_config);
329 // `transcript` is for challenge generation.
330 let mut transcript = sponge.clone();
331 transcript.absorb(&pp_hash)?;
332
333 // NOTE: we use the same enumeration as in Nova's DeciderEthCircuit described at
334 // https://privacy-scaling-explorations.github.io/sonobe-docs/design/nova-decider-onchain.html
335 // in order to make it easier to reason about.
336
337 // 1. check LCCCS relation of U_{i+1}
338 let z_U1: Vec<FpVar<CF1<C1>>> =
339 [vec![U_i1.u.clone()], U_i1.x.to_vec(), W_i1.w.to_vec()].concat();
340 LCCCSCheckerGadget::check(
341 self.ccs.s,
342 ccs_matrices,
343 z_U1,
344 U_i1.r_x.clone(),
345 U_i1.v.clone(),
346 )?;
347
348 // 3.a u_i.x[0] == H(i, z_0, z_i, U_i)
349 let (u_i_x, _) = U_i.clone().hash(&sponge, &pp_hash, &i, &z_0, &z_i)?;
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}