Browse Source

First test added

wasm
Jordi Baylina 6 years ago
parent
commit
ff2ecd310e
No known key found for this signature in database GPG Key ID: 7480C80C1BE43112
40 changed files with 4689 additions and 479 deletions
  1. +1226
    -0
      barry.js
  2. +43
    -0
      circuits/barry.jaz
  3. +2
    -2
      circuits/sha256/constants.jaz
  4. +18
    -0
      circuits/sha256/constants_test.jaz
  5. +290
    -0
      constant_test.json
  6. +1
    -0
      index.js
  7. +3
    -0
      input_barry.json
  8. +103
    -95
      jaz.js
  9. +1
    -0
      output_barry.json
  10. +261
    -0
      package-lock.json
  11. +3
    -1
      package.json
  12. +6
    -0
      parser/jaz.jison
  13. +0
    -209
      src/calculateWitness.js
  14. +0
    -156
      src/circuit_generator.js
  15. +27
    -0
      src/cli.js
  16. +279
    -0
      src/compiler.js
  17. +1
    -2
      src/exec.js
  18. +12
    -12
      src/gencode.js
  19. +9
    -1
      src/lcalgebra.js
  20. +2371
    -0
      sum.json
  21. +18
    -0
      test/circuits/constants_test.jaz
  22. +1
    -1
      test/circuits/sum_test.jaz
  23. +14
    -0
      test/sha256.js
  24. +0
    -0
      test_old/commandline.js
  25. +0
    -0
      test_old/jorge.prg
  26. +0
    -0
      test_old/mainTest.js
  27. +0
    -0
      test_old/test1.jaz
  28. +0
    -0
      test_old/test10.jaz
  29. +0
    -0
      test_old/test11.jaz
  30. +0
    -0
      test_old/test12.jaz
  31. +0
    -0
      test_old/test13.jaz
  32. +0
    -0
      test_old/test14.jaz
  33. +0
    -0
      test_old/test2.jaz
  34. +0
    -0
      test_old/test3.jaz
  35. +0
    -0
      test_old/test4.jaz
  36. +0
    -0
      test_old/test5.jaz
  37. +0
    -0
      test_old/test6.jaz
  38. +0
    -0
      test_old/test7.jaz
  39. +0
    -0
      test_old/test8.jaz
  40. +0
    -0
      test_old/test9.jaz

+ 1226
- 0
barry.js
File diff suppressed because it is too large
View File


+ 43
- 0
circuits/barry.jaz

@ -0,0 +1,43 @@
template AND() {
signal input a;
signal input b;
signal output c;
c <== a*b;
}
template AND3() {
signal input in1;
signal input in2;
signal input in3;
signal output out;
component and1 = AND();
component and2 = AND();
in1 ==> and1.a;
in2 ==> and1.b;
in3 ==> and2.a;
and1.c ==> and2.b;
and2.c ==> out;
}
template ToBin() {
signal input in;
signal output out[32];
var lc = 0;
for (var i=0; i<32; i++) {
out[i] <-- (in >> i) & 1;
lc = lc + out[i] * 2**i;
out[i]*(out[i]-1) === 0;
}
lc === in;
}
component main = ToBin();

+ 2
- 2
circuits/sha256/constants.jaz

@ -12,7 +12,7 @@ template H(x) {
0x5be0cd19]; 0x5be0cd19];
for (var i=0; i<32; i++) { for (var i=0; i<32; i++) {
out[i] = (c[x] >> i) & 1;
out[i] <== (c[x] >> i) & 1;
} }
} }
@ -30,6 +30,6 @@ template K(x) {
]; ];
for (var i=0; i<32; i++) { for (var i=0; i<32; i++) {
out[i] = (c[x] >> i) & 1;
out[i] <== (c[x] >> i) & 1;
} }
} }

+ 18
- 0
circuits/sha256/constants_test.jaz

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

+ 290
- 0
constant_test.json

