MerkleProof.sol 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.6.0;
  3. /**
  4. * @dev These functions deal with verification of Merkle trees (hash trees),
  5. */
  6. library MerkleProof {
  7. /**
  8. * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
  9. * defined by `root`. For this, a `proof` must be provided, containing
  10. * sibling hashes on the branch from the leaf to the root of the tree. Each
  11. * pair of leaves and each pair of pre-images are assumed to be sorted.
  12. */
  13. function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
  14. bytes32 computedHash = leaf;
  15. for (uint256 i = 0; i < proof.length; i++) {
  16. bytes32 proofElement = proof[i];
  17. if (computedHash <= proofElement) {
  18. // Hash(current computed hash + current element of the proof)
  19. computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
  20. } else {
  21. // Hash(current element of the proof + current computed hash)
  22. computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
  23. }
  24. }
  25. // Check if the computed hash (root) is equal to the provided root
  26. return computedHash == root;
  27. }
  28. }