Skip to content

Commit

Permalink
Introduce verifyAndRecoverIndex
Browse files Browse the repository at this point in the history
  • Loading branch information
k06a committed Aug 7, 2021
1 parent 5b0233c commit ab80341
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion contracts/utils/cryptography/MerkleProof.sol
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,23 @@ library MerkleProof {
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
(bool success, uint256 index) = verifyAndRecoverIndex(proof, root, leaf);
return success;
}

/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verifyAndRecoverIndex(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool, uint256) {
bytes32 computedHash = leaf;
uint256 index = 0;

for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
Expand All @@ -34,11 +50,12 @@ library MerkleProof {
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
index |= 1 << i;
}
}

// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
return (computedHash == root, index);
}

/**
Expand Down

0 comments on commit ab80341

Please sign in to comment.