MerkleProof.sol 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/MerkleProof.sol)
  3. pragma solidity ^0.8.19;
  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. * _Available since v4.7._
  36. */
  37. function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
  38. return processProofCalldata(proof, leaf) == root;
  39. }
  40. /**
  41. * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
  42. * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
  43. * hash matches the root of the tree. When processing the proof, the pairs
  44. * of leafs & pre-images are assumed to be sorted.
  45. *
  46. * _Available since v4.4._
  47. */
  48. function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
  49. bytes32 computedHash = leaf;
  50. for (uint256 i = 0; i < proof.length; i++) {
  51. computedHash = _hashPair(computedHash, proof[i]);
  52. }
  53. return computedHash;
  54. }
  55. /**
  56. * @dev Calldata version of {processProof}
  57. *
  58. * _Available since v4.7._
  59. */
  60. function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
  61. bytes32 computedHash = leaf;
  62. for (uint256 i = 0; i < proof.length; i++) {
  63. computedHash = _hashPair(computedHash, proof[i]);
  64. }
  65. return computedHash;
  66. }
  67. /**
  68. * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by
  69. * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
  70. *
  71. * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
  72. *
  73. * _Available since v4.7._
  74. */
  75. function multiProofVerify(
  76. bytes32[] memory proof,
  77. bool[] memory proofFlags,
  78. bytes32 root,
  79. bytes32[] memory leaves
  80. ) internal pure returns (bool) {
  81. return processMultiProof(proof, proofFlags, leaves) == root;
  82. }
  83. /**
  84. * @dev Calldata version of {multiProofVerify}
  85. *
  86. * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
  87. *
  88. * _Available since v4.7._
  89. */
  90. function multiProofVerifyCalldata(
  91. bytes32[] calldata proof,
  92. bool[] calldata proofFlags,
  93. bytes32 root,
  94. bytes32[] memory leaves
  95. ) internal pure returns (bool) {
  96. return processMultiProofCalldata(proof, proofFlags, leaves) == 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. * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
  105. * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
  106. * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
  107. *
  108. * _Available since v4.7._
  109. */
  110. function processMultiProof(
  111. bytes32[] memory proof,
  112. bool[] memory proofFlags,
  113. bytes32[] memory leaves
  114. ) internal pure returns (bytes32 merkleRoot) {
  115. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  116. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  117. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  118. // the merkle tree.
  119. uint256 leavesLen = leaves.length;
  120. uint256 totalHashes = proofFlags.length;
  121. // Check proof validity.
  122. if (leavesLen + proof.length - 1 != totalHashes) {
  123. revert MerkleProofInvalidMultiproof();
  124. }
  125. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  126. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  127. bytes32[] memory hashes = new bytes32[](totalHashes);
  128. uint256 leafPos = 0;
  129. uint256 hashPos = 0;
  130. uint256 proofPos = 0;
  131. // At each step, we compute the next hash using two values:
  132. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  133. // get the next hash.
  134. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  135. // `proof` array.
  136. for (uint256 i = 0; i < totalHashes; i++) {
  137. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  138. bytes32 b = proofFlags[i]
  139. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  140. : proof[proofPos++];
  141. hashes[i] = _hashPair(a, b);
  142. }
  143. if (totalHashes > 0) {
  144. unchecked {
  145. return hashes[totalHashes - 1];
  146. }
  147. } else if (leavesLen > 0) {
  148. return leaves[0];
  149. } else {
  150. return proof[0];
  151. }
  152. }
  153. /**
  154. * @dev Calldata version of {processMultiProof}.
  155. *
  156. * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
  157. *
  158. * _Available since v4.7._
  159. */
  160. function processMultiProofCalldata(
  161. bytes32[] calldata proof,
  162. bool[] calldata proofFlags,
  163. bytes32[] memory leaves
  164. ) internal pure returns (bytes32 merkleRoot) {
  165. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  166. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  167. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  168. // the merkle tree.
  169. uint256 leavesLen = leaves.length;
  170. uint256 totalHashes = proofFlags.length;
  171. // Check proof validity.
  172. if (leavesLen + proof.length - 1 != totalHashes) {
  173. revert MerkleProofInvalidMultiproof();
  174. }
  175. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  176. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  177. bytes32[] memory hashes = new bytes32[](totalHashes);
  178. uint256 leafPos = 0;
  179. uint256 hashPos = 0;
  180. uint256 proofPos = 0;
  181. // At each step, we compute the next hash using two values:
  182. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  183. // get the next hash.
  184. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  185. // `proof` array.
  186. for (uint256 i = 0; i < totalHashes; i++) {
  187. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  188. bytes32 b = proofFlags[i]
  189. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  190. : proof[proofPos++];
  191. hashes[i] = _hashPair(a, b);
  192. }
  193. if (totalHashes > 0) {
  194. unchecked {
  195. return hashes[totalHashes - 1];
  196. }
  197. } else if (leavesLen > 0) {
  198. return leaves[0];
  199. } else {
  200. return proof[0];
  201. }
  202. }
  203. function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
  204. return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
  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. }