import hashlib
import json
from time import time
from typing import List, Any
class Block:
"""
Represents a single block in the blockchain.
"""
def __init__(self, index: int, previous_hash: str, timestamp: float, data: Any, hash: str = None):
self.index = index
self.previous_hash = previous_hash
self.timestamp = timestamp
self.data = data
self.hash = hash or self._calculate_hash()
def _calculate_hash(self) -> str:
"""
Calculates the SHA-256 hash of the block using its attributes.
"""
block_string = json.dumps({
"index": self.index,
"previous_hash": self.previous_hash,
"timestamp": self.timestamp,
"data": self.data
}, sort_keys=True)
return hashlib.sha256(block_string.encode()).hexdigest()
def __repr__(self) -> str:
return (f"Block({self.index}, hash={self.hash[:16]}..., "
f"prev_hash={self.previous_hash[:16]}..., "
f"data={self.data}, timestamp={self.timestamp})")
class Blockchain:
"""
A simple blockchain implementation.
"""
def __init__(self):
self.chain: List[Block] = [self._create_genesis_block()]
def _create_genesis_block(self) -> Block:
"""
Creates the first (genesis) block in the chain.
"""
return Block(0, "0", time(), "Genesis Block")
def get_latest_block(self) -> Block:
"""
Returns the last block in the chain.
"""
return self.chain[-1]
def add_block(self, data: Any) -> None:
"""
Adds a new block to the chain.
"""
index = len(self.chain)
previous_hash = self.get_latest_block().hash
timestamp = time()
new_block = Block(index, previous_hash, timestamp, data)
self.chain.append(new_block)
def is_chain_valid(self) -> bool:
"""
Validates the blockchain integrity:
- Each block's hash is correct.
- Each block's previous_hash matches the previous block's hash.
"""
for i in range(1, len(self.chain)):
current = self.chain[i]
previous = self.chain[i-1]
# Check if current block's hash is valid
if current.hash != current._calculate_hash():
return False
# Check if previous_hash links correctly
if current.previous_hash != previous.hash:
return False
return True
def print_chain(self) -> None:
"""
Prints the entire blockchain.
"""
print("=== BLOCKCHAIN ===\n")
for block in self.chain:
print(f"Index: {block.index}")
print(f"Hash: {block.hash}")
print(f"Previous Hash: {block.previous_hash}")
print(f"Timestamp: {block.timestamp}")
print(f"Data: {block.data}")
print("-" * 50)
# Example usage and testing
if __name__ == "__main__":
# Create a new blockchain
mycoin = Blockchain()
# Add some blocks
mycoin.add_block("Alice sends 10 coins to Bob")
mycoin.add_block("Bob sends 5 coins to Charlie")
mycoin.add_block("Charlie mines a new block")
# Print the chain
mycoin.print_chain()
# Validate the chain
print(f"\nIs chain valid? {mycoin.is_chain_valid()}")
# Tamper with a block to test validation
print("\n--- Tampering with block 1 ---")
mycoin.chain[1].data = "Hacked data!"
print(f"Is chain still valid? {mycoin.is_chain_valid()}")
How to Run
Copy and paste the code into a file, e.g., simple_blockchain.py.
Run it with python simple_blockchain.py.
Features
Genesis Block: Automatically created.
Hashing: SHA-256 for block integrity.
Chain Linking: Each block references the previous hash.
Validation: Detects tampering.
Extensible: Easy to add proof-of-work, transactions, etc.
This is a minimal, educational implementation. Real blockchains include consensus, networking, and more security! 🚀