Skip to content

Instantly share code, notes, and snippets.

@jakekara
Created September 16, 2018 14:48
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 jakekara/b4025eb68bc616c472cda90e3784bd2c to your computer and use it in GitHub Desktop.
Save jakekara/b4025eb68bc616c472cda90e3784bd2c to your computer and use it in GitHub Desktop.
Demo of how blockchain mining works, and why it gets harder and harder
"""
usage: python mine_demo.py ZEROES VALUE_TO_HASH
Find a nonce that, when concatenated with VALUE_TO_HASH, results in an
SHA256 hexdigest that starts with ZEROES number of zeroes.
output: NONCE HASH
Where NONCE is the solution that resulted in a HASH that the required
number of zeroes at the start.
The more zeroes required, the harder it is to find the solution through
brute force.
Example usage:
$ python mine_demo.py 6 one-hundreds
10849447 000000379be85754d2fca6c562c4a62b8546e7d2ec53eeaa0db656765bc4b662
"""
from hashlib import sha256
from sys import argv
def hash_value(val):
""" Just turn any input into 256 bits of gibberish, AKA hash it.
The important thing to know is that the output for a hash
will be unique for every input.
"""
return sha256(val.encode()).hexdigest()
def test_hash(hash_value, zcount):
""" Test whether a string starts with zcount zero (0) characters. """
while zcount >= 0:
if hash_value[zcount] != "0":
return False
zcount -= 1
return True
def test(nonce, something, zcount=0):
""" Test whether the hash of a nonce plus some value (the previous block in
bitcoin mining) results in a hash that starts with zcount zero (0)
characters. """
result = hash_value(str(nonce) + something)
if test_hash(result, zcount):
return result
return None
def main():
zcount = int(argv[1]) - 1
msg = str(argv[2])
nonce = 0
while True:
solution = test(nonce, msg, zcount=zcount)
if solution is not None:
print nonce, solution
break
nonce += 1
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment