Untitled
unknown
plain_text
22 days ago
1.7 kB
1
Indexable
Never
import hashlib import json class Block: def __init__(self, timestamp, previous_hash, transactions): self.timestamp = timestamp self.previous_hash = previous_hash self.transactions = transactions self.hash = hashlib.sha256(json.dumps(self.__dict__).encode('utf-8')).hexdigest() class Transaction: def __init__(self, sender, recipient, amount): self.sender = sender self.recipient = recipient self.amount = amount class Blockchain: def __init__(self): self.chain = [] self.create_genesis_block() def create_genesis_block(self): genesis_block = Block(timestamp='2023-11-15', previous_hash='0', transactions=[]) self.chain.append(genesis_block) def add_block(self, block): if block.previous_hash != self.chain[-1].hash: raise ValueError('Invalid previous hash') self.chain.append(block) def get_latest_block(self): return self.chain[-1] def is_valid_block(self, block): if block.hash != hashlib.sha256(json.dumps(block.__dict__).encode('utf-8')).hexdigest(): return False if block.previous_hash != self.get_latest_block().hash: return False return True blockchain = Blockchain() # Create transactions transaction1 = Transaction(sender='Alice', recipient='Bob', amount=10) transaction2 = Transaction(sender='Bob', recipient='Charlie', amount=5) # Create a block new_block = Block(timestamp='2023-11-16', previous_hash=blockchain.get_latest_block().hash, transactions=[transaction1, transaction2]) # Add the block to the blockchain blockchain.add_block(new_block) print(json.dumps(blockchain.chain, indent=4))
Leave a Comment