MerkleProof.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. * IMPORTANT: Consider memory side-effects when using custom hashing functions
  25. * that access memory in an unsafe way.
  26. *
  27. * NOTE: This library supports proof verification for merkle trees built using
  28. * custom _commutative_ hashing functions (i.e. \`H(a, b) == H(b, a)\`). Proving
  29. * leaf inclusion in trees built using non-commutative hashing functions requires
  30. * additional logic that is not supported by this library.
  31. */
  32. `;
  33. const errors = `\
  34. /**
  35. *@dev The multiproof provided is not valid.
  36. */
  37. error MerkleProofInvalidMultiproof();
  38. `;
  39. const templateProof = ({ suffix, location, visibility, hash }) => `\
  40. /**
  41. * @dev Returns true if a \`leaf\` can be proved to be a part of a Merkle tree
  42. * defined by \`root\`. For this, a \`proof\` must be provided, containing
  43. * sibling hashes on the branch from the leaf to the root of the tree. Each
  44. * pair of leaves and each pair of pre-images are assumed to be sorted.
  45. *
  46. * This version handles proofs in ${location} with ${hash ? 'a custom' : 'the default'} hashing function.
  47. */
  48. function verify${suffix}(${(hash ? formatArgsMultiline : formatArgsSingleLine)(
  49. `bytes32[] ${location} proof`,
  50. 'bytes32 root',
  51. 'bytes32 leaf',
  52. hash && `function(bytes32, bytes32) view returns (bytes32) ${hash}`,
  53. )}) internal ${visibility} returns (bool) {
  54. return processProof${suffix}(proof, leaf${hash ? `, ${hash}` : ''}) == root;
  55. }
  56. /**
  57. * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
  58. * from \`leaf\` using \`proof\`. A \`proof\` is valid if and only if the rebuilt
  59. * hash matches the root of the tree. When processing the proof, the pairs
  60. * of leaves & pre-images are assumed to be sorted.
  61. *
  62. * This version handles proofs in ${location} with ${hash ? 'a custom' : 'the default'} hashing function.
  63. */
  64. function processProof${suffix}(${(hash ? formatArgsMultiline : formatArgsSingleLine)(
  65. `bytes32[] ${location} proof`,
  66. 'bytes32 leaf',
  67. hash && `function(bytes32, bytes32) view returns (bytes32) ${hash}`,
  68. )}) internal ${visibility} returns (bytes32) {
  69. bytes32 computedHash = leaf;
  70. for (uint256 i = 0; i < proof.length; i++) {
  71. computedHash = ${hash ?? DEFAULT_HASH}(computedHash, proof[i]);
  72. }
  73. return computedHash;
  74. }
  75. `;
  76. const templateMultiProof = ({ suffix, location, visibility, hash }) => `\
  77. /**
  78. * @dev Returns true if the \`leaves\` can be simultaneously proven to be a part of a Merkle tree defined by
  79. * \`root\`, according to \`proof\` and \`proofFlags\` as described in {processMultiProof}.
  80. *
  81. * This version handles multiproofs in ${location} with ${hash ? 'a custom' : 'the default'} hashing function.
  82. *
  83. * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
  84. *
  85. * NOTE: Consider the case where \`root == proof[0] && leaves.length == 0\` as it will return \`true\`.
  86. * The \`leaves\` must be validated independently. See {processMultiProof${suffix}}.
  87. */
  88. function multiProofVerify${suffix}(${formatArgsMultiline(
  89. `bytes32[] ${location} proof`,
  90. `bool[] ${location} proofFlags`,
  91. 'bytes32 root',
  92. `bytes32[] memory leaves`,
  93. hash && `function(bytes32, bytes32) view returns (bytes32) ${hash}`,
  94. )}) internal ${visibility} returns (bool) {
  95. return processMultiProof${suffix}(proof, proofFlags, leaves${hash ? `, ${hash}` : ''}) == root;
  96. }
  97. /**
  98. * @dev Returns the root of a tree reconstructed from \`leaves\` and sibling nodes in \`proof\`. The reconstruction
  99. * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
  100. * leaf/inner node or a proof sibling node, depending on whether each \`proofFlags\` item is true or false
  101. * respectively.
  102. *
  103. * This version handles multiproofs in ${location} with ${hash ? 'a custom' : 'the default'} hashing function.
  104. *
  105. * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
  106. * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
  107. * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
  108. *
  109. * NOTE: The _empty set_ (i.e. the case where \`proof.length == 1 && leaves.length == 0\`) is considered a no-op,
  110. * and therefore a valid multiproof (i.e. it returns \`proof[0]\`). Consider disallowing this case if you're not
  111. * validating the leaves elsewhere.
  112. */
  113. function processMultiProof${suffix}(${formatArgsMultiline(
  114. `bytes32[] ${location} proof`,
  115. `bool[] ${location} proofFlags`,
  116. `bytes32[] memory leaves`,
  117. hash && `function(bytes32, bytes32) view returns (bytes32) ${hash}`,
  118. )}) internal ${visibility} returns (bytes32 merkleRoot) {
  119. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  120. // consuming and producing values on a queue. The queue starts with the \`leaves\` array, then goes onto the
  121. // \`hashes\` array. At the end of the process, the last hash in the \`hashes\` array should contain the root of
  122. // the Merkle tree.
  123. uint256 leavesLen = leaves.length;
  124. uint256 proofFlagsLen = proofFlags.length;
  125. // Check proof validity.
  126. if (leavesLen + proof.length != proofFlagsLen + 1) {
  127. revert MerkleProofInvalidMultiproof();
  128. }
  129. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  130. // \`xxx[xxxPos++]\`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  131. bytes32[] memory hashes = new bytes32[](proofFlagsLen);
  132. uint256 leafPos = 0;
  133. uint256 hashPos = 0;
  134. uint256 proofPos = 0;
  135. // At each step, we compute the next hash using two values:
  136. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  137. // get the next hash.
  138. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  139. // \`proof\` array.
  140. for (uint256 i = 0; i < proofFlagsLen; i++) {
  141. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  142. bytes32 b = proofFlags[i]
  143. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  144. : proof[proofPos++];
  145. hashes[i] = ${hash ?? DEFAULT_HASH}(a, b);
  146. }
  147. if (proofFlagsLen > 0) {
  148. if (proofPos != proof.length) {
  149. revert MerkleProofInvalidMultiproof();
  150. }
  151. unchecked {
  152. return hashes[proofFlagsLen - 1];
  153. }
  154. } else if (leavesLen > 0) {
  155. return leaves[0];
  156. } else {
  157. return proof[0];
  158. }
  159. }
  160. `;
  161. // GENERATE
  162. module.exports = format(
  163. header.trimEnd(),
  164. 'library MerkleProof {',
  165. format(
  166. [].concat(
  167. errors,
  168. OPTS.flatMap(opts => templateProof(opts)),
  169. OPTS.flatMap(opts => templateMultiProof(opts)),
  170. ),
  171. ).trimEnd(),
  172. '}',
  173. );