A complete, feature-rich blockchain implementation in Python with cryptographic security, proof-of-work consensus, and a user-friendly CLI interface.
- Features
- Architecture
- Installation
- Quick Start
- Usage
- Components
- Testing
- Examples
- Configuration
- Contributing
- License
- ๐ Cryptographic Security: ECDSA key pairs with SECP256K1 curve
- โ๏ธ Proof of Work: Configurable difficulty mining algorithm
- ๐ฐ Digital Wallets: Secure wallet management with public/private key pairs
- ๐ Transaction Signing: Digital signatures for transaction verification
- ๐ Chain Validation: Complete blockchain integrity validation
- ๐ Network Nodes: Support for distributed node registration
- ๐ป CLI Interface: User-friendly command-line tools
- ๐งช Comprehensive Tests: Full test coverage with pytest
- ๐ Detailed Logging: Built-in logging for debugging and monitoring
- ๐ณ Docker Support: Containerized deployment ready
The blockchain is organized into modular components:
Blockchain/
โโโ blockchain_core/ # Core blockchain implementation
โ โโโ blockchain.py # Main blockchain class
โ โโโ block.py # Block structure and validation
โ โโโ wallet.py # Wallet and cryptographic functions
โ โโโ transaction.py # Transaction handling
โ โโโ utils.py # Utility functions
โโโ cli/ # Command-line interface
โโโ config/ # Configuration settings
โโโ tests/ # Unit and integration tests
โโโ examples/ # Usage examples
โโโ docs/ # Documentation
Manages the chain of blocks and transactions, including:
- Block creation and validation
- Transaction pool management
- Proof of work consensus
- Balance calculation
- Chain validation
Represents each block in the blockchain with:
- Index and timestamp
- List of transactions
- Previous block hash
- Nonce for proof of work
- Computed hash
Handles wallet functionalities:
- Generate private/public key pairs (ECDSA SECP256K1)
- Serialize and export keys
- Sign transactions
- Verify signatures
Manages transaction operations:
- Transaction creation and validation
- Digital signature verification
- Structured transaction data
- Python 3.8 or higher
- pip package manager
# Clone the repository
git clone https://github.com/pyenthusiasts/Blockchain.git
cd Blockchain
# Install dependencies
pip install -r requirements.txt
# Install the package
pip install -e .# Build the Docker image
docker build -t blockchain .
# Run the container
docker run -it blockchainfrom blockchain_core import Blockchain, Wallet
# Create a blockchain
blockchain = Blockchain(difficulty=2, miner_rewards=50)
# Create wallets
alice = Wallet()
bob = Wallet()
# Mine a block
blockchain.mine(alice.address)
# Create a transaction
from collections import OrderedDict
transaction = OrderedDict({
'sender_public_key': alice.address,
'recipient_address': bob.address,
'value': 10
})
signature = alice.sign_transaction(transaction)
blockchain.add_transaction(alice.address, bob.address, 10, signature)
# Mine to confirm
blockchain.mine(alice.address)
# Check balances
print(f"Alice's balance: {blockchain.get_balance(alice.address)}")
print(f"Bob's balance: {blockchain.get_balance(bob.address)}")from blockchain_core import Blockchain
# Create with default settings
blockchain = Blockchain()
# Create with custom settings
blockchain = Blockchain(difficulty=4, miner_rewards=25)from blockchain_core import Wallet
# Create a new wallet
wallet = Wallet()
# Export private key
private_key = wallet.export_private_key()
# Import wallet from private key
imported_wallet = Wallet.from_private_key(private_key)
# Sign a transaction
signature = wallet.sign_transaction(transaction_data)from collections import OrderedDict
# Create transaction data
transaction = OrderedDict({
'sender_public_key': sender_wallet.address,
'recipient_address': recipient_wallet.address,
'value': 50
})
# Sign the transaction
signature = sender_wallet.sign_transaction(transaction)
# Add to blockchain
blockchain.add_transaction(
sender_wallet.address,
recipient_wallet.address,
50,
signature
)# Mine a new block
block_index = blockchain.mine(miner_wallet.address)
if block_index:
print(f"Block {block_index} mined successfully!")balance = blockchain.get_balance(wallet.address)
print(f"Balance: {balance}")if blockchain.is_valid_chain():
print("Blockchain is valid!")
else:
print("Blockchain has been compromised!")The blockchain includes a comprehensive CLI for all operations.
# Create and display wallet
blockchain create-wallet
# Save wallet to file
blockchain create-wallet -o mywallet.jsonblockchain balance <address># Mine with default difficulty
blockchain mine <miner_address>
# Mine with custom difficulty
blockchain mine <miner_address> -d 4blockchain send <sender_wallet_file> <recipient_address> <amount># View summary
blockchain chain
# View detailed information
blockchain chain --detailblockchain pendingblockchain validateblockchain export blockchain_data.jsonblockchain infoMain blockchain implementation with:
- Genesis block creation
- Transaction management
- Proof of work algorithm
- Block addition and validation
- Balance calculation
- Network node management
Block structure with:
- Index, timestamp, transactions
- Previous hash linkage
- Nonce for mining
- Hash computation
- Validation methods
Cryptographic wallet with:
- ECDSA key generation (SECP256K1)
- Key serialization and export
- Transaction signing
- Signature verification
Transaction handling with:
- Structured transaction format
- Digital signatures
- Validation methods
- Coinbase transactions
Utility functions:
- Hash computation
- Address validation
- Transaction serialization
- Logging setup
The project includes comprehensive unit tests with pytest.
# Run all tests
pytest
# Run with coverage
pytest --cov=blockchain_core
# Run specific test file
pytest tests/test_blockchain.py
# Run with verbose output
pytest -v- โ Block creation and validation
- โ Wallet generation and signing
- โ Transaction creation and validation
- โ Blockchain operations
- โ Proof of work
- โ Chain validation
- โ Balance calculations
- โ Utility functions
See examples/basic_usage.py for a complete basic example covering:
- Blockchain creation
- Wallet management
- Mining
- Transactions
- Balance checking
Run it:
python examples/basic_usage.pySee examples/advanced_features.py for advanced usage:
- Multiple transactions
- Wallet import/export
- Transaction validation
- Failed transaction handling
- Chain exploration
- Blockchain export
Run it:
python examples/advanced_features.pyConfiguration is managed in config/config.py:
# Mining settings
DIFFICULTY = 2 # Number of leading zeros required
MINER_REWARD = 50 # Reward for mining a block
INITIAL_BALANCE = 150 # Initial wallet balance
# Cryptography
CURVE = 'SECP256K1' # Elliptic curve for ECDSA
HASH_ALGORITHM = 'SHA256' # Hash algorithm
# Network
DEFAULT_PORT = 5000 # Default network port
MAX_NODES = 100 # Maximum network nodes
# Logging
LOG_LEVEL = 'INFO' # Logging level# Build image
docker build -t blockchain .
# Run container
docker run -it blockchain
# Run with volume mount
docker run -it -v $(pwd)/data:/app/data blockchain# Start services
docker-compose up
# Stop services
docker-compose downFor detailed API documentation, see docs/API.md.
- Private Keys: Always keep private keys secure and never share them
- Initial Balance: The default initial balance is for demonstration purposes
- Network Security: In production, implement proper network security
- Consensus: The proof-of-work difficulty should be adjusted based on network needs
- REST API implementation
- Consensus algorithm improvements (PoS)
- Smart contract support
- Web interface
- Merkle tree implementation
- Enhanced networking capabilities
- Database persistence
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
# Install development dependencies
pip install -r requirements.txt
# Run tests
pytest
# Run linting
flake8 blockchain_core tests
# Format code
black blockchain_core testsThis project is licensed under the MIT License - see the LICENSE file for details.
Python Enthusiasts - GitHub
- Inspired by Bitcoin and Ethereum implementations
- Built with Python's cryptography library
- Thanks to all contributors
For questions, issues, or suggestions:
- Open an issue on GitHub
- Email: [Contact through GitHub]
โญ If you find this project useful, please consider giving it a star!