Compare commits

..

38 Commits

Author SHA1 Message Date
Jordi Baylina
680e3fe139 0.0.31 2019-08-29 16:26:28 +02:00
Jordi Baylina
f05c4e1338 compute block added 2019-08-29 16:26:19 +02:00
Jordi Baylina
597deb1eaa Merge pull request #31 from Mikerah/patch-1
Typo fixes
2019-06-27 11:40:21 +02:00
Jordi Baylina
7a1c606ca6 0.0.30 2019-06-21 10:43:11 +02:00
Jordi Baylina
6642d4cf93 Fix: include allways reduce constants 2019-06-21 10:42:49 +02:00
Jordi Baylina
da0c60a919 0.0.29 2019-06-16 00:28:32 +02:00
Jordi Baylina
534efcf355 fast mode 2019-06-16 00:27:42 +02:00
Mikerah
a43154241e Typo fixes 2019-06-10 20:41:01 -04:00
Jordi Baylina
859c98d2a4 0.0.28 2019-06-03 07:23:55 +02:00
Jordi Baylina
8048a5ef7d Fix and and or 2019-06-03 07:23:25 +02:00
Jordi Baylina
b7a41cda14 0.0.27 2019-05-11 20:55:54 +02:00
Jordi Baylina
34049f2fbd Conditions to boolean in old versions of node 2019-05-11 20:55:05 +02:00
Jordi Baylina
a602551ee5 0.0.26 2019-05-11 20:40:10 +02:00
Jordi Baylina
4d5760ff67 Merge pull request #24 from karsrhyder/patch-1
Update TUTORIAL.md
2019-05-11 20:38:29 +02:00
Jordi Baylina
4a8bcff3da Merge pull request #30 from kobigurk/master
fix: fixes ^ to do xor
2019-05-11 20:32:49 +02:00
Kobi Gurkan
b8068e8d05 fix: changes ^ to do xor 2019-05-11 19:51:30 +03:00
Jordi Baylina
54092044ae Add video tutorial link 2019-04-12 05:21:20 -07:00
Jordi Baylina
11275d59d9 0.0.25 2019-04-12 05:12:04 -07:00
Jordi Baylina
b0607a6e53 update packages 2019-04-12 05:10:48 -07:00
Kars Rhyder
5fccdd6ef1 Update TUTORIAL.md
Some spelling and grammar things
2019-03-04 22:06:37 +01:00
Jordi Baylina
6611f2f024 Merge pull request #22 from 0xGabi/patch-1
Small typo fixes
2019-02-15 00:01:36 +01:00
Gabriel Garcia
e37386115c Remove comment
This comment have the same command again, this supposed to be different syntax?
2019-01-30 00:47:39 +01:00
Gabriel Garcia
b6a00c6d17 Fix small command typo 2019-01-30 00:42:50 +01:00
Jordi Baylina
b0c21ce622 README edited 2018-12-29 11:37:22 +01:00
Jordi Baylina
b10b574816 Tutorial added 2018-12-29 11:34:50 +01:00
Jordi Baylina
3a4352afbe 0.0.24 2018-12-23 00:01:21 +01:00
Jordi Baylina
23f153e91d deps 2018-12-23 00:01:14 +01:00
Jordi Baylina
45c9735a18 0.0.23 2018-12-22 23:52:34 +01:00
Jordi Baylina
81da4747da small patches 2018-12-22 23:52:19 +01:00
Jordi Baylina
394ce29fb2 0.0.22 2018-12-06 17:19:09 +01:00
Jordi Baylina
47be0369e1 Move basic circuits to circomlib 2018-12-06 17:18:52 +01:00
Jordi Baylina
1965dd7f78 0.0.21 2018-11-28 10:27:34 +01:00
Jordi Baylina
145a3eefeb Merge branch 'master' of github.com:iden3/circom 2018-11-28 10:27:17 +01:00
Jordi Baylina
38fa024745 Various small fixes 2018-11-28 10:27:06 +01:00
Jordi Baylina
5020d3f4ee Merge pull request #18 from canadaduane/patch-1
Fix name & grammatical issues
2018-11-19 00:41:24 +01:00
Jordi Baylina
ed63f08aeb Merge pull request #19 from igorbarinov/patch-1
Update README.md
2018-11-19 00:40:57 +01:00
Igor Barinov
c2a54e9187 Update README.md
Problem: -s option is not required and returns an error when used
```
 circom -s ./mycircuit.circom -o ./mycircuit.json
ENOENT: no such file or directory, open '/Users/user/js/jsbench/circuit.circom'
```

Solution:
remove -s option in the README file
2018-11-18 16:51:25 +01:00
Duane Johnson
3f99f4eb53 Fix name & grammatical issues 2018-11-06 14:20:02 -07:00
48 changed files with 1235 additions and 4884 deletions

View File

