Skip to content

CryptoChain ⛓️ A full-stack blockchain & cryptocurrency system featuring PoW mining, digital signatures, real-time network analytics, a P2P sync layer, and a modern React dashboard. Built with Node.js, Redis/PubNub, and TDD throughout.

Notifications You must be signed in to change notification settings

InfiKnight-TGP/CloneChain

Repository files navigation

CryptoChain ⛓️

A full-stack blockchain and cryptocurrency implementation with real-time network analytics, proof-of-work mining, digital signatures, and a modern React interface. Built with test-driven development principles and featuring a peer-to-peer network architecture.

✨ Features

🔗 Core Blockchain

  • Proof-of-Work Mining: Dynamic difficulty adjustment targeting 1000ms block time
  • Digital Signatures: Cryptographic transaction signing using elliptic curve cryptography
  • Chain Validation: Automatic validation of blockchain integrity and consensus rules
  • Genesis Block: Hardcoded initial block with predefined hash and difficulty
  • Block Structure: Timestamp, hash, previous hash, nonce, difficulty, and transaction data

💰 Cryptocurrency Wallet

  • Wallet Generation: Public/private key pair using elliptic curve cryptography
  • Digital Signatures: Sign transactions with private keys
  • Balance Tracking: Starting balance of 1000 units per wallet
  • Transaction Creation: Send funds to other addresses with signature verification
  • Mining Rewards: 50 units reward for successfully mining a block

📊 Network Analytics Dashboard

  • Real-time Monitoring: Live performance metrics with auto-refresh (5s intervals)
  • Mining Analytics:
    • Current and average difficulty
    • Mining time distribution
    • Hash rate calculation
    • Difficulty trend analysis (increasing/decreasing/stable)
    • Blocks per minute
  • Transaction Metrics:
    • Pending and processed transaction counts
    • Throughput (tx/second)
    • Average transactions per block
  • Network Health:
    • Chain validity status
    • Mining performance (optimal/adjusting)
    • Target deviation from 1000ms
    • Uptime tracking
    • Chain replacement counter

🌐 Peer-to-Peer Network

  • Real-time Sync: Pub/Sub architecture for broadcasting blocks and transactions
  • Redis Integration: Local pub/sub with Redis (fallback to PubNub for distributed deployment)
  • Automatic Chain Replacement: Longest chain rule with validation
  • Transaction Pool Broadcasting: Real-time propagation of pending transactions
  • Multi-peer Support: Run multiple nodes on different ports

🎨 Modern React UI

  • Tailwind CSS Styling: Professional dark theme with responsive design
  • Interactive Dashboard: View blocks, transactions, and network analytics
  • Transaction Management: Create and broadcast transactions
  • Block Explorer: Browse blockchain with detailed block information
  • Transaction Pool: View pending transactions awaiting mining
  • Vintage Postcard Design: 3D flip cards with Material Symbols icons

🧪 Test-Driven Development

  • Jest Test Suite: Comprehensive unit and integration tests
  • Block Tests: Mining, validation, difficulty adjustment
  • Blockchain Tests: Chain replacement, validation, transaction handling
  • Wallet Tests: Transaction creation, signing, balance updates
  • Transaction Pool Tests: Transaction management, clearing

🛠️ Tech Stack

Backend

  • Runtime: Node.js
  • Framework: Express.js 4.16.3
  • Database/State: In-memory (Redis for pub/sub)
  • Cryptography: elliptic 6.4.1 (SECP256K1 curve)
  • Hashing: SHA-256 via crypto-js, hex-to-binary 1.0.1
  • Pub/Sub: Redis 2.8.0 or PubNub 4.21.6
  • Testing: Jest 23.6.0
  • Utilities: uuid 3.3.2, body-parser 1.18.3, request 2.88.0

Frontend

  • Framework: React 16.6.0
  • Build Tool: Parcel 1.10.3
  • Routing: React Router DOM 4.3.1
  • Styling: Tailwind CSS (via custom configuration)
  • Icons: Material Symbols (Google Icons)
  • Fonts: System fonts with custom configurations
  • Babel: ES6+ transpilation with class properties and object spread

Development Tools

  • Process Manager: nodemon 1.18.4
  • Concurrent Tasks: concurrently 8.2.2
  • Environment Variables: cross-env 5.2.0
  • Clean Builds: rimraf 5.0.10

🚀 Getting Started

Prerequisites

  • Node.js 12+ (tested with Node 18+)
  • Redis Server (optional, for local development)
  • npm or yarn package manager

Installation

  1. Clone the repository
git clone https://github.com/15Dkatz/cryptochain.git
cd cryptochain
  1. Install dependencies
