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