Ledgers to Smart Contracts: What is the Blockchain?

Blockchain Technology: A Deep Dive into Distributed Ledgers

Blockchain technology has emerged as one of the most transformative innovations of the 21st century, promising to revolutionize industries from finance to supply chain management. This comprehensive guide will take you through the core concepts, cryptographic foundations, and practical implementations of blockchain systems.

Understanding Blockchain Fundamentals

A blockchain is a distributed, decentralized digital ledger that records transactions across multiple computers in a way that ensures security, transparency, and immutability. Each block contains a list of transactions, and blocks are linked together using cryptographic hashes, forming a chain.

Core Characteristics

Cryptographic Foundations

Blockchain security relies heavily on cryptographic principles. Understanding these is essential for building secure blockchain applications.

Hash Functions

Hash functions are one-way functions that convert input data into fixed-size output strings. They're crucial for creating digital fingerprints and linking blocks.

import hashlib
import json

class BlockHasher:
    def __init__(self):
        self.hash_algorithm = hashlib.sha256
    
    def hash_data(self, data):
        """Hash any data structure"""
        if isinstance(data, (dict, list)):
            data_string = json.dumps(data, sort_keys=True)
        else:
            data_string = str(data)
        
        return self.hash_algorithm(data_string.encode('utf-8')).hexdigest()
    
    def hash_block(self, block_data):
        """Hash block data including previous hash"""
        block_string = json.dumps(block_data, sort_keys=True)
        return self.hash_algorithm(block_string.encode('utf-8')).hexdigest()

# Example usage
hasher = BlockHasher()

# Hash simple data
simple_hash = hasher.hash_data("Hello, Blockchain!")
print(f"Hash of 'Hello, Blockchain!': {simple_hash}")

# Hash complex data
complex_data = {
    "sender": "Alice",
    "recipient": "Bob",
    "amount": 100,
    "timestamp": "2024-01-01T12:00:00Z"
}
complex_hash = hasher.hash_data(complex_data)
print(f"Hash of complex data: {complex_hash}")

# Verify hash consistency
hash1 = hasher.hash_data(complex_data)
hash2 = hasher.hash_data(complex_data)
print(f"Hash consistency: {hash1 == hash2}")

Public Key Cryptography

Public key cryptography enables secure digital signatures and identity verification in blockchain networks.

from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.backends import default_backend
import base64

class BlockchainCrypto:
    def __init__(self):
        self.backend = default_backend()
    
    def generate_key_pair(self):
        """Generate RSA key pair"""
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=self.backend
        )
        public_key = private_key.public_key()
        return private_key, public_key
    
    def sign_message(self, private_key, message):
        """Sign a message with private key"""
        if isinstance(message, str):
            message = message.encode('utf-8')
        
        signature = private_key.sign(
            message,
            padding.PSS(
                mgf=padding.MGF1(hashes.SHA256()),
                salt_length=padding.PSS.MAX_LENGTH
            ),
            hashes.SHA256()
        )
        return base64.b64encode(signature).decode('utf-8')
    
    def verify_signature(self, public_key, message, signature):
        """Verify signature with public key"""
        try:
            if isinstance(message, str):
                message = message.encode('utf-8')
            
            signature_bytes = base64.b64decode(signature)
            public_key.verify(
                signature_bytes,
                message,
                padding.PSS(
                    mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=padding.PSS.MAX_LENGTH
                ),
                hashes.SHA256()
            )
            return True
        except Exception:
            return False

# Example usage
crypto = BlockchainCrypto()

# Generate key pair
private_key, public_key = crypto.generate_key_pair()
print("Key pair generated successfully")

# Sign a message
message = "Transfer 100 tokens to Bob"
signature = crypto.sign_message(private_key, message)
print(f"Message: {message}")
print(f"Signature: {signature}")

# Verify signature
is_valid = crypto.verify_signature(public_key, message, signature)
print(f"Signature valid: {is_valid}")

# Try to verify with wrong message
wrong_message = "Transfer 200 tokens to Bob"
is_valid_wrong = crypto.verify_signature(public_key, wrong_message, signature)
print(f"Wrong message signature valid: {is_valid_wrong}")

Building a Simple Blockchain

Let's implement a basic blockchain to understand the core concepts.

Block Structure

import time
from typing import List, Dict, Any

