A production-ready, enterprise-grade blockchain implementation built with Node.js, featuring advanced security, real-time capabilities, and comprehensive monitoring.
- βοΈ Proof of Work Mining - Configurable difficulty consensus
- πΈ Digital Transactions - Cryptographically signed with secp256k1
- π Chain Validation - Complete integrity verification
- π Multi-Node Network - Distributed blockchain synchronization
- π Encrypted Key Storage - AES-256-GCM encryption with PBKDF2
- π‘οΈ Multi-Layer Protection - Input sanitization, rate limiting, CSRF protection
- π Real-Time Monitoring - Integrity monitoring and threat detection
- π Complete Audit Trail - All operations logged with timestamps
- β‘ Attack Prevention - DoS protection, injection prevention, mining spam protection
- π‘ WebSocket Real-Time Updates - Live transaction and mining notifications
- π Performance Metrics - System monitoring and analytics
- π₯ Health Monitoring - Comprehensive node status tracking
- πΎ Data Persistence - Blockchain state survives restarts
- π Graceful Operations - Proper startup, shutdown, and error recovery
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β Client Apps β β WebSocket β β REST API β
β β β Real-time β β HTTP/HTTPS β
βββββββ¬ββββββββββββ ββββββββββ¬ββββββββββ βββββββ¬ββββββββββββ
β β β
βββββββββββββββββββββββββββΌβββββββββββββββββββββ
β
βββββββββββββΌββββββββββββ
β Express Server β
β Security Layer β
βββββββββββββ¬ββββββββββββ
β
βββββββββββββββββββββββββΌββββββββββββββββββββββββ
β β β
βββββββββΌβββββββββ βββββββββββΌβββββββββ βββββββββββΌβββββββββ
β Blockchain β β Security β β Monitoring β
β Core Engine β β Services β β & Metrics β
β β β β β β
β β’ Proof of Work β β β’ Key Management β β β’ Performance β
β β’ Transactions β β β’ Audit Logging β β β’ Health Checks β
β β’ Validation β β β’ Rate Limiting β β β’ Real-time Data β
β β’ P2P Network β β β’ Input Sanitize β β β’ Error Tracking β
βββββββββββββββββββ ββββββββββββββββββββ ββββββββββββββββββββ
- Node.js 14+ (18+ recommended)
- Git
- Terminal/Command Prompt
# Clone the repository
git clone <repository-url>
cd "Blockchain Node 1"
# Install dependencies
npm install
# Create secure directory (Linux/macOS)
mkdir -p server/secure && chmod 700 server/secure
# Create secure directory (Windows)
mkdir server\secure# Run security check
npm run security-check
# Start development server
npm run serve
# The blockchain node will be running at http://localhost:8001# Security validation and production start
npm run production
# Or manual production setup
NODE_ENV=production npm startMost endpoints are public for development. In production, implement proper authentication.
GET /api/healthReturns node status, blockchain info, and system metrics.
GET /api/generateKeysCreates a new cryptographic keypair for blockchain transactions.
POST /api/transactionCreate
Content-Type: application/json
{
"recipient": "04a1b2c3d4e5f6...",
"amount": 10.5
}GET /api/minePendingTxsProcesses pending transactions into a new block using Proof of Work.
GET /api/chainListReturns the complete blockchain with all blocks and transactions.
GET /api/chainValidationVerifies the cryptographic integrity of the entire blockchain.
# Connect to other nodes
POST /api/nodeConnection
{
"nodes": ["http://node2:8001", "http://node3:8001"]
}
# Synchronize with network
GET /api/chainSync
# Get statistics
GET /api/statsconst ws = new WebSocket('ws://localhost:8001');
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log('Real-time update:', data.type, data.data);
};h:\Blockchain\Node 1\
βββ server/
β βββ app/
β β βββ Blockchain/ # Core blockchain logic
β β β βββ Block.js # Block structure and mining
β β β βββ Blockchain.js # Main blockchain class
β β β βββ Transaction.js # Transaction handling
β β β βββ Validation.js # Chain validation logic
β β β βββ Network.js # P2P networking
β β βββ Controllers/ # API endpoint handlers
β β β βββ BlockchainController.js
β β β βββ WalletController.js
β β βββ Middleware/ # Express middleware
β β βββ ErrorMiddleware.js
β βββ config/ # Configuration files
β β βββ blockchain.js # Blockchain parameters
β βββ controllers/ # Advanced controllers
β β βββ StatsController.js # Analytics and metrics
β βββ middleware/ # Security and validation
β β βββ security.js # Security middleware
β β βββ validation.js # Input validation
β β βββ rateLimiter.js # Rate limiting
β β βββ enhancedValidation.js
β βββ routes/ # API routes
β β βββ api.js # Main API routes
β β βββ docs.js # Documentation routes
β βββ utils/ # Utility functions
β β βββ logger.js # Logging system
β β βββ metrics.js # Performance metrics
β β βββ persistence.js # Data storage
β β βββ websocket.js # WebSocket handling
β β βββ secureKeyManager.js # Cryptographic key management
β β βββ integrityMonitor.js # Security monitoring
β β βββ auditLogger.js # Audit trail
β β βββ configValidator.js # Configuration validation
β β βββ processMonitor.js # Process management
β βββ server.js # Main server file
βββ scripts/ # Utility scripts
β βββ runTests.js # Automated testing
β βββ securityCheck.js # Security validation
β βββ production-start.js # Production launcher
βββ .env # Environment configuration
βββ .gitignore # Git ignore rules
βββ package.json # Node.js dependencies
βββ README.md # This file
βββ TESTING.md # Testing guide
βββ ARCHITECTURE.md # Detailed architecture
class Block {
constructor(timestamp, transactions, previousHash) {
this.timestamp = timestamp;
this.transactions = transactions;
this.previousHash = previousHash;
this.hash = this.calculateHash();
this.nonce = 0; // For proof of work
}
// Proof of work mining
mineBlock(difficulty) { ... }
// SHA256 hash calculation
calculateHash() { ... }
// Validate all transactions in block
hasValidTransactions() { ... }
}class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
this.difficulty = 2;
this.pendingTransactions = [];
this.miningReward = 100;
this.nodes = [];
}
// Add new transactions
addTransaction(transaction) { ... }
// Mine pending transactions
minePendingTransactions(miningRewardAddress) { ... }
// Validate entire chain
isChainValid() { ... }
// Network synchronization
replaceChain() { ... }
}class Transaction {
constructor(fromAddress, toAddress, amount) {
this.fromAddress = fromAddress;
this.toAddress = toAddress;
this.amount = amount;
this.timestamp = Date.now();
}
// Sign with private key
signTransaction(keyPair) { ... }
// Verify signature
isValid() { ... }
// Calculate transaction hash
calculateHash() { ... }
}- Elliptic Curve Cryptography: secp256k1 for transaction signatures
- SHA-256 Hashing: For block and transaction integrity
- Proof of Work: Prevents spam and ensures consensus
- Key Encryption: AES-256-GCM with PBKDF2 key derivation
- Rate Limiting: Prevents DoS attacks (5 tx/min, 2 mining/min)
- Input Sanitization: XSS and injection protection
- Request Size Limits: 50MB maximum request size
- IP-based Controls: Production access restrictions
- Audit Logging: Every operation logged with timestamps
- Integrity Monitoring: Real-time tamper detection
- Secure Storage: Encrypted key files with restricted permissions
- Graceful Shutdown: Proper state saving on exit
# Security validation
npm run security-check
# Automated test suite
node scripts/runTests.js
# Manual API testing (see TESTING.md)
curl http://localhost:8001/api/health- β Core blockchain functionality
- β Transaction creation and validation
- β Block mining and proof of work
- β Chain synchronization
- β Security features and rate limiting
- β WebSocket real-time updates
- β Error handling and recovery
See TESTING.md for comprehensive testing guide.
# .env file
NODE_ENV=development # development | production
PORT=8001 # Server port
SECURE_KEY_STORAGE=true # Enable encrypted key storage
ENABLE_KEY_GENERATION=true # Auto-generate keys on startup// server/config/blockchain.js
module.exports = {
DIFFICULTY: 2, // Mining difficulty
MINING_REWARD: 100, # Reward per mined block
MAX_PENDING_TRANSACTIONS: 100,
MAX_BLOCK_SIZE: 10,
RATE_LIMIT: {
TRANSACTION: { max: 5, window: 60000 },
MINING: { max: 2, window: 60000 }
}
};- Transaction throughput (tx/second)
- Block mining time (seconds)
- Memory usage (MB)
- Network latency (ms)
- Error rates (%)
# Real-time health check
curl http://localhost:8001/api/health
# Detailed statistics
curl http://localhost:8001/api/stats
# System metrics
curl http://localhost:8001/api/health | jq '.system'# View recent activity
tail -f server/logs/audit.log
# Search specific events
grep "TRANSACTION_CREATED" server/logs/audit.log
grep "SECURITY_EVENT" server/logs/audit.log# Start nodes on different ports
PORT=8001 npm start & # Node 1
PORT=8002 npm start & # Node 2
PORT=8003 npm start & # Node 3
# Connect nodes together
curl -X POST http://localhost:8001/api/nodeConnection \
-H "Content-Type: application/json" \
-d '{"nodes": ["http://localhost:8002", "http://localhost:8003"]}'
# Synchronize chains
curl http://localhost:8001/api/chainSync Node 1 (8001) ββ Node 2 (8002)
β β
Node 4 (8004) ββ Node 3 (8003)
We welcome contributions! Here's how to get started:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Run tests (
npm run security-check && node scripts/runTests.js) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Create a Pull Request
- Follow existing code style and patterns
- Add comprehensive tests for new features
- Update documentation for API changes
- Ensure all security checks pass
- Add audit logging for new operations
- Never commit private keys or sensitive data
- All user inputs must be validated and sanitized
- New endpoints require rate limiting consideration
- Security-related changes need thorough review
- Always run security checks before submission
- Environment variables configured
- SSL/TLS certificates installed
- Firewall rules configured
- Log rotation setup
- Monitoring alerts configured
- Backup strategy implemented
- Security audit completed
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN mkdir -p server/secure && chmod 700 server/secure
EXPOSE 8001
CMD ["npm", "run", "production"]server {
listen 443 ssl;
server_name blockchain.example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location / {
proxy_pass http://localhost:8001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}This project is licensed under the MIT License - see the LICENSE file for details.
- Elliptic Curve Cryptography: Built on the battle-tested
ellipticlibrary - Express.js: Robust web framework for Node.js
- WebSocket: Real-time communication with
wslibrary - Security: Following OWASP security best practices
- Community: Thanks to all contributors and users
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Security: Report security issues privately to [email protected]
- Documentation: Full Documentation
π Security First: This project prioritizes security and follows industry best practices. All security-related contributions are thoroughly reviewed.
π Star this repo if you find it useful! Your support helps us continue improving this open-source blockchain implementation.