4

Exactly which items from a block are included in the data that is hashed to produce the block hash?

2

In Mastering Bitcoin there is this diagram which shows the data included:

Block header and hashing

Previous Block Header Hash
Timestamp
Difficulty
Nonce
Merkle Root

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.


Related:

0

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:

  1. Version
  2. Previous Block Header Hash
  3. Merkle root
  4. Timestamp
  5. Bits (Difficulty)
  6. Nonce

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.