MerkleProof.sol 1.2 KB

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