@ -0,0 +1,290 @@
{
"mainCode": "{\n {\n }\n}\n",
"signalName2Idx": {
"one": 0,
"main.in": 1,
"main.h0.out[0]": 2,
"main.h0.out[1]": 3,
"main.h0.out[2]": 4,
"main.h0.out[3]": 5,
"main.h0.out[4]": 6,
"main.h0.out[5]": 7,
"main.h0.out[6]": 8,
"main.h0.out[7]": 9,
"main.h0.out[8]": 10,
"main.h0.out[9]": 11,
"main.h0.out[10]": 12,
"main.h0.out[11]": 13,
"main.h0.out[12]": 14,
"main.h0.out[13]": 15,
"main.h0.out[14]": 16,
"main.h0.out[15]": 17,
"main.h0.out[16]": 18,
"main.h0.out[17]": 19,
"main.h0.out[18]": 20,
"main.h0.out[19]": 21,
"main.h0.out[20]": 22,
"main.h0.out[21]": 23,
"main.h0.out[22]": 24,
"main.h0.out[23]": 25,
"main.h0.out[24]": 26,
"main.h0.out[25]": 27,
"main.h0.out[26]": 28,
"main.h0.out[27]": 29,
"main.h0.out[28]": 30,
"main.h0.out[29]": 31,
"main.h0.out[30]": 32,
"main.h0.out[31]": 33
},
"components": [
{
"name": "main",
"params": {},
"template": "A",
"inputSignals": 1
},
{
"name": "main.h0",
"params": {
"x": "8"
},
"template": "K",
"inputSignals": 0
}
],
"componentName2Idx": {
"main": 0,
"main.h0": 1
},
"signals": [
{
"names": [
"one"
],
"triggerComponents": []
},
{
"names": [
"main.in"
],
"triggerComponents": [
0
]
},
{
"names": [
"main.h0.out[0]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[1]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[2]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[3]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[4]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[5]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[6]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[7]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[8]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[9]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[10]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[11]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[12]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[13]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[14]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[15]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[16]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[17]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[18]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[19]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[20]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[21]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[22]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[23]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[24]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[25]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[26]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[27]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[28]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[29]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[30]"
],
"triggerComponents": []
},
{
"names": [
"main.h0.out[31]"
],
"triggerComponents": []
}
],
"constrains": [
[
{},
{},
{
"0": "21888242871839275222246405745257275088548364400416034343698204186572184114537",
"1": "1"
}
]
],
"templates": {
"H": "function(ctx) {\n ctx.setVar(\"c\", [], [\"1779033703\",\"3144134277\",\"1013904242\",\"2773480762\",\"1359893119\",\"2600822924\",\"528734635\",\"1541459225\"]);\n for (ctx.setVar(\"i\", [], \"0\");bigInt(ctx.getVar(\"i\",[])).lt(bigInt(\"32\")) ? 1 : 0;(ctx.setVar(\"i\", [], bigInt(ctx.getVar(\"i\",[])).add(bigInt(\"1\")).mod(__P__))).add(__P__).sub(bigInt(1)).mod(__P__))\n {\n ctx.setSignal(\"out\", [ctx.getVar(\"i\",[])], bigInt(bigInt(ctx.getVar(\"i\",[])).greater(bigInt(256)) ? 0 : bigInt(ctx.getVar(\"c\",[ctx.getVar(\"x\",[])])).shr(bigInt(ctx.getVar(\"i\",[]))).and(__MASK__)).and(bigInt(\"1\")).and(__MASK__));\n ctx.assert(ctx.getSignal(\"out\", [ctx.getVar(\"i\",[])]), bigInt(bigInt(ctx.getVar(\"i\",[])).greater(bigInt(256)) ? 0 : bigInt(ctx.getVar(\"c\",[ctx.getVar(\"x\",[])])).shr(bigInt(ctx.getVar(\"i\",[]))).and(__MASK__)).and(bigInt(\"1\")).and(__MASK__));\n }\n}\n",
"K": "function(ctx) {\n ctx.setVar(\"c\", [], [\"1116352408\",\"1899447441\",\"3049323471\",\"3921009573\",\"961987163\",\"1508970993\",\"2453635748\",\"2870763221\",\"3624381080\",\"310598401\",\"607225278\",\"1426881987\",\"1925078388\",\"2162078206\",\"2614888103\",\"3248222580\",\"3835390401\",\"4022224774\",\"264347078\",\"604807628\",\"770255983\",\"1249150122\",\"1555081692\",\"1996064986\",\"2554220882\",\"2821834349\",\"2952996808\",\"3210313671\",\"3336571891\",\"3584528711\",\"113926993\",\"338241895\",\"666307205\",\"773529912\",\"1294757372\",\"1396182291\",\"1695183700\",\"1986661051\",\"2177026350\",\"2456956037\",\"2730485921\",\"2820302411\",\"3259730800\",\"3345764771\",\"3516065817\",\"3600352804\",\"4094571909\",\"275423344\",\"430227734\",\"506948616\",\"659060556\",\"883997877\",\"958139571\",\"1322822218\",\"1537002063\",\"1747873779\",\"1955562222\",\"2024104815\",\"2227730452\",\"2361852424\",\"2428436474\",\"2756734187\",\"3204031479\",\"3329325298\"]);\n for (ctx.setVar(\"i\", [], \"0\");bigInt(ctx.getVar(\"i\",[])).lt(bigInt(\"32\")) ? 1 : 0;(ctx.setVar(\"i\", [], bigInt(ctx.getVar(\"i\",[])).add(bigInt(\"1\")).mod(__P__))).add(__P__).sub(bigInt(1)).mod(__P__))\n {\n ctx.setSignal(\"out\", [ctx.getVar(\"i\",[])], bigInt(bigInt(ctx.getVar(\"i\",[])).greater(bigInt(256)) ? 0 : bigInt(ctx.getVar(\"c\",[ctx.getVar(\"x\",[])])).shr(bigInt(ctx.getVar(\"i\",[]))).and(__MASK__)).and(bigInt(\"1\")).and(__MASK__));\n ctx.assert(ctx.getSignal(\"out\", [ctx.getVar(\"i\",[])]), bigInt(bigInt(ctx.getVar(\"i\",[])).greater(bigInt(256)) ? 0 : bigInt(ctx.getVar(\"c\",[ctx.getVar(\"x\",[])])).shr(bigInt(ctx.getVar(\"i\",[]))).and(__MASK__)).and(bigInt(\"1\")).and(__MASK__));\n }\n}\n",
"A": "function(ctx) {\n ctx.setVar(\"lc\", [], \"0\");\n ctx.setVar(\"e\", [], \"1\");\n for (ctx.setVar(\"i\", [], \"0\");bigInt(ctx.getVar(\"i\",[])).lt(bigInt(\"32\")) ? 1 : 0;(ctx.setVar(\"i\", [], bigInt(ctx.getVar(\"i\",[])).add(bigInt(\"1\")).mod(__P__))).add(__P__).sub(bigInt(1)).mod(__P__))\n {\n ctx.setVar(\"lc\", [], bigInt(ctx.getVar(\"lc\",[])).add(bigInt(bigInt(ctx.getVar(\"e\",[])).mul(bigInt(ctx.getPin(\"h0\", [], \"out\", [ctx.getVar(\"i\",[])]))).mod(__P__))).mod(__P__));\n ctx.setVar(\"e\", [], bigInt(ctx.getVar(\"e\",[])).mul(bigInt(\"2\")).mod(__P__));\n }\n ctx.assert(ctx.getVar(\"lc\",[]), ctx.getSignal(\"in\", []));\n}\n"
},
"functions": {},
"nPrvInputs": 0,
"nPubInputs": 1,
"nInputs": 1,
"nOutputs": 0,
"nVars": 2,
"nConstants": 32,
"nSignals": 34
}

+ 1
- 0
index.js

@ -0,0 +1 @@
module.exports = require("./src/compiler.js");

+ 3
- 0
input_barry.json

@ -0,0 +1,3 @@
{
"in": "10"
}

+ 103
- 95
jaz.js
File diff suppressed because it is too large
View File


+ 1
- 0
output_barry.json

@ -0,0 +1 @@
["1","10","0","1","0","1","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"]

+ 261
- 0
package-lock.json

