Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle the precondition in path length from key when the number of leaves is <= 1 #274

Merged
merged 3 commits into from
Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/lib/tree/Utils.sol
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@ function getStartingBit(uint256 numLeaves) pure returns (uint256 startingBit) {
/// @param key: The key of the leaf
/// @param numLeaves: The total number of leaves in the tree
/// @return pathLength : The length of the path to the leaf
/// @dev A precondition to this function is that `numLeaves > 1`, so that `(pathLength - 1)` does not cause an underflow when pathLength = 0.
// solhint-disable-next-line func-visibility
function pathLengthFromKey(uint256 key, uint256 numLeaves) pure returns (uint256 pathLength) {
if (numLeaves <= 1) {
// if the number of leaves of the tree is 1 or 0, the path always is 0.
return 0;
}
// Get the height of the left subtree. This is equal to the offset of the starting bit of the path
pathLength = Constants.MAX_HEIGHT - getStartingBit(numLeaves);

Expand Down
22 changes: 22 additions & 0 deletions src/lib/tree/binary/test/BinaryMerkleTree.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,28 @@ contract BinaryMerkleProofTest is DSTest {
assertEq(result[1], data[2]);
}

function testSameKeyAndLeavesNumber() external {
bytes32 root = 0xb855b42d6c30f5b087e05266783fbd6e394f7b926013ccaa67700a8b0c5a596f;
bytes32[] memory sideNodes = new bytes32[](0);
uint256 key = 3;
uint256 numLeaves = 3;
BinaryMerkleProof memory proof = BinaryMerkleProof(sideNodes, key, numLeaves);
bytes memory data = bytes(hex"01");
bool isValid = BinaryMerkleTree.verify(root, proof, data);
assert(!isValid);
}

function testConsecutiveKeyAndNumberOfLeaves() external {
bytes32 root = 0xb855b42d6c30f5b087e05266783fbd6e394f7b926013ccaa67700a8b0c5a596f;
bytes32[] memory sideNodes = new bytes32[](0);
uint256 key = 6;
uint256 numLeaves = 7;
BinaryMerkleProof memory proof = BinaryMerkleProof(sideNodes, key, numLeaves);
bytes memory data = bytes(hex"01");
bool isValid = BinaryMerkleTree.verify(root, proof, data);
assert(!isValid);
}

function testInvalidSliceBeginEnd() public {
bytes32[] memory data = new bytes32[](4);
data[0] = "a";
Expand Down
Loading