01
Write a simple Proof of Work loop in Python with a difficulty setting.
Show answer
The miner increments the nonce until the hash starts with the required number of zero hex digits.
import hashlib
def mine(data, difficulty=4):
prefix = '0' * difficulty
nonce = 0
while True:
h = hashlib.sha256(f'{data}{nonce}'.encode()).hexdigest()
if h.startswith(prefix):
return nonce, h
nonce += 1
print(mine('block-1: A pays B 5'))
Each extra zero makes mining about 16 times harder, while verifying still needs one hash.