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