MerkleProof.sol 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MerkleProof.sol)
  3. pragma solidity ^0.8.20;
  4. /**
  5. * @dev These functions deal with verification of Merkle Tree proofs.
  6. *
  7. * The tree and the proofs can be generated using our
  8. * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
  9. * You will find a quickstart guide in the readme.
  10. *
  11. * WARNING: You should avoid using leaf values that are 64 bytes long prior to
  12. * hashing, or use a hash function other than keccak256 for hashing leaves.
  13. * This is because the concatenation of a sorted pair of internal nodes in
  14. * the Merkle tree could be reinterpreted as a leaf value.
  15. * OpenZeppelin's JavaScript library generates Merkle trees that are safe
  16. * against this attack out of the box.
  17. */
  18. library MerkleProof {
  19. /**
  20. *@dev The multiproof provided is not valid.
  21. */
  22. error MerkleProofInvalidMultiproof();
  23. /**
  24. * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
  25. * defined by `root`. For this, a `proof` must be provided, containing
  26. * sibling hashes on the branch from the leaf to the root of the tree. Each
  27. * pair of leaves and each pair of pre-images are assumed to be sorted.
  28. */
  29. function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
  30. return processProof(proof, leaf) == root;
  31. }
  32. /**
  33. * @dev Calldata version of {verify}
  34. */
  35. function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
  36. return processProofCalldata(proof, leaf) == root;
  37. }
  38. /**
  39. * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
  40. * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
  41. * hash matches the root of the tree. When processing the proof, the pairs
  42. * of leafs & pre-images are assumed to be sorted.
  43. */
  44. function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
  45. bytes32 computedHash = leaf;
  46. for (uint256 i = 0; i < proof.length; i++) {
  47. computedHash = _hashPair(computedHash, proof[i]);
  48. }
  49. return computedHash;
  50. }
  51. /**
  52. * @dev Calldata version of {processProof}
  53. */
  54. function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
  55. bytes32 computedHash = leaf;
  56. for (uint256 i = 0; i < proof.length; i++) {
  57. computedHash = _hashPair(computedHash, proof[i]);
  58. }
  59. return computedHash;
  60. }
  61. /**
  62. * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
  63. * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
  64. *
  65. * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
  66. */
  67. function multiProofVerify(
  68. bytes32[] memory proof,
  69. bool[] memory proofFlags,
  70. bytes32 root,
  71. bytes32[] memory leaves
  72. ) internal pure returns (bool) {
  73. return processMultiProof(proof, proofFlags, leaves) == root;
  74. }
  75. /**
  76. * @dev Calldata version of {multiProofVerify}
  77. *
  78. * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
  79. */
  80. function multiProofVerifyCalldata(
  81. bytes32[] calldata proof,
  82. bool[] calldata proofFlags,
  83. bytes32 root,
  84. bytes32[] memory leaves
  85. ) internal pure returns (bool) {
  86. return processMultiProofCalldata(proof, proofFlags, leaves) == root;
  87. }
  88. /**
  89. * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
  90. * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
  91. * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
  92. * respectively.
  93. *
  94. * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
  95. * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
  96. * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
  97. */
  98. function processMultiProof(
  99. bytes32[] memory proof,
  100. bool[] memory proofFlags,
  101. bytes32[] memory leaves
  102. ) internal pure returns (bytes32 merkleRoot) {
  103. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  104. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  105. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  106. // the Merkle tree.
  107. uint256 leavesLen = leaves.length;
  108. uint256 proofLen = proof.length;
  109. uint256 totalHashes = proofFlags.length;
  110. // Check proof validity.
  111. if (leavesLen + proofLen != totalHashes + 1) {
  112. revert MerkleProofInvalidMultiproof();
  113. }
  114. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  115. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  116. bytes32[] memory hashes = new bytes32[](totalHashes);
  117. uint256 leafPos = 0;
  118. uint256 hashPos = 0;
  119. uint256 proofPos = 0;
  120. // At each step, we compute the next hash using two values:
  121. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  122. // get the next hash.
  123. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  124. // `proof` array.
  125. for (uint256 i = 0; i < totalHashes; i++) {
  126. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  127. bytes32 b = proofFlags[i]
  128. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  129. : proof[proofPos++];
  130. hashes[i] = _hashPair(a, b);
  131. }
  132. if (totalHashes > 0) {
  133. if (proofPos != proofLen) {
  134. revert MerkleProofInvalidMultiproof();
  135. }
  136. unchecked {
  137. return hashes[totalHashes - 1];
  138. }
  139. } else if (leavesLen > 0) {
  140. return leaves[0];
  141. } else {
  142. return proof[0];
  143. }
  144. }
  145. /**
  146. * @dev Calldata version of {processMultiProof}.
  147. *
  148. * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
  149. */
  150. function processMultiProofCalldata(
  151. bytes32[] calldata proof,
  152. bool[] calldata proofFlags,
  153. bytes32[] memory leaves
  154. ) internal pure returns (bytes32 merkleRoot) {
  155. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  156. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  157. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  158. // the Merkle tree.
  159. uint256 leavesLen = leaves.length;
  160. uint256 proofLen = proof.length;
  161. uint256 totalHashes = proofFlags.length;
  162. // Check proof validity.
  163. if (leavesLen + proofLen != totalHashes + 1) {
  164. revert MerkleProofInvalidMultiproof();
  165. }
  166. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  167. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  168. bytes32[] memory hashes = new bytes32[](totalHashes);
  169. uint256 leafPos = 0;
  170. uint256 hashPos = 0;
  171. uint256 proofPos = 0;
  172. // At each step, we compute the next hash using two values:
  173. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  174. // get the next hash.
  175. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  176. // `proof` array.
  177. for (uint256 i = 0; i < totalHashes; i++) {
  178. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  179. bytes32 b = proofFlags[i]
  180. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  181. : proof[proofPos++];
  182. hashes[i] = _hashPair(a, b);
  183. }
  184. if (totalHashes > 0) {
  185. if (proofPos != proofLen) {
  186. revert MerkleProofInvalidMultiproof();
  187. }
  188. unchecked {
  189. return hashes[totalHashes - 1];
  190. }
  191. } else if (leavesLen > 0) {
  192. return leaves[0];
  193. } else {
  194. return proof[0];
  195. }
  196. }
  197. /**
  198. * @dev Sorts the pair (a, b) and hashes the result.
  199. */
  200. function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
  201. return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
  202. }
  203. /**
  204. * @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
  205. */
  206. function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
  207. /// @solidity memory-safe-assembly
  208. assembly {
  209. mstore(0x00, a)
  210. mstore(0x20, b)
  211. value := keccak256(0x00, 0x40)
  212. }
  213. }
  214. }