Skip to content

Commit f7236cc

Browse files
committed
blockchain/simple_proof_of_work.py added
1 parent 8106aea commit f7236cc

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

blockchain/simple_proof_of_work.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import hashlib
2+
3+
def proof_of_work(block_number: int, transactions: str, previous_hash: str,
4+
difficulty: int) -> tuple[int, str]:
5+
"""
6+
Finds a nonce such that the hash of the block
7+
starts with a specfic number of zeros
8+
"""
9+
prefix = '0' * difficulty
10+
nonce = 0
11+
12+
while True:
13+
# Create a single string representing all block data
14+
text = str(block_number) + transactions + previous_hash + str(nonce)
15+
16+
# Calculate the SHA-256
17+
current_hash = hashlib.sha256(text.encode()).hexdigest()
18+
19+
# Check if the hash meets the difficulty requirement
20+
if current_hash.startswith(prefix):
21+
return nonce, current_hash
22+
23+
nonce += 1
24+
25+
if __name__ == "__main__":
26+
# Example usage:
27+
example_tx = "Alice sends 1 BTC to Bob"
28+
prev_h = "00000abcdef1234567890"
29+
diff = 5 # Increase to see get much slower
30+
31+
print(f"Mining block... (Difficulty: {diff})")
32+
nonce,hash_found = proof_of_work(1, example_tx, prev_h, diff)
33+
34+
print(f"Success! Nonce: {nonce}")
35+
print(f"Hash: {hash_found}")

0 commit comments

Comments
 (0)