A complete, production-ready blockchain implementation designed specifically for hosting custom tokens. Built with TypeScript and Node.js, featuring smart contracts, P2P networking, mining, REST API, CLI, and web dashboard.
- Proof of Work (PoW) Consensus: Secure mining with difficulty adjustment
- Token System: Native token support with custom token creation
- Transaction Validation: Cryptographic validation and signature verification
- Chain Validation: Full blockchain integrity verification
- Contract Deployment: Deploy custom contracts to the blockchain
- Contract Execution: Execute contract functions with sandboxed environment
- State Management: Persistent contract state storage
- Token Balance Management: Contract-level token balance tracking
- P2P Network: Decentralized node communication
- Block Synchronization: Automatic chain sync with peers
- Transaction Broadcasting: Real-time transaction propagation
- Peer Discovery: Connect to other blockchain nodes
- REST API: Complete HTTP API for blockchain interaction
- CLI Tool: Command-line interface for blockchain management
- Web Dashboard: Real-time monitoring and control interface
- Node.js 16.x or higher
- npm or yarn package manager
- TypeScript 5.x
- Clone the repository:
git clone <repo-url>
cd blockchain- Install dependencies:
npm install- Build the project:
npm run buildEdit .env file to configure:
# Mining difficulty (higher = harder)
DIFFICULTY=4
# Average block time in milliseconds
BLOCK_TIME=10000
# Mining reward per block
REWARD_PER_BLOCK=100
# P2P Network settings
P2P_HOST=localhost
P2P_PORT=8000
# API Server settings
API_PORT=3000
# Dashboard settings
DASHBOARD_PORT=8080npm run nodeThis will start:
- REST API on port 3000
- P2P network on port 8000
npm run dashboardOpen http://localhost:8080 in your browser to access the web dashboard.
# Get blockchain information
npm run blockchain -- info
# Display blockchain
npm run blockchain -- chain --limit 10
# Get address balance
npm run blockchain -- balance 0x1234... NATIVE_TOKEN
# Create a transaction
npm run blockchain -- tx 0xfrom 0xto 100 NATIVE_TOKEN
# Mine pending transactions
npm run blockchain -- mine 0xminer
# Mint tokens
npm run blockchain -- mint 0xaddress 1000 TOKEN_ID
# Burn tokens
npm run blockchain -- burn 0xaddress 100 TOKEN_ID
# Generate keypair
npm run blockchain -- keygen
# Sign a message
npm run blockchain -- sign "message" "private_key"
# Verify a signature
npm run blockchain -- verify "message" "signature" "public_key"
# Deploy smart contract
npm run blockchain -- deploy 0xcreator
# Reset blockchain
npm run blockchain -- resetGET /health- Server health checkGET /blockchain/info- Blockchain statisticsGET /blockchain/chain- Get entire blockchainGET /blockchain/block/:height- Get block by heightGET /blockchain/block-hash/:hash- Get block by hash
GET /transactions/pending- Get pending transactionsPOST /transactions- Create new transactionPOST /mint- Mint tokens (admin)POST /burn- Burn tokens
GET /balance/:address- Get all balancesGET /balance/:address/:tokenId- Get specific token balance
GET /crypto/keypair- Generate new keypairPOST /crypto/sign- Sign a messagePOST /crypto/verify- Verify a signature
POST /contracts/deploy- Deploy contractGET /contracts/:address- Get contractPOST /contracts/:address/call- Call contract function
GET /network/info- Network statisticsGET /network/node- Node informationPOST /network/peers- Connect to peerGET /network/peers- Get connected peers
npm run blockchain -- keygen
# Save the generated address and private keynpm run blockchain -- mint 0xonlyouraddress 1000 MY_TOKENnpm run blockchain -- tx 0xyouraddress 0xrecipient 100 MY_TOKENnpm run blockchain -- mine 0xmineraddressnpm run blockchain -- balance 0xrecipient MY_TOKENNode 1 (Primary):
npm run node
# Listen on port 8000Node 2 (Secondary):
P2P_PORT=8001 npm run nodeVia REST API:
curl -X POST http://localhost:3000/network/peers \
-H "Content-Type: application/json" \
-d '{
"peerId": "node2-id",
"host": "localhost",
"port": 8001
}'const tokenContract = `{
initialize(owner) {
this.state.owner = owner;
this.state.totalSupply = 0;
this.state.balances = {};
return { success: true };
},
mint(amount) {
if (context.sender !== this.state.owner) {
throw new Error('Only owner can mint');
}
this.state.totalSupply += amount;
this.state.balances[context.sender] = (this.state.balances[context.sender] || 0) + amount;
return { success: true, totalSupply: this.state.totalSupply };
},
transfer(to, amount) {
const from = context.sender;
const fromBalance = this.state.balances[from] || 0;
if (fromBalance < amount) {
throw new Error('Insufficient balance');
}
this.state.balances[from] -= amount;
this.state.balances[to] = (this.state.balances[to] || 0) + amount;
return { success: true, to, amount };
},
balanceOf(account) {
return this.state.balances[account] || 0;
}
}`;
// Deploy via REST API
curl -X POST http://localhost:3000/contracts/deploy \
-H "Content-Type: application/json" \
-d '{
"creator": "0xcontractCreator",
"code": "'"$tokenContract"'"
}'curl -X POST http://localhost:3000/contracts/0xcontractaddress/call \
-H "Content-Type: application/json" \
-d '{
"functionName": "transfer",
"args": ["0xrecipient", 100],
"sender": "0xcaller"
}'blockchain/
βββ src/
β βββ core/ # Core blockchain logic
β β βββ blockchain.ts # Main blockchain implementation
β β βββ crypto.ts # Cryptographic utilities
β β βββ smartContract.ts # Smart contract VM
β β βββ types.ts # TypeScript interfaces
β βββ network/ # P2P networking
β β βββ p2p.ts # P2P node implementation
β βββ api/ # REST API
β β βββ server.ts # Express API server
β βββ cli/ # Command-line interface
β β βββ blockchain.ts # CLI entry point
β β βββ blockchainCLI.ts # CLI commands
β βββ node/ # Node runner
β β βββ node.ts # Main node class
β βββ dashboard/ # Web dashboard
β β βββ server.ts # Dashboard server
β βββ public/ # Static files
β β βββ index.html # Dashboard UI
β βββ index.ts # Application entry point
βββ dist/ # Compiled JavaScript
βββ package.json # Dependencies and scripts
βββ tsconfig.json # TypeScript configuration
βββ .env # Configuration
βββ .gitignore # Git ignore rules
βββ README.md # This file
interface Block {
index: number;
timestamp: number;
transactions: Transaction[];
previousHash: string;
hash: string;
nonce: number;
miner: string;
difficulty: number;
}interface Transaction {
id: string;
fromAddress: string;
toAddress: string;
amount: number;
tokenId: string;
timestamp: number;
signature?: string;
data?: any;
}interface SmartContract {
id: string;
address: string;
creator: string;
code: string;
state: any;
balance: { [tokenId: string]: number };
createdAt: number;
deploymentBlockHeight: number;
}- Cryptographic Hashing: SHA-256 for block hashing
- Digital Signatures: ECDSA (secp256k1) for transaction signing
- Proof of Work: Difficulty-based consensus mechanism
- Chain Validation: Full blockchain integrity verification
- Signature Verification: Cryptographic transaction validation
# Run tests
npm test
# Run with coverage
npm test -- --coverage- Block Time: ~10 seconds (configurable)
- Transaction Throughput: ~100 transactions per block
- Mining Speed: Depends on difficulty setting
- Network Latency: Peer-dependent
# Change ports in .env
API_PORT=3001
P2P_PORT=8001
DASHBOARD_PORT=8081# Reduce difficulty in .env
DIFFICULTY=2# Check P2P network configuration
npm run blockchain -- infoMIT License - See LICENSE file for details
Contributions are welcome! Please feel free to submit a Pull Request.
This is an educational blockchain implementation designed for learning purposes. For production use, additional security audits and optimizations are recommended.
For issues or questions, please open an issue on GitHub.
Built with β€οΈ using TypeScript and Node.js