merkleTree.circom 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. include "../node_modules/circomlib/circuits/mimcsponge.circom";
  2. // Computes MiMC([left, right])
  3. template HashLeftRight() {
  4. signal input left;
  5. signal input right;
  6. signal output hash;
  7. component hasher = MiMCSponge(2, 1);
  8. hasher.ins[0] <== left;
  9. hasher.ins[1] <== right;
  10. hasher.k <== 0;
  11. hash <== hasher.outs[0];
  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 MerkleTreeChecker(levels) {
  26. signal input leaf;
  27. signal input root;
  28. signal input pathElements[levels];
  29. signal input pathIndices[levels];
  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. }