MerkleProof.sol 1.3 KB

12345678910111213141516171819202122232425262728293031323334
  1. pragma solidity ^0.5.7;
  2. /**
  3. * @title MerkleProof
  4. * @dev Merkle proof verification based on
  5. * https://github.com/ameensol/merkle-tree-solidity/blob/master/src/MerkleProof.sol
  6. */
  7. library MerkleProof {
  8. /**
  9. * @dev Verifies a Merkle proof proving the existence of a leaf in a Merkle tree. Assumes that each pair of leaves
  10. * and each pair of pre-images are sorted.
  11. * @param proof Merkle proof containing sibling hashes on the branch from the leaf to the root of the Merkle tree
  12. * @param root Merkle root
  13. * @param leaf Leaf of Merkle tree
  14. */
  15. function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
  16. bytes32 computedHash = leaf;
  17. for (uint256 i = 0; i < proof.length; i++) {
  18. bytes32 proofElement = proof[i];
  19. if (computedHash < proofElement) {
  20. // Hash(current computed hash + current element of the proof)
  21. computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
  22. } else {
  23. // Hash(current element of the proof + current computed hash)
  24. computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
  25. }
  26. }
  27. // Check if the computed hash (root) is equal to the provided root
  28. return computedHash == root;
  29. }
  30. }