Creating a highly complex Python program involves integrating multiple advanced concepts, such as object-oriented programming, cryptography, networking, concurrency, and data management. Below is a comprehensive implementation of a simplified blockchain system. This program includes features like block creation, proof-of-work consensus, transaction handling, and chain validation. Additionally, it sets up a basic peer-to-peer network using Flask for distributed consensus.
Please Note: This example is for educational purposes and does not cover all security and scalability aspects required for a production-grade blockchain system.
Comprehensive Blockchain Implementation in Python
Prerequisites
Before running the program, ensure you have the following Python packages installed:
pip install Flask
pip install requests
Program Structure
- Block Class: Represents each block in the blockchain.
- Blockchain Class: Manages the chain, handles new transactions, mining, and validation.
- Flask App: Sets up RESTful APIs to interact with the blockchain network.
- Node Registration: Allows multiple nodes to register and achieve consensus.
Complete Code
import hashlib
import json
import time
from time import sleep
from uuid import uuid4
from flask import Flask, jsonify, request
import requests
from urllib.parse import urlparse
from threading import Thread
class Block:
def __init__(self, index, timestamp, transactions, proof, previous_hash):
"""
Initialize a new block in the blockchain.
:param index: <int> Position of the block in the chain
:param timestamp: <float> Time of creation
:param transactions: <list> List of transactions
:param proof: <int> Proof of work number
:param previous_hash: <str> Hash of the previous block
"""
self.index = index
self.timestamp = timestamp
self.transactions = transactions
self.proof = proof
self.previous_hash = previous_hash
def to_dict(self):
"""
Converts block data to a dictionary.
:return: <dict> Block data
"""
return {
'index': self.index,
'timestamp': self.timestamp,
'transactions': self.transactions,
'proof': self.proof,
'previous_hash': self.previous_hash,
}
class Blockchain:
def __init__(self):
"""
Initialize the blockchain with the genesis block and setup necessary variables.
"""
self.chain = []
self.transactions = []
self.nodes = set()
# Create the genesis block
self.create_block(proof=1, previous_hash='0')
def create_block(self, proof, previous_hash):
"""
Creates a new block and adds it to the chain.
:param proof: <int> Proof of work
:param previous_hash: <str> Hash of previous block
:return: <Block> New block
"""
block = Block(
index=len(self.chain) + 1,
timestamp=time.time(),
transactions=self.transactions.copy(),
proof=proof,
previous_hash=previous_hash,
)
self.transactions = []
self.chain.append(block)
return block
def get_previous_block(self):
"""
Retrieves the last block in the chain.
:return: <Block> Last block
"""
return self.chain[-1]
def proof_of_work(self, previous_proof):
"""
Simple Proof of Work algorithm:
- Find a number p' such that hash(pp') contains leading 4 zeros
- p is the previous proof
:param previous_proof: <int>
:return: <int>
"""
new_proof = 1
check_proof = False
while not check_proof:
# Perform hash computation
hash_operation = hashlib.sha256(str(new_proof**2 - previous_proof**2).encode()).hexdigest()
# Check if hash has 4 leading zeros
if hash_operation[:4] == '0000':
check_proof = True
else:
new_proof += 1
return new_proof
def hash(self, block):
"""
Creates a SHA-256 hash of a block.
:param block: <Block>
:return: <str>
"""
# Ensure dictionary is ordered to prevent inconsistent hashes
block_string = json.dumps(block.to_dict(), sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
def is_chain_valid(self, chain):
"""
Validates the entire blockchain.
:param chain: <list> Blockchain
:return: <bool> True if valid, False otherwise
"""
previous_block = chain[0]
current_index = 1
while current_index < len(chain):
block = chain[current_index]
print(f'Validating block {block.index}...')
# Check if previous_hash is correct
if block.previous_hash != self.hash(previous_block):
print(f'Block {block.index}: Previous hash does not match.')
return False
# Check if the Proof of Work is correct
previous_proof = previous_block.proof
proof = block.proof
hash_operation = hashlib.sha256(str(proof**2 - previous_proof**2).encode()).hexdigest()
if hash_operation[:4] != '0000':
print(f'Block {block.index}: Invalid proof of work.')
return False
previous_block = block
current_index += 1
return True
def add_transaction(self, sender, receiver, amount):
"""
Adds a new transaction to the list of transactions.
:param sender: <str>
:param receiver: <str>
:param amount: <float>
:return: <int> Index of block that will hold this transaction
"""
self.transactions.append({
'sender': sender,
'receiver': receiver,
'amount': amount,
})
return self.get_previous_block().index + 1
def add_node(self, address):
"""
Adds a new node to the list of nodes.
:param address: <str> Address of node. Eg. 'http://192.168.0.5:5000'
"""
parsed_url = urlparse(address)
self.nodes.add(parsed_url.netloc)
def replace_chain(self):
"""
Consensus Algorithm:
- Replace our chain with the longest one in the network.
:return: <bool> True if chain was replaced, False otherwise
"""
network = self.nodes
longest_chain = None
max_length = len(self.chain)
for node in network:
try:
response = requests.get(f'http://{node}/get_chain')
if response.status_code == 200:
length = response.json()['length']
chain_data = response.json()['chain']
# Reconstruct the chain
chain = []
for block_data in chain_data:
block = Block(
index=block_data['index'],
timestamp=block_data['timestamp'],
transactions=block_data['transactions'],
proof=block_data['proof'],
previous_hash=block_data['previous_hash'],
)
chain.append(block)
if length > max_length and self.is_chain_valid(chain):
max_length = length
longest_chain = chain
except requests.exceptions.RequestException as e:
print(f'Error connecting to node {node}: {e}')
if longest_chain:
self.chain = longest_chain
return True
return False
# Instantiate the Flask app
app = Flask(__name__)
# Generate a unique address for this node
node_address = str(uuid4()).replace('-', '')
# Instantiate the Blockchain
blockchain = Blockchain()
@app.route('/mine_block', methods=['GET'])
def mine_block():
"""
Endpoint to mine a new block.
"""
previous_block = blockchain.get_previous_block()
previous_proof = previous_block.proof
proof = blockchain.proof_of_work(previous_proof)
previous_hash = blockchain.hash(previous_block)
blockchain.add_transaction(sender=node_address, receiver='Alice', amount=1)
block = blockchain.create_block(proof, previous_hash)
response = {
'message': 'Congratulations, you just mined a block!',
'index': block.index,
'timestamp': block.timestamp,
'transactions': block.transactions,
'proof': block.proof,
'previous_hash': block.previous_hash,
}
return jsonify(response), 200
@app.route('/get_chain', methods=['GET'])
def get_chain():
"""
Endpoint to retrieve the full blockchain.
"""
chain_data = []
for block in blockchain.chain:
chain_data.append(block.to_dict())
response = {
'chain': chain_data,
'length': len(chain_data),
}
return jsonify(response), 200
@app.route('/is_valid', methods=['GET'])
def is_valid():
"""
Endpoint to check if the blockchain is valid.
"""
is_valid_chain = blockchain.is_chain_valid(blockchain.chain)
if is_valid_chain:
response = {'message': 'All good. The Blockchain is valid.'}
else:
response = {'message': 'Houston, we have a problem. The Blockchain is not valid.'}
return jsonify(response), 200
@app.route('/add_transaction', methods=['POST'])
def add_transaction():
"""
Endpoint to add a new transaction to the blockchain.
"""
json_data = request.get_json()
transaction_keys = ['sender', 'receiver', 'amount']
if not all(key in json_data for key in transaction_keys):
return 'Some elements of the transaction are missing', 400
index = blockchain.add_transaction(
sender=json_data['sender'],
receiver=json_data['receiver'],
amount=json_data['amount'],
)
response = {'message': f'This transaction will be added to Block {index}'}
return jsonify(response), 201
@app.route('/connect_node', methods=['POST'])
def connect_node():
"""
Endpoint to connect new nodes to the network.
"""
json_data = request.get_json()
nodes = json_data.get('nodes')
if nodes is None:
return "No node", 400
for node in nodes:
blockchain.add_node(node)
response = {
'message': 'All the nodes are now connected. The Blockchain now contains the following nodes:',
'total_nodes': list(blockchain.nodes),
}
return jsonify(response), 201
@app.route('/replace_chain', methods=['GET'])
def replace_chain():
"""
Endpoint to replace the chain with the longest one in the network.
"""
is_replaced = blockchain.replace_chain()
if is_replaced:
response = {
'message': 'The nodes had different chains so the chain was replaced by the longest one.',
'new_chain': [block.to_dict() for block in blockchain.chain],
}
else:
response = {
'message': 'All good. The chain is the largest one.',
'actual_chain': [block.to_dict() for block in blockchain.chain],
}
return jsonify(response), 200
def run_flask():
"""
Runs the Flask app.
"""
app.run(host='0.0.0.0', port=5000)
if __name__ == '__main__':
# Run the Flask app in a separate thread to allow interaction
flask_thread = Thread(target=run_flask)
flask_thread.start()
# Simple command-line interface for interacting with the blockchain
while True:
print("\n--- Blockchain Menu ---")
print("1. Mine a new block")
print("2. Add a new transaction")
print("3. Get the full blockchain")
print("4. Check if the blockchain is valid")
print("5. Connect to new nodes")
print("6. Replace the chain with the longest one")
print("7. Exit")
choice = input("Enter your choice: ")
if choice == '1':
try:
response = requests.get('http://127.0.0.1:5000/mine_block')
print(response.json())
except requests.exceptions.RequestException as e:
print(f'Error: {e}')
elif choice == '2':
sender = input("Enter sender address: ")
receiver = input("Enter receiver address: ")
amount = float(input("Enter amount: "))
transaction = {
'sender': sender,
'receiver': receiver,
'amount': amount,
}
try:
response = requests.post('http://127.0.0.1:5000/add_transaction', json=transaction)
print(response.json())
except requests.exceptions.RequestException as e:
print(f'Error: {e}')
elif choice == '3':
try:
response = requests.get('http://127.0.0.1:5000/get_chain')
chain = response.json()['chain']
for block in chain:
print(json.dumps(block, indent=4))
except requests.exceptions.RequestException as e:
print(f'Error: {e}')
elif choice == '4':
try:
response = requests.get('http://127.0.0.1:5000/is_valid')
print(response.json())
except requests.exceptions.RequestException as e:
print(f'Error: {e}')
elif choice == '5':
nodes = input("Enter node addresses (comma separated, e.g., http://127.0.0.1:5001): ")
nodes = nodes.replace(" ", "").split(',')
data = {'nodes': nodes}
try:
response = requests.post('http://127.0.0.1:5000/connect_node', json=data)
print(response.json())
except requests.exceptions.RequestException as e:
print(f'Error: {e}')
elif choice == '6':
try:
response = requests.get('http://127.0.0.1:5000/replace_chain')
print(response.json())
except requests.exceptions.RequestException as e:
print(f'Error: {e}')
elif choice == '7':
print("Exiting...")
break
else:
print("Invalid choice. Please select a valid option.")
Explanation of Components
-
Block Class:
- Represents each block in the blockchain.
- Contains attributes like
index, timestamp, transactions, proof, and previous_hash.
- The
to_dict method converts the block's data into a dictionary for easy serialization.
-
Blockchain Class:
- Manages the chain of blocks and handles the core functionality.
- Initialization: Starts with a genesis block (the first block in the chain).
- create_block: Adds a new block to the chain after verifying the proof of work.
- proof_of_work: Simple algorithm to find a proof number such that the hash of the operation has four leading zeros.
- hash: Generates a SHA-256 hash of a block.
- is_chain_valid: Validates the entire blockchain to ensure integrity.
- add_transaction: Queues a new transaction to be added to the next block.
- add_node: Registers a new node's address for network consensus.
- replace_chain: Implements the consensus mechanism to replace the chain with the longest valid one in the network.
-
Flask App:
- Provides RESTful APIs to interact with the blockchain.
- /mine_block: Mines a new block by finding the proof of work.
- /get_chain: Retrieves the full blockchain.
- /is_valid: Checks if the current blockchain is valid.
- /add_transaction: Adds a new transaction to the blockchain.
- /connect_node: Connects new nodes to the network.
- /replace_chain: Replaces the chain with the longest one if a longer valid chain is found in the network.
-
Command-Line Interface:
- Allows users to interact with the blockchain through a simple menu-driven interface.
- Supports actions like mining, adding transactions, viewing the chain, validating the chain, connecting nodes, and replacing the chain.
-
Concurrency:
- The Flask app runs in a separate thread to allow simultaneous interaction via the command-line interface.
Running the Program
-
Start the Program:
- Run the script using Python 3:
python3 blockchain.py
-
Interact via the Menu:
- Use the command-line menu to perform actions such as mining blocks, adding transactions, and connecting to other nodes.
-
Simulate Multiple Nodes:
- To simulate a network with multiple nodes, run multiple instances of the program on different ports by modifying the
run_flask function's port parameter.
-
Consensus Mechanism:
- After connecting multiple nodes, use the replace chain option to ensure all nodes agree on the longest valid chain.
Advanced Features and Considerations
Conclusion
This comprehensive Python program showcases the fundamental components of a blockchain system, integrating various advanced programming concepts. While it serves as a solid foundation for understanding blockchain mechanics, creating a production-ready blockchain requires addressing additional complexities related to security, scalability, and decentralization.