Calculate Double-SHA256 Hash with Python

This section describes how to calculate Double-SHA256 hash with Python.

Before writing Python code to verify the Merkle Root in Bitcoin block, we need to get familiar with two Python modules needed for calculating SHA256 hash.

• "hashlib" module - Provides us the SHA56 hash functions.
• "binascii" module - Provides us functions to convert data between binary and hex formats.

Here is my Python script to perform SHA256 hash and Double-SHA256 hash on 3 test vectors:

```#- Double-SHA256-Test-Vectors.py

import hashlib
import binascii

def doubleSha256(hex):
bin = binascii.unhexlify(hex)
hash = hashlib.sha256(bin).digest()
hash2 = hashlib.sha256(hash).digest()
print("Input Hex: "+str(hex,"ascii"))
print("SHA256:\n   "+str(binascii.hexlify(hash),"ascii"))
print("Double-SHA256:\n   "+str(binascii.hexlify(hash2),"ascii"))

print("\nTest 1:")
ascii = "null"
hex = b"00"
print("Input ASCII: "+ascii)
doubleSha256(hex)

print("\nTest 2:")
ascii = "abc"
hex = binascii.hexlify(bytes(ascii,"ascii"))
print("Input ASCII: '"+ascii+"'")
doubleSha256(hex)

print("\nTest 2:")
ascii = "The quick brown fox jumps over the lazy dog"
hex = binascii.hexlify(bytes(ascii,"ascii"))
print("Input ASCII: '"+ascii+"'")
doubleSha256(hex)
```

The output looks good. SHA256 values match well with tests published on the Internet.

```E:\herong\bitcoin_20080000\cod>python Double-SHA256-Test-Vectors.py

Test 1:
Input ASCII: null
Input Hex: 00
SHA256:
6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d
Double-SHA256:
1406e05881e299367766d313e26c05564ec91bf721d31726bd6e46e60689539a

Test 2:
Input ASCII: 'abc'
Input Hex: 616263
SHA256:
Double-SHA256: