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