MerkleProof.sol 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. pragma solidity ^0.4.18;
  2. /*
  3. * @title MerkleProof
  4. * @dev Merkle proof verification
  5. * @note Based on 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 is 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(bytes _proof, bytes32 _root, bytes32 _leaf) public pure returns (bool) {
  16. // Check if proof length is a multiple of 32
  17. if (_proof.length % 32 != 0) {
  18. return false;
  19. }
  20. bytes32 proofElement;
  21. bytes32 computedHash = _leaf;
  22. for (uint256 i = 32; i <= _proof.length; i += 32) {
  23. // solium-disable-next-line security/no-inline-assembly
  24. assembly {
  25. // Load the current element of the proof
  26. proofElement := mload(add(_proof, i))
  27. }
  28. if (computedHash < proofElement) {
  29. // Hash(current computed hash + current element of the proof)
  30. computedHash = keccak256(computedHash, proofElement);
  31. } else {
  32. // Hash(current element of the proof + current computed hash)
  33. computedHash = keccak256(proofElement, computedHash);
  34. }
  35. }
  36. // Check if the computed hash (root) is equal to the provided root
  37. return computedHash == _root;
  38. }
  39. }