Block Hash Calculation in Python

This section describes how to calculate Bitcoin block hash in Python.

In the previous tutorial, we verify the Bitcoin block hash calculation quickly with the Python example code given in Block hashing algorithm. It uses header values given in little-endian hex notation directly.

Now let's create a detailed version of Python code that takes header values displayed on blockexplorer.com and follows our Bitcoin block hash calculation algorithm precisely.

```C:\>Python
>>> import hashlib
>>> import binascii

>>> # 1. Getting header values from blockexplorer.com
>>> version = "00000001" # 1
>>> hashPrevBlock = "00000000000008a3a41b85b8b29ad444def299fee21793cd8b9e567eab02cd81"
>>> hashMerkleRoot = "2b12fcf1b09288fcaff797d71e950e71ae42b91e8bdb2304758dfcffc2b620e3"
>>> time = "4dd7f5c7" # May 21, 2011 1:26:31 PM
>>> bits = "1a44b9f2"
>>> nonce = 2504433986 # in decimal notation
>>> nonce = hex(int(0x100000000)+nonce))[-8:] # in 4-byte hex notation "9546a142"

>>> # 2. Convert them in little-endian hex notation
>>> version = binascii.hexlify(binascii.unhexlify(version)[::-1])
>>> hashPrevBlock = binascii.hexlify(binascii.unhexlify(hashPrevBlock)[::-1])
>>> hashMerkleRoot = binascii.hexlify(binascii.unhexlify(hashMerkleRoot)[::-1])
>>> time = binascii.hexlify(binascii.unhexlify(time)[::-1])
>>> bits = binascii.hexlify(binascii.unhexlify(bits)[::-1])
>>> nonce = binascii.hexlify(binascii.unhexlify(nonce)[::-1])

>>> # 3. Concatenating header values
>>> header = version+hashPrevBlock+hashMerkleRoot+time+bits+nonce

>>> # 4. Taking the double-SHA256 hash value
>>> header = binascii.unhexlify(header)
>>> hash = hashlib.sha256(hashlib.sha256(header).digest()).digest()
>>> hash = binascii.hexlify(hash)

>>> # 5. Converting the hash value in big-endian hex notation
>>> hash = binascii.hexlify(binascii.unhexlify(hash)[::-1])
>>> hash
b'00000000000000001e8d6829a8a21adc5d38d0a473b144b6765798e61f98bd1d'
```

Cool. Our Python script works!

Last update: 2018.

Table of Contents