Skip to content

Commit cccf2c7

Browse files
committed
blockchain: implement simple_proof_of_work.py
1 parent 678dedb commit cccf2c7

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

blockchain/simple_proof_of_work.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""
2+
Proof of Work (PoW) implementation.
3+
This algorithm is used in blockchain technology
4+
to reach consensus and secure the network
5+
"""
6+
7+
import hashlib
8+
9+
10+
def proof_of_work(
11+
block_number: int, transactions: str, previous_hash: str, difficulty: int
12+
) -> tuple[int, str]:
13+
"""
14+
Finds a nonce such that the SHA-256 hash of the block starts with
15+
a specific number of zeros (difficulty).
16+
17+
>>> proof_of_work(1, "test", "abc", 1)[1].startswith("0")
18+
True
19+
>>> # Consistency check: same input must produce same output
20+
>>> res1 = proof_of_work(1, "data", "hash", 2)
21+
>>> res2 = proof_of_work(1, "data", "hash", 2)
22+
>>> res1 == res2
23+
True
24+
>>> # Difficulty 0 should return nonce 0 immediately
25+
>>> proof_of_work(1, "data", "hash", 0)[0]
26+
0
27+
"""
28+
if difficulty < 0:
29+
raise ValueError("difficulty must be a non-negative integer")
30+
31+
prefix = "0" * difficulty
32+
nonce = 0
33+
34+
while True:
35+
# Create a single string representing all block data
36+
text = f"{block_number}{transactions}{previous_hash}{nonce}"
37+
38+
# Calculate the SHA-256 hash
39+
current_hash = hashlib.sha256(text.encode()).hexdigest()
40+
41+
# Check if the hash meets the difficulty requirement
42+
if current_hash.startswith(prefix):
43+
return nonce, current_hash
44+
45+
nonce += 1
46+
47+
48+
if __name__ == "__main__":
49+
import doctest
50+
51+
doctest.testmod()
52+
53+
# Example usage:
54+
example_tx = "Alice sends 1 BTC to Bob"
55+
prev_h = "00000abcdef1234567890"
56+
diff = 4
57+
58+
print(f"Mining block... (Difficulty: {diff})")
59+
nonce, hash_found = proof_of_work(1, example_tx, prev_h, diff)
60+
61+
print(f"Success! Nonce: {nonce}")
62+
print(f"Hash: {hash_found}")

0 commit comments

Comments
 (0)