You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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])));
}
}