npm install
  1. Start Redis (optional, for local pub/sub)
npm run start-redis
# Or manually: redis-server --daemonize yes
  1. Run the application

Production Mode (single node):

npm start
# Builds client and starts server on port 3000

Development Mode (with hot reload):

npm run dev
# Runs client dev server, Redis, and nodemon

Development with PubNub (cloud pub/sub):

npm run dev-pubnub
# Uses PubNub instead of Redis

Run Peer Node (additional node on random port):

npm run dev-peer
  1. Access the application

Running Tests

npm test
# Runs Jest in watch mode

📁 Project Structure

cryptochain/
├── app/
│   ├── pubsub.js                    # Redis pub/sub implementation
│   ├── pubsub.pubnub.js             # PubNub pub/sub (cloud alternative)
│   ├── transaction-miner.js          # Transaction mining logic
│   └── network-analytics.js          # Real-time analytics service
├── blockchain/
│   ├── block.js                      # Block class with PoW mining
│   ├── block.test.js                 # Block unit tests
│   ├── index.js                      # Blockchain class
│   └── index.test.js                 # Blockchain tests
├── wallet/
│   ├── index.js                      # Wallet class with key generation
│   ├── index.test.js                 # Wallet tests
│   ├── transaction.js                # Transaction class with signatures
│   ├── transaction.test.js           # Transaction tests
│   ├── transaction-pool.js           # Transaction pool management
│   └── transaction-pool.test.js      # Transaction pool tests
├── client/
│   └── src/
│       ├── index.js                  # React app entry + routing
│       ├── index.html                # HTML template
│       ├── index.css                 # Global styles + Tailwind
│       ├── history.js                # Browser history for routing
│       ├── assets/                   # Static assets
│       └── components/
│           ├── App.js                # Home/Dashboard
│           ├── Blocks.js             # Block explorer
│           ├── Block.js              # Individual block display
│           ├── ConductTransaction.js # Transaction creation
│           ├── Transaction.js        # Transaction display
│           ├── TransactionPool.js    # Mining interface
│           └── NetworkAnalytics.js   # Analytics dashboard
├── scripts/
│   └── performance-metrics.js        # CLI benchmarking tool
├── util/
│   ├── crypto-hash.js                # SHA-256 hashing utility
│   ├── crypto-hash.test.js           # Hash tests
│   └── index.js                      # Elliptic curve utilities
├── config.js                         # Network configuration constants
├── index.js                          # Express server + API routes
└── package.json                      # Dependencies and scripts

🎯 Configuration

Edit config.js to customize blockchain parameters:

const MINE_RATE = 1000;              // Target block time (ms)
const INITIAL_DIFFICULTY = 3;         // Starting difficulty
const STARTING_BALANCE = 1000;        // Initial wallet balance
const MINING_REWARD = 50;             // Reward per mined block

📡 API Endpoints

Blockchain Endpoints

GET  /api/blocks              # Get all blocks (paginated by 5)
GET  /api/blocks/length       # Get total block count
GET  /api/blocks/:id          # Get specific page of blocks

Wallet & Transactions

GET  /api/wallet-info         # Get wallet public key and balance
POST /api/transact            # Create new transaction
GET  /api/transaction-pool-map # Get pending transactions
GET  /api/mine-transactions    # Mine block with pending transactions

Network Analytics

GET  /api/analytics/metrics    # Complete metrics snapshot
GET  /api/analytics/difficulty # Difficulty analysis
GET  /api/analytics/health     # Network health status
GET  /api/analytics/report     # Formatted live report

Network Sync

GET  /api/known-addresses      # Get all wallet addresses
POST /api/mine                 # Mine single block (development)

💻 Usage Examples

Mine a Block

Navigate to Transaction Pool page and click "Mine Pending Transactions"

Create Transaction

  1. Go to Transactions page
  2. Enter recipient address
  3. Enter amount (must not exceed balance)
  4. Click "Submit Transaction"

View Network Analytics

Navigate to Network Analytics page to see:

  • Real-time mining performance
  • Transaction throughput
  • Network health metrics
  • Auto-refresh toggle (ON/OFF)

Run Performance Benchmarks

node scripts/performance-metrics.js

This will:

  • Mine 50 blocks and track performance
  • Analyze difficulty adjustment
  • Process 100 transactions
  • Validate blockchain 1000 times
  • Display network analytics report

🏗️ Architecture Highlights

Proof-of-Work Algorithm

  • Dynamic difficulty adjustment based on mining time
  • Target: 1000ms per block (configurable via MINE_RATE)
  • Difficulty increases if block mined too quickly
  • Difficulty decreases if block takes too long
  • SHA-256 hashing with leading zero requirement