@ -4,6 +4,18 @@
"lockfileVersion": 1, "lockfileVersion": 1,
"requires": true, "requires": true,
"dependencies": { "dependencies": {
"JSONSelect": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/JSONSelect/-/JSONSelect-0.4.0.tgz",
"integrity": "sha1-oI7cxn6z/L6Z7WMIVTRKDPKCu40=",
"dev": true
},
"JSV": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/JSV/-/JSV-4.0.2.tgz",
"integrity": "sha1-0Hf2glVx+CEy+d/67Vh7QCn+/1c=",
"dev": true
},
"acorn": { "acorn": {
"version": "5.7.1", "version": "5.7.1",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-5.7.1.tgz", "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.7.1.tgz",
@ -37,6 +49,13 @@
"integrity": "sha1-6GuBnGAs+IIa1jdBNpjx3sAhhHo=", "integrity": "sha1-6GuBnGAs+IIa1jdBNpjx3sAhhHo=",
"dev": true "dev": true
}, },
"amdefine": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/amdefine/-/amdefine-1.0.1.tgz",
"integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=",
"dev": true,
"optional": true
},
"ansi-escapes": { "ansi-escapes": {
"version": "3.1.0", "version": "3.1.0",
"resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz",
@ -85,6 +104,12 @@
"integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=",
"dev": true "dev": true
}, },
"assertion-error": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz",
"integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==",
"dev": true
},
"babel-code-frame": { "babel-code-frame": {
"version": "6.26.0", "version": "6.26.0",
"resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz",
@ -141,6 +166,12 @@
"concat-map": "0.0.1" "concat-map": "0.0.1"
} }
}, },
"browser-stdout": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz",
"integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==",
"dev": true
},
"caller-path": { "caller-path": {
"version": "0.1.0", "version": "0.1.0",
"resolved": "https://registry.npmjs.org/caller-path/-/caller-path-0.1.0.tgz", "resolved": "https://registry.npmjs.org/caller-path/-/caller-path-0.1.0.tgz",
@ -156,6 +187,20 @@
"integrity": "sha1-r6uWJikQp/M8GaV3WCXGnzTjUMo=", "integrity": "sha1-r6uWJikQp/M8GaV3WCXGnzTjUMo=",
"dev": true "dev": true
}, },
"chai": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chai/-/chai-4.1.2.tgz",
"integrity": "sha1-D2RYS6ZC8PKs4oBiefTwbKI61zw=",
"dev": true,
"requires": {
"assertion-error": "^1.0.1",
"check-error": "^1.0.1",
"deep-eql": "^3.0.0",
"get-func-name": "^2.0.0",
"pathval": "^1.0.0",
"type-detect": "^4.0.0"
}
},
"chalk": { "chalk": {
"version": "2.4.1", "version": "2.4.1",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz",
@ -193,12 +238,27 @@
"integrity": "sha1-tUc7M9yXxCTl2Y3IfVXU2KKci/I=", "integrity": "sha1-tUc7M9yXxCTl2Y3IfVXU2KKci/I=",
"dev": true "dev": true
}, },
"check-error": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz",
"integrity": "sha1-V00xLt2Iu13YkS6Sht1sCu1KrII=",
"dev": true
},
"circular-json": { "circular-json": {
"version": "0.3.3", "version": "0.3.3",
"resolved": "https://registry.npmjs.org/circular-json/-/circular-json-0.3.3.tgz", "resolved": "https://registry.npmjs.org/circular-json/-/circular-json-0.3.3.tgz",
"integrity": "sha512-UZK3NBx2Mca+b5LsG7bY183pHWt5Y1xts4P3Pz7ENTwGVnJOUWbRb3ocjvX7hx9tq/yTAdclXm9sZ38gNuem4A==", "integrity": "sha512-UZK3NBx2Mca+b5LsG7bY183pHWt5Y1xts4P3Pz7ENTwGVnJOUWbRb3ocjvX7hx9tq/yTAdclXm9sZ38gNuem4A==",
"dev": true "dev": true
}, },
"cjson": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/cjson/-/cjson-0.3.0.tgz",
"integrity": "sha1-5kObkHA9MS/24iJAl76pLOPQKhQ=",
"dev": true,
"requires": {
"jsonlint": "1.6.0"
}
},
"cli-cursor": { "cli-cursor": {
"version": "2.1.0", "version": "2.1.0",
"resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz", "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz",
@ -229,6 +289,18 @@
"integrity": "sha1-SxQVMEz1ACjqgWQ2Q72C6gWANok=", "integrity": "sha1-SxQVMEz1ACjqgWQ2Q72C6gWANok=",
"dev": true "dev": true
}, },
"colors": {
"version": "0.5.1",
"resolved": "https://registry.npmjs.org/colors/-/colors-0.5.1.tgz",
"integrity": "sha1-fQAj6usVTo7p/Oddy5I9DtFmd3Q=",
"dev": true
},
"commander": {
"version": "2.15.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.15.1.tgz",
"integrity": "sha512-VlfT9F3V0v+jr4yxPc5gg9s62/fIVWsd2Bk2iD435um1NlGMYdVCq+MjcXnhYq2icNOizHr1kK+5TI6H0Hy0ag==",
"dev": true
},
"concat-map": { "concat-map": {
"version": "0.0.1", "version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
@ -257,6 +329,15 @@
"ms": "2.0.0" "ms": "2.0.0"
} }
}, },
"deep-eql": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-3.0.1.tgz",
"integrity": "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw==",
"dev": true,
"requires": {
"type-detect": "^4.0.0"
}
},
"deep-is": { "deep-is": {
"version": "0.1.3", "version": "0.1.3",
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz",
@ -288,6 +369,12 @@
"rimraf": "^2.2.8" "rimraf": "^2.2.8"
} }
}, },
"diff": {
"version": "3.5.0",
"resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz",
"integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==",
"dev": true
},
"doctrine": { "doctrine": {
"version": "2.1.0", "version": "2.1.0",
"resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz",
@ -297,6 +384,12 @@
"esutils": "^2.0.2" "esutils": "^2.0.2"
} }
}, },
"ebnf-parser": {
"version": "0.1.10",
"resolved": "https://registry.npmjs.org/ebnf-parser/-/ebnf-parser-0.1.10.tgz",
"integrity": "sha1-zR9rpHfFY4xAyX7ZtXLbW6tdgzE=",
"dev": true
},
"es-abstract": { "es-abstract": {
"version": "1.12.0", "version": "1.12.0",
"resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.12.0.tgz", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.12.0.tgz",
@ -327,6 +420,38 @@
"integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=",
"dev": true "dev": true
}, },
"escodegen": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.3.3.tgz",
"integrity": "sha1-8CQBb1qI4Eb9EgBQVek5gC5sXyM=",
"dev": true,
"requires": {
"esprima": "~1.1.1",
"estraverse": "~1.5.0",
"esutils": "~1.0.0",
"source-map": "~0.1.33"
},
"dependencies": {
"esprima": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/esprima/-/esprima-1.1.1.tgz",
"integrity": "sha1-W28VR/TRAuZw4UDFCb5ncdautUk=",
"dev": true
},
"estraverse": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/estraverse/-/estraverse-1.5.1.tgz",
"integrity": "sha1-hno+jlip+EYYr7bC3bzZFrfLr3E=",
"dev": true
},
"esutils": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/esutils/-/esutils-1.0.0.tgz",
"integrity": "sha1-gVHTWOIMisx/t0XnRywAJf5JZXA=",
"dev": true
}
}
},
"eslint": { "eslint": {
"version": "5.0.1", "version": "5.0.1",
"resolved": "https://registry.npmjs.org/eslint/-/eslint-5.0.1.tgz", "resolved": "https://registry.npmjs.org/eslint/-/eslint-5.0.1.tgz",
@ -528,6 +653,12 @@
"integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=",
"dev": true "dev": true
}, },
"get-func-name": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.0.tgz",
"integrity": "sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=",
"dev": true
},
"glob": { "glob": {
"version": "7.1.2", "version": "7.1.2",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz",
@ -568,6 +699,12 @@
"integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=", "integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=",
"dev": true "dev": true
}, },
"growl": {
"version": "1.10.5",
"resolved": "https://registry.npmjs.org/growl/-/growl-1.10.5.tgz",
"integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==",
"dev": true
},
"has": { "has": {
"version": "1.0.3", "version": "1.0.3",
"resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz",
@ -598,6 +735,12 @@
"integrity": "sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q=", "integrity": "sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q=",
"dev": true "dev": true
}, },
"he": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/he/-/he-1.1.1.tgz",
"integrity": "sha1-k0EP0hsAlzUVH4howvJx80J+I/0=",
"dev": true
},
"iconv-lite": { "iconv-lite": {
"version": "0.4.23", "version": "0.4.23",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.23.tgz", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.23.tgz",
@ -731,6 +874,40 @@
"integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=",
"dev": true "dev": true
}, },
"jison": {
"version": "0.4.18",
"resolved": "https://registry.npmjs.org/jison/-/jison-0.4.18.tgz",
"integrity": "sha512-FKkCiJvozgC7VTHhMJ00a0/IApSxhlGsFIshLW6trWJ8ONX2TQJBBz6DlcO1Gffy4w9LT+uL+PA+CVnUSJMF7w==",
"dev": true,
"requires": {
"JSONSelect": "0.4.0",
"cjson": "0.3.0",
"ebnf-parser": "0.1.10",
"escodegen": "1.3.x",
"esprima": "1.1.x",
"jison-lex": "0.3.x",
"lex-parser": "~0.1.3",
"nomnom": "1.5.2"
},
"dependencies": {
"esprima": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/esprima/-/esprima-1.1.1.tgz",
"integrity": "sha1-W28VR/TRAuZw4UDFCb5ncdautUk=",
"dev": true
}
}
},
"jison-lex": {
"version": "0.3.4",
"resolved": "https://registry.npmjs.org/jison-lex/-/jison-lex-0.3.4.tgz",
"integrity": "sha1-gcoo2E+ESZ36jFlNzePYo/Jux6U=",
"dev": true,
"requires": {
"lex-parser": "0.1.x",
"nomnom": "1.5.2"
}
},
"js-tokens": { "js-tokens": {
"version": "3.0.2", "version": "3.0.2",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz",
@ -759,6 +936,16 @@
"integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=",
"dev": true "dev": true
}, },
"jsonlint": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/jsonlint/-/jsonlint-1.6.0.tgz",
"integrity": "sha1-iKpGvCiaesk7tGyuLVihh6m7SUo=",
"dev": true,
"requires": {
"JSV": ">= 4.0.x",
"nomnom": ">= 1.5.x"
}
},
"levn": { "levn": {
"version": "0.3.0", "version": "0.3.0",
"resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz",
@ -769,6 +956,12 @@
"type-check": "~0.3.2" "type-check": "~0.3.2"
} }
}, },
"lex-parser": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/lex-parser/-/lex-parser-0.1.4.tgz",
"integrity": "sha1-ZMTwJfF/1Tv7RXY/rrFvAVp0dVA=",
"dev": true
},
"lodash": { "lodash": {
"version": "4.17.10", "version": "4.17.10",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.10.tgz", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.10.tgz",
@ -812,6 +1005,36 @@
} }
} }
}, },
"mocha": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/mocha/-/mocha-5.2.0.tgz",
"integrity": "sha512-2IUgKDhc3J7Uug+FxMXuqIyYzH7gJjXECKe/w43IGgQHTSj3InJi+yAA7T24L9bQMRKiUEHxEX37G5JpVUGLcQ==",
"dev": true,
"requires": {
"browser-stdout": "1.3.1",
"commander": "2.15.1",
"debug": "3.1.0",
"diff": "3.5.0",
"escape-string-regexp": "1.0.5",
"glob": "7.1.2",
"growl": "1.10.5",
"he": "1.1.1",
"minimatch": "3.0.4",
"mkdirp": "0.5.1",
"supports-color": "5.4.0"
},
"dependencies": {
"supports-color": {
"version": "5.4.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.4.0.tgz",
"integrity": "sha512-zjaXglF5nnWpsq470jSv6P9DwPvgLkuapYmfDm3JWOm0vkNTVF2tI4UrN2r6jH1qM/uc/WtxYY1hYoA2dOKj5w==",
"dev": true,
"requires": {
"has-flag": "^3.0.0"
}
}
}
},
"ms": { "ms": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
@ -836,6 +1059,16 @@
"integrity": "sha512-2NpiFHqC87y/zFke0fC0spBXL3bBsoh/p5H1EFhshxjCR5+0g2d6BiXbUFz9v1sAcxsk2htp2eQnNIci2dIYcA==", "integrity": "sha512-2NpiFHqC87y/zFke0fC0spBXL3bBsoh/p5H1EFhshxjCR5+0g2d6BiXbUFz9v1sAcxsk2htp2eQnNIci2dIYcA==",
"dev": true "dev": true
}, },
"nomnom": {
"version": "1.5.2",
"resolved": "https://registry.npmjs.org/nomnom/-/nomnom-1.5.2.tgz",
"integrity": "sha1-9DRUSKhTz71cDSYyDyR3qwUm/i8=",
"dev": true,
"requires": {
"colors": "0.5.x",
"underscore": "1.1.x"
}
},
"object-assign": { "object-assign": {
"version": "4.1.1", "version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
@ -921,6 +1154,12 @@
"integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=",
"dev": true "dev": true
}, },
"pathval": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.0.tgz",
"integrity": "sha1-uULm1L3mUwBe9rcTYd74cn0GReA=",
"dev": true
},
"pify": { "pify": {
"version": "2.3.0", "version": "2.3.0",
"resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
@ -1082,6 +1321,16 @@
"is-fullwidth-code-point": "^2.0.0" "is-fullwidth-code-point": "^2.0.0"
} }
}, },
"source-map": {
"version": "0.1.43",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.1.43.tgz",
"integrity": "sha1-wkvBRspRfBRx9drL4lcbK3+eM0Y=",
"dev": true,
"optional": true,
"requires": {
"amdefine": ">=0.0.4"
}
},
"sprintf-js": { "sprintf-js": {
"version": "1.0.3", "version": "1.0.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
@ -1190,6 +1439,18 @@
"prelude-ls": "~1.1.2" "prelude-ls": "~1.1.2"
} }
}, },
"type-detect": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz",
"integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==",
"dev": true
},
"underscore": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/underscore/-/underscore-1.1.7.tgz",
"integrity": "sha1-QLq4S60Z0jAJbo1u9ii/8FXYPbA=",
"dev": true
},
"uri-js": { "uri-js": {
"version": "4.2.2", "version": "4.2.2",
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz",

+ 3
- 1
package.json

@ -7,7 +7,8 @@
"test": "test" "test": "test"
}, },
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "mocha",
"buildParser": "jison parser/jaz.jison"
}, },
"keywords": [ "keywords": [
"zkSnarks", "zkSnarks",
@ -25,6 +26,7 @@
"optimist": "^0.6.1" "optimist": "^0.6.1"
}, },
"devDependencies": { "devDependencies": {
"chai": "^4.1.2",
"eslint": "^5.0.1", "eslint": "^5.0.1",
"eslint-plugin-mocha": "^5.0.0" "eslint-plugin-mocha": "^5.0.0"
} }

