MerkleProof.sol 9.1 KB

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