"""
import datetime as date
import hashlib as hasher
import random
# Users of the blockchain
users = ["Alice", "Bob", "Charlie", "You"]
class Transaction:
def __init__(self, sender, receiver, amount):
self.sender = sender
self.receiver = receiver
self.amount = amount
class Block:
def __init__(self, index, timestamp, data, previous_hash, nonce):
self.index = index
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.nonce = nonce
self.hash = self.hash_block()
def hash_block(self):
sha = hasher.sha256()
sha.update((str(self.index) + str(self.timestamp) + str(self.data) + str(self.nonce) + str(self.previous_hash)).encode())
return sha.hexdigest()
def create_genesis_block():
return Block(0, date.datetime.now(), "Genesis Block", "0", 1)
def next_block(last_block):
this_index = last_block.index + 1
this_timestamp = date.datetime.now()
rnd = random.Random()
user_transactions = users.copy()
sender = rnd.choice(user_transactions)
user_transactions.remove(sender)
receiver = rnd.choice(user_transactions)
amount = rnd.randint(1, 100)
this_data = Transaction(sender, receiver, amount)
previous_hash = last_block.hash
this_nonce = proof_of_work(last_block.nonce, this_index, this_timestamp, this_data, previous_hash)
return Block(this_index, this_timestamp, this_data, previous_hash, this_nonce)
def proof_of_work(last_nonce, this_index, this_timestamp, this_data, previous_hash):
incrementor = 0
block = Block(this_index, this_timestamp, this_data, previous_hash, incrementor)
while str(block.hash)[:4] != '0000':
incrementor += 1
block = Block(this_index, this_timestamp, this_data, previous_hash, incrementor)
return incrementor
# Initialize the blockchain
blockchain = [create_genesis_block()]
previous_block = blockchain[0]
# Generate a number of blocks with fake transactions
num_of_blocks_to_add = 100
for i in range(num_of_blocks_to_add):
block_to_add = next_block(previous_block)
blockchain.append(block_to_add)
previous_block = block_to_add
# Calculate the balance of each user
balances = {user: 0 for user in users}
for block in blockchain:
if block.index == 0:
continue
transaction = block.data
balances[transaction.sender] -= transaction.amount
balances[transaction.receiver] += transaction.amount
# Display the balance of each user
for user, balance in balances.items():
print(f"{user}'s balance: {balance}")
Comments