MerkleProof.sol 9.0 KB

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