How to calculate the hash of a block in bitcoin?

Do you want to calculate the hash of a block yourself? Let’s create a python program.

Jayamine Alupotha
hackergirl
2 min readFeb 20, 2018

--

In Bitcoin, creating a new block is difficult. But it is easy to verify whether a block is acceptable or not.

Parameters

To calculate the hash of a block, we need these parameters,

  • Version( “ver”)
  • Previous block hash(“prev_block”)
  • Merkle root(“mrkl_root”)
  • Time stamp(“time”)
  • Difficulty bits(“bits”)
  • Nonce(“nonce”)

Let’s verify the hash of the genesis block (block 0). Find the block data in JSON format here.

Version

The version of a block is a decimal number which is denoted by 4 bytes. Translate the version into a little-endian hex.

#Big endian encoding
0x00000001
#Little endian encoding
0x01000000

Previous block hash

Translate the previous block hash to a little endian hex.

0x0000000000000000000000000000000000000000000000000000000000000000

Merkle root

Translate the merkle root to a little endian hex.

0x3ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a

Time stamp

Time is a decimal value. Translate it into a little endian hex.

#Decimal value
1231006505
#Hex values
0x495fab29
#Little endian encoding
0x29ab5f49

Difficulty bits

The difficulty bits are in decimal format. Convert them into a little-endian hex.

#Decimal Value
486604799
#Little endian encoding
0xffff001d

Nonce

The nonce is a decimal value. Convert it into a little-endian hex.

#Decimal Value
2083236893
#Hex Value
0x7c2bac1d
#Little endian encoding
0x1dac2b7c

Calculating the Hash Value

Now we can append all the parameters together.

0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c

Let’s get the SHA-256 value of the appended parameters. The little-endian format of that SHA-256 value is the hash value of the block.

0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f

Acceptability

There are two conditions for the hash of a block,

  1. The manually calculated hash value must match with the hash value which was sent by the block creator (miner).
  2. The hash value must be equal or smaller than the target value defined by the difficulty bits (bits).

Python Verifier

The following python program calculates and verifies the hash of a block. Please go to the GitHub repository to download the code.

Run the python program

Import block data from webbtc.

python hashCalculator.py -i http://webbtc.com/block/000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f.json

Import block data from a file(*.json).

python hashCalculator.py -f block0.json

Results

The program returns the acceptability of the hash of the block.

--

--