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;
  9pub mod errors;
 10pub mod pasta;
 11pub mod r1cs;
 12pub mod traits;
 13
 14use std::marker::PhantomData;
 15
 16use commitments::{AppendToTranscriptTrait, CompressedCommitment};
 17use errors::NovaError;
 18use merlin::Transcript;
 19use r1cs::{
 20  R1CSGens, R1CSInstance, R1CSShape, R1CSWitness, RelaxedR1CSInstance, RelaxedR1CSWitness,
 21};
 22use traits::{ChallengeTrait, Group};
 23
 24/// A SNARK that holds the proof of a step of an incremental computation
 25pub struct StepSNARK<G: Group> {
 26  comm_T: CompressedCommitment<G::CompressedGroupElement>,
 27  _p: PhantomData<G>,
 28}
 29
 30impl<G: Group> StepSNARK<G> {
 31  fn protocol_name() -> &'static [u8] {
 32    b"NovaStepSNARK"
 33  }
 34
 35  /// Takes as input a Relaxed R1CS instance-witness tuple `(U1, W1)` and
 36  /// an R1CS instance-witness tuple `(U2, W2)` with the same structure `shape`
 37  /// and defined with respect to the same `gens`, and outputs
 38  /// a folded Relaxed R1CS instance-witness tuple `(U, W)` of the same shape `shape`,
 39  /// with the guarantee that the folded witness `W` satisfies the folded instance `U`
 40  /// if and only if `W1` satisfies `U1` and `W2` satisfies `U2`.
 41  pub fn prove(
 42    gens: &R1CSGens<G>,
 43    S: &R1CSShape<G>,
 44    U1: &RelaxedR1CSInstance<G>,
 45    W1: &RelaxedR1CSWitness<G>,
 46    U2: &R1CSInstance<G>,
 47    W2: &R1CSWitness<G>,
 48    transcript: &mut Transcript,
 49  ) -> Result<
 50    (
 51      StepSNARK<G>,
 52      (RelaxedR1CSInstance<G>, RelaxedR1CSWitness<G>),
 53    ),
 54    NovaError,
 55  > {
 56    // append the protocol name to the transcript
 57    //transcript.append_protocol_name(StepSNARK::protocol_name());
 58    transcript.append_message(b"protocol-name", StepSNARK::<G>::protocol_name());
 59
 60    // compute a commitment to the cross-term
 61    let (T, comm_T) = S.commit_T(gens, U1, W1, U2, W2)?;
 62
 63    // append `comm_T` to the transcript and obtain a challenge
 64    comm_T.append_to_transcript(b"comm_T", transcript);
 65
 66    // compute a challenge from the transcript
 67    let r = G::Scalar::challenge(b"r", transcript);
 68
 69    // fold the instance using `r` and `comm_T`
 70    let U = U1.fold(U2, &comm_T, &r)?;
 71
 72    // fold the witness using `r` and `T`
 73    let W = W1.fold(W2, &T, &r)?;
 74
 75    // return the folded instance and witness
 76    Ok((
 77      StepSNARK {
 78        comm_T,
 79        _p: Default::default(),
 80      },
 81      (U, W),
 82    ))
 83  }
 84
 85  /// Takes as input a relaxed R1CS instance `U1` and and R1CS instance `U2`
 86  /// with the same shape and defined with respect to the same parameters,
 87  /// and outputs a folded instance `U` with the same shape,
 88  /// with the guarantee that the folded instance `U`
 89  /// if and only if `U1` and `U2` are satisfiable.
 90  pub fn verify(
 91    &self,
 92    U1: &RelaxedR1CSInstance<G>,
 93    U2: &R1CSInstance<G>,
 94    transcript: &mut Transcript,
 95  ) -> Result<RelaxedR1CSInstance<G>, NovaError> {
 96    // append the protocol name to the transcript
 97    transcript.append_message(b"protocol-name", StepSNARK::<G>::protocol_name());
 98
 99    // append `comm_T` to the transcript and obtain a challenge
100    self.comm_T.append_to_transcript(b"comm_T", transcript);
101
102    // compute a challenge from the transcript
103    let r = G::Scalar::challenge(b"r", transcript);
104
105    // fold the instance using `r` and `comm_T`
106    let U = U1.fold(U2, &self.comm_T, &r)?;
107
108    // return the folded instance
109    Ok(U)
110  }
111}
112
113/// A SNARK that holds the proof of the final step of an incremental computation
114pub struct FinalSNARK<G: Group> {
115  W: RelaxedR1CSWitness<G>,
116}
117
118impl<G: Group> FinalSNARK<G> {
119  /// Produces a proof of a instance given its satisfying witness `W`.
120  pub fn prove(W: &RelaxedR1CSWitness<G>) -> Result<FinalSNARK<G>, NovaError> {
121    Ok(FinalSNARK { W: W.clone() })
122  }
123
124  /// Verifies the proof of a folded instance `U` given its shape `S` public parameters `gens`
125  pub fn verify(
126    &self,
127    gens: &R1CSGens<G>,
128    S: &R1CSShape<G>,
129    U: &RelaxedR1CSInstance<G>,
130  ) -> Result<(), NovaError> {
131    // check that the witness is a valid witness to the folded instance `U`
132    S.is_sat_relaxed(gens, U, &self.W)
133  }
134}
135
136#[cfg(test)]
137mod tests {
138  use super::*;
139  use crate::traits::PrimeField;
140  use rand::rngs::OsRng;
141
142  type S = pasta_curves::pallas::Scalar;
143  type G = pasta_curves::pallas::Point;
144
145  #[test]
146  fn test_tiny_r1cs() {
147    let one = S::one();
148    let (num_cons, num_vars, num_io, A, B, C) = {
149      let num_cons = 4;
150      let num_vars = 4;
151      let num_io = 2;
152
153      // Consider a cubic equation: `x^3 + x + 5 = y`, where `x` and `y` are respectively the input and output.
154      // The R1CS for this problem consists of the following constraints:
155      // `I0 * I0 - Z0 = 0`
156      // `Z0 * I0 - Z1 = 0`
157      // `(Z1 + I0) * 1 - Z2 = 0`
158      // `(Z2 + 5) * 1 - I1 = 0`
159
160      // Relaxed R1CS is a set of three sparse matrices (A B C), where there is a row for every
161      // constraint and a column for every entry in z = (vars, u, inputs)
162      // An R1CS instance is satisfiable iff:
163      // Az \circ Bz = u \cdot Cz + E, where z = (vars, 1, inputs)
164      let mut A: Vec<(usize, usize, S)> = Vec::new();
165      let mut B: Vec<(usize, usize, S)> = Vec::new();
166      let mut C: Vec<(usize, usize, S)> = Vec::new();
167
168      // constraint 0 entries in (A,B,C)
169      // `I0 * I0 - Z0 = 0`
170      A.push((0, num_vars + 1, one));
171      B.push((0, num_vars + 1, one));
172      C.push((0, 0, one));
173
174      // constraint 1 entries in (A,B,C)
175      // `Z0 * I0 - Z1 = 0`
176      A.push((1, 0, one));
177      B.push((1, num_vars + 1, one));
178      C.push((1, 1, one));
179
180      // constraint 2 entries in (A,B,C)
181      // `(Z1 + I0) * 1 - Z2 = 0`
182      A.push((2, 1, one));
183      A.push((2, num_vars + 1, one));
184      B.push((2, num_vars, one));
185      C.push((2, 2, one));
186
187      // constraint 3 entries in (A,B,C)
188      // `(Z2 + 5) * 1 - I1 = 0`
189      A.push((3, 2, one));
190      A.push((3, num_vars, one + one + one + one + one));
191      B.push((3, num_vars, one));
192      C.push((3, num_vars + 2, one));
193
194      (num_cons, num_vars, num_io, A, B, C)
195    };
196
197    // create a shape object
198    let S = {
199      let res = R1CSShape::new(num_cons, num_vars, num_io, &A, &B, &C);
200      assert!(res.is_ok());
201      res.unwrap()
202    };
203
204    // generate generators
205    let gens = R1CSGens::new(num_cons, num_vars);
206
207    let rand_inst_witness_generator =
208      |gens: &R1CSGens<G>, I: &S| -> (S, R1CSInstance<G>, R1CSWitness<G>) {
209        let i0 = *I;
210
211        // compute a satisfying (vars, X) tuple
212        let (O, vars, X) = {
213          let z0 = i0 * i0; // constraint 0
214          let z1 = i0 * z0; // constraint 1
215          let z2 = z1 + i0; // constraint 2
216          let i1 = z2 + one + one + one + one + one; // constraint 3
217
218          // store the witness and IO for the instance
219          let W = vec![z0, z1, z2, S::zero()];
220          let X = vec![i0, i1];
221          (i1, W, X)
222        };
223
224        let W = {
225          let res = R1CSWitness::new(&S, &vars);
226          assert!(res.is_ok());
227          res.unwrap()
228        };
229        let U = {
230          let comm_W = W.commit(gens);
231          let res = R1CSInstance::new(&S, &comm_W, &X);
232          assert!(res.is_ok());
233          res.unwrap()
234        };
235
236        // check that generated instance is satisfiable
237        assert!(S.is_sat(gens, &U, &W).is_ok());
238
239        (O, U, W)
240      };
241
242    let mut csprng: OsRng = OsRng;
243    let I = S::random(&mut csprng); // the first input is picked randomly for the first instance
244    let (O, U1, W1) = rand_inst_witness_generator(&gens, &I);
245    let (_O, U2, W2) = rand_inst_witness_generator(&gens, &O);
246
247    // produce a default running instance
248    let mut r_W = RelaxedR1CSWitness::default(&S);
249    let mut r_U = RelaxedR1CSInstance::default(&gens, &S);
250
251    // produce a step SNARK with (W1, U1) as the first incoming witness-instance pair
252    let mut prover_transcript = Transcript::new(b"StepSNARKExample");
253    let res = StepSNARK::prove(&gens, &S, &r_U, &r_W, &U1, &W1, &mut prover_transcript);
254    assert!(res.is_ok());
255    let (step_snark, (_U, W)) = res.unwrap();
256
257    // verify the step SNARK with U1 as the first incoming instance
258    let mut verifier_transcript = Transcript::new(b"StepSNARKExample");
259    let res = step_snark.verify(&r_U, &U1, &mut verifier_transcript);
260    assert!(res.is_ok());
261    let U = res.unwrap();
262
263    assert_eq!(U, _U);
264
265    // update the running witness and instance
266    r_W = W;
267    r_U = U;
268
269    // produce a step SNARK with (W2, U2) as the second incoming witness-instance pair
270    let res = StepSNARK::prove(&gens, &S, &r_U, &r_W, &U2, &W2, &mut prover_transcript);
271    assert!(res.is_ok());
272    let (step_snark, (_U, W)) = res.unwrap();
273
274    // verify the step SNARK with U1 as the first incoming instance
275    let res = step_snark.verify(&r_U, &U2, &mut verifier_transcript);
276    assert!(res.is_ok());
277    let U = res.unwrap();
278
279    assert_eq!(U, _U);
280
281    // update the running witness and instance
282    r_W = W;
283    r_U = U;
284
285    // produce a final SNARK
286    let res = FinalSNARK::prove(&r_W);
287    assert!(res.is_ok());
288    let final_snark = res.unwrap();
289    // verify the final SNARK
290    let res = final_snark.verify(&gens, &S, &r_U);
291    assert!(res.is_ok());
292  }
293}