arnaucube
arnaucube/circomlibPublic Self-hosted repository
circomlib/test/eddsa.js
test/eddsa.jsRaw
 1const chai = require("chai");
 2const path = require("path");
 3const snarkjs = require("snarkjs");
 4const compiler = require("circom");
 5// const crypto = require("crypto");
 6
 7const eddsa = require("../src/eddsa.js");
 8const babyJub = require("../src/babyjub.js");
 9
10const assert = chai.assert;
11
12const bigInt = snarkjs.bigInt;
13
14function print(circuit, w, s) {
15    console.log(s + ": " + w[circuit.getSignalIdx(s)]);
16}
17
18function buffer2bits(buff) {
19    const res = [];
20    for (let i=0; i<buff.length; i++) {
21        for (let j=0; j<8; j++) {
22            if ((buff[i]>>j)&1) {
23                res.push(bigInt.one);
24            } else {
25                res.push(bigInt.zero);
26            }
27        }
28    }
29    return res;
30}
31
32
33describe("EdDSA test", function () {
34    let circuit;
35
36    this.timeout(100000);
37
38    before( async () => {
39        const cirDef = await compiler(path.join(__dirname, "circuits", "eddsa_test.circom"));
40
41        circuit = new snarkjs.Circuit(cirDef);
42
43        console.log("NConstrains EdDSA: " + circuit.nConstraints);
44    });
45
46    it("Sign a single 10 bytes from 0 to 9", async () => {
47        const msg = Buffer.from("00010203040506070809", "hex");
48
49//        const prvKey = crypto.randomBytes(32);
50
51        const prvKey = Buffer.from("0001020304050607080900010203040506070809000102030405060708090001", "hex");
52
53        const pubKey = eddsa.prv2pub(prvKey);
54
55        const pPubKey = babyJub.packPoint(pubKey);
56
57        const signature = eddsa.sign(prvKey, msg);
58
59        const pSignature = eddsa.packSignature(signature);
60        const uSignature = eddsa.unpackSignature(pSignature);
61
62        assert(eddsa.verify(msg, uSignature, pubKey));
63
64        const msgBits = buffer2bits(msg);
65        const r8Bits = buffer2bits(pSignature.slice(0, 32));
66        const sBits = buffer2bits(pSignature.slice(32, 64));
67        const aBits = buffer2bits(pPubKey);
68
69        const w = circuit.calculateWitness({A: aBits, R8: r8Bits, S: sBits, msg: msgBits});
70
71        assert(circuit.checkWitness(w));
72
73    });
74});