Build a Javascript Blockchain

Blockchain! It’s the mystical buzzword that every company is saying right now. At its core, the basic concept of blockchain is not hard to understand; it’s essentially a distributed linked list. It’s also used by the popular cryptocurrency called Bitcoin. The advantages of Blockchain is that it allows for a decentralized collection of data whose integrity is easily verifiable, and the data itself is immutable Keep in mind that a fully robust blockchain will also contain smart contracts, mining algorithms (proof of work/proof of stake) and other flavorful elements that you could enhance the chain with. For this tutorial, we are going to stick with the bare minimum. We are going to implement a pure Javascript Blockchain.

The Javascript Blockchain

Before we get started, let’s cover some basic concepts. A blockchain always starts off with an initial block called the genesis block. The contents of each block contain the following fields:

  1. Index
  2. Timestamp
  3. Data
  4. Nonce
  5. PreviousHash
  6. Hash

For this tutorial, we are going to exclude the nonce field because we will not be implementing a mining algorithm. The block’s hash is a SHA256 hash that is made from combining all the fields listed above. What’s cool about a blockchain is that every block will contain the hash of the previous block. This means that the chain becomes immutable. If any of the data in the previous blocks were to change, then the block would contain a new hash, resulting in an invalidation of the rest of the chain.

Block Class

Let’s start by creating a simple block class:

const crypto = require('crypto');

class Block {
 constructor(index, timestamp, data, previousHash) {
 this.index = index;
 this.previousHash = previousHash;
 this.timestamp = timestamp;
 this.data = data;
 this.hash = this.calculateHash();
 }
 // Calculating the Hash for the block
 calculateHash() {
 const stringToHash = this.index + this.previousHash + this.timestamp + JSON.stringify(this.data);
 return crypto.createHash('sha256').update(stringToHash).digest('hex');
 }
}

module.exports = Block;

This class’s constructor contains all the information that we would want for a new block. The only function in this class is calculateHash().  You will need to install the crypto library from npm to use the crypto.createHash function.

Blockchain Class

Create another class called blockchain. The purpose of this class is to hold the actual chain and provide us with some functions that we can use to interact with the blockchain. Start by adding the constructor:

const Block = require('./block');

class Blockchain {
 // Initialize Blockchain with genosis block
 constructor() {
 this.chain = [new Block(0, new Date().toUTCString(), 'I am the genosis block', '0')];
 }
}

module.exports = Blockchain;

Notice that in the constructor we initialize the chain as an array (that’s your only option for lists in Javascript). In this array, we have to provide a default genosis block. This block will have 0 for the previous hash because there are no blocks that come before it. Now let’s add in the rest of the methods we will need:

const Block = require('./block');

class Blockchain {
// Initialize Blockchain with genosis block
constructor() {
this.chain = [new Block(0, new Date().toUTCString(), 'I am the genosis block', '0')];
}
// Getting the hash of the latest block in the blockchain
getPreviousHash() {
return this.chain[this.chain.length - 1].hash;
}
// Adding a new block to the chain
addBlock(data) {
const timeStamp = new Date().toUTCString();
const index = this.chain.length;
const previousHash = this.getPreviousHash();
const newBlock = new Block(index, timeStamp, data, previousHash);
if (this.isValid(newBlock)) {
this.chain.push(newBlock);
} else {
console.log('Block is invalid');
}
}
// Checking to see if the new block is valid
isValid(newBlock) {
const currentBlock = this.chain[this.chain.length - 1];
if (currentBlock.index + 1 !== newBlock.index) {
return false;
} else if (newBlock.previousHash !== currentBlock.hash) {
return false;
} else if (newBlock.hash !== newBlock.calculateHash()) {
return false;
}
return true;
}

printChain() {
console.log(this.chain);
}
}

module.exports = Blockchain;

In this class, we created four functions. The getPreviousHash() function just returns the hash of the latest block in the chain. We need this because every new block needs to have the hash of the previous block. This function only gets called in the **addBlock() **function.

In the addBlock() function, we a parameter called data that can contain any arbitrary piece of data. We then set all the necessary information we need to form a new block. Before we add the block to the chain, we need to call the isValid() function.

The isValid() functions checks to see if the block has the correct hash, index and it’s previous hash is equal to the hash of the latest block in the blockchain. If all of this is true, then we return true and add the block to the blockchain. There’s also a print() function that allows us to print the chain.

App Class

Finally, create a class called app. This will be the class that we use to run the program. Here’s what it looks like:

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

const myChain = new Blockchain();
myChain.addBlock('Hey I am the second block');
myChain.addBlock('Hey I am the third block');
myChain.printChain();

That’s it! When you run the app class you should get an output that contains your chain. The output should have three blocks with the appropriate data in each block. That’s how to build a basic blockchain in javascript.

You can check out the full project on GitHub.