Skip to content

Instantly share code, notes, and snippets.

@AveragePythonEnjoyer29
Created January 1, 2023 20:16
Show Gist options
  • Save AveragePythonEnjoyer29/0c0f4d49a110af5ef4f4f12d4e589f4a to your computer and use it in GitHub Desktop.
Save AveragePythonEnjoyer29/0c0f4d49a110af5ef4f4f12d4e589f4a to your computer and use it in GitHub Desktop.
Simple proof-of-work example in Python 3
import time, hashlib
# max nonces should scale with
# the difficulty, haven't calculated
# how to do that tho
max_nonces = 500000
difficulty = 4
pattern = '0' * difficulty
payload = f't={time.time()}&m=This is an example message!'
check_hash = b''
print(f'[Task] Solve hash with difficulty {difficulty}')
# creates a SHA512 hash based
# off the payload and the given
# nonce
def mhash(nonce) -> str:
return hashlib.sha512(f'{payload}&n={nonce}'.encode()).hexdigest()
# while the nonce is lower
# than the max nonces counter
# try and guess the hash
nonce = 0
while nonce < max_nonces:
check_hash = mhash(nonce) # create the hash
print(f'[Miner/Client] Hash: {check_hash} | Pattern: {pattern} | Nonce: {nonce}')
if check_hash.startswith(pattern): # check if it matches the pattern
break
nonce +=1
print(f'[Miner/Client] Finished! Hash: {check_hash}, Nonce: {nonce}')
print(f'\nChecking...')
if mhash(nonce).startswith(pattern): # check if the hash matches the pattern
print('PoW completed!')
else:
print('Failed!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment