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