+ 6
- 0
parser/jaz.jison

@ -10,6 +10,7 @@
\/\/.* { /* console.log("SINGLE LINE COMMENT: "+yytext); */ } \/\/.* { /* console.log("SINGLE LINE COMMENT: "+yytext); */ }
var { return 'var'; } var { return 'var'; }
signal { return 'signal'; } signal { return 'signal'; }
private { return 'private'; }
input { return 'input'; } input { return 'input'; }
output { return 'output'; } output { return 'output'; }
linearCombination { return 'linearCombination'; } linearCombination { return 'linearCombination'; }
@ -822,6 +823,11 @@ declaration
$$ = {type: "DECLARE", declareType: "SIGNALIN", name: $3}; $$ = {type: "DECLARE", declareType: "SIGNALIN", name: $3};
setLines($$, @1, @3); setLines($$, @1, @3);
} }
| 'signal' 'private' 'input' simpleLeftHandExpression %prec DECL
{
$$ = {type: "DECLARE", declareType: "SIGNALIN", private: true, name: $4};
setLines($$, @1, @4);
}
| 'signal' 'output' simpleLeftHandExpression %prec DECL | 'signal' 'output' simpleLeftHandExpression %prec DECL
{ {
$$ = {type: "DECLARE", declareType: "SIGNALOUT", name: $3}; $$ = {type: "DECLARE", declareType: "SIGNALOUT", name: $3};

+ 0
- 209
src/calculateWitness.js

@ -1,209 +0,0 @@
const bigInt = require("big-integer");
module.exports = calculateWitness;
function calculateWitness(circuit, inputSignals) {
const ctx = new RTCtx(circuit);
function iterateSelector(values, sels, cb) {
if (!Array.isArray(values)) {
return cb(sels, values);
}
for (let i=0; i<values.length; i++) {
sels.push(i);
iterateSelector(values[i], sels, cb);
sels.pop(i);
}
}
ctx.setSignal("one", [], bigInt(1));
for (let c in ctx.notInitSignals) {
if (ctx.notInitSignals[c] == 0) ctx.triggerComponent(c);
}
for (let s in inputSignals) {
ctx.currentComponent = "main";
iterateSelector(inputSignals[s], [], function(selector, value) {
ctx.setSignal(s, selector, bigInt(value));
});
}
for (let i=0; i<ctx.witness.length; i++) {
if (typeof(ctx.witness[i]) == "undefined") {
throw("Signal not assigned: " + ctx.circuit.witnessNames[i].join(", "));
}
console.log(ctx.circuit.witnessNames[i].join(",") + " --> " + ctx.witness[i].toString());
}
return ctx.witness;
}
class RTCtx {
constructor(circuit) {
this.scopes = [];
this.circuit = circuit;
this.witness = [];
this.notInitSignals = {};
for (let c in this.circuit.components) {
this.notInitSignals[c] = this.circuit.components[c].inputSignals;
if (this.notInitSignals == 0) {
this.currentComponent = c;
this.components.calc(this);
this.currentComponent = null;
}
}
}
_sels2str(sels) {
let res = "";
for (let i=0; i<sels.length; i++) {
res += `[${sels[i]}]`;
}
return res;
}
setPin(componentName, componentSels, signalName, signalSels, value) {
let fullName = componentName=="one" ? "one" : this.currentComponent + "." + componentName;
fullName += this._sels2str(componentSels) +
"."+
signalName+
this._sels2str(signalSels);
this.setSignalFullName(fullName, value);
}
setSignal(name, sels, value) {
let fullName = this.currentComponent ? this.currentComponent + "." + name : name;
fullName += this._sels2str(sels);
this.setSignalFullName(fullName, value);
}
triggerComponent(c) {
console.log("Component Treiggered: " + c);
// Set notInitSignals to -1 to not initialize again
this.notInitSignals[c] --;
const oldComponent = this.currentComponent;
this.currentComponent = c;
const template = this.circuit.components[c].template;
const newScope = {};
for (let p in this.circuit.components[c].params) {
newScope[p] = this.circuit.components[c].params[p];
}
const oldScope = this.scopes;
this.scopes = [ this.scopes[0], newScope ];
// TODO set params.
this.circuit.templates[template](this);
this.scopes = oldScope;
this.currentComponent = oldComponent;
}
callFunction(functionName, params) {
const newScope = {};
for (let p=0; p<this.circuit.functionParams[functionName].length; p++) {
const paramName = this.circuit.functionParams[functionName][p];
newScope[paramName] = params[p];
}
const oldScope = this.scopes;
this.scopes = [ this.scopes[0], newScope ];
// TODO set params.
const res = this.circuit.functions[functionName](this);
this.scopes = oldScope;
return res;
}
setSignalFullName(fullName, value) {
console.log("set " + fullName + " <-- " + value.toString());
const sId = this.circuit.signals[fullName].id;
let firstInit =false;
if (!this.witness[sId]) {
firstInit = true;
}
this.witness[sId] = value;
const callComponents = [];
for (let i=0; i<this.circuit.witnessNames[sId].length; i++) {
const ss = this.circuit.witnessNames[sId][i];
if (this.circuit.signals[ss].direction == "IN") {
if (firstInit) this.notInitSignals[ this.circuit.signals[ss].component] --;
callComponents.push(this.circuit.signals[ss].component);
}
}
for (let i in callComponents) {
const c= callComponents[i];
if (this.notInitSignals[c] == 0) this.triggerComponent(c);
}
return value;
}
setVar(name, sels, value) {
function setVarArray(a, sels2, value) {
if (sels2.length == 1) {
a[sels2[0]] = value;
} else {
if (typeof(a[sels2[0]]) == "undefined") a[sels2[0]] = [];
setVarArray(a[sels2[0]], sels2.slice(1), value);
}
}
const scope = this.scopes[this.scopes.length-1];
if (sels.length == 0) {
scope[name] = value;
} else {
if (typeof(scope[name]) == "undefined") scope[name] = [];
setVarArray(scope[name], sels, value);
}
return value;
}
getVar(name, sels) {
function select(a, sels2) {
return (sels2.length == 0) ? a : select(a[sels2[0]], sels2.slice(1));
}
for (let i=this.scopes.length-1; i>=0; i--) {
if (typeof(this.scopes[i][name]) != "undefined") return select(this.scopes[i][name], sels);
}
throw new Error("Variable not defined: " + name);
}
getSignal(name, sels) {
let fullName = name=="one" ? "one" : this.currentComponent + "." + name;
fullName += this._sels2str(sels);
return this.getSignalFullName(fullName);
}
getPin(componentName, componentSels, signalName, signalSels) {
let fullName = componentName=="one" ? "one" : this.currentComponent + "." + componentName;
fullName += this._sels2str(componentSels) +
"."+
signalName+
this._sels2str(signalSels);
return this.getSignalFullName(fullName);
}
getSignalFullName(fullName) {
const sId = this.circuit.signals[fullName].id;
if (typeof(this.witness[sId]) == "undefined") {
throw new Error("Signal not initialized: "+fullName);
}
console.log("get --->" + fullName + " = " + this.witness[sId].toString() );
return this.witness[sId];
}
assert(a,b) {
const ba = bigInt(a);
const bb = bigInt(b);
if (!ba.equals(bb)) {
throw new Error("Constrain doesn't match: " + ba.toString() + " != " + bb.toString());
}
}
}

+ 0
- 156
src/circuit_generator.js

@ -1,156 +0,0 @@
const fs = require("fs");
const path = require("path");
const bigInt = require("big-integer");
const __P__ = new bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
const __MASK__ = new bigInt(2).pow(253).minus(1);
const assert = require("assert");
const gen = require("./gencode");
const exec = require("./exec");
const lc = require("./lcalgebra");
const argv = require("optimist")
.alias("c", "circuit")
.alias("o", "output")
.alias("w", "witnes")
.argv;
const parser = require("../jaz.js").parser;
const fullFileName = path.resolve(process.cwd(), argv.circuit);
const fullFilePath = path.dirname(fullFileName);
const src = fs.readFileSync(fullFileName, "utf8");
const ast = parser.parse(src);
assert(ast.type == "BLOCK");
const ctx = {
scopes: [{}],
signals: {
one: {
fullName: "one",
value: bigInt(1),
equivalence: "",
direction: ""
}
},
currentComponent: "",
constrains: [],
components: {},
templates: {},
functions: {},
functionParams: {},
filePath: fullFilePath,
fileName: fullFileName
};
exec(ctx, ast);
reduceConstrains(ctx);
generateWitnessNames(ctx);
generateWitnessConstrains(ctx);
if (ctx.error) {
console.log(`ERROR at ${ctx.error.errFile}:${ctx.error.pos.first_line},${ctx.error.pos.first_column}-${ctx.error.pos.last_line},${ctx.error.pos.last_column} ${ctx.error.errStr}`);
console.log(JSON.stringify(ctx.error.ast, null, 1));
process.exit(1);
}
/*
console.log("SIGNALS");
console.log("==========");
for (let key in ctx.signals) {
const signal = ctx.signals[key];
console.log(signal.fullName);
}
console.log("CONSTRAINS");
console.log("==========");
for (let i=0; i<ctx.constrains.length; i++) {
console.log(lc.toString(ctx.constrains[i], ctx) + " === 0");
}
*/
ctx.scopes = [{}];
const mainCode = gen(ctx,ast);
if (ctx.error) {
console.log(`ERROR at ${ctx.error.pos.first_line},${ctx.error.pos.first_column}-${ctx.error.pos.last_line},${ctx.error.pos.last_column} ${ctx.error.errStr}`);
console.log(JSON.stringify(ctx.error.ast, null, 1));
process.exit(1);
}
let outCode = "";
outCode += "const bigInt = require(\"big-integer\");\n";
outCode += "const __P__ = new bigInt(\"21888242871839275222246405745257275088696311157297823662689037894645226208583\");\n";
outCode += "const __MASK__ = new bigInt(2).pow(253).minus(1);\n";
outCode += "const circuit = {};\n";
outCode += "module.exports = circuit;\n\n";
outCode += `circuit.signals=${JSON.stringify(ctx.signals, null, 1)};\n\n`;
outCode += `circuit.components=${JSON.stringify(ctx.components, null, 1)};\n\n`;
outCode += `circuit.signalConstrains=${JSON.stringify(ctx.constrains, null, 1)};\n\n`;
outCode += `circuit.witnessNames=${JSON.stringify(ctx.witnessNames, null, 1)};\n\n`;
outCode += mainCode;
outCode += "\ncircuit.templates = {};\n";
for (let t in ctx.templates) {
outCode += `\ncircuit.templates["${t}"] = ${ctx.templates[t]};\n`;
}
outCode += `circuit.functionParams=${JSON.stringify(ctx.functionParams, null, 1)};\n\n`;
outCode += "\ncircuit.functions = {};\n";
for (let f in ctx.functions) {
outCode += `\ncircuit.functions["${f}"] = ${ctx.functions[f]};\n`;
}
/*
console.log("CODE");
console.log("====");
console.log(outCode);
*/
console.log("#Constrains:" +ctx.constrains.length);
fs.writeFileSync(argv.output, outCode, "utf8");
function generateWitnessNames(ctx) {
ctx.witnessNames = [];
for (let c in ctx.components) {
ctx.components[c].inputSignals = 0;
}
for (let s in ctx.signals) {
const signal = ctx.signals[s];
let lSignal = signal;
while (lSignal.equivalence) {
lSignal = ctx.signals[lSignal.equivalence];
}
if ( typeof(lSignal.id) === "undefined" ) {
lSignal.id = ctx.witnessNames.length;
ctx.witnessNames.push([]);
}
if (signal.direction == "IN") {
ctx.components[signal.component].inputSignals++;
}
signal.id = lSignal.id;
ctx.witnessNames[signal.id].push(signal.fullName);
}
}
function reduceConstrains(ctx) {
const newConstrains = [];
for (let i=0; i<ctx.constrains.length; i++) {
const c = lc.canonize(ctx, ctx.constrains[i]);
if (!lc.isZero(c)) {
newConstrains.push(c);
}
}
ctx.constrains = newConstrains;
}
function generateWitnessConstrains(ctx) {
}

+ 27
- 0
src/cli.js

@ -0,0 +1,27 @@
/* eslint-disable no-console */
const fs = require("fs");
const path = require("path");
const compiler = require("./compiler");
const argv = require("yargs")
.usage("jaz -s [input source circuit file] -o [output definition circuit file]")
.alias("s", "source")
.alias("o", "output")
.require(["s","o"])
.argv;
const fullFileName = path.resolve(process.cwd(), argv.source);
compiler(fullFileName).then( (cir) => {
fs.writeFileSync(argv.output, JSON.stringify(cir, null, 1), "utf8");
}, (err) => {
console.error(`ERROR at ${err.errFile}:${err.pos.first_line},${err.pos.first_column}-${err.pos.last_line},${err.pos.last_column} ${err.errStr}`);
console.error(JSON.stringify(err.ast, null, 1));
process.exit(1);
});

+ 279
- 0
src/compiler.js

@ -0,0 +1,279 @@
const fs = require("fs");
const path = require("path");
const bigInt = require("big-integer");
const __P__ = new bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
const __MASK__ = new bigInt(2).pow(253).minus(1);
const assert = require("assert");
const gen = require("./gencode");
const exec = require("./exec");
const lc = require("./lcalgebra");
module.exports = compile;
const parser = require("../jaz.js").parser;
function compile(srcFile) {
return new Promise ((resolve, reject) => {
const fullFileName = srcFile;
const fullFilePath = path.dirname(fullFileName);
const src = fs.readFileSync(fullFileName, "utf8");
const ast = parser.parse(src);
assert(ast.type == "BLOCK");
const ctx = {
scopes: [{}],
signals: {
one: {
fullName: "one",
value: bigInt(1),
equivalence: "",
direction: ""
}
},
currentComponent: "",
constrains: [],
components: {},
templates: {},
functions: {},
functionParams: {},
filePath: fullFilePath,
fileName: fullFileName
};
exec(ctx, ast);
reduceConstrains(ctx);
generateWitnessNames(ctx);
if (ctx.error) {
reject(ctx.error);
}
ctx.scopes = [{}];
const mainCode = gen(ctx,ast);
if (ctx.error) reject(ctx.error);
const def = buildCircuitDef(ctx, mainCode);
resolve(def);
});
}
function generateWitnessNames(ctx) {
const totals = {
"output": 0,
"pubInput": 0,
"one": 0,
"prvInput": 0,
"internal": 0,
"constant": 0,
};
const ids = {};
function priorize(t1, t2) {
if ((t1 == "error") || (t2=="error")) return "error";
if (t1 == "internal") {
return t2;
} else if (t2=="internal") {
return t1;
}
if ((t1 == "one") || (t2 == "one")) return "one";
if ((t1 == "constant") || (t2 == "constant")) return "constant";
if (t1!=t2) return "error";
return t1;
}
// First classify the signals
for (let s in ctx.signals) {
const signal = ctx.signals[s];
let tAll = "internal";
let lSignal = signal;
let end = false;
while (!end) {
let t = lSignal.category || "internal";
if (s == "one") {
t = "one";
} else if (lSignal.value) {
t = "constant";
} else if (lSignal.component=="main") {
if (lSignal.direction == "IN") {
if (lSignal.private) {
t = "prvInput";
} else {
t = "pubInput";
}
} else if (lSignal.direction == "OUT") {
t = "output";
}
}
tAll = priorize(t,tAll);
if (lSignal.equivalence) {
lSignal = ctx.signals[lSignal.equivalence];
} else {
end=true;
}
}
if (tAll == "error") {
throw new Error("Incompatible types in signal: " + s);
}
if (lSignal.category) totals[lSignal.category]--;
lSignal.category = tAll;
totals[lSignal.category] ++;
}
ids["one"] = 0;
ids["output"] = 1;
ids["pubInput"] = ids["output"] + totals["output"];
ids["prvInput"] = ids["pubInput"] + totals["pubInput"];
ids["internal"] = ids["prvInput"] + totals["prvInput"];
ids["constant"] = ids["internal"] + totals["internal"];
const nSignals = ids["constant"] + totals["constant"];
ctx.signalNames = new Array(nSignals);
for (let i=0; i< nSignals; i++) ctx.signalNames[i] = [];
ctx.signalName2Idx = {};
for (let s in ctx.signals) {
const signal = ctx.signals[s];
let lSignal = signal;
while (lSignal.equivalence) {
lSignal = ctx.signals[lSignal.equivalence];
}
if ( typeof(lSignal.id) === "undefined" ) {
lSignal.id = ids[lSignal.category] ++;
}
signal.id = lSignal.id;
ctx.signalNames[signal.id].push(signal.fullName);
ctx.signalName2Idx[signal.fullName] = signal.id;
}
ctx.totals = totals;
}
function reduceConstrains(ctx) {
const newConstrains = [];
for (let i=0; i<ctx.constrains.length; i++) {
const c = lc.canonize(ctx, ctx.constrains[i]);
if (!lc.isZero(c)) {
newConstrains.push(c);
}
}
ctx.constrains = newConstrains;
}
function buildCircuitDef(ctx, mainCode) {
const res = {
mainCode: mainCode
};
res.signalName2Idx = ctx.signalName2Idx;
res.components = [];
res.componentName2Idx = {};
for (let c in ctx.components) {
const idCoponent = res.components.length;
res.components.push({
name: c,
params: ctx.components[c].params,
template: ctx.components[c].template,
inputSignals: 0
});
res.componentName2Idx[c] = idCoponent;
}
res.signals = new Array(ctx.signalNames.length);
for (let i=0; i<ctx.signalNames.length; i++) {
res.signals[i] = {
names: ctx.signalNames[i],
triggerComponents: []
};
ctx.signalNames[i].map( (fullName) => {
const idComponet = res.componentName2Idx[ctx.signals[fullName].component];
if (ctx.signals[fullName].direction == "IN") {
res.signals[i].triggerComponents.push(idComponet);
res.components[idComponet].inputSignals++;
}
});
}
res.constrains = buildConstrains(ctx);
res.templates = ctx.templates;
res.functions = {};
for (let f in ctx.functions) {
res.functions[f] = {
params: ctx.functionParams[f],
func: ctx.functions[f]
};
}
res.nPrvInputs = ctx.totals.prvInput;
res.nPubInputs = ctx.totals.pubInput;
res.nInputs = res.nPrvInputs + res.nPubInputs;
res.nOutputs = ctx.totals.output;
res.nVars = res.nInputs + res.nOutputs + ctx.totals.one + ctx.totals.internal;
res.nConstants = ctx.totals.constant;
res.nSignals = res.nVars + res.nConstants;
return res;
}
/*
Build constrains
A constrain like this
[s1 + 2*s2 + 3*s3] * [ s2 + 5*s4] - [s0 ] = 0
[ 5*s2 + 6*s3] * [ s2 + ] - [s0 + 2* s2] = 0
[s1 + s3] * [ s2 + 5*s3] - [s4 ] = 0
is converted to
[
[{"1":"1","2":"2","3":"3"} , {"2":"1","4":"5"} , {"0":"1" }],
[{ "2":"5","3":"6"} , {"2":"1" } , {"0":"1", "2":"2"}],
[{"1":"1", "3":"1"} , {"2":"1","3":"5"} , {"4":"1" }]
]
^ ^ ^
| | |
A B C
*/
function buildConstrains(ctx) {
const res = [];
function fillLC(dst, src) {
for (let s in src.values) {
const v = src.values[s].toString();
const id = ctx.signalName2Idx[s];
dst[id] = v;
}
}
for (let i=0; i<ctx.constrains.length; i++) {
const A = {};
const B = {};
const C = {};
fillLC(A, ctx.constrains[i].a);
fillLC(B, ctx.constrains[i].b);
fillLC(C, lc.negate(ctx.constrains[i].c));
res.push([A,B,C]);
}
return res;
}

+ 1
- 2
src/exec.js

@ -419,6 +419,7 @@ function execDeclareSignal(ctx, ast) {
ctx.signals[fullName] = { ctx.signals[fullName] = {
fullName: fullName, fullName: fullName,
direction: ast.declareType == "SIGNALIN" ? "IN" : (ast.declareType == "SIGNALOUT" ? "OUT" : ""), direction: ast.declareType == "SIGNALIN" ? "IN" : (ast.declareType == "SIGNALOUT" ? "OUT" : ""),
private: ast.private,
component: ctx.currentComponent, component: ctx.currentComponent,
equivalence: "", equivalence: "",
alias: [fullName] alias: [fullName]
@ -828,8 +829,6 @@ function execInclude(ctx, ast) {
const incFileName = path.resolve(ctx.filePath, ast.file); const incFileName = path.resolve(ctx.filePath, ast.file);
const incFilePath = path.dirname(incFileName); const incFilePath = path.dirname(incFileName);
console.log("Include: "+incFileName);
ctx.includedFiles = ctx.includedFiles || []; ctx.includedFiles = ctx.includedFiles || [];
if (ctx.includedFiles[incFileName]) return; if (ctx.includedFiles[incFileName]) return;

+ 12
- 12
src/gencode.js

@ -368,7 +368,7 @@ function genVarMulAssignement(ctx, ast) {
} }
function genPlusPlusRight(ctx, ast) { function genPlusPlusRight(ctx, ast) {
return `(${genVarAssignement(ctx, {values: [ast.values[0], {type: "OP", op: "+", values: [ast.values[0], {type: "NUMBER", value: bigInt(1)}]}]})}).add(__P__).minus(1).mod(__P__)`;
return `(${genVarAssignement(ctx, {values: [ast.values[0], {type: "OP", op: "+", values: [ast.values[0], {type: "NUMBER", value: bigInt(1)}]}]})}).add(__P__).sub(bigInt(1)).mod(__P__)`;
} }
function genPlusPlusLeft(ctx, ast) { function genPlusPlusLeft(ctx, ast) {
@ -380,7 +380,7 @@ function genAdd(ctx, ast) {
if (ctx.error) return; if (ctx.error) return;
const b = gen(ctx, ast.values[1]); const b = gen(ctx, ast.values[1]);
if (ctx.error) return; if (ctx.error) return;
return `bigInt(${a}).add(${b}).mod(__P__)`;
return `bigInt(${a}).add(bigInt(${b})).mod(__P__)`;
} }
function genMul(ctx, ast) { function genMul(ctx, ast) {
@ -388,7 +388,7 @@ function genMul(ctx, ast) {
if (ctx.error) return; if (ctx.error) return;
const b = gen(ctx, ast.values[1]); const b = gen(ctx, ast.values[1]);
if (ctx.error) return; if (ctx.error) return;
return `bigInt(${a}).times(${b}).mod(__P__)`;
return `bigInt(${a}).mul(bigInt(${b})).mod(__P__)`;
} }
function genSub(ctx, ast) { function genSub(ctx, ast) {
@ -396,7 +396,7 @@ function genSub(ctx, ast) {
if (ctx.error) return; if (ctx.error) return;
const b = gen(ctx, ast.values[1]); const b = gen(ctx, ast.values[1]);
if (ctx.error) return; if (ctx.error) return;
return `bigInt(${a}).add(__P__).minus(${b}).mod(__P__)`;
return `bigInt(${a}).add(__P__).sub(bigInt(${b})).mod(__P__)`;
} }
function genExp(ctx, ast) { function genExp(ctx, ast) {
@ -404,7 +404,7 @@ function genExp(ctx, ast) {
if (ctx.error) return; if (ctx.error) return;
const b = gen(ctx, ast.values[1]); const b = gen(ctx, ast.values[1]);
if (ctx.error) return; if (ctx.error) return;
return `bigInt(${a}).modPow(${b}, __P__)`;
return `bigInt(${a}).modPow(bigInt(${b}), __P__)`;
} }
function genBAnd(ctx, ast) { function genBAnd(ctx, ast) {
@ -412,7 +412,7 @@ function genBAnd(ctx, ast) {
if (ctx.error) return; if (ctx.error) return;
const b = gen(ctx, ast.values[1]); const b = gen(ctx, ast.values[1]);
if (ctx.error) return; if (ctx.error) return;
return `bigInt(${a}).and(${b}).and(__MASK__)`;
return `bigInt(${a}).and(bigInt(${b})).and(__MASK__)`;
} }
function genShl(ctx, ast) { function genShl(ctx, ast) {
@ -420,7 +420,7 @@ function genShl(ctx, ast) {
if (ctx.error) return; if (ctx.error) return;
const b = gen(ctx, ast.values[1]); const b = gen(ctx, ast.values[1]);
if (ctx.error) return; if (ctx.error) return;
return `bigInt(${b}).greater(256) ? 0 : bigInt(${a}).shiftLeft(bigInt(${b}).value).and(__MASK__)`;
return `bigInt(${b}).greater(bigInt(256)) ? 0 : bigInt(${a}).shl(bigInt(${b})).and(__MASK__)`;
} }
function genShr(ctx, ast) { function genShr(ctx, ast) {
@ -428,7 +428,7 @@ function genShr(ctx, ast) {
if (ctx.error) return; if (ctx.error) return;
const b = gen(ctx, ast.values[1]); const b = gen(ctx, ast.values[1]);
if (ctx.error) return; if (ctx.error) return;
return `bigInt(${b}).greater(256) ? 0 : bigInt(${a}).shiftRight(bigInt(${b}).value).and(__MASK__)`;
return `bigInt(${b}).greater(bigInt(256)) ? 0 : bigInt(${a}).shr(bigInt(${b})).and(__MASK__)`;
} }
function genLt(ctx, ast) { function genLt(ctx, ast) {
@ -436,7 +436,7 @@ function genLt(ctx, ast) {
if (ctx.error) return; if (ctx.error) return;
const b = gen(ctx, ast.values[1]); const b = gen(ctx, ast.values[1]);
if (ctx.error) return; if (ctx.error) return;
return `bigInt(${a}).lt(${b}) ? 1 : 0`;
return `bigInt(${a}).lt(bigInt(${b})) ? 1 : 0`;
} }
function genEq(ctx, ast) { function genEq(ctx, ast) {
@ -444,13 +444,13 @@ function genEq(ctx, ast) {
if (ctx.error) return; if (ctx.error) return;
const b = gen(ctx, ast.values[1]); const b = gen(ctx, ast.values[1]);
if (ctx.error) return; if (ctx.error) return;
return `bigInt(${a}).eq(${b}) ? 1 : 0`;
return `bigInt(${a}).eq(bigInt(${b})) ? 1 : 0`;
} }
function genUMinus(ctx, ast) { function genUMinus(ctx, ast) {
const a = gen(ctx, ast.values[0]); const a = gen(ctx, ast.values[0]);
if (ctx.error) return; if (ctx.error) return;
return `__P__.minus(bigInt(${a})).mod(__P__)`;
return `__P__.sub(bigInt(${a})).mod(__P__)`;
} }
function genTerCon(ctx, ast) { function genTerCon(ctx, ast) {
@ -460,7 +460,7 @@ function genTerCon(ctx, ast) {
if (ctx.error) return; if (ctx.error) return;
const c = gen(ctx, ast.values[2]); const c = gen(ctx, ast.values[2]);
if (ctx.error) return; if (ctx.error) return;
return `bigInt(${a}).neq(0) ? (${b}) : (${c})`;
return `bigInt(${a}).neq(bigInt(0)) ? (${b}) : (${c})`;
} }
function genInclude(ctx, ast) { function genInclude(ctx, ast) {

+ 9
- 1
src/lcalgebra.js

@ -418,7 +418,15 @@ function canonize(ctx, a) {
for (let k in a.values) { for (let k in a.values) {
let s = k; let s = k;
while (ctx.signals[s].equivalence) s= ctx.signals[s].equivalence; while (ctx.signals[s].equivalence) s= ctx.signals[s].equivalence;
if (s != k) {
if (typeof(ctx.signals[s].value) != "undefined") {
const v = a.values[k].times(ctx.signals[s].value).mod(__P__);
if (!a.values["one"]) {
a.values["one"]=v;
} else {
a.values["one"]= a.values["one"].add(v).mod(__P__);
}
delete a.values[k];
} else if (s != k) {
if (!a.values[s]) { if (!a.values[s]) {
a.values[s]=bigInt(a.values[k]); a.values[s]=bigInt(a.values[k]);
} else { } else {

+ 2371
- 0
sum.json
File diff suppressed because it is too large
View File


+ 18
- 0
test/circuits/constants_test.jaz

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

circuits/sha256/sum_test.jaz → test/circuits/sum_test.jaz

@ -2,7 +2,7 @@ include "bitify.jaz"
include "binsum.jaz" include "binsum.jaz"
template A() { template A() {
signal input a;
signal private input a;
signal input b; signal input b;
signal output out; signal output out;

+ 14
- 0
test/sha256.js

@ -0,0 +1,14 @@
const chai = require("chai");
const path = require("path");
const compiler = require("../index.js");
const assert = chai.assert;
describe("SHA256 test", () => {
it("Should create a constant circuit", async () => {
const cir = await compiler(path.join(__dirname, "circuits", "constants_test.jaz"));
assert.equal(cir.nVars, 2);
});
});

test/commandline.js → test_old/commandline.js


test/jorge.prg → test_old/jorge.prg


test/mainTest.js → test_old/mainTest.js


test/test1.jaz → test_old/test1.jaz


test/test10.jaz → test_old/test10.jaz


test/test11.jaz → test_old/test11.jaz


test/test12.jaz → test_old/test12.jaz


test/test13.jaz → test_old/test13.jaz


test/test14.jaz → test_old/test14.jaz


test/test2.jaz → test_old/test2.jaz


test/test3.jaz → test_old/test3.jaz


test/test4.jaz → test_old/test4.jaz


test/test5.jaz → test_old/test5.jaz


test/test6.jaz → test_old/test6.jaz


test/test7.jaz → test_old/test7.jaz


test/test8.jaz → test_old/test8.jaz


test/test9.jaz → test_old/test9.jaz


Loading…
Cancel
Save