Generate Merkle Root
How to verify the lottery/raffle outcome.
Generating Merkle Root for verification
Step 1: Construct Leaf Bytes
For each holder:
Encode the public key as 32 bytes
Convert the
start,end, andleaf indexvalues into 8-byte little-endian integers.Concatenate the values in this order:
leaf_bytes = pubkey_bytes || start_bytes || end_bytes || leaf_index_bytes
This ensures the leaf structure matches the on-chain verification logic.
Step 2: Hash Leaves (Double Hashing)
Apply Keccak256 to the leaf bytes.
Then, hash the result again (double hashing):
leaf_hash = Keccak256(Keccak256(leaf_bytes))
Step 3: Build the Merkle Tree
Start with all the double-hashed leaves.
Iteratively build parent nodes:
Pair adjacent hashes (
left,right) and compute the parent hash:
parent_hash = Keccak256(left || right)
If there is an odd number of nodes at the current level, duplicate the last node:
parent_hash = Keccak256(last_node || last_node)3. Replace the current level with the newly computed parent hashes. 4. Repeat until only one hash remains.
Step 4: Merkle Root
The final single hash at the top of the tree is the Merkle root.
This root is used in the smart contract to verify individual proofs against the tree.
Important Notes:
Leaf ordering: The order of leaves determines the root; it must be consistent with proof generation.
Intermediate nodes: Only single Keccak256 hash is applied per parent node.
Odd leaves: The last node is duplicated if the number of nodes at a level is odd.
Double hash: Only applies to leaves, not to parent nodes.
Hashing algorithm: Use Keccak256 consistently across leaves and nodes.
Last updated