Digital Signatures

  • SECP256K1 elliptic curve (same as Bitcoin)
  • Private key signs transaction data
  • Public key used for address
  • Signature verification prevents tampering

Consensus Rules

  1. Longest Chain: Network always accepts longest valid chain
  2. Chain Validation: Every block hash must be correct
  3. Hash Links: Each block references previous block hash
  4. Genesis Block: First block must match hardcoded genesis
  5. Difficulty Rules: Difficulty can only change by ±1

Real-time Sync

  • Broadcasts on two channels: BLOCKCHAIN and TRANSACTION
  • All peers receive new blocks and transactions instantly
  • Automatic chain replacement if longer valid chain found
  • Transaction pool cleared after mining

🎨 Recent UI Enhancements

Vintage Postcard Theme

  • ✅ Modern dark theme with Tailwind CSS
  • ✅ Material Symbols icons throughout
  • ✅ Responsive design for mobile/tablet/desktop
  • ✅ Smooth transitions and hover effects

Network Analytics Dashboard

  • ✅ Real-time metrics with 5-second auto-refresh
  • ✅ Clean card-based layout with visual indicators
  • ✅ Color-coded status (green/yellow/red)
  • ✅ Interactive buttons (auto-refresh toggle, manual refresh)
  • ✅ Comprehensive health monitoring

Navigation Updates

  • ✅ Consistent top navigation across all pages
  • ✅ Active page highlighting
  • ✅ Clean header with "Network Analytics" title
  • ✅ Links: Dashboard → Transactions → Blocks → Pool

📈 Performance Metrics

Typical performance on modern hardware:

  • Block Mining: ~1000ms (adjusted by difficulty)
  • Transaction Creation: <10ms
  • Signature Verification: <5ms
  • Chain Validation: ~1-2ms per block
  • Hash Rate: Varies by CPU (tracked in analytics)

🧪 Testing

The project includes comprehensive test coverage:

# Run all tests in watch mode
npm test

# Test coverage includes:
# - Block mining and validation
# - Difficulty adjustment logic
# - Blockchain replacement and validation
# - Transaction creation and signing
# - Transaction pool management
# - Cryptographic utilities
# - Wallet operations

🚢 Deployment

Single Server Deployment

  1. Build the client: npm run build-client
  2. Start the server: node index.js
  3. Set ROOT_NODE_ADDRESS environment variable for peers

Multi-Node Network

  1. Start root node: npm start (port 3000)
  2. Start peer nodes: npm run dev-peer (random ports)
  3. Peers automatically sync with root node via ROOT_NODE_ADDRESS

Environment Variables

PORT=3000                              # Server port
ROOT_NODE_ADDRESS=http://localhost:3000 # Root node for sync
USE_PUBNUB=true                         # Use PubNub instead of Redis
ENV=development                         # Development mode
GENERATE_PEER_PORT=true                # Auto-generate peer port

📚 Documentation

🤝 Contributing

This project is based on the Build a Blockchain and Cryptocurrency | Full-Stack Edition course by David Katz. Contributions and improvements are welcome!

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Write tests for your changes
  4. Ensure all tests pass (npm test)
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

📖 Learning Resources

🔮 Future Enhancements

  • 🔍 Transaction History: Per-wallet transaction logs
  • 📊 Advanced Analytics: Chart visualizations for metrics
  • 🌐 WebSocket Support: Replace pub/sub with WebSockets
  • 🔐 Enhanced Security: Rate limiting, DDoS protection
  • 💾 Persistent Storage: Database integration (PostgreSQL, MongoDB)
  • 🎨 Wallet UI: Enhanced wallet management interface
  • 📱 Mobile App: React Native mobile application
  • 🔗 Smart Contracts: Basic scripting capabilities
  • Performance: Merkle tree implementation
  • 🌍 Internationalization: Multi-language support

📜 License

ISC License

🙏 Acknowledgments

  • David Katz - Course creator and original implementation
  • Udemy - Course platform
  • Bitcoin Whitepaper - Blockchain and cryptocurrency concepts
  • Elliptic Curve Cryptography - SECP256K1 curve
  • React Community - Modern UI framework
  • Tailwind CSS - Utility-first styling

Built with ❤️ using Node.js, React, and blockchain technology

For issues or questions, please check the commit-by-commit course breakdown or open an issue on GitHub.

About

CryptoChain ⛓️ A full-stack blockchain & cryptocurrency system featuring PoW mining, digital signatures, real-time network analytics, a P2P sync layer, and a modern React dashboard. Built with Node.js, Redis/PubNub, and TDD throughout.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages