Skip to content

Commit 374cbc2

Browse files
authored
Created proof_of_work.py
1 parent e14f6d5 commit 374cbc2

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

blockchain/proof_of_work.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import hashlib
2+
import time
3+
4+
def proof_of_work(difficulty: int) -> int:
5+
"""
6+
Simulates a Proof of Work mining process.
7+
8+
The miner must find a nonce such that the hash of the nonce starts
9+
with a specific number of leading zeros (difficulty).
10+
11+
Args:
12+
difficulty (int): The number of leading zeros required in the hash.
13+
14+
Returns:
15+
int: The nonce value that solves the puzzle.
16+
17+
Example:
18+
>>> result = proof_of_work(2) # Difficulty of 2 should be fast
19+
>>> isinstance(result, int)
20+
True
21+
"""
22+
prefix = '0' * difficulty
23+
nonce = 0
24+
start = time.time()
25+
26+
while True:
27+
hash_result = hashlib.sha256(f"{nonce}".encode()).hexdigest()
28+
if hash_result.startswith(prefix):
29+
end = time.time()
30+
print(f"Nonce: {nonce}, Hash: {hash_result}, Time: {end - start:.2f}s")
31+
return nonce
32+
nonce += 1

0 commit comments

Comments
 (0)