Skip to content

Handle Odd Number of Leaf Nodes in Merkle Tree Construction #339

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

Open
wants to merge 1 commit into
base: gh-pages
Choose a base branch
from

Conversation

Ayush-Dutt-Sharma
Copy link

@Ayush-Dutt-Sharma Ayush-Dutt-Sharma commented Jul 9, 2025

#338
Merkle tree example where an odd number of leaf nodes would result in an incorrect root hash.

Previously, the last unpaired node was skipped during hashing. This fix ensures the tree remains valid by duplicating the last node when necessary.

#Fix
Replaced the loop inside the constructor with logic that handles both even and odd numbers of nodes:

while (n > 1) {
    for (uint256 i = 0; i < n; i += 2) {
        bytes32 left = hashes[offset + i];
        bytes32 right;

        if (i + 1 < n) {
            right = hashes[offset + i + 1];
        } else {
            right = left; // duplicate last node if odd
        }

        hashes.push(keccak256(abi.encodePacked(left, right)));
    }
    offset += n;
    n = (n + 1) / 2;
}

the while loop is not working properly when there are an odd number of leaf nodes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant