MerkleTree.circom 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. include "../node_modules/circomlib/circuits/poseidon.circom";
  2. include "../node_modules/circomlib/circuits/bitify.circom";
  3. // Computes Poseidon([left, right])
  4. template HashLeftRight() {
  5. signal input left;
  6. signal input right;
  7. signal output hash;
  8. component hasher = Poseidon(2);
  9. hasher.inputs[0] <== left;
  10. hasher.inputs[1] <== right;
  11. hash <== hasher.out;
  12. }
  13. // if s == 0 returns [in[0], in[1]]
  14. // if s == 1 returns [in[1], in[0]]
  15. template DualMux() {
  16. signal input in[2];
  17. signal input s;
  18. signal output out[2];
  19. s * (1 - s) === 0;
  20. out[0] <== (in[1] - in[0])*s + in[0];
  21. out[1] <== (in[0] - in[1])*s + in[1];
  22. }
  23. // Verifies that merkle proof is correct for given merkle root and a leaf
  24. // pathIndices input is an array of 0/1 selectors telling whether given pathElement is on the left or right side of merkle path
  25. template RawMerkleTree(levels) {
  26. signal input leaf;
  27. signal input pathElements[levels];
  28. signal input pathIndices[levels];
  29. signal output root;
  30. component selectors[levels];
  31. component hashers[levels];
  32. for (var i = 0; i < levels; i++) {
  33. selectors[i] = DualMux();
  34. selectors[i].in[0] <== i == 0 ? leaf : hashers[i - 1].hash;
  35. selectors[i].in[1] <== pathElements[i];
  36. selectors[i].s <== pathIndices[i];
  37. hashers[i] = HashLeftRight();
  38. hashers[i].left <== selectors[i].out[0];
  39. hashers[i].right <== selectors[i].out[1];
  40. }
  41. root <== hashers[levels - 1].hash;
  42. }
  43. template MerkleTree(levels) {
  44. signal input leaf;
  45. signal input pathElements[levels];
  46. signal input pathIndices;
  47. signal output root;
  48. component indexBits = Num2Bits(levels);
  49. indexBits.in <== pathIndices;
  50. component tree = RawMerkleTree(levels)
  51. tree.leaf <== leaf;
  52. for (var i = 0; i < levels; i++) {
  53. tree.pathIndices[i] <== indexBits.out[i];
  54. tree.pathElements[i] <== pathElements[i];
  55. }
  56. root <== tree.root
  57. }