snarkjs/test/zksnark.js
test/zksnark.jsRaw
1/*
2 Copyright 2018 0kims association.
3
4 This file is part of zksnark JavaScript library.
5
6 zksnark JavaScript library is a free software: you can redistribute it and/or
7 modify it under the terms of the GNU General Public License as published by the
8 Free Software Foundation, either version 3 of the License, or (at your option)
9 any later version.
10
11 zksnark JavaScript library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 more details.
15
16 You should have received a copy of the GNU General Public License along with
17 zksnark JavaScript library. If not, see <https://www.gnu.org/licenses/>.
18*/
19
20const chai = require("chai");
21const fs = require("fs");
22const path = require("path");
23const bigInt = require("../src/bigint.js");
24
25const Circuit = require("../src/circuit.js");
26const zkSnark = require("../index.js");
27
28const assert = chai.assert;
29
30
31function stringifyBigInts(o) {
32 if ((typeof(o) == "bigint") || (o instanceof bigInt)) {
33 return o.toString(10);
34 } else if (Array.isArray(o)) {
35 return o.map(stringifyBigInts);
36 } else if (typeof o == "object") {
37 const res = {};
38 for (let k in o) {
39 res[k] = stringifyBigInts(o[k]);
40 }
41 return res;
42 } else {
43 return o;
44 }
45}
46
47function unstringifyBigInts(o) {
48 if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) {
49 return bigInt(o);
50 } else if (Array.isArray(o)) {
51 return o.map(unstringifyBigInts);
52 } else if (typeof o == "object") {
53 const res = {};
54 for (let k in o) {
55 res[k] = unstringifyBigInts(o[k]);
56 }
57 return res;
58 } else {
59 return o;
60 }
61}
62
63describe("zkSnark", () => {
64 it("Load a circuit, create trusted setup, create a proof and validate it", () => {
65
66 const cirDef = JSON.parse(fs.readFileSync(path.join(__dirname, "circuit", "sum.json"), "utf8"));
67 const cir = new Circuit(cirDef);
68
69 const setup = zkSnark.setup(cir);
70 const strSetup = stringifyBigInts(setup);
71 fs.writeFileSync("vk_proof.json", JSON.stringify(strSetup.vk_proof), "utf-8");
72 fs.writeFileSync("vk_verifier.json", JSON.stringify(strSetup.vk_verifier), "utf-8");
73
74/*
75 const setup = {};
76 setup.vk_proof = unstringifyBigInts(JSON.parse(fs.readFileSync("vk_proof.json", "utf8")));
77 setup.vk_verifier = unstringifyBigInts(JSON.parse(fs.readFileSync("vk_verifier.json", "utf8")));
78*/
79 const witness = cir.calculateWitness({"a": "33", "b": "34"});
80
81 assert.equal(witness[cir.getSignalIdx("main.out")].toString(), "67");
82
83 const {proof, publicSignals} = zkSnark.genProof(setup.vk_proof, witness);
84
85 assert( zkSnark.isValid(setup.vk_verifier, proof, publicSignals));
86 }).timeout(10000000);
87});