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.

412 lines
15 KiB

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