arnaucube
arnaucube/circomPublic Self-hosted repository
circom/test/sha256.js
test/sha256.jsRaw
 1const chai = require("chai");
 2const path = require("path");
 3const zkSnark = require("zksnark");
 4const crypto = require("crypto");
 5
 6const compiler = require("../index.js");
 7
 8const assert = chai.assert;
 9
10const sha256 = require("./helpers/sha256");
11const bigInt = require("big-integer");
12
13function hexBits(cir, witness, sig, nBits) {
14    let v = bigInt(0);
15    for (let i=nBits-1; i>=0; i--) {
16        v = v.shiftLeft(1);
17        const name = sig+"["+i+"]";
18        const idx = cir.getSignalIdx(name);
19        const vbit = bigInt(witness[idx].toString());
20        if (vbit.equals(bigInt(1))) {
21            v = v.add(bigInt(1));
22        } else if (vbit.equals(bigInt(0))) {
23            v;
24        } else {
25            console.log("Not Binary: "+name);
26        }
27    }
28    return v.toString(16);
29}
30
31describe("SHA256 test", () => {
32    it("Should create a constant circuit", async () => {
33
34        const cirDef = await compiler(path.join(__dirname, "circuits", "constants_test.circom"));
35        assert.equal(cirDef.nVars, 2);
36
37        const circuit = new zkSnark.Circuit(cirDef);
38
39        const witness = circuit.calculateWitness({ "in": "0xd807aa98" });
40
41        assert(witness[0].equals(zkSnark.bigInt(1)));
42        assert(witness[1].equals(zkSnark.bigInt("0xd807aa98")));
43    });
44    it("Should create a sum circuit", async () => {
45
46        const cirDef = await compiler(path.join(__dirname, "circuits", "sum_test.circom"));
47        assert.equal(cirDef.nVars, 101);
48
49        const circuit = new zkSnark.Circuit(cirDef);
50
51        const witness = circuit.calculateWitness({ "a": "111", "b": "222" });
52
53        assert(witness[0].equals(zkSnark.bigInt(1)));
54        assert(witness[1].equals(zkSnark.bigInt("333")));
55    });
56    it("Should calculate a hash", async () => {
57        const cirDef = await compiler(path.join(__dirname, "circuits", "sha256_2_test.circom"));
58        const circuit = new zkSnark.Circuit(cirDef);
59
60        const witness = circuit.calculateWitness({ "a": "1", "b": "2" });
61
62        const b = new Buffer.alloc(54);
63        b[26] = 1;
64        b[53] = 2;
65
66        const hash = crypto.createHash("sha256")
67            .update(b)
68            .digest("hex");
69        const r = "0x" + hash.slice(10);
70
71        const hash2 = sha256.hash(b.toString("hex"), {msgFormat: "hex-bytes"});
72
73        assert.equal(hash, hash2);
74
75        assert(witness[1].equals(zkSnark.bigInt(r)));
76    }).timeout(1000000);
77
78
79});