arnaucube
arnaucube/testudoPublic Self-hosted repository
testudo/README.md
README.mdRaw
  1# Spartan: High-speed zkSNARKs without trusted setup
  2
  3![Rust](https://github.com/microsoft/Spartan/workflows/Rust/badge.svg)
  4[![](https://img.shields.io/crates/v/spartan.svg)](<(https://crates.io/crates/spartan)>)
  5
  6Spartan is a high-speed zero-knowledge proof system, a cryptographic primitive that enables a prover to prove a mathematical statement to a verifier without revealing anything besides the validity of the statement. This repository provides `libspartan,` a Rust library that implements a zero-knowledge succinct non-interactive argument of knowledge (zkSNARK), which is a type of zero-knowledge proof system with short proofs and fast verification times. The details of the Spartan proof system are described in our [paper](https://eprint.iacr.org/2019/550) published at [CRYPTO 2020](https://crypto.iacr.org/2020/). The security of the Spartan variant implemented in this library is based on the discrete logarithm problem in the random oracle model.
  7
  8A simple example application is proving the knowledge of a secret s such that H(s) == d for a public d, where H is a cryptographic hash function (e.g., SHA-256, Keccak). A more complex application is a database-backed cloud service that produces proofs of correct state machine transitions for auditability. See this [paper](https://eprint.iacr.org/2020/758.pdf) for an overview and this [paper](https://eprint.iacr.org/2018/907.pdf) for details.
  9
 10Note that this library has _not_ received a security review or audit.
 11
 12## Highlights
 13
 14We now highlight Spartan's distinctive features.
 15
 16- **No "toxic" waste:** Spartan is a _transparent_ zkSNARK and does not require a trusted setup. So, it does not involve any trapdoors that must be kept secret or require a multi-party ceremony to produce public parameters.
 17
 18- **General-purpose:** Spartan produces proofs for arbitrary NP statements. `libspartan` supports NP statements expressed as rank-1 constraint satisfiability (R1CS) instances, a popular language for which there exists efficient transformations and compiler toolchains from high-level programs of interest.
 19
 20- **Sub-linear verification costs:** Spartan is the first transparent proof system with sub-linear verification costs for arbitrary NP statements (e.g., R1CS).
 21
 22- **Standardized security:** Spartan's security relies on the hardness of computing discrete logarithms (a standard cryptographic assumption) in the random oracle model. `libspartan` uses `ristretto255`, a prime-order group abstraction atop `curve25519` (a high-speed elliptic curve). We use [`curve25519-dalek`](https://docs.rs/curve25519-dalek) for arithmetic over `ristretto255`.
 23
 24- **State-of-the-art performance:**
 25  Among transparent SNARKs, Spartan offers the fastest prover with speedups of 36–152× depending on the baseline, produces proofs that are shorter by 1.2–416×, and incurs the lowest verification times with speedups of 3.6–1326×. The only exception is proof sizes under Bulletproofs, but Bulletproofs incurs slower verification both asymptotically and concretely. When compared to the state-of-the-art zkSNARK with trusted setup, Spartan’s prover is 2× faster for arbitrary R1CS instances and 16× faster for data-parallel workloads.
 26
 27### Implementation details
 28
 29`libspartan` uses [`merlin`](https://docs.rs/merlin/) to automate the Fiat-Shamir transform. We also introduce a new type called `RandomTape` that extends a `Transcript` in `merlin` to allow the prover's internal methods to produce private randomness using its private transcript without having to create `OsRng` objects throughout the code. An object of type `RandomTape` is initialized with a new random seed from `OsRng` for each proof produced by the library.
 30
 31## Examples
 32
 33To import `libspartan` into your Rust project, add the following dependency to `Cargo.toml`:
 34
 35```text
 36spartan = "0.4.1"
 37```
 38
 39The following example shows how to use `libspartan` to create and verify a SNARK proof.
 40Some of our public APIs' style is inspired by the underlying crates we use.
 41
 42```rust
 43# extern crate libspartan;
 44# extern crate merlin;
 45# use libspartan::{Instance, SNARKGens, SNARK};
 46# use merlin::Transcript;
 47# fn main() {
 48    // specify the size of an R1CS instance
 49    let num_vars = 1024;
 50    let num_cons = 1024;
 51    let num_inputs = 10;
 52    let num_non_zero_entries = 1024;
 53
 54    // produce public parameters
 55    let gens = SNARKGens::new(num_cons, num_vars, num_inputs, num_non_zero_entries);
 56
 57    // ask the library to produce a synthentic R1CS instance
 58    let (inst, vars, inputs) = Instance::produce_synthetic_r1cs(num_cons, num_vars, num_inputs);
 59
 60    // create a commitment to the R1CS instance
 61    let (comm, decomm) = SNARK::encode(&inst, &gens);
 62
 63    // produce a proof of satisfiability
 64    let mut prover_transcript = Transcript::new(b"snark_example");
 65    let proof = SNARK::prove(&inst, &comm, &decomm, vars, &inputs, &gens, &mut prover_transcript);
 66
 67    // verify the proof of satisfiability
 68    let mut verifier_transcript = Transcript::new(b"snark_example");
 69    assert!(proof
 70      .verify(&comm, &inputs, &mut verifier_transcript, &gens)
 71      .is_ok());
 72    println!("proof verification successful!");
 73# }
 74```
 75
 76Here is another example to use the NIZK variant of the Spartan proof system:
 77
 78```rust
 79# extern crate libspartan;
 80# extern crate merlin;
 81# use libspartan::{Instance, NIZKGens, NIZK};
 82# use merlin::Transcript;
 83# fn main() {
 84    // specify the size of an R1CS instance
 85    let num_vars = 1024;
 86    let num_cons = 1024;
 87    let num_inputs = 10;
 88
 89    // produce public parameters
 90    let gens = NIZKGens::new(num_cons, num_vars, num_inputs);
 91
 92    // ask the library to produce a synthentic R1CS instance
 93    let (inst, vars, inputs) = Instance::produce_synthetic_r1cs(num_cons, num_vars, num_inputs);
 94
 95    // produce a proof of satisfiability
 96    let mut prover_transcript = Transcript::new(b"nizk_example");
 97    let proof = NIZK::prove(&inst, vars, &inputs, &gens, &mut prover_transcript);
 98
 99    // verify the proof of satisfiability
100    let mut verifier_transcript = Transcript::new(b"nizk_example");
101    assert!(proof
102      .verify(&inst, &inputs, &mut verifier_transcript, &gens)
103      .is_ok());
104    println!("proof verification successful!");
105# }
106```
107
108Finally, we provide an example that specifies a custom R1CS instance instead of using a synthetic instance
109
110```rust
111#![allow(non_snake_case)]
112# extern crate curve25519_dalek;
113# extern crate libspartan;
114# extern crate merlin;
115# use curve25519_dalek::scalar::Scalar;
116# use libspartan::{InputsAssignment, Instance, SNARKGens, VarsAssignment, SNARK};
117# use merlin::Transcript;
118# use rand::rngs::OsRng;
119# fn main() {
120  // produce a tiny instance
121  let (
122    num_cons,
123    num_vars,
124    num_inputs,
125    num_non_zero_entries,
126    inst,
127    assignment_vars,
128    assignment_inputs,
129  ) = produce_tiny_r1cs();
130
131  // produce public parameters
132  let gens = SNARKGens::new(num_cons, num_vars, num_inputs, num_non_zero_entries);
133
134  // create a commitment to the R1CS instance
135  let (comm, decomm) = SNARK::encode(&inst, &gens);
136
137  // produce a proof of satisfiability
138  let mut prover_transcript = Transcript::new(b"snark_example");
139  let proof = SNARK::prove(
140    &inst,
141    &comm,
142    &decomm,
143    assignment_vars,
144    &assignment_inputs,
145    &gens,
146    &mut prover_transcript,
147  );
148
149  // verify the proof of satisfiability
150  let mut verifier_transcript = Transcript::new(b"snark_example");
151  assert!(proof
152    .verify(&comm, &assignment_inputs, &mut verifier_transcript, &gens)
153    .is_ok());
154  println!("proof verification successful!");
155# }
156
157# fn produce_tiny_r1cs() -> (
158#  usize,
159#  usize,
160#  usize,
161#  usize,
162#  Instance,
163#  VarsAssignment,
164#  InputsAssignment,
165# ) {
166  // We will use the following example, but one could construct any R1CS instance.
167  // Our R1CS instance is three constraints over five variables and two public inputs
168  // (Z0 + Z1) * I0 - Z2 = 0
169  // (Z0 + I1) * Z2 - Z3 = 0
170  // Z4 * 1 - 0 = 0
171
172  // parameters of the R1CS instance rounded to the nearest power of two
173  let num_cons = 4;
174  let num_vars = 5;
175  let num_inputs = 2;
176  let num_non_zero_entries = 5;
177
178  // We will encode the above constraints into three matrices, where
179  // the coefficients in the matrix are in the little-endian byte order
180  let mut A: Vec<(usize, usize, [u8; 32])> = Vec::new();
181  let mut B: Vec<(usize, usize, [u8; 32])> = Vec::new();
182  let mut C: Vec<(usize, usize, [u8; 32])> = Vec::new();
183
184  // The constraint system is defined over a finite field, which in our case is
185  // the scalar field of ristreeto255/curve25519 i.e., p =  2^{252}+27742317777372353535851937790883648493
186  // To construct these matrices, we will use `curve25519-dalek` but one can use any other method.
187
188  // a variable that holds a byte representation of 1
189  let one = Scalar::one().to_bytes();
190
191  // R1CS is a set of three sparse matrices A B C, where is a row for every
192  // constraint and a column for every entry in z = (vars, 1, inputs)
193  // An R1CS instance is satisfiable iff:
194  // Az \circ Bz = Cz, where z = (vars, 1, inputs)
195
196  // constraint 0 entries in (A,B,C)
197  // constraint 0 is (Z0 + Z1) * I0 - Z2 = 0.
198  // We set 1 in matrix A for columns that correspond to Z0 and Z1
199  // We set 1 in matrix B for column that corresponds to I0
200  // We set 1 in matrix C for column that corresponds to Z2
201  A.push((0, 0, one));
202  A.push((0, 1, one));
203  B.push((0, num_vars + 1, one));
204  C.push((0, 2, one));
205
206  // constraint 1 entries in (A,B,C)
207  A.push((1, 0, one));
208  A.push((1, num_vars + 2, one));
209  B.push((1, 2, one));
210  C.push((1, 3, one));
211
212  // constraint 3 entries in (A,B,C)
213  A.push((2, 4, one));
214  B.push((2, num_vars, one));
215
216  let inst = Instance::new(num_cons, num_vars, num_inputs, &A, &B, &C).unwrap();
217
218  // compute a satisfying assignment
219let mut rng = ark_std::rand::thread_rng();
220  let i0 = Scalar::rand(&mut rng);
221  let i1 = Scalar::rand(&mut rng);
222  let z0 = Scalar::rand(&mut rng);
223  let z1 = Scalar::rand(&mut rng);
224  let z2 = (z0 + z1) * i0; // constraint 0
225  let z3 = (z0 + i1) * z2; // constraint 1
226  let z4 = Scalar::zero(); //constraint 2
227
228  // create a VarsAssignment
229  let mut vars = vec![Scalar::zero().to_bytes(); num_vars];
230  vars[0] = z0.to_bytes();
231  vars[1] = z1.to_bytes();
232  vars[2] = z2.to_bytes();
233  vars[3] = z3.to_bytes();
234  vars[4] = z4.to_bytes();
235  let assignment_vars = VarsAssignment::new(&vars).unwrap();
236
237  // create an InputsAssignment
238  let mut inputs = vec![Scalar::zero().to_bytes(); num_inputs];
239  inputs[0] = i0.to_bytes();
240  inputs[1] = i1.to_bytes();
241  let assignment_inputs = InputsAssignment::new(&inputs).unwrap();
242
243  // check if the instance we created is satisfiable
244  let res = inst.is_sat(&assignment_vars, &assignment_inputs);
245  assert_eq!(res.unwrap(), true);
246
247  (
248    num_cons,
249    num_vars,
250    num_inputs,
251    num_non_zero_entries,
252    inst,
253    assignment_vars,
254    assignment_inputs,
255  )
256# }
257```
258
259For more examples, see [`examples/`](examples) directory in this repo.
260
261## Building `libspartan`
262
263Install [`rustup`](https://rustup.rs/)
264
265Switch to nightly Rust using `rustup`:
266
267```text
268rustup default nightly
269```
270
271Clone the repository:
272
273```text
274git clone https://github.com/Microsoft/Spartan
275cd Spartan
276```
277
278To build docs for public APIs of `libspartan`:
279
280```text
281cargo doc
282```
283
284To run tests:
285
286```text
287RUSTFLAGS="-C target_cpu=native" cargo test
288```
289
290To build `libspartan`:
291
292```text
293RUSTFLAGS="-C target_cpu=native" cargo build --release
294```
295
296> NOTE: We enable SIMD instructions in `curve25519-dalek` by default, so if it fails to build remove the "simd_backend" feature argument in `Cargo.toml`.
297
298### Supported features
299
300- `profile`: enables fine-grained profiling information (see below for its use)
301
302## Performance
303
304### End-to-end benchmarks
305
306`libspartan` includes two benches: `benches/nizk.rs` and `benches/snark.rs`. If you report the performance of Spartan in a research paper, we recommend using these benches for higher accuracy instead of fine-grained profiling (listed below).
307
308To run end-to-end benchmarks:
309
310```text
311RUSTFLAGS="-C target_cpu=native" cargo bench
312```
313
314### Fine-grained profiling
315
316Build `libspartan` with `profile` feature enabled. It creates two profilers: `./target/release/snark` and `./target/release/nizk`.
317
318These profilers report performance as depicted below (for varying R1CS instance sizes). The reported
319performance is from running the profilers on a Microsoft Surface Laptop 3 on a single CPU core of Intel Core i7-1065G7 running Ubuntu 20.04 (atop WSL2 on Windows 10).
320See Section 9 in our [paper](https://eprint.iacr.org/2019/550) to see how this compares with other zkSNARKs in the literature.
321
322```text
323$ ./target/release/snark
324Profiler:: SNARK
325  * number_of_constraints 1048576
326  * number_of_variables 1048576
327  * number_of_inputs 10
328  * number_non-zero_entries_A 1048576
329  * number_non-zero_entries_B 1048576
330  * number_non-zero_entries_C 1048576
331  * SNARK::encode
332  * SNARK::encode 14.2644201s
333  * SNARK::prove
334    * R1CSProof::prove
335      * polycommit
336      * polycommit 2.7175848s
337      * prove_sc_phase_one
338      * prove_sc_phase_one 683.7481ms
339      * prove_sc_phase_two
340      * prove_sc_phase_two 846.1056ms
341      * polyeval
342      * polyeval 193.4216ms
343    * R1CSProof::prove 4.4416193s
344    * len_r1cs_sat_proof 47024
345    * eval_sparse_polys
346    * eval_sparse_polys 377.357ms
347    * R1CSEvalProof::prove
348      * commit_nondet_witness
349      * commit_nondet_witness 14.4507331s
350      * build_layered_network
351      * build_layered_network 3.4360521s
352      * evalproof_layered_network
353        * len_product_layer_proof 64712
354      * evalproof_layered_network 15.5708066s
355    * R1CSEvalProof::prove 34.2930559s
356    * len_r1cs_eval_proof 133720
357  * SNARK::prove 39.1297568s
358  * SNARK::proof_compressed_len 141768
359  * SNARK::verify
360    * verify_sat_proof
361    * verify_sat_proof 20.0828ms
362    * verify_eval_proof
363      * verify_polyeval_proof
364        * verify_prod_proof
365        * verify_prod_proof 1.1847ms
366        * verify_hash_proof
367        * verify_hash_proof 81.06ms
368      * verify_polyeval_proof 82.3583ms
369    * verify_eval_proof 82.8937ms
370  * SNARK::verify 103.0536ms
371```
372
373```text
374$ ./target/release/nizk
375Profiler:: NIZK
376  * number_of_constraints 1048576
377  * number_of_variables 1048576
378  * number_of_inputs 10
379  * number_non-zero_entries_A 1048576
380  * number_non-zero_entries_B 1048576
381  * number_non-zero_entries_C 1048576
382  * NIZK::prove
383    * R1CSProof::prove
384      * polycommit
385      * polycommit 2.7220635s
386      * prove_sc_phase_one
387      * prove_sc_phase_one 722.5487ms
388      * prove_sc_phase_two
389      * prove_sc_phase_two 862.6796ms
390      * polyeval
391      * polyeval 190.2233ms
392    * R1CSProof::prove 4.4982305s
393    * len_r1cs_sat_proof 47024
394  * NIZK::prove 4.5139888s
395  * NIZK::proof_compressed_len 48134
396  * NIZK::verify
397    * eval_sparse_polys
398    * eval_sparse_polys 395.0847ms
399    * verify_sat_proof
400    * verify_sat_proof 19.286ms
401  * NIZK::verify 414.5102ms
402```
403
404## LICENSE
405
406See [LICENSE](./LICENSE)
407
408## Contributing
409
410See [CONTRIBUTING](./CONTRIBUTING.md)