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.

265 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. ```
  41. to compile the circuit to a file named `circuit.json`
  42. ## 3. Taking the compiled circuit to *snarkjs*
  43. Now that the circuit is compiled, we will continue with `snarkjs`.
  44. Please note that you can always access the help of `snarkjs` by typing:
  45. ```sh
  46. snarkjs --help
  47. ```
  48. ### 3.1 View information and stats regarding a circuit
  49. To show general statistics of this circuit, you can run:
  50. ```sh
  51. snarkjs info -c circuit.json
  52. ```
  53. You can also print the constraints of the circuit by running:
  54. ```sh
  55. snarkjs printconstraints -c circuit.json
  56. ```
  57. ### 3.2 Setting up using *snarkjs*
  58. Ok, let's run a setup for our circuit:
  59. ```sh
  60. snarkjs setup
  61. ```
  62. > 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>`
  63. The output of the setup will in the form of 2 files: `proving_key.json` and `verification_key.json`
  64. ### 3.3. Calculating a witness
  65. Before creating any proof, we need to calculate all the signals of the circuit that match (all) the constrains of the circuit.
  66. `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*.
  67. 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.
  68. 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.
  69. > Of course you can always use one and the same number as `a` and `b`. We will deal with this problem later.
  70. So you want to prove that you know 3 and 11.
  71. Let's create a file named `input.json`
  72. ```json
  73. {"a": 3, "b": 11}
  74. ```
  75. And now let's calculate the witness:
  76. ```sh
  77. snarkjs calculatewitness
  78. ```
  79. You may want to take a look at `witness.json` file with all the signals.
  80. ### Create the proof
  81. Now that we have the witness generated, we can create the proof.
  82. ```sh
  83. snarkjs proof
  84. ```
  85. This command will use the `prooving_key.json` and the `witness.json` files by default to generate `proof.json` and `public.json`
  86. 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.
  87. ### Verifying the proof
  88. To verify the proof run:
  89. ```sh
  90. snarkjs verify
  91. ```
  92. This command will use `verification_key.json`, `proof.json` and `public.json` to verify that is valid.
  93. Here we are veifying that we know a witness that the public inputs and the outputs matches the ones in the `public.json` file.
  94. If the proof is ok, you will see an `OK` in the screen or `INVALID` otherwise.
  95. ### Generate the solidity verifier
  96. ```sh
  97. snarkjs generateverifier
  98. ```
  99. This command will take the `verification_key.json` and generate a solidity code in `verifier.sol` file.
  100. You can take the code in `verifier.sol` and cut and paste in remix.
  101. This code contains two contracts: Pairings and Verifier. You just need to deploy the `Verifier` contract.
  102. > 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.
  103. ### Verifying the proof on-chain
  104. The verifier contract deployed in the last step has a `view` function called `verifyProof`.
  105. This function will return true if the proof and the inputs are valid.
  106. To facilitiate the call, you can use snarkjs to generate the parameters of the call by typing:
  107. ```sh
  108. snarkjs generatecall
  109. ```
  110. Just cut and paste the output to the parameters field of the `verifyProof` method in Remix.
  111. If every thing works ok, this method should return true.
  112. If you just change any bit in the parameters, you can check that the result will be false.
  113. ## Bonus track
  114. We can fix the circuit to not accept one as any of the values by adding some extra constraints.
  115. Here the trick is that we use the property that 0 has no inverse. so `(a-1)` should not have an inverse.
  116. that means that `(a-1)*inv = 1` will be inpossible to match if `a` is one.
  117. We just calculate inv by `1/(a-1)`
  118. So let's modify the circuit:
  119. ```
  120. template Multiplier() {
  121. signal private input a;
  122. signal private input b;
  123. signal output c;
  124. signal inva;
  125. signal invb;
  126. inva <-- 1/(a-1);
  127. (a-1)*inva === 1;
  128. invb <-- 1/(b-1);
  129. (b-1)*invb === 1;
  130. c <== a*b;
  131. }
  132. component main = Multiplier();
  133. ```
  134. A nice thing of circom language is that you can split a <== into two independent acions: <-- and ===
  135. The <-- and --> operators Just assign a value to a signal without creating any constraints.
  136. The === operator just adds a constraint without assigning any value to any signal.
  137. 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.
  138. ## Where to go from here.
  139. You may want to read the [README](https://github.com/iden3/circom) to learn more features about circom.
  140. 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).
  141. Or a exponentiation in the Baby Jub curve [here](https://github.com/iden3/circomlib) (Work in progress).
  142. # Final note
  143. 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.
  144. 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!.
  145. Enjoy zero knowledge proving!