Skip to content

Commit cd42352

Browse files
authored
Added proof_of_work.py
1 parent 8ad7381 commit cd42352

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

blockchain/proof_of_work.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
Returns:
14+
int: The nonce value that solves the puzzle.
15+
16+
Example:
17+
>>> result = proof_of_work(2) # Difficulty of 2 should be fast
18+
>>> isinstance(result, int)
19+
True
20+
"""
21+
prefix = '0' * difficulty
22+
nonce = 0
23+
start = time.time() # Timing starts
24+
25+
while True:
26+
hash_result = hashlib.sha256(f"{nonce}".encode()).hexdigest()
27+
if hash_result.startswith(prefix):
28+
end = time.time() # Timing ends
29+
print(f"Time taken: {end - start:.2f}s") # Print time taken
30+
return nonce
31+
nonce += 1

0 commit comments

Comments
 (0)