[Ethereum] Correct way to concatenate hashes for merkle tree

hashjavascriptkeccakmerkle-patricia-tries

I'm using Richard Moore's ethers.js to create hashes of documents that will eventually be stored on the EVM. To create a merkle tree with many documents I'll need to hash together hashes. What's the correct/conical way to concatenate these before I apply the hashing function?

var left = 0xbe5b5152fcd01b6bf53f149bfd1493a49ec5e8ae94cc4c29a81563eea0e347f4;
var right = 0xe97032473c4f6788bf3f197518c925b296172520eae8df21f8ce2c6a1df54146;

// Is this the best way to concat?
var joined = left.toString(16) + right.toString(16);
var newHash = ethers.utils.keccak256( ethers.utils.toUtf8Bytes(joined) );

Best Answer

Here is an article that makes use of Merkle trees using ethers.js, in both JavaScript and Solidity.

Here is the JavaScript for the Merkle tree creation and here is the Solidity that verifies it.

Given the above example though, keep in mind you cannot use JavaScript numbers that way. You will need the left and right to be strings.

For example:

// JavaScript (with quotes)
var left = '0xbe5b5152fcd01b6bf53f149bfd1493a49ec5e8ae94cc4c29a81563eea0e347f4';
var right = '0xe97032473c4f6788bf3f197518c925b296172520eae8df21f8ce2c6a1df54146';
var newHash = ethers.utils.keccak256(ethers.utils.concat([ left, right ]))

// Solidity (without quotes)
bytes32 left = 0xbe5b5152fcd01b6bf53f149bfd1493a49ec5e8ae94cc4c29a81563eea0e347f4;
bytes32 right = 0xe97032473c4f6788bf3f197518c925b296172520eae8df21f8ce2c6a1df54146;
bytes32 newHash = keccak256(left, right);
Related Topic