|
1 | 1 | import hashlib
|
2 | 2 | import time
|
3 | 3 |
|
| 4 | + |
4 | 5 | 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 | 6 | """
|
21 |
| - prefix = '0' * difficulty |
22 |
| - nonce = 0 |
23 |
| - start = time.time() # Timing starts |
| 7 | + Simulates a Proof of Work mining process. |
| 8 | +
|
| 9 | + The miner must find a nonce such that the hash of the nonce starts |
| 10 | + with a specific number of leading zeros (difficulty) |
| 11 | +
|
| 12 | + Args: |
| 13 | + difficulty (int): The number of leading zeros required in the hash. |
| 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() # Timing starts |
24 | 25 |
|
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 |
| 26 | + while True: |
| 27 | + hash_result = hashlib.sha256(f"{nonce}".encode()).hexdigest() |
| 28 | + if hash_result.startswith(prefix): |
| 29 | + end = time.time() # Timing ends |
| 30 | + print(f"Time taken: {end - start:.2f}s") # Print time taken |
| 31 | + return nonce |
| 32 | + nonce += 1 |
0 commit comments