MerkleProof.js 7.8 KB

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