52 lines
1.8 KiB
Python
52 lines
1.8 KiB
Python
# imports
|
|
from hashlib import sha256
|
|
from random import randint
|
|
|
|
# Constants
|
|
MAX_NONCE = 1000000 # Limit for the simulation
|
|
DIFFICULTY = 3 # How many lead zeros has the hash
|
|
|
|
def random_with_N_digits(n):
|
|
"""Generate a random string with n chars."""
|
|
range_start = 10 ** (n - 1)
|
|
range_end = (10 ** n) - 1
|
|
return randint(range_start, range_end)
|
|
|
|
def generate_transactions(count=3):
|
|
"""Create the list of transactions"""
|
|
transactions = []
|
|
for _ in range(count):
|
|
sender = random_with_N_digits(5)
|
|
receiver = random_with_N_digits(5)
|
|
bitcoins = random_with_N_digits(2)
|
|
transactions.append(f"{sender}->{receiver}->{bitcoins}")
|
|
return "; ".join(transactions)
|
|
|
|
def SHA256(text):
|
|
"""Creates a SHA256-Hash for the text."""
|
|
return sha256(text.encode("ascii")).hexdigest()
|
|
|
|
def mine(block_number, transactions, previous_hash, prefix_zeros):
|
|
"""Simulates the mining of a block."""
|
|
prefix_str = '0' * prefix_zeros
|
|
for nonce in range(MAX_NONCE):
|
|
text = f"{block_number}{transactions}{previous_hash}{nonce}"
|
|
new_hash = SHA256(text)
|
|
if new_hash.startswith(prefix_str):
|
|
print(f"Block found! Nonce: {nonce}, Hash: {new_hash}")
|
|
return new_hash
|
|
raise RuntimeError(f"Mining not succesful after {MAX_NONCE} tries.")
|
|
|
|
if __name__ == '__main__':
|
|
block_number = 1
|
|
previous_hash = "0" * 64 # Star Value for the first block
|
|
num_blocks_to_mine = 10
|
|
|
|
for _ in range(num_blocks_to_mine):
|
|
transactions = generate_transactions()
|
|
print(f"Mining Block {block_number} with transactions: {transactions}")
|
|
new_hash = mine(block_number, transactions, previous_hash, DIFFICULTY)
|
|
previous_hash = new_hash # Hash wird zum vorherigen Hash für den nächsten Block
|
|
block_number += 1
|
|
print(f"New Hash: {new_hash}\n")
|