Compare commits

...

56 Commits

Author SHA1 Message Date
Jordi Baylina
6df6e9cb1c 0.1.2 2020-03-31 15:38:46 +02:00
Jordi Baylina
9c68d4a363 Exporting buffer to int 2020-03-31 15:38:37 +02:00
Jordi Baylina
57be559c44 0.1.1 2020-03-26 22:49:49 +01:00
Jordi Baylina
7bf8325662 deps 2020-03-26 22:49:31 +01:00
Jordi Baylina
899d15f0c2 0.1.0 2020-03-26 19:58:53 +01:00
Jordi Baylina
0bf26ea5ec Merge branch 'c_build' 2020-03-26 19:52:34 +01:00
Jordi Baylina
e240605642 pre 0.5 all working 2020-03-26 19:24:20 +01:00
Jordi Baylina
273ab79665 Negative numbers and fix in comparator 2020-03-16 20:41:11 +01:00
Jordi Baylina
a851d08a46 0.0.21 2020-02-25 05:42:31 -08:00
Jordi Baylina
19bbada388 Poseidon for t=3 2020-02-25 05:41:51 -08:00
Jordi Baylina
cf6d1f0bb1 Test name changed on comparators 2020-02-04 19:19:11 +01:00
Jordi Baylina
2f28fc7002 remove pows and shifts for optimization 2020-01-23 07:23:17 +07:00
Jordi Baylina
4f11565ca4 Adapted circuits to the construction fase refactorization 2019-12-23 19:36:26 +01:00
Jordi Baylina
756f1f51e5 Multithread 2019-12-20 21:59:58 +01:00
Jordi Baylina
bc0fb60f89 SMT test title better explained 2019-12-17 17:12:29 +01:00
Jordi Baylina
7a6b0eda6e All testst finished with c_build 2019-12-16 21:35:52 +01:00
Jordi Baylina
e32460efe1 All tests working 2019-12-14 20:32:45 +01:00
Jordi Baylina
a8107abbe9 pedersen2 adapted 2019-12-13 19:05:20 +01:00
Jordi Baylina
4117ebc64a pedersen working 2019-12-13 18:35:29 +01:00
Jordi Baylina
b4cd3889b6 babyjub.js adapted 2019-12-12 19:46:07 +01:00
Jordi Baylina
30c6cf55b9 Alias Check and Babyjub adapted 2019-12-12 16:49:58 +01:00
Jordi Baylina
d5bca9feb6 sha256 tests updated to c 2019-12-12 13:04:02 +01:00
Jordi Baylina
bdfb0fb928 clean sha256 tests 2019-12-11 21:55:51 +01:00
Jordi Baylina
8bd0fac913 sha256 testing 2019-12-11 21:41:15 +01:00
Jordi Baylina
9941aac2f2 Fix sha256 last 448 test 2019-12-11 06:55:23 +01:00
Jordi Baylina
3c2b566e68 0.0.20 2019-12-04 21:57:32 +01:00
Jordi Baylina
15eadfe50c Merge branch 'master' of github.com:iden3/circomlib 2019-12-04 21:57:08 +01:00
Jordi Baylina
a1d4d1dca7 Convert constant components to functions 2019-12-04 21:57:02 +01:00
Jordi Baylina
d6e6a3b3f4 Fix assigning to signal 2019-12-03 19:16:19 +01:00
arnau
e3eb834322 Merge pull request #23 from kobigurk/fix/mimcsponge_round_constants
MiMCSponge: makes first and last round constants always zero
2019-10-12 14:03:37 +02:00
Kobi Gurkan
01a5530213 MiMCSponge: makes first and last round constants always zero 2019-10-04 17:39:53 +03:00
Jordi Baylina
50a725c174 0.0.19 2019-10-02 09:35:06 +02:00
Jordi Baylina
c4ce4cd946 multiget 2019-10-02 09:34:49 +02:00
Jordi Baylina
5bf52cda57 Merge pull request #20 from bellesmarta/master
Updated README files
2019-09-23 14:58:24 +02:00
Jordi Baylina
95abdd06d5 0.0.18 2019-09-17 07:57:45 +02:00
Jordi Baylina
9f69fab7c6 Merge pull request #22 from kobigurk/fix/mimcsponge_unconstrained
mimcsponge: fixes assignment to outs[0]
2019-09-17 08:55:22 +03:00
Kobi Gurkan
109cdf4056 mimcsponge: fixes assignment to outs[0] 2019-09-17 08:53:02 +03:00
Jordi Baylina
79d30349b4 0.0.17 2019-09-15 10:52:50 +02:00
Jordi Baylina
e3cd0e5aa7 Dependencies and publish smt 2019-09-15 10:52:18 +02:00
Jordi Baylina
86e970b888 0.0.16 2019-09-07 20:23:18 +02:00
Jordi Baylina
29e162383d Allow full poseidnon fix handle enable in the sigposeidon 2019-09-07 20:22:44 +02:00
Marta Belles
97b870b725 Updated README files 2019-09-06 17:14:45 +02:00
Jordi Baylina
f9e0484663 0.0.15 2019-09-05 17:12:56 +02:00
Jordi Baylina
7bdb254f4f deps snarkjs 2019-09-05 17:12:47 +02:00
Jordi Baylina
024188b638 Support mutiply by point 0 in scalarmulany 2019-09-05 17:10:20 +02:00
Jordi Baylina
ebbeaebc73 Merge branch 'arnaucube-master' 2019-09-05 16:51:29 +02:00
Jordi Baylina
25f392c8ae sha256 with number of bits as a paramter 2019-09-05 16:41:58 +02:00
Jordi Baylina
52a1fb895d 0.0.14 2019-08-30 10:38:19 +02:00
Jordi Baylina
1621483d3b deps 2019-08-30 10:38:04 +02:00
arnaucube
ae362ec61b add tests for babyjub eddsa poseidon sign & verify 2019-08-29 17:44:44 +02:00
Jordi Baylina
425f50a9ed 0.0.13 2019-08-24 19:53:41 +02:00
Jordi Baylina
173c17dedc Change to a standard generator for Baby Jub 2019-08-03 12:46:21 +02:00
Jordi Baylina
23616427cd 0.0.12 2019-07-30 20:16:38 +02:00
Jordi Baylina
7c743659db Fix escalarfix 2019-07-30 20:16:06 +02:00
Jordi Baylina
f04a318800 0.0.11 2019-07-30 19:35:35 +02:00
Jordi Baylina
b15c7c8089 FIX: escalarmul fix 2019-07-30 19:35:19 +02:00
92 changed files with 6063 additions and 16132 deletions

View File

@@ -1,7 +1,4 @@
module.exports = {
"plugins": [
"mocha"
],
"env": {
"es6": true,
"node": true,
@@ -27,7 +24,6 @@ module.exports = {
"semi": [
"error",
"always"
],
"mocha/no-exclusive-tests": "error"
]
}
};

View File

