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.

394 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/spartan))
  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:** Spartan is the first transparent proof system with sub-linear verification costs for arbitrary NP statements (e.g., R1CS).
  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, &comm, &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. &comm,
  108. &decomm,
  109. assignment_vars,
  110. &assignment_inputs,
  111. &gens,
  112. &mut prover_transcript,
  113. );
  114. // verify the proof of satisfiability
  115. let mut verifier_transcript = Transcript::new(b"snark_example");
  116. assert!(proof
  117. .verify(&comm, &assignment_inputs, &mut verifier_transcript, &gens)
  118. .is_ok());
  119. println!("proof verification successful!");
  120. # }
  121. # fn produce_tiny_r1cs() -> (
  122. # usize,
  123. # usize,
  124. # usize,
  125. # usize,
  126. # Instance,
  127. # VarsAssignment,
  128. # InputsAssignment,
  129. # ) {
  130. // We will use the following example, but one could construct any R1CS instance.
  131. // Our R1CS instance is three constraints over five variables and two public inputs
  132. // (Z0 + Z1) * I0 - Z2 = 0
  133. // (Z0 + I1) * Z2 - Z3 = 0
  134. // Z4 * 1 - 0 = 0
  135. // parameters of the R1CS instance rounded to the nearest power of two
  136. let num_cons = 4;
  137. let num_vars = 5;
  138. let num_inputs = 2;
  139. let num_non_zero_entries = 5;
  140. // We will encode the above constraints into three matrices, where
  141. // the coefficients in the matrix are in the little-endian byte order
  142. let mut A: Vec<(usize, usize, [u8; 32])> = Vec::new();
  143. let mut B: Vec<(usize, usize, [u8; 32])> = Vec::new();
  144. let mut C: Vec<(usize, usize, [u8; 32])> = Vec::new();
  145. // The constraint system is defined over a finite field, which in our case is
  146. // the scalar field of ristreeto255/curve25519 i.e., p = 2^{252}+27742317777372353535851937790883648493
  147. // To construct these matrices, we will use `curve25519-dalek` but one can use any other method.
  148. // a variable that holds a byte representation of 1
  149. let one = Scalar::one().to_bytes();
  150. // R1CS is a set of three sparse matrices A B C, where is a row for every
  151. // constraint and a column for every entry in z = (vars, 1, inputs)
  152. // An R1CS instance is satisfiable iff:
  153. // Az \circ Bz = Cz, where z = (vars, 1, inputs)
  154. // constraint 0 entries in (A,B,C)
  155. // constraint 0 is (Z0 + Z1) * I0 - Z2 = 0.
  156. // We set 1 in matrix A for columns that correspond to Z0 and Z1
  157. // We set 1 in matrix B for column that corresponds to I0
  158. // We set 1 in matrix C for column that corresponds to Z2
  159. A.push((0, 0, one));
  160. A.push((0, 1, one));
  161. B.push((0, num_vars + 1, one));
  162. C.push((0, 2, one));
  163. // constraint 1 entries in (A,B,C)
  164. A.push((1, 0, one));
  165. A.push((1, num_vars + 2, one));
  166. B.push((1, 2, one));
  167. C.push((1, 3, one));
  168. // constraint 3 entries in (A,B,C)
  169. A.push((2, 4, one));
  170. B.push((2, num_vars, one));
  171. let inst = Instance::new(num_cons, num_vars, num_inputs, &A, &B, &C).unwrap();
  172. // compute a satisfying assignment
  173. let mut csprng: OsRng = OsRng;
  174. let i0 = Scalar::random(&mut csprng);
  175. let i1 = Scalar::random(&mut csprng);
  176. let z0 = Scalar::random(&mut csprng);
  177. let z1 = Scalar::random(&mut csprng);
  178. let z2 = (z0 + z1) * i0; // constraint 0
  179. let z3 = (z0 + i1) * z2; // constraint 1
  180. let z4 = Scalar::zero(); //constraint 2
  181. // create a VarsAssignment
  182. let mut vars = vec![Scalar::zero().to_bytes(); num_vars];
  183. vars[0] = z0.to_bytes();
  184. vars[1] = z1.to_bytes();
  185. vars[2] = z2.to_bytes();
  186. vars[3] = z3.to_bytes();
  187. vars[4] = z4.to_bytes();
  188. let assignment_vars = VarsAssignment::new(&vars).unwrap();
  189. // create an InputsAssignment
  190. let mut inputs = vec![Scalar::zero().to_bytes(); num_inputs];
  191. inputs[0] = i0.to_bytes();
  192. inputs[1] = i1.to_bytes();
  193. let assignment_inputs = InputsAssignment::new(&inputs).unwrap();
  194. // check if the instance we created is satisfiable
  195. let res = inst.is_sat(&assignment_vars, &assignment_inputs);
  196. assert_eq!(res.unwrap(), true);
  197. (
  198. num_cons,
  199. num_vars,
  200. num_inputs,
  201. num_non_zero_entries,
  202. inst,
  203. assignment_vars,
  204. assignment_inputs,
  205. )
  206. # }
  207. ```
  208. For more examples, see [`examples/`](examples) directory in this repo.
  209. ## Building `libspartan`
  210. Install [`rustup`](https://rustup.rs/)
  211. Switch to nightly Rust using `rustup`:
  212. ```text
  213. rustup default nightly
  214. ```
  215. Clone the repository:
  216. ```text
  217. git clone https://github.com/Microsoft/Spartan
  218. cd Spartan
  219. ```
  220. To build docs for public APIs of `libspartan`:
  221. ```text
  222. cargo doc
  223. ```
  224. To run tests:
  225. ```text
  226. RUSTFLAGS="-C target_cpu=native" cargo test
  227. ```
  228. To build `libspartan`:
  229. ```text
  230. RUSTFLAGS="-C target_cpu=native" cargo build --release
  231. ```
  232. > 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`.
  233. ### Supported features
  234. * `profile`: enables fine-grained profiling information (see below for its use)
  235. ## Performance
  236. ### End-to-end benchmarks
  237. `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).
  238. To run end-to-end benchmarks:
  239. ```text
  240. RUSTFLAGS="-C target_cpu=native" cargo bench
  241. ```
  242. ### Fine-grained profiling
  243. Build `libspartan` with `profile` feature enabled. It creates two profilers: `./target/release/snark` and `./target/release/nizk`.
  244. These profilers report performance as depicted below (for varying R1CS instance sizes). The reported
  245. 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).
  246. See Section 9 in our [paper](https://eprint.iacr.org/2019/550) to see how this compares with other zkSNARKs in the literature.
  247. ```text
  248. $ ./target/release/snark
  249. Profiler:: SNARK
  250. * number_of_constraints 1048576
  251. * number_of_variables 1048576
  252. * number_of_inputs 10
  253. * number_non-zero_entries_A 1048576
  254. * number_non-zero_entries_B 1048576
  255. * number_non-zero_entries_C 1048576
  256. * SNARK::encode
  257. * SNARK::encode 14.2644201s
  258. * SNARK::prove
  259. * R1CSProof::prove
  260. * polycommit
  261. * polycommit 2.7175848s
  262. * prove_sc_phase_one
  263. * prove_sc_phase_one 683.7481ms
  264. * prove_sc_phase_two
  265. * prove_sc_phase_two 846.1056ms
  266. * polyeval
  267. * polyeval 193.4216ms
  268. * R1CSProof::prove 4.4416193s
  269. * len_r1cs_sat_proof 47024
  270. * eval_sparse_polys
  271. * eval_sparse_polys 377.357ms
  272. * R1CSEvalProof::prove
  273. * commit_nondet_witness
  274. * commit_nondet_witness 14.4507331s
  275. * build_layered_network
  276. * build_layered_network 3.4360521s
  277. * evalproof_layered_network
  278. * len_product_layer_proof 64712
  279. * evalproof_layered_network 15.5708066s
  280. * R1CSEvalProof::prove 34.2930559s
  281. * len_r1cs_eval_proof 133720
  282. * SNARK::prove 39.1297568s
  283. * SNARK::proof_compressed_len 141768
  284. * SNARK::verify
  285. * verify_sat_proof
  286. * verify_sat_proof 20.0828ms
  287. * verify_eval_proof
  288. * verify_polyeval_proof
  289. * verify_prod_proof
  290. * verify_prod_proof 1.1847ms
  291. * verify_hash_proof
  292. * verify_hash_proof 81.06ms
  293. * verify_polyeval_proof 82.3583ms
  294. * verify_eval_proof 82.8937ms
  295. * SNARK::verify 103.0536ms
  296. ```
  297. ```text
  298. $ ./target/release/nizk
  299. Profiler:: NIZK
  300. * number_of_constraints 1048576
  301. * number_of_variables 1048576
  302. * number_of_inputs 10
  303. * number_non-zero_entries_A 1048576
  304. * number_non-zero_entries_B 1048576
  305. * number_non-zero_entries_C 1048576
  306. * NIZK::prove
  307. * R1CSProof::prove
  308. * polycommit
  309. * polycommit 2.7220635s
  310. * prove_sc_phase_one
  311. * prove_sc_phase_one 722.5487ms
  312. * prove_sc_phase_two
  313. * prove_sc_phase_two 862.6796ms
  314. * polyeval
  315. * polyeval 190.2233ms
  316. * R1CSProof::prove 4.4982305s
  317. * len_r1cs_sat_proof 47024
  318. * NIZK::prove 4.5139888s
  319. * NIZK::proof_compressed_len 48134
  320. * NIZK::verify
  321. * eval_sparse_polys
  322. * eval_sparse_polys 395.0847ms
  323. * verify_sat_proof
  324. * verify_sat_proof 19.286ms
  325. * NIZK::verify 414.5102ms
  326. ```
  327. ## LICENSE
  328. See [LICENSE](./LICENSE)
  329. ## Contributing
  330. See [CONTRIBUTING](./CONTRIBUTING.md)