@@ -1,12 +1,18 @@
# Circom # Circom
Circon is a language designed to write arithmetic circuits that can be used in zero knowledge proofs. Circom is a language designed to write arithmetic circuits that can be used in zero knowledge proofs.
In particular, it is designed to work in [zksnarks JavaScript library](https://github.com/iden3/zksnark). In particular, it is designed to work in [zksnarks JavaScript library](https://github.com/iden3/zksnark).
## Usage ## Usage
### Tutorial
A good starting point [is this tutorial](https://github.com/iden3/circom/blob/master/TUTORIAL.md)
Also this [video](https://www.youtube.com/watch?v=-9TJa1hVsKA) is a good starting point.
### First circuit ### First circuit
Creation of a circuit. This is an example of a NAND door: Creation of a circuit. This is an example of a NAND door:
@@ -25,7 +31,7 @@ template NAND() {
component main = NAND(); component main = NAND();
``` ```
The language uses mainly JavaScript/C syntax together with 5 extra operators to define the constraints: The language uses mainly JavaScript/C syntax together with 5 extra operators to define the following constraints:
`<==` , `==>` : These two operators are used to connect signals and at the same time imply a constraint. `<==` , `==>` : These two operators are used to connect signals and at the same time imply a constraint.
@@ -39,7 +45,7 @@ In the above example, both inputs are forced to be binary by adding the constrai
### Compilation the circuit ### Compilation the circuit
First of all, the compiler must be installed typing: First of all, the compiler must be installed by typing:
``` ```
npm install -g circom npm install -g circom
@@ -48,7 +54,7 @@ npm install -g circom
The circuit is compiled with the following command: The circuit is compiled with the following command:
``` ```
circom -s mycircuit.circom -o mycircuit.json circom mycircuit.circom -o mycircuit.json
``` ```
The resulting output ( `mycircuit.json` ) can be used in the [zksnarks JavaScript library](https://github.com/iden3/zksnark). The resulting output ( `mycircuit.json` ) can be used in the [zksnarks JavaScript library](https://github.com/iden3/zksnark).
@@ -91,7 +97,7 @@ in === out[0]*2**0 + out[1]*2**1 + out[2]*2**2 + ... + out[n-1]*2**(n-1)
``` ```
We do this by using a variable `lc1` and adding each signal multiplied by its coefficient. We do this by using a variable `lc1` and adding each signal multiplied by its coefficient.
This variable does not hold a value in compilation time, but it holds a linear combination and it is used in the last constraint: This variable does not hold a value at compilation time, but it holds a linear combination and it is used in the last constraint:
``` ```
lc1 === in; lc1 === in;
@@ -254,9 +260,14 @@ component main = Adder();
In this example we have shown how to design a top-down circuit with many subcircuits and how to connect them together. One can also see that auxiliary functions to do specific computations can be created. In this example we have shown how to design a top-down circuit with many subcircuits and how to connect them together. One can also see that auxiliary functions to do specific computations can be created.
### More examples.
You can find more examples in this library of basic circits [circomlib](https://github.com/iden3/circomlib)
## License ## License
Circon is part of the iden3 project copyright 2018 0KIMS association and published with GPL-3 license. Please check the COPYING file for more details. Circom is part of the iden3 project copyright 2018 0KIMS association and published with GPL-3 license. Please check the COPYING file for more details.

254
TUTORIAL.md Normal file
View File

@@ -0,0 +1,254 @@
# circom and snarkjs tutorial
This tutorial will guide you in creating your first Zero Knowledge zkSnark circuit. It will take you through the various techniques to write circuits, and will show you how to create proofs and verify them off-chain and on-chain on Ethereum.
## 1. Installing the tools
### 1.1 Pre-requisites
If you don't have it installed yet, you need to install `Node.js`.
The 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 a significant increase in performance. 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 (!).
### 1.2 Install **circom** and **snarkjs**
Run:
```sh
npm install -g circom
npm install -g snarkjs
```
## 2. Working with a circuit
Let's create a circuit that tries to prove that you are able to factor a number!
### 2.1 Create a circuit in a new directory
1. Create an empty directory called `factor` where you will put all the files that you will use in this tutorial.
```
mkdir factor
cd factor
```
> 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.
2. Create a new file named `circuit.circom` with the following content:
```
template Multiplier() {
signal private input a;
signal private input b;
signal output c;
c <== a*b;
}
component main = Multiplier();
```
This circuit has 2 private input signals named `a` and `b` and one output named `c`.
The only thing that the circuit does is forcing the signal `c` to be the value of `a*b`
After declaring the `Multiplier` template, we instantiate it with a component named`main`.
Note: When compiling a circuit, a component named `main` must always exist.
### 2.2 Compile the circuit
We are now ready to compile the circuit. Run the following command:
```sh
circom circuit.circom -o circuit.json
```
to compile the circuit to a file named `circuit.json`
## 3. Taking the compiled circuit to *snarkjs*
Now that the circuit is compiled, we will continue with `snarkjs`.
Please note that you can always access the help of `snarkjs` by typing:
```sh
snarkjs --help
```
### 3.1 View information and stats regarding a circuit
To show general statistics of this circuit, you can run:
```sh
snarkjs info -c circuit.json
```
You can also print the constraints of the circuit by running:
```sh
snarkjs printconstraints -c circuit.json
```
### 3.2 Setting up using *snarkjs*
Ok, let's run a setup for our circuit:
```sh
snarkjs setup
```
> 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>`
The output of the setup will in the form of 2 files: `proving_key.json` and `verification_key.json`
### 3.3. Calculating a witness
Before creating any proof, we need to calculate all the signals of the circuit that match (all) the constrains of the circuit.
`snarkjs` calculates those 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*.
The zero knowledge proofs prove that you know a set of signals (witness) that match all the constraints, without revealing any of the signals except the public inputs plus the outputs.
For example, imagine you want to prove you are able to factor 33. It means that you know two numbers `a` and `b` and when you multiply them, it results in 33.
> Of course you can always use one and the same number as `a` and `b`. We will deal with this problem later.
So you want to prove that you know 3 and 11.
Let's create a file named `input.json`
```json
{"a": 3, "b": 11}
```
Now let's calculate the witness:
```sh
snarkjs calculatewitness
```
You may want to take a look at `witness.json` file with all the signals.
### Create the proof
Now that we have the witness generated, we can create the proof.
```sh
snarkjs proof
```
This command will use the `proving_key.json` and the `witness.json` files by default to generate `proof.json` and `public.json`
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.
### Verifying the proof
To verify the proof run:
```sh
snarkjs verify
```
This command will use `verification_key.json`, `proof.json` and `public.json` to verify that is valid.
Here we are verifying that we know a witness that the public inputs and the outputs matches the ones in the `public.json` file.
If the proof is ok, you will see `OK` or `INVALID` if not ok.
### Generate the solidity verifier
```sh
snarkjs generateverifier
```
This command will take the `verification_key.json` and generate solidity code in `verifier.sol` file.
You can take the code in `verifier.sol` and cut and paste it in remix.
This code contains two contracts: Pairings and Verifier. You only need to deploy the `Verifier` contract.
> 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.
### Verifying the proof on-chain
The verifier contract deployed in the last step has a `view` function called `verifyProof`.
This function will return true if the proof and the inputs are valid.
To facilitate the call, you can use snarkjs to generate the parameters of the call by typing:
```sh
snarkjs generatecall
```
Just cut and paste the output to the parameters field of the `verifyProof` method in Remix.
If every thing works ok, this method should return true.
If you change any bit in the parameters, the result will be verifiably false.
## Bonus track
We can fix the circuit to not accept one as any of the values by adding some extra constraints.
Here the trick is that we use the property that 0 has no inverse. So `(a-1)` should not have an inverse.
That means that `(a-1)*inv = 1` will be inpossible to match if `a` is 1.
We just calculate inv by `1/(a-1)`
So let's modify the circuit:
```
template Multiplier() {
signal private input a;
signal private input b;
signal output c;
signal inva;
signal invb;
inva <-- 1/(a-1);
(a-1)*inva === 1;
invb <-- 1/(b-1);
(b-1)*invb === 1;
c <== a*b;
}
component main = Multiplier();
```
A nice thing of the circom language is that you can split a <== into two independent actions: <-- and ===
The <-- and --> operators assign a value to a signal without creating any constraints.
The === operator adds a constraint without assigning any value to any signal.
The circuit also has another problem: the operation works in Zr, so we need to guarantee the multiplication does not overflow. This can be done by converting the inputs to binary and checking the ranges, but we will reserve it for future tutorials.
## Where to go from here:
You may want to read the [README](https://github.com/iden3/circom) to learn more features about circom.
You can also check a library with many basic circuits lib binarizations, comparators, eddsa, hashes, merkle trees etc [here](https://github.com/iden3/circomlib) (Work in progress).
Or a exponentiation in the Baby Jub curve [here](https://github.com/iden3/circomlib) (Work in progress).
# Final note
There is nothing worse 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 work needs to be done. Please have it present if you are doing anything serious with it.
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 useful to us.
Enjoy zero knowledge proving!

View File

@@ -1,93 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
/*
Binary Sum
==========
This component creates a binary sum componet of ops operands and n bits each operand.
e is Number of carries: Depends on the number of operands in the input.
Main Constraint:
in[0][0] * 2^0 + in[0][1] * 2^1 + ..... + in[0][n-1] * 2^(n-1) +
+ in[1][0] * 2^0 + in[1][1] * 2^1 + ..... + in[1][n-1] * 2^(n-1) +
+ ..
+ in[ops-1][0] * 2^0 + in[ops-1][1] * 2^1 + ..... + in[ops-1][n-1] * 2^(n-1) +
===
out[0] * 2^0 + out[1] * 2^1 + + out[n+e-1] *2(n+e-1)
To waranty binary outputs:
out[0] * (out[0] - 1) === 0
out[1] * (out[0] - 1) === 0
.
.
.
out[n+e-1] * (out[n+e-1] - 1) == 0
*/
/*
This function calculates the number of extra bits in the output to do the full sum.
*/
function nbits(a) {
var n = 1;
var r = 0;
while (n-1<a) {
r++;
n *= 2;
}
return r;
}
template BinSum(n, ops) {
var nout = nbits((2**n -1)*ops);
signal input in[ops][n];
signal output out[nout];
var lin = 0;
var lout = 0;
var k;
var j;
for (k=0; k<n; k++) {
for (j=0; j<ops; j++) {
lin += in[j][k] * 2**k;
}
}
for (k=0; k<nout; k++) {
out[k] <-- (lin >> k) & 1;
// Ensure out is binary
out[k] * (out[k] - 1) === 0;
lout += out[k] * 2**k;
}
// Ensure the sum;
lin === lout;
}

View File

@@ -1,72 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
include "comparators.circom";
template Num2Bits(n) {
signal input in;
signal output out[n];
var lc1=0;
for (var i = 0; i<n; i++) {
out[i] <-- (in >> i) & 1;
out[i] * (out[i] -1 ) === 0;
lc1 += out[i] * 2**i;
}
lc1 === in;
}
template Bits2Num(n) {
signal input in[n];
signal output out;
var lc1=0;
for (var i = 0; i<n; i++) {
lc1 += in[i] * 2**i;
}
lc1 ==> out;
}
template Num2BitsNeg(n) {
signal input in;
signal output out[n];
var lc1=0;
component isZero;
isZero = IsZero();
var neg = n == 0 ? 0 : 2**n - in;
for (var i = 0; i<n; i++) {
out[i] <-- (neg >> i) & 1;
out[i] * (out[i] -1 ) === 0;
lc1 += out[i] * 2**i;
}
in ==> isZero.in;
lc1 + isZero.out * 2**n === 2**n - in;
}

View File

@@ -1,55 +0,0 @@
include "bitify.circom";
include "binsum.circom";
template IsZero() {
signal input in;
signal output out;
signal inv;
inv <-- in!=0 ? 1/in : 0;
out <== -in*inv +1;
in*out === 0;
}
template IsEqual() {
signal input in[2];
signal output out;
component isz = IsZero();
in[1] - in[0] ==> isz.in;
isz.out ==> out;
}
// N is the number of bits the input have.
// The MSF is the sign bit.
template LessThan(n) {
signal input in[2];
signal output out;
component num2Bits0;
component num2Bits1;
component adder;
adder = BinSum(n, 2);
num2Bits0 = Num2Bits(n);
num2Bits1 = Num2BitsNeg(n);
in[0] ==> num2Bits0.in;
in[1] ==> num2Bits1.in;
var i;
for (i=0;i<n;i++) {
num2Bits0.out[i] ==> adder.in[0][i];
num2Bits1.out[i] ==> adder.in[1][i];
}
adder.out[n-1] ==> out;
}

View File

@@ -1,67 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
template XOR() {
signal input a;
signal input b;
signal output out;
out <== a + b - 2*a*b;
}
template AND() {
signal input a;
signal input b;
signal output out;
out <== a*b;
}
template OR() {
signal input a;
signal input b;
signal output out;
out <== a + b - a*b;
}
template NOT() {
signal input in;
signal output out;
out <== 1 + in - 2*in;
}
template NAND() {
signal input a;
signal input b;
signal output out;
out <== 1 - a*b;
}
template NOR() {
signal input a;
signal input b;
signal output out;
out <== a*b + 1 - a - b;
}

View File

@@ -1,93 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
// --> Assignation without constraint
// <-- Assignation without constraint
// === Constraint
// <== Assignation with constraint
// ==> Assignation with constraint
// All variables are members of the field F[p]
// https://github.com/zcash-hackworks/sapling-crypto
// https://github.com/ebfull/bellman
/*
function log2(a) {
if (a==0) {
return 0;
}
let n = 1;
let r = 1;
while (n<a) {
r++;
n *= 2;
}
return r;
}
*/
template EscalarProduct(w) {
signal input in1[w];
signal input in2[w];
signal output out;
signal aux[w];
var lc = 0;
for (var i=0; i<w; i++) {
aux[i] <== in1[i]*in2[i];
lc = lc + aux[i];
}
out <== lc;
}
template Decoder(w) {
signal input inp;
signal output out[w];
signal output success;
var lc=0;
for (var i=0; i<w; i++) {
out[i] <-- (inp == i) ? 1 : 0;
out[i] * (inp-i) === 0;
lc = lc + out[i];
}
lc ==> success;
success * (success -1) === 0;
}
template Multiplexor(wIn, nIn) {
signal input inp[nIn][wIn];
signal input sel;
signal output out[wIn];
component Decoder(nIn) dec;
component EscalarProduct(nIn) ep[wIn];
sel ==> dec.inp;
for (var j=0; j<wIn; j++) {
for (var k=0; k<nIn; k++) {
inp[k][j] ==> ep[j].in1[k];
dec.out[k] ==> ep[j].in2[k];
}
ep[j].out ==> out[j];
}
dec.success === 1;
}
component Multiplexor(8,3) main;

View File

@@ -1,46 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
/* Ch
000 0
001 1
010 0
011 1
100 0
101 0
110 1
111 1
out = a&b ^ (!a)&c =>
out = a*(b-c) + c
*/
template Ch(n) {
signal input a[n];
signal input b[n];
signal input c[n];
signal output out[n];
for (var k=0; k<n; k++) {
out[k] <== a[k] * (b[k]-c[k]) + c[k];
}
}

View File

@@ -1,52 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
template H(x) {
signal output out[32];
var c = [0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19];
for (var i=0; i<32; i++) {
out[i] <== (c[x] >> i) & 1;
}
}
template K(x) {
signal output out[32];
var c = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
for (var i=0; i<32; i++) {
out[i] <== (c[x] >> i) & 1;
}
}

View File

@@ -1,34 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
include "sha256_2.jaz";
template Main() {
signal private input a;
signal private input b;
signal output out;
component sha256_2 = SHA256_2();
sha256_2.a <== a;
sha256_2.b <== a;
out <== sha256_2.out;
}
component main = Main();

View File

@@ -1,44 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
/* Maj function for sha256
out = a&b ^ a&c ^ b&c =>
out = a*b + a*c + b*c - 2*a*b*c =>
out = a*( b + c - 2*b*c ) + b*c =>
mid = b*c
out = a*( b + c - 2*mid ) + mid
*/
template Maj(n) {
signal input a[n];
signal input b[n];
signal input c[n];
signal output out[n];
signal mid[n];
for (var k=0; k<n; k++) {
mid[k] <== b[k]*c[k];
out[k] <== a[k] * (b[k]+c[k]-2*mid[k]) + mid[k];
}
}

View File

@@ -1,27 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
template RotR(n, r) {
signal input in[n];
signal output out[n];
for (var i=0; i<n; i++) {
out[i] <== in[ (i+r)%n ];
}
}

View File

@@ -1,67 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
include "sha256compression.circom";
include "../bitify.circom"
template Sha256_2() {
signal input a;
signal input b;
signal output out;
component bits2num = Bits2Num(216);
component num2bits[2];
num2bits[0] = Num2Bits(216);
num2bits[1] = Num2Bits(216);
num2bits[0].in <== a;
num2bits[1].in <== b;
component sha256compression = Sha256compression() ;
var i;
for (i=0; i<216; i++) {
sha256compression.inp[i] <== num2bits[0].out[215-i];
sha256compression.inp[i+216] <== num2bits[1].out[215-i];
}
sha256compression.inp[432] <== 1;
for (i=433; i<503; i++) {
sha256compression.inp[i] <== 0;
}
sha256compression.inp[503] <== 1;
sha256compression.inp[504] <== 1;
sha256compression.inp[505] <== 0;
sha256compression.inp[506] <== 1;
sha256compression.inp[507] <== 1;
sha256compression.inp[508] <== 0;
sha256compression.inp[509] <== 0;
sha256compression.inp[510] <== 0;
sha256compression.inp[511] <== 0;
for (i=0; i<216; i++) {
bits2num.in[i] <== sha256compression.out[255-i];
}
out <== bits2num.out;
}

View File

@@ -1,164 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
include "constants.circom";
include "t1.circom";
include "t2.circom";
include "../binsum.circom";
include "sigmaplus.circom";
template Sha256compression() {
signal input inp[512];
signal output out[256];
signal a[65][32];
signal b[65][32];
signal c[65][32];
signal d[65][32];
signal e[65][32];
signal f[65][32];
signal g[65][32];
signal h[65][32];
signal w[64][32];
var i;
component sigmaPlus[48];
for (i=0; i<48; i++) sigmaPlus[i] = SigmaPlus();
component ct_k[64];
for (i=0; i<64; i++) ct_k[i] = K(i);
component ha0 = H(0);
component hb0 = H(1);
component hc0 = H(2);
component hd0 = H(3);
component he0 = H(4);
component hf0 = H(5);
component hg0 = H(6);
component hh0 = H(7);
component t1[64];
for (i=0; i<64; i++) t1[i] = T1();
component t2[64];
for (i=0; i<64; i++) t2[i] = T2();
component suma[64];
for (i=0; i<64; i++) suma[i] = BinSum(32, 2);
component sume[64];
for (i=0; i<64; i++) sume[i] = BinSum(32, 2);
component fsum[8];
for (i=0; i<8; i++) fsum[i] = BinSum(32, 2);
var k;
var t;
for (t=0; t<64; t++) {
if (t<16) {
for (k=0; k<32; k++) {
w[t][k] <== inp[t*32+31-k];
}
} else {
for (k=0; k<32; k++) {
sigmaPlus[t-16].in2[k] <== w[t-2][k];
sigmaPlus[t-16].in7[k] <== w[t-7][k];
sigmaPlus[t-16].in15[k] <== w[t-15][k];
sigmaPlus[t-16].in16[k] <== w[t-16][k];
w[t][k] <== sigmaPlus[t-16].out[k];
}
}
}
for (k=0; k<32; k++ ) {
a[0][k] <== ha0.out[k]
b[0][k] <== hb0.out[k]
c[0][k] <== hc0.out[k]
d[0][k] <== hd0.out[k]
e[0][k] <== he0.out[k]
f[0][k] <== hf0.out[k]
g[0][k] <== hg0.out[k]
h[0][k] <== hh0.out[k]
}
for (t = 0; t<64; t++) {
for (k=0; k<32; k++) {
t1[t].h[k] <== h[t][k];
t1[t].e[k] <== e[t][k];
t1[t].f[k] <== f[t][k];
t1[t].g[k] <== g[t][k];
t1[t].k[k] <== ct_k[t].out[k];
t1[t].w[k] <== w[t][k];
t2[t].a[k] <== a[t][k];
t2[t].b[k] <== b[t][k];
t2[t].c[k] <== c[t][k];
}
for (k=0; k<32; k++) {
sume[t].in[0][k] <== d[t][k];
sume[t].in[1][k] <== t1[t].out[k];
suma[t].in[0][k] <== t1[t].out[k];
suma[t].in[1][k] <== t2[t].out[k];
}
for (k=0; k<32; k++) {
h[t+1][k] <== g[t][k];
g[t+1][k] <== f[t][k];
f[t+1][k] <== e[t][k];
e[t+1][k] <== sume[t].out[k];
d[t+1][k] <== c[t][k];
c[t+1][k] <== b[t][k];
b[t+1][k] <== a[t][k];
a[t+1][k] <== suma[t].out[k];
}
}
for (k=0; k<32; k++) {
fsum[0].in[0][k] <== ha0.out[k];
fsum[0].in[1][k] <== a[64][k];
fsum[1].in[0][k] <== hb0.out[k];
fsum[1].in[1][k] <== b[64][k];
fsum[2].in[0][k] <== hc0.out[k];
fsum[2].in[1][k] <== c[64][k];
fsum[3].in[0][k] <== hd0.out[k];
fsum[3].in[1][k] <== d[64][k];
fsum[4].in[0][k] <== he0.out[k];
fsum[4].in[1][k] <== e[64][k];
fsum[5].in[0][k] <== hf0.out[k];
fsum[5].in[1][k] <== f[64][k];
fsum[6].in[0][k] <== hg0.out[k];
fsum[6].in[1][k] <== g[64][k];
fsum[7].in[0][k] <== hh0.out[k];
fsum[7].in[1][k] <== h[64][k];
}
for (k=0; k<32; k++) {
out[31-k] <== fsum[0].out[k];
out[32+31-k] <== fsum[1].out[k];
out[64+31-k] <== fsum[2].out[k];
out[96+31-k] <== fsum[3].out[k];
out[128+31-k] <== fsum[4].out[k];
out[160+31-k] <== fsum[5].out[k];
out[192+31-k] <== fsum[6].out[k];
out[224+31-k] <== fsum[7].out[k];
}
}

View File

@@ -1,32 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
template ShR(n, r) {
signal input in[n];
signal output out[n];
for (var i=0; i<n; i++) {
if (i+r >= n) {
out[i] <== 0;
} else {
out[i] <== in[ i+r ];
}
}
}

View File

@@ -1,68 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
include "xor3.circom";
include "rotate.circom";
include "shift.circom";
template SmallSigma(ra, rb, rc) {
signal input in[32];
signal output out[32];
component xor3 = Xor3(32);
component rota = RotR(32, ra);
component rotb = RotR(32, rb);
component shrc = ShR(32, rc);
for (var k=0; k<32; k++) {
rota.in[k] <== in[k];
rotb.in[k] <== in[k];
shrc.in[k] <== in[k];
xor3.a[k] <== rota.out[k];
xor3.b[k] <== rotb.out[k];
xor3.c[k] <== shrc.out[k];
out[k] <== xor3.out[k];
}
}
template BigSigma(ra, rb, rc) {
signal input in[32];
signal output out[32];
component xor3 = Xor3(32);
component rota = RotR(32, ra);
component rotb = RotR(32, rb);
component rotc = RotR(32, rc);
for (var k=0; k<32; k++) {
rota.in[k] <== in[k];
rotb.in[k] <== in[k];
rotc.in[k] <== in[k];
xor3.a[k] <== rota.out[k];
xor3.b[k] <== rotb.out[k];
xor3.c[k] <== rotc.out[k];
out[k] <== xor3.out[k];
}
}

View File

@@ -1,45 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
include "../binsum.circom"
include "sigma.circom"
template SigmaPlus() {
signal input in2[32];
signal input in7[32];
signal input in15[32];
signal input in16[32];
signal output out[32];
component sum = BinSum(32, 4);
component sigma1 = SmallSigma(17,19,10);
component sigma0 = SmallSigma(7, 18, 3);
for (var k=0; k<32; k++) {
sigma1.in[k] <== in2[k];
sigma0.in[k] <== in15[k];
sum.in[0][k] <== sigma1.out[k];
sum.in[1][k] <== in7[k];
sum.in[2][k] <== sigma0.out[k];
sum.in[3][k] <== in16[k];
out[k] <== sum.out[k];
}
}

View File

@@ -1,52 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
include "../binsum.circom";
include "sigma.circom";
include "ch.circom";
template T1() {
signal input h[32];
signal input e[32];
signal input f[32];
signal input g[32];
signal input k[32];
signal input w[32];
signal output out[32];
component sum = BinSum(32, 5);
component ch = Ch(32);
component bigsigma1 = BigSigma(6, 11, 25);
for (var ki=0; ki<32; ki++) {
bigsigma1.in[ki] <== e[ki];
ch.a[ki] <== e[ki];
ch.b[ki] <== f[ki];
ch.c[ki] <== g[ki]
sum.in[0][ki] <== h[ki];
sum.in[1][ki] <== bigsigma1.out[ki];
sum.in[2][ki] <== ch.out[ki];
sum.in[3][ki] <== k[ki];
sum.in[4][ki] <== w[ki];
out[ki] <== sum.out[ki];
}
}

View File

@@ -1,47 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
include "../binsum.circom";
include "sigma.circom";
include "maj.circom"
template T2() {
signal input a[32];
signal input b[32];
signal input c[32];
signal output out[32];
component sum = BinSum(32, 2);
component bigsigma0 = BigSigma(2, 13, 22);
component maj = Maj(32);
for (var k=0; k<32; k++) {
bigsigma0.in[k] <== a[k];
maj.a[k] <== a[k];
maj.b[k] <== b[k];
maj.c[k] <== c[k];
sum.in[0][k] <== bigsigma0.out[k];
sum.in[1][k] <== maj.out[k];
out[k] <== sum.out[k];
}
}

View File

@@ -1,44 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
/* Xor3 function for sha256
out = a ^ b ^ c =>
out = a+b+c - 2*a*b - 2*a*c - 2*b*c + 4*a*b*c =>
out = a*( 1 - 2*b - 2*c + 4*b*c ) + b + c - 2*b*c =>
mid = b*c
out = a*( 1 - 2*b -2*c + 4*mid ) + b + c - 2 * mid
*/
template Xor3(n) {
signal input a[n];
signal input b[n];
signal input c[n];
signal output out[n];
signal mid[n];
for (var k=0; k<n; k++) {
mid[k] <== b[k]*c[k];
out[k] <== a[k] * (1 -2*b[k] -2*c[k] +4*mid[k]) + b[k] + c[k] -2*mid[k];
}
}

View File

@@ -1,37 +0,0 @@
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
circom is a free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
circom is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
template toBin(n) {
signal input inp;
signal output out[n];
var lc1=0;
for (var i = 0; i<n; i++) {
out[i] <-- (inp >> i) & 1;
out[i] * (out[i] -1 ) === 0;
lc1 += out[i] * 2**i;
}
lc1 === inp;
}
component toBin(3) main;

3
cli.js
View File

@@ -35,6 +35,7 @@ const argv = require("yargs")
.help("h") .help("h")
.alias("h", "help") .alias("h", "help")
.alias("v", "verbose") .alias("v", "verbose")
.alias("f", "fast")
.epilogue(`Copyright (C) 2018 0kims association .epilogue(`Copyright (C) 2018 0kims association
This program comes with ABSOLUTELY NO WARRANTY; This program comes with ABSOLUTELY NO WARRANTY;
This is free software, and you are welcome to redistribute it This is free software, and you are welcome to redistribute it
@@ -56,7 +57,7 @@ if (argv._.length == 0) {
const fullFileName = path.resolve(process.cwd(), inputFile); const fullFileName = path.resolve(process.cwd(), inputFile);
const outName = argv.output ? argv.output : "circuit.json"; const outName = argv.output ? argv.output : "circuit.json";
compiler(fullFileName).then( (cir) => { compiler(fullFileName, {reduceConstraints: !argv.fast}).then( (cir) => {
fs.writeFileSync(outName, JSON.stringify(cir, null, 1), "utf8"); fs.writeFileSync(outName, JSON.stringify(cir, null, 1), "utf8");
process.exit(0); process.exit(0);
}, (err) => { }, (err) => {

1152
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "circom", "name": "circom",
"version": "0.0.20", "version": "0.0.31",
"description": "Language to generate logic circuits", "description": "Language to generate logic circuits",
"main": "index.js", "main": "index.js",
"directories": { "directories": {
@@ -34,10 +34,10 @@
"yargs": "^12.0.2" "yargs": "^12.0.2"
}, },
"devDependencies": { "devDependencies": {
"chai": "^4.1.2", "chai": "^4.2.0",
"eslint": "^5.0.1", "eslint": "^5.16.0",
"eslint-plugin-mocha": "^5.0.0", "eslint-plugin-mocha": "^5.3.0",
"jison": "^0.4.18", "jison": "^0.4.18",
"snarkjs": "0.1.6" "snarkjs": "0.1.14"
} }
} }

View File

@@ -40,6 +40,7 @@ if { return 'if'; }
else { return 'else'; } else { return 'else'; }
for { return 'for'; } for { return 'for'; }
while { return 'while'; } while { return 'while'; }
compute { return 'compute'; }
do { return 'do'; } do { return 'do'; }
return { return 'return'; } return { return 'return'; }
include { return 'include'; } include { return 'include'; }
@@ -78,6 +79,7 @@ include { return 'include'; }
\- { return '-'; } \- { return '-'; }
\* { return '*'; } \* { return '*'; }
\/ { return '/'; } \/ { return '/'; }
\\ { return '\\'; }
\% { return '%'; } \% { return '%'; }
\^ { return '^'; } \^ { return '^'; }
\& { return '&'; } \& { return '&'; }
@@ -118,7 +120,7 @@ include { return 'include'; }
%left '<<' '>>' %left '<<' '>>'
%left '+' '-' %left '+' '-'
%left '*' '/' '%' %left '*' '/' '\\' '%'
%left '**' %left '**'
%right '++' '--' UMINUS UPLUS '!' '~' %right '++' '--' UMINUS UPLUS '!' '~'
%left '.' %left '.'
@@ -197,6 +199,10 @@ statment
{ {
$$ = $1; $$ = $1;
} }
| computeStatment
{
$$ = $1;
}
| returnStatment | returnStatment
{ {
$$ = $1; $$ = $1;
@@ -301,6 +307,14 @@ doWhileStatment
} }
; ;
computeStatment
: 'compute' statment
{
$$ = { type: "COMPUTE", body: $2 };
setLines($$, @1, @2);
}
;
returnStatment returnStatment
: 'return' expression ';' : 'return' expression ';'
{ {
@@ -513,7 +527,7 @@ e12
: e12 '^' e11 : e12 '^' e11
{ {
if (($1.type == "NUMBER") && ($3.type == "NUMBER")) { if (($1.type == "NUMBER") && ($3.type == "NUMBER")) {
$$ = { type: "NUMBER", value: $1.value.or($3.value).and(__MASK__) }; $$ = { type: "NUMBER", value: $1.value.xor($3.value).and(__MASK__) };
} else { } else {
$$ = { type: "OP", op: "^", values: [$1, $3] }; $$ = { type: "OP", op: "^", values: [$1, $3] };
} }
@@ -627,7 +641,7 @@ e7
{ {
if (($1.type == "NUMBER") && ($3.type == "NUMBER")) { if (($1.type == "NUMBER") && ($3.type == "NUMBER")) {
let v = $3.value.greater(256) ? 256 : $3.value.value; let v = $3.value.greater(256) ? 256 : $3.value.value;
$$ = {t1ype: "NUMBER", value: $1.value.shiftRight(v).and(__MASK__) }; $$ = {type: "NUMBER", value: $1.value.shiftRight(v).and(__MASK__) };
} else { } else {
$$ = { type: "OP", op: ">>", values: [$1, $3] }; $$ = { type: "OP", op: ">>", values: [$1, $3] };
} }
@@ -684,6 +698,15 @@ e5
} }
setLines($$, @1, @3); setLines($$, @1, @3);
} }
| e5 '\\' e4
{
if (($1.type == "NUMBER") && ($3.type == "NUMBER")) {
$$ = { type: "NUMBER", value: ($1.value.divide($3.value)) };
} else {
$$ = { type: "OP", op: "\\", values: [$1, $3] };
}
setLines($$, @1, @3);
}
| e5 '%' e4 | e5 '%' e4
{ {
if (($1.type == "NUMBER") && ($3.type == "NUMBER")) { if (($1.type == "NUMBER") && ($3.type == "NUMBER")) {

File diff suppressed because one or more lines are too long

View File

@@ -33,7 +33,13 @@ const parser = require("../parser/jaz.js").parser;
const timeout = ms => new Promise(res => setTimeout(res, ms)); const timeout = ms => new Promise(res => setTimeout(res, ms));
async function compile(srcFile) { async function compile(srcFile, options) {
if (!options) {
options = {};
}
if (typeof options.reduceConstraints === "undefined") {
options.reduceConstraints = true;
}
const fullFileName = srcFile; const fullFileName = srcFile;
const fullFilePath = path.dirname(fullFileName); const fullFilePath = path.dirname(fullFileName);
@@ -70,13 +76,16 @@ async function compile(srcFile) {
} }
classifySignals(ctx); classifySignals(ctx);
reduceConstants(ctx);
// Repeat while reductions are performed reduceConstants(ctx);
let oldNConstrains = -1; if (options.reduceConstraints) {
while (ctx.constraints.length != oldNConstrains) {
oldNConstrains = ctx.constraints.length; // Repeat while reductions are performed
reduceConstrains(ctx); let oldNConstrains = -1;
while (ctx.constraints.length != oldNConstrains) {
oldNConstrains = ctx.constraints.length;
reduceConstrains(ctx);
}
} }
generateWitnessNames(ctx); generateWitnessNames(ctx);

View File

@@ -78,12 +78,22 @@ function exec(ctx, ast) {
return execPlusPlusRight(ctx, ast); return execPlusPlusRight(ctx, ast);
} else if (ast.op == "PLUSPLUSLEFT") { } else if (ast.op == "PLUSPLUSLEFT") {
return execPlusPlusLeft(ctx, ast); return execPlusPlusLeft(ctx, ast);
} else if (ast.op == "MINUSMINUSRIGHT") {
return execMinusMinusRight(ctx, ast);
} else if (ast.op == "MINUSMINUSLEFT") {
return execMinusMinusLeft(ctx, ast);
} else if (ast.op == "/") { } else if (ast.op == "/") {
return execDiv(ctx, ast); return execDiv(ctx, ast);
} else if (ast.op == "\\") {
return execIDiv(ctx, ast);
} else if (ast.op == "**") { } else if (ast.op == "**") {
return execExp(ctx, ast); return execExp(ctx, ast);
} else if (ast.op == "&") { } else if (ast.op == "&") {
return execBAnd(ctx, ast); return execBAnd(ctx, ast);
} else if (ast.op == "&&") {
return execAnd(ctx, ast);
} else if (ast.op == "||") {
return execOr(ctx, ast);
} else if (ast.op == "<<") { } else if (ast.op == "<<") {
return execShl(ctx, ast); return execShl(ctx, ast);
} else if (ast.op == ">>") { } else if (ast.op == ">>") {
@@ -121,6 +131,8 @@ function exec(ctx, ast) {
return execFunctionCall(ctx, ast); return execFunctionCall(ctx, ast);
} else if (ast.type == "BLOCK") { } else if (ast.type == "BLOCK") {
return execBlock(ctx, ast); return execBlock(ctx, ast);
} else if (ast.type == "COMPUTE") {
return ;
} else if (ast.type == "FOR") { } else if (ast.type == "FOR") {
return execFor(ctx, ast); return execFor(ctx, ast);
} else if (ast.type == "WHILE") { } else if (ast.type == "WHILE") {
@@ -152,7 +164,8 @@ function error(ctx, ast, errStr) {
}, },
errStr: errStr, errStr: errStr,
errFile: ctx.fileName, errFile: ctx.fileName,
ast: ast ast: ast,
message: errStr
}; };
} }
@@ -361,6 +374,8 @@ function execInstantiateComponet(ctx, vr, fn) {
ctx.scopes = oldScopes.slice(0, scopeLevel+1); ctx.scopes = oldScopes.slice(0, scopeLevel+1);
if (template.params.length != paramValues.length) return error(ctx, fn, "Invalid number of parameters: " + templateName);
const scope = {}; const scope = {};
for (let i=0; i< template.params.length; i++) { for (let i=0; i< template.params.length; i++) {
scope[template.params[i]] = paramValues[i]; scope[template.params[i]] = paramValues[i];
@@ -384,6 +399,12 @@ function execInstantiateComponet(ctx, vr, fn) {
function execFunctionCall(ctx, ast) { function execFunctionCall(ctx, ast) {
if (ast.name == "log") {
const v = exec(ctx, ast.params[0]);
console.log(v.value.toString());
return;
}
const scopeLevel = getScopeLevel(ctx, ast.name); const scopeLevel = getScopeLevel(ctx, ast.name);
if (scopeLevel == -1) return error(ctx, ast, "Function not defined: " + ast.name); if (scopeLevel == -1) return error(ctx, ast, "Function not defined: " + ast.name);
const fnc = getScope(ctx, ast.name); const fnc = getScope(ctx, ast.name);
@@ -546,6 +567,8 @@ function execPin(ctx, ast) {
} }
function execFor(ctx, ast) { function execFor(ctx, ast) {
ctx.scopes.push({});
exec(ctx, ast.init); exec(ctx, ast.init);
if (ctx.error) return; if (ctx.error) return;
@@ -564,6 +587,7 @@ function execFor(ctx, ast) {
if (ctx.error) return; if (ctx.error) return;
} }
} }
ctx.scopes.pop();
} }
function execWhile(ctx, ast) { function execWhile(ctx, ast) {
@@ -613,6 +637,8 @@ function execVarAssignement(ctx, ast) {
if ((typeof(num) != "object")||(num == null)) return error(ctx, ast, "Variable not defined"); if ((typeof(num) != "object")||(num == null)) return error(ctx, ast, "Variable not defined");
if (num.type == "COMPONENT") return execInstantiateComponet(ctx, v, ast.values[1]); if (num.type == "COMPONENT") return execInstantiateComponet(ctx, v, ast.values[1]);
if (ctx.error) return;
// if (num.type == "SIGNAL") return error(ctx, ast, "Cannot assign to a signal with `=` use <-- or <== ops");
const res = exec(ctx, ast.values[1]); const res = exec(ctx, ast.values[1]);
if (ctx.error) return; if (ctx.error) return;
@@ -722,6 +748,34 @@ function execBAnd(ctx, ast) {
}; };
} }
function execAnd(ctx, ast) {
const a = exec(ctx, ast.values[0]);
if (ctx.error) return;
if (a.type != "NUMBER") return { type: "NUMBER" };
const b = exec(ctx, ast.values[1]);
if (ctx.error) return;
if (b.type != "NUMBER") return { type: "NUMBER" };
if (!a.value || !b.value) return { type: "NUMBER" };
return {
type: "NUMBER",
value: (a.value.neq(0) && b.value.neq(0)) ? bigInt(1) : bigInt(0)
};
}
function execOr(ctx, ast) {
const a = exec(ctx, ast.values[0]);
if (ctx.error) return;
if (a.type != "NUMBER") return { type: "NUMBER" };
const b = exec(ctx, ast.values[1]);
if (ctx.error) return;
if (b.type != "NUMBER") return { type: "NUMBER" };
if (!a.value || !b.value) return { type: "NUMBER" };
return {
type: "NUMBER",
value: (a.value.neq(0) || b.value.neq(0)) ? bigInt(1) : bigInt(0)
};
}
function execShl(ctx, ast) { function execShl(ctx, ast) {
const a = exec(ctx, ast.values[0]); const a = exec(ctx, ast.values[0]);
if (ctx.error) return; if (ctx.error) return;
@@ -796,6 +850,21 @@ function execDiv(ctx, ast) {
}; };
} }
function execIDiv(ctx, ast) {
const a = exec(ctx, ast.values[0]);
if (ctx.error) return;
if (a.type != "NUMBER") return { type: "NUMBER" };
const b = exec(ctx, ast.values[1]);
if (ctx.error) return;
if (b.type != "NUMBER") return { type: "NUMBER" };
if (!a.value || !b.value) return { type: "NUMBER" };
if (b.value.isZero()) return error(ctx, ast, "Division by zero");
return {
type: "NUMBER",
value: a.value.divide(b.value)
};
}
function execAdd(ctx, ast) { function execAdd(ctx, ast) {
const a = exec(ctx, ast.values[0]); const a = exec(ctx, ast.values[0]);
if (ctx.error) return; if (ctx.error) return;
@@ -872,6 +941,23 @@ function execPlusPlusLeft(ctx, ast) {
return resAfter; return resAfter;
} }
function execMinusMinusRight(ctx, ast) {
const resBefore = exec(ctx, ast.values[0]);
if (ctx.error) return;
const resAfter = execSub(ctx,{ values: [ast.values[0], {type: "NUMBER", value: bigInt(1)}] } );
if (ctx.error) return;
execVarAssignement(ctx, { values: [ast.values[0], resAfter] });
return resBefore;
}
function execMinusMinusLeft(ctx, ast) {
if (ctx.error) return;
const resAfter = execSub(ctx,{ values: [ast.values[0], {type: "NUMBER", value: bigInt(1)}] } );
if (ctx.error) return;
execVarAssignement(ctx, { values: [ast.values[0], resAfter] });
return resAfter;
}
function execTerCon(ctx, ast) { function execTerCon(ctx, ast) {
const cond = exec(ctx, ast.values[0]); const cond = exec(ctx, ast.values[0]);
if (ctx.error) return; if (ctx.error) return;

70
src/genOptCode.js Normal file
View File

@@ -0,0 +1,70 @@
module.exports = genOpt;
function genOpt(ctx, ast) {
if (ast.type == "OP") {
if (ast.op == "=") {
return genOptVarAssignement(ctx, ast);
} else {
error(ctx, ast, "GENOPT -> Invalid operation: " + ast.op);
}
} else if (ast.type == "TEMPLATEDEF") {
return genOptTemplateDef(ctx, ast);
} else {
error(ctx, ast, "GENOPT -> Invalid AST node type: " + ast.type);
}
}
function error(ctx, ast, errStr) {
ctx.error = {
pos: {
first_line: ast.first_line,
first_column: ast.first_column,
last_line: ast.last_line,
last_column: ast.last_column
},
errStr: errStr,
errFile: ctx.fileName,
ast: ast
};
}
function genOptTemplateDef(ctx, ast) {
if (ctx.templates[ast.name]) {
return error(ctx, ast, "Template name already exists: "+ast.name);
}
ctx.templates[ast.name] = {
type: "TEMPLATE",
params: ast.params,
block: ast.block,
fileName: ctx.fileName,
filePath: ctx.filePath
};
}
function genOptVarAssignement(ctx, ast) {
let varName;
if (ast.values[0].type == "DECLARE") {
varName = genOptCode(ctx, ast.values[0]);
if (ctx.error) return;
} else {
varName = ast.values[0];
}
const varContent = getScope(ctx, varName.name, varName.selectors);
if (ctx.error) return;
if ((typeof(varContent) != "object")||(varContent == null)) return error(ctx, ast, "Variable not defined");
if (varContent.type == "COMPONENT") return genOptInstantiateComponet(ctx, varName, ast.values[1]);
if (varContent.type == "SIGNAL") return error(ctx, ast, "Cannot assig to a signal with `=` use <-- or <== ops");
const res = genOpt(ctx, ast.values[1]);
if (ctx.error) return;
setScope(ctx, varName.name, varName.selectors, res);
return v;
}

View File

@@ -63,12 +63,22 @@ function gen(ctx, ast) {
return genPlusPlusRight(ctx, ast); return genPlusPlusRight(ctx, ast);
} else if (ast.op == "PLUSPLUSLEFT") { } else if (ast.op == "PLUSPLUSLEFT") {
return genPlusPlusLeft(ctx, ast); return genPlusPlusLeft(ctx, ast);
} else if (ast.op == "MINUSMINUSRIGHT") {
return genMinusMinusRight(ctx, ast);
} else if (ast.op == "MINUSMINUSLEFT") {
return genMinusMinusLeft(ctx, ast);
} else if (ast.op == "**") { } else if (ast.op == "**") {
return genExp(ctx, ast); return genExp(ctx, ast);
} else if (ast.op == "/") { } else if (ast.op == "/") {
return genDiv(ctx, ast); return genDiv(ctx, ast);
} else if (ast.op == "\\") {
return genIDiv(ctx, ast);
} else if (ast.op == "&") { } else if (ast.op == "&") {
return genBAnd(ctx, ast); return genBAnd(ctx, ast);
} else if (ast.op == "&&") {
return genAnd(ctx, ast);
} else if (ast.op == "||") {
return genOr(ctx, ast);
} else if (ast.op == "<<") { } else if (ast.op == "<<") {
return genShl(ctx, ast); return genShl(ctx, ast);
} else if (ast.op == ">>") { } else if (ast.op == ">>") {
@@ -106,6 +116,8 @@ function gen(ctx, ast) {
return genFunctionCall(ctx, ast); return genFunctionCall(ctx, ast);
} else if (ast.type == "BLOCK") { } else if (ast.type == "BLOCK") {
return genBlock(ctx, ast); return genBlock(ctx, ast);
} else if (ast.type == "COMPUTE") {
return genCompute(ctx, ast);
} else if (ast.type == "FOR") { } else if (ast.type == "FOR") {
return genFor(ctx, ast); return genFor(ctx, ast);
} else if (ast.type == "WHILE") { } else if (ast.type == "WHILE") {
@@ -137,7 +149,8 @@ function error(ctx, ast, errStr) {
last_column: ast.last_column last_column: ast.last_column
}, },
errStr: errStr, errStr: errStr,
ast: ast ast: ast,
message: errStr
}; };
} }
@@ -224,6 +237,7 @@ function genFunctionDef(ctx, ast) {
} }
function genFor(ctx, ast) { function genFor(ctx, ast) {
ctx.scopes.push({});
const init = gen(ctx, ast.init); const init = gen(ctx, ast.init);
if (ctx.error) return; if (ctx.error) return;
const condition = gen(ctx, ast.condition); const condition = gen(ctx, ast.condition);
@@ -232,7 +246,8 @@ function genFor(ctx, ast) {
if (ctx.error) return; if (ctx.error) return;
const body = gen(ctx, ast.body); const body = gen(ctx, ast.body);
if (ctx.error) return; if (ctx.error) return;
return `for (${init};${condition};${step}) { \n${body}\n }\n`; ctx.scopes.pop();
return `for (${init};bigInt(${condition}).neq(bigInt(0));${step}) { \n${body}\n }\n`;
} }
function genWhile(ctx, ast) { function genWhile(ctx, ast) {
@@ -240,7 +255,13 @@ function genWhile(ctx, ast) {
if (ctx.error) return; if (ctx.error) return;
const body = gen(ctx, ast.body); const body = gen(ctx, ast.body);
if (ctx.error) return; if (ctx.error) return;
return `while (${condition}) {\n${body}\n}\n`; return `while (bigInt(${condition}).neq(bigInt(0))) {\n${body}\n}\n`;
}
function genCompute(ctx, ast) {
const body = gen(ctx, ast.body);
if (ctx.error) return;
return `{\n${body}\n}\n`;
} }
function genIf(ctx, ast) { function genIf(ctx, ast) {
@@ -251,9 +272,9 @@ function genIf(ctx, ast) {
if (ast.else) { if (ast.else) {
const elseBody = gen(ctx, ast.else); const elseBody = gen(ctx, ast.else);
if (ctx.error) return; if (ctx.error) return;
return `if (${condition}) {\n${thenBody}\n} else {\n${elseBody}\n}\n`; return `if (bigInt(${condition}).neq(bigInt(0))) {\n${thenBody}\n} else {\n${elseBody}\n}\n`;
} else { } else {
return `if (${condition}) {\n${thenBody}\n}\n`; return `if (bigInt(${condition}).neq(bigInt(0))) {\n${thenBody}\n}\n`;
} }
} }
@@ -424,6 +445,14 @@ function genPlusPlusLeft(ctx, ast) {
return genVarAssignement(ctx, {values: [ast.values[0], {type: "OP", op: "+", values: [ast.values[0], {type: "NUMBER", value: bigInt(1)}]}]}); return genVarAssignement(ctx, {values: [ast.values[0], {type: "OP", op: "+", values: [ast.values[0], {type: "NUMBER", value: bigInt(1)}]}]});
} }
function genMinusMinusRight(ctx, ast) {
return `(${genVarAssignement(ctx, {values: [ast.values[0], {type: "OP", op: "-", values: [ast.values[0], {type: "NUMBER", value: bigInt(1)}]}]})}).add(__P__).sub(bigInt(1)).mod(__P__)`;
}
function genMinusMinusLeft(ctx, ast) {
return genVarAssignement(ctx, {values: [ast.values[0], {type: "OP", op: "-", values: [ast.values[0], {type: "NUMBER", value: bigInt(1)}]}]});
}
function genAdd(ctx, ast) { function genAdd(ctx, ast) {
const a = gen(ctx, ast.values[0]); const a = gen(ctx, ast.values[0]);
if (ctx.error) return; if (ctx.error) return;
@@ -457,6 +486,15 @@ function genDiv(ctx, ast) {
return `bigInt(${a}).mul( bigInt(${b}).inverse(__P__) ).mod(__P__)`; return `bigInt(${a}).mul( bigInt(${b}).inverse(__P__) ).mod(__P__)`;
} }
function genIDiv(ctx, ast) {
const a = gen(ctx, ast.values[0]);
if (ctx.error) return;
const b = gen(ctx, ast.values[1]);
if (ctx.error) return;
return `bigInt(${a}).div( bigInt(${b}))`;
}
function genExp(ctx, ast) { function genExp(ctx, ast) {
const a = gen(ctx, ast.values[0]); const a = gen(ctx, ast.values[0]);
if (ctx.error) return; if (ctx.error) return;
@@ -473,6 +511,22 @@ function genBAnd(ctx, ast) {
return `bigInt(${a}).and(bigInt(${b})).and(__MASK__)`; return `bigInt(${a}).and(bigInt(${b})).and(__MASK__)`;
} }
function genAnd(ctx, ast) {
const a = gen(ctx, ast.values[0]);
if (ctx.error) return;
const b = gen(ctx, ast.values[1]);
if (ctx.error) return;
return `((bigInt(${a}).neq(bigInt(0)) && bigInt(${b}).neq(bigInt(0))) ? bigInt(1) : bigInt(0))`;
}
function genOr(ctx, ast) {
const a = gen(ctx, ast.values[0]);
if (ctx.error) return;
const b = gen(ctx, ast.values[1]);
if (ctx.error) return;
return `((bigInt(${a}).neq(bigInt(0)) || bigInt(${b}).neq(bigInt(0))) ? bigInt(1) : bigInt(0))`;
}
function genShl(ctx, ast) { function genShl(ctx, ast) {
const a = gen(ctx, ast.values[0]); const a = gen(ctx, ast.values[0]);
if (ctx.error) return; if (ctx.error) return;

View File

@@ -1,14 +1,62 @@
const chai = require("chai"); const chai = require("chai");
const path = require("path"); const path = require("path");
const snarkjs = require("snarkjs"); const snarkjs = require("snarkjs");
const crypto = require("crypto");
const bigInt = snarkjs.bigInt;
const compiler = require("../index.js"); const compiler = require("../index.js");
const assert = chai.assert; const assert = chai.assert;
async function assertThrowsAsync(fn, regExp) {
let f = () => {};
try {
await fn();
} catch(e) {
f = () => { throw e; };
} finally {
assert.throws(f, regExp);
}
}
describe("Sum test", () => { describe("Sum test", () => {
it("Should compile a code with an undefined if", async() => { it("Should compile a code with an undefined if", async () => {
await compiler(path.join(__dirname, "circuits", "undefinedif.circom")); await compiler(path.join(__dirname, "circuits", "undefinedif.circom"));
}); });
it("Should compile a code with vars inside a for", async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "forvariables.circom"));
const circuit = new snarkjs.Circuit(cirDef);
const witness = circuit.calculateWitness({ "in": 111});
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(114)));
assert(witness[2].equals(bigInt(111)));
});
it("Should compile a code with an undefined if", async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "mixvarsignal.circom"));
const circuit = new snarkjs.Circuit(cirDef);
const witness = circuit.calculateWitness({ "i": 111});
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(111*111)));
assert(witness[2].equals(bigInt(111)));
});
// it("Should assign signal ERROR", async () => {
// await assertThrowsAsync(async () => {
// await compiler(path.join(__dirname, "circuits", "assignsignal.circom"));
// }, /Cannot assign to a signal .*/);
// });
it("Should compile a code with compute", async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "compute.circom"));
const circuit = new snarkjs.Circuit(cirDef);
const witness = circuit.calculateWitness({ "x": 6});
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(37)));
assert(witness[2].equals(bigInt(6)));
});
}); });

View File

@@ -0,0 +1,7 @@
template A() {
signal output out;
out = 3; // This is an error that compile should detect
}
component main = A();

View File

@@ -0,0 +1,17 @@
template X() {
signal input x;
signal output y;
signal x2;
signal x3;
var a;
compute {
a = (x*x*x+6)/x;
y <-- a;
}
x2 <== x*x;
x3 <== x2*x;
x*y === x3+6;
}
component main = X();

View File

@@ -1,18 +0,0 @@
include "../../circuits/sha256/constants.circom"
template A() {
signal input in;
component h0;
h0 = K(8);
var lc = 0;
var e = 1;
for (var i=0; i<32; i++) {
lc = lc + e*h0.out[i];
e *= 2;
}
lc === in;
}
component main = A();

View File

@@ -0,0 +1,12 @@
template A() {
signal a;
}
template B() {
component a[2] = A();
}
component main = B();

View File

@@ -0,0 +1,19 @@
template A() {
signal input in;
signal output out;
var acc = 0;
for (var i=0; i<3; i++) {
if (i==1) {
var accIn = 0;
for (var j=0; j<3; j++) {
accIn= accIn+1;
}
acc = acc + accIn;
}
}
out <== in + acc;
}
component main = A();

View File

@@ -1,4 +0,0 @@
include "../../circuits/comparators.circom";
component main = IsEqual();

View File

@@ -1,5 +0,0 @@
include "../../circuits/comparators.circom";
component main = IsZero();

View File

@@ -1,4 +0,0 @@
include "../../circuits/comparators.circom";
component main = LessThan(32);

View File

@@ -0,0 +1,14 @@
template X() {
signal input i;
signal output out;
var r = 0;
for (var n=0; n<i; n++) {
r++;
}
i === r;
out <== i*i;
}
component main = X();

File diff suppressed because it is too large Load Diff

View File

@@ -1,15 +0,0 @@
include "../../circuits/sha256/sha256_2.circom";
template Main() {
signal private input a;
signal private input b;
signal output out;
component sha256_2 = Sha256_2();
sha256_2.a <== a;
sha256_2.b <== b;
out <== sha256_2.out;
}
component main = Main();

View File

@@ -1,26 +0,0 @@
include "../../circuits/bitify.circom"
include "../../circuits/binsum.circom"
template A() {
signal private input a;
signal input b;
signal output out;
component n2ba = Num2Bits(32);
component n2bb = Num2Bits(32);
component sum = BinSum(32,2);
component b2n = Bits2Num(32);
n2ba.in <== a;
n2bb.in <== b;
for (var i=0; i<32; i++) {
sum.in[0][i] <== n2ba.out[i];
sum.in[1][i] <== n2bb.out[i];
b2n.in[i] <== sum.out[i];
}
out <== b2n.out;
}
component main = A();

View File

@@ -1,77 +0,0 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const crypto = require("crypto");
const compiler = require("../index.js");
const assert = chai.assert;
describe("Sum test", () => {
it("Should create a iszero circuit", async() => {
const cirDef = await compiler(path.join(__dirname, "circuits", "iszero.circom"));
const circuit = new snarkjs.Circuit(cirDef);
let witness;
witness = circuit.calculateWitness({ "in": 111});
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
witness = circuit.calculateWitness({ "in": 0 });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(1)));
});
it("Should create a isequal circuit", async() => {
const cirDef = await compiler(path.join(__dirname, "circuits", "isequal.circom"));
const circuit = new snarkjs.Circuit(cirDef);
let witness;
witness = circuit.calculateWitness({ "in[0]": "111", "in[1]": "222" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
witness = circuit.calculateWitness({ "in[0]": "444", "in[1]": "444" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(1)));
});
it("Should create a comparison", async() => {
const cirDef = await compiler(path.join(__dirname, "circuits", "lessthan.circom"));
const circuit = new snarkjs.Circuit(cirDef);
let witness;
witness = circuit.calculateWitness({ "in[0]": "333", "in[1]": "444" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(1)));
witness = circuit.calculateWitness({ "in[0]": "1", "in[1]": "1" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
witness = circuit.calculateWitness({ "in[0]": "661", "in[1]": "660" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
witness = circuit.calculateWitness({ "in[0]": "0", "in[1]": "1" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(1)));
witness = circuit.calculateWitness({ "in[0]": "0", "in[1]": "444" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(1)));
witness = circuit.calculateWitness({ "in[0]": "1", "in[1]": "0" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
witness = circuit.calculateWitness({ "in[0]": "555", "in[1]": "0" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
witness = circuit.calculateWitness({ "in[0]": "0", "in[1]": "0" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
});
});

View File

@@ -1,22 +0,0 @@
const snarkjs = require("snarkjs");
const bigInt = snarkjs.bigInt;
module.exports = function hexBits(cir, witness, sig, nBits) {
let v = bigInt(0);
for (let i=nBits-1; i>=0; i--) {
v = v.shiftLeft(1);
const name = sig+"["+i+"]";
const idx = cir.getSignalIdx(name);
const vbit = bigInt(witness[idx].toString());
if (vbit.equals(bigInt(1))) {
v = v.add(bigInt(1));
} else if (vbit.equals(bigInt(0))) {
v;
} else {
console.log("Not Binary: "+name);
}
}
return v.toString(16);
};

View File

@@ -1,178 +0,0 @@
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* SHA-256 (FIPS 180-4) implementation in JavaScript (c) Chris Veness 2002-2017 */
/* MIT Licence */
/* www.movable-type.co.uk/scripts/sha256.html */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
'use strict';
/**
* SHA-256 hash function reference implementation.
*
* This is an annotated direct implementation of FIPS 180-4, without any optimisations. It is
* intended to aid understanding of the algorithm rather than for production use.
*
* While it could be used where performance is not critical, I would recommend using the Web
* Cryptography API (developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest) for the browser,
* or the crypto library (nodejs.org/api/crypto.html#crypto_class_hash) in Node.js.
*
* See csrc.nist.gov/groups/ST/toolkit/secure_hashing.html
* csrc.nist.gov/groups/ST/toolkit/examples.html
*/
class Sha256 {
/**
* Generates SHA-256 hash of string.
*
* @param {string} msg - (Unicode) string to be hashed.
* @param {Object} [options]
* @param {string} [options.msgFormat=string] - Message format: 'string' for JavaScript string
* (gets converted to UTF-8 for hashing); 'hex-bytes' for string of hex bytes ('616263' ≡ 'abc') .
* @param {string} [options.outFormat=hex] - Output format: 'hex' for string of contiguous
* hex bytes; 'hex-w' for grouping hex bytes into groups of (4 byte / 8 character) words.
* @returns {string} Hash of msg as hex character string.
*/
static hash(msg, options) {
const defaults = { msgFormat: 'string', outFormat: 'hex' };
const opt = Object.assign(defaults, options);
// note use throughout this routine of 'n >>> 0' to coerce Number 'n' to unsigned 32-bit integer
switch (opt.msgFormat) {
default: // default is to convert string to UTF-8, as SHA only deals with byte-streams
case 'string': msg = utf8Encode(msg); break;
case 'hex-bytes':msg = hexBytesToString(msg); break; // mostly for running tests
}
// constants [§4.2.2]
const K = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ];
// initial hash value [§5.3.3]
const H = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ];
// PREPROCESSING [§6.2.1]
msg += String.fromCharCode(0x80); // add trailing '1' bit (+ 0's padding) to string [§5.1.1]
// convert string msg into 512-bit blocks (array of 16 32-bit integers) [§5.2.1]
const l = msg.length/4 + 2; // length (in 32-bit integers) of msg + 1 + appended length
const N = Math.ceil(l/16); // number of 16-integer (512-bit) blocks required to hold 'l' ints
const M = new Array(N); // message M is N×16 array of 32-bit integers
for (let i=0; i<N; i++) {
M[i] = new Array(16);
for (let j=0; j<16; j++) { // encode 4 chars per integer (64 per block), big-endian encoding
M[i][j] = (msg.charCodeAt(i*64+j*4+0)<<24) | (msg.charCodeAt(i*64+j*4+1)<<16)
| (msg.charCodeAt(i*64+j*4+2)<< 8) | (msg.charCodeAt(i*64+j*4+3)<< 0);
} // note running off the end of msg is ok 'cos bitwise ops on NaN return 0
}
// add length (in bits) into final pair of 32-bit integers (big-endian) [§5.1.1]
// note: most significant word would be (len-1)*8 >>> 32, but since JS converts
// bitwise-op args to 32 bits, we need to simulate this by arithmetic operators
const lenHi = ((msg.length-1)*8) / Math.pow(2, 32);
const lenLo = ((msg.length-1)*8) >>> 0;
M[N-1][14] = Math.floor(lenHi);
M[N-1][15] = lenLo;
// HASH COMPUTATION [§6.2.2]
for (let i=0; i<N; i++) {
const W = new Array(64);
// 1 - prepare message schedule 'W'
for (let t=0; t<16; t++) W[t] = M[i][t];
for (let t=16; t<64; t++) {
W[t] = (Sha256.σ1(W[t-2]) + W[t-7] + Sha256.σ0(W[t-15]) + W[t-16]) >>> 0;
}
// 2 - initialise working variables a, b, c, d, e, f, g, h with previous hash value
let a = H[0], b = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];
// 3 - main loop (note '>>> 0' for 'addition modulo 2^32')
for (let t=0; t<64; t++) {
const T1 = h + Sha256.Σ1(e) + Sha256.Ch(e, f, g) + K[t] + W[t];
const T2 = Sha256.Σ0(a) + Sha256.Maj(a, b, c);
h = g;
g = f;
f = e;
e = (d + T1) >>> 0;
d = c;
c = b;
b = a;
a = (T1 + T2) >>> 0;
}
// 4 - compute the new intermediate hash value (note '>>> 0' for 'addition modulo 2^32')
H[0] = (H[0]+a) >>> 0;
H[1] = (H[1]+b) >>> 0;
H[2] = (H[2]+c) >>> 0;
H[3] = (H[3]+d) >>> 0;
H[4] = (H[4]+e) >>> 0;
H[5] = (H[5]+f) >>> 0;
H[6] = (H[6]+g) >>> 0;
H[7] = (H[7]+h) >>> 0;
}
// convert H0..H7 to hex strings (with leading zeros)
for (let h=0; h<H.length; h++) H[h] = ('00000000'+H[h].toString(16)).slice(-8);
// concatenate H0..H7, with separator if required
const separator = opt.outFormat=='hex-w' ? ' ' : '';
return H.join(separator);
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
function utf8Encode(str) {
try {
return new TextEncoder().encode(str, 'utf-8').reduce((prev, curr) => prev + String.fromCharCode(curr), '');
} catch (e) { // no TextEncoder available?
return unescape(encodeURIComponent(str)); // monsur.hossa.in/2012/07/20/utf-8-in-javascript.html
}
}
function hexBytesToString(hexStr) { // convert string of hex numbers to a string of chars (eg '616263' -> 'abc').
const str = hexStr.replace(' ', ''); // allow space-separated groups
return str=='' ? '' : str.match(/.{2}/g).map(byte => String.fromCharCode(parseInt(byte, 16))).join('');
}
}
/**
* Rotates right (circular right shift) value x by n positions [§3.2.4].
* @private
*/
static ROTR(n, x) {
return (x >>> n) | (x << (32-n));
}
/**
* Logical functions [§4.1.2].
* @private
*/
static Σ0(x) { return Sha256.ROTR(2, x) ^ Sha256.ROTR(13, x) ^ Sha256.ROTR(22, x); }
static Σ1(x) { return Sha256.ROTR(6, x) ^ Sha256.ROTR(11, x) ^ Sha256.ROTR(25, x); }
static σ0(x) { return Sha256.ROTR(7, x) ^ Sha256.ROTR(18, x) ^ (x>>>3); }
static σ1(x) { return Sha256.ROTR(17, x) ^ Sha256.ROTR(19, x) ^ (x>>>10); }
static Ch(x, y, z) { return (x & y) ^ (~x & z); } // 'choice'
static Maj(x, y, z) { return (x & y) ^ (x & z) ^ (y & z); } // 'majority'
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
if (typeof module != 'undefined' && module.exports) module.exports = Sha256; // ≡ export default Sha256

View File

@@ -1,42 +0,0 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const crypto = require("crypto");
const compiler = require("../index.js");
const assert = chai.assert;
const sha256 = require("./helpers/sha256");
// const printSignal = require("./helpers/printsignal");
describe("SHA256 test", () => {
it("Should calculate a hash", async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "sha256_2_test.circom"));
const circuit = new snarkjs.Circuit(cirDef);
console.log("Vars: "+circuit.nVars);
console.log("Constraints: "+circuit.nConstraints);
const witness = circuit.calculateWitness({ "a": "1", "b": "2" });
const b = new Buffer.alloc(54);
b[26] = 1;
b[53] = 2;
const hash = crypto.createHash("sha256")
.update(b)
.digest("hex");
const r = "0x" + hash.slice(10);
const hash2 = sha256.hash(b.toString("hex"), {msgFormat: "hex-bytes"});
assert.equal(hash, hash2);
assert(witness[1].equals(snarkjs.bigInt(r)));
}).timeout(1000000);
});

View File

@@ -1,35 +0,0 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const crypto = require("crypto");
const compiler = require("../index.js");
const assert = chai.assert;
describe("Sum test", () => {
it("Should create a constant circuit", async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "constants_test.circom"));
assert.equal(cirDef.nVars, 2);
const circuit = new snarkjs.Circuit(cirDef);
const witness = circuit.calculateWitness({ "in": "0xd807aa98" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt("0xd807aa98")));
});
it("Should create a sum circuit", async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "sum_test.circom"));
assert.equal(cirDef.nVars, 101);
const circuit = new snarkjs.Circuit(cirDef);
const witness = circuit.calculateWitness({ "a": "111", "b": "222" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt("333")));
});
});