Exactly which items from a block are included in the data that is hashed to produce the block hash?
In Mastering Bitcoin there is this diagram which shows the data included:
Previous Block Header Hash
Other sources indicate that the version number from the block header is also included in the data hashed.
The difficulty, which is loosely an inverse of the target, is in a compact representation known as "bits".
The Merkle root is a hash produced in a tree-wise fashion from hashes of transaction data.
- What is the difference between Root Hash and Block Hash?
- Block Hashing Algorithm (wiki)
- Block Chain (developer reference)
Agree with @RedGrittyBrick. And I would like to make it more clear.The version number is also included.
All six params are simply concatenated by the order listed below, but be careful about the datatype(int or string) and the byte-order(little-endian or big-endian), the correct order is:
- Previous Block Header Hash
- Merkle root
- Bits (Difficulty)
Here is a Python program with comments to validate a block hash with height 2
from hashlib import sha256 import struct # below are the params of Block height 2 ver = 1 # 4 Bytes (32 bits) prev_block = "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048" # 32 Bytes (256 bits) mrkl_root = "9b0fc92260312ce44e74ef369f5c66bbb85848f2eddd5a7a1cde251e54ccfdd5" # 32 Bytes (256 bits) time = 1231469744 # 4 Bytes (32 bits) bits = 486604799 # 4 Bytes (32 bits) nonce = 1639830024 # 4 Bytes (32 bits) def deal_str(big_endian): return bytes.fromhex(big_endian)[::-1] # [::-1] will reverse the bytes to little-endian def deal_int(n): # < means "Little-endian" # L means "unsigned long" return struct.pack("<L", n) header_bin = deal_int(ver) + deal_str(prev_block) + deal_str(mrkl_root) + deal_int(time) + deal_int(bits) + deal_int(nonce) hash = sha256(sha256(header_bin).digest()).digest() cur_block = hash[::-1].hex() #reverse back to big-endian, which is block hash. print(cur_block) # block hash of block height 2: 000000006a625f06636b8bb6ac7b960a8d03705d1ace08b1a19da3fdcc99ddbd