You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.9 KiB

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