MerkleProof.sol 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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 proofs can be generated using the JavaScript library
  8. * https://github.com/miguelmota/merkletreejs[merkletreejs].
  9. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
  10. *
  11. * See `test/utils/cryptography/MerkleProof.test.js` for some examples.
  12. *
  13. * WARNING: You should avoid using leaf values that are 64 bytes long prior to
  14. * hashing, or use a hash function other than keccak256 for hashing leaves.
  15. * This is because the concatenation of a sorted pair of internal nodes in
  16. * the merkle tree could be reinterpreted as a leaf value.
  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 proved to be a part of a Merkle tree defined by
  73. * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
  74. *
  75. * _Available since v4.7._
  76. */
  77. function multiProofVerify(
  78. bytes32[] memory proof,
  79. bool[] memory proofFlags,
  80. bytes32 root,
  81. bytes32[] memory leaves
  82. ) internal pure returns (bool) {
  83. return processMultiProof(proof, proofFlags, leaves) == root;
  84. }
  85. /**
  86. * @dev Calldata version of {multiProofVerify}
  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 the sibling nodes in `proof`,
  100. * consuming from one or the other at each step according to the instructions given by
  101. * `proofFlags`.
  102. *
  103. * _Available since v4.7._
  104. */
  105. function processMultiProof(
  106. bytes32[] memory proof,
  107. bool[] memory proofFlags,
  108. bytes32[] memory leaves
  109. ) internal pure returns (bytes32 merkleRoot) {
  110. // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by
  111. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  112. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  113. // the merkle tree.
  114. uint256 leavesLen = leaves.length;
  115. uint256 totalHashes = proofFlags.length;
  116. // Check proof validity.
  117. require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");
  118. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  119. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  120. bytes32[] memory hashes = new bytes32[](totalHashes);
  121. uint256 leafPos = 0;
  122. uint256 hashPos = 0;
  123. uint256 proofPos = 0;
  124. // At each step, we compute the next hash using two values:
  125. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  126. // get the next hash.
  127. // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the
  128. // `proof` array.
  129. for (uint256 i = 0; i < totalHashes; i++) {
  130. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  131. bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
  132. hashes[i] = _hashPair(a, b);
  133. }
  134. if (totalHashes > 0) {
  135. return hashes[totalHashes - 1];
  136. } else if (leavesLen > 0) {
  137. return leaves[0];
  138. } else {
  139. return proof[0];
  140. }
  141. }
  142. /**
  143. * @dev Calldata version of {processMultiProof}
  144. *
  145. * _Available since v4.7._
  146. */
  147. function processMultiProofCalldata(
  148. bytes32[] calldata proof,
  149. bool[] calldata proofFlags,
  150. bytes32[] memory leaves
  151. ) internal pure returns (bytes32 merkleRoot) {
  152. // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by
  153. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  154. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  155. // the merkle tree.
  156. uint256 leavesLen = leaves.length;
  157. uint256 totalHashes = proofFlags.length;
  158. // Check proof validity.
  159. require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");
  160. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  161. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  162. bytes32[] memory hashes = new bytes32[](totalHashes);
  163. uint256 leafPos = 0;
  164. uint256 hashPos = 0;
  165. uint256 proofPos = 0;
  166. // At each step, we compute the next hash using two values:
  167. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  168. // get the next hash.
  169. // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the
  170. // `proof` array.
  171. for (uint256 i = 0; i < totalHashes; i++) {
  172. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  173. bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
  174. hashes[i] = _hashPair(a, b);
  175. }
  176. if (totalHashes > 0) {
  177. return hashes[totalHashes - 1];
  178. } else if (leavesLen > 0) {
  179. return leaves[0];
  180. } else {
  181. return proof[0];
  182. }
  183. }
  184. function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
  185. return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
  186. }
  187. function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
  188. /// @solidity memory-safe-assembly
  189. assembly {
  190. mstore(0x00, a)
  191. mstore(0x20, b)
  192. value := keccak256(0x00, 0x40)
  193. }
  194. }
  195. }