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.

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