Skip to content

Techminate-Labs/Blockchain

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ”— Enterprise Blockchain Node

License: MIT Node.js Security WebSocket

A production-ready, enterprise-grade blockchain implementation built with Node.js, featuring advanced security, real-time capabilities, and comprehensive monitoring.

🌟 Features

Core Blockchain

  • ⛏️ Proof of Work Mining - Configurable difficulty consensus
  • πŸ’Έ Digital Transactions - Cryptographically signed with secp256k1
  • πŸ”— Chain Validation - Complete integrity verification
  • 🌍 Multi-Node Network - Distributed blockchain synchronization

Enterprise Security

  • πŸ” 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

Advanced Features

  • πŸ“‘ 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

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   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 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸš€ Quick Start

Prerequisites

  • Node.js 14+ (18+ recommended)
  • Git
  • Terminal/Command Prompt

Installation

# 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

Development Setup

# Run security check
npm run security-check

# Start development server
npm run serve

# The blockchain node will be running at http://localhost:8001

Production Deployment

# Security validation and production start
npm run production

# Or manual production setup
NODE_ENV=production npm start

πŸ“š API Documentation

Authentication

Most endpoints are public for development. In production, implement proper authentication.

Core Endpoints

Health Check

GET /api/health

Returns node status, blockchain info, and system metrics.

Generate Wallet

GET /api/generateKeys

Creates a new cryptographic keypair for blockchain transactions.

Create Transaction

POST /api/transactionCreate
Content-Type: application/json

{
  "recipient": "04a1b2c3d4e5f6...", 
  "amount": 10.5
}

Mine Block

GET /api/minePendingTxs

Processes pending transactions into a new block using Proof of Work.

View Blockchain

GET /api/chainList

Returns the complete blockchain with all blocks and transactions.

Validate Chain

GET /api/chainValidation

Verifies the cryptographic integrity of the entire blockchain.

Network Operations

# Connect to other nodes
POST /api/nodeConnection
{
  "nodes": ["http://node2:8001", "http://node3:8001"]
}

# Synchronize with network
GET /api/chainSync

# Get statistics
GET /api/stats

WebSocket Connection

const 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);
};

πŸ—οΈ Code Architecture

Directory Structure

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

Core Classes

Block Class

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() { ... }
}

Blockchain Class

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() { ... }
}

Transaction Class

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() { ... }
}

πŸ”’ Security Features

Cryptographic Security

  • 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

Network Security

  • 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

Operational Security

  • 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

πŸ§ͺ Testing

Run All Tests

# 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

Test Coverage

  • βœ… 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.

πŸ”§ Configuration

Environment Variables

# .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

Blockchain Parameters

// 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 }
  }
};

πŸ“Š Monitoring & Metrics

Performance Metrics

  • Transaction throughput (tx/second)
  • Block mining time (seconds)
  • Memory usage (MB)
  • Network latency (ms)
  • Error rates (%)

Health Monitoring

# 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'

Audit Logs

# 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

🌐 Network & Multi-Node Setup

Connect Multiple Nodes

# 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

Network Topology

     Node 1 (8001) ←→ Node 2 (8002)
           ↕               ↕
     Node 4 (8004) ←→ Node 3 (8003)

🀝 Contributing

We welcome contributions! Here's how to get started:

Development Workflow

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Run tests (npm run security-check && node scripts/runTests.js)
  4. Commit changes (git commit -m 'Add amazing feature')
  5. Push to branch (git push origin feature/amazing-feature)
  6. Create a Pull Request

Code Standards

  • 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

Security Guidelines

  • 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

πŸš€ Deployment

Production Checklist

  • Environment variables configured
  • SSL/TLS certificates installed
  • Firewall rules configured
  • Log rotation setup
  • Monitoring alerts configured
  • Backup strategy implemented
  • Security audit completed

Docker Deployment

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"]

Reverse Proxy (Nginx)

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;
    }
}

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Elliptic Curve Cryptography: Built on the battle-tested elliptic library
  • Express.js: Robust web framework for Node.js
  • WebSocket: Real-time communication with ws library
  • Security: Following OWASP security best practices
  • Community: Thanks to all contributors and users

πŸ“ž Support & Community


⚠️ Production Notice: This blockchain implements enterprise-grade security. Always run comprehensive security checks before production deployment. Regular security audits are recommended.

πŸ”’ 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.

About

Decentralized-Voting-Blockchain-Node

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published