Nova/src/nifs.rs
src/nifs.rsRaw
1//! This module implements a non-interactive folding scheme
2#![allow(non_snake_case)]
3#![allow(clippy::type_complexity)]
4
5use crate::{
6 constants::{NUM_CHALLENGE_BITS, NUM_FE_FOR_RO},
7 errors::NovaError,
8 r1cs::{R1CSGens, R1CSInstance, R1CSShape, R1CSWitness, RelaxedR1CSInstance, RelaxedR1CSWitness},
9 traits::{commitment::CommitmentTrait, AbsorbInROTrait, Group, ROTrait},
10 Commitment, CompressedCommitment,
11};
12use core::marker::PhantomData;
13use serde::{Deserialize, Serialize};
14
15/// A SNARK that holds the proof of a step of an incremental computation
16#[allow(clippy::upper_case_acronyms)]
17#[derive(Clone, Debug, Serialize, Deserialize)]
18#[serde(bound = "")]
19pub struct NIFS<G: Group> {
20 pub(crate) comm_T: CompressedCommitment<G>,
21 _p: PhantomData<G>,
22}
23
24type ROConstants<G> =
25 <<G as Group>::RO as ROTrait<<G as Group>::Base, <G as Group>::Scalar>>::Constants;
26
27impl<G: Group> NIFS<G> {
28 /// Takes as input a Relaxed R1CS instance-witness tuple `(U1, W1)` and
29 /// an R1CS instance-witness tuple `(U2, W2)` with the same structure `shape`
30 /// and defined with respect to the same `gens`, and outputs
31 /// a folded Relaxed R1CS instance-witness tuple `(U, W)` of the same shape `shape`,
32 /// with the guarantee that the folded witness `W` satisfies the folded instance `U`
33 /// if and only if `W1` satisfies `U1` and `W2` satisfies `U2`.
34 pub fn prove(
35 gens: &R1CSGens<G>,
36 ro_consts: &ROConstants<G>,
37 S: &R1CSShape<G>,
38 U1: &RelaxedR1CSInstance<G>,
39 W1: &RelaxedR1CSWitness<G>,
40 U2: &R1CSInstance<G>,
41 W2: &R1CSWitness<G>,
42 ) -> Result<(NIFS<G>, (RelaxedR1CSInstance<G>, RelaxedR1CSWitness<G>)), NovaError> {
43 // initialize a new RO
44 let mut ro = G::RO::new(ro_consts.clone(), NUM_FE_FOR_RO);
45
46 // append S to the transcript
47 S.absorb_in_ro(&mut ro);
48
49 // append U1 and U2 to transcript
50 U1.absorb_in_ro(&mut ro);
51 U2.absorb_in_ro(&mut ro);
52
53 // compute a commitment to the cross-term
54 let (T, comm_T) = S.commit_T(gens, U1, W1, U2, W2)?;
55
56 // append `comm_T` to the transcript and obtain a challenge
57 comm_T.absorb_in_ro(&mut ro);
58
59 // compute a challenge from the RO
60 let r = ro.squeeze(NUM_CHALLENGE_BITS);
61
62 // fold the instance using `r` and `comm_T`
63 let U = U1.fold(U2, &comm_T, &r)?;
64
65 // fold the witness using `r` and `T`
66 let W = W1.fold(W2, &T, &r)?;
67
68 // return the folded instance and witness
69 Ok((
70 Self {
71 comm_T: comm_T.compress(),
72 _p: Default::default(),
73 },
74 (U, W),
75 ))
76 }
77
78 /// Takes as input a relaxed R1CS instance `U1` and and R1CS instance `U2`
79 /// with the same shape and defined with respect to the same parameters,
80 /// and outputs a folded instance `U` with the same shape,
81 /// with the guarantee that the folded instance `U`
82 /// if and only if `U1` and `U2` are satisfiable.
83 pub fn verify(
84 &self,
85 ro_consts: &ROConstants<G>,
86 S: &R1CSShape<G>,
87 U1: &RelaxedR1CSInstance<G>,
88 U2: &R1CSInstance<G>,
89 ) -> Result<RelaxedR1CSInstance<G>, NovaError> {
90 // initialize a new RO
91 let mut ro = G::RO::new(ro_consts.clone(), NUM_FE_FOR_RO);
92
93 // append S to the transcript
94 S.absorb_in_ro(&mut ro);
95
96 // append U1 and U2 to transcript
97 U1.absorb_in_ro(&mut ro);
98 U2.absorb_in_ro(&mut ro);
99
100 // append `comm_T` to the transcript and obtain a challenge
101 let comm_T = Commitment::<G>::decompress(&self.comm_T)?;
102 comm_T.absorb_in_ro(&mut ro);
103
104 // compute a challenge from the RO
105 let r = ro.squeeze(NUM_CHALLENGE_BITS);
106
107 // fold the instance using `r` and `comm_T`
108 let U = U1.fold(U2, &comm_T, &r)?;
109
110 // return the folded instance
111 Ok(U)
112 }
113}
114
115#[cfg(test)]
116mod tests {
117 use super::*;
118 use crate::traits::{Group, ROConstantsTrait};
119 use ::bellperson::{gadgets::num::AllocatedNum, ConstraintSystem, SynthesisError};
120 use ff::{Field, PrimeField};
121 use rand::rngs::OsRng;
122
123 type S = pasta_curves::pallas::Scalar;
124 type G = pasta_curves::pallas::Point;
125
126 fn synthesize_tiny_r1cs_bellperson<Scalar: PrimeField, CS: ConstraintSystem<Scalar>>(
127 cs: &mut CS,
128 x_val: Option<Scalar>,
129 ) -> Result<(), SynthesisError> {
130 // Consider a cubic equation: `x^3 + x + 5 = y`, where `x` and `y` are respectively the input and output.
131 let x = AllocatedNum::alloc(cs.namespace(|| "x"), || Ok(x_val.unwrap()))?;
132 let _ = x.inputize(cs.namespace(|| "x is input"));
133
134 let x_sq = x.square(cs.namespace(|| "x_sq"))?;
135 let x_cu = x_sq.mul(cs.namespace(|| "x_cu"), &x)?;
136 let y = AllocatedNum::alloc(cs.namespace(|| "y"), || {
137 Ok(x_cu.get_value().unwrap() + x.get_value().unwrap() + Scalar::from(5u64))
138 })?;
139 let _ = y.inputize(cs.namespace(|| "y is output"));
140
141 cs.enforce(
142 || "y = x^3 + x + 5",
143 |lc| {
144 lc + x_cu.get_variable()
145 + x.get_variable()
146 + CS::one()
147 + CS::one()
148 + CS::one()
149 + CS::one()
150 + CS::one()
151 },
152 |lc| lc + CS::one(),
153 |lc| lc + y.get_variable(),
154 );
155
156 Ok(())
157 }
158
159 #[test]
160 fn test_tiny_r1cs_bellperson() {
161 use crate::bellperson::{
162 r1cs::{NovaShape, NovaWitness},
163 shape_cs::ShapeCS,
164 solver::SatisfyingAssignment,
165 };
166
167 // First create the shape
168 let mut cs: ShapeCS<G> = ShapeCS::new();
169 let _ = synthesize_tiny_r1cs_bellperson(&mut cs, None);
170 let shape = cs.r1cs_shape();
171 let gens = cs.r1cs_gens();
172 let ro_consts =
173 <<G as Group>::RO as ROTrait<<G as Group>::Base, <G as Group>::Scalar>>::Constants::new();
174
175 // Now get the instance and assignment for one instance
176 let mut cs: SatisfyingAssignment<G> = SatisfyingAssignment::new();
177 let _ = synthesize_tiny_r1cs_bellperson(&mut cs, Some(S::from(5)));
178 let (U1, W1) = cs.r1cs_instance_and_witness(&shape, &gens).unwrap();
179
180 // Make sure that the first instance is satisfiable
181 assert!(shape.is_sat(&gens, &U1, &W1).is_ok());
182
183 // Now get the instance and assignment for second instance
184 let mut cs: SatisfyingAssignment<G> = SatisfyingAssignment::new();
185 let _ = synthesize_tiny_r1cs_bellperson(&mut cs, Some(S::from(135)));
186 let (U2, W2) = cs.r1cs_instance_and_witness(&shape, &gens).unwrap();
187
188 // Make sure that the second instance is satisfiable
189 assert!(shape.is_sat(&gens, &U2, &W2).is_ok());
190
191 // execute a sequence of folds
192 execute_sequence(&gens, &ro_consts, &shape, &U1, &W1, &U2, &W2);
193 }
194
195 fn execute_sequence(
196 gens: &R1CSGens<G>,
197 ro_consts: &<<G as Group>::RO as ROTrait<<G as Group>::Base, <G as Group>::Scalar>>::Constants,
198 shape: &R1CSShape<G>,
199 U1: &R1CSInstance<G>,
200 W1: &R1CSWitness<G>,
201 U2: &R1CSInstance<G>,
202 W2: &R1CSWitness<G>,
203 ) {
204 // produce a default running instance
205 let mut r_W = RelaxedR1CSWitness::default(shape);
206 let mut r_U = RelaxedR1CSInstance::default(gens, shape);
207
208 // produce a step SNARK with (W1, U1) as the first incoming witness-instance pair
209 let res = NIFS::prove(gens, ro_consts, shape, &r_U, &r_W, U1, W1);
210 assert!(res.is_ok());
211 let (nifs, (_U, W)) = res.unwrap();
212
213 // verify the step SNARK with U1 as the first incoming instance
214 let res = nifs.verify(ro_consts, shape, &r_U, U1);
215 assert!(res.is_ok());
216 let U = res.unwrap();
217
218 assert_eq!(U, _U);
219
220 // update the running witness and instance
221 r_W = W;
222 r_U = U;
223
224 // produce a step SNARK with (W2, U2) as the second incoming witness-instance pair
225 let res = NIFS::prove(gens, ro_consts, shape, &r_U, &r_W, U2, W2);
226 assert!(res.is_ok());
227 let (nifs, (_U, W)) = res.unwrap();
228
229 // verify the step SNARK with U1 as the first incoming instance
230 let res = nifs.verify(ro_consts, shape, &r_U, U2);
231 assert!(res.is_ok());
232 let U = res.unwrap();
233
234 assert_eq!(U, _U);
235
236 // update the running witness and instance
237 r_W = W;
238 r_U = U;
239
240 // check if the running instance is satisfiable
241 assert!(shape.is_sat_relaxed(gens, &r_U, &r_W).is_ok());
242 }
243
244 #[test]
245 fn test_tiny_r1cs() {
246 let one = S::one();
247 let (num_cons, num_vars, num_io, A, B, C) = {
248 let num_cons = 4;
249 let num_vars = 4;
250 let num_io = 2;
251
252 // Consider a cubic equation: `x^3 + x + 5 = y`, where `x` and `y` are respectively the input and output.
253 // The R1CS for this problem consists of the following constraints:
254 // `I0 * I0 - Z0 = 0`
255 // `Z0 * I0 - Z1 = 0`
256 // `(Z1 + I0) * 1 - Z2 = 0`
257 // `(Z2 + 5) * 1 - I1 = 0`
258
259 // Relaxed R1CS is a set of three sparse matrices (A B C), where there is a row for every
260 // constraint and a column for every entry in z = (vars, u, inputs)
261 // An R1CS instance is satisfiable iff:
262 // Az \circ Bz = u \cdot Cz + E, where z = (vars, 1, inputs)
263 let mut A: Vec<(usize, usize, S)> = Vec::new();
264 let mut B: Vec<(usize, usize, S)> = Vec::new();
265 let mut C: Vec<(usize, usize, S)> = Vec::new();
266
267 // constraint 0 entries in (A,B,C)
268 // `I0 * I0 - Z0 = 0`
269 A.push((0, num_vars + 1, one));
270 B.push((0, num_vars + 1, one));
271 C.push((0, 0, one));
272
273 // constraint 1 entries in (A,B,C)
274 // `Z0 * I0 - Z1 = 0`
275 A.push((1, 0, one));
276 B.push((1, num_vars + 1, one));
277 C.push((1, 1, one));
278
279 // constraint 2 entries in (A,B,C)
280 // `(Z1 + I0) * 1 - Z2 = 0`
281 A.push((2, 1, one));
282 A.push((2, num_vars + 1, one));
283 B.push((2, num_vars, one));
284 C.push((2, 2, one));
285
286 // constraint 3 entries in (A,B,C)
287 // `(Z2 + 5) * 1 - I1 = 0`
288 A.push((3, 2, one));
289 A.push((3, num_vars, one + one + one + one + one));
290 B.push((3, num_vars, one));
291 C.push((3, num_vars + 2, one));
292
293 (num_cons, num_vars, num_io, A, B, C)
294 };
295
296 // create a shape object
297 let S = {
298 let res = R1CSShape::new(num_cons, num_vars, num_io, &A, &B, &C);
299 assert!(res.is_ok());
300 res.unwrap()
301 };
302
303 // generate generators and ro constants
304 let gens = R1CSGens::new(num_cons, num_vars);
305 let ro_consts =
306 <<G as Group>::RO as ROTrait<<G as Group>::Base, <G as Group>::Scalar>>::Constants::new();
307
308 let rand_inst_witness_generator =
309 |gens: &R1CSGens<G>, I: &S| -> (S, R1CSInstance<G>, R1CSWitness<G>) {
310 let i0 = *I;
311
312 // compute a satisfying (vars, X) tuple
313 let (O, vars, X) = {
314 let z0 = i0 * i0; // constraint 0
315 let z1 = i0 * z0; // constraint 1
316 let z2 = z1 + i0; // constraint 2
317 let i1 = z2 + one + one + one + one + one; // constraint 3
318
319 // store the witness and IO for the instance
320 let W = vec![z0, z1, z2, S::zero()];
321 let X = vec![i0, i1];
322 (i1, W, X)
323 };
324
325 let W = {
326 let res = R1CSWitness::new(&S, &vars);
327 assert!(res.is_ok());
328 res.unwrap()
329 };
330 let U = {
331 let comm_W = W.commit(gens);
332 let res = R1CSInstance::new(&S, &comm_W, &X);
333 assert!(res.is_ok());
334 res.unwrap()
335 };
336
337 // check that generated instance is satisfiable
338 assert!(S.is_sat(gens, &U, &W).is_ok());
339
340 (O, U, W)
341 };
342
343 let mut csprng: OsRng = OsRng;
344 let I = S::random(&mut csprng); // the first input is picked randomly for the first instance
345 let (O, U1, W1) = rand_inst_witness_generator(&gens, &I);
346 let (_O, U2, W2) = rand_inst_witness_generator(&gens, &O);
347
348 // execute a sequence of folds
349 execute_sequence(&gens, &ro_consts, &S, &U1, &W1, &U2, &W2);
350 }
351}