Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions blockchain/simple_proof_of_work.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import hashlib


def proof_of_work(

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file blockchain/simple_proof_of_work.py, please provide doctest for the function proof_of_work

block_number: int, transactions: str, previous_hash: str, difficulty: int
) -> tuple[int, str]:
"""
Finds a nonce such that the hash of the block
starts with a specific number of zeros
"""
prefix = "0" * difficulty
nonce = 0

while True:
# Create a single string representing all block data
text = str(block_number) + transactions + previous_hash + str(nonce)

# Calculate the SHA-256
current_hash = hashlib.sha256(text.encode()).hexdigest()

# Check if the hash meets the difficulty requirement
if current_hash.startswith(prefix):
return nonce, current_hash

nonce += 1


if __name__ == "__main__":
# Example usage:
example_tx = "Alice sends 1 BTC to Bob"
prev_h = "00000abcdef1234567890"
diff = 5 # Increase to see get much slower

print(f"Mining block... (Difficulty: {diff})")
nonce, hash_found = proof_of_work(1, example_tx, prev_h, diff)

print(f"Success! Nonce: {nonce}")
print(f"Hash: {hash_found}")