Build Your Own Blockchain and Cryptocurrency with TypeScript

·

Creating your own blockchain and cryptocurrency might sound like a task reserved for elite developers or tech giants, but with the right tools and understanding, it’s entirely possible to build a functional prototype from scratch. In this guide, you’ll learn how to create a simple blockchain using Node.js and TypeScript, implement core cryptographic principles, and simulate a working cryptocurrency system complete with wallets, transactions, and mining.

Whether you're a developer exploring decentralized systems or someone curious about how cryptocurrencies work under the hood, this step-by-step tutorial will give you hands-on experience while reinforcing key concepts in blockchain technology.


Prerequisites

Before diving into the code, ensure your development environment meets the following requirements:

We'll use TypeScript for its strong typing and modern syntax, making our blockchain logic more maintainable and less error-prone.


Step 1: Initialize the Project

Start by setting up a new Node.js project:

npm init -y

Install TypeScript and Node.js type definitions:

npm install -D typescript @types/node

Create a tsconfig.json file in your project root to configure the TypeScript compiler:

{
  "compilerOptions": {
    "lib": ["es2020"],
    "module": "commonjs",
    "target": "es2019",
    "types": ["node"],
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}

Add a development script to package.json to automatically compile TypeScript on changes:

"scripts": {
  "dev": "tsc -w"
}

Now run npm run dev to start watching for file changes.

👉 Discover how real-world blockchains power digital assets today.


Step 2: Define the Transaction Class

The foundation of any cryptocurrency is the transaction. Each transaction represents a transfer of value between two parties.

Create an index.ts file as your entry point and import Node.js's built-in crypto module:

import * as crypto from 'crypto';

Now define the Transaction class:

class Transaction {
  constructor(
    public amount: number,
    public payer: string,
    public payee: string
  ) {}

  toString() {
    return JSON.stringify(this);
  }
}

This class holds the transaction amount, sender (payer), and recipient (payee). The toString() method serializes the object for hashing and digital signing.


Step 3: Build the Block Class

A block contains one or more transactions and links to the previous block via its hash, forming a chain.

Each block includes:

Here's the Block class:

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

The hash getter computes a SHA256 hash of the block’s contents, ensuring immutability — any change in data alters the hash completely.


Step 4: Implement the Blockchain (Chain) Class

The Chain class manages the entire blockchain. It starts with a genesis block and grows as new blocks are added.

Use a singleton pattern to ensure only one chain exists:

class Chain {
  public static instance = new Chain();
  public chain: Block[];

  constructor() {
    this.chain = [new Block('', new Transaction(1000, 'genesis', 'agp'))];
  }

  get lastBlock() {
    return this.chain[this.chain.length - 1];
  }
}

This initializes the chain with a genesis block that mints 1000 units of your cryptocurrency — essentially your "pre-mine."


Step 5: Create the Wallet Class

A wallet allows users to send and receive cryptocurrency using public-key cryptography.

Using RSA encryption, generate a key pair where:

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

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

The sendMoney method creates a transaction and signs it with the private key. This signature proves ownership without revealing the key.


Step 6: Finalize the Chain with Mining & Verification

Back in the Chain class, add methods to verify signatures and mine blocks:

addBlock(transaction: Transaction, senderPublicKey: string, signature: Buffer) {
  console.log("🐢 Sending TurtleCoin...");
  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);
    this.chain.push(newBlock);
  }
}

mine(nonce: number): 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 is confirmed!\n`);
      return solution;
    }
    solution++;
  }
}

This implements a Proof-of-Work system. Miners must find a number (solution) such that when combined with the nonce, the resulting MD5 hash starts with four zeros. This mechanism secures the network by making tampering computationally expensive.

👉 See how leading platforms handle blockchain validation at scale.


Step 7: Test Your Blockchain

At the bottom of index.ts, simulate some transactions:

const agp = new Wallet();
const jz = new Wallet();
const jb = new Wallet();

agp.sendMoney(50, jz.publicKey);
jz.sendMoney(23, jb.publicKey);
jb.sendMoney(5, jz.publicKey);

console.log(Chain.instance);

Run the script using node dist/index.js (after compilation), and watch your transactions get mined and added to the blockchain.

You’ll see output showing each mining process and finally a logged chain of cryptographically linked blocks — congratulations, you’ve built your own cryptocurrency!


Frequently Asked Questions

What is a blockchain in simple terms?

A blockchain is a secure, decentralized ledger that records transactions across multiple computers. Each record (or “block”) is linked to the previous one via cryptography, making it nearly impossible to alter past entries.

Can I create a real cryptocurrency like Bitcoin?

Yes — though this example is simplified, the core principles (transactions, hashing, mining, wallets) mirror real systems like Bitcoin. To launch a production-grade coin, you’d need consensus mechanisms, peer-to-peer networking, and robust security.

Is mining necessary for all blockchains?

Not all blockchains use mining. Some use alternative consensus models like Proof-of-Stake (PoS). Mining (Proof-of-Work) ensures security through computational effort but consumes significant energy.

How are wallets secured?

Wallets rely on asymmetric cryptography. The private key must remain secret — anyone who has it can spend funds. Never expose your private key in code or logs.

What prevents someone from spending the same coin twice?

Double-spending is prevented by validating each transaction against the existing blockchain. Since each block references the prior one, altering history would require re-mining all subsequent blocks — an infeasible task on large networks.

Can I monetize my own cryptocurrency?

While technically possible, launching a token involves legal, regulatory, and technical considerations. Most projects today use established blockchains (like Ethereum or Solana) via smart contracts rather than building chains from scratch.

👉 Explore secure ways to manage digital assets on trusted platforms.


Core Keywords

By following this guide, you’ve gained practical insight into how decentralized systems operate — from digital signatures to mining algorithms. Use this knowledge to explore more advanced topics like smart contracts, distributed nodes, or even launching tokens on existing ecosystems.