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.

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

#- Double-SHA256-Test-Vectors.py
#- Copyright (c) 2018, HerongYang.com, All Rights Reserved.

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:
   ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
Double-SHA256:
   4f8b42c22dd3729b519ba6f68d2da7cc5b2d606d05daed5ad5128cc03e6c6358

Test 2:
Input ASCII: 'The quick brown fox jumps over the lazy dog'
Input Hex: 54686520717569636b2062726f776e20666f78206a756d7073206f76657220746
           865206c617a7920646f67
SHA256:
   d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592
Double-SHA256:
   6d37795021e544d82b41850edf7aabab9a0ebe274e54a519840c4666f35b3937

Last update: 2018.

Table of Contents

 About This Book

 Introduction of Bitcoin

 Bitcoin Blockchain

 Bitcoin Wallet

 Bitcoin Core

 Bitcoin Transaction

 Bitcoin-Qt - Bitcoin Core GUI

 Bitcoin Mining

 Bitcoin Consensus Rules

Bitcoin Block Data Structure

 Data Components of Bitcoin Block

 Data Properties of Bitcoin Block

 Merkle Root of Bitcoin Block

Calculate Double-SHA256 Hash with Python

 Verify Merkle Root of 2 Transactions

 Verify Merkle Root of 7 Transactions

 Data Structure of Bitcoin Block

 "getblock blockhash 0" - Serialized Hex Block Data

 Block Hash Calculation Algorithm

 Block Hash Calculation in Python

 Calculate Double-SHA256 Hash with Java

 Bitcoin Transaction Data Structure

 blockexplorer.com API

 Copay - Bitcoin Wallet

 References

 PDF Printing Version