MerkleProof.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. const format = require('../format-lines');
  2. const { OPTS } = require('./MerkleProof.opts');
  3. const DEFAULT_HASH = 'Hashes.commutativeKeccak256';
  4. const formatArgsSingleLine = (...args) => args.filter(Boolean).join(', ');
  5. const formatArgsMultiline = (...args) => '\n' + format(args.filter(Boolean).join(',\0').split('\0'));
  6. // TEMPLATE
  7. const header = `\
  8. pragma solidity ^0.8.20;
  9. import {Hashes} from "./Hashes.sol";
  10. /**
  11. * @dev These functions deal with verification of Merkle Tree proofs.
  12. *
  13. * The tree and the proofs can be generated using our
  14. * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
  15. * You will find a quickstart guide in the readme.
  16. *
  17. * WARNING: You should avoid using leaf values that are 64 bytes long prior to
  18. * hashing, or use a hash function other than keccak256 for hashing leaves.
  19. * This is because the concatenation of a sorted pair of internal nodes in
  20. * the Merkle tree could be reinterpreted as a leaf value.
  21. * OpenZeppelin's JavaScript library generates Merkle trees that are safe
  22. * against this attack out of the box.
  23. *
  24. * NOTE: This library supports proof verification for merkle trees built using
  25. * custom _commutative_ hashing functions (i.e. \`H(a, b) == H(b, a)\`). Proving
  26. * leaf inclusion in trees built using non-commutative hashing functions requires
  27. * additional logic that is not supported by this library.
  28. */
  29. `;
  30. const errors = `\
  31. /**
  32. *@dev The multiproof provided is not valid.
  33. */
  34. error MerkleProofInvalidMultiproof();
  35. `;
  36. /* eslint-disable max-len */
  37. const templateProof = ({ suffix, location, visibility, hash }) => `\
  38. /**
  39. * @dev Returns true if a \`leaf\` can be proved to be a part of a Merkle tree
  40. * defined by \`root\`. For this, a \`proof\` must be provided, containing
  41. * sibling hashes on the branch from the leaf to the root of the tree. Each
  42. * pair of leaves and each pair of pre-images are assumed to be sorted.
  43. *
  44. * This version handles proofs in ${location} with ${hash ? 'a custom' : 'the default'} hashing function.
  45. */
  46. function verify${suffix}(${(hash ? formatArgsMultiline : formatArgsSingleLine)(
  47. `bytes32[] ${location} proof`,
  48. 'bytes32 root',
  49. 'bytes32 leaf',
  50. hash && `function(bytes32, bytes32) view returns (bytes32) ${hash}`,
  51. )}) internal ${visibility} returns (bool) {
  52. return processProof(proof, leaf${hash ? `, ${hash}` : ''}) == root;
  53. }
  54. /**
  55. * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
  56. * from \`leaf\` using \`proof\`. A \`proof\` is valid if and only if the rebuilt
  57. * hash matches the root of the tree. When processing the proof, the pairs
  58. * of leafs & pre-images are assumed to be sorted.
  59. *
  60. * This version handles proofs in ${location} with ${hash ? 'a custom' : 'the default'} hashing function.
  61. */
  62. function processProof${suffix}(${(hash ? formatArgsMultiline : formatArgsSingleLine)(
  63. `bytes32[] ${location} proof`,
  64. 'bytes32 leaf',
  65. hash && `function(bytes32, bytes32) view returns (bytes32) ${hash}`,
  66. )}) internal ${visibility} returns (bytes32) {
  67. bytes32 computedHash = leaf;
  68. for (uint256 i = 0; i < proof.length; i++) {
  69. computedHash = ${hash ?? DEFAULT_HASH}(computedHash, proof[i]);
  70. }
  71. return computedHash;
  72. }
  73. `;
  74. const templateMultiProof = ({ suffix, location, visibility, hash }) => `\
  75. /**
  76. * @dev Returns true if the \`leaves\` can be simultaneously proven to be a part of a Merkle tree defined by
  77. * \`root\`, according to \`proof\` and \`proofFlags\` as described in {processMultiProof}.
  78. *
  79. * This version handles multiproofs in ${location} with ${hash ? 'a custom' : 'the default'} hashing function.
  80. *
  81. * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
  82. */
  83. function multiProofVerify${suffix}(${formatArgsMultiline(
  84. `bytes32[] ${location} proof`,
  85. `bool[] ${location} proofFlags`,
  86. 'bytes32 root',
  87. `bytes32[] ${location} leaves`,
  88. hash && `function(bytes32, bytes32) view returns (bytes32) ${hash}`,
  89. )}) internal ${visibility} returns (bool) {
  90. return processMultiProof(proof, proofFlags, leaves${hash ? `, ${hash}` : ''}) == root;
  91. }
  92. /**
  93. * @dev Returns the root of a tree reconstructed from \`leaves\` and sibling nodes in \`proof\`. The reconstruction
  94. * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
  95. * leaf/inner node or a proof sibling node, depending on whether each \`proofFlags\` item is true or false
  96. * respectively.
  97. *
  98. * This version handles multiproofs in ${location} with ${hash ? 'a custom' : 'the default'} hashing function.
  99. *
  100. * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
  101. * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
  102. * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
  103. */
  104. function processMultiProof${suffix}(${formatArgsMultiline(
  105. `bytes32[] ${location} proof`,
  106. `bool[] ${location} proofFlags`,
  107. `bytes32[] ${location} leaves`,
  108. hash && `function(bytes32, bytes32) view returns (bytes32) ${hash}`,
  109. )}) internal ${visibility} returns (bytes32 merkleRoot) {
  110. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  111. // consuming and producing values on a queue. The queue starts with the \`leaves\` array, then goes onto the
  112. // \`hashes\` array. At the end of the process, the last hash in the \`hashes\` array should contain the root of
  113. // the Merkle tree.
  114. uint256 leavesLen = leaves.length;
  115. // Check proof validity.
  116. if (leavesLen + proof.length != proofFlags.length + 1) {
  117. revert MerkleProofInvalidMultiproof();
  118. }
  119. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  120. // \`xxx[xxxPos++]\`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  121. bytes32[] memory hashes = new bytes32[](proofFlags.length);
  122. uint256 leafPos = 0;
  123. uint256 hashPos = 0;
  124. uint256 proofPos = 0;
  125. // At each step, we compute the next hash using two values:
  126. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  127. // get the next hash.
  128. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  129. // \`proof\` array.
  130. for (uint256 i = 0; i < proofFlags.length; i++) {
  131. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  132. bytes32 b = proofFlags[i]
  133. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  134. : proof[proofPos++];
  135. hashes[i] = ${hash ?? DEFAULT_HASH}(a, b);
  136. }
  137. if (proofFlags.length > 0) {
  138. if (proofPos != proof.length) {
  139. revert MerkleProofInvalidMultiproof();
  140. }
  141. unchecked {
  142. return hashes[proofFlags.length - 1];
  143. }
  144. } else if (leavesLen > 0) {
  145. return leaves[0];
  146. } else {
  147. return proof[0];
  148. }
  149. }
  150. `;
  151. /* eslint-enable max-len */
  152. // GENERATE
  153. module.exports = format(
  154. header.trimEnd(),
  155. 'library MerkleProof {',
  156. format(
  157. [].concat(
  158. errors,
  159. OPTS.flatMap(opts => templateProof(opts)),
  160. OPTS.flatMap(opts => templateMultiProof(opts)),
  161. ),
  162. ).trimEnd(),
  163. '}',
  164. );