You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

393 lines
15 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. # Spartan: High-speed zkSNARKs without trusted setup
  2. ![Rust](https://github.com/microsoft/Spartan/workflows/Rust/badge.svg)
  3. [![](https://img.shields.io/crates/v/spartan.svg)]((https://crates.io/crates/curve25519-dalek))
  4. Spartan 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.
  5. A 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.
  6. Note that this library has *not* received a security review or audit.
  7. ## Highlights
  8. We now highlight Spartan's distinctive features.
  9. * **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.
  10. * **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.
  11. * **Sub-linear verification costs and linear-time proving costs:** Spartan is the first transparent proof system with sub-linear verification costs for arbitrary NP statements (e.g., R1CS). Spartan also features a linear-time prover, a property that has remained elusive for nearly all zkSNARKs in the literature.
  12. * **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`.
  13. * **State-of-the-art performance:**
  14. 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.
  15. ### Implementation details
  16. `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.
  17. ## Examples
  18. To import `libspartan` into your Rust project, add the following dependency to `Cargo.toml`:
  19. ```text
  20. spartan = "0.4.1"
  21. ```
  22. The following example shows how to use `libspartan` to create and verify a SNARK proof.
  23. Some of our public APIs' style is inspired by the underlying crates we use.
  24. ```rust
  25. # extern crate libspartan;
  26. # extern crate merlin;
  27. # use libspartan::{Instance, SNARKGens, SNARK};
  28. # use merlin::Transcript;
  29. # fn main() {
  30. // specify the size of an R1CS instance
  31. let num_vars = 1024;
  32. let num_cons = 1024;
  33. let num_inputs = 10;
  34. let num_non_zero_entries = 1024;
  35. // produce public parameters
  36. let gens = SNARKGens::new(num_cons, num_vars, num_inputs, num_non_zero_entries);
  37. // ask the library to produce a synthentic R1CS instance
  38. let (inst, vars, inputs) = Instance::produce_synthetic_r1cs(num_cons, num_vars, num_inputs);
  39. // create a commitment to the R1CS instance
  40. let (comm, decomm) = SNARK::encode(&inst, &gens);
  41. // produce a proof of satisfiability
  42. let mut prover_transcript = Transcript::new(b"snark_example");
  43. let proof = SNARK::prove(&inst, &decomm, vars, &inputs, &gens, &mut prover_transcript);
  44. // verify the proof of satisfiability
  45. let mut verifier_transcript = Transcript::new(b"snark_example");
  46. assert!(proof
  47. .verify(&comm, &inputs, &mut verifier_transcript, &gens)
  48. .is_ok());
  49. println!("proof verification successful!");
  50. # }
  51. ```
  52. Here is another example to use the NIZK variant of the Spartan proof system:
  53. ```rust
  54. # extern crate libspartan;
  55. # extern crate merlin;
  56. # use libspartan::{Instance, NIZKGens, NIZK};
  57. # use merlin::Transcript;
  58. # fn main() {
  59. // specify the size of an R1CS instance
  60. let num_vars = 1024;
  61. let num_cons = 1024;
  62. let num_inputs = 10;
  63. // produce public parameters
  64. let gens = NIZKGens::new(num_cons, num_vars, num_inputs);
  65. // ask the library to produce a synthentic R1CS instance
  66. let (inst, vars, inputs) = Instance::produce_synthetic_r1cs(num_cons, num_vars, num_inputs);
  67. // produce a proof of satisfiability
  68. let mut prover_transcript = Transcript::new(b"nizk_example");
  69. let proof = NIZK::prove(&inst, vars, &inputs, &gens, &mut prover_transcript);
  70. // verify the proof of satisfiability
  71. let mut verifier_transcript = Transcript::new(b"nizk_example");
  72. assert!(proof
  73. .verify(&inst, &inputs, &mut verifier_transcript, &gens)
  74. .is_ok());
  75. println!("proof verification successful!");
  76. # }
  77. ```
  78. Finally, we provide an example that specifies a custom R1CS instance instead of using a synthetic instance
  79. ```rust
  80. #![allow(non_snake_case)]
  81. # extern crate curve25519_dalek;
  82. # extern crate libspartan;
  83. # extern crate merlin;
  84. # use curve25519_dalek::scalar::Scalar;
  85. # use libspartan::{InputsAssignment, Instance, SNARKGens, VarsAssignment, SNARK};
  86. # use merlin::Transcript;
  87. # use rand::rngs::OsRng;
  88. # fn main() {
  89. // produce a tiny instance
  90. let (
  91. num_cons,
  92. num_vars,
  93. num_inputs,
  94. num_non_zero_entries,
  95. inst,
  96. assignment_vars,
  97. assignment_inputs,
  98. ) = produce_tiny_r1cs();
  99. // produce public parameters
  100. let gens = SNARKGens::new(num_cons, num_vars, num_inputs, num_non_zero_entries);
  101. // create a commitment to the R1CS instance
  102. let (comm, decomm) = SNARK::encode(&inst, &gens);
  103. // produce a proof of satisfiability
  104. let mut prover_transcript = Transcript::new(b"snark_example");
  105. let proof = SNARK::prove(
  106. &inst,
  107. &decomm,
  108. assignment_vars,
  109. &assignment_inputs,
  110. &gens,
  111. &mut prover_transcript,
  112. );
  113. // verify the proof of satisfiability
  114. let mut verifier_transcript = Transcript::new(b"snark_example");
  115. assert!(proof
  116. .verify(&comm, &assignment_inputs, &mut verifier_transcript, &gens)
  117. .is_ok());
  118. println!("proof verification successful!");
  119. # }
  120. # fn produce_tiny_r1cs() -> (
  121. # usize,
  122. # usize,
  123. # usize,
  124. # usize,
  125. # Instance,
  126. # VarsAssignment,
  127. # InputsAssignment,
  128. # ) {
  129. // We will use the following example, but one could construct any R1CS instance.
  130. // Our R1CS instance is three constraints over five variables and two public inputs
  131. // (Z0 + Z1) * I0 - Z2 = 0
  132. // (Z0 + I1) * Z2 - Z3 = 0
  133. // Z4 * 1 - 0 = 0
  134. // parameters of the R1CS instance rounded to the nearest power of two
  135. let num_cons = 4;
  136. let num_vars = 5;
  137. let num_inputs = 2;
  138. let num_non_zero_entries = 5;
  139. // We will encode the above constraints into three matrices, where
  140. // the coefficients in the matrix are in the little-endian byte order
  141. let mut A: Vec<(usize, usize, [u8; 32])> = Vec::new();
  142. let mut B: Vec<(usize, usize, [u8; 32])> = Vec::new();
  143. let mut C: Vec<(usize, usize, [u8; 32])> = Vec::new();
  144. // The constraint system is defined over a finite field, which in our case is
  145. // the scalar field of ristreeto255/curve25519 i.e., p = 2^{252}+27742317777372353535851937790883648493
  146. // To construct these matrices, we will use `curve25519-dalek` but one can use any other method.
  147. // a variable that holds a byte representation of 1
  148. let one = Scalar::one().to_bytes();
  149. // R1CS is a set of three sparse matrices A B C, where is a row for every
  150. // constraint and a column for every entry in z = (vars, 1, inputs)
  151. // An R1CS instance is satisfiable iff:
  152. // Az \circ Bz = Cz, where z = (vars, 1, inputs)
  153. // constraint 0 entries in (A,B,C)
  154. // constraint 0 is (Z0 + Z1) * I0 - Z2 = 0.
  155. // We set 1 in matrix A for columns that correspond to Z0 and Z1
  156. // We set 1 in matrix B for column that corresponds to I0
  157. // We set 1 in matrix C for column that corresponds to Z2
  158. A.push((0, 0, one));
  159. A.push((0, 1, one));
  160. B.push((0, num_vars + 1, one));
  161. C.push((0, 2, one));
  162. // constraint 1 entries in (A,B,C)
  163. A.push((1, 0, one));
  164. A.push((1, num_vars + 2, one));
  165. B.push((1, 2, one));
  166. C.push((1, 3, one));
  167. // constraint 3 entries in (A,B,C)
  168. A.push((2, 4, one));
  169. B.push((2, num_vars, one));
  170. let inst = Instance::new(num_cons, num_vars, num_inputs, &A, &B, &C).unwrap();
  171. // compute a satisfying assignment
  172. let mut csprng: OsRng = OsRng;
  173. let i0 = Scalar::random(&mut csprng);
  174. let i1 = Scalar::random(&mut csprng);
  175. let z0 = Scalar::random(&mut csprng);
  176. let z1 = Scalar::random(&mut csprng);
  177. let z2 = (z0 + z1) * i0; // constraint 0
  178. let z3 = (z0 + i1) * z2; // constraint 1
  179. let z4 = Scalar::zero(); //constraint 2
  180. // create a VarsAssignment
  181. let mut vars = vec![Scalar::zero().to_bytes(); num_vars];
  182. vars[0] = z0.to_bytes();
  183. vars[1] = z1.to_bytes();
  184. vars[2] = z2.to_bytes();
  185. vars[3] = z3.to_bytes();
  186. vars[4] = z4.to_bytes();
  187. let assignment_vars = VarsAssignment::new(&vars).unwrap();
  188. // create an InputsAssignment
  189. let mut inputs = vec![Scalar::zero().to_bytes(); num_inputs];
  190. inputs[0] = i0.to_bytes();
  191. inputs[1] = i1.to_bytes();
  192. let assignment_inputs = InputsAssignment::new(&inputs).unwrap();
  193. // check if the instance we created is satisfiable
  194. let res = inst.is_sat(&assignment_vars, &assignment_inputs);
  195. assert_eq!(res.unwrap(), true);
  196. (
  197. num_cons,
  198. num_vars,
  199. num_inputs,
  200. num_non_zero_entries,
  201. inst,
  202. assignment_vars,
  203. assignment_inputs,
  204. )
  205. # }
  206. ```
  207. For more examples, see [`examples/`](examples) directory in this repo.
  208. ## Building `libspartan`
  209. Install [`rustup`](https://rustup.rs/)
  210. Switch to nightly Rust using `rustup`:
  211. ```text
  212. rustup default nightly
  213. ```
  214. Clone the repository:
  215. ```text
  216. git clone https://github.com/Microsoft/Spartan
  217. cd Spartan
  218. ```
  219. To build docs for public APIs of `libspartan`:
  220. ```text
  221. cargo doc
  222. ```
  223. To run tests:
  224. ```text
  225. RUSTFLAGS="-C target_cpu=native" cargo test
  226. ```
  227. To build `libspartan`:
  228. ```text
  229. RUSTFLAGS="-C target_cpu=native" cargo build --release
  230. ```
  231. > 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`.
  232. ### Supported features
  233. * `profile`: enables fine-grained profiling information (see below for its use)
  234. ## Performance
  235. ### End-to-end benchmarks
  236. `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).
  237. To run end-to-end benchmarks:
  238. ```text
  239. RUSTFLAGS="-C target_cpu=native" cargo bench
  240. ```
  241. ### Fine-grained profiling
  242. Build `libspartan` with `profile` feature enabled. It creates two profilers: `./target/release/snark` and `./target/release/nizk`.
  243. These profilers report performance as depicted below (for varying R1CS instance sizes). The reported
  244. performance 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).
  245. See Section 9 in our [paper](https://eprint.iacr.org/2019/550) to see how this compares with other zkSNARKs in the literature.
  246. ```text
  247. $ ./target/release/snark
  248. Profiler:: SNARK
  249. * number_of_constraints 1048576
  250. * number_of_variables 1048576
  251. * number_of_inputs 10
  252. * number_non-zero_entries_A 1048576
  253. * number_non-zero_entries_B 1048576
  254. * number_non-zero_entries_C 1048576
  255. * SNARK::encode
  256. * SNARK::encode 14.2644201s
  257. * SNARK::prove
  258. * R1CSProof::prove
  259. * polycommit
  260. * polycommit 2.7175848s
  261. * prove_sc_phase_one
  262. * prove_sc_phase_one 683.7481ms
  263. * prove_sc_phase_two
  264. * prove_sc_phase_two 846.1056ms
  265. * polyeval
  266. * polyeval 193.4216ms
  267. * R1CSProof::prove 4.4416193s
  268. * len_r1cs_sat_proof 47024
  269. * eval_sparse_polys
  270. * eval_sparse_polys 377.357ms
  271. * R1CSEvalProof::prove
  272. * commit_nondet_witness
  273. * commit_nondet_witness 14.4507331s
  274. * build_layered_network
  275. * build_layered_network 3.4360521s
  276. * evalproof_layered_network
  277. * len_product_layer_proof 64712
  278. * evalproof_layered_network 15.5708066s
  279. * R1CSEvalProof::prove 34.2930559s
  280. * len_r1cs_eval_proof 133720
  281. * SNARK::prove 39.1297568s
  282. * SNARK::proof_compressed_len 141768
  283. * SNARK::verify
  284. * verify_sat_proof
  285. * verify_sat_proof 20.0828ms
  286. * verify_eval_proof
  287. * verify_polyeval_proof
  288. * verify_prod_proof
  289. * verify_prod_proof 1.1847ms
  290. * verify_hash_proof
  291. * verify_hash_proof 81.06ms
  292. * verify_polyeval_proof 82.3583ms
  293. * verify_eval_proof 82.8937ms
  294. * SNARK::verify 103.0536ms
  295. ```
  296. ```text
  297. $ ./target/release/nizk
  298. Profiler:: NIZK
  299. * number_of_constraints 1048576
  300. * number_of_variables 1048576
  301. * number_of_inputs 10
  302. * number_non-zero_entries_A 1048576
  303. * number_non-zero_entries_B 1048576
  304. * number_non-zero_entries_C 1048576
  305. * NIZK::prove
  306. * R1CSProof::prove
  307. * polycommit
  308. * polycommit 2.7220635s
  309. * prove_sc_phase_one
  310. * prove_sc_phase_one 722.5487ms
  311. * prove_sc_phase_two
  312. * prove_sc_phase_two 862.6796ms
  313. * polyeval
  314. * polyeval 190.2233ms
  315. * R1CSProof::prove 4.4982305s
  316. * len_r1cs_sat_proof 47024
  317. * NIZK::prove 4.5139888s
  318. * NIZK::proof_compressed_len 48134
  319. * NIZK::verify
  320. * eval_sparse_polys
  321. * eval_sparse_polys 395.0847ms
  322. * verify_sat_proof
  323. * verify_sat_proof 19.286ms
  324. * NIZK::verify 414.5102ms
  325. ```
  326. ## LICENSE
  327. See [LICENSE](./LICENSE)
  328. ## Contributing
  329. See [CONTRIBUTING](./CONTRIBUTING.md)