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.

74 lines
2.0 KiB

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