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 G = pasta_curves::pallas::Point;
130
131 fn synthesize_tiny_r1cs_bellperson<Scalar: PrimeField, CS: ConstraintSystem<Scalar>>(
132 cs: &mut CS,
133 x_val: Option<Scalar>,
134 ) -> Result<(), SynthesisError> {
135 // Consider a cubic equation: `x^3 + x + 5 = y`, where `x` and `y` are respectively the input and output.
136 let x = AllocatedNum::alloc(cs.namespace(|| "x"), || Ok(x_val.unwrap()))?;
137 let _ = x.inputize(cs.namespace(|| "x is input"));
138
139 let x_sq = x.square(cs.namespace(|| "x_sq"))?;
140 let x_cu = x_sq.mul(cs.namespace(|| "x_cu"), &x)?;
141 let y = AllocatedNum::alloc(cs.namespace(|| "y"), || {
142 Ok(x_cu.get_value().unwrap() + x.get_value().unwrap() + Scalar::from(5u64))
143 })?;
144 let _ = y.inputize(cs.namespace(|| "y is output"));
145
146 cs.enforce(
147 || "y = x^3 + x + 5",
148 |lc| {
149 lc + x_cu.get_variable()
150 + x.get_variable()
151 + CS::one()
152 + CS::one()
153 + CS::one()
154 + CS::one()
155 + CS::one()
156 },
157 |lc| lc + CS::one(),
158 |lc| lc + y.get_variable(),
159 );
160
161 Ok(())
162 }
163
164 fn test_tiny_r1cs_bellperson_with<G>()
165 where
166 G: Group,
167 {
168 use crate::bellperson::{
169 r1cs::{NovaShape, NovaWitness},
170 shape_cs::ShapeCS,
171 solver::SatisfyingAssignment,
172 };
173
174 // First create the shape
175 let mut cs: ShapeCS<G> = ShapeCS::new();
176 let _ = synthesize_tiny_r1cs_bellperson(&mut cs, None);
177 let (shape, ck) = cs.r1cs_shape();
178 let ro_consts =
179 <<G as Group>::RO as ROTrait<<G as Group>::Base, <G as Group>::Scalar>>::Constants::new();
180
181 // Now get the instance and assignment for one instance
182 let mut cs: SatisfyingAssignment<G> = SatisfyingAssignment::new();
183 let _ = synthesize_tiny_r1cs_bellperson(&mut cs, Some(G::Scalar::from(5)));
184 let (U1, W1) = cs.r1cs_instance_and_witness(&shape, &ck).unwrap();
185
186 // Make sure that the first instance is satisfiable
187 assert!(shape.is_sat(&ck, &U1, &W1).is_ok());
188
189 // Now get the instance and assignment for second instance
190 let mut cs: SatisfyingAssignment<G> = SatisfyingAssignment::new();
191 let _ = synthesize_tiny_r1cs_bellperson(&mut cs, Some(G::Scalar::from(135)));
192 let (U2, W2) = cs.r1cs_instance_and_witness(&shape, &ck).unwrap();
193
194 // Make sure that the second instance is satisfiable
195 assert!(shape.is_sat(&ck, &U2, &W2).is_ok());
196
197 // execute a sequence of folds
198 execute_sequence(
199 &ck,
200 &ro_consts,
201 &<G as Group>::Scalar::ZERO,
202 &shape,
203 &U1,
204 &W1,
205 &U2,
206 &W2,
207 );
208 }
209
210 #[test]
211 fn test_tiny_r1cs_bellperson() {
212 test_tiny_r1cs_bellperson_with::<G>();
213 }
214
215 #[allow(clippy::too_many_arguments)]
216 fn execute_sequence<G>(
217 ck: &CommitmentKey<G>,
218 ro_consts: &<<G as Group>::RO as ROTrait<<G as Group>::Base, <G as Group>::Scalar>>::Constants,
219 pp_digest: &<G as Group>::Scalar,
220 shape: &R1CSShape<G>,
221 U1: &R1CSInstance<G>,
222 W1: &R1CSWitness<G>,
223 U2: &R1CSInstance<G>,
224 W2: &R1CSWitness<G>,
225 ) where
226 G: Group,
227 {
228 // produce a default running instance
229 let mut r_W = RelaxedR1CSWitness::default(shape);
230 let mut r_U = RelaxedR1CSInstance::default(ck, shape);
231
232 // produce a step SNARK with (W1, U1) as the first incoming witness-instance pair
233 let res = NIFS::prove(ck, ro_consts, pp_digest, shape, &r_U, &r_W, U1, W1);
234 assert!(res.is_ok());
235 let (nifs, (_U, W)) = res.unwrap();
236
237 // verify the step SNARK with U1 as the first incoming instance
238 let res = nifs.verify(ro_consts, pp_digest, &r_U, U1);
239 assert!(res.is_ok());
240 let U = res.unwrap();
241
242 assert_eq!(U, _U);
243
244 // update the running witness and instance
245 r_W = W;
246 r_U = U;
247
248 // produce a step SNARK with (W2, U2) as the second incoming witness-instance pair
249 let res = NIFS::prove(ck, ro_consts, pp_digest, shape, &r_U, &r_W, U2, W2);
250 assert!(res.is_ok());
251 let (nifs, (_U, W)) = res.unwrap();
252
253 // verify the step SNARK with U1 as the first incoming instance
254 let res = nifs.verify(ro_consts, pp_digest, &r_U, U2);
255 assert!(res.is_ok());
256 let U = res.unwrap();
257
258 assert_eq!(U, _U);
259
260 // update the running witness and instance
261 r_W = W;
262 r_U = U;
263
264 // check if the running instance is satisfiable
265 assert!(shape.is_sat_relaxed(ck, &r_U, &r_W).is_ok());
266 }
267
268 fn test_tiny_r1cs_with<G: Group>() {
269 let one = <G::Scalar as Field>::ONE;
270 let (num_cons, num_vars, num_io, A, B, C) = {
271 let num_cons = 4;
272 let num_vars = 3;
273 let num_io = 2;
274
275 // Consider a cubic equation: `x^3 + x + 5 = y`, where `x` and `y` are respectively the input and output.
276 // The R1CS for this problem consists of the following constraints:
277 // `I0 * I0 - Z0 = 0`
278 // `Z0 * I0 - Z1 = 0`
279 // `(Z1 + I0) * 1 - Z2 = 0`
280 // `(Z2 + 5) * 1 - I1 = 0`
281
282 // Relaxed R1CS is a set of three sparse matrices (A B C), where there is a row for every
283 // constraint and a column for every entry in z = (vars, u, inputs)
284 // An R1CS instance is satisfiable iff:
285 // Az \circ Bz = u \cdot Cz + E, where z = (vars, 1, inputs)
286 let mut A: Vec<(usize, usize, G::Scalar)> = Vec::new();
287 let mut B: Vec<(usize, usize, G::Scalar)> = Vec::new();
288 let mut C: Vec<(usize, usize, G::Scalar)> = Vec::new();
289
290 // constraint 0 entries in (A,B,C)
291 // `I0 * I0 - Z0 = 0`
292 A.push((0, num_vars + 1, one));
293 B.push((0, num_vars + 1, one));
294 C.push((0, 0, one));
295
296 // constraint 1 entries in (A,B,C)
297 // `Z0 * I0 - Z1 = 0`
298 A.push((1, 0, one));
299 B.push((1, num_vars + 1, one));
300 C.push((1, 1, one));
301
302 // constraint 2 entries in (A,B,C)
303 // `(Z1 + I0) * 1 - Z2 = 0`
304 A.push((2, 1, one));
305 A.push((2, num_vars + 1, one));
306 B.push((2, num_vars, one));
307 C.push((2, 2, one));
308
309 // constraint 3 entries in (A,B,C)
310 // `(Z2 + 5) * 1 - I1 = 0`
311 A.push((3, 2, one));
312 A.push((3, num_vars, one + one + one + one + one));
313 B.push((3, num_vars, one));
314 C.push((3, num_vars + 2, one));
315
316 (num_cons, num_vars, num_io, A, B, C)
317 };
318
319 // create a shape object
320 let S = {
321 let res = R1CSShape::new(num_cons, num_vars, num_io, &A, &B, &C);
322 assert!(res.is_ok());
323 res.unwrap()
324 };
325
326 // generate generators and ro constants
327 let ck = R1CS::<G>::commitment_key(&S);
328 let ro_consts =
329 <<G as Group>::RO as ROTrait<<G as Group>::Base, <G as Group>::Scalar>>::Constants::new();
330
331 let rand_inst_witness_generator =
332 |ck: &CommitmentKey<G>, I: &G::Scalar| -> (G::Scalar, R1CSInstance<G>, R1CSWitness<G>) {
333 let i0 = *I;
334
335 // compute a satisfying (vars, X) tuple
336 let (O, vars, X) = {
337 let z0 = i0 * i0; // constraint 0
338 let z1 = i0 * z0; // constraint 1
339 let z2 = z1 + i0; // constraint 2
340 let i1 = z2 + one + one + one + one + one; // constraint 3
341
342 // store the witness and IO for the instance
343 let W = vec![z0, z1, z2];
344 let X = vec![i0, i1];
345 (i1, W, X)
346 };
347
348 let W = {
349 let res = R1CSWitness::new(&S, &vars);
350 assert!(res.is_ok());
351 res.unwrap()
352 };
353 let U = {
354 let comm_W = W.commit(ck);
355 let res = R1CSInstance::new(&S, &comm_W, &X);
356 assert!(res.is_ok());
357 res.unwrap()
358 };
359
360 // check that generated instance is satisfiable
361 assert!(S.is_sat(ck, &U, &W).is_ok());
362
363 (O, U, W)
364 };
365
366 let mut csprng: OsRng = OsRng;
367 let I = G::Scalar::random(&mut csprng); // the first input is picked randomly for the first instance
368 let (O, U1, W1) = rand_inst_witness_generator(&ck, &I);
369 let (_O, U2, W2) = rand_inst_witness_generator(&ck, &O);
370
371 // execute a sequence of folds
372 execute_sequence(
373 &ck,
374 &ro_consts,
375 &<G as Group>::Scalar::ZERO,
376 &S,
377 &U1,
378 &W1,
379 &U2,
380 &W2,
381 );
382 }
383
384 #[test]
385 fn test_tiny_r1cs() {
386 test_tiny_r1cs_with::<pasta_curves::pallas::Point>();
387 }
388}