For constructing the merkle tree txids are paired and hashed. ¹
But how are these txids paired? Does it happen chronologically or is there a certain pattern of pairing?
Transaction order in the block
Currently, there are only two requirements for the order of transactions:
- The coinbase transaction is always first.
- Intra block dependencies must preceed, i.e. if
Transaction Bare both in the same block, and
Transaction Bspends outputs of
Amust be listed before
It is likely that in the future a correct order for transaction will be introduced, as this will allow proving the absence of a transaction in a block with logarithmic effort, and will allow more efficient block data propagation through IBLT. Right now, transactions are propagated in the network before confirmation, and then again as the content of a block. With a deterministic transaction order and IBLT set reconciliation, each transaction would only have to be received once instead of twice.
Building the Merkle Tree
The transactions are inserted into the Merkle Tree in the same order they are listed in the block. If a block only contains the Coinbase Transaction, the Coinbase's transaction ID is used as the Merkle Root.
Otherwise, a binary tree is created from the transactions by pairing transaction hashes on the first level, then pairing resulting hashes on each next level until only one hash results, which is then used as the Merkle Root. If there is an odd number of hashes to be paired, the last hash is paired with itself.
The Developer Reference has additional details. The image is from the Developer Reference as well, and hence licensed MIT.
Antonopoulos covers Merkle trees in detail in his book, also providing examples of how it is used to prove transaction presence in blocks.