Block Hash Calculation Algorithm

This section describes the Block Hash Calculation Algorithm.

Bitcoin uses the following algorithm to calculate the block hash:

• 1. Get values from block header fields: version, hashPrevBlock, hashMerkleRoot, time, bits, nonce.
• 2. Convert field values in little-endian hex notation, if they are displayed in big-endian hex notation as with most Bitcoin tools including Bitcoin Core and blockexplorer.com.
• 3. Concatenate header field values into a header string: header = version+hashPrevBlock+hashMerkleRoot+time+bits+nonce.
• 4. Take the double-SHA256 hash value from the header string: hash = SHA256(SHA256(header)).
• 5. Return the hash value as the block hash.
• 6. Convert the hash value in big-endian hex notation, in order to compare it with other Bitcoin tools.

First lets follow the Python example given in Block hashing algorithm, which calculates the block hash of Bitcoin Block 125552. Note that I had to replace string decode() and encode() with binascii.unhexlify() and binascii.hexlify() on my Python installation.

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

>>> header_hex = ("01000000" +
...  "81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000" +
...  "e320b6c2fffc8d750423db8b1eb942ae710e951ed797f7affc8892b0f1fc122b" +
...  "c7f5d74d" +
...  "f2b9441a" +
...  "42a14695")
>>> hash = hashlib.sha256(hashlib.sha256(header_bin).digest()).digest()

>>> binascii.hexlify(hash)
b'1dbd981fe6985776b644b173a4d0385ddc1aa2a829688d1e0000000000000000'

>>> binascii.hexlify(hash[::-1])
```Block #125552