MerkleProof.sol 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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) pure returns (bool) {
  16. // Check if proof length is a multiple of 32
  17. if (_proof.length % 32 != 0) return false;
  18. bytes32 proofElement;
  19. bytes32 computedHash = _leaf;
  20. for (uint256 i = 32; i <= _proof.length; i += 32) {
  21. assembly {
  22. // Load the current element of the proof
  23. proofElement := mload(add(_proof, i))
  24. }
  25. if (computedHash < proofElement) {
  26. // Hash(current computed hash + current element of the proof)
  27. computedHash = keccak256(computedHash, proofElement);
  28. } else {
  29. // Hash(current element of the proof + current computed hash)
  30. computedHash = keccak256(proofElement, computedHash);
  31. }
  32. }
  33. // Check if the computed hash (root) is equal to the provided root
  34. return computedHash == _root;
  35. }
  36. }