Build a Tiny Blockchain with Nodejs - Chapter 1

3 minute read

The basic concept of a blockchain is very simple, Blockchain is a distributed database that maintains a growing list of ordered records that anyone can read. Nothing special, but they have an interesting property, they are immutable, once a block has been added to the chain, it cannot be changed anymore without invalidating the rest of the chain.

That is the reason why cryptocurrencies are based on blockchains. You don’t want people changing their transactions after they’ve made them.

I think you get the general idea of a blockchain.

Build a Block

A blockchain consists of many blocks that are linked together. The chaining of blocks happens in a way that allows us to detect once someone has manipulated any of the previous blocks.

Each block contains a hash that is computed based on its contents. It also contains the hash of the previous block.

This is what a Block class look like in JavaScript code:

var SHA256 = require('crypto-js/sha256');

class Block {
  constructor(index, data, prevHash) {
    this.index = index;
    this.timestamp = Math.floor(Date.now() / 1000);
    this.data = data;
    this.prevHash = prevHash;
    this.hash = this.calculateHash();
  }

  calculateHash() {
    return SHA256(JSON.stringify(this.data) + this.prevHash + this.index + this.timestamp).toString();
  }
}

constructor

A block consists of several properties: index, timestamp, data, prevHash, and hash.:

  • index is used to tell us at what position the block on the chain.
  • timestamp is used to indicated the moment the block got created.
  • data is used to stored data.
  • prevHash is used to stored the hash of previous block.
  • hash is used to stored the its block hash.

calculateHash()

The hash is calculated using the sha256() functionality offered by the crypto-js package. We simply take the data, previous hash, index and timestamp as input for the creation of a new hash.

Building the Chain

We are ready to start building our blockchain. Here’s what that look like in JavaScript code:

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

  createGenesisBlock() {
    return new Block(0, "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;
  }
}

We’ve initialized the chain by creating an array that contains the genesis block. The first block has no previous block. We’ve created three methods are getLatestBlock(), addBlock() and chainIsValid() as well:

  • getLatestBlock() returns the latest block of the chain.
  • addBlock() this will be responsible for adding a new block to the chain. Inside the function, add the hash of the previous block to the new block with the value of the last block in the chain. Finally, create a new object of the Block class and plug in the calculated values in the constructor. Push this object into the chain array.
  • chainIsValid() this will be responsible for ensuring that no one has messed up with the blockchain. It loops over all the blocks and checks if the hash of each block is correct. It also checks if each block points to the correct previous block by comparing the previousHash value. If everything checks out it returns true and if something goes wrong it returns false.

Testing

First lets test if the blockchain is working without any errors. Create an object of the BlockChain class and name it myCoin. Then add a few blocks to it using addBlock() function:

let myCoin = new Blockchain();

myCoin.addBlock(new Block(1, { amount: 4 }));
myCoin.addBlock(new Block(2, { amount: 8 }));

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

// Check if chain is valid (will return true)
console.log('Blockchain valid? ' + myCoin.isChainValid());

As we said blocks can’t be changed once they are added. lets tamper one of the blocks by changing its data:

myCoin.chain[1].data = { amount: 100 };

// Check the chain again (will now return false)
console.log("Blockchain valid? " + myCoin.isChainValid());

You can download the source code and try it out on Github.

Categories:

Updated: