Skip to content

Instantly share code, notes, and snippets.

@RGGH
Last active March 3, 2024 20:08
Show Gist options
  • Save RGGH/a96764152960eadc73f145944d5d3d06 to your computer and use it in GitHub Desktop.
Save RGGH/a96764152960eadc73f145944d5d3d06 to your computer and use it in GitHub Desktop.
hash checker for Bitcoin
#!/usr/bin/env python3
''' python3.10 hash_check.py -f inp.json '''
from binascii import unhexlify
from hashlib import sha256
import json
import sys
import urllib.request
# Convert into little endian format
def little_endian(string):
splited = [str(string)[i:i + 2] for i in range(0, len(str(string)), 2)]
splited.reverse()
return "".join(splited)
help_message = 'Please give arguments to read the block data\nTo read the block as a json file\n-f <fileName>\nTo read the block from a url as a json body\n-i <url>\n'
if len(sys.argv) < 3:
print(help_message)
sys.exit()
elif sys.argv[1] == '-f':
with open(sys.argv[2], 'r') as file:
response = json.load(file)
elif sys.argv[1] == '-i':
with urllib.request.urlopen(sys.argv[2]) as url:
response = json.loads(url.read().decode())
version = '01000000'
little_endian_previous_hash = little_endian(response['prev_block'])
little_endian_merkle_root = little_endian(response['mrkl_root'])
little_endian_time = little_endian(hex(response['time'])[2:])
little_endian_difficulty_bits = little_endian(hex(response['bits'])[2:])
little_endian_nonce = little_endian(hex(response['nonce'])[2:])
# Append
header = version + little_endian_previous_hash + little_endian_merkle_root + little_endian_time + little_endian_difficulty_bits + little_endian_nonce
header = unhexlify(header)
# Sent hash by the miner
response_hash = little_endian(response['hash'])
# Calculated hash
calculated_hash = sha256(sha256(header).digest()).hexdigest()
# Verify the hash is smaller than the target
solved = 'Hash is smaller than the target' if response_hash <= little_endian_difficulty_bits else 'Hash is larger than the target'
print(solved)
# Equality of the calculated and received hashes
state = 'Hash of the block is acceptable.' if response_hash == calculated_hash else 'Hash of the block is not acceptable.'
print(state)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment