Merkle root of a bitcoin block calculated in C#

Merkle root of a bitcoin block calculated in C#

What is a Merkle Tree?

Merkle tree aka binary hash tree is a data structure used for efficiently summarising and verifying the integrity of large data sets
Merkle tree is a kind of inverted tree structure with the root (known as the Merkle root) at the top and the leaves at the bottom. See the example below.
This data structure is used in the bitcoin and blockchain technologies to summarise all the transactions in a block, providing a very efficient process to verify whether a transaction is included in a block.

A bit of history

Merkle was also one of the inventors of public key cryptography and he appears to have long moved on from cryptography to solving more interesting problems. You can check out his webpage here.
While learning about Merkle tree, I had an idea to quickly write some code to download a block from the bitcoin chain and calculate the Merkle root of the transactions to see if I would arrive at the same Merkle root calculated by a block miner and verified by the network because …… well why not?

  • The transaction represents the original data blocks which are hashed to produce transaction hashes (transaction id) which form the leaf nodes.
  • The leaf nodes have to be even in number for a binary hash tree to work so if the number of leaf nodes is an odd number, then the last leaf node is duplicated to even the count.
  • Each pair of leaf nodes is concatenated and hashed to form the second row of hashes.
  • The process is repeated until a row is obtained with only two hashes
  • These last two hashes are concatenated to form the Merkle root.

In little endian machines , it will be arranged in memory as

Address0 Byte0
Address1 Byte1
Address2 Byte2
Address3 Byte3

In big endian machines , it will be arranged in memory as

Address0 Byte3
Address1 Byte2
Address2 Byte1
Address3 Byte0

  • convert the transaction hashes from little-endian to big-endian before. running the BuildMerkleRoot algorithm.
  • convert the Merkle root back to little-endian

  • this is just get it working code 🙂