@@ -1,4 +1,17 @@
# cirpedersen
# CircomLib
Pedersen Hash and Exponentiation circuits using Baby Jub Curve in circom language
## Description
- This repository contains a library of circuit templates.
- All files are copyrighted under 2018 0KIMS association and part of the free software [circom](https://github.com/iden3/circom) (Zero Knowledge Circuit Compiler).
## Organisation
This respository contains 5 folders:
- `circuits`: it contains the implementation of different cryptographic primitives in circom language.
- `calcpedersenbases`: set of functions in JavaScript used to find a set of points in [Baby Jubjub](https://github.com/barryWhiteHat/baby_jubjub) elliptic curve that serve as basis for the [Pedersen Hash](https://github.com/zcash/zcash/issues/2234).
- `doc`: it contains some circuit schemes in ASCII (must be opened with Monodraw, an ASCII art editor for Mac).
- `src`: it contains similar implementation of circuits in JavaScript.
- `test`: tests.
A description of the specific circuit templates for the `circuit` folder will be soon updated.

View File

@@ -64,8 +64,8 @@ function generatePoint(S) {
const g = [
bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475")];
bigInt("5299619240641551281634865583518297030282874472190772894086521144482721001553"),
bigInt("16950150798460657717958625567821834550301663161624707787222815936182638968203")];
// Sanity check
if (!babyJub.inCurve(g)) {

View File

@@ -1,3 +1,19 @@
# CircomLib/Circuits
## Description
- This folder contains circuit templates for standard operations and many cryptographic primitives.
- Below you can find specifications of each function. In the representation of elements, there are three tyes:
- Binary
- String
- Field element (the field is specified in each case. We consider 2 possible fields: Fp and Fr, where p... and r... .)
## Table of Contents
[TOC]
## Jordi
* compconstant - Returns 1 if `in` (expanded to binary array) > `ct`
* aliascheck - check if `in` (expanded to binary array) oveflowed its 254 bits (<= -1)
* babyjub - twisted Edwards curve 168700.x^2 + y^2 = 1 + 168696.x^2.y^2
@@ -11,4 +27,804 @@
* zcash/zcash#2233
* smt - Sparse Merkle Tree
* https://ethresear.ch/t/optimizing-sparse-merkle-trees/3751
* montgomery https://en.wikipedia.org/wiki/Montgomery_curve
* montgomery https://en.wikipedia.org/wiki/Montgomery_curve
## Circuits
### sha256
Folder containing the implementation of sha256 hash circuit.
### smt
Folder containing the circuit implementation of Sparse Merkle Trees.
### aliascheck
- `AliasCheck()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### babyjub
Arithmetic on [Baby Jubjub elliptic curve](https://github.com/barryWhiteHat/baby_jubjub) in twisted Edwards form. (TODO: Expose here the characteristics of the curve?)
- `BabyAdd()`
- DESCRIPTION
It adds two points on the Baby Jubjub curve. More specifically, given two points P1 = (`x1`, `y1`) and P2 = (`x2`, `y2`) it returns a point P3 = (`xout`, `yout`) such that
(`xout`, `yout`) = (`x1`,`y1`) + (`x2`,`y2`)
= ((`x1y2`+`y1x2`)/(1+`dx1x2y1y2`)),(`y1y2`-`ax1x2`)/(1-`dx1x2y1y2`))
- SCHEMA
```
var a var d
| |
| |
______v_________v_______
input x1 ----> | |
input y1 ----> | BabyAdd() | ----> output xout
input x2 ----> | | ----> output yout
input y2 ----> |________________________|
```
- INPUTS
| Input | Representation | Description | |
| ------------- | ------------- | ------------- | ------------- |
| `x1` | Bigint | Field element of Fp | First coordinate of a point (x1, y1) on E. |
| `y1` | Bigint | Field element of Fp | Second coordinate of a point (x1, y1) on E. |
| `x2` | Bigint | Field element of Fp | First coordinate of a point (x2, y2) on E. |
| `y2` | Bigint | Field element of Fp | Second coordinate of a point (x2, y2) on E. |
Requirement: at least `x1`!=`x2` or `y1`!=`y2`.
- OUTPUT
| Input | Representation | Description | |
| ------------- | ------------- | ------------- | ------------- |
| `xout` | Bigint | Field element of Fp | First coordinate of the addition point (xout, yout) = (x1, y1) + (x2, y2). |
| `yout` | Bigint | Field element of Fp | Second coordinate of the addition point (xout, yout) = (x1, y1) + (x2, y2). |
- BENCHMARKS (constraints)
- EXAMPLE
- `BabyDbl()`
- DESCRIPTION : doubles a point (`xout`,`yout`) = 2*(`x`,`y`).
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `BabyCheck()`
- DESCRIPTION : checks if a given point is in the curve.
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `BabyPbk()`
- DESCRIPTION: : given a private key, it returns the associated public key.
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### binsub
- `BinSub(n)`
- DESCRIPTION: binary substraction.
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### binsum
- `nbits(a)`
- DESCRIPTION : binary sum.
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `BinSum(n, ops)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### bitify
- `Num2Bits()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Num2Bits_strict()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Bits2Num()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Bits2Num_strict()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Num2BitsNeg()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### comparators
- `IsZero() `
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `IsEqual()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `ForceEqualIfEnabled()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `LessThan()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `GreaterThan()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `GreaterEqThan()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### compconstant
- `CompConstant(ct)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### eddsa
Edwards Digital Signature Algorithm in Baby Jubjbub (link a eddsa)
- `EdDSAVerifier(n)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### eddsamimc
- `EdDSAMiMCVerifier()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### eddsamimcsponge
- `EdDSAMiMCSpongeVerifier()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### eddsaposeidon
- `EdDSAPoseidonVerifier()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### escalarmul
- `EscalarMulWindow(base, k)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `EscalarMul(n, base)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### escalarmulany
- `Multiplexor2()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `BitElementMulAny()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `SegmentMulAny(n)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `EscalarMulAny(n)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### escalarmulfix
- `WindowMulFix()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `SegmentMulFix(nWindows)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `EscalarMulFix(n, BASE)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### escalarmulw4table
- `pointAdd`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `EscalarMulW4Table`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### gates
- `XOR`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `AND`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `OR`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `NOT`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `NAND`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `NOR`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `MultiAND`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### mimc
Implementation of MiMC-7 hash in Fp being... (link to description of the hash)
- `MiMC7(nrounds)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `MultiMiMC7(nInputs, nRounds)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### mimcsponge
- `MiMCSponge(nInputs, nRounds, nOutputs)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `MiMCFeistel(nrounds)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### montgomery
- `Edwards2Montgomery()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Montgomery2Edwards()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `MontgomeryAdd()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `MontgomeryDouble()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### multiplexer
- `log2(a)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `EscalarProduct(w)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Decoder(w)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Multiplexer(wIn, nIn)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### mux1
- `MultiMux1(n)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Mux1()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### mux2
- `MultiMux2(n)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Mux2()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### mux3
- `MultiMux3(n)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Mux3()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### mux4
- `MultiMux4(n)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Mux4()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### pedersen_old
Old version of the Pedersen hash (do not use any
more?).
### pedersen
- `Window4()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Segment(nWindows)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Pedersen(n)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### pointbits
- `sqrt(n)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Bits2Point()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Bits2Point_Strict()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Point2Bits`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Point2Bits_Strict`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### poseidon
Implementation of Poseidon hash function (LINK)
- `Sigma()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Ark(t, C)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Mix(t, M)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
- `Poseidon(nInputs, t, nRoundsF, nRoundsP)`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### sign
- `Sign()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE
### switcher
- `Switcher()`
- DESCRIPTION
- SCHEMA
- INPUT
- OUTPUT
- BENCHMARKS
- EXAMPLE

View File

@@ -87,9 +87,9 @@ template BabyPbk() {
signal output Ax;
signal output Ay;
var BASE8 = [
17777552123799933955779906779655732241715742912184938656739573121738514868268,
2626589144620713026669568689430873010625803728049924121243784502389097019475
var BASE8[2] = [
5299619240641551281634865583518297030282874472190772894086521144482721001553,
16950150798460657717958625567821834550301663161624707787222815936182638968203
];
component pvkBits = Num2Bits(253);

View File

@@ -48,12 +48,14 @@ template BinSub(n) {
var lin = 2**n;
var lout = 0;
for (var i=0; i<n; i++) {
var i;
for (i=0; i<n; i++) {
lin = lin + in[0][i]*(2**i);
lin = lin - in[1][i]*(2**i);
}
for (var i=0; i<n; i++) {
for (i=0; i<n; i++) {
out[i] <-- (lin >> i) & 1;
// Ensure out is binary

View File

@@ -72,19 +72,26 @@ template BinSum(n, ops) {
var k;
var j;
var e2;
e2 = 1;
for (k=0; k<n; k++) {
for (j=0; j<ops; j++) {
lin += in[j][k] * 2**k;
lin += in[j][k] * e2;
}
e2 = e2 + e2;
}
e2 = 1;
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;
lout += out[k] * e2;
e2 = e2+e2;
}
// Ensure the sum;

View File

@@ -26,10 +26,12 @@ template Num2Bits(n) {
signal output out[n];
var lc1=0;
var e2=1;
for (var i = 0; i<n; i++) {
out[i] <-- (in >> i) & 1;
out[i] * (out[i] -1 ) === 0;
lc1 += out[i] * 2**i;
lc1 += out[i] * e2;
e2 = e2+e2;
}
lc1 === in;
@@ -54,8 +56,10 @@ template Bits2Num(n) {
signal output out;
var lc1=0;
var e2 = 1;
for (var i = 0; i<n; i++) {
lc1 += in[i] * 2**i;
lc1 += in[i] * e2;
e2 = e2 + e2;
}
lc1 ==> out;

View File

@@ -46,12 +46,11 @@ template CompConstant(ct) {
slsb = in[i*2];
smsb = in[i*2+1];
if ((cmsb==0)&(clsb==0)) {
if ((cmsb==0)&&(clsb==0)) {
parts[i] <== -b*smsb*slsb + b*smsb + b*slsb;
} else if ((cmsb==0)&(clsb==1)) {
} else if ((cmsb==0)&&(clsb==1)) {
parts[i] <== a*smsb*slsb - a*slsb + b*smsb - a*smsb + a;
} else if ((cmsb==1)&(clsb==0)) {
} else if ((cmsb==1)&&(clsb==0)) {
parts[i] <== b*smsb*slsb - a*smsb + a;
} else {
parts[i] <== -a*smsb*slsb + a;

View File

@@ -122,9 +122,9 @@ template EdDSAVerifier(n) {
// Calculate left side of equation left = S*B8
var BASE8 = [
17777552123799933955779906779655732241715742912184938656739573121738514868268,
2626589144620713026669568689430873010625803728049924121243784502389097019475
var BASE8[2] = [
5299619240641551281634865583518297030282874472190772894086521144482721001553,
16950150798460657717958625567821834550301663161624707787222815936182638968203
];
component mulFix = EscalarMulFix(256, BASE8);
for (i=0; i<256; i++) {

View File

@@ -100,9 +100,9 @@ template EdDSAMiMCVerifier() {
// Calculate left side of equation left = S*B8
var BASE8 = [
17777552123799933955779906779655732241715742912184938656739573121738514868268,
2626589144620713026669568689430873010625803728049924121243784502389097019475
var BASE8[2] = [
5299619240641551281634865583518297030282874472190772894086521144482721001553,
16950150798460657717958625567821834550301663161624707787222815936182638968203
];
component mulFix = EscalarMulFix(253, BASE8);
for (i=0; i<253; i++) {

View File

@@ -100,9 +100,9 @@ template EdDSAMiMCSpongeVerifier() {
// Calculate left side of equation left = S*B8
var BASE8 = [
17777552123799933955779906779655732241715742912184938656739573121738514868268,
2626589144620713026669568689430873010625803728049924121243784502389097019475
var BASE8[2] = [
5299619240641551281634865583518297030282874472190772894086521144482721001553,
16950150798460657717958625567821834550301663161624707787222815936182638968203
];
component mulFix = EscalarMulFix(253, BASE8);
for (i=0; i<253; i++) {

View File

@@ -47,7 +47,7 @@ template EdDSAPoseidonVerifier() {
snum2bits.out[i] ==> compConstant.in[i];
}
compConstant.in[253] <== 0;
compConstant.out === 0;
compConstant.out*enabled === 0;
// Calculate the h = H(R,A, msg)
@@ -79,7 +79,7 @@ template EdDSAPoseidonVerifier() {
// We check that A is not zero.
component isZero = IsZero();
isZero.in <== dbl3.x;
isZero.out === 0;
isZero.out*enabled === 0;
component mulAny = EscalarMulAny(254);
for (i=0; i<254; i++) {
@@ -99,9 +99,9 @@ template EdDSAPoseidonVerifier() {
// Calculate left side of equation left = S*B8
var BASE8 = [
17777552123799933955779906779655732241715742912184938656739573121738514868268,
2626589144620713026669568689430873010625803728049924121243784502389097019475
var BASE8[2] = [
5299619240641551281634865583518297030282874472190772894086521144482721001553,
16950150798460657717958625567821834550301663161624707787222815936182638968203
];
component mulFix = EscalarMulFix(253, BASE8);
for (i=0; i<253; i++) {

View File

@@ -1,4 +1,4 @@
/*
/*
Copyright 2018 0KIMS association.
This file is part of circom (Zero Knowledge Circuit Compiler).
@@ -71,7 +71,7 @@ template EscalarMulWindow(base, k) {
signal input sel[4];
signal output out[2];
component table;
var table[16][2];
component mux;
component adder;
@@ -86,8 +86,8 @@ template EscalarMulWindow(base, k) {
}
for (i=0; i<16; i++) {
table.out[i][0] ==> mux.c[0][i];
table.out[i][1] ==> mux.c[1][i];
mux.c[0][i] <== table[i][0];
mux.c[1][i] <== table[i][1];
}
in[0] ==> adder.x1;

View File

@@ -19,6 +19,7 @@
include "montgomery.circom";
include "babyjub.circom";
include "comparators.circom";
template Multiplexor2() {
signal input sel;
@@ -138,6 +139,8 @@ template EscalarMulAny(n) {
component doublers[nsegments-1];
component m2e[nsegments-1];
component adders[nsegments-1];
component zeropoint = IsZero();
zeropoint.in <== p[0];
var s;
var i;
@@ -154,8 +157,9 @@ template EscalarMulAny(n) {
}
if (s==0) {
p[0] ==> segments[s].p[0];
p[1] ==> segments[s].p[1];
// force G8 point if input point is zero
segments[s].p[0] <== p[0] + (5299619240641551281634865583518297030282874472190772894086521144482721001553 - p[0])*zeropoint.out;
segments[s].p[1] <== p[1] + (16950150798460657717958625567821834550301663161624707787222815936182638968203 - p[1])*zeropoint.out;
} else {
doublers[s-1] = MontgomeryDouble();
m2e[s-1] = Montgomery2Edwards();
@@ -183,10 +187,10 @@ template EscalarMulAny(n) {
}
if (nsegments == 1) {
segments[0].out[0] ==> out[0];
segments[0].out[1] ==> out[1];
segments[0].out[0]*(1-zeropoint.out) ==> out[0];
segments[0].out[1]+(1-segments[0].out[1])*zeropoint.out ==> out[1];
} else {
adders[nsegments-2].xout ==> out[0];
adders[nsegments-2].yout ==> out[1];
adders[nsegments-2].xout*(1-zeropoint.out) ==> out[0];
adders[nsegments-2].yout+(1-adders[nsegments-2].yout)*zeropoint.out ==> out[1];
}
}

View File

@@ -28,6 +28,22 @@ include "babyjub.circom";
The result should be compensated.
*/
/*
The scalar is s = a0 + a1*2^3 + a2*2^6 + ...... + a81*2^243
First We calculate Q = B + 2^3*B + 2^6*B + ......... + 2^246*B
Then we calculate S1 = 2*2^246*B + (1 + a0)*B + (2^3 + a1)*B + .....+ (2^243 + a81)*B
And Finaly we compute the result: RES = SQ - Q
As you can see the input of the adders cannot be equal nor zero, except for the last
substraction that it's done in montgomery.
A good way to see it is that the accumulator input of the adder >= 2^247*B and the other input
is the output of the windows that it's going to be <= 2^246*B
*/
template WindowMulFix() {
signal input in[3];
signal input base[2];
@@ -140,54 +156,60 @@ template SegmentMulFix(nWindows) {
e2m.in[1] <== base[1];
component windows[nWindows];
component adders[nWindows-1];
component cadders[nWindows-1];
component adders[nWindows];
component cadders[nWindows];
// In the last step we add an extra doubler so that numbers do not match.
component dblLast = MontgomeryDouble();
for (i=0; i<nWindows; i++) {
windows[i] = WindowMulFix();
cadders[i] = MontgomeryAdd();
if (i==0) {
windows[i].base[0] <== e2m.out[0];
windows[i].base[1] <== e2m.out[1];
cadders[i].in1[0] <== e2m.out[0];
cadders[i].in1[1] <== e2m.out[1];
} else {
windows[i].base[0] <== windows[i-1].out8[0];
windows[i].base[1] <== windows[i-1].out8[1];
adders[i-1] = MontgomeryAdd();
cadders[i-1] = MontgomeryAdd();
if (i==1) {
adders[i-1].in1[0] <== windows[0].out[0];
adders[i-1].in1[1] <== windows[0].out[1];
cadders[i-1].in1[0] <== e2m.out[0];
cadders[i-1].in1[1] <== e2m.out[1];
} else {
adders[i-1].in1[0] <== adders[i-2].out[0];
adders[i-1].in1[1] <== adders[i-2].out[1];
cadders[i-1].in1[0] <== cadders[i-2].out[0];
cadders[i-1].in1[1] <== cadders[i-2].out[1];
}
adders[i-1].in2[0] <== windows[i].out[0];
adders[i-1].in2[1] <== windows[i].out[1];
cadders[i-1].in2[0] <== windows[i-1].out8[0];
cadders[i-1].in2[1] <== windows[i-1].out8[1];
cadders[i].in1[0] <== cadders[i-1].out[0];
cadders[i].in1[1] <== cadders[i-1].out[1];
}
for (j=0; j<3; j++) {
windows[i].in[j] <== e[3*i+j];
}
if (i<nWindows-1) {
cadders[i].in2[0] <== windows[i].out8[0];
cadders[i].in2[1] <== windows[i].out8[1];
} else {
dblLast.in[0] <== windows[i].out8[0];
dblLast.in[1] <== windows[i].out8[1];
cadders[i].in2[0] <== dblLast.out[0];
cadders[i].in2[1] <== dblLast.out[1];
}
}
for (i=0; i<nWindows; i++) {
adders[i] = MontgomeryAdd();
if (i==0) {
adders[i].in1[0] <== dblLast.out[0];
adders[i].in1[1] <== dblLast.out[1];
} else {
adders[i].in1[0] <== adders[i-1].out[0];
adders[i].in1[1] <== adders[i-1].out[1];
}
adders[i].in2[0] <== windows[i].out[0];
adders[i].in2[1] <== windows[i].out[1];
}
component m2e = Montgomery2Edwards();
component cm2e = Montgomery2Edwards();
if (nWindows > 1) {
m2e.in[0] <== adders[nWindows-2].out[0];
m2e.in[1] <== adders[nWindows-2].out[1];
cm2e.in[0] <== cadders[nWindows-2].out[0];
cm2e.in[1] <== cadders[nWindows-2].out[1];
} else {
m2e.in[0] <== windows[0].out[0];
m2e.in[1] <== windows[0].out[1];
cm2e.in[0] <== e2m.out[0];
cm2e.in[1] <== e2m.out[1];
}
m2e.in[0] <== adders[nWindows-1].out[0];
m2e.in[1] <== adders[nWindows-1].out[1];
cm2e.in[0] <== cadders[nWindows-1].out[0];
cm2e.in[1] <== cadders[nWindows-1].out[1];
component cAdd = BabyAdd();
cAdd.x1 <== m2e.out[0];
@@ -195,7 +217,6 @@ template SegmentMulFix(nWindows) {
cAdd.x2 <== -cm2e.out[0];
cAdd.y2 <== cm2e.out[1];
cAdd.xout ==> out[0];
cAdd.yout ==> out[1];
@@ -214,7 +235,7 @@ template EscalarMulFix(n, BASE) {
signal input e[n]; // Input in binary format
signal output out[2]; // Point (Twisted format)
var nsegments = (n-1)\249 +1;
var nsegments = (n-1)\246 +1; // 249 probably would work. But I'm not sure and for security I keep 246
var nlastsegment = n - (nsegments-1)*249;
component segments[nsegments];
@@ -225,7 +246,7 @@ template EscalarMulFix(n, BASE) {
var s;
var i;
var nseg;
var nWindows
var nWindows;
for (s=0; s<nsegments; s++) {

View File

@@ -27,23 +27,25 @@ function pointAdd(x1,y1,x2,y2) {
return res;
}
template EscalarMulW4Table(base, k) {
signal output out[16][2];
function EscalarMulW4Table(base, k) {
var out[16][2];
var i;
var p[2];
var dbl = base;
var dbl[2] = base;
for (i=0; i<k*4; i++) {
dbl = pointAdd(dbl[0], dbl[1], dbl[0], dbl[1]);
}
out[0][0] <== 0;
out[0][1] <== 1;
out[0][0] = 0;
out[0][1] = 1;
for (i=1; i<16; i++) {
p = pointAdd(out[i-1][0], out[i-1][1], dbl[0], dbl[1]);
out[i][0] <== p[0];
out[i][1] <== p[1];
out[i][0] = p[0];
out[i][1] = p[1];
}
return out;
}

View File

@@ -67,6 +67,7 @@ template NOR() {
template MultiAND(n) {
signal input in[n];
signal output out;
var i;
if (n==1) {
out <== in[0];
} else if (n==2) {
@@ -81,8 +82,8 @@ template MultiAND(n) {
var n2 = n-n\2;
ands[0] = MultiAND(n1);
ands[1] = MultiAND(n2);
for (var i=0; i<n1; i++) ands[0].in[i] <== in[i];
for (var i=0; i<n2; i++) ands[1].in[i] <== in[n1+i];
for (i=0; i<n1; i++) ands[0].in[i] <== in[i];
for (i=0; i<n2; i++) ands[1].in[i] <== in[n1+i];
and2.a <== ands[0].out;
and2.b <== ands[1].out;
out <== and2.out;

View File

@@ -22,7 +22,7 @@ template MiMC7(nrounds) {
signal input k;
signal output out;
var c = [
var c[91] = [
0,
20888961410941983456478427210666206549300505294776164667214940546594746570981,
15265126113435022738560151911929040668591755459209400716467504685752745317193,

View File

@@ -6,10 +6,12 @@ template MiMCSponge(nInputs, nRounds, nOutputs) {
signal input k;
signal output outs[nOutputs];
var i;
// S = R||C
component S[nInputs + nOutputs - 1];
for (var i = 0; i < nInputs; i++) {
for (i = 0; i < nInputs; i++) {
S[i] = MiMCFeistel(nRounds);
S[i].k <== k;
if (i == 0) {
@@ -21,9 +23,9 @@ template MiMCSponge(nInputs, nRounds, nOutputs) {
}
}
outs[0] = S[nInputs - 1].xL_out;
outs[0] <== S[nInputs - 1].xL_out;
for (var i = 0; i < nOutputs - 1; i++) {
for (i = 0; i < nOutputs - 1; i++) {
S[nInputs + i] = MiMCFeistel(nRounds);
S[nInputs + i].k <== k;
S[nInputs + i].xL_in <== S[nInputs + i - 1].xL_out;
@@ -39,8 +41,8 @@ template MiMCFeistel(nrounds) {
signal output xL_out;
signal output xR_out;
var c = [
0,
// doesn't contain the first and last round constants, which are always zero
var c_partial[218] = [
7120861356467848435263064379192047478074060781135320967663101236819528304084,
5024705281721889198577876690145313457398658950011302225525409148828000436681,
17980351014018068290387269214713820287804403312720763401943303895585469787384,
@@ -258,8 +260,7 @@ template MiMCFeistel(nrounds) {
18224457394066545825553407391290108485121649197258948320896164404518684305122,
274945154732293792784580363548970818611304339008964723447672490026510689427,
11050822248291117548220126630860474473945266276626263036056336623671308219529,
2119542016932434047340813757208803962484943912710204325088879681995922344971,
0
2119542016932434047340813757208803962484943912710204325088879681995922344971
];
var t;
@@ -268,13 +269,19 @@ template MiMCFeistel(nrounds) {
signal xL[nrounds-1];
signal xR[nrounds-1];
var c;
for (var i=0; i<nrounds; i++) {
t = (i==0) ? k+xL_in : k + xL[i-1] + c[i];
if ((i == 0) || (i == nrounds - 1)) {
c = 0;
} else {
c = c_partial[i - 1];
}
t = (i==0) ? k+xL_in : k + xL[i-1] + c;
t2[i] <== t*t;
t4[i] <== t2[i]*t2[i];
if (i<nrounds-1) {
xL[i] <== ((i==0) ? xR_in : xR[i-1]) + t4[i]*t;
xR[i] = (i==0) ? xL_in : xL[i-1];
xR[i] <== (i==0) ? xL_in : xL[i-1];
} else {
xR_out <== xR[i-1] + t4[i]*t;
xL_out <== xL[i-1];

View File

@@ -128,6 +128,9 @@ template Segment(nWindows) {
component adders[nWindows-1];
for (i=0; i<nWindows; i++) {
windows[i] = Window4();
for (j=0; j<4; j++) {
windows[i].in[j] <== in[4*i+j];
}
if (i==0) {
windows[i].base[0] <== e2m.out[0];
windows[i].base[1] <== e2m.out[1];
@@ -153,9 +156,6 @@ template Segment(nWindows) {
adders[i-1].in2[0] <== windows[i].out[0];
adders[i-1].in2[1] <== windows[i].out[1];
}
for (j=0; j<4; j++) {
windows[i].in[j] <== in[4*i+j];
}
}
component m2e = Montgomery2Edwards();
@@ -176,7 +176,7 @@ template Pedersen(n) {
signal input in[n];
signal output out[2];
var BASE = [
var BASE[10][2] = [
[10457101036533406547632367118273992217979173478358440826365724437999023779287,19824078218392094440610104313265183977899662750282163392862422243483260492317],
[2671756056509184035029146175565761955751135805354291559563293617232983272177,2663205510731142763556352975002641716101654201788071096152948830924149045094],
[5802099305472655231388284418920769829666717045250560929368476121199858275951,5980429700218124965372158798884772646841287887664001482443826541541529227896],

View File

@@ -28,7 +28,7 @@ template Pedersen(n) {
component escalarMuls[nexps];
var PBASE = [
var PBASE[10][2] = [
[10457101036533406547632367118273992217979173478358440826365724437999023779287,19824078218392094440610104313265183977899662750282163392862422243483260492317],
[2671756056509184035029146175565761955751135805354291559563293617232983272177,2663205510731142763556352975002641716101654201788071096152948830924149045094],
[5802099305472655231388284418920769829666717045250560929368476121199858275951,5980429700218124965372158798884772646841287887664001482443826541541529227896],

View File

@@ -61,7 +61,7 @@ function sqrt(n) {
r = r*b;
}
if (r > ((-1) >> 1)) {
if (r < 0 ) {
r = -r;
}

View File

@@ -25,9 +25,12 @@ template Mix(t, M) {
signal output out[t];
var lc;
for (var i=0; i<t; i++) {
var i;
var j;
for (i=0; i<t; i++) {
lc = 0;
for (var j=0; j<t; j++) {
for (j=0; j<t; j++) {
lc = lc + M[i][j]*in[j];
}
out[i] <== lc;
@@ -40,7 +43,7 @@ template Mix(t, M) {
template Poseidon(nInputs, t, nRoundsF, nRoundsP) {
var C = [
var C[65] = [
14397397413755236225575615486459253198602422701513067526754101844196324375522,
10405129301473404666785234951972711717481302463898292859783056520670200613128,
5179144822360023508491245509308555580251733042407187134628755730783052214509,
@@ -108,7 +111,7 @@ template Poseidon(nInputs, t, nRoundsF, nRoundsP) {
10635360132728137321700090133109897687122647659471659996419791842933639708516
];
var M = [
var M[6][6] = [
[
19167410339349846567561662441069598364702008768579734801591448511131028229281,
14183033936038168803360723133013092560869148726790180682363054735190196956789,
@@ -163,13 +166,15 @@ template Poseidon(nInputs, t, nRoundsF, nRoundsP) {
component sigmaP[nRoundsP];
component mix[nRoundsF + nRoundsP];
var i;
var j;
var k;
for (var i=0; i<(nRoundsF + nRoundsP); i++) {
for (i=0; i<(nRoundsF + nRoundsP); i++) {
ark[i] = Ark(t, C[i]);
mix[i] = Mix(t, M);
for (var j=0; j<t; j++) {
for (j=0; j<t; j++) {
if (i==0) {
if (j<nInputs) {
ark[i].in[j] <== inputs[j];
@@ -183,7 +188,7 @@ template Poseidon(nInputs, t, nRoundsF, nRoundsP) {
if ((i<(nRoundsF/2)) || (i>= (nRoundsP + nRoundsF/2))) {
k= i<nRoundsF/2 ? i : (i-nRoundsP);
for (var j=0; j<t; j++) {
for (j=0; j<t; j++) {
sigmaF[k][j] = Sigma();
sigmaF[k][j].in <== ark[i].out[j];
mix[i].in[j] <== sigmaF[k][j].out;
@@ -193,7 +198,7 @@ template Poseidon(nInputs, t, nRoundsF, nRoundsP) {
sigmaP[k] = Sigma();
sigmaP[k].in <== ark[i].out[0];
mix[i].in[0] <== sigmaP[k].out;
for (var j=1; j<t; j++) {
for (j=1; j<t; j++) {
mix[i].in[j] <== ark[i].out[j];
}
}

View File

@@ -19,7 +19,7 @@
template H(x) {
signal output out[32];
var c = [0x6a09e667,
var c[8] = [0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
@@ -35,7 +35,7 @@ template H(x) {
template K(x) {
signal output out[32];
var c = [
var c[64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,

View File

@@ -0,0 +1,81 @@
include "constants.circom";
include "sha256compression.circom";
template Sha256(nBits) {
signal input in[nBits];
signal output out[256];
var i;
var k;
var nBlocks;
var bitsLastBlock;
nBlocks = ((nBits + 64)\512)+1;
signal paddedIn[nBlocks*512];
for (k=0; k<nBits; k++) {
paddedIn[k] <== in[k];
}
paddedIn[nBits] <== 1;
for (k=nBits+1; k<nBlocks*512-64; k++) {
paddedIn[k] <== 0;
}
for (k = 0; k< 64; k++) {
paddedIn[nBlocks*512 - k -1] <== (nBits >> k)&1;
}
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 sha256compression[nBlocks];
for (i=0; i<nBlocks; i++) {
sha256compression[i] = Sha256compression() ;
if (i==0) {
for (k=0; k<32; k++ ) {
sha256compression[i].hin[0*32+k] <== ha0.out[k];
sha256compression[i].hin[1*32+k] <== hb0.out[k];
sha256compression[i].hin[2*32+k] <== hc0.out[k];
sha256compression[i].hin[3*32+k] <== hd0.out[k];
sha256compression[i].hin[4*32+k] <== he0.out[k];
sha256compression[i].hin[5*32+k] <== hf0.out[k];
sha256compression[i].hin[6*32+k] <== hg0.out[k];
sha256compression[i].hin[7*32+k] <== hh0.out[k];
}
} else {
for (k=0; k<32; k++ ) {
sha256compression[i].hin[32*0+k] <== sha256compression[i-1].out[32*0+31-k];
sha256compression[i].hin[32*1+k] <== sha256compression[i-1].out[32*1+31-k];
sha256compression[i].hin[32*2+k] <== sha256compression[i-1].out[32*2+31-k];
sha256compression[i].hin[32*3+k] <== sha256compression[i-1].out[32*3+31-k];
sha256compression[i].hin[32*4+k] <== sha256compression[i-1].out[32*4+31-k];
sha256compression[i].hin[32*5+k] <== sha256compression[i-1].out[32*5+31-k];
sha256compression[i].hin[32*6+k] <== sha256compression[i-1].out[32*6+31-k];
sha256compression[i].hin[32*7+k] <== sha256compression[i-1].out[32*7+31-k];
}
}
for (k=0; k<512; k++) {
sha256compression[i].inp[k] <== paddedIn[i*512+k];
}
}
for (k=0; k<256; k++) {
out[k] <== sha256compression[nBlocks-1].out[k];
}
}

View File

@@ -17,6 +17,7 @@
along with circom. If not, see <https://www.gnu.org/licenses/>.
*/
include "constants.circom";
include "sha256compression.circom";
include "../bitify.circom"
@@ -25,6 +26,9 @@ template Sha256_2() {
signal input b;
signal output out;
var i;
var k;
component bits2num = Bits2Num(216);
component num2bits[2];
@@ -34,9 +38,28 @@ template Sha256_2() {
num2bits[0].in <== a;
num2bits[1].in <== b;
component sha256compression = Sha256compression() ;
var 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);
for (k=0; k<32; k++ ) {
sha256compression.hin[0*32+k] <== ha0.out[k];
sha256compression.hin[1*32+k] <== hb0.out[k];
sha256compression.hin[2*32+k] <== hc0.out[k];
sha256compression.hin[3*32+k] <== hd0.out[k];
sha256compression.hin[4*32+k] <== he0.out[k];
sha256compression.hin[5*32+k] <== hf0.out[k];
sha256compression.hin[6*32+k] <== hg0.out[k];
sha256compression.hin[7*32+k] <== hh0.out[k];
}
for (i=0; i<216; i++) {
sha256compression.inp[i] <== num2bits[0].out[215-i];

View File

@@ -24,6 +24,7 @@ include "../binsum.circom";
include "sigmaplus.circom";
template Sha256compression() {
signal input hin[256];
signal input inp[512];
signal output out[256];
signal a[65][32];
@@ -44,15 +45,6 @@ template Sha256compression() {
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();
@@ -82,20 +74,23 @@ template Sha256compression() {
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];
}
for (k=0; k<32; 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]
a[0][k] <== hin[k];
b[0][k] <== hin[32*1 + k];
c[0][k] <== hin[32*2 + k];
d[0][k] <== hin[32*3 + k];
e[0][k] <== hin[32*4 + k];
f[0][k] <== hin[32*5 + k];
g[0][k] <== hin[32*6 + k];
h[0][k] <== hin[32*7 + k];
}
for (t = 0; t<64; t++) {
@@ -133,21 +128,21 @@ template Sha256compression() {
}
for (k=0; k<32; k++) {
fsum[0].in[0][k] <== ha0.out[k];
fsum[0].in[0][k] <== hin[32*0+k];
fsum[0].in[1][k] <== a[64][k];
fsum[1].in[0][k] <== hb0.out[k];
fsum[1].in[0][k] <== hin[32*1+k];
fsum[1].in[1][k] <== b[64][k];
fsum[2].in[0][k] <== hc0.out[k];
fsum[2].in[0][k] <== hin[32*2+k];
fsum[2].in[1][k] <== c[64][k];
fsum[3].in[0][k] <== hd0.out[k];
fsum[3].in[0][k] <== hin[32*3+k];
fsum[3].in[1][k] <== d[64][k];
fsum[4].in[0][k] <== he0.out[k];
fsum[4].in[0][k] <== hin[32*4+k];
fsum[4].in[1][k] <== e[64][k];
fsum[5].in[0][k] <== hf0.out[k];
fsum[5].in[0][k] <== hin[32*5+k];
fsum[5].in[1][k] <== f[64][k];
fsum[6].in[0][k] <== hg0.out[k];
fsum[6].in[0][k] <== hin[32*6+k];
fsum[6].in[1][k] <== g[64][k];
fsum[7].in[0][k] <== hh0.out[k];
fsum[7].in[0][k] <== hin[32*7+k];
fsum[7].in[1][k] <== h[64][k];
}

View File

@@ -24,22 +24,26 @@ include "shift.circom";
template SmallSigma(ra, rb, rc) {
signal input in[32];
signal output out[32];
component xor3 = Xor3(32);
var k;
component rota = RotR(32, ra);
component rotb = RotR(32, rb);
component shrc = ShR(32, rc);
for (var k=0; k<32; k++) {
for (k=0; k<32; k++) {
rota.in[k] <== in[k];
rotb.in[k] <== in[k];
shrc.in[k] <== in[k];
}
component xor3 = Xor3(32);
for (k=0; k<32; k++) {
xor3.a[k] <== rota.out[k];
xor3.b[k] <== rotb.out[k];
xor3.c[k] <== shrc.out[k];
}
for (k=0; k<32; k++) {
out[k] <== xor3.out[k];
}
}
@@ -47,22 +51,26 @@ template SmallSigma(ra, rb, rc) {
template BigSigma(ra, rb, rc) {
signal input in[32];
signal output out[32];
component xor3 = Xor3(32);
var k;
component rota = RotR(32, ra);
component rotb = RotR(32, rb);
component rotc = RotR(32, rc);
for (var k=0; k<32; k++) {
for (k=0; k<32; k++) {
rota.in[k] <== in[k];
rotb.in[k] <== in[k];
rotc.in[k] <== in[k];
}
component xor3 = Xor3(32);
for (k=0; k<32; k++) {
xor3.a[k] <== rota.out[k];
xor3.b[k] <== rotb.out[k];
xor3.c[k] <== rotc.out[k];
}
for (k=0; k<32; k++) {
out[k] <== xor3.out[k];
}
}

View File

@@ -26,20 +26,24 @@ template SigmaPlus() {
signal input in15[32];
signal input in16[32];
signal output out[32];
var k;
component sum = BinSum(32, 4);
component sigma1 = SmallSigma(17,19,10);
component sigma0 = SmallSigma(7, 18, 3);
for (var k=0; k<32; k++) {
for (k=0; k<32; k++) {
sigma1.in[k] <== in2[k];
sigma0.in[k] <== in15[k];
}
component sum = BinSum(32, 4);
for (k=0; k<32; 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];
}
for (k=0; k<32; k++) {
out[k] <== sum.out[k];
}
}

View File

@@ -30,23 +30,28 @@ template T1() {
signal input w[32];
signal output out[32];
component sum = BinSum(32, 5);
component ch = Ch(32);
var ki;
component ch = Ch(32);
component bigsigma1 = BigSigma(6, 11, 25);
for (var ki=0; ki<32; ki++) {
for (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]
ch.c[ki] <== g[ki];
}
component sum = BinSum(32, 5);
for (ki=0; ki<32; 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];
}
for (ki=0; ki<32; ki++) {
out[ki] <== sum.out[ki];
}
}

View File

@@ -26,22 +26,25 @@ template T2() {
signal input b[32];
signal input c[32];
signal output out[32];
component sum = BinSum(32, 2);
var k;
component bigsigma0 = BigSigma(2, 13, 22);
component maj = Maj(32);
for (var k=0; k<32; k++) {
for (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];
}
component sum = BinSum(32, 2);
for (k=0; k<32; k++) {
sum.in[0][k] <== bigsigma0.out[k];
sum.in[1][k] <== maj.out[k];
}
for (k=0; k<32; k++) {
out[k] <== sum.out[k];
}
}

View File

@@ -79,9 +79,11 @@ template SMTLevIns(nLevels) {
signal output levIns[nLevels];
signal done[nLevels-1]; // Indicates if the insLevel has aready been detected.
var i;
component isZero[nLevels];
for (var i=0; i<nLevels; i++) {
for (i=0; i<nLevels; i++) {
isZero[i] = IsZero();
isZero[i].in <== siblings[i];
}
@@ -91,7 +93,7 @@ template SMTLevIns(nLevels) {
levIns[nLevels-1] <== (1-isZero[nLevels-2].out);
done[nLevels-2] <== levIns[nLevels-1];
for (var i=nLevels-2; i>0; i--) {
for (i=nLevels-2; i>0; i--) {
levIns[i] <== (1-done[i])*(1-isZero[i-1].out)
done[i-1] <== levIns[i] + done[i];
}

View File

@@ -150,6 +150,8 @@ template SMTProcessor(nLevels) {
signal enabled;
var i;
enabled <== fnc[0] + fnc[1] - fnc[0]*fnc[1]
component hash1Old = SMTHash1();
@@ -167,18 +169,18 @@ template SMTProcessor(nLevels) {
n2bNew.in <== newKey;
component smtLevIns = SMTLevIns(nLevels);
for (var i=0; i<nLevels; i++) smtLevIns.siblings[i] <== siblings[i];
for (i=0; i<nLevels; i++) smtLevIns.siblings[i] <== siblings[i];
smtLevIns.enabled <== enabled;
component xors[nLevels];
for (var i=0; i<nLevels; i++) {
for (i=0; i<nLevels; i++) {
xors[i] = XOR();
xors[i].a <== n2bOld.out[i];
xors[i].b <== n2bNew.out[i];
}
component sm[nLevels];
for (var i=0; i<nLevels; i++) {
for (i=0; i<nLevels; i++) {
sm[i] = SMTProcessorSM();
if (i==0) {
sm[i].prev_top <== enabled;
@@ -204,7 +206,7 @@ template SMTProcessor(nLevels) {
sm[nLevels-1].st_na + sm[nLevels-1].st_new1 + sm[nLevels-1].st_old0 +sm[nLevels-1].st_upd === 1;
component levels[nLevels];
for (var i=nLevels-1; i != -1; i--) {
for (i=nLevels-1; i != -1; i--) {
levels[i] = SMTProcessorLevel();
levels[i].st_top <== sm[i].st_top;

View File

@@ -48,6 +48,8 @@ template SMTVerifier(nLevels) {
signal input value;
signal input fnc;
var i;
component hash1Old = SMTHash1();
hash1Old.key <== oldKey;
hash1Old.value <== oldValue;
@@ -63,11 +65,11 @@ template SMTVerifier(nLevels) {
n2bNew.in <== key;
component smtLevIns = SMTLevIns(nLevels);
for (var i=0; i<nLevels; i++) smtLevIns.siblings[i] <== siblings[i];
for (i=0; i<nLevels; i++) smtLevIns.siblings[i] <== siblings[i];
smtLevIns.enabled <== enabled;
component sm[nLevels];
for (var i=0; i<nLevels; i++) {
for (i=0; i<nLevels; i++) {
sm[i] = SMTVerifierSM();
if (i==0) {
sm[i].prev_top <== enabled;
@@ -89,7 +91,7 @@ template SMTVerifier(nLevels) {
sm[nLevels-1].st_na + sm[nLevels-1].st_iold + sm[nLevels-1].st_inew + sm[nLevels-1].st_i0 === 1;
component levels[nLevels];
for (var i=nLevels-1; i != -1; i--) {
for (i=nLevels-1; i != -1; i--) {
levels[i] = SMTVerifierLevel();
levels[i].st_top <== sm[i].st_top;

View File

@@ -4,3 +4,11 @@ exports.mimc7 = require("./src/mimc7");
exports.mimcsponge = require("./src/mimcsponge");
exports.babyJub = require("./src/babyjub");
exports.pedersenHash = require("./src/pedersenHash");
exports.SMT = require("./src/smt").SMT;
exports.SMTMemDB = require("./src/smt_memdb");
exports.poseidon = require("./src/poseidon");
exports.leInt2Buff = require("./src/utils").leInt2Buff;
exports.leBuff2int = require("./src/utils").leBuff2int;

11471
log.txt

File diff suppressed because it is too large Load Diff

6979
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "circomlib",
"version": "0.0.10",
"version": "0.1.2",
"description": "Basic circuits library for Circom",
"main": "index.js",
"directories": {
@@ -26,14 +26,15 @@
"dependencies": {
"blake-hash": "^1.1.0",
"blake2b": "^2.1.3",
"snarkjs": "0.1.11",
"circom": "0.5.3",
"ffjavascript": "0.0.3",
"snarkjs": "^0.1.22",
"typedarray-to-buffer": "^3.1.5",
"web3": "^1.0.0-beta.55"
"web3": "^1.2.6"
},
"devDependencies": {
"circom": "0.0.28",
"eslint-plugin-mocha": "^5.2.0",
"ganache-cli": "^6.4.4",
"mocha": "^5.2.0"
"eslint": "^6.8.0",
"ganache-cli": "^6.9.1",
"mocha": "^7.1.1"
}
}

View File

@@ -1,5 +1,6 @@
const bn128 = require("snarkjs").bn128;
const bigInt = require("snarkjs").bigInt;
const bigInt = require("big-integer");
const ZqField = require("ffjavascript").ZqField;
const utils = require("./utils.js");
exports.addPoint = addPoint;
exports.mulPointEscalar = mulPointEscalar;
@@ -7,19 +8,23 @@ exports.inCurve = inCurve;
exports.inSubgroup = inSubgroup;
exports.packPoint = packPoint;
exports.unpackPoint = unpackPoint;
exports.Generator = [
bigInt("995203441582195749578291179787384436505546430278305826713579947235728471134"),
bigInt("5472060717959818805561601436314318772137091100104008585924551046643952123905")
];
exports.Base8 = [
bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475")
bigInt("5299619240641551281634865583518297030282874472190772894086521144482721001553"),
bigInt("16950150798460657717958625567821834550301663161624707787222815936182638968203")
];
exports.order = bigInt("21888242871839275222246405745257275088614511777268538073601725287587578984328");
exports.subOrder = exports.order.shr(3);
exports.p = bn128.r;
exports.subOrder = exports.order.shiftRight(3);
exports.p = bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
exports.A = bigInt("168700");
exports.D = bigInt("168696");
function addPoint(a,b) {
const q = bn128.r;
const cta = bigInt("168700");
const d = bigInt("168696");
const F = new ZqField(exports.p);
const res = [];
@@ -27,8 +32,25 @@ function addPoint(a,b) {
res[0] = bigInt((a[0]*b[1] + b[0]*a[1]) * bigInt(bigInt("1") + d*a[0]*b[0]*a[1]*b[1]).inverse(q)).affine(q);
res[1] = bigInt((a[1]*b[1] - cta*a[0]*b[0]) * bigInt(bigInt("1") - d*a[0]*b[0]*a[1]*b[1]).inverse(q)).affine(q);
*/
res[0] = bigInt((bigInt(a[0]).mul(b[1]).add(bigInt(b[0]).mul(a[1]))).mul(bigInt(bigInt("1").add(d.mul(a[0]).mul(b[0]).mul(a[1]).mul(b[1]))).inverse(q))).affine(q);
res[1] = bigInt((bigInt(a[1]).mul(b[1]).sub(cta.mul(a[0]).mul(b[0]))).mul(bigInt(bigInt("1").sub(d.mul(a[0]).mul(b[0]).mul(a[1]).mul(b[1]))).inverse(q))).affine(q);
const beta = F.mul(a[0],b[1]);
const gamma = F.mul(a[1],b[0]);
const delta = F.mul(
F.sub(a[1], F.mul(exports.A, a[0])),
F.add(b[0], b[1])
);
const tau = F.mul(beta, gamma);
const dtau = F.mul(exports.D, tau);
res[0] = F.div(
F.add(beta, gamma),
F.add(bigInt.one, dtau)
);
res[1] = F.div(
F.add(delta, F.sub(F.mul(exports.A,beta), gamma)),
F.sub(bigInt.one, dtau)
);
return res;
}
@@ -43,7 +65,7 @@ function mulPointEscalar(base, e) {
res = addPoint(res, exp);
}
exp = addPoint(exp, exp);
rem = rem.shr(1);
rem = rem.shiftRight(1);
}
return res;
@@ -56,31 +78,28 @@ function inSubgroup(P) {
}
function inCurve(P) {
const F = bn128.Fr;
const a = bigInt("168700");
const d = bigInt("168696");
const F = new ZqField(exports.p);
const x2 = F.square(P[0]);
const y2 = F.square(P[1]);
if (!F.equals(
F.add(F.mul(a, x2), y2),
F.add(F.one, F.mul(F.mul(x2, y2), d)))) return false;
if (!F.eq(
F.add(F.mul(exports.A, x2), y2),
F.add(F.one, F.mul(F.mul(x2, y2), exports.D)))) return false;
return true;
}
function packPoint(P) {
const buff = bigInt.leInt2Buff(P[1], 32);
if (P[0].greater(exports.p.shr(1))) {
const buff = utils.leInt2Buff(P[1], 32);
if (P[0].greater(exports.p.shiftRight(1))) {
buff[31] = buff[31] | 0x80;
}
return buff;
}
function unpackPoint(_buff) {
const F = bn128.Fr;
const F = new ZqField(exports.p);
const buff = Buffer.from(_buff);
let sign = false;
@@ -89,23 +108,20 @@ function unpackPoint(_buff) {
sign = true;
buff[31] = buff[31] & 0x7F;
}
P[1] = bigInt.leBuff2int(buff);
P[1] = utils.leBuff2int(buff);
if (P[1].greaterOrEquals(exports.p)) return null;
const a = bigInt("168700");
const d = bigInt("168696");
const y2 = F.square(P[1]);
let x = F.sqrt(F.div(
F.sub(F.one, y2),
F.sub(a, F.mul(d, y2))));
F.sub(exports.A, F.mul(exports.D, y2))));
if (x == null) return null;
if (sign) x = F.neg(x);
P[0] = F.affine(x);
P[0] = x;
return P;
}

View File

@@ -1,11 +1,13 @@
const createBlakeHash = require("blake-hash");
const bigInt = require("snarkjs").bigInt;
const bigInt = require("big-integer");
const babyJub = require("./babyjub");
const utils = require("./utils");
const pedersenHash = require("./pedersenHash").hash;
const mimc7 = require("./mimc7");
const poseidon = require("./poseidon.js");
const mimcsponge = require("./mimcsponge");
exports.prv2pub= prv2pub;
exports.sign = sign;
exports.signMiMC = signMiMC;
@@ -30,26 +32,26 @@ function pruneBuffer(_buff) {
function prv2pub(prv) {
const sBuff = pruneBuffer(createBlakeHash("blake512").update(prv).digest().slice(0,32));
let s = bigInt.leBuff2int(sBuff);
const A = babyJub.mulPointEscalar(babyJub.Base8, s.shr(3));
let s = utils.leBuff2int(sBuff);
const A = babyJub.mulPointEscalar(babyJub.Base8, s.shiftRight(3));
return A;
}
function sign(prv, msg) {
const h1 = createBlakeHash("blake512").update(prv).digest();
const sBuff = pruneBuffer(h1.slice(0,32));
const s = bigInt.leBuff2int(sBuff);
const A = babyJub.mulPointEscalar(babyJub.Base8, s.shr(3));
const s = utils.leBuff2int(sBuff);
const A = babyJub.mulPointEscalar(babyJub.Base8, s.shiftRight(3));
const rBuff = createBlakeHash("blake512").update(Buffer.concat([h1.slice(32,64), msg])).digest();
let r = bigInt.leBuff2int(rBuff);
let r = utils.leBuff2int(rBuff);
r = r.mod(babyJub.subOrder);
const R8 = babyJub.mulPointEscalar(babyJub.Base8, r);
const R8p = babyJub.packPoint(R8);
const Ap = babyJub.packPoint(A);
const hmBuff = pedersenHash(Buffer.concat([R8p, Ap, msg]));
const hm = bigInt.leBuff2int(hmBuff);
const S = r.add(hm.mul(s)).mod(babyJub.subOrder);
const hm = utils.leBuff2int(hmBuff);
const S = r.add(hm.times(s)).mod(babyJub.subOrder);
return {
R8: R8,
S: S
@@ -59,16 +61,16 @@ function sign(prv, msg) {
function signMiMC(prv, msg) {
const h1 = createBlakeHash("blake512").update(prv).digest();
const sBuff = pruneBuffer(h1.slice(0,32));
const s = bigInt.leBuff2int(sBuff);
const A = babyJub.mulPointEscalar(babyJub.Base8, s.shr(3));
const s = utils.leBuff2int(sBuff);
const A = babyJub.mulPointEscalar(babyJub.Base8, s.shiftRight(3));
const msgBuff = bigInt.leInt2Buff(msg, 32);
const msgBuff = utils.leInt2Buff(msg, 32);
const rBuff = createBlakeHash("blake512").update(Buffer.concat([h1.slice(32,64), msgBuff])).digest();
let r = bigInt.leBuff2int(rBuff);
let r = utils.leBuff2int(rBuff);
r = r.mod(babyJub.subOrder);
const R8 = babyJub.mulPointEscalar(babyJub.Base8, r);
const hm = mimc7.multiHash([R8[0], R8[1], A[0], A[1], msg]);
const S = r.add(hm.mul(s)).mod(babyJub.subOrder);
const S = r.add(hm.times(s)).mod(babyJub.subOrder);
return {
R8: R8,
S: S
@@ -78,16 +80,16 @@ function signMiMC(prv, msg) {
function signMiMCSponge(prv, msg) {
const h1 = createBlakeHash("blake512").update(prv).digest();
const sBuff = pruneBuffer(h1.slice(0,32));
const s = bigInt.leBuff2int(sBuff);
const A = babyJub.mulPointEscalar(babyJub.Base8, s.shr(3));
const s = utils.leBuff2int(sBuff);
const A = babyJub.mulPointEscalar(babyJub.Base8, s.shiftRight(3));
const msgBuff = bigInt.leInt2Buff(msg, 32);
const msgBuff = utils.leInt2Buff(msg, 32);
const rBuff = createBlakeHash("blake512").update(Buffer.concat([h1.slice(32,64), msgBuff])).digest();
let r = bigInt.leBuff2int(rBuff);
let r = utils.leBuff2int(rBuff);
r = r.mod(babyJub.subOrder);
const R8 = babyJub.mulPointEscalar(babyJub.Base8, r);
const hm = mimcsponge.multiHash([R8[0], R8[1], A[0], A[1], msg]);
const S = r.add(hm.mul(s)).mod(babyJub.subOrder);
const S = r.add(hm.times(s)).mod(babyJub.subOrder);
return {
R8: R8,
S: S
@@ -97,17 +99,17 @@ function signMiMCSponge(prv, msg) {
function signPoseidon(prv, msg) {
const h1 = createBlakeHash("blake512").update(prv).digest();
const sBuff = pruneBuffer(h1.slice(0,32));
const s = bigInt.leBuff2int(sBuff);
const A = babyJub.mulPointEscalar(babyJub.Base8, s.shr(3));
const s = utils.leBuff2int(sBuff);
const A = babyJub.mulPointEscalar(babyJub.Base8, s.shiftRight(3));
const msgBuff = bigInt.leInt2Buff(msg, 32);
const msgBuff = utils.leInt2Buff(msg, 32);
const rBuff = createBlakeHash("blake512").update(Buffer.concat([h1.slice(32,64), msgBuff])).digest();
let r = bigInt.leBuff2int(rBuff);
let r = utils.leBuff2int(rBuff);
r = r.mod(babyJub.subOrder);
const R8 = babyJub.mulPointEscalar(babyJub.Base8, r);
const hash = poseidon.createHash(6, 8, 57);
const hm = hash([R8[0], R8[1], A[0], A[1], msg]);
const S = r.add(hm.mul(s)).mod(babyJub.subOrder);
const S = r.add(hm.times(s)).mod(babyJub.subOrder);
return {
R8: R8,
S: S
@@ -128,10 +130,10 @@ function verify(msg, sig, A) {
const R8p = babyJub.packPoint(sig.R8);
const Ap = babyJub.packPoint(A);
const hmBuff = pedersenHash(Buffer.concat([R8p, Ap, msg]));
const hm = bigInt.leBuff2int(hmBuff);
const hm = utils.leBuff2int(hmBuff);
const Pleft = babyJub.mulPointEscalar(babyJub.Base8, sig.S);
let Pright = babyJub.mulPointEscalar(A, hm.mul(bigInt("8")));
let Pright = babyJub.mulPointEscalar(A, hm.times(bigInt("8")));
Pright = babyJub.addPoint(sig.R8, Pright);
if (!Pleft[0].equals(Pright[0])) return false;
@@ -153,7 +155,7 @@ function verifyMiMC(msg, sig, A) {
const hm = mimc7.multiHash([sig.R8[0], sig.R8[1], A[0], A[1], msg]);
const Pleft = babyJub.mulPointEscalar(babyJub.Base8, sig.S);
let Pright = babyJub.mulPointEscalar(A, hm.mul(bigInt("8")));
let Pright = babyJub.mulPointEscalar(A, hm.times(bigInt("8")));
Pright = babyJub.addPoint(sig.R8, Pright);
if (!Pleft[0].equals(Pright[0])) return false;
@@ -177,7 +179,7 @@ function verifyPoseidon(msg, sig, A) {
const hm = hash([sig.R8[0], sig.R8[1], A[0], A[1], msg]);
const Pleft = babyJub.mulPointEscalar(babyJub.Base8, sig.S);
let Pright = babyJub.mulPointEscalar(A, hm.mul(bigInt("8")));
let Pright = babyJub.mulPointEscalar(A, hm.times(bigInt("8")));
Pright = babyJub.addPoint(sig.R8, Pright);
if (!Pleft[0].equals(Pright[0])) return false;
@@ -199,7 +201,7 @@ function verifyMiMCSponge(msg, sig, A) {
const hm = mimcsponge.multiHash([sig.R8[0], sig.R8[1], A[0], A[1], msg]);
const Pleft = babyJub.mulPointEscalar(babyJub.Base8, sig.S);
let Pright = babyJub.mulPointEscalar(A, hm.mul(bigInt("8")));
let Pright = babyJub.mulPointEscalar(A, hm.times(bigInt("8")));
Pright = babyJub.addPoint(sig.R8, Pright);
if (!Pleft[0].equals(Pright[0])) return false;
@@ -209,14 +211,14 @@ function verifyMiMCSponge(msg, sig, A) {
function packSignature(sig) {
const R8p = babyJub.packPoint(sig.R8);
const Sp = bigInt.leInt2Buff(sig.S, 32);
const Sp = utils.leInt2Buff(sig.S, 32);
return Buffer.concat([R8p, Sp]);
}
function unpackSignature(sigBuff) {
return {
R8: babyJub.unpackPoint(sigBuff.slice(0,32)),
S: bigInt.leBuff2int(sigBuff.slice(32,64))
S: utils.leBuff2int(sigBuff.slice(32,64))
};
}

View File

@@ -1,7 +1,8 @@
const bn128 = require("snarkjs").bn128;
const bigInt = require("snarkjs").bigInt;
const bigInt = require("big-integer");
const ZqField = require("ffjavascript").ZqField;
const Web3Utils = require("web3-utils");
const F = bn128.Fr;
const F = new ZqField(bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"));
const SEED = "mimc";
const NROUNDS = 91;
@@ -10,7 +11,7 @@ exports.getIV = (seed) => {
if (typeof seed === "undefined") seed = SEED;
const c = Web3Utils.keccak256(seed+"_iv");
const cn = bigInt(Web3Utils.toBN(c).toString());
const iv = cn.mod(F.q);
const iv = cn.mod(F.p);
return iv;
};
@@ -22,7 +23,7 @@ exports.getConstants = (seed, nRounds) => {
for (let i=1; i<nRounds; i++) {
c = Web3Utils.keccak256(c);
const n1 = Web3Utils.toBN(c).mod(Web3Utils.toBN(F.q.toString()));
const n1 = Web3Utils.toBN(c).mod(Web3Utils.toBN(F.p.toString()));
const c2 = Web3Utils.padLeft(Web3Utils.toHex(n1), 64);
cts[i] = bigInt(Web3Utils.toBN(c2).toString());
}
@@ -39,9 +40,9 @@ exports.hash = (_x_in, _k) =>{
for (let i=0; i<NROUNDS; i++) {
const c = cts[i];
const t = (i==0) ? F.add(x_in, k) : F.add(F.add(r, k), c);
r = F.exp(t, 7);
r = F.pow(t, 7);
}
return F.affine(F.add(r, k));
return F.add(r, k);
};
exports.multiHash = (arr, key) => {
@@ -60,5 +61,5 @@ exports.multiHash = (arr, key) => {
exports.hash(bigInt(arr[i]), r)
);
}
return F.affine(r);
return r;
};

View File

@@ -1,7 +1,7 @@
const bn128 = require("snarkjs").bn128;
const bigInt = require("snarkjs").bigInt;
const bigInt = require("big-integer");
const Web3Utils = require("web3-utils");
const F = bn128.Fr;
const ZqField = require("ffjavascript").ZqField;
const F = new ZqField(bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"));
const SEED = "mimcsponge";
const NROUNDS = 220;
@@ -10,7 +10,7 @@ exports.getIV = (seed) => {
if (typeof seed === "undefined") seed = SEED;
const c = Web3Utils.keccak256(seed+"_iv");
const cn = bigInt(Web3Utils.toBN(c).toString());
const iv = cn.mod(F.q);
const iv = cn.mod(F.p);
return iv;
};
@@ -22,7 +22,7 @@ exports.getConstants = (seed, nRounds) => {
for (let i=1; i<nRounds; i++) {
c = Web3Utils.keccak256(c);
const n1 = Web3Utils.toBN(c).mod(Web3Utils.toBN(F.q.toString()));
const n1 = Web3Utils.toBN(c).mod(Web3Utils.toBN(F.p.toString()));
const c2 = Web3Utils.padLeft(Web3Utils.toHex(n1), 64);
cts[i] = bigInt(Web3Utils.toBN(c2).toString());
}
@@ -42,21 +42,21 @@ exports.hash = (_xL_in, _xR_in, _k) =>{
const t = (i==0) ? F.add(xL, k) : F.add(F.add(xL, k), c);
const xR_tmp = bigInt(xR);
if (i < (NROUNDS - 1)) {
xR = xL;
xL = F.add(xR_tmp, F.exp(t, 5));
xR = xL;
xL = F.add(xR_tmp, F.pow(t, 5));
} else {
xR = F.add(xR_tmp, F.exp(t, 5));
xR = F.add(xR_tmp, F.pow(t, 5));
}
}
return {
xL: F.affine(xL),
xR: F.affine(xR),
xL: F.normalize(xL),
xR: F.normalize(xR),
};
};
exports.multiHash = (arr, key, numOutputs) => {
if (typeof(numOutputs) === "undefined") {
numOutputs = 1;
numOutputs = 1;
}
if (typeof(key) === "undefined") {
key = F.zero;
@@ -66,21 +66,21 @@ exports.multiHash = (arr, key, numOutputs) => {
let C = F.zero;
for (let i=0; i<arr.length; i++) {
R = F.add(R, bigInt(arr[i]));
const S = exports.hash(R, C, key);
R = S.xL;
C = S.xR;
R = F.add(R, bigInt(arr[i]));
const S = exports.hash(R, C, key);
R = S.xL;
C = S.xR;
}
let outputs = [R];
for (let i=1; i < numOutputs; i++) {
const S = exports.hash(R, C, key);
R = S.xL;
C = S.xR;
outputs.push(R);
const S = exports.hash(R, C, key);
R = S.xL;
C = S.xR;
outputs.push(R);
}
if (numOutputs == 1) {
return F.affine(outputs[0]);
return F.normalize(outputs[0]);
} else {
return outputs.map(x => F.affine(x));
return outputs.map(x => F.normalize(x));
}
};

View File

@@ -1,5 +1,4 @@
const bn128 = require("snarkjs").bn128;
const bigInt = require("snarkjs").bigInt;
const bigInt = require("big-integer");
const babyJub = require("./babyjub");
const createBlakeHash = require("blake-hash");
@@ -32,18 +31,18 @@ function pedersenHash(msg) {
let acc = bigInt.one;
for (let b=0; ((b<windowSize-1)&&(o<bits.length)) ; b++) {
if (bits[o]) {
acc = acc.add( bigInt.one.shl(b) );
acc = acc.add( bigInt.one.shiftLeft(b) );
}
o++;
}
if (o<bits.length) {
if (bits[o]) {
acc = acc.neg();
acc = bigInt.zero.minus(acc);
}
o++;
}
escalar = escalar.add(acc.mul(exp));
exp = exp.shl(windowSize+1);
escalar = escalar.add(acc.times(exp));
exp = exp.shiftLeft(windowSize+1);
}
if (escalar.lesser(bigInt.zero)) {

View File

@@ -1,8 +1,10 @@
const bn128 = require("snarkjs").bn128;
const bigInt = require("snarkjs").bigInt;
const blake2b = require('blake2b');
const bigInt = require("big-integer");
const blake2b = require("blake2b");
const assert = require("assert");
const F = bn128.Fr;
const ZqField = require("ffjavascript").ZqField;
const utils = require("./utils");
const F = new ZqField(bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"));
const SEED = "poseidon";
const NROUNDSF = 8;
@@ -12,11 +14,11 @@ const T = 6;
function getPseudoRandom(seed, n) {
const res = [];
let input = Buffer.from(seed);
let h = blake2b(32).update(input).digest()
let h = blake2b(32).update(input).digest();
while (res.length<n) {
const n = F.affine(bigInt.leBuff2int(h));
const n = F.normalize(utils.leBuff2int(h));
res.push(n);
h = blake2b(32).update(h).digest()
h = blake2b(32).update(h).digest();
}
return res;
@@ -36,6 +38,8 @@ exports.getMatrix = (t, seed, nRounds) => {
if (typeof seed === "undefined") seed = SEED;
if (typeof nRounds === "undefined") nRounds = NROUNDSF + NROUNDSP;
if (typeof t === "undefined") t = T;
assert(t<=6); // Force the same matrix for all.
t=6;
let nonce = "0000";
let cmatrix = getPseudoRandom(seed+"_matrix_"+nonce, t*2);
while (!allDifferent(cmatrix)) {
@@ -48,7 +52,7 @@ exports.getMatrix = (t, seed, nRounds) => {
for (let i=0; i<t; i++) {
M[i] = new Array(t);
for (let j=0; j<t; j++) {
M[i][j] = F.affine(F.inverse(F.sub(cmatrix[i], cmatrix[t+j])));
M[i][j] = F.normalize(F.inv(F.sub(cmatrix[i], cmatrix[t+j])));
}
}
return M;
@@ -95,7 +99,7 @@ exports.createHash = (t, nRoundsF, nRoundsP, seed) => {
const M = exports.getMatrix(t, seed, nRoundsF + nRoundsP);
return function(inputs) {
let state = [];
assert(inputs.length < t);
assert(inputs.length <= t);
assert(inputs.length > 0);
for (let i=0; i<inputs.length; i++) state[i] = bigInt(inputs[i]);
for (let i=inputs.length; i<t; i++) state[i] = F.zero;
@@ -109,7 +113,7 @@ exports.createHash = (t, nRoundsF, nRoundsP, seed) => {
}
mix(state, M);
}
return F.affine(state[0]);
return F.normalize(state[0]);
};
};

View File

@@ -121,7 +121,7 @@ function createCode(t, nRoundsF, nRoundsP, seed) {
// We ignore the pointer and the length and just load 6 values to the state
// (Stack positions 0-5) If the array is shorter, we just set zeros.
for (let i=0; i<t; i++) {
C.push(0x44+(0x20*(5-i)));
C.push(0x44+(0x20*(t-1-i)));
C.calldataload();
}

View File

@@ -1,4 +1,4 @@
const bigInt = require("snarkjs").bigInt;
const bigInt = require("big-integer");
const SMTMemDB = require("./smt_memdb");
const {hash0, hash1} = require("./smt_hashes_poseidon");
@@ -21,7 +21,7 @@ class SMT {
} else {
res.push(false);
}
k = k.shr(1);
k = k.shiftRight(1);
}
while (res.length<256) res.push(false);
@@ -309,3 +309,5 @@ async function newMemEmptyTrie() {
module.exports.loadFromFile = loadFromFile;
module.exports.newMemEmptyTrie = newMemEmptyTrie;
module.exports.SMT = SMT;
module.exports.SMTMemDB = SMTMemDB;

View File

@@ -1,5 +1,5 @@
const mimc7 = require("./mimc7");
const bigInt = require("snarkjs").bigInt;
const bigInt = require("big-integer");
exports.hash0 = function (left, right) {
return mimc7.multiHash(left, right);

View File

@@ -1,5 +1,5 @@
const Poseidon = require("./poseidon");
const bigInt = require("snarkjs").bigInt;
const bigInt = require("big-integer");
const hash = Poseidon.createHash(6, 8, 57);

View File

@@ -1,4 +1,4 @@
const bigInt = require("snarkjs").bigInt;
const bigInt = require("big-integer");
class SMTMemDb {
constructor() {
@@ -27,6 +27,14 @@ class SMTMemDb {
return this.nodes[keyS];
}
async multiGet(keys) {
const promises = [];
for (let i=0; i<keys.length; i++) {
promises.push(this.get(keys[i]));
}
return await Promise.all(promises);
}
async setRoot(rt) {
this.root = rt;
}

87
src/utils.js Normal file
View File

@@ -0,0 +1,87 @@
const bigInt = require("big-integer");
module.exports.leBuff2int = leBuff2int;
module.exports.leInt2Buff = leInt2Buff;
module.exports.beBuff2int = beBuff2int;
module.exports.beInt2Buff = beInt2Buff;
module.exports.stringifyBigInts = stringifyBigInts;
module.exports.unstringifyBigInts = unstringifyBigInts;
function leBuff2int (buff) {
let res = bigInt.zero;
for (let i=0; i<buff.length; i++) {
const n = bigInt(buff[i]);
res = res.add(n.shiftLeft(i*8));
}
return res;
}
function leInt2Buff(n, len) {
let r = n;
let o =0;
const buff = Buffer.alloc(len);
while ((r.gt(bigInt.zero))&&(o<buff.length)) {
let c = Number(r.and(bigInt(255)));
buff[o] = c;
o++;
r = r.shiftRight(8);
}
if (r.gt(bigInt.zero)) throw new Error("Number does not feed in buffer");
return buff;
}
function beBuff2int (buff) {
let res = bigInt.zero;
for (let i=0; i<buff.length; i++) {
const n = bigInt(buff[buff.length - i - 1]);
res = res.add(n.shiftLeft(i*8));
}
return res;
}
function beInt2Buff(n, len) {
let r = n;
let o =len-1;
const buff = Buffer.alloc(len);
while ((r.greater(bigInt.zero))&&(o>=0)) {
let c = Number(r.and(bigInt(255)));
buff[o] = c;
o--;
r = r.shiftRight(8);
}
if (r.gt(bigInt.zero)) throw new Error("Number does not feed in buffer");
return buff;
}
function stringifyBigInts(o) {
if ((typeof(o) == "bigint") || o.isZero !== undefined) {
return o.toString(10);
} else if (Array.isArray(o)) {
return o.map(stringifyBigInts);
} else if (typeof o == "object") {
const res = {};
for (let k in o) {
res[k] = stringifyBigInts(o[k]);
}
return res;
} else {
return o;
}
}
function unstringifyBigInts(o) {
if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) {
return bigInt(o);
} else if (Array.isArray(o)) {
return o.map(unstringifyBigInts);
} else if (typeof o == "object") {
const res = {};
for (let k in o) {
res[k] = unstringifyBigInts(o[k]);
}
return res;
} else {
return o;
}
}

View File

@@ -1,11 +1,11 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
const bigInt = require("big-integer");
const tester = require("circom").tester;
function print(circuit, w, s) {
console.log(s + ": " + w[circuit.getSignalIdx(s)]);
@@ -14,7 +14,7 @@ function print(circuit, w, s) {
function getBits(v, n) {
const res = [];
for (let i=0; i<n; i++) {
if (v.shr(i).isOdd()) {
if (v.shiftRight(i).isOdd()) {
res.push(bigInt.one);
} else {
res.push(bigInt.zero);
@@ -25,49 +25,48 @@ function getBits(v, n) {
const q = bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
describe("Aliascheck test", () => {
let circuit;
describe("Aliascheck test", function () {
this.timeout(100000);
let cir;
before( async() => {
const cirDef = await compiler(path.join(__dirname, "circuits", "aliascheck_test.circom"));
circuit = new snarkjs.Circuit(cirDef);
console.log("NConstrains: " + circuit.nConstraints);
cir = await tester(path.join(__dirname, "circuits", "aliascheck_test.circom"));
});
it("Satisfy the aliastest 0", async () => {
const inp = getBits(bigInt.zero, 254);
circuit.calculateWitness({in: inp});
await cir.calculateWitness({in: inp}, true);
});
it("Satisfy the aliastest 3", async () => {
const inp = getBits(bigInt(3), 254);
circuit.calculateWitness({in: inp});
await cir.calculateWitness({in: inp}, true);
});
it("Satisfy the aliastest q-1", async () => {
const inp = getBits(q.sub(bigInt.one), 254);
circuit.calculateWitness({in: inp});
const inp = getBits(q.minus(bigInt.one), 254);
await cir.calculateWitness({in: inp}, true);
});
it("Nhot not satisfy an input of q", async () => {
it("Should not satisfy an input of q", async () => {
const inp = getBits(q, 254);
try {
circuit.calculateWitness({in: inp});
await cir.calculateWitness({in: inp}, true);
assert(false);
} catch(err) {
assert.equal(err.message, "Constraint doesn't match: 1 != 0");
assert(/Constraint\sdoesn't\smatch(.*)1\s!=\s0/.test(err.message) );
}
});
it("Nhot not satisfy all ones", async () => {
it("Should not satisfy all ones", async () => {
const inp = getBits(bigInt(1).shl(254).sub(bigInt(1)), 254);
const inp = getBits(bigInt(1).shiftLeft(254).minus(bigInt.one), 254);
try {
circuit.calculateWitness({in: inp});
await cir.calculateWitness({in: inp}, true);
assert(false);
} catch(err) {
assert.equal(err.message, "Constraint doesn't match: 1 != 0");
assert(/Constraint\sdoesn't\smatch(.*)1\s!=\s0/.test(err.message) );
}
});

View File

@@ -1,125 +1,112 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const createBlakeHash = require("blake-hash");
const eddsa = require("../src/eddsa.js");
const assert = chai.assert;
const bigInt = require("snarkjs").bigInt;
const bigInt = require("big-integer");
const tester = require("circom").tester;
const utils = require("../src/utils.js");
describe("Baby Jub test", function () {
let circuitAdd;
let circuitTest;
let circuitPbk;
this.timeout(100000);
before( async() => {
const cirDefAdd = await compiler(path.join(__dirname, "circuits", "babyadd_tester.circom"));
circuitAdd = new snarkjs.Circuit(cirDefAdd);
console.log("NConstrains BabyAdd: " + circuitAdd.nConstraints);
circuitAdd = await tester(path.join(__dirname, "circuits", "babyadd_tester.circom"));
const cirDefTest = await compiler(path.join(__dirname, "circuits", "babycheck_test.circom"));
circuitTest = new snarkjs.Circuit(cirDefTest);
console.log("NConstrains BabyTest: " + circuitTest.nConstraints);
const cirDefPbk = await compiler(path.join(__dirname, "circuits", "babypbk_test.circom"));
circuitPbk = new snarkjs.Circuit(cirDefPbk);
console.log("NConstrains BabyPbk: " + circuitPbk.nConstraints);
circuitTest = await tester(path.join(__dirname, "circuits", "babycheck_test.circom"));
circuitPbk = await tester(path.join(__dirname, "circuits", "babypbk_test.circom"));
});
it("Should add point (0,1) and (0,1)", async () => {
const input={
x1: snarkjs.bigInt(0),
y1: snarkjs.bigInt(1),
x2: snarkjs.bigInt(0),
y2: snarkjs.bigInt(1)
x1: bigInt(0),
y1: bigInt(1),
x2: bigInt(0),
y2: bigInt(1)
};
const w = circuitAdd.calculateWitness(input);
const w = await circuitAdd.calculateWitness(input, true);
const xout = w[circuitAdd.getSignalIdx("main.xout")];
const yout = w[circuitAdd.getSignalIdx("main.yout")];
assert(xout.equals(0));
assert(yout.equals(1));
await circuitAdd.assertOut(w, {xout: bigInt(0), yout: bigInt(1)});
});
it("Should add 2 same numbers", async () => {
const input={
x1: snarkjs.bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
y1: snarkjs.bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
x2: snarkjs.bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
y2: snarkjs.bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475")
x1: bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
y1: bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
x2: bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
y2: bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475")
};
const w = circuitAdd.calculateWitness(input);
const w = await circuitAdd.calculateWitness(input, true);
const xout = w[circuitAdd.getSignalIdx("main.xout")];
const yout = w[circuitAdd.getSignalIdx("main.yout")];
await circuitAdd.assertOut(w, {
xout: bigInt("6890855772600357754907169075114257697580319025794532037257385534741338397365"),
yout: bigInt("4338620300185947561074059802482547481416142213883829469920100239455078257889")
});
assert(xout.equals(snarkjs.bigInt("6890855772600357754907169075114257697580319025794532037257385534741338397365")));
assert(yout.equals(snarkjs.bigInt("4338620300185947561074059802482547481416142213883829469920100239455078257889")));
});
it("Should add 2 different numbers", async () => {
const input={
x1: snarkjs.bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
y1: snarkjs.bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
x2: snarkjs.bigInt("16540640123574156134436876038791482806971768689494387082833631921987005038935"),
y2: snarkjs.bigInt("20819045374670962167435360035096875258406992893633759881276124905556507972311")
x1: bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
y1: bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
x2: bigInt("16540640123574156134436876038791482806971768689494387082833631921987005038935"),
y2: bigInt("20819045374670962167435360035096875258406992893633759881276124905556507972311")
};
const w = circuitAdd.calculateWitness(input);
const w = await circuitAdd.calculateWitness(input, true);
const xout = w[circuitAdd.getSignalIdx("main.xout")];
const yout = w[circuitAdd.getSignalIdx("main.yout")];
await circuitAdd.assertOut(w, {
xout: bigInt("7916061937171219682591368294088513039687205273691143098332585753343424131937"),
yout: bigInt("14035240266687799601661095864649209771790948434046947201833777492504781204499")
});
/*
console.log(xout.toString());
console.log(yout.toString());
*/
assert(xout.equals(snarkjs.bigInt("7916061937171219682591368294088513039687205273691143098332585753343424131937")));
assert(yout.equals(snarkjs.bigInt("14035240266687799601661095864649209771790948434046947201833777492504781204499")));
});
it("Should check 0 is a valid poiny", async() => {
const w = circuitTest.calculateWitness({x: 0, y:1});
assert(circuitTest.checkWitness(w));
it("Should check (0,1) is a valid point", async() => {
const w = await circuitTest.calculateWitness({x: 0, y:1}, true);
await circuitTest.checkConstraints(w);
});
it("Should check 0 is an invalid poiny", async() => {
it("Should check (1,0) is an invalid point", async() => {
try {
circuitTest.calculateWitness({x: 1, y: 0});
await circuitTest.calculateWitness({x: 1, y: 0}, true);
assert(false, "Should be a valid point");
} catch(err) {
assert.equal(err.message, "Constraint doesn't match: 168700 != 1");
assert(/Constraint\sdoesn't\smatch(.*)168700\s!=\s1/.test(err.message) );
}
});
it("Should extract the public key from the private one", async () => {
it("Should extract the public key from the private one", async () => {
const rawpvk = Buffer.from("0001020304050607080900010203040506070809000102030405060708090021", "hex");
const pvk = eddsa.pruneBuffer(createBlakeHash("blake512").update(rawpvk).digest().slice(0,32));
const S = bigInt.leBuff2int(pvk).shr(3);
const S = utils.leBuff2int(pvk).shiftRight(3);
const A = eddsa.prv2pub(rawpvk);
const input = {
in : S,
Ax : A[0],
Ay : A[1]
}
in : S
};
const w = circuitPbk.calculateWitness(input);
assert(circuitPbk.checkWitness(w));
const w = await circuitPbk.calculateWitness(input, true);
await circuitPbk.assertOut(w, {Ax : A[0], Ay: A[1]});
await circuitPbk.checkConstraints(w);
});
});

View File

@@ -1,7 +1,5 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const bigInt = require("big-integer");
const babyjub = require("../src/babyjub.js");
const assert = chai.assert;
@@ -16,58 +14,68 @@ describe("Baby Jub js test", function () {
it("Should add point (0,1) and (0,1)", () => {
const p1 = [
snarkjs.bigInt(0),
snarkjs.bigInt(1)];
bigInt(0),
bigInt(1)];
const p2 = [
snarkjs.bigInt(0),
snarkjs.bigInt(1)
bigInt(0),
bigInt(1)
];
const out = babyjub.addPoint(p1, p2)
const out = babyjub.addPoint(p1, p2);
assert(out[0].equals(0));
assert(out[1].equals(1));
});
it("Should base be 8*generator", () => {
let res;
res = babyjub.addPoint(babyjub.Generator, babyjub.Generator);
res = babyjub.addPoint(res, res);
res = babyjub.addPoint(res, res);
assert(res[0].equals(babyjub.Base8[0]));
assert(res[1].equals(babyjub.Base8[1]));
});
it("Should add 2 same numbers", () => {
const p1 = [
snarkjs.bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
snarkjs.bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
];
const p2 = [
snarkjs.bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
snarkjs.bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
];
const out = babyjub.addPoint(p1, p2)
assert(out[0].equals(snarkjs.bigInt("6890855772600357754907169075114257697580319025794532037257385534741338397365")));
assert(out[1].equals(snarkjs.bigInt("4338620300185947561074059802482547481416142213883829469920100239455078257889")));
const out = babyjub.addPoint(p1, p2);
assert(out[0].equals(bigInt("6890855772600357754907169075114257697580319025794532037257385534741338397365")));
assert(out[1].equals(bigInt("4338620300185947561074059802482547481416142213883829469920100239455078257889")));
});
it("Should add 2 different numbers", () => {
const p1 = [
snarkjs.bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
snarkjs.bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
];
const p2 = [
snarkjs.bigInt("16540640123574156134436876038791482806971768689494387082833631921987005038935"),
snarkjs.bigInt("20819045374670962167435360035096875258406992893633759881276124905556507972311"),
bigInt("16540640123574156134436876038791482806971768689494387082833631921987005038935"),
bigInt("20819045374670962167435360035096875258406992893633759881276124905556507972311"),
];
const out = babyjub.addPoint(p1, p2)
const out = babyjub.addPoint(p1, p2);
assert(out[0].equals(snarkjs.bigInt("7916061937171219682591368294088513039687205273691143098332585753343424131937")));
assert(out[1].equals(snarkjs.bigInt("14035240266687799601661095864649209771790948434046947201833777492504781204499")));
assert(out[0].equals(bigInt("7916061937171219682591368294088513039687205273691143098332585753343424131937")));
assert(out[1].equals(bigInt("14035240266687799601661095864649209771790948434046947201833777492504781204499")));
});
it("should mulPointEscalar 0", () => {
const p = [
snarkjs.bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
snarkjs.bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
];
const r = babyjub.mulPointEscalar(p, snarkjs.bigInt("3"));
const r = babyjub.mulPointEscalar(p, bigInt("3"));
let r2 = babyjub.addPoint(p, p);
r2 = babyjub.addPoint(r2, p);
assert.equal(r2[0].toString(), r[0].toString());
@@ -78,65 +86,65 @@ describe("Baby Jub js test", function () {
it("should mulPointEscalar 1", () => {
const p = [
snarkjs.bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
snarkjs.bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
];
const r = babyjub.mulPointEscalar(p, snarkjs.bigInt("14035240266687799601661095864649209771790948434046947201833777492504781204499"));
const r = babyjub.mulPointEscalar(p, bigInt("14035240266687799601661095864649209771790948434046947201833777492504781204499"));
assert.equal(r[0].toString(), "17070357974431721403481313912716834497662307308519659060910483826664480189605");
assert.equal(r[1].toString(), "4014745322800118607127020275658861516666525056516280575712425373174125159339");
});
it("should mulPointEscalar 2", () => {
const p = [
snarkjs.bigInt("6890855772600357754907169075114257697580319025794532037257385534741338397365"),
snarkjs.bigInt("4338620300185947561074059802482547481416142213883829469920100239455078257889"),
bigInt("6890855772600357754907169075114257697580319025794532037257385534741338397365"),
bigInt("4338620300185947561074059802482547481416142213883829469920100239455078257889"),
];
const r = babyjub.mulPointEscalar(p, snarkjs.bigInt("20819045374670962167435360035096875258406992893633759881276124905556507972311"));
const r = babyjub.mulPointEscalar(p, bigInt("20819045374670962167435360035096875258406992893633759881276124905556507972311"));
assert.equal(r[0].toString(), "13563888653650925984868671744672725781658357821216877865297235725727006259983");
assert.equal(r[1].toString(), "8442587202676550862664528699803615547505326611544120184665036919364004251662");
});
it("should inCurve 1", () => {
const p = [
snarkjs.bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
snarkjs.bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
];
assert(babyjub.inCurve(p));
});
it("should inCurve 2", () => {
const p = [
snarkjs.bigInt("6890855772600357754907169075114257697580319025794532037257385534741338397365"),
snarkjs.bigInt("4338620300185947561074059802482547481416142213883829469920100239455078257889"),
bigInt("6890855772600357754907169075114257697580319025794532037257385534741338397365"),
bigInt("4338620300185947561074059802482547481416142213883829469920100239455078257889"),
];
assert(babyjub.inCurve(p));
});
it("should inSubgroup 1", () => {
const p = [
snarkjs.bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
snarkjs.bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
];
assert(babyjub.inSubgroup(p));
});
it("should inSubgroup 2", () => {
const p = [
snarkjs.bigInt("6890855772600357754907169075114257697580319025794532037257385534741338397365"),
snarkjs.bigInt("4338620300185947561074059802482547481416142213883829469920100239455078257889"),
bigInt("6890855772600357754907169075114257697580319025794532037257385534741338397365"),
bigInt("4338620300185947561074059802482547481416142213883829469920100239455078257889"),
];
assert(babyjub.inSubgroup(p));
});
it("should packPoint - unpackPoint 1", () => {
const p = [
snarkjs.bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
snarkjs.bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475"),
];
const buf = babyjub.packPoint(p);
assert.equal(buf.toString('hex'), '53b81ed5bffe9545b54016234682e7b2f699bd42a5e9eae27ff4051bc698ce85');
assert.equal(buf.toString("hex"), "53b81ed5bffe9545b54016234682e7b2f699bd42a5e9eae27ff4051bc698ce85");
const p2 = babyjub.unpackPoint(buf);
assert.equal(p2[0].toString(), "17777552123799933955779906779655732241715742912184938656739573121738514868268");
assert.equal(p2[1].toString(), "2626589144620713026669568689430873010625803728049924121243784502389097019475");
@@ -144,11 +152,11 @@ describe("Baby Jub js test", function () {
it("should packPoint - unpackPoint 2", () => {
const p = [
snarkjs.bigInt("6890855772600357754907169075114257697580319025794532037257385534741338397365"),
snarkjs.bigInt("4338620300185947561074059802482547481416142213883829469920100239455078257889"),
bigInt("6890855772600357754907169075114257697580319025794532037257385534741338397365"),
bigInt("4338620300185947561074059802482547481416142213883829469920100239455078257889"),
];
const buf = babyjub.packPoint(p);
assert.equal(buf.toString('hex'), 'e114eb17eddf794f063a68fecac515e3620e131976108555735c8b0773929709');
assert.equal(buf.toString("hex"), "e114eb17eddf794f063a68fecac515e3620e131976108555735c8b0773929709");
const p2 = babyjub.unpackPoint(buf);
assert.equal(p2[0].toString(), "6890855772600357754907169075114257697580319025794532037257385534741338397365");
assert.equal(p2[1].toString(), "4338620300185947561074059802482547481416142213883829469920100239455078257889");

View File

@@ -1,55 +1,50 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
const bigInt = require("big-integer");
const tester = require("circom").tester;
function print(circuit, w, s) {
console.log(s + ": " + w[circuit.getSignalIdx(s)]);
}
function checkSub(_a,_b, circuit) {
async function checkSub(_a,_b, circuit) {
let a=bigInt(_a);
let b=bigInt(_b);
if (a.lesser(bigInt.zero)) a = a.add(bigInt.one.shl(16));
if (b.lesser(bigInt.zero)) b = b.add(bigInt.one.shl(16));
const w = circuit.calculateWitness({a: a, b: b});
if (a.lesser(bigInt.zero)) a = a.add(bigInt.one.shiftLeft(16));
if (b.lesser(bigInt.zero)) b = b.add(bigInt.one.shiftLeft(16));
const w = await circuit.calculateWitness({a: a, b: b}, true);
let res = a.sub(b);
if (res.lesser(bigInt.zero)) res = res.add(bigInt.one.shl(16));
assert( w[circuit.getSignalIdx("main.out")].equals(bigInt(res)) );
let res = a.minus(b);
if (res.lesser(bigInt.zero)) res = res.add(bigInt.one.shiftLeft(16));
await circuit.assertOut(w, {out: bigInt(res)});
}
describe("BinSub test", () => {
describe("BinSub test", function () {
this.timeout(100000);
let circuit;
before( async() => {
const cirDef = await compiler(path.join(__dirname, "circuits", "binsub_test.circom"));
circuit = new snarkjs.Circuit(cirDef);
console.log("NConstrains BinSub: " + circuit.nConstraints);
circuit = await tester(path.join(__dirname, "circuits", "binsub_test.circom"));
});
it("Should check variuos ege cases", async () => {
checkSub(0,0, circuit);
checkSub(1,0, circuit);
checkSub(-1,0, circuit);
checkSub(2,1, circuit);
checkSub(2,2, circuit);
checkSub(2,3, circuit);
checkSub(2,-1, circuit);
checkSub(2,-2, circuit);
checkSub(2,-3, circuit);
checkSub(-2,-3, circuit);
checkSub(-2,-2, circuit);
checkSub(-2,-1, circuit);
checkSub(-2,0, circuit);
checkSub(-2,1, circuit);
checkSub(-2,2, circuit);
checkSub(-2,3, circuit);
await checkSub(0,0, circuit);
await checkSub(1,0, circuit);
await checkSub(-1,0, circuit);
await checkSub(2,1, circuit);
await checkSub(2,2, circuit);
await checkSub(2,3, circuit);
await checkSub(2,-1, circuit);
await checkSub(2,-2, circuit);
await checkSub(2,-3, circuit);
await checkSub(-2,-3, circuit);
await checkSub(-2,-2, circuit);
await checkSub(-2,-1, circuit);
await checkSub(-2,0, circuit);
await checkSub(-2,1, circuit);
await checkSub(-2,2, circuit);
await checkSub(-2,3, circuit);
});

View File

@@ -1,35 +1,37 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const crypto = require("crypto");
const compiler = require("circom");
const tester = require("circom").tester;
const bigInt = require("big-integer");
const assert = chai.assert;
describe("Sum test", () => {
describe("Binary sum test", function () {
this.timeout(100000000);
it("Should create a constant circuit", async () => {
const circuit = await tester(path.join(__dirname, "circuits", "constants_test.circom"));
await circuit.loadConstraints();
const cirDef = await compiler(path.join(__dirname, "circuits", "constants_test.circom"));
assert.equal(cirDef.nVars, 2);
assert.equal(circuit.nVars, 2);
assert.equal(circuit.constraints.length, 1);
const circuit = new snarkjs.Circuit(cirDef);
const witness = await circuit.calculateWitness({ "in": bigInt("d807aa98", 16)}, true);
const witness = circuit.calculateWitness({ "in": "0xd807aa98" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt("0xd807aa98")));
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt("d807aa98", 16)));
});
it("Should create a sum circuit", async () => {
const circuit = await tester(path.join(__dirname, "circuits", "sum_test.circom"));
await circuit.loadConstraints();
const cirDef = await compiler(path.join(__dirname, "circuits", "sum_test.circom"));
assert.equal(cirDef.nVars, 101);
assert.equal(circuit.constraints.length, 97); // 32 (in1) + 32(in2) + 32(out) + 1 (carry)
const circuit = new snarkjs.Circuit(cirDef);
const witness = await circuit.calculateWitness({ "a": "111", "b": "222" }, true);
const witness = circuit.calculateWitness({ "a": "111", "b": "222" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt("333")));
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt("333")));
});
});

View File

@@ -6,6 +6,8 @@ template A() {
signal input b;
signal output out;
var i;
component n2ba = Num2Bits(16);
component n2bb = Num2Bits(16);
component sub = BinSub(16);
@@ -14,9 +16,12 @@ template A() {
n2ba.in <== a;
n2bb.in <== b;
for (var i=0; i<16; i++) {
for (i=0; i<16; i++) {
sub.in[0][i] <== n2ba.out[i];
sub.in[1][i] <== n2bb.out[i];
}
for (i=0; i<16; i++) {
b2n.in[i] <== sub.out[i];
}

View File

@@ -7,8 +7,8 @@ template Main() {
var i;
var base = [17777552123799933955779906779655732241715742912184938656739573121738514868268,
2626589144620713026669568689430873010625803728049924121243784502389097019475]
var base = [5299619240641551281634865583518297030282874472190772894086521144482721001553,
16950150798460657717958625567821834550301663161624707787222815936182638968203];
component escalarMul = EscalarMul(256, base);

View File

@@ -6,8 +6,8 @@ template Main() {
signal input in;
signal output out[2];
var base = [17777552123799933955779906779655732241715742912184938656739573121738514868268,
2626589144620713026669568689430873010625803728049924121243784502389097019475]
var base[2] = [5299619240641551281634865583518297030282874472190772894086521144482721001553,
16950150798460657717958625567821834550301663161624707787222815936182638968203];
component n2b = Num2Bits(253);

View File

@@ -7,8 +7,8 @@ template Main() {
var i;
var base = [17777552123799933955779906779655732241715742912184938656739573121738514868268,
2626589144620713026669568689430873010625803728049924121243784502389097019475]
var base[2] = [5299619240641551281634865583518297030282874472190772894086521144482721001553,
16950150798460657717958625567821834550301663161624707787222815936182638968203];
component escalarMul = EscalarMul(256, base);

View File

@@ -6,8 +6,8 @@ template Main() {
signal input e;
signal output out[2];
var base = [17777552123799933955779906779655732241715742912184938656739573121738514868268,
2626589144620713026669568689430873010625803728049924121243784502389097019475]
var base[2] = [5299619240641551281634865583518297030282874472190772894086521144482721001553,
16950150798460657717958625567821834550301663161624707787222815936182638968203]
component n2b = Num2Bits(253);

View File

@@ -1,6 +1,6 @@
include "../../circuits/escalarmulw4table.circom";
var base = [17777552123799933955779906779655732241715742912184938656739573121738514868268,
2626589144620713026669568689430873010625803728049924121243784502389097019475]
var base[2] = [5299619240641551281634865583518297030282874472190772894086521144482721001553,
16950150798460657717958625567821834550301663161624707787222815936182638968203]
component main = EscalarMulW4Table(base, 0);

View File

@@ -1,6 +1,17 @@
include "../../circuits/escalarmulw4table.circom";
var base = [17777552123799933955779906779655732241715742912184938656739573121738514868268,
2626589144620713026669568689430873010625803728049924121243784502389097019475];
component main = EscalarMulW4Table(base, 0);
template Main() {
signal input in;
signal output out[16][2];
var base[2] = [5299619240641551281634865583518297030282874472190772894086521144482721001553,
16950150798460657717958625567821834550301663161624707787222815936182638968203];
var escalarMul[16][2] = EscalarMulW4Table(base, 0);
for (var i=0; i<16; i++) {
out[i][0] <== escalarMul[i][0]*in;
out[i][1] <== escalarMul[i][1]*in;
}
}
component main = Main();

View File

@@ -1,6 +1,17 @@
include "../../circuits/escalarmulw4table.circom";
var base = [17777552123799933955779906779655732241715742912184938656739573121738514868268,
2626589144620713026669568689430873010625803728049924121243784502389097019475]
component main = EscalarMulW4Table(base, 3);
template Main() {
signal input in;
signal output out[16][2];
var base[2] = [5299619240641551281634865583518297030282874472190772894086521144482721001553,
16950150798460657717958625567821834550301663161624707787222815936182638968203];
var escalarMul[16][2] = EscalarMulW4Table(base, 3);
for (var i=0; i<16; i++) {
out[i][0] <== escalarMul[i][0]*in;
out[i][1] <== escalarMul[i][1]*in;
}
}
component main = Main();

258
test/circuits/in.json Normal file
View File

@@ -0,0 +1,258 @@
{
"in": [
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1",
"1"
]
}

View File

@@ -0,0 +1,3 @@
include "../../circuits/poseidon.circom"
component main = Poseidon(2, 3, 8, 57);

View File

@@ -0,0 +1,3 @@
include "../../circuits/sha256/sha256.circom";
component main = Sha256(448);

View File

@@ -0,0 +1,3 @@
include "../../circuits/sha256/sha256.circom";
component main = Sha256(512);

View File

@@ -6,6 +6,8 @@ template A() {
signal input b;
signal output out;
var i;
component n2ba = Num2Bits(32);
component n2bb = Num2Bits(32);
component sum = BinSum(32,2);
@@ -14,9 +16,12 @@ template A() {
n2ba.in <== a;
n2bb.in <== b;
for (var i=0; i<32; i++) {
for (i=0; i<32; i++) {
sum.in[0][i] <== n2ba.out[i];
sum.in[1][i] <== n2bb.out[i];
}
for (i=0; i<32; i++) {
b2n.in[i] <== sum.out[i];
}

View File

@@ -1,193 +1,184 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const crypto = require("crypto");
const compiler = require("circom");
const tester = require("circom").tester;
const bigInt = require("big-integer");
const assert = chai.assert;
describe("Sum test", () => {
it("Should create a iszero circuit", async() => {
const cirDef = await compiler(path.join(__dirname, "circuits", "iszero.circom"));
describe("Comparators test", function () {
const circuit = new snarkjs.Circuit(cirDef);
this.timeout(100000);
it("Should create a iszero circuit", async() => {
const circuit = await tester(path.join(__dirname, "circuits", "iszero.circom"));
let witness;
witness = circuit.calculateWitness({ "in": 111});
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
witness = await circuit.calculateWitness({ "in": 111}, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(0)));
witness = circuit.calculateWitness({ "in": 0 });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(1)));
witness = await circuit.calculateWitness({ "in": 0 }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(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);
const circuit = await tester(path.join(__dirname, "circuits", "isequal.circom"));
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 = await circuit.calculateWitness({ "in": [111,222] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(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)));
witness = await circuit.calculateWitness({ "in": [444,444] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(1)));
});
it("Should create a comparison lessthan", async() => {
const cirDef = await compiler(path.join(__dirname, "circuits", "lessthan.circom"));
const circuit = new snarkjs.Circuit(cirDef);
const circuit = await tester(path.join(__dirname, "circuits", "lessthan.circom"));
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 = await circuit.calculateWitness({ "in": [333,444] }), true;
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(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 = await circuit.calculateWitness({ "in":[1,1] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(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 = await circuit.calculateWitness({ "in": [661, 660] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(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 = await circuit.calculateWitness({ "in": [0, 1] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(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 = await circuit.calculateWitness({ "in": [0, 444] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(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 = await circuit.calculateWitness({ "in": [1, 0] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(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 = await circuit.calculateWitness({ "in": [555, 0] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(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)));
witness = await circuit.calculateWitness({ "in": [0, 0] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(0)));
});
it("Should create a comparison lesseqthan", async() => {
const cirDef = await compiler(path.join(__dirname, "circuits", "lesseqthan.circom"));
const circuit = new snarkjs.Circuit(cirDef);
const circuit = await tester(path.join(__dirname, "circuits", "lesseqthan.circom"));
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 = await circuit.calculateWitness({ "in": [333,444] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(1)));
witness = circuit.calculateWitness({ "in[0]": "1", "in[1]": "1" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(1)));
witness = await circuit.calculateWitness({ "in":[1,1] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(1)));
witness = circuit.calculateWitness({ "in[0]": "661", "in[1]": "660" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
witness = await circuit.calculateWitness({ "in": [661, 660] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(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 = await circuit.calculateWitness({ "in": [0, 1] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(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 = await circuit.calculateWitness({ "in": [0, 444] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(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 = await circuit.calculateWitness({ "in": [1, 0] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(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 = await circuit.calculateWitness({ "in": [555, 0] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(0)));
witness = circuit.calculateWitness({ "in[0]": "0", "in[1]": "0" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(1)));
witness = await circuit.calculateWitness({ "in": [0, 0] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(1)));
});
it("Should create a comparison greaterthan", async() => {
const cirDef = await compiler(path.join(__dirname, "circuits", "greaterthan.circom"));
const circuit = new snarkjs.Circuit(cirDef);
const circuit = await tester(path.join(__dirname, "circuits", "greaterthan.circom"));
let witness;
witness = circuit.calculateWitness({ "in[0]": "333", "in[1]": "444" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
witness = await circuit.calculateWitness({ "in": [333,444] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(0)));
witness = circuit.calculateWitness({ "in[0]": "1", "in[1]": "1" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
witness = await circuit.calculateWitness({ "in":[1,1] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(0)));
witness = circuit.calculateWitness({ "in[0]": "661", "in[1]": "660" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(1)));
witness = await circuit.calculateWitness({ "in": [661, 660] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(1)));
witness = circuit.calculateWitness({ "in[0]": "0", "in[1]": "1" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
witness = await circuit.calculateWitness({ "in": [0, 1] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(0)));
witness = circuit.calculateWitness({ "in[0]": "0", "in[1]": "444" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
witness = await circuit.calculateWitness({ "in": [0, 444] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(0)));
witness = circuit.calculateWitness({ "in[0]": "1", "in[1]": "0" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(1)));
witness = await circuit.calculateWitness({ "in": [1, 0] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(1)));
witness = circuit.calculateWitness({ "in[0]": "555", "in[1]": "0" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(1)));
witness = await circuit.calculateWitness({ "in": [555, 0] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(1)));
witness = circuit.calculateWitness({ "in[0]": "0", "in[1]": "0" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
witness = await circuit.calculateWitness({ "in": [0, 0] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(0)));
});
it("Should create a comparison greatereqthan", async() => {
const cirDef = await compiler(path.join(__dirname, "circuits", "greatereqthan.circom"));
const circuit = new snarkjs.Circuit(cirDef);
console.log("NConstraints BalancesUpdater: " + circuit.nConstraints);
const circuit = await tester(path.join(__dirname, "circuits", "greatereqthan.circom"));
let witness;
witness = circuit.calculateWitness({ "in[0]": "333", "in[1]": "444" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
witness = await circuit.calculateWitness({ "in": [333,444] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(0)));
witness = circuit.calculateWitness({ "in[0]": "1", "in[1]": "1" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(1)));
witness = await circuit.calculateWitness({ "in":[1,1] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(1)));
witness = circuit.calculateWitness({ "in[0]": "661", "in[1]": "660" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(1)));
witness = await circuit.calculateWitness({ "in": [661, 660] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(1)));
witness = circuit.calculateWitness({ "in[0]": "0", "in[1]": "1" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
witness = await circuit.calculateWitness({ "in": [0, 1] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(0)));
witness = circuit.calculateWitness({ "in[0]": "0", "in[1]": "444" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(0)));
witness = await circuit.calculateWitness({ "in": [0, 444] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(0)));
witness = circuit.calculateWitness({ "in[0]": "1", "in[1]": "0" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(1)));
witness = await circuit.calculateWitness({ "in": [1, 0] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(1)));
witness = circuit.calculateWitness({ "in[0]": "555", "in[1]": "0" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(1)));
witness = await circuit.calculateWitness({ "in": [555, 0] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(1)));
witness = circuit.calculateWitness({ "in[0]": "0", "in[1]": "0" });
assert(witness[0].equals(snarkjs.bigInt(1)));
assert(witness[1].equals(snarkjs.bigInt(1)));
witness = await circuit.calculateWitness({ "in": [0, 0] }, true);
assert(witness[0].equals(bigInt(1)));
assert(witness[1].equals(bigInt(1)));
});
});

View File

@@ -1,16 +1,14 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
// const crypto = require("crypto");
const tester = require("circom").tester;
const bigInt = require("big-integer");
const eddsa = require("../src/eddsa.js");
const babyJub = require("../src/babyjub.js");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
function print(circuit, w, s) {
console.log(s + ": " + w[circuit.getSignalIdx(s)]);
}
@@ -36,11 +34,7 @@ describe("EdDSA test", function () {
this.timeout(100000);
before( async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "eddsa_test.circom"));
circuit = new snarkjs.Circuit(cirDef);
console.log("NConstrains EdDSA: " + circuit.nConstraints);
circuit = await tester(path.join(__dirname, "circuits", "eddsa_test.circom"));
});
it("Sign a single 10 bytes from 0 to 9", async () => {
@@ -66,9 +60,8 @@ describe("EdDSA test", function () {
const sBits = buffer2bits(pSignature.slice(32, 64));
const aBits = buffer2bits(pPubKey);
const w = circuit.calculateWitness({A: aBits, R8: r8Bits, S: sBits, msg: msgBits});
assert(circuit.checkWitness(w));
const w = await circuit.calculateWitness({A: aBits, R8: r8Bits, S: sBits, msg: msgBits}, true);
await circuit.checkConstraints(w);
});
});

View File

@@ -1,20 +1,20 @@
const chai = require("chai");
const snarkjs = require("snarkjs");
const eddsa = require("../src/eddsa.js");
const babyJub = require("../src/babyjub.js");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
const bigInt = require("big-integer");
const utils = require("../src/utils.js");
describe("EdDSA js test", function () {
this.timeout(100000);
it("Sign a single 10 bytes from 0 to 9", () => {
it("Sign (using Mimc7) a single 10 bytes from 0 to 9", () => {
const msgBuf = Buffer.from("00010203040506070809", "hex");
const msg = bigInt.leBuff2int(msgBuf);
const msg = utils.leBuff2int(msgBuf);
// const prvKey = crypto.randomBytes(32);
@@ -23,27 +23,60 @@ describe("EdDSA js test", function () {
const pubKey = eddsa.prv2pub(prvKey);
assert.equal(pubKey[0].toString(),
"2610057752638682202795145288373380503107623443963127956230801721756904484787");
"13277427435165878497778222415993513565335242147425444199013288855685581939618");
assert.equal(pubKey[1].toString(),
"16617171478497210597712478520507818259149717466230047843969353176573634386897");
"13622229784656158136036771217484571176836296686641868549125388198837476602820");
const pPubKey = babyJub.packPoint(pubKey);
const signature = eddsa.signMiMC(prvKey, msg);
assert.equal(signature.R8[0].toString(),
"4974729414807584049518234760796200867685098748448054182902488636762478901554");
"11384336176656855268977457483345535180380036354188103142384839473266348197733");
assert.equal(signature.R8[1].toString(),
"18714049394522540751536514815950425694461287643205706667341348804546050128733");
"15383486972088797283337779941324724402501462225528836549661220478783371668959");
assert.equal(signature.S.toString(),
"2171284143457722024136077617757713039502332290425057126942676527240038689549");
"2523202440825208709475937830811065542425109372212752003460238913256192595070");
const pSignature = eddsa.packSignature(signature);
assert.equal(pSignature.toString("hex"), ""+
"5dfb6f843c023fe3e52548ccf22e55c81b426f7af81b4f51f7152f2fcfc65f29"+
"0dab19c5a0a75973cd75a54780de0c3a41ede6f57396fe99b5307fff3ce7cc04");
"dfedb4315d3f2eb4de2d3c510d7a987dcab67089c8ace06308827bf5bcbe02a2"+
"7ed40dab29bf993c928e789d007387998901a24913d44fddb64b1f21fc149405");
const uSignature = eddsa.unpackSignature(pSignature);
assert(eddsa.verifyMiMC(msg, uSignature, pubKey));
});
it("Sign (using Poseidon) a single 10 bytes from 0 to 9", () => {
const msgBuf = Buffer.from("00010203040506070809", "hex");
const msg = utils.leBuff2int(msgBuf);
const prvKey = Buffer.from("0001020304050607080900010203040506070809000102030405060708090001", "hex");
const pubKey = eddsa.prv2pub(prvKey);
assert.equal(pubKey[0].toString(),
"13277427435165878497778222415993513565335242147425444199013288855685581939618");
assert.equal(pubKey[1].toString(),
"13622229784656158136036771217484571176836296686641868549125388198837476602820");
const pPubKey = babyJub.packPoint(pubKey);
const signature = eddsa.signPoseidon(prvKey, msg);
assert.equal(signature.R8[0].toString(),
"11384336176656855268977457483345535180380036354188103142384839473266348197733");
assert.equal(signature.R8[1].toString(),
"15383486972088797283337779941324724402501462225528836549661220478783371668959");
assert.equal(signature.S.toString(),
"248298168863866362217836334079793350221620631973732197668910946177382043688");
const pSignature = eddsa.packSignature(signature);
assert.equal(pSignature.toString("hex"), ""+
"dfedb4315d3f2eb4de2d3c510d7a987dcab67089c8ace06308827bf5bcbe02a2"+
"28506bce274aa1b3f7e7c2fd7e4fe09bff8f9aa37a42def7994e98f322888c00");
const uSignature = eddsa.unpackSignature(pSignature);
assert(eddsa.verifyPoseidon(msg, uSignature, pubKey));
});
});

View File

@@ -1,25 +1,20 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const tester = require("circom").tester;
const bigInt = require("big-integer");
const eddsa = require("../src/eddsa.js");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
describe("EdDSA MiMC test", function () {
let circuit;
this.timeout(100000);
before( async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "eddsamimc_test.circom"));
circuit = new snarkjs.Circuit(cirDef);
console.log("NConstrains EdDSA MiMC: " + circuit.nConstraints);
circuit = await tester(path.join(__dirname, "circuits", "eddsamimc_test.circom"));
});
it("Sign a single number", async () => {
@@ -33,16 +28,18 @@ describe("EdDSA MiMC test", function () {
assert(eddsa.verifyMiMC(msg, signature, pubKey));
const w = circuit.calculateWitness({
const w = await circuit.calculateWitness({
enabled: 1,
Ax: pubKey[0],
Ay: pubKey[1],
R8x: signature.R8[0],
R8y: signature.R8[1],
S: signature.S,
M: msg});
M: msg}, true);
await circuit.checkConstraints(w);
assert(circuit.checkWitness(w));
});
it("Detect Invalid signature", async () => {
@@ -57,17 +54,17 @@ describe("EdDSA MiMC test", function () {
assert(eddsa.verifyMiMC(msg, signature, pubKey));
try {
const w = circuit.calculateWitness({
const w = await circuit.calculateWitness({
enabled: 1,
Ax: pubKey[0],
Ay: pubKey[1],
R8x: signature.R8[0].add(bigInt(1)),
R8y: signature.R8[1],
S: signature.S,
M: msg});
M: msg}, true);
assert(false);
} catch(err) {
assert.equal(err.message, "Constraint doesn't match: 1 != 0");
assert(/Constraint\sdoesn't\smatch(.*)1\s!=\s0/.test(err.message) );
}
});
@@ -84,15 +81,16 @@ describe("EdDSA MiMC test", function () {
assert(eddsa.verifyMiMC(msg, signature, pubKey));
const w = circuit.calculateWitness({
const w = await circuit.calculateWitness({
enabled: 0,
Ax: pubKey[0],
Ay: pubKey[1],
R8x: signature.R8[0].add(bigInt(1)),
R8y: signature.R8[1],
S: signature.S,
M: msg});
M: msg}, true);
await circuit.checkConstraints(w);
assert(circuit.checkWitness(w));
});
});

View File

@@ -1,25 +1,21 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const bigInt = require("big-integer");
const tester = require("circom").tester;
const eddsa = require("../src/eddsa.js");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
describe("EdDSA Poseidon test", function () {
let circuit;
this.timeout(100000);
before( async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "eddsaposeidon_test.circom"));
circuit = new snarkjs.Circuit(cirDef);
circuit = await tester(path.join(__dirname, "circuits", "eddsaposeidon_test.circom"));
console.log("NConstrains EdDSA Poseidon: " + circuit.nConstraints);
});
it("Sign a single number", async () => {
@@ -33,16 +29,21 @@ describe("EdDSA Poseidon test", function () {
assert(eddsa.verifyPoseidon(msg, signature, pubKey));
const w = circuit.calculateWitness({
const input = {
enabled: 1,
Ax: pubKey[0],
Ay: pubKey[1],
R8x: signature.R8[0],
R8y: signature.R8[1],
S: signature.S,
M: msg});
M: msg
};
assert(circuit.checkWitness(w));
// console.log(JSON.stringify(utils.stringifyBigInts(input)));
const w = await circuit.calculateWitness(input, true);
await circuit.checkConstraints(w);
});
it("Detect Invalid signature", async () => {
@@ -57,17 +58,17 @@ describe("EdDSA Poseidon test", function () {
assert(eddsa.verifyPoseidon(msg, signature, pubKey));
try {
circuit.calculateWitness({
await circuit.calculateWitness({
enabled: 1,
Ax: pubKey[0],
Ay: pubKey[1],
R8x: signature.R8[0].add(bigInt(1)),
R8y: signature.R8[1],
S: signature.S,
M: msg});
M: msg}, true);
assert(false);
} catch(err) {
assert.equal(err.message, "Constraint doesn't match: 1 != 0");
assert(/Constraint\sdoesn't\smatch(.*)1\s!=\s0/.test(err.message) );
}
});
@@ -84,15 +85,15 @@ describe("EdDSA Poseidon test", function () {
assert(eddsa.verifyPoseidon(msg, signature, pubKey));
const w = circuit.calculateWitness({
const w = await circuit.calculateWitness({
enabled: 0,
Ax: pubKey[0],
Ay: pubKey[1],
R8x: signature.R8[0].add(bigInt(1)),
R8y: signature.R8[1],
S: signature.S,
M: msg});
M: msg}, true);
assert(circuit.checkWitness(w));
await circuit.checkConstraints(w);
});
});

View File

@@ -1,168 +1,114 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const bigInt = require("big-integer");
const tester = require("circom").tester;
const babyJub = require("../src/babyjub.js");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
const q=bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
function addPoint(a,b) {
const cta = bigInt("168700");
const d = bigInt("168696");
const res = [];
res[0] = bigInt((a[0]*b[1] + b[0]*a[1]) * bigInt(bigInt.one + d*a[0]*b[0]*a[1]*b[1]).inverse(q)).affine(q);
res[1] = bigInt((a[1]*b[1] - cta*a[0]*b[0]) * bigInt(bigInt.one - d*a[0]*b[0]*a[1]*b[1]).inverse(q)).affine(q);
return res;
}
function print(circuit, w, s) {
console.log(s + ": " + w[circuit.getSignalIdx(s)]);
}
describe("Exponentioation test", () => {
describe("Exponentioation test", function () {
this.timeout(100000);
it("Should generate the Exponentiation table in k=0", async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "escalarmulw4table_test.circom"));
const circuit = await tester(path.join(__dirname, "circuits", "escalarmulw4table_test.circom"));
// console.log(JSON.stringify(cirDef, null, 1));
const w = await circuit.calculateWitness({in: 1});
// assert.equal(cirDef.nVars, 2);
await circuit.checkConstraints(w);
const circuit = new snarkjs.Circuit(cirDef);
let g = [
bigInt("5299619240641551281634865583518297030282874472190772894086521144482721001553"),
bigInt("16950150798460657717958625567821834550301663161624707787222815936182638968203")
];
console.log("NConstrains: " + circuit.nConstraints);
let dbl= [bigInt("0"), bigInt("1")];
const w = circuit.calculateWitness({});
let g = [bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475")]
dbl= [bigInt("0"), snarkjs.bigInt("1")];
const expectedOut = [];
for (let i=0; i<16; i++) {
const xout1 = w[circuit.getSignalIdx(`main.out[${i}][0]`)];
const yout1 = w[circuit.getSignalIdx(`main.out[${i}][1]`)];
/*
console.log(xout1.toString());
console.log(yout1.toString());
console.log(dbl[0]);
console.log(dbl[1]);
*/
assert(xout1.equals(dbl[0]));
assert(yout1.equals(dbl[1]));
dbl = addPoint([xout1, yout1],g);
expectedOut.push(dbl);
dbl = babyJub.addPoint(dbl,g);
}
await circuit.assertOut(w, {out: expectedOut});
});
it("Should generate the Exponentiation table in k=3", async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "escalarmulw4table_test3.circom"));
const circuit = await tester(path.join(__dirname, "circuits", "escalarmulw4table_test3.circom"));
// console.log(JSON.stringify(cirDef, null, 1));
const w = await circuit.calculateWitness({in: 1});
// assert.equal(cirDef.nVars, 2);
await circuit.checkConstraints(w);
const circuit = new snarkjs.Circuit(cirDef);
console.log("NConstrains: " + circuit.nConstraints);
const w = circuit.calculateWitness({});
let g = [snarkjs.bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
snarkjs.bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475")]
let g = [
bigInt("5299619240641551281634865583518297030282874472190772894086521144482721001553"),
bigInt("16950150798460657717958625567821834550301663161624707787222815936182638968203")
];
for (let i=0; i<12;i++) {
g = addPoint(g,g);
g = babyJub.addPoint(g,g);
}
dbl= [snarkjs.bigInt("0"), snarkjs.bigInt("1")];
let dbl= [bigInt("0"), bigInt("1")];
const expectedOut = [];
for (let i=0; i<16; i++) {
const xout1 = w[circuit.getSignalIdx(`main.out[${i}][0]`)];
const yout1 = w[circuit.getSignalIdx(`main.out[${i}][1]`)];
expectedOut.push(dbl);
/*
console.log(xout1.toString());
console.log(yout1.toString());
console.log(dbl[0]);
console.log(dbl[1]);
*/
assert(xout1.equals(dbl[0]));
assert(yout1.equals(dbl[1]));
dbl = addPoint([xout1, yout1],g);
dbl = babyJub.addPoint(dbl,g);
}
await circuit.assertOut(w, {out: expectedOut});
});
it("Should exponentiate g^31", async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "escalarmul_test.circom"));
// console.log(JSON.stringify(cirDef, null, 1));
const circuit = await tester(path.join(__dirname, "circuits", "escalarmul_test.circom"));
// assert.equal(cirDef.nVars, 2);
const w = await circuit.calculateWitness({"in": 31});
const circuit = new snarkjs.Circuit(cirDef);
await circuit.checkConstraints(w);
console.log("NConstrains: " + circuit.nConstraints);
let g = [
bigInt("5299619240641551281634865583518297030282874472190772894086521144482721001553"),
bigInt("16950150798460657717958625567821834550301663161624707787222815936182638968203")
];
const w = circuit.calculateWitness({"in": 31});
assert(circuit.checkWitness(w));
let g = [snarkjs.bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
snarkjs.bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475")]
let c = [0n, 1n];
let c = [bigInt(0), bigInt(1)];
for (let i=0; i<31;i++) {
c = addPoint(c,g);
c = babyJub.addPoint(c,g);
}
const xout = w[circuit.getSignalIdx(`main.out[0]`)];
const yout = w[circuit.getSignalIdx(`main.out[1]`)];
await circuit.assertOut(w, {out: c});
/*
console.log(xout.toString());
console.log(yout.toString());
*/
assert(xout.equals(c[0]));
assert(yout.equals(c[1]));
console.log("-------")
const w2 = circuit.calculateWitness({"in": (1n<<252n)+1n});
const xout2 = w2[circuit.getSignalIdx(`main.out[0]`)];
const yout2 = w2[circuit.getSignalIdx(`main.out[1]`)];
const w2 = await circuit.calculateWitness({"in": bigInt(1).shiftLeft(252).add(bigInt.one)});
c = [g[0], g[1]];
for (let i=0; i<252;i++) {
c = addPoint(c,c);
c = babyJub.addPoint(c,c);
}
c = addPoint(c,g);
/*
console.log(xout2.toString());
console.log(yout2.toString());
console.log(c[0].toString());
console.log(c[1].toString());
*/
assert(xout2.equals(c[0]));
assert(yout2.equals(c[1]));
c = babyJub.addPoint(c,g);
await circuit.assertOut(w2, {out: c});
}).timeout(10000000);
it("Number of constrains for 256 bits", async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "escalarmul_test_min.circom"));
const circuit = new snarkjs.Circuit(cirDef);
const circuit = await tester(path.join(__dirname, "circuits", "escalarmul_test_min.circom"));
console.log("NConstrains: " + circuit.nConstraints);
}).timeout(10000000);
});

View File

@@ -1,12 +1,7 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
const bigInt = require("big-integer");
const tester = require("circom").tester;
function print(circuit, w, s) {
console.log(s + ": " + w[circuit.getSignalIdx(s)]);
@@ -18,41 +13,33 @@ describe("Escalarmul test", function () {
this.timeout(100000);
let g = [
snarkjs.bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
snarkjs.bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475")
bigInt("5299619240641551281634865583518297030282874472190772894086521144482721001553"),
bigInt("16950150798460657717958625567821834550301663161624707787222815936182638968203")
];
before( async() => {
const cirDefEMulAny = await compiler(path.join(__dirname, "circuits", "escalarmulany_test.circom"));
circuitEMulAny = new snarkjs.Circuit(cirDefEMulAny);
console.log("NConstrains Escalarmul any: " + circuitEMulAny.nConstraints);
circuitEMulAny = await tester(path.join(__dirname, "circuits", "escalarmulany_test.circom"));
});
it("Should generate Same escalar mul", async () => {
const w = circuitEMulAny.calculateWitness({"e": 1, "p": g});
const w = await circuitEMulAny.calculateWitness({"e": 1, "p": g});
assert(circuitEMulAny.checkWitness(w));
await circuitEMulAny.checkConstraints(w);
const xout = w[circuitEMulAny.getSignalIdx("main.out[0]")];
const yout = w[circuitEMulAny.getSignalIdx("main.out[1]")];
await circuitEMulAny.assertOut(w, {out: g}, true);
assert(xout.equals(g[0]));
assert(yout.equals(g[1]));
});
it("If multiply by order should return 0", async () => {
const r = bigInt("2736030358979909402780800718157159386076813972158567259200215660948447373041");
const w = circuitEMulAny.calculateWitness({"e": r, "p": g});
const w = await circuitEMulAny.calculateWitness({"e": r, "p": g});
assert(circuitEMulAny.checkWitness(w));
await circuitEMulAny.checkConstraints(w);
const xout = w[circuitEMulAny.getSignalIdx("main.out[0]")];
const yout = w[circuitEMulAny.getSignalIdx("main.out[1]")];
await circuitEMulAny.assertOut(w, {out: [0,1]}, true);
assert(xout.equals(bigInt.zero));
assert(yout.equals(bigInt.one));
});
});

View File

@@ -1,14 +1,11 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const bigInt = require("big-integer");
const tester = require("circom").tester;
const babyjub = require("../src/babyjub");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
function print(circuit, w, s) {
console.log(s + ": " + w[circuit.getSignalIdx(s)]);
}
@@ -19,48 +16,74 @@ describe("Escalarmul test", function () {
this.timeout(100000);
before( async() => {
const cirDef = await compiler(path.join(__dirname, "circuits", "escalarmulfix_test.circom"));
circuit = new snarkjs.Circuit(cirDef);
console.log("NConstrains Escalarmul fix: " + circuit.nConstraints);
circuit = await tester(path.join(__dirname, "circuits", "escalarmulfix_test.circom"));
});
it("Should generate Same escalar mul", async () => {
const w = circuit.calculateWitness({"e": 0});
const w = await circuit.calculateWitness({"e": 0});
assert(circuit.checkWitness(w));
await circuit.checkConstraints(w);
const xout = w[circuit.getSignalIdx("main.out[0]")];
const yout = w[circuit.getSignalIdx("main.out[1]")];
await circuit.assertOut(w, {out: [0,1]}, true);
assert(xout.equals(0));
assert(yout.equals(1));
});
it("Should generate Same escalar mul", async () => {
const w = circuit.calculateWitness({"e": 1});
const w = await circuit.calculateWitness({"e": 1}, true);
assert(circuit.checkWitness(w));
await circuit.checkConstraints(w);
const xout = w[circuit.getSignalIdx("main.out[0]")];
const yout = w[circuit.getSignalIdx("main.out[1]")];
await circuit.assertOut(w, {out: babyjub.Base8});
assert(xout.equals(babyjub.Base8[0]));
assert(yout.equals(babyjub.Base8[1]));
});
it("Should generate scalar mul of a specific constant", async () => {
const s = bigInt("2351960337287830298912035165133676222414898052661454064215017316447594616519");
const base8 = [
bigInt("5299619240641551281634865583518297030282874472190772894086521144482721001553"),
bigInt("16950150798460657717958625567821834550301663161624707787222815936182638968203")
];
const w = await circuit.calculateWitness({"e": s}, true);
await circuit.checkConstraints(w);
const expectedRes = babyjub.mulPointEscalar(base8, s);
await circuit.assertOut(w, {out: expectedRes});
});
it("Should generate scalar mul of the firsts 50 elements", async () => {
const base8 = [
bigInt("5299619240641551281634865583518297030282874472190772894086521144482721001553"),
bigInt("16950150798460657717958625567821834550301663161624707787222815936182638968203")
];
for (let i=0; i<50; i++) {
const s = bigInt(i);
const w = await circuit.calculateWitness({"e": s}, true);
await circuit.checkConstraints(w);
const expectedRes = babyjub.mulPointEscalar(base8, s);
await circuit.assertOut(w, {out: expectedRes});
}
});
it("If multiply by order should return 0", async () => {
const w = circuit.calculateWitness({"e": babyjub.subOrder });
const w = await circuit.calculateWitness({"e": babyjub.subOrder }, true);
assert(circuit.checkWitness(w));
await circuit.checkConstraints(w);
const xout = w[circuit.getSignalIdx("main.out[0]")];
const yout = w[circuit.getSignalIdx("main.out[1]")];
assert(xout.equals(bigInt.zero));
assert(yout.equals(bigInt.one));
await circuit.assertOut(w, {out: [0,1]});
});
});

View File

@@ -1,35 +1,25 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const tester = require("circom").tester;
const mimcjs = require("../src/mimc7.js");
const assert = chai.assert;
describe("MiMC Circuit test", function () {
let circuit;
this.timeout(100000);
before( async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "mimc_test.circom"));
circuit = new snarkjs.Circuit(cirDef);
console.log("MiMC constraints: " + circuit.nConstraints);
circuit = await tester(path.join(__dirname, "circuits", "mimc_test.circom"));
});
it("Should check constrain", async () => {
const w = circuit.calculateWitness({x_in: 1, k: 2});
const res = w[circuit.getSignalIdx("main.out")];
const w = await circuit.calculateWitness({x_in: 1, k: 2}, true);
const res2 = mimcjs.hash(1,2,91);
assert.equal(res.toString(), res2.toString());
assert(circuit.checkWitness(w));
await circuit.assertOut(w, {out: res2});
await circuit.checkConstraints(w);
});
});

View File

@@ -1,11 +1,8 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const tester = require("circom").tester;
const mimcjs = require("../src/mimcsponge.js");
const assert = chai.assert;
describe("MiMC Sponge Circuit test", function () {
let circuit;
@@ -13,46 +10,28 @@ describe("MiMC Sponge Circuit test", function () {
this.timeout(100000);
it("Should check permutation", async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "mimc_sponge_test.circom"));
circuit = new snarkjs.Circuit(cirDef);
circuit = await tester(path.join(__dirname, "circuits", "mimc_sponge_test.circom"));
console.log("MiMC Feistel constraints: " + circuit.nConstraints);
const w = circuit.calculateWitness({xL_in: 1, xR_in: 2, k: 3});
const xLout = w[circuit.getSignalIdx("main.xL_out")];
const xRout = w[circuit.getSignalIdx("main.xR_out")];
const w = await circuit.calculateWitness({xL_in: 1, xR_in: 2, k: 3});
const out2 = mimcjs.hash(1,2,3);
assert.equal(xLout.toString(), out2.xL.toString());
assert.equal(xRout.toString(), out2.xR.toString());
await circuit.assertOut(w, {xL_out: out2.xL, xR_out: out2.xR});
assert(circuit.checkWitness(w));
await circuit.checkConstraints(w);
});
it("Should check hash", async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "mimc_sponge_hash_test.circom"));
circuit = await tester(path.join(__dirname, "circuits", "mimc_sponge_hash_test.circom"));
circuit = new snarkjs.Circuit(cirDef);
console.log("MiMC Sponge constraints: " + circuit.nConstraints);
const w = circuit.calculateWitness({ins: [1, 2], k: 0});
const o1 = w[circuit.getSignalIdx("main.outs[0]")];
const o2 = w[circuit.getSignalIdx("main.outs[1]")];
const o3 = w[circuit.getSignalIdx("main.outs[2]")];
const w = await circuit.calculateWitness({ins: [1, 2], k: 0});
const out2 = mimcjs.multiHash([1,2], 0, 3);
assert.equal(o1.toString(), out2[0].toString());
assert.equal(o2.toString(), out2[1].toString());
assert.equal(o3.toString(), out2[2].toString());
assert(circuit.checkWitness(w));
await circuit.assertOut(w, {outs: out2});
await circuit.checkConstraints(w);
});
});

View File

@@ -1,13 +1,11 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const bigInt = require("big-integer");
const tester = require("circom").tester;
const babyJub = require("../src/babyjub.js");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
describe("Montgomery test", function () {
let circuitE2M;
let circuitM2E;
@@ -15,43 +13,37 @@ describe("Montgomery test", function () {
let circuitMDouble;
let g = [
snarkjs.bigInt("17777552123799933955779906779655732241715742912184938656739573121738514868268"),
snarkjs.bigInt("2626589144620713026669568689430873010625803728049924121243784502389097019475")];
bigInt("5299619240641551281634865583518297030282874472190772894086521144482721001553"),
bigInt("16950150798460657717958625567821834550301663161624707787222815936182638968203")
];
let mg, mg2, g2, g3, mg3;
this.timeout(100000);
before( async() => {
const cirDefE2M = await compiler(path.join(__dirname, "circuits", "edwards2montgomery.circom"));
circuitE2M = new snarkjs.Circuit(cirDefE2M);
console.log("NConstrains Edwards -> Montgomery: " + circuitE2M.nConstraints);
const cirDefM2E = await compiler(path.join(__dirname, "circuits", "montgomery2edwards.circom"));
circuitM2E = new snarkjs.Circuit(cirDefM2E);
console.log("NConstrains Montgomery -> Edwards: " + circuitM2E.nConstraints);
const cirDefMAdd = await compiler(path.join(__dirname, "circuits", "montgomeryadd.circom"));
circuitMAdd = new snarkjs.Circuit(cirDefMAdd);
console.log("NConstrains Montgomery Add: " + circuitMAdd.nConstraints);
const cirDefMDouble = await compiler(path.join(__dirname, "circuits", "montgomerydouble.circom"));
circuitMDouble = new snarkjs.Circuit(cirDefMDouble);
console.log("NConstrains Montgomery Double: " + circuitMDouble.nConstraints);
circuitE2M = await tester(path.join(__dirname, "circuits", "edwards2montgomery.circom"));
await circuitE2M.loadSymbols();
circuitM2E = await tester(path.join(__dirname, "circuits", "montgomery2edwards.circom"));
await circuitM2E.loadSymbols();
circuitMAdd = await tester(path.join(__dirname, "circuits", "montgomeryadd.circom"));
await circuitMAdd.loadSymbols();
circuitMDouble = await tester(path.join(__dirname, "circuits", "montgomerydouble.circom"));
await circuitMDouble.loadSymbols();
});
it("Convert Edwards to Montgomery and back again", async () => {
let w, xout, yout;
w = circuitE2M.calculateWitness({ in: g});
w = await circuitE2M.calculateWitness({ in: g}, true);
xout = w[circuitE2M.getSignalIdx("main.out[0]")];
yout = w[circuitE2M.getSignalIdx("main.out[1]")];
xout = w[circuitE2M.symbols["main.out[0]"].varIdx];
yout = w[circuitE2M.symbols["main.out[1]"].varIdx];
mg = [xout, yout];
w = circuitM2E.calculateWitness({ in: [xout, yout]});
w = await circuitM2E.calculateWitness({ in: [xout, yout]}, true);
xout = w[circuitM2E.getSignalIdx("main.out[0]")];
yout = w[circuitM2E.getSignalIdx("main.out[1]")];
xout = w[circuitM2E.symbols["main.out[0]"].varIdx];
yout = w[circuitM2E.symbols["main.out[1]"].varIdx];
assert(xout.equals(g[0]));
assert(yout.equals(g[1]));
@@ -61,17 +53,17 @@ describe("Montgomery test", function () {
g2 = babyJub.addPoint(g,g);
w = circuitMDouble.calculateWitness({ in: mg});
w = await circuitMDouble.calculateWitness({ in: mg}, true);
xout = w[circuitE2M.getSignalIdx("main.out[0]")];
yout = w[circuitE2M.getSignalIdx("main.out[1]")];
xout = w[circuitE2M.symbols["main.out[0]"].varIdx];
yout = w[circuitE2M.symbols["main.out[1]"].varIdx];
mg2 = [xout, yout];
w = circuitM2E.calculateWitness({ in: mg2});
w = await circuitM2E.calculateWitness({ in: mg2}, true);
xout = w[circuitM2E.getSignalIdx("main.out[0]")];
yout = w[circuitM2E.getSignalIdx("main.out[1]")];
xout = w[circuitM2E.symbols["main.out[0]"].varIdx];
yout = w[circuitM2E.symbols["main.out[1]"].varIdx];
assert(xout.equals(g2[0]));
assert(yout.equals(g2[1]));
@@ -81,17 +73,17 @@ describe("Montgomery test", function () {
g3 = babyJub.addPoint(g,g2);
w = circuitMAdd.calculateWitness({ in1: mg, in2: mg2});
w = await circuitMAdd.calculateWitness({ in1: mg, in2: mg2}, true);
xout = w[circuitMAdd.getSignalIdx("main.out[0]")];
yout = w[circuitMAdd.getSignalIdx("main.out[1]")];
xout = w[circuitMAdd.symbols["main.out[0]"].varIdx];
yout = w[circuitMAdd.symbols["main.out[1]"].varIdx];
mg3 = [xout, yout];
w = circuitM2E.calculateWitness({ in: mg3});
w = await circuitM2E.calculateWitness({ in: mg3}, true);
xout = w[circuitM2E.getSignalIdx("main.out[0]")];
yout = w[circuitM2E.getSignalIdx("main.out[1]")];
xout = w[circuitM2E.symbols["main.out[0]"].varIdx];
yout = w[circuitM2E.symbols["main.out[1]"].varIdx];
assert(xout.equals(g3[0]));
assert(yout.equals(g3[1]));

View File

@@ -1,25 +1,12 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const bigInt = require("big-integer");
const tester = require("circom").tester;
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
describe("Mux4 test", () => {
describe("Mux4 test", function() {
this.timeout(100000);
it("Should create a constant multiplexer 4", async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "mux4_1.circom"));
// console.log(JSON.stringify(cirDef, null, 1));
// assert.equal(cirDef.nVars, 2);
const circuit = new snarkjs.Circuit(cirDef);
console.log("NConstrains Mux4: " + circuit.nConstraints);
const circuit = await tester(path.join(__dirname, "circuits", "mux4_1.circom"));
const ct16 = [
bigInt("123"),
@@ -41,22 +28,17 @@ describe("Mux4 test", () => {
];
for (let i=0; i<16; i++) {
const w = circuit.calculateWitness({ "selector": i });
const w = await circuit.calculateWitness({ "selector": i }, true);
assert(w[0].equals(bigInt(1)));
await circuit.checkConstraints(w);
// console.log(i + " -> " + w[circuit.getSignalIdx("main.out")].toString());
assert(w[circuit.getSignalIdx("main.out")].equals(ct16[i]));
await circuit.assertOut(w, {out: ct16[i]});
}
});
it("Should create a constant multiplexer 3", async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "mux3_1.circom"));
const circuit = new snarkjs.Circuit(cirDef);
console.log("NConstrains Mux3: " + circuit.nConstraints);
const circuit = await tester(path.join(__dirname, "circuits", "mux3_1.circom"));
const ct8 = [
bigInt("37"),
@@ -70,23 +52,18 @@ describe("Mux4 test", () => {
];
for (let i=0; i<8; i++) {
const w = circuit.calculateWitness({ "selector": i });
const w = await circuit.calculateWitness({ "selector": i }, true);
assert(w[0].equals(bigInt(1)));
await circuit.checkConstraints(w);
// console.log(i + " -> " + w[circuit.getSignalIdx("main.out")].toString());
assert(w[circuit.getSignalIdx("main.out")].equals(ct8[i]));
await circuit.assertOut(w, {out: ct8[i]});
}
});
it("Should create a constant multiplexer 2", async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "mux2_1.circom"));
const circuit = await tester(path.join(__dirname, "circuits", "mux2_1.circom"));
const circuit = new snarkjs.Circuit(cirDef);
console.log("NConstrains Mux2: " + circuit.nConstraints);
const ct8 = [
const ct4 = [
bigInt("37"),
bigInt("47"),
bigInt("53"),
@@ -94,34 +71,28 @@ describe("Mux4 test", () => {
];
for (let i=0; i<4; i++) {
const w = circuit.calculateWitness({ "selector": i });
const w = await circuit.calculateWitness({ "selector": i }, true);
assert(w[0].equals(bigInt(1)));
await circuit.checkConstraints(w);
// console.log(i + " -> " + w[circuit.getSignalIdx("main.out")].toString());
assert(w[circuit.getSignalIdx("main.out")].equals(ct8[i]));
await circuit.assertOut(w, {out: ct4[i]});
}
});
it("Should create a constant multiplexer 1", async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "mux1_1.circom"));
const circuit = await tester(path.join(__dirname, "circuits", "mux1_1.circom"));
const circuit = new snarkjs.Circuit(cirDef);
console.log("NConstrains Mux1: " + circuit.nConstraints);
const ct8 = [
const ct2 = [
bigInt("37"),
bigInt("47"),
];
for (let i=0; i<2; i++) {
const w = circuit.calculateWitness({ "selector": i });
const w = await circuit.calculateWitness({ "selector": i }, true);
assert(w[0].equals(bigInt(1)));
await circuit.checkConstraints(w);
// console.log(i + " -> " + w[circuit.getSignalIdx("main.out")].toString());
assert(w[circuit.getSignalIdx("main.out")].equals(ct8[i]));
await circuit.assertOut(w, {out: ct2[i]});
}
});
});

View File

@@ -1,11 +1,8 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
const bigInt = require("big-integer");
const tester = require("circom").tester;
const babyJub = require("../src/babyjub.js");
@@ -22,79 +19,59 @@ describe("Double Pedersen test", function() {
let circuit;
this.timeout(100000);
before( async() => {
const cirDef = await compiler(path.join(__dirname, "circuits", "pedersen_test.circom"));
circuit = new snarkjs.Circuit(cirDef);
circuit = await tester(path.join(__dirname, "circuits", "pedersen_test.circom"));
console.log("NConstrains: " + circuit.nConstraints);
});
it("Should pedersen at zero", async () => {
let w, xout, yout;
let w;
w = circuit.calculateWitness({ in: ["0", "0"]});
w = await circuit.calculateWitness({ in: ["0", "0"]}, true);
xout = w[circuit.getSignalIdx("main.out[0]")];
yout = w[circuit.getSignalIdx("main.out[1]")];
await circuit.assertOut(w, {out: [0,1]});
assert(xout.equals("0"));
assert(yout.equals("1"));
});
it("Should pedersen at one first generator", async () => {
let w, xout, yout;
let w;
w = circuit.calculateWitness({ in: ["1", "0"]});
w = await circuit.calculateWitness({ in: ["1", "0"]}, true);
xout = bigInt(w[circuit.getSignalIdx("main.out[0]")]);
yout = bigInt(w[circuit.getSignalIdx("main.out[1]")]);
await circuit.assertOut(w, {out: PBASE[0]});
assert(xout.equals(PBASE[0][0]));
assert(yout.equals(PBASE[0][1]));
});
it("Should pedersen at one second generator", async () => {
let w, xout, yout;
let w;
w = circuit.calculateWitness({ in: ["0", "1"]});
w = await circuit.calculateWitness({ in: ["0", "1"]}, true);
xout = w[circuit.getSignalIdx("main.out[0]")];
yout = w[circuit.getSignalIdx("main.out[1]")];
assert(xout.equals(PBASE[1][0]));
assert(yout.equals(PBASE[1][1]));
await circuit.assertOut(w, {out: PBASE[1]});
});
it("Should pedersen at mixed generators", async () => {
let w, xout, yout;
w = circuit.calculateWitness({ in: ["3", "7"]});
xout = w[circuit.getSignalIdx("main.out[0]")];
yout = w[circuit.getSignalIdx("main.out[1]")];
let w;
w = await circuit.calculateWitness({ in: ["3", "7"]}, true);
const r = babyJub.addPoint(
babyJub.mulPointEscalar(PBASE[0], 3),
babyJub.mulPointEscalar(PBASE[1], 7)
);
assert(xout.equals(r[0]));
assert(yout.equals(r[1]));
await circuit.assertOut(w, {out: r});
});
it("Should pedersen all ones", async () => {
let w, xout, yout;
let w;
const allOnes = bigInt("1").shl(250).sub(bigInt("1"));
w = circuit.calculateWitness({ in: [allOnes, allOnes]});
const allOnes = bigInt("1").shiftLeft(250).minus(bigInt("1"));
w = await circuit.calculateWitness({ in: [allOnes, allOnes]}, true);
xout = w[circuit.getSignalIdx("main.out[0]")];
yout = w[circuit.getSignalIdx("main.out[1]")];
const r2 = babyJub.addPoint(
babyJub.mulPointEscalar(PBASE[0], allOnes),
babyJub.mulPointEscalar(PBASE[1], allOnes)
);
assert(xout.equals(r2[0]));
assert(yout.equals(r2[1]));
await circuit.assertOut(w, {out: r2});
});
});

View File

@@ -1,11 +1,7 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
const bigInt = require("big-integer");
const tester = require("circom").tester;
const babyJub = require("../src/babyjub.js");
const pedersen = require("../src/pedersenHash.js");
@@ -15,60 +11,39 @@ describe("Pedersen test", function() {
let circuit;
this.timeout(100000);
before( async() => {
const cirDef = await compiler(path.join(__dirname, "circuits", "pedersen2_test.circom"));
circuit = new snarkjs.Circuit(cirDef);
console.log("NConstrains Pedersen2: " + circuit.nConstraints);
circuit = await tester(path.join(__dirname, "circuits", "pedersen2_test.circom"));
});
it("Should pedersen at zero", async () => {
let w, xout, yout;
let w;
w = circuit.calculateWitness({ in: 0});
xout = w[circuit.getSignalIdx("main.out[0]")];
yout = w[circuit.getSignalIdx("main.out[1]")];
w = await circuit.calculateWitness({ in: 0}, true);
const b = Buffer.alloc(32);
const h = pedersen.hash(b);
const hP = babyJub.unpackPoint(h);
/*
console.log(`[${xout.toString()}, ${yout.toString()}]`);
console.log(`[${hP[0].toString()}, ${hP[1].toString()}]`);
*/
await circuit.assertOut(w, {out: hP});
assert(xout.equals(hP[0]));
assert(yout.equals(hP[1]));
});
it("Should pedersen with 253 ones", async () => {
let w, xout, yout;
let w;
const n = bigInt.one.shl(253).sub(bigInt.one);
console.log(n.toString(16));
const n = bigInt.one.shiftLeft(253).minus(bigInt.one);
w = circuit.calculateWitness({ in: n});
xout = w[circuit.getSignalIdx("main.out[0]")];
yout = w[circuit.getSignalIdx("main.out[1]")];
w = await circuit.calculateWitness({ in: n}, true);
const b = Buffer.alloc(32);
for (let i=0; i<31; i++) b[i] = 0xFF;
b[31] = 0x1F;
const h = pedersen.hash(b);
const hP = babyJub.unpackPoint(h);
/*
console.log(`[${xout.toString()}, ${yout.toString()}]`);
console.log(`[${hP[0].toString()}, ${hP[1].toString()}]`);
*/
await circuit.assertOut(w, {out: hP});
assert(xout.equals(hP[0]));
assert(yout.equals(hP[1]));
});
});

View File

@@ -1,11 +1,5 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
const tester = require("circom").tester;
const babyJub = require("../src/babyjub.js");
@@ -14,20 +8,16 @@ describe("Point 2 bits test", function() {
let circuit;
this.timeout(100000);
before( async() => {
const cirDef = await compiler(path.join(__dirname, "circuits", "pointbits_loopback.circom"));
circuit = new snarkjs.Circuit(cirDef);
console.log("NConstrains Point2Bits loopback: " + circuit.nConstraints);
circuit = await tester(path.join(__dirname, "circuits", "pointbits_loopback.circom"));
});
it("Should do the both convertions for 8Base", async () => {
const w = circuit.calculateWitness({ in: babyJub.Base8});
const w = await circuit.calculateWitness({ in: babyJub.Base8}, true);
assert(circuit.checkWitness(w));
await circuit.checkConstraints(w);
});
it("Should do the both convertions for Zero point", async () => {
const w = circuit.calculateWitness({ in: [0, 1]});
const w = await circuit.calculateWitness({ in: [0, 1]}, true);
assert(circuit.checkWitness(w));
await circuit.checkConstraints(w);
});
});

View File

@@ -1,8 +1,8 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
var blake2b = require('blake2b');
var blake2b = require("blake2b");
const bigInt = require("big-integer");
const tester = require("circom").tester;
const poseidon = require("../src/poseidon.js");
@@ -11,50 +11,66 @@ const assert = chai.assert;
describe("Blake2b version test", function() {
it("Should give the expected output for blake2b version", async () => {
var output = new Uint8Array(32);
var input = Buffer.from('poseidon_constants');
h = blake2b(output.length).update(input).digest('hex')
assert.equal('e57ba154fb2c47811dc1a2369b27e25a44915b4e4ece4eb8ec74850cb78e01b1', h);
var input = Buffer.from("poseidon_constants");
const h = blake2b(output.length).update(input).digest("hex");
assert.equal("e57ba154fb2c47811dc1a2369b27e25a44915b4e4ece4eb8ec74850cb78e01b1", h);
});
});
describe("Poseidon Circuit test", function () {
let circuit;
let circuit6;
let circuit3;
this.timeout(100000);
before( async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "poseidon_test.circom"));
circuit = new snarkjs.Circuit(cirDef);
console.log("Poseidon constraints: " + circuit.nConstraints);
circuit6 = await tester(path.join(__dirname, "circuits", "poseidon6_test.circom"));
circuit3 = await tester(path.join(__dirname, "circuits", "poseidon3_test.circom"));
});
it("Should check constrain of hash([1, 2])", async () => {
const w = circuit.calculateWitness({inputs: [1, 2]});
const res = w[circuit.getSignalIdx("main.out")];
it("Should check constrain of hash([1, 2]) t=6", async () => {
const w = await circuit6.calculateWitness({inputs: [1, 2]}, true);
const hash = poseidon.createHash(6, 8, 57);
const res2 = hash([1,2]);
assert.equal('12242166908188651009877250812424843524687801523336557272219921456462821518061', res2.toString());
assert.equal(res.toString(), res2.toString());
assert(circuit.checkWitness(w));
assert.equal("12242166908188651009877250812424843524687801523336557272219921456462821518061", res2.toString());
await circuit6.assertOut(w, {out : res2});
await circuit6.checkConstraints(w);
});
it("Should check constrain of hash([3, 4])", async () => {
const w = circuit.calculateWitness({inputs: [3, 4]});
const res = w[circuit.getSignalIdx("main.out")];
it("Should check constrain of hash([3, 4]) t=6", async () => {
const w = await circuit6.calculateWitness({inputs: [3, 4]});
const hash = poseidon.createHash(6, 8, 57);
const res2 = hash([3, 4]);
assert.equal('17185195740979599334254027721507328033796809509313949281114643312710535000993', res2.toString());
assert.equal(res.toString(), res2.toString());
assert.equal("17185195740979599334254027721507328033796809509313949281114643312710535000993", res2.toString());
await circuit6.assertOut(w, {out : res2});
await circuit6.checkConstraints(w);
});
assert(circuit.checkWitness(w));
it("Should check constrain of hash([1, 2]) t=3", async () => {
const w = await circuit3.calculateWitness({inputs: [1, 2]});
const hash = poseidon.createHash(3, 8, 57);
const res2 = hash([1,2]);
assert.equal("2104035019328376391822106787753454168168617545136592089411833517434990977743", res2.toString());
await circuit3.assertOut(w, {out : res2});
await circuit3.checkConstraints(w);
});
it("Should check constrain of hash([3, 4]) t=3", async () => {
const w = await circuit3.calculateWitness({inputs: [3, 4]});
const hash = poseidon.createHash(3, 8, 57);
const res2 = hash([3, 4]);
assert.equal("12456141564250880945411182508630957604732712316993112736876413121277158512223", res2.toString());
await circuit3.assertOut(w, {out : res2});
await circuit3.checkConstraints(w);
});
});

View File

@@ -8,13 +8,13 @@ const bigInt = require("snarkjs").bigInt;
const assert = chai.assert;
const log = (msg) => { if (process.env.MOCHA_VERBOSE) console.log(msg); };
const SEED = "mimc";
describe("Poseidon Smart contract test", () => {
describe("Poseidon Smart contract test", function () {
let testrpc;
let web3;
let mimc;
let poseidon6;
let poseidon3;
let accounts;
this.timeout(100000);
before(async () => {
web3 = new Web3(ganache.provider(), null, { transactionConfirmationBlocks: 1 });
@@ -24,17 +24,23 @@ describe("Poseidon Smart contract test", () => {
it("Should deploy the contract", async () => {
const C = new web3.eth.Contract(poseidonGenContract.abi);
mimc = await C.deploy({
data: poseidonGenContract.createCode()
poseidon6 = await C.deploy({
data: poseidonGenContract.createCode(6)
}).send({
gas: 2500000,
from: accounts[0]
});
poseidon3 = await C.deploy({
data: poseidonGenContract.createCode(3)
}).send({
gas: 2500000,
from: accounts[0]
});
});
it("Shold calculate the mimic correctly", async () => {
it("Shold calculate the poseidon correctly t=6", async () => {
const res = await mimc.methods.poseidon([1,2]).call();
const res = await poseidon6.methods.poseidon([1,2]).call();
// console.log("Cir: " + bigInt(res.toString(16)).toString(16));
@@ -45,5 +51,19 @@ describe("Poseidon Smart contract test", () => {
assert.equal(res.toString(), res2.toString());
});
it("Shold calculate the poseidon correctly t=3", async () => {
const res = await poseidon3.methods.poseidon([1,2]).call();
// console.log("Cir: " + bigInt(res.toString(16)).toString(16));
const hash = Poseidon.createHash(3, 8, 57);
const res2 = hash([1,2]);
// console.log("Ref: " + bigInt(res2).toString(16));
assert.equal(res.toString(), res2.toString());
});
});

View File

@@ -3,24 +3,56 @@ const path = require("path");
const snarkjs = require("snarkjs");
const crypto = require("crypto");
const compiler = require("circom");
const assert = chai.assert;
const sha256 = require("./helpers/sha256");
const tester = require("circom").tester;
// 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);
function buffer2bitArray(b) {
const res = [];
for (let i=0; i<b.length; i++) {
for (let j=0; j<8; j++) {
res.push((b[i] >> (7-j) &1));
}
}
return res;
}
console.log("Vars: "+circuit.nVars);
console.log("Constraints: "+circuit.nConstraints);
function bitArray2buffer(a) {
const len = Math.floor((a.length -1 )/8)+1;
const b = new Buffer.alloc(len);
const witness = circuit.calculateWitness({ "a": "1", "b": "2" });
for (let i=0; i<a.length; i++) {
const p = Math.floor(i/8);
b[p] = b[p] | (Number(a[i]) << ( 7 - (i%8) ));
}
return b;
}
describe("SHA256 test", function () {
this.timeout(100000);
it("Should work bits to array and array to bits", async () => {
const b = new Buffer.alloc(64);
for (let i=0; i<64; i++) {
b[i] = i+1;
}
const a = buffer2bitArray(b);
const b2 = bitArray2buffer(a);
assert.equal(b.toString("hex"), b2.toString("hex"), true);
});
it("Should calculate a hash of 1 compressor", async () => {
const cir = await tester(path.join(__dirname, "circuits", "sha256_2_test.circom"));
const witness = await cir.calculateWitness({ "a": "1", "b": "2" }, true);
const b = new Buffer.alloc(54);
b[26] = 1;
@@ -38,5 +70,46 @@ describe("SHA256 test", () => {
assert(witness[1].equals(snarkjs.bigInt(r)));
}).timeout(1000000);
it("Should calculate a hash of 2 compressor", async () => {
const cir = await tester(path.join(__dirname, "circuits", "sha256_test512.circom"));
const b = new Buffer.alloc(64);
for (let i=0; i<64; i++) {
b[i] = i+1;
}
const hash = crypto.createHash("sha256")
.update(b)
.digest("hex");
const arrIn = buffer2bitArray(b);
const witness = await cir.calculateWitness({ "in": arrIn }, true);
const arrOut = witness.slice(1, 257);
const hash2 = bitArray2buffer(arrOut).toString("hex");
assert.equal(hash, hash2);
}).timeout(1000000);
it ("Should calculate a hash of 2 compressor", async () => {
const cir = await tester(path.join(__dirname, "circuits", "sha256_test448.circom"));
const testStr = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
const b = Buffer.from(testStr, "utf8");
const hash = crypto.createHash("sha256")
.update(b)
.digest("hex");
const arrIn = buffer2bitArray(b);
const witness = await cir.calculateWitness({ "in": arrIn }, true);
const arrOut = witness.slice(1, 257);
const hash2 = bitArray2buffer(arrOut).toString("hex");
assert.equal(hash, hash2);
});
});

View File

@@ -1,11 +1,6 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
const bigInt = require("big-integer");
const tester = require("circom").tester;
function print(circuit, w, s) {
console.log(s + ": " + w[circuit.getSignalIdx(s)]);
@@ -14,7 +9,7 @@ function print(circuit, w, s) {
function getBits(v, n) {
const res = [];
for (let i=0; i<n; i++) {
if (v.shr(i).isOdd()) {
if (v.shiftRight(i).isOdd()) {
res.push(bigInt.one);
} else {
res.push(bigInt.zero);
@@ -25,64 +20,60 @@ function getBits(v, n) {
const q = bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
describe("Sign test", () => {
describe("Sign test", function() {
let circuit;
this.timeout(100000);
before( async() => {
const cirDef = await compiler(path.join(__dirname, "circuits", "sign_test.circom"));
circuit = new snarkjs.Circuit(cirDef);
console.log("NConstrains: " + circuit.nConstraints);
circuit = await tester(path.join(__dirname, "circuits", "sign_test.circom"));
});
it("Sign of 0", async () => {
const inp = getBits(bigInt.zero, 254);
const w = circuit.calculateWitness({in: inp});
const w = await circuit.calculateWitness({in: inp}, true);
assert( w[circuit.getSignalIdx("main.sign")].equals(bigInt(0)) );
await circuit.assertOut(w, {sign: 0});
});
it("Sign of 3", async () => {
const inp = getBits(bigInt(3), 254);
const w = circuit.calculateWitness({in: inp});
const w = await circuit.calculateWitness({in: inp}, true);
assert( w[circuit.getSignalIdx("main.sign")].equals(bigInt(0)) );
await circuit.assertOut(w, {sign: 0});
});
it("Sign of q/2", async () => {
const inp = getBits(q.shr(bigInt.one), 254);
const w = circuit.calculateWitness({in: inp});
const inp = getBits(q.shiftRight(bigInt.one), 254);
const w = await circuit.calculateWitness({in: inp}, true);
assert( w[circuit.getSignalIdx("main.sign")].equals(bigInt(0)) );
await circuit.assertOut(w, {sign: 0});
});
it("Sign of q/2+1", async () => {
const inp = getBits(q.shr(bigInt.one).add(bigInt.one), 254);
const w = circuit.calculateWitness({in: inp});
const inp = getBits(q.shiftRight(bigInt.one).add(bigInt.one), 254);
const w = await circuit.calculateWitness({in: inp}, true);
assert( w[circuit.getSignalIdx("main.sign")].equals(bigInt(1)) );
await circuit.assertOut(w, {sign: 1});
});
it("Sign of q-1", async () => {
const inp = getBits(q.sub(bigInt.one), 254);
const w = circuit.calculateWitness({in: inp});
const inp = getBits(q.minus(bigInt.one), 254);
const w = await circuit.calculateWitness({in: inp}, true);
assert( w[circuit.getSignalIdx("main.sign")].equals(bigInt(1)) );
await circuit.assertOut(w, {sign: 1});
});
it("Sign of q", async () => {
const inp = getBits(q, 254);
const w = circuit.calculateWitness({in: inp});
const w = await circuit.calculateWitness({in: inp}, true);
assert( w[circuit.getSignalIdx("main.sign")].equals(bigInt(1)) );
await circuit.assertOut(w, {sign: 1});
});
it("Sign of all ones", async () => {
const inp = getBits(bigInt(1).shl(254).sub(bigInt(1)), 254);
const w = circuit.calculateWitness({in: inp});
const inp = getBits(bigInt(1).shiftLeft(254).minus(bigInt(1)), 254);
const w = await circuit.calculateWitness({in: inp}, true);
assert( w[circuit.getSignalIdx("main.sign")].equals(bigInt(1)) );
await circuit.assertOut(w, {sign: 1});
});
});

View File

@@ -1,12 +1,11 @@
const chai = require("chai");
const snarkjs = require("snarkjs");
const bigInt = require("big-integer");
const smt = require("../src/smt.js");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
function stringifyBigInts(o) {
if ((typeof(o) == "bigint") || (o instanceof bigInt)) {

View File

@@ -1,25 +1,23 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const bigInt = require("big-integer");
const tester = require("circom").tester;
const smt = require("../src/smt.js");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
function print(circuit, w, s) {
console.log(s + ": " + w[circuit.getSignalIdx(s)]);
}
async function testInsert(tree, key, value, circuit, log ) {
async function testInsert(tree, key, value, circuit ) {
const res = await tree.insert(key,value);
let siblings = res.siblings;
while (siblings.length<10) siblings.push(bigInt(0));
const w = circuit.calculateWitness({
const w = await circuit.calculateWitness({
fnc: [1,0],
oldRoot: res.oldRoot,
siblings: siblings,
@@ -28,11 +26,12 @@ async function testInsert(tree, key, value, circuit, log ) {
isOld0: res.isOld0 ? 1 : 0,
newKey: key,
newValue: value
}, log);
}, true);
await circuit.checkConstraints(w);
await circuit.assertOut(w, {newRoot: res.newRoot});
const root1 = w[circuit.getSignalIdx("main.newRoot")];
assert(circuit.checkWitness(w));
assert(root1.equals(res.newRoot));
}
async function testDelete(tree, key, circuit) {
@@ -40,7 +39,7 @@ async function testDelete(tree, key, circuit) {
let siblings = res.siblings;
while (siblings.length<10) siblings.push(bigInt(0));
const w = circuit.calculateWitness({
const w = await circuit.calculateWitness({
fnc: [1,1],
oldRoot: res.oldRoot,
siblings: siblings,
@@ -49,12 +48,11 @@ async function testDelete(tree, key, circuit) {
isOld0: res.isOld0 ? 1 : 0,
newKey: res.delKey,
newValue: res.delValue
});
}, true);
const root1 = w[circuit.getSignalIdx("main.newRoot")];
await circuit.checkConstraints(w);
assert(circuit.checkWitness(w));
assert(root1.equals(res.newRoot));
await circuit.assertOut(w, {newRoot: res.newRoot});
}
async function testUpdate(tree, key, newValue, circuit) {
@@ -62,7 +60,7 @@ async function testUpdate(tree, key, newValue, circuit) {
let siblings = res.siblings;
while (siblings.length<10) siblings.push(bigInt(0));
const w = circuit.calculateWitness({
const w = await circuit.calculateWitness({
fnc: [0,1],
oldRoot: res.oldRoot,
siblings: siblings,
@@ -73,25 +71,21 @@ async function testUpdate(tree, key, newValue, circuit) {
newValue: res.newValue
});
const root1 = w[circuit.getSignalIdx("main.newRoot")];
await circuit.checkConstraints(w);
assert(circuit.checkWitness(w));
assert(root1.equals(res.newRoot));
await circuit.assertOut(w, {newRoot: res.newRoot});
}
describe("SMT test", function () {
describe("SMT Processor test", function () {
let circuit;
let tree;
this.timeout(10000000);
before( async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "smtprocessor10_test.circom"));
circuit = new snarkjs.Circuit(cirDef);
console.log("NConstrains SMTProcessor: " + circuit.nConstraints);
circuit = await tester(path.join(__dirname, "circuits", "smtprocessor10_test.circom"));
await circuit.loadSymbols();
tree = await smt.newMemEmptyTrie();
});
@@ -110,8 +104,6 @@ describe("SMT test", function () {
await testInsert(tree, key, value, circuit);
});
it("Should remove an element", async () => {
await testDelete(tree, 111, circuit);
await testDelete(tree, 333, circuit);
@@ -179,7 +171,7 @@ describe("SMT test", function () {
it("Should match a NOp with random vals", async () => {
let siblings = [];
while (siblings.length<10) siblings.push(bigInt(88));
const w = circuit.calculateWitness({
const w = await circuit.calculateWitness({
fnc: [0,0],
oldRoot: 11,
siblings: siblings,
@@ -190,12 +182,12 @@ describe("SMT test", function () {
newValue: 77
});
const root1 = w[circuit.getSignalIdx("main.oldRoot")];
const root2 = w[circuit.getSignalIdx("main.newRoot")];
const root1 = w[circuit.symbols["main.oldRoot"].varIdx];
const root2 = w[circuit.symbols["main.newRoot"].varIdx];
await circuit.checkConstraints(w);
assert(circuit.checkWitness(w));
assert(root1.equals(root2));
});
it("Should update an element", async () => {
const tree1 = await smt.newMemEmptyTrie();
@@ -213,5 +205,4 @@ describe("SMT test", function () {
await testUpdate(tree1, 9, 999, circuit);
await testUpdate(tree1, 32, 323232, circuit);
});
});

View File

@@ -1,14 +1,12 @@
const chai = require("chai");
const path = require("path");
const snarkjs = require("snarkjs");
const compiler = require("circom");
const bigInt = require("big-integer");
const tester = require("circom").tester;
const smt = require("../src/smt.js");
const assert = chai.assert;
const bigInt = snarkjs.bigInt;
function print(circuit, w, s) {
console.log(s + ": " + w[circuit.getSignalIdx(s)]);
}
@@ -21,7 +19,7 @@ async function testInclusion(tree, key, circuit) {
let siblings = res.siblings;
while (siblings.length<10) siblings.push(bigInt(0));
const w = circuit.calculateWitness({
const w = await circuit.calculateWitness({
enabled: 1,
fnc: 0,
root: tree.root,
@@ -31,9 +29,10 @@ async function testInclusion(tree, key, circuit) {
isOld0: 0,
key: key,
value: res.foundValue
});
}, true);
await circuit.checkConstraints(w);
assert(circuit.checkWitness(w));
}
async function testExclusion(tree, key, circuit) {
@@ -43,7 +42,7 @@ async function testExclusion(tree, key, circuit) {
let siblings = res.siblings;
while (siblings.length<10) siblings.push(bigInt(0));
const w = circuit.calculateWitness({
const w = await circuit.calculateWitness({
enabled: 1,
fnc: 1,
root: tree.root,
@@ -55,21 +54,18 @@ async function testExclusion(tree, key, circuit) {
value: 0
});
assert(circuit.checkWitness(w));
await circuit.checkConstraints(w);
}
describe("SMT test", function () {
describe("SMT Verifier test", function () {
let circuit;
let tree;
this.timeout(100000);
before( async () => {
const cirDef = await compiler(path.join(__dirname, "circuits", "smtverifier10_test.circom"));
circuit = new snarkjs.Circuit(cirDef);
console.log("NConstrains SMTVerifier: " + circuit.nConstraints);
circuit = await tester(path.join(__dirname, "circuits", "smtverifier10_test.circom"));
tree = await smt.newMemEmptyTrie();
await tree.insert(7,77);
@@ -97,7 +93,7 @@ describe("SMT test", function () {
let siblings = [];
for (let i=0; i<10; i++) siblings.push(i);
const w = circuit.calculateWitness({
const w = await circuit.calculateWitness({
enabled: 0,
fnc: 0,
root: 1,
@@ -108,7 +104,32 @@ describe("SMT test", function () {
key: 44,
value: 0
});
assert(circuit.checkWitness(w));
await circuit.checkConstraints(w);
});
it("Check inclussion Adria case", async () => {
const e1_hi= bigInt("17124152697573569611556136390143205198134245887034837071647643529178599000839");
const e1_hv= bigInt("19650379996168153643111744440707177573540245771926102415571667548153444658179");
const e2ok_hi= bigInt("16498254692537945203721083102154618658340563351558973077349594629411025251262");
const e2ok_hv= bigInt("19650379996168153643111744440707177573540245771926102415571667548153444658179");
const e2fail_hi= bigInt("17195092312975762537892237130737365903429674363577646686847513978084990105579");
const e2fail_hv= bigInt("19650379996168153643111744440707177573540245771926102415571667548153444658179");
const tree1 = await smt.newMemEmptyTrie();
await tree1.insert(e1_hi,e1_hv);
await tree1.insert(e2ok_hi,e2ok_hv);
await testInclusion(tree1, e2ok_hi, circuit);
const tree2 = await smt.newMemEmptyTrie();
await tree2.insert(e1_hi,e1_hv);
await tree2.insert(e2fail_hi,e2fail_hv);
await testInclusion(tree2, e2fail_hi, circuit);
});