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.

267 lines
7.9 KiB

5 years ago
5 years ago
5 years ago
  1. # circom and snarkjs tutorial
  2. This tutorial will guide you in creating your first Zero Knowledge zkSnark circuit. It will navegate across the various techniques to write circuits and it will show you how to create proofs and verify them off-chain and on-chain on Ethereum.
  3. ## 1. Installing the tools
  4. ### 1.1 Pre-requisites
  5. If you don't have it installed yet, you need to install `Node.js` in your laptop.
  6. Last stable version of `Node.js` (Or 8.12.0) works just fine. But if you install the latest current version `Node.js` (10.12.0) you will see significant performance increase. This is because last versions of node includes Big Integer Libraries nativelly. The `snarkjs` library makes use of this feature if available, and this improves the performance x10 (!).
  7. ### 1.2 Install **circom** and **snarkjs**
  8. Just run:
  9. ```sh
  10. npm install -g circom
  11. npm install -g snarkjs
  12. ```
  13. ## 2. Working with a circuit
  14. Let's create a circuit that tries to prove that you are able to factor a number!
  15. ### 2.1 Create a circuit in a new directory
  16. 1. Create an empty directory called `factor` where you will put all the files that you will use in this tutorial.
  17. ```
  18. mkdir factor
  19. cd factor
  20. ```
  21. > In a real circuit, you will probably want to create a `git` repository with a `circuits` directory and a `test` directory with all your tests, and the needed scripts to build all the circuits.
  22. 2. Create a new file named `circuit.circom` with the following content:
  23. ```
  24. template Multiplier() {
  25. signal private input a;
  26. signal private input b;
  27. signal output c;
  28. c <== a*b;
  29. }
  30. component main = Multiplier();
  31. ```
  32. This circuit has 2 private input signals named `a` and `b` and one output named `c`.
  33. The only thing that the circuit does is forcing the signal `c` to be the value of `a*b`
  34. After declaring the `Multiplier` template, we instantiate it with a component named`main`.
  35. Note: When compiling a circuit a component named `main` must always exist.
  36. ### 2.2 Compile the circuit
  37. We are now ready to compile the circuit. Run the following command:
  38. ```sh
  39. circom circuit.circom -o circuit.json
  40. // Which is equivalent to "circom circuit.circom -o circuit.json"
  41. ```
  42. to compile the circuit to a file named `circuit.json`
  43. ## 3. Taking the compiled circuit to *snarkjs*
  44. Now that the circuit is compiled, we will continue with `snarkjs`.
  45. Please note that you can always access the help of `snarkjs` by typing:
  46. ```sh
  47. snarkjs --help
  48. ```
  49. ### 3.1 View information and stats regarding a circuit
  50. To show general statistics of this circuit, you can run:
  51. ```sh
  52. snarkjs info -c circuit.json
  53. ```
  54. You can also print the constraints of the circuit by running:
  55. ```sh
  56. snarkjs printconstraints -c circuit.json
  57. ```
  58. ### 3.2 Setting up using *snarkjs*
  59. Ok, let's run a setup for our circuit:
  60. ```sh
  61. snarkjs setup
  62. ```
  63. > By default `snarkjs` will look for and use `circuit.json`. You can always specify a different circuit file by adding `-c <circuit JSON file name>`
  64. The output of the setup will in the form of 2 files: `proving_key.json` and `verification_key.json`
  65. ### 3.3. Calculating a witness
  66. Before creating any proof, we need to calculate all the signals of the circuit that match (all) the constrains of the circuit.
  67. `snarkjs` calculates these for you. You need to provide a file with the inputs and it will execute the circuit and calculate all the intermediate signals and the output. This set of signals is the *witness*.
  68. The zero knowledge proofs prove that you know a set of signals (witness) that match all the constraints but without revealing any of the signals except the public inputs plus the outputs.
  69. For example, Imagine that you want to prove that you are able to factor 33 that means that you know two numbers `a` and `b` that when you multiply them, it results in 33.
  70. > Of course you can always use one and the same number as `a` and `b`. We will deal with this problem later.
  71. So you want to prove that you know 3 and 11.
  72. Let's create a file named `input.json`
  73. ```json
  74. {"a": 3, "b": 11}
  75. ```
  76. And now let's calculate the witness:
  77. ```sh
  78. snarkjs calculatewitness
  79. ```
  80. You may want to take a look at `witness.json` file with all the signals.
  81. ### Create the proof
  82. Now that we have the witness generated, we can create the proof.
  83. ```sh
  84. snarkjs proof
  85. ```
  86. This command will use the `prooving_key.json` and the `witness.json` files by default to generate `proof.json` and `public.json`
  87. The `proof.json` file will contain the actual proof. And the `public.json` file will contain just the values of the public inputs and the outputs.
  88. ### Verifying the proof
  89. To verify the proof run:
  90. ```sh
  91. snarkjs verify
  92. ```
  93. This command will use `verification_key.json`, `proof.json` and `public.json` to verify that is valid.
  94. Here we are veifying that we know a witness that the public inputs and the outputs matches the ones in the `public.json` file.
  95. If the proof is ok, you will see an `OK` in the screen or `INVALID` otherwise.
  96. ### Generate the solidity verifier
  97. ```sh
  98. snarkjs generateverifier
  99. ```
  100. This command will take the `verification_key.json` and generate a solidity code in `verifier.sol` file.
  101. You can take the code in `verifier.sol` and cut and paste in remix.
  102. This code contains two contracts: Pairings and Verifier. You just need to deploy the `Verifier` contract.
  103. > You may want to use a test net like Rinkeby, Kovan or Ropsten. You can also use the Javascript VM, but in some browsers, the verification takes long and it may hang the page.
  104. ### Verifying the proof on-chain
  105. The verifier contract deployed in the last step has a `view` function called `verifyProof`.
  106. This function will return true if the proof and the inputs are valid.
  107. To facilitiate the call, you can use snarkjs to generate the parameters of the call by typing:
  108. ```sh
  109. snarkjs generatecall
  110. ```
  111. Just cut and paste the output to the parameters field of the `verifyProof` method in Remix.
  112. If every thing works ok, this method should return true.
  113. If you just change any bit in the parameters, you can check that the result will be false.
  114. ## Bonus track
  115. We can fix the circuit to not accept one as any of the values by adding some extra constraints.
  116. Here the trick is that we use the property that 0 has no inverse. so `(a-1)` should not have an inverse.
  117. that means that `(a-1)*inv = 1` will be inpossible to match if `a` is one.
  118. We just calculate inv by `1/(a-1)`
  119. So let's modify the circuit:
  120. ```
  121. template Multiplier() {
  122. signal private input a;
  123. signal private input b;
  124. signal output c;
  125. signal inva;
  126. signal invb;
  127. inva <-- 1/(a-1);
  128. (a-1)*inva === 1;
  129. invb <-- 1/(b-1);
  130. (b-1)*invb === 1;
  131. c <== a*b;
  132. }
  133. component main = Multiplier();
  134. ```
  135. A nice thing of circom language is that you can split a <== into two independent acions: <-- and ===
  136. The <-- and --> operators Just assign a value to a signal without creating any constraints.
  137. The === operator just adds a constraint without assigning any value to any signal.
  138. The circuit has also another problem and it's that the operation works in Zr, so we need to guarantee too that the multiplication does not overflow. This can be done by binarizing the inputs and checking the ranges, but we will reserve it for future tutorials.
  139. ## Where to go from here.
  140. You may want to read the [README](https://github.com/iden3/circom) to learn more features about circom.
  141. You can also check a a library with many basic circuits lib binaritzations, comparators, eddsa, hashes, merkle trees etc [here](https://github.com/iden3/circomlib) (Work in progress).
  142. Or a exponentiation in the Baby Jub curve [here](https://github.com/iden3/circomlib) (Work in progress).
  143. # Final note
  144. There is nothing worst for a dev than working with a buggy compiler. This is a very early stage of the compiler, so there are many bugs and lots of works needs to be done. Please have it present if you are doing anything serious with it.
  145. And please contact us for any isue you have. In general, a github issue with a small piece of code with the bug is very worthy!.
  146. Enjoy zero knowledge proving!