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.

82 lines
2.5 KiB

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