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.

95 lines
2.4 KiB

  1. const chai = require("chai");
  2. const path = require("path");
  3. const snarkjs = require("snarkjs");
  4. const compiler = require("circom");
  5. const smt = require("../src/smt.js");
  6. const assert = chai.assert;
  7. const bigInt = snarkjs.bigInt;
  8. function print(circuit, w, s) {
  9. console.log(s + ": " + w[circuit.getSignalIdx(s)]);
  10. }
  11. async function testInclusion(tree, key, circuit) {
  12. const res = await tree.find(key);
  13. assert(res.found);
  14. let siblings = res.siblings;
  15. while (siblings.length<10) siblings.push(bigInt(0));
  16. const w = circuit.calculateWitness({
  17. fnc: 0,
  18. root: tree.root,
  19. siblings: siblings,
  20. oldKey: 0,
  21. oldValue: 0,
  22. isOld0: 0,
  23. key: key,
  24. value: res.foundValue
  25. });
  26. assert(circuit.checkWitness(w));
  27. }
  28. async function testExclusion(tree, key, circuit) {
  29. const res = await tree.find(key);
  30. assert(!res.found);
  31. let siblings = res.siblings;
  32. while (siblings.length<10) siblings.push(bigInt(0));
  33. const w = circuit.calculateWitness({
  34. fnc: 1,
  35. root: tree.root,
  36. siblings: siblings,
  37. oldKey: res.isOld0 ? 0 : res.notFoundKey,
  38. oldValue: res.isOld0 ? 0 : res.notFoundValue,
  39. isOld0: res.isOld0 ? 1 : 0,
  40. key: key,
  41. value: 0
  42. });
  43. assert(circuit.checkWitness(w));
  44. }
  45. describe("SMT test", function () {
  46. let circuit;
  47. let tree;
  48. this.timeout(100000);
  49. before( async () => {
  50. const cirDef = await compiler(path.join(__dirname, "circuits", "smtverifier10_test.circom"));
  51. circuit = new snarkjs.Circuit(cirDef);
  52. console.log("NConstrains SMTVerifier: " + circuit.nConstraints);
  53. tree = await smt.newMemEmptyTrie();
  54. await tree.insert(7,77);
  55. await tree.insert(8,88);
  56. await tree.insert(32,3232);
  57. });
  58. it("Check inclussion in a tree of 3", async () => {
  59. await testInclusion(tree, 7, circuit);
  60. await testInclusion(tree, 8, circuit);
  61. await testInclusion(tree, 32, circuit);
  62. });
  63. it("Check exclussion in a tree of 3", async () => {
  64. await testExclusion(tree, 0, circuit);
  65. await testExclusion(tree, 6, circuit);
  66. await testExclusion(tree, 9, circuit);
  67. await testExclusion(tree, 33, circuit);
  68. await testExclusion(tree, 31, circuit);
  69. await testExclusion(tree, 16, circuit);
  70. await testExclusion(tree, 64, circuit);
  71. });
  72. });