Building a blockchain from scratch might sound like a task reserved for elite developers at major tech firms, but with the right tools and understanding, anyone familiar with Node.js and TypeScript can create their own simple blockchain and cryptocurrency. This guide walks you through each step—designing core classes, implementing cryptographic security, and simulating mining—all in under 200 lines of clean, object-oriented TypeScript code.
Whether you're a developer exploring decentralized systems or a tech enthusiast curious about how cryptocurrencies work under the hood, this hands-on tutorial delivers practical insight into blockchain architecture, digital signatures, proof of work, and secure transactions.
Getting Started: Project Setup
Before diving into blockchain logic, ensure your development environment meets the following requirements:
- Node.js version 12 or higher
- Basic understanding of TypeScript and object-oriented programming
Start by initializing a new Node.js project in your preferred code editor (like VS Code):
npm init -yNext, install TypeScript and Node.js type definitions:
npm install -D typescript @types/nodeThe @types/node package enhances code readability and enables better IntelliSense support in your editor.
Create a tsconfig.json file in the project root to configure the TypeScript compiler:
{
"compilerOptions": {
"lib": ["es2020"],
"module": "commonjs",
"target": "es2019",
"types": ["node"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
}
}Finally, add a development script to automatically compile your TypeScript code in real time. Open package.json and include:
"scripts": {
"dev": "tsc -w"
}Now run npm run dev to start watching for changes and compiling your code into JavaScript.
👉 Discover how real-world blockchains handle transactions at scale.
Step 1: Building the Transaction Class
The foundation of any cryptocurrency is the transaction—a record of value being transferred between parties.
In this implementation, each Transaction has three properties:
amount: The quantity of cryptocurrency sentpayer: The sender’s public keypayee: The recipient’s public key
We also include a toString() method to serialize the transaction for hashing and signing.
class Transaction {
constructor(
public amount: number,
public payer: string,
public payee: string
) {}
toString() {
return JSON.stringify(this);
}
}This class ensures every transaction is structured consistently and ready for cryptographic verification.
Step 2: Designing the Block Class
A block contains one or more transactions and links to the previous block via its hash—forming a chain.
Our simplified Block includes:
prevHash: Hash of the previous blocktransaction: The transaction it recordsts: Timestamp for chronological orderingnumOnlyUsedOnce(nonce): A random number used in mining
Using Node.js's built-in crypto module, we compute a SHA-256 hash of the block’s contents:
import * as crypto from 'crypto';
class Block {
public numOnlyUsedOnce = Math.round(Math.random() * 999999999);
constructor(
public prevHash: string,
public transaction: Transaction,
public ts = Date.now()
) {}
get hash() {
const str = JSON.stringify(this);
const hash = crypto.createHash('SHA256');
hash.update(str).end();
return hash.digest('hex');
}
}This hash ensures data integrity—any change to the block invalidates its hash and breaks the chain.
Step 3: Creating the Blockchain with the Chain Class
The Chain class manages the entire blockchain. It follows the singleton pattern, ensuring only one instance exists:
class Chain {
public static instance = new Chain();
public chain: Block[] = [];
constructor() {
// Genesis block — first block in the chain
this.chain = [new Block('', new Transaction(100, 'genesis', 'godwin'))];
}
}We include a getter to easily access the latest block:
get lastBlock() {
return this.chain[this.chain.length - 1];
}Adding New Blocks
To add a block, we verify the transaction using digital signatures (covered in the Wallet section). Once verified, a new block is created and appended:
addBlock(transaction: Transaction, senderPublicKey: string, signature: Buffer) {
const verifier = crypto.createVerify('SHA256');
verifier.update(transaction.toString());
const isValid = verifier.verify(senderPublicKey, signature);
if (isValid) {
console.log("✅ Transaction is valid!");
const newBlock = new Block(this.lastBlock.hash, transaction);
this.mine(newBlock.numOnlyUsedOnce); // Mine before adding
this.chain.push(newBlock);
}
}Proof of Work: Mining Blocks
To simulate mining, we implement a simplified proof of work algorithm. Miners must find a number (solution) such that when combined with the nonce, the MD5 hash starts with four zeros (0000):
mine(nonce: number) {
let solution = 1;
console.log('⛏️ Mining transaction...');
while (true) {
const hash = crypto.createHash('MD5');
hash.update((nonce + solution).toString()).end();
const attempt = hash.digest('hex');
if (attempt.substr(0, 4) === '0000') {
console.log(`✅ Solved transaction with solution: ${solution}. Block confirmed!`);
return solution;
}
solution++;
}
}This mechanism secures the blockchain by making tampering computationally expensive.
Step 4: Implementing Wallets with Public-Key Cryptography
A wallet allows users to send and receive cryptocurrency securely using RSA key pairs:
- Private key: Used to sign transactions (must be kept secret)
- Public key: Shared with others to receive funds
The wallet generates keys during initialization:
class Wallet {
public publicKey: string;
public privateKey: string;
constructor() {
const keypair = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
});
this.privateKey = keypair.privateKey;
this.publicKey = keypair.publicKey;
}
}To send money, the wallet signs the transaction with its private key:
sendMoney(amount: number, payeePublicKey: string) {
const transaction = new Transaction(amount, this.publicKey, payeePublicKey);
const sign = crypto.createSign('SHA256');
sign.update(transaction.toString()).end();
const signature = sign.sign(this.privateKey);
Chain.instance.addBlock(transaction, this.publicKey, signature);
}Only someone with the correct private key can authorize a transaction—ensuring security and authenticity.
👉 See how leading platforms secure digital assets today.
Final Code Summary
Here's the complete implementation:
import * as crypto from 'crypto';
// Transaction Class
class Transaction { /* ... */ }
// Block Class
class Block { /* ... */ }
// Chain Class
class Chain { /* ... */ }
// Wallet Class
class Wallet { /* ... */ }Testing Your Blockchain
Add test transactions at the bottom of index.ts:
const wallet1 = new Wallet();
const wallet2 = new Wallet();
const wallet3 = new Wallet();
wallet1.sendMoney(50, wallet2.publicKey);
wallet2.sendMoney(23, wallet3.publicKey);
wallet3.sendMoney(5, wallet2.publicKey);
console.log(Chain.instance);Run the script with npm run dev. You’ll see output showing each transaction being mined and added to the chain.
Frequently Asked Questions
Q: Can I use this blockchain in production?
No. This is an educational model designed to illustrate core concepts. Real-world blockchains include consensus algorithms, peer-to-peer networking, persistent storage, and advanced security layers.
Q: What makes a blockchain secure?
Security comes from cryptographic hashing, digital signatures, and proof of work. Changing any block would require re-mining all subsequent blocks—a near-impossible task on large networks.
Q: Why use SHA-256 over MD5?
SHA-256 is more secure and collision-resistant. We use MD5 only for mining simulation due to its speed; real systems use stronger algorithms.
Q: How do wallets prevent theft?
Wallets rely on private keys. If your private key is compromised, so is your cryptocurrency. Always store it securely—never share it.
Q: What is the purpose of the genesis block?
The genesis block is the first block in a blockchain. It initializes the system and often contains an initial supply of cryptocurrency (like Bitcoin’s 50 BTC reward).
Q: Can I expand this project?
Absolutely! Enhance it by adding:
- Peer-to-peer networking
- REST API for transactions
- Wallet balance tracking
- Difficulty adjustment in mining
👉 Explore advanced blockchain tools used by developers worldwide.
Core Keywords
- blockchain development
- create cryptocurrency
- TypeScript blockchain
- proof of work
- digital signatures
- RSA encryption
- SHA-256 hashing
- Node.js crypto
By following this guide, you've built a functional understanding of how decentralized ledgers operate—from transaction creation to mining and validation. While simple, this model encapsulates the principles behind giants like Bitcoin and Ethereum.