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