node-jssolidityBlockchain

Build Your Own Bitcoin

Author

Taylor Segell

Picture of the author
Published
Published on
image alt attribute

How to Build Your Own Bitcoin

This is a simple guide to building a cryptocurrency blockchain in Node.js.

Ever wondered what makes Bitcoin tick? At its core, Bitcoin is just a blockchain—a decentralized ledger where each transaction is recorded securely and transparently. In this tutorial, we’ll demystify blockchain technology by creating a simple cryptocurrency using Node.js. Let’s get started!


Prerequisites

Before we dive in, ensure you have:

  • Node.js installed on your computer.
  • Basic understanding of JavaScript.
  • A curious mind ready to explore blockchain fundamentals!

Step 1: Setting Up Your Project

First, create a new project directory and initialize it:

mkdir simple-crypto  
cd simple-crypto  
npm init -y  

This creates a new Node.js project. Next, install the crypto package for generating hashes:

npm install crypto  

Step 2: Creating the Blockchain Class

In blockchain technology, data is stored in "blocks" that are linked together in a "chain." Let’s create a Blockchain class in a file named blockchain.js:

const crypto = require('crypto');

class Blockchain {
    constructor() {
        this.chain = []; // Array to store blocks
        this.pendingTransactions = []; // Array to store new transactions
        this.createBlock(1, '0'); // Genesis block
    }

    createBlock(nonce, previousHash) {
        const block = {
            index: this.chain.length + 1,
            timestamp: Date.now(),
            transactions: this.pendingTransactions,
            nonce,
            previousHash,
        };

        this.pendingTransactions = [];
        this.chain.push(block);
        return block;
    }

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

    addTransaction(sender, receiver, amount) {
        const transaction = { sender, receiver, amount };
        this.pendingTransactions.push(transaction);
    }

    hashBlock(nonce, previousHash, transactions) {
        const data = nonce + previousHash + JSON.stringify(transactions);
        return crypto.createHash('sha256').update(data).digest('hex');
    }

    proofOfWork(previousHash, transactions) {
        let nonce = 0;
        let hash;
        do {
            nonce++;
            hash = this.hashBlock(nonce, previousHash, transactions);
        } while (!hash.startsWith('0000')); // Mining condition
        return nonce;
    }
}

module.exports = Blockchain;

Here’s what’s happening:

  1. Blocks: Each block contains transactions, a timestamp, a nonce (proof of work), and the hash of the previous block.
  2. Genesis Block: The first block in the chain is created manually.
  3. Proof of Work: This ensures that creating a new block requires computational effort (mining).

Step 3: Testing Your Blockchain

Let’s test our blockchain in a main.js file:

const Blockchain = require('./blockchain');

const myBlockchain = new Blockchain();

// Add transactions
myBlockchain.addTransaction('Alice', 'Bob', 50);
myBlockchain.addTransaction('Bob', 'Charlie', 25);

// Mine a new block
const previousHash = myBlockchain.getLastBlock().previousHash;
const nonce = myBlockchain.proofOfWork(previousHash, myBlockchain.pendingTransactions);
myBlockchain.createBlock(nonce, previousHash);

console.log(JSON.stringify(myBlockchain, null, 2));

Run the script:

node main.js  

You’ll see a simple blockchain printed to your console! Each block will have:

  • Transactions: The data being recorded.
  • Previous Hash: The hash of the preceding block, ensuring immutability.
  • Nonce: The number used to solve the proof-of-work puzzle.

Step 4: Expanding Your Crypto

Want to take this further? Here are a few ideas:

  1. Add Validations: Ensure transactions follow rules, like preventing double spending.
  2. Network: Create a peer-to-peer network where nodes communicate and share blocks.
  3. Wallets: Use cryptographic keys to create unique wallets for users.

Conclusion

Building a blockchain from scratch might sound daunting, but as you’ve seen, the basic structure is quite straightforward. By breaking it into steps, you can demystify the concepts and gain a deeper understanding of what powers Bitcoin and other cryptocurrencies.

Now go ahead—play with the code, customize it, and maybe even mint your own “coin”!

Newsletter

Stay tuned

Articles, links, and notes on data, AI, and building—roughly weekly in your inbox.