MerkleProof.js 7.7 KB

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