class Block:
    def __init__(self, index: int, transactions: List[Dict], timestamp: float, previous_hash: str):
        self.index = index
        self.transactions = transactions
        self.timestamp = timestamp
        self.previous_hash = previous_hash
        self.nonce = 0
        self.hash = self.calculate_hash()
    
    def calculate_hash(self) -> str:
        """Calculate hash of the block"""
        block_string = json.dumps({
            'index': self.index,
            'transactions': self.transactions,
            'timestamp': self.timestamp,
            'previous_hash': self.previous_hash,
            'nonce': self.nonce
        }, sort_keys=True)
        
        return hashlib.sha256(block_string.encode('utf-8')).hexdigest()
    
    def mine_block(self, difficulty: int) -> None:
        """Mine block with proof of work"""
        target = '0' * difficulty
        
        while self.hash[:difficulty] != target:
            self.nonce += 1
            self.hash = self.calculate_hash()
        
        print(f"Block mined! Hash: {self.hash}")
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert block to dictionary"""
        return {
            'index': self.index,
            'transactions': self.transactions,
            'timestamp': self.timestamp,
            'previous_hash': self.previous_hash,
            'nonce': self.nonce,
            'hash': self.hash
        }

# Example block creation
genesis_transactions = [
    {"sender": "Genesis", "recipient": "Alice", "amount": 1000},
    {"sender": "Genesis", "recipient": "Bob", "amount": 1000}
]

genesis_block = Block(0, genesis_transactions, time.time(), "0")
print("Genesis block created:")
print(f"Index: {genesis_block.index}")
print(f"Hash: {genesis_block.hash}")
print(f"Previous Hash: {genesis_block.previous_hash}")

Blockchain Implementation

class Blockchain:
    def __init__(self):
        self.chain = []
        self.difficulty = 4
        self.pending_transactions = []
        self.mining_reward = 10
        
        # Create genesis block
        self.create_genesis_block()
    
    def create_genesis_block(self):
        """Create the first block in the chain"""
        genesis_block = Block(0, [], time.time(), "0")
        self.chain.append(genesis_block)
        print("Genesis block created")
    
    def get_latest_block(self) -> Block:
        """Get the most recent block"""
        return self.chain[-1]
    
    def add_transaction(self, sender: str, recipient: str, amount: float) -> int:
        """Add a new transaction to pending transactions"""
        self.pending_transactions.append({
            'sender': sender,
            'recipient': recipient,
            'amount': amount,
            'timestamp': time.time()
        })
        
        return len(self.chain) + 1
    
    def mine_pending_transactions(self, miner_address: str):
        """Mine a new block with pending transactions"""
        block = Block(
            len(self.chain),
            self.pending_transactions,
            time.time(),
            self.get_latest_block().hash
        )
        
        print(f"Mining block {block.index}...")
        block.mine_block(self.difficulty)
        
        print("Block successfully mined!")
        self.chain.append(block)
        
        # Reset pending transactions and add mining reward
        self.pending_transactions = [
            {
                'sender': "Network",
                'recipient': miner_address,
                'amount': self.mining_reward,
                'timestamp': time.time()
            }
        ]
    
    def is_chain_valid(self) -> bool:
        """Verify the blockchain integrity"""
        for i in range(1, len(self.chain)):
            current_block = self.chain[i]
            previous_block = self.chain[i-1]
            
            # Verify current block hash
            if current_block.hash != current_block.calculate_hash():
                print(f"Invalid hash in block {i}")
                return False
            
            # Verify chain linkage
            if current_block.previous_hash != previous_block.hash:
                print(f"Invalid previous hash in block {i}")
                return False
        
        return True
    
    def get_balance(self, address: str) -> float:
        """Calculate balance for a given address"""
        balance = 0.0
        
        for block in self.chain:
            for transaction in block.transactions:
                if transaction['recipient'] == address:
                    balance += transaction['amount']
                if transaction['sender'] == address:
                    balance -= transaction['amount']
        
        return balance
    
    def display_chain(self):
        """Display the entire blockchain"""
        print("\n" + "="*50)
        print("BLOCKCHAIN")
        print("="*50)
        
        for block in self.chain:
            print(f"\nBlock #{block.index}")
            print(f"Timestamp: {time.ctime(block.timestamp)}")
            print(f"Hash: {block.hash}")
            print(f"Previous Hash: {block.previous_hash}")
            print(f"Nonce: {block.nonce}")
            print("Transactions:")
            
            for tx in block.transactions:
                print(f"  {tx['sender']} -> {tx['recipient']}: {tx['amount']}")
            
            print("-" * 30)

# Create and test blockchain
print("Creating blockchain...")
my_blockchain = Blockchain()

# Add some transactions
my_blockchain.add_transaction("Alice", "Bob", 50)
my_blockchain.add_transaction("Bob", "Charlie", 30)
my_blockchain.add_transaction("Charlie", "David", 20)

# Mine the first block
print("\nMining first block...")
my_blockchain.mine_pending_transactions("miner1")

# Add more transactions
my_blockchain.add_transaction("David", "Eve", 15)
my_blockchain.add_transaction("Eve", "Frank", 10)

# Mine the second block
print("\nMining second block...")
my_blockchain.mine_pending_transactions("miner2")

# Display the blockchain
my_blockchain.display_chain()

# Check balances
print(f"\nBalances:")
print(f"Alice: {my_blockchain.get_balance('Alice')}")
print(f"Bob: {my_blockchain.get_balance('Bob')}")
print(f"Charlie: {my_blockchain.get_balance('Charlie')}")
print(f"David: {my_blockchain.get_balance('David')}")
print(f"Eve: {my_blockchain.get_balance('Eve')}")
print(f"Frank: {my_blockchain.get_balance('Frank')}")
print(f"miner1: {my_blockchain.get_balance('miner1')}")
print(f"miner2: {my_blockchain.get_balance('miner2')}")

# Verify chain integrity
print(f"\nBlockchain valid: {my_blockchain.is_chain_valid()}")

Proof of Work Consensus

Proof of Work (PoW) is a consensus mechanism that requires computational work to validate transactions and create new blocks.

Mining Algorithm

class ProofOfWork:
    def __init__(self, difficulty: int = 4):
        self.difficulty = difficulty
        self.target = '0' * difficulty
    
    def mine_block(self, block: Block) -> str:
        """Mine a block with proof of work"""
        print(f"Mining block with difficulty {self.difficulty}")
        print(f"Target: {self.target}")
        
        start_time = time.time()
        attempts = 0
        
        while block.hash[:self.difficulty] != self.target:
            block.nonce += 1
            block.hash = block.calculate_hash()
            attempts += 1
            
            if attempts % 10000 == 0:
                print(f"Attempts: {attempts}, Current hash: {block.hash}")
        
        end_time = time.time()
        mining_time = end_time - start_time
        
        print(f"Block mined successfully!")
        print(f"Final hash: {block.hash}")
        print(f"Nonce: {block.nonce}")
        print(f"Attempts: {attempts}")
        print(f"Mining time: {mining_time:.2f} seconds")
        print(f"Hash rate: {attempts/mining_time:.0f} hashes/second")
        
        return block.hash
    
    def verify_proof(self, block: Block) -> bool:
        """Verify that a block meets the proof of work requirement"""
        return block.hash[:self.difficulty] == self.target

# Test proof of work
print("Testing Proof of Work...")
pow_system = ProofOfWork(difficulty=4)

test_block = Block(1, [{"test": "transaction"}], time.time(), "0")
print(f"Initial hash: {test_block.hash}")

# Mine the block
pow_system.mine_block(test_block)

# Verify the proof
is_valid = pow_system.verify_proof(test_block)
print(f"Proof verification: {is_valid}")

Smart Contracts

Smart contracts are self-executing contracts with the terms directly written into code. They automatically execute when predefined conditions are met.

Simple Smart Contract Implementation

class SmartContract:
    def __init__(self, contract_id: str, owner: str):
        self.contract_id = contract_id
        self.owner = owner
        self.balance = 0.0
        self.conditions = {}
        self.executed = False
    
    def add_condition(self, condition_type: str, **kwargs):
        """Add a condition to the smart contract"""
        self.conditions[condition_type] = kwargs
    
    def execute_contract(self, **kwargs) -> bool:
        """Execute the smart contract if conditions are met"""
        if self.executed:
            print("Contract already executed")
            return False
        
        # Check conditions
        for condition_type, condition_params in self.conditions.items():
            if not self._check_condition(condition_type, condition_params, kwargs):
                print(f"Condition {condition_type} not met")
                return False
        
        # Execute contract logic
        self._execute_logic(kwargs)
        self.executed = True
        print("Smart contract executed successfully")
        return True
    
    def _check_condition(self, condition_type: str, condition_params: dict, execution_params: dict) -> bool:
        """Check if a specific condition is met"""
        if condition_type == "time_based":
            current_time = time.time()
            start_time = condition_params.get('start_time', 0)
            end_time = condition_params.get('end_time', float('inf'))
            return start_time <= current_time <= end_time
        
        elif condition_type == "amount_based":
            required_amount = condition_params.get('amount', 0)
            provided_amount = execution_params.get('amount', 0)
            return provided_amount >= required_amount
        
        elif condition_type == "signature_based":
            required_signatures = condition_params.get('signatures', [])
            provided_signatures = execution_params.get('signatures', [])
            return all(sig in provided_signatures for sig in required_signatures)
        
        return False
    
    def _execute_logic(self, execution_params: dict):
        """Execute the main logic of the smart contract"""
        # Example: Transfer funds
        if 'amount' in execution_params:
            self.balance += execution_params['amount']
            print(f"Funds transferred: {execution_params['amount']}")
        
        # Example: Record transaction
        if 'transaction_id' in execution_params:
            print(f"Transaction recorded: {execution_params['transaction_id']}")

# Example smart contract usage
print("\nCreating smart contract...")
escrow_contract = SmartContract("ESC001", "Alice")

# Add conditions
escrow_contract.add_condition("time_based", start_time=time.time(), end_time=time.time() + 3600)
escrow_contract.add_condition("amount_based", amount=100)
escrow_contract.add_condition("signature_based", signatures=["Alice", "Bob"])

print("Smart contract created with conditions:")
for condition_type, params in escrow_contract.conditions.items():
    print(f"  {condition_type}: {params}")

# Try to execute with insufficient conditions
print("\nAttempting execution with insufficient conditions...")
success = escrow_contract.execute_contract(amount=50)
print(f"Execution successful: {success}")

# Execute with proper conditions
print("\nExecuting with proper conditions...")
success = escrow_contract.execute_contract(
    amount=150,
    signatures=["Alice", "Bob", "Charlie"],
    transaction_id="TX123"
)
print(f"Execution successful: {success}")

# Try to execute again
print("\nAttempting to execute again...")
success = escrow_contract.execute_contract(amount=100)
print(f"Execution successful: {success}")

Decentralized Applications (DApps)

DApps are applications that run on a decentralized network rather than a single computer.

Simple DApp Framework

class DecentralizedApp:
    def __init__(self, name: str, blockchain: Blockchain):
        self.name = name
        self.blockchain = blockchain
        self.users = {}
        self.app_state = {}
    
    def register_user(self, username: str, public_key: str) -> bool:
        """Register a new user in the DApp"""
        if username in self.users:
            print(f"User {username} already exists")
            return False
        
        self.users[username] = {
            'public_key': public_key,
            'balance': 0.0,
            'created_at': time.time()
        }
        
        # Record user registration on blockchain
        self.blockchain.add_transaction("System", username, 100)  # Welcome bonus
        
        print(f"User {username} registered successfully")
        return True
    
    def execute_action(self, username: str, action: str, **params) -> bool:
        """Execute an action in the DApp"""
        if username not in self.users:
            print(f"User {username} not found")
            return False
        
        if action == "transfer":
            recipient = params.get('recipient')
            amount = params.get('amount', 0)
            
            if self.users[username]['balance'] >= amount:
                self.blockchain.add_transaction(username, recipient, amount)
                self.users[username]['balance'] -= amount
                if recipient in self.users:
                    self.users[recipient]['balance'] += amount
                print(f"Transfer successful: {username} -> {recipient}: {amount}")
                return True
            else:
                print(f"Insufficient balance for {username}")
                return False
        
        elif action == "update_state":
            key = params.get('key')
            value = params.get('value')
            self.app_state[key] = value
            print(f"State updated: {key} = {value}")
            return True
        
        return False
    
    def get_user_info(self, username: str) -> dict:
        """Get information about a user"""
        if username in self.users:
            user_info = self.users[username].copy()
            user_info['blockchain_balance'] = self.blockchain.get_balance(username)
            return user_info
        return None
    
    def display_app_state(self):
        """Display current DApp state"""
        print(f"\n{self.name} - Current State")
        print("=" * 40)
        
        print("\nUsers:")
        for username, user_data in self.users.items():
            print(f"  {username}: Balance = {user_data['balance']}")
        
        print("\nApp State:")
        for key, value in self.app_state.items():
            print(f"  {key}: {value}")
        
        print(f"\nBlockchain blocks: {len(self.blockchain.chain)}")

# Create and test DApp
print("\nCreating decentralized application...")
dapp = DecentralizedApp("TokenExchange", my_blockchain)

# Register users
dapp.register_user("Alice", "alice_public_key")
dapp.register_user("Bob", "bob_public_key")
dapp.register_user("Charlie", "charlie_public_key")

# Mine a block to process registrations
my_blockchain.mine_pending_transactions("miner3")

# Execute some actions
dapp.execute_action("Alice", "transfer", recipient="Bob", amount=25)
dapp.execute_action("Bob", "transfer", recipient="Charlie", amount=15)
dapp.execute_action("Alice", "update_state", key="preferences", value="dark_mode")

# Mine another block
my_blockchain.mine_pending_transactions("miner4")

# Display DApp state
dapp.display_app_state()

# Get user information
alice_info = dapp.get_user_info("Alice")
print(f"\nAlice's info: {alice_info}")

Blockchain Security and Attacks

Understanding security vulnerabilities is crucial for building robust blockchain systems.

Security Analysis Tools

class BlockchainSecurity:
    def __init__(self, blockchain: Blockchain):
        self.blockchain = blockchain
    
    def analyze_51_percent_attack(self) -> dict:
        """Analyze vulnerability to 51% attack"""
        total_mining_power = 100  # Assume total network hashrate
        
        # Simulate different attacker hashrates
        attack_scenarios = {}
        for attacker_power in [25, 30, 40, 51, 60, 70]:
            success_probability = self._calculate_attack_success(attacker_power, total_mining_power)
            attack_scenarios[attacker_power] = success_probability
        
        return attack_scenarios
    
    def _calculate_attack_success(self, attacker_power: int, total_power: int) -> float:
        """Calculate probability of successful 51% attack"""
        if attacker_power >= total_power / 2:
            return 1.0
        
        # Simplified probability calculation
        attacker_ratio = attacker_power / total_power
        return (attacker_ratio / (1 - attacker_ratio)) ** 6
    
    def detect_double_spending(self) -> List[Dict]:
        """Detect potential double spending attempts"""
        double_spends = []
        address_balances = {}
        
        for block in self.blockchain.chain:
            for transaction in block.transactions:
                sender = transaction['sender']
                amount = transaction['amount']
                
                if sender not in address_balances:
                    address_balances[sender] = 0
                
                # Check if sender has sufficient balance
                if address_balances[sender] < amount and sender != "Genesis" and sender != "Network":
                    double_spends.append({
                        'block_index': block.index,
                        'transaction': transaction,
                        'available_balance': address_balances[sender],
                        'required_amount': amount
                    })
                
                # Update balances
                address_balances[sender] -= amount
                recipient = transaction['recipient']
                if recipient not in address_balances:
                    address_balances[recipient] = 0
                address_balances[recipient] += amount
        
        return double_spends
    
    def analyze_fork_attack(self) -> dict:
        """Analyze potential fork attacks"""
        fork_analysis = {
            'longest_chain_length': len(self.blockchain.chain),
            'potential_forks': 0,
            'security_level': 'High'
        }
        
        # Check for orphaned blocks (simplified)
        if len(self.blockchain.chain) < 6:
            fork_analysis['security_level'] = 'Low'
        elif len(self.blockchain.chain) < 12:
            fork_analysis['security_level'] = 'Medium'
        
        return fork_analysis

# Test security analysis
print("\nAnalyzing blockchain security...")
security_analyzer = BlockchainSecurity(my_blockchain)

# 51% attack analysis
attack_analysis = security_analyzer.analyze_51_percent_attack()
print("\n51% Attack Analysis:")
for attacker_power, success_prob in attack_analysis.items():
    print(f"  Attacker power {attacker_power}%: {success_prob:.2%} success probability")

# Double spending detection
double_spends = security_analyzer.detect_double_spending()
if double_spends:
    print(f"\nDouble spending attempts detected: {len(double_spends)}")
    for attempt in double_spends:
        print(f"  Block {attempt['block_index']}: {attempt['transaction']}")
else:
    print("\nNo double spending attempts detected")

# Fork attack analysis
fork_analysis = security_analyzer.analyze_fork_attack()
print(f"\nFork Attack Analysis:")
print(f"  Chain length: {fork_analysis['longest_chain_length']}")
print(f"  Security level: {fork_analysis['security_level']}")

Scalability Solutions

Blockchain scalability is a major challenge. Let's explore some solutions.

Sharding Implementation

class ShardedBlockchain:
    def __init__(self, num_shards: int = 4):
        self.num_shards = num_shards
        self.shards = {}
        self.cross_shard_transactions = []
        
        # Initialize shards
        for i in range(num_shards):
            self.shards[i] = {
                'chain': [],
                'pending_transactions': [],
                'validators': []
            }
    
    def add_transaction_to_shard(self, shard_id: int, transaction: dict) -> bool:
        """Add transaction to specific shard"""
        if shard_id not in self.shards:
            return False
        
        self.shards[shard_id]['pending_transactions'].append(transaction)
        return True
    
    def mine_shard(self, shard_id: int, miner_address: str):
        """Mine a block in a specific shard"""
        if shard_id not in self.shards:
            return False
        
        shard = self.shards[shard_id]
        if not shard['pending_transactions']:
            return False
        
        # Create block for this shard
        block = Block(
            len(shard['chain']),
            shard['pending_transactions'],
            time.time(),
            shard['chain'][-1].hash if shard['chain'] else "0"
        )
        
        # Mine with lower difficulty for shards
        block.mine_block(2)  # Lower difficulty for faster processing
        
        shard['chain'].append(block)
        shard['pending_transactions'] = []
        
        print(f"Shard {shard_id} block mined: {block.hash}")
        return True
    
    def process_cross_shard_transaction(self, from_shard: int, to_shard: int, 
                                      transaction: dict) -> bool:
        """Process transaction between different shards"""
        cross_shard_tx = {
            'from_shard': from_shard,
            'to_shard': to_shard,
            'transaction': transaction,
            'timestamp': time.time(),
            'status': 'pending'
        }
        
        self.cross_shard_transactions.append(cross_shard_tx)
        
        # Add to both shards
        self.add_transaction_to_shard(from_shard, transaction)
        self.add_transaction_to_shard(to_shard, transaction)
        
        return True
    
    def get_shard_info(self, shard_id: int) -> dict:
        """Get information about a specific shard"""
        if shard_id not in self.shards:
            return None
        
        shard = self.shards[shard_id]
        return {
            'shard_id': shard_id,
            'block_count': len(shard['chain']),
            'pending_transactions': len(shard['pending_transactions']),
            'validator_count': len(shard['validators'])
        }
    
    def display_all_shards(self):
        """Display information about all shards"""
        print(f"\nSharded Blockchain ({self.num_shards} shards)")
        print("=" * 50)
        
        for shard_id in self.shards:
            info = self.get_shard_info(shard_id)
            print(f"\nShard {shard_id}:")
            print(f"  Blocks: {info['block_count']}")
            print(f"  Pending transactions: {info['pending_transactions']}")
            print(f"  Validators: {info['validator_count']}")
        
        print(f"\nCross-shard transactions: {len(self.cross_shard_transactions)}")

# Test sharded blockchain
print("\nCreating sharded blockchain...")
sharded_bc = ShardedBlockchain(num_shards=3)

# Add transactions to different shards
sharded_bc.add_transaction_to_shard(0, {"sender": "Alice", "recipient": "Bob", "amount": 50})
sharded_bc.add_transaction_to_shard(1, {"sender": "Charlie", "recipient": "David", "amount": 30})
sharded_bc.add_transaction_to_shard(2, {"sender": "Eve", "recipient": "Frank", "amount": 25})

# Process cross-shard transaction
sharded_bc.process_cross_shard_transaction(0, 1, {"sender": "Alice", "recipient": "Charlie", "amount": 20})

# Mine blocks in different shards
sharded_bc.mine_shard(0, "miner_shard_0")
sharded_bc.mine_shard(1, "miner_shard_1")
sharded_bc.mine_shard(2, "miner_shard_2")

# Display shard information
sharded_bc.display_all_shards()

Conclusion

Blockchain technology represents a paradigm shift in how we think about trust, security, and decentralized systems. This comprehensive guide covered:

Key takeaways:

The blockchain ecosystem is rapidly evolving with new consensus mechanisms, scalability solutions, and use cases emerging regularly. Understanding these fundamentals provides a solid foundation for building and contributing to the next generation of decentralized technologies.

As you continue your blockchain journey, focus on: