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 crate::{
  6  constants::{NUM_CHALLENGE_BITS, NUM_FE_FOR_RO},
  7  errors::NovaError,
  8  r1cs::{R1CSGens, R1CSInstance, R1CSShape, R1CSWitness, RelaxedR1CSInstance, RelaxedR1CSWitness},
  9  traits::{
 10    commitment::{CommitmentTrait, CompressedCommitmentTrait},
 11    AbsorbInROTrait, Group, ROTrait,
 12  },
 13  CompressedCommitment,
 14};
 15use core::marker::PhantomData;
 16use serde::{Deserialize, Serialize};
 17
 18/// A SNARK that holds the proof of a step of an incremental computation
 19#[allow(clippy::upper_case_acronyms)]
 20#[derive(Clone, Debug, Serialize, Deserialize)]
 21#[serde(bound = "")]
 22pub struct NIFS<G: Group> {
 23  pub(crate) comm_T: CompressedCommitment<G>,
 24  _p: PhantomData<G>,
 25}
 26
 27type ROConstants<G> =
 28  <<G as Group>::RO as ROTrait<<G as Group>::Base, <G as Group>::Scalar>>::Constants;
 29
 30impl<G: Group> NIFS<G> {
 31  /// Takes as input a Relaxed R1CS instance-witness tuple `(U1, W1)` and
 32  /// an R1CS instance-witness tuple `(U2, W2)` with the same structure `shape`
 33  /// and defined with respect to the same `gens`, and outputs
 34  /// a folded Relaxed R1CS instance-witness tuple `(U, W)` of the same shape `shape`,
 35  /// with the guarantee that the folded witness `W` satisfies the folded instance `U`
 36  /// if and only if `W1` satisfies `U1` and `W2` satisfies `U2`.
 37  pub fn prove(
 38    gens: &R1CSGens<G>,
 39    ro_consts: &ROConstants<G>,
 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 S to the transcript
 50    S.absorb_in_ro(&mut ro);
 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(gens, 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    S: &R1CSShape<G>,
 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 S to the transcript
 97    S.absorb_in_ro(&mut ro);
 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 = self.comm_T.decompress()?;
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::traits::{Group, ROConstantsTrait};
122  use ::bellperson::{gadgets::num::AllocatedNum, ConstraintSystem, SynthesisError};
123  use ff::{Field, PrimeField};
124  use rand::rngs::OsRng;
125
126  type S = pasta_curves::pallas::Scalar;
127  type G = pasta_curves::pallas::Point;
128
129  fn synthesize_tiny_r1cs_bellperson<Scalar: PrimeField, CS: ConstraintSystem<Scalar>>(
130    cs: &mut CS,
131    x_val: Option<Scalar>,
132  ) -> Result<(), SynthesisError> {
133    // Consider a cubic equation: `x^3 + x + 5 = y`, where `x` and `y` are respectively the input and output.
134    let x = AllocatedNum::alloc(cs.namespace(|| "x"), || Ok(x_val.unwrap()))?;
135    let _ = x.inputize(cs.namespace(|| "x is input"));
136
137    let x_sq = x.square(cs.namespace(|| "x_sq"))?;
138    let x_cu = x_sq.mul(cs.namespace(|| "x_cu"), &x)?;
139    let y = AllocatedNum::alloc(cs.namespace(|| "y"), || {
140      Ok(x_cu.get_value().unwrap() + x.get_value().unwrap() + Scalar::from(5u64))
141    })?;
142    let _ = y.inputize(cs.namespace(|| "y is output"));
143
144    cs.enforce(
145      || "y = x^3 + x + 5",
146      |lc| {
147        lc + x_cu.get_variable()
148          + x.get_variable()
149          + CS::one()
150          + CS::one()
151          + CS::one()
152          + CS::one()
153          + CS::one()
154      },
155      |lc| lc + CS::one(),
156      |lc| lc + y.get_variable(),
157    );
158
159    Ok(())
160  }
161
162  #[test]
163  fn test_tiny_r1cs_bellperson() {
164    use crate::bellperson::{
165      r1cs::{NovaShape, NovaWitness},
166      shape_cs::ShapeCS,
167      solver::SatisfyingAssignment,
168    };
169
170    // First create the shape
171    let mut cs: ShapeCS<G> = ShapeCS::new();
172    let _ = synthesize_tiny_r1cs_bellperson(&mut cs, None);
173    let shape = cs.r1cs_shape();
174    let gens = cs.r1cs_gens();
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, &gens).unwrap();
182
183    // Make sure that the first instance is satisfiable
184    assert!(shape.is_sat(&gens, &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, &gens).unwrap();
190
191    // Make sure that the second instance is satisfiable
192    assert!(shape.is_sat(&gens, &U2, &W2).is_ok());
193
194    // execute a sequence of folds
195    execute_sequence(&gens, &ro_consts, &shape, &U1, &W1, &U2, &W2);
196  }
197
198  fn execute_sequence(
199    gens: &R1CSGens<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(gens, shape);
210
211    // produce a step SNARK with (W1, U1) as the first incoming witness-instance pair
212    let res = NIFS::prove(gens, 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, &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(gens, 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, &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(gens, &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 gens = R1CSGens::new(num_cons, num_vars);
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      |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}