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