MerkleProof.sol 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MerkleProof.sol)
  3. // This file was procedurally generated from scripts/generate/templates/MerkleProof.js.
  4. pragma solidity ^0.8.20;
  5. import {Hashes} from "./Hashes.sol";
  6. /**
  7. * @dev These functions deal with verification of Merkle Tree proofs.
  8. *
  9. * The tree and the proofs can be generated using our
  10. * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
  11. * You will find a quickstart guide in the readme.
  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. * OpenZeppelin's JavaScript library generates Merkle trees that are safe
  18. * against this attack out of the box.
  19. *
  20. * NOTE: This library supports proof verification for merkle trees built using
  21. * custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
  22. * leaf inclusion in trees built using non-commutative hashing functions requires
  23. * additional logic that is not supported by this library.
  24. */
  25. library MerkleProof {
  26. /**
  27. *@dev The multiproof provided is not valid.
  28. */
  29. error MerkleProofInvalidMultiproof();
  30. /**
  31. * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
  32. * defined by `root`. For this, a `proof` must be provided, containing
  33. * sibling hashes on the branch from the leaf to the root of the tree. Each
  34. * pair of leaves and each pair of pre-images are assumed to be sorted.
  35. *
  36. * This version handles proofs in memory with the default hashing function.
  37. */
  38. function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
  39. return processProof(proof, leaf) == root;
  40. }
  41. /**
  42. * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
  43. * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
  44. * hash matches the root of the tree. When processing the proof, the pairs
  45. * of leafs & pre-images are assumed to be sorted.
  46. *
  47. * This version handles proofs in memory with the default hashing function.
  48. */
  49. function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
  50. bytes32 computedHash = leaf;
  51. for (uint256 i = 0; i < proof.length; i++) {
  52. computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
  53. }
  54. return computedHash;
  55. }
  56. /**
  57. * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
  58. * defined by `root`. For this, a `proof` must be provided, containing
  59. * sibling hashes on the branch from the leaf to the root of the tree. Each
  60. * pair of leaves and each pair of pre-images are assumed to be sorted.
  61. *
  62. * This version handles proofs in memory with a custom hashing function.
  63. */
  64. function verify(
  65. bytes32[] memory proof,
  66. bytes32 root,
  67. bytes32 leaf,
  68. function(bytes32, bytes32) view returns (bytes32) hasher
  69. ) internal view returns (bool) {
  70. return processProof(proof, leaf, hasher) == root;
  71. }
  72. /**
  73. * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
  74. * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
  75. * hash matches the root of the tree. When processing the proof, the pairs
  76. * of leafs & pre-images are assumed to be sorted.
  77. *
  78. * This version handles proofs in memory with a custom hashing function.
  79. */
  80. function processProof(
  81. bytes32[] memory proof,
  82. bytes32 leaf,
  83. function(bytes32, bytes32) view returns (bytes32) hasher
  84. ) internal view returns (bytes32) {
  85. bytes32 computedHash = leaf;
  86. for (uint256 i = 0; i < proof.length; i++) {
  87. computedHash = hasher(computedHash, proof[i]);
  88. }
  89. return computedHash;
  90. }
  91. /**
  92. * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
  93. * defined by `root`. For this, a `proof` must be provided, containing
  94. * sibling hashes on the branch from the leaf to the root of the tree. Each
  95. * pair of leaves and each pair of pre-images are assumed to be sorted.
  96. *
  97. * This version handles proofs in calldata with the default hashing function.
  98. */
  99. function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
  100. return processProofCalldata(proof, leaf) == root;
  101. }
  102. /**
  103. * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
  104. * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
  105. * hash matches the root of the tree. When processing the proof, the pairs
  106. * of leafs & pre-images are assumed to be sorted.
  107. *
  108. * This version handles proofs in calldata with the default hashing function.
  109. */
  110. function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
  111. bytes32 computedHash = leaf;
  112. for (uint256 i = 0; i < proof.length; i++) {
  113. computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
  114. }
  115. return computedHash;
  116. }
  117. /**
  118. * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
  119. * defined by `root`. For this, a `proof` must be provided, containing
  120. * sibling hashes on the branch from the leaf to the root of the tree. Each
  121. * pair of leaves and each pair of pre-images are assumed to be sorted.
  122. *
  123. * This version handles proofs in calldata with a custom hashing function.
  124. */
  125. function verifyCalldata(
  126. bytes32[] calldata proof,
  127. bytes32 root,
  128. bytes32 leaf,
  129. function(bytes32, bytes32) view returns (bytes32) hasher
  130. ) internal view returns (bool) {
  131. return processProofCalldata(proof, leaf, hasher) == root;
  132. }
  133. /**
  134. * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
  135. * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
  136. * hash matches the root of the tree. When processing the proof, the pairs
  137. * of leafs & pre-images are assumed to be sorted.
  138. *
  139. * This version handles proofs in calldata with a custom hashing function.
  140. */
  141. function processProofCalldata(
  142. bytes32[] calldata proof,
  143. bytes32 leaf,
  144. function(bytes32, bytes32) view returns (bytes32) hasher
  145. ) internal view returns (bytes32) {
  146. bytes32 computedHash = leaf;
  147. for (uint256 i = 0; i < proof.length; i++) {
  148. computedHash = hasher(computedHash, proof[i]);
  149. }
  150. return computedHash;
  151. }
  152. /**
  153. * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
  154. * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
  155. *
  156. * This version handles multiproofs in memory with the default hashing function.
  157. *
  158. * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
  159. */
  160. function multiProofVerify(
  161. bytes32[] memory proof,
  162. bool[] memory proofFlags,
  163. bytes32 root,
  164. bytes32[] memory leaves
  165. ) internal pure returns (bool) {
  166. return processMultiProof(proof, proofFlags, leaves) == root;
  167. }
  168. /**
  169. * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
  170. * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
  171. * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
  172. * respectively.
  173. *
  174. * This version handles multiproofs in memory with the default hashing function.
  175. *
  176. * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
  177. * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
  178. * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
  179. */
  180. function processMultiProof(
  181. bytes32[] memory proof,
  182. bool[] memory proofFlags,
  183. bytes32[] memory leaves
  184. ) internal pure returns (bytes32 merkleRoot) {
  185. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  186. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  187. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  188. // the Merkle tree.
  189. uint256 leavesLen = leaves.length;
  190. uint256 proofFlagsLen = proofFlags.length;
  191. // Check proof validity.
  192. if (leavesLen + proof.length != proofFlagsLen + 1) {
  193. revert MerkleProofInvalidMultiproof();
  194. }
  195. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  196. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  197. bytes32[] memory hashes = new bytes32[](proofFlagsLen);
  198. uint256 leafPos = 0;
  199. uint256 hashPos = 0;
  200. uint256 proofPos = 0;
  201. // At each step, we compute the next hash using two values:
  202. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  203. // get the next hash.
  204. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  205. // `proof` array.
  206. for (uint256 i = 0; i < proofFlagsLen; i++) {
  207. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  208. bytes32 b = proofFlags[i]
  209. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  210. : proof[proofPos++];
  211. hashes[i] = Hashes.commutativeKeccak256(a, b);
  212. }
  213. if (proofFlagsLen > 0) {
  214. if (proofPos != proof.length) {
  215. revert MerkleProofInvalidMultiproof();
  216. }
  217. unchecked {
  218. return hashes[proofFlagsLen - 1];
  219. }
  220. } else if (leavesLen > 0) {
  221. return leaves[0];
  222. } else {
  223. return proof[0];
  224. }
  225. }
  226. /**
  227. * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
  228. * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
  229. *
  230. * This version handles multiproofs in memory with a custom hashing function.
  231. *
  232. * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
  233. */
  234. function multiProofVerify(
  235. bytes32[] memory proof,
  236. bool[] memory proofFlags,
  237. bytes32 root,
  238. bytes32[] memory leaves,
  239. function(bytes32, bytes32) view returns (bytes32) hasher
  240. ) internal view returns (bool) {
  241. return processMultiProof(proof, proofFlags, leaves, hasher) == root;
  242. }
  243. /**
  244. * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
  245. * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
  246. * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
  247. * respectively.
  248. *
  249. * This version handles multiproofs in memory with a custom hashing function.
  250. *
  251. * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
  252. * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
  253. * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
  254. */
  255. function processMultiProof(
  256. bytes32[] memory proof,
  257. bool[] memory proofFlags,
  258. bytes32[] memory leaves,
  259. function(bytes32, bytes32) view returns (bytes32) hasher
  260. ) internal view returns (bytes32 merkleRoot) {
  261. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  262. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  263. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  264. // the Merkle tree.
  265. uint256 leavesLen = leaves.length;
  266. uint256 proofFlagsLen = proofFlags.length;
  267. // Check proof validity.
  268. if (leavesLen + proof.length != proofFlagsLen + 1) {
  269. revert MerkleProofInvalidMultiproof();
  270. }
  271. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  272. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  273. bytes32[] memory hashes = new bytes32[](proofFlagsLen);
  274. uint256 leafPos = 0;
  275. uint256 hashPos = 0;
  276. uint256 proofPos = 0;
  277. // At each step, we compute the next hash using two values:
  278. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  279. // get the next hash.
  280. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  281. // `proof` array.
  282. for (uint256 i = 0; i < proofFlagsLen; i++) {
  283. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  284. bytes32 b = proofFlags[i]
  285. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  286. : proof[proofPos++];
  287. hashes[i] = hasher(a, b);
  288. }
  289. if (proofFlagsLen > 0) {
  290. if (proofPos != proof.length) {
  291. revert MerkleProofInvalidMultiproof();
  292. }
  293. unchecked {
  294. return hashes[proofFlagsLen - 1];
  295. }
  296. } else if (leavesLen > 0) {
  297. return leaves[0];
  298. } else {
  299. return proof[0];
  300. }
  301. }
  302. /**
  303. * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
  304. * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
  305. *
  306. * This version handles multiproofs in calldata with the default hashing function.
  307. *
  308. * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
  309. */
  310. function multiProofVerifyCalldata(
  311. bytes32[] calldata proof,
  312. bool[] calldata proofFlags,
  313. bytes32 root,
  314. bytes32[] memory leaves
  315. ) internal pure returns (bool) {
  316. return processMultiProofCalldata(proof, proofFlags, leaves) == root;
  317. }
  318. /**
  319. * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
  320. * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
  321. * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
  322. * respectively.
  323. *
  324. * This version handles multiproofs in calldata with the default hashing function.
  325. *
  326. * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
  327. * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
  328. * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
  329. */
  330. function processMultiProofCalldata(
  331. bytes32[] calldata proof,
  332. bool[] calldata proofFlags,
  333. bytes32[] memory leaves
  334. ) internal pure returns (bytes32 merkleRoot) {
  335. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  336. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  337. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  338. // the Merkle tree.
  339. uint256 leavesLen = leaves.length;
  340. uint256 proofFlagsLen = proofFlags.length;
  341. // Check proof validity.
  342. if (leavesLen + proof.length != proofFlagsLen + 1) {
  343. revert MerkleProofInvalidMultiproof();
  344. }
  345. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  346. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  347. bytes32[] memory hashes = new bytes32[](proofFlagsLen);
  348. uint256 leafPos = 0;
  349. uint256 hashPos = 0;
  350. uint256 proofPos = 0;
  351. // At each step, we compute the next hash using two values:
  352. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  353. // get the next hash.
  354. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  355. // `proof` array.
  356. for (uint256 i = 0; i < proofFlagsLen; i++) {
  357. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  358. bytes32 b = proofFlags[i]
  359. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  360. : proof[proofPos++];
  361. hashes[i] = Hashes.commutativeKeccak256(a, b);
  362. }
  363. if (proofFlagsLen > 0) {
  364. if (proofPos != proof.length) {
  365. revert MerkleProofInvalidMultiproof();
  366. }
  367. unchecked {
  368. return hashes[proofFlagsLen - 1];
  369. }
  370. } else if (leavesLen > 0) {
  371. return leaves[0];
  372. } else {
  373. return proof[0];
  374. }
  375. }
  376. /**
  377. * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
  378. * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
  379. *
  380. * This version handles multiproofs in calldata with a custom hashing function.
  381. *
  382. * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
  383. */
  384. function multiProofVerifyCalldata(
  385. bytes32[] calldata proof,
  386. bool[] calldata proofFlags,
  387. bytes32 root,
  388. bytes32[] memory leaves,
  389. function(bytes32, bytes32) view returns (bytes32) hasher
  390. ) internal view returns (bool) {
  391. return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
  392. }
  393. /**
  394. * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
  395. * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
  396. * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
  397. * respectively.
  398. *
  399. * This version handles multiproofs in calldata with a custom hashing function.
  400. *
  401. * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
  402. * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
  403. * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
  404. */
  405. function processMultiProofCalldata(
  406. bytes32[] calldata proof,
  407. bool[] calldata proofFlags,
  408. bytes32[] memory leaves,
  409. function(bytes32, bytes32) view returns (bytes32) hasher
  410. ) internal view returns (bytes32 merkleRoot) {
  411. // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
  412. // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
  413. // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
  414. // the Merkle tree.
  415. uint256 leavesLen = leaves.length;
  416. uint256 proofFlagsLen = proofFlags.length;
  417. // Check proof validity.
  418. if (leavesLen + proof.length != proofFlagsLen + 1) {
  419. revert MerkleProofInvalidMultiproof();
  420. }
  421. // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
  422. // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
  423. bytes32[] memory hashes = new bytes32[](proofFlagsLen);
  424. uint256 leafPos = 0;
  425. uint256 hashPos = 0;
  426. uint256 proofPos = 0;
  427. // At each step, we compute the next hash using two values:
  428. // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
  429. // get the next hash.
  430. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
  431. // `proof` array.
  432. for (uint256 i = 0; i < proofFlagsLen; i++) {
  433. bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
  434. bytes32 b = proofFlags[i]
  435. ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
  436. : proof[proofPos++];
  437. hashes[i] = hasher(a, b);
  438. }
  439. if (proofFlagsLen > 0) {
  440. if (proofPos != proof.length) {
  441. revert MerkleProofInvalidMultiproof();
  442. }
  443. unchecked {
  444. return hashes[proofFlagsLen - 1];
  445. }
  446. } else if (leavesLen > 0) {
  447. return leaves[0];
  448. } else {
  449. return proof[0];
  450. }
  451. }
  452. }