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
>>> import datetime

>>> # 1. Getting header values from blockexplorer.com
>>> version = "00000001" # 1 from blockexplorer.com
>>> hashPrevBlock = \
>>> hashMerkleRoot =  \
"2b12fcf1b09288fcaff797d71e950e71ae42b91e8bdb2304758dfcffc2b620e3"

>>> time = datetime.datetime(2011,5,21,13,26,31) # May 21, 2011 1:26:31 PM
>>> time = int(time.timestamp()) # 1305998791 as POSIX timstamp
>>> time = hex(int(0x100000000)+time)[-8:] # in 4-byte hex notation
>>> print(time) # should print '4dd7f5c7'

>>> bits = "1a44b9f2" # blockexplorer.com

>>> nonce = 2504433986 # in decimal notation from blockexplorer.com
>>> nonce = hex(int(0x100000000)+nonce)[-8:] # in 4-byte hex notation
>>> print(nonce) # should print '9546a142'

>>> # 2. Converting 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

>>> # 4. Taking the double-SHA256 hash value