sonobe/src/frontend/mod.rs
src/frontend/mod.rsRaw
1pub mod circom;
2
3use crate::Error;
4use ark_ff::PrimeField;
5use ark_r1cs_std::fields::fp::FpVar;
6use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError};
7use ark_std::fmt::Debug;
8
9/// FCircuit defines the trait of the circuit of the F function, which is the one being folded (ie.
10/// inside the agmented F' function).
11/// The parameter z_i denotes the current state, and z_{i+1} denotes the next state after applying
12/// the step.
13pub trait FCircuit<F: PrimeField>: Clone + Copy + Debug {
14 type Params: Debug;
15
16 /// returns a new FCircuit instance
17 fn new(params: Self::Params) -> Self;
18
19 /// computes the next state values in place, assigning z_{i+1} into z_i, and computing the new
20 /// z_{i+1}
21 fn step_native(
22 // this method uses self, so that each FCircuit implementation (and different frontends)
23 // can hold a state if needed to store data to compute the next state.
24 self,
25 z_i: Vec<F>,
26 ) -> Result<Vec<F>, Error>;
27
28 /// generates the constraints for the step of F for the given z_i
29 fn generate_step_constraints(
30 // this method uses self, so that each FCircuit implementation (and different frontends)
31 // can hold a state if needed to store data to generate the constraints.
32 self,
33 cs: ConstraintSystemRef<F>,
34 z_i: Vec<FpVar<F>>,
35 ) -> Result<Vec<FpVar<F>>, SynthesisError>;
36}
37
38#[cfg(test)]
39pub mod tests {
40 use super::*;
41 use ark_pallas::Fr;
42 use ark_r1cs_std::{alloc::AllocVar, eq::EqGadget};
43 use ark_relations::r1cs::{
44 ConstraintSynthesizer, ConstraintSystem, ConstraintSystemRef, SynthesisError,
45 };
46 use core::marker::PhantomData;
47
48 /// CubicFCircuit is a struct that implements the FCircuit trait, for the R1CS example circuit
49 /// from https://www.vitalik.ca/general/2016/12/10/qap.html, which checks `x^3 + x + 5 = y`. It
50 /// has 2 public inputs which are used as the state. `z_i` is used as `x`, and `z_{i+1}` is
51 /// used as `y`, and at the next step, `z_{i+1}` will be assigned to `z_i`, and a new `z+{i+1}`
52 /// will be computted.
53 #[derive(Clone, Copy, Debug)]
54 pub struct CubicFCircuit<F: PrimeField> {
55 _f: PhantomData<F>,
56 }
57 impl<F: PrimeField> FCircuit<F> for CubicFCircuit<F> {
58 type Params = ();
59 fn new(_params: Self::Params) -> Self {
60 Self { _f: PhantomData }
61 }
62 fn step_native(self, z_i: Vec<F>) -> Result<Vec<F>, Error> {
63 Ok(vec![z_i[0] * z_i[0] * z_i[0] + z_i[0] + F::from(5_u32)])
64 }
65 fn generate_step_constraints(
66 self,
67 cs: ConstraintSystemRef<F>,
68 z_i: Vec<FpVar<F>>,
69 ) -> Result<Vec<FpVar<F>>, SynthesisError> {
70 let five = FpVar::<F>::new_constant(cs.clone(), F::from(5u32))?;
71 let z_i = z_i[0].clone();
72
73 Ok(vec![&z_i * &z_i * &z_i + &z_i + &five])
74 }
75 }
76
77 /// CustomFCircuit is a circuit that has the number of constraints specified in the
78 /// `n_constraints` parameter. Note that the generated circuit will have very sparse matrices.
79 #[derive(Clone, Copy, Debug)]
80 pub struct CustomFCircuit<F: PrimeField> {
81 _f: PhantomData<F>,
82 pub n_constraints: usize,
83 }
84 impl<F: PrimeField> FCircuit<F> for CustomFCircuit<F> {
85 type Params = usize;
86
87 fn new(params: Self::Params) -> Self {
88 Self {
89 _f: PhantomData,
90 n_constraints: params,
91 }
92 }
93 fn step_native(self, z_i: Vec<F>) -> Result<Vec<F>, Error> {
94 let mut z_i1 = F::one();
95 for _ in 0..self.n_constraints - 1 {
96 z_i1 *= z_i[0];
97 }
98 Ok(vec![z_i1])
99 }
100 fn generate_step_constraints(
101 self,
102 cs: ConstraintSystemRef<F>,
103 z_i: Vec<FpVar<F>>,
104 ) -> Result<Vec<FpVar<F>>, SynthesisError> {
105 let mut z_i1 = FpVar::<F>::new_witness(cs.clone(), || Ok(F::one()))?;
106 for _ in 0..self.n_constraints - 1 {
107 z_i1 *= z_i[0].clone();
108 }
109
110 Ok(vec![z_i1])
111 }
112 }
113
114 /// WrapperCircuit is a circuit that wraps any circuit that implements the FCircuit trait. This
115 /// is used to test the `FCircuit.generate_step_constraints` method. This is a similar wrapping
116 /// than the one done in the `AugmentedFCircuit`, but without adding all the extra constraints
117 /// of the AugmentedF circuit logic, in order to run lighter tests when we're not interested in
118 /// the the AugmentedF logic but in the wrapping of the circuits.
119 pub struct WrapperCircuit<F: PrimeField, FC: FCircuit<F>> {
120 pub FC: FC, // F circuit
121 pub z_i: Option<Vec<F>>,
122 pub z_i1: Option<Vec<F>>,
123 }
124 impl<F, FC> ConstraintSynthesizer<F> for WrapperCircuit<F, FC>
125 where
126 F: PrimeField,
127 FC: FCircuit<F>,
128 {
129 fn generate_constraints(self, cs: ConstraintSystemRef<F>) -> Result<(), SynthesisError> {
130 let z_i = Vec::<FpVar<F>>::new_witness(cs.clone(), || {
131 Ok(self.z_i.unwrap_or(vec![F::zero()]))
132 })?;
133 let z_i1 = Vec::<FpVar<F>>::new_input(cs.clone(), || {
134 Ok(self.z_i1.unwrap_or(vec![F::zero()]))
135 })?;
136 let computed_z_i1 = self.FC.generate_step_constraints(cs.clone(), z_i.clone())?;
137
138 computed_z_i1.enforce_equal(&z_i1)?;
139 Ok(())
140 }
141 }
142
143 #[test]
144 fn test_testfcircuit() {
145 let cs = ConstraintSystem::<Fr>::new_ref();
146 let F_circuit = CubicFCircuit::<Fr>::new(());
147
148 let wrapper_circuit = WrapperCircuit::<Fr, CubicFCircuit<Fr>> {
149 FC: F_circuit,
150 z_i: Some(vec![Fr::from(3_u32)]),
151 z_i1: Some(vec![Fr::from(35_u32)]),
152 };
153 wrapper_circuit.generate_constraints(cs.clone()).unwrap();
154 assert_eq!(cs.num_constraints(), 3);
155 }
156
157 #[test]
158 fn test_customtestfcircuit() {
159 let cs = ConstraintSystem::<Fr>::new_ref();
160 let n_constraints = 1000;
161 let custom_circuit = CustomFCircuit::<Fr>::new(n_constraints);
162 let z_i = vec![Fr::from(5_u32)];
163 let wrapper_circuit = WrapperCircuit::<Fr, CustomFCircuit<Fr>> {
164 FC: custom_circuit,
165 z_i: Some(z_i.clone()),
166 z_i1: Some(custom_circuit.step_native(z_i).unwrap()),
167 };
168 wrapper_circuit.generate_constraints(cs.clone()).unwrap();
169 assert_eq!(cs.num_constraints(), n_constraints);
170 }
171}