Skip to content

Instantly share code, notes, and snippets.

@wisammechano
Forked from ironpark/block_hash.py
Created June 29, 2021 18:11
Show Gist options
  • Select an option

  • Save wisammechano/05286b0906113fc8c26cc74d179b9e04 to your computer and use it in GitHub Desktop.

Select an option

Save wisammechano/05286b0906113fc8c26cc74d179b9e04 to your computer and use it in GitHub Desktop.

Revisions

  1. @ironpark ironpark created this gist Nov 23, 2017.
    61 changes: 61 additions & 0 deletions block_hash.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,61 @@
    import requests
    import hashlib
    import struct


    def load_block_data(block_hash):
    r = requests.get('https://blockchain.info/ko/rawblock/' + block_hash)
    return r.json()


    def block_hash(version: int,
    prevblock,
    merkle_root,
    time: int,
    bits: int,
    nonce: int):

    prevblock_little = bytearray.fromhex(prevblock)[::-1]
    merkle_root_little = bytearray.fromhex(merkle_root)[::-1]

    # pack binary little endian
    header_bin = struct.pack(
    # < : little endian
    # i : signed int (32 bit) - +
    # I : unsigned int (32 bit) +
    # 32s : 32 byte (char)

    # <i32s32sIII = little endian | int | byte[32] | byte[32] | unsigned int | unsigned int | unsigned int
    '<i32s32sIII',
    version,
    prevblock_little, # little -> big
    merkle_root_little, # little -> big
    time,
    bits,
    nonce,
    )
    # double hash
    h = hashlib.sha256(
    hashlib.sha256(header_bin).digest()
    ).digest()

    return h


    # load block data from blockchain info
    block = load_block_data("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f")

    # calculate block hash
    hashed_block_header = block_hash(
    version=block['ver'],
    prevblock=block['prev_block'],
    merkle_root=block['mrkl_root'],
    time=block['time'],
    bits=block['bits'],
    nonce=block['nonce'],
    )

    # block hash to hex string
    hex = hashed_block_header[::-1].hex()

    print(hex)