MerkleProof.sol 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. pragma solidity ^0.4.24;
  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 verifyProof(
  16. bytes32[] _proof,
  17. bytes32 _root,
  18. bytes32 _leaf
  19. )
  20. internal
  21. pure
  22. returns (bool)
  23. {
  24. bytes32 computedHash = _leaf;
  25. for (uint256 i = 0; i < _proof.length; i++) {
  26. bytes32 proofElement = _proof[i];
  27. if (computedHash < proofElement) {
  28. // Hash(current computed hash + current element of the proof)
  29. computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
  30. } else {
  31. // Hash(current element of the proof + current computed hash)
  32. computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
  33. }
  34. }
  35. // Check if the computed hash (root) is equal to the provided root
  36. return computedHash == _root;
  37. }
  38. }