How to Implement a Simple Blockchain in Node.js

In this article, we will see how to build a basic blockchain from scratch using Node.js. The goal is to understand fundamental concepts such as blocks, hashing, and chain validation.

1. Requirements

Make sure you have Node.js installed. You can check with the command:

node -v

To get started, create a new project:

mkdir simple-blockchain
cd simple-blockchain
npm init -y

2. Creating the Block Model

Let's create a file blockchain.js and define a Block class:


const crypto = require('crypto');

class Block {
  constructor(index, timestamp, data, previousHash = '') {
    this.index = index;
    this.timestamp = timestamp;
    this.data = data;
    this.previousHash = previousHash;
    this.hash = this.calculateHash();
  }

  calculateHash() {
    return crypto
      .createHash('sha256')
      .update(this.index + this.timestamp + JSON.stringify(this.data) + this.previousHash)
      .digest('hex');
  }
}

3. Creating the Blockchain

Now let's define the Blockchain class to manage the chain of blocks:


class Blockchain {
  constructor() {
    this.chain = [this.createGenesisBlock()];
  }

  createGenesisBlock() {
    return new Block(0, Date.now().toString(), 'Genesis Block', '0');
  }

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

  addBlock(newBlock) {
    newBlock.previousHash = this.getLatestBlock().hash;
    newBlock.hash = newBlock.calculateHash();
    this.chain.push(newBlock);
  }

  isChainValid() {
    for (let i = 1; i < this.chain.length; i++) {
      const currentBlock = this.chain[i];
      const previousBlock = this.chain[i - 1];

      if (currentBlock.hash !== currentBlock.calculateHash()) {
        return false;
      }

      if (currentBlock.previousHash !== previousBlock.hash) {
        return false;
      }
    }

    return true;
  }
}

4. Usage Example

Now we can use our blockchain:


const myBlockchain = new Blockchain();
myBlockchain.addBlock(new Block(1, Date.now().toString(), { amount: 10 }));
myBlockchain.addBlock(new Block(2, Date.now().toString(), { amount: 25 }));

console.log(JSON.stringify(myBlockchain, null, 2));
console.log('Is blockchain valid?', myBlockchain.isChainValid());

Conclusions

This simple implementation shows how a blockchain works conceptually. It does not include features such as proof-of-work, a distributed network, or consensus mechanisms, but it provides a solid foundation to build on for further development.

Back to top