Python/blockchain/proof_of_work.py

34 lines
930 B
Python
Raw Normal View History

2024-10-10 16:20:01 +00:00
import hashlib
import time
2024-10-10 16:20:01 +00:00
def proof_of_work(difficulty: int) -> int:
"""
Simulates a Proof of Work mining process.
The miner must find a nonce such that the hash of the nonce starts
2024-10-10 16:20:01 +00:00
with a specific number of leading zeros (difficulty).
Args:
difficulty (int): The number of leading zeros required in the hash.
Returns:
int: The nonce value that solves the puzzle.
Example:
>>> result = proof_of_work(2) # Difficulty of 2 should be fast
>>> isinstance(result, int)
True
"""
prefix = "0" * difficulty
2024-10-10 16:20:01 +00:00
nonce = 0
2024-10-10 16:31:48 +00:00
start = time.time() # Timing starts
2024-10-10 16:20:01 +00:00
while True:
hash_result = hashlib.sha256(f"{nonce}".encode()).hexdigest()
if hash_result.startswith(prefix):
2024-10-10 16:31:48 +00:00
end = time.time() # Timing ends
print(f"Time taken: {end - start:.2f}s") # Print time taken
2024-10-10 16:20:01 +00:00
return nonce
nonce += 1