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