Skip to content

MerkleTree Contract Constructor while loop is not working properly for odd leaf nodes. #338

@Ayush-Dutt-Sharma

Description

@Ayush-Dutt-Sharma

I noticed the Merkle tree example doesn’t handle odd numbers of leaf nodes correctly. When there's an odd number of transactions, the last unpaired hash gets skipped instead of being duplicated, which leads to an incorrect Merkle root.

#Issue
In this loop:

for (uint256 i = 0; i < n - 1; i += 2) {
// ...
}

The last hash is ignored if n is odd.

#Fix

Duplicate the last hash when needed

for (uint256 i = 0; i < n; i += 2) {
if (i + 1 < n) {
hashes.push(keccak256(abi.encodePacked(hashes[offset + i], hashes[offset + i + 1])));
} else {
hashes.push(keccak256(abi.encodePacked(hashes[offset + i], hashes[offset + i])));
}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions