From 6b06abc41cd691ddb42cc6b8f384adfbf0af8570 Mon Sep 17 00:00:00 2001 From: myh <95896306+Anchor-x@users.noreply.github.com> Date: Wed, 5 Jun 2024 16:09:04 +0800 Subject: [PATCH] =?UTF-8?q?Merkle=E6=A0=91=E7=9A=84Solidity=E5=90=88?= =?UTF-8?q?=E7=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contracts/MerkleProof.sol | 42 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 contracts/MerkleProof.sol diff --git a/contracts/MerkleProof.sol b/contracts/MerkleProof.sol new file mode 100644 index 0000000..932534b --- /dev/null +++ b/contracts/MerkleProof.sol @@ -0,0 +1,42 @@ +pragma solidity ^0.5.0; + +/** + * @title MerkleProof + * @dev Merkle proof verification based on https://github.com/ameensol/merkle-tree-solidity/blob/master/src/MerkleProof.sol + * Source: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/MerkleProof.sol + */ +library MerkleProof { + /** + * @dev Verifies a Merkle proof proving the existence of a leaf in a Merkle tree. Assumes that each pair of leaves + * and each pair of pre-images are sorted. + * @param _proof Merkle proof containing sibling hashes on the branch from the leaf to the root of the Merkle tree + * @param _root Merkle root + * @param _leaf Leaf of Merkle tree + */ + function verifyProof( + bytes32[] memory _proof, + bytes32 _root, + bytes32 _leaf + ) + internal + pure + returns (bool) + { + bytes32 computedHash = _leaf; + + for (uint256 i = 0; i < _proof.length; i++) { + bytes32 proofElement = _proof[i]; + + if (computedHash < proofElement) { + // Hash(current computed hash + current element of the proof) + computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); + } else { + // Hash(current element of the proof + current computed hash) + computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); + } + } + + // Check if the computed hash (root) is equal to the provided root + return computedHash == _root; + } +} \ No newline at end of file