Skip to content

Instantly share code, notes, and snippets.

@omgbbqhaxx
Forked from turunut/minePYTHON36.py
Created October 22, 2019 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omgbbqhaxx/e916dfc99df80823c3438130730d8064 to your computer and use it in GitHub Desktop.
Save omgbbqhaxx/e916dfc99df80823c3438130730d8064 to your computer and use it in GitHub Desktop.
Example of how a Bitcoin block is mined by finding a successful nonce
import hashlib, struct, codecs
ver = 2
prev_block = "000000000000000117c80378b8da0e33559b5997f2ad55e2f7d18ec1975b9717"
mrkl_root = "871714dcbae6c8193a2bb9b2a69fe1c0440399f38d94b3a0f1b447275a29978a"
time_ = 0x53058b35 # 2014-02-20 04:57:25
bits = 0x19015f53
# https://en.bitcoin.it/wiki/Difficulty
exp = bits >> 24
mant = bits & 0xffffff
target_hexstr = '%064x' % (mant * (1<<(8*(exp - 3))))
target_str = codecs.decode(target_hexstr, "hex")
nonce = 0
while nonce < 0x100000000:
header = ( struct.pack("<L", ver) + codecs.decode(prev_block, "hex")[::-1] +
codecs.decode(mrkl_root, "hex")[::-1] + struct.pack("<LLL", time_, bits, nonce))
hash = hashlib.sha256(hashlib.sha256(header).digest()).digest()
print( nonce, codecs.encode(hash[::-1], "hex"))
if hash[::-1] < target_str:
print('success')
break
nonce += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment