Building a blockchain

Blockchain is a immutable globally distributed ledger which depends on the resources of a peer-to-peer network. Simply put, think of the Blockchain as a really long spreadsheet.

Read this for a primer on Blockchain. If you are already familiar, read along.

We’ll use Javascript to write a small blockchain. The point is to learn by doing and understand how a blockchain works. You can find a link to the complete code towards the end of this article.

I’m calling this Blockchain koreCoin. You can call it anything.

Step 1: Create the folder structure and main.js

Step 2: Create a block

In the Block class, we create a constructor and assign it some properties.

The constructor has the following properties

  1. index
    This property is optional and tells you where the block sits on the chain.
  2. timestamp
    As the name indicates, this property assigns a time stamp to the block that is created.
  3. data
    This property stores any type of data that you might want to store like currency transactions such as how much money was transferred and who was the sender and recipient. You can also store other types of data like energy consumption, dog names, etc.
  4. previousHash
    We create a previousHash property that contains a string that stores the hash value of the previous block.

We will keep track of the properties in our constructor as follows. We also will add another property to our constructor called hash. We will set it as empty.

Step 3: Calculate the Hash value of the block

The calculateHash function as the name suggests calculates the hash value of the block. In this case, we take the properties on the block mentioned earlier and run it through the hash function.

Simply put, the calculateHash function does the following:
this.hash = this.index + this.previousHash + this.timestamp +

The above function is too simplistic and would return an inconsistent datatype. To ensure consistency, we will convert the return value into a string:
this.hash = ( this.index + this.previousHash + this.timestamp + JSON.stringify( ).toString();

The above function too is not robust enough. So we run it through a hash function. In this case we’ll use a SHA256 hash function.

The SHA256 hash function doesn’t come preinstalled. Here’s how you’d install it.

  1. First you need to install node and npm. Here’s how to do it.
  2. Now that you’ve installed npm. In the terminal app, go to the folder where you’ve saved your blockchain code and type the following command
    sudo npm install --save crypto-js
installing crypto npm package to import SHA256 library

Now that we have the SHA256 function installed, we need to import the library in our blockchain code as follows:

Our hash function now looks like this
this.hash = SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(;

Our block code now looks like this

Step 4: Create a Blockchain class

  1. constructor
    The constructor function initializes the blockchain.
    this.chain = [this.createGenesisBlock()];

    In this function we initialize an array of blocks.
  2. createGenesisBlock
    The first block on the blockchain is called a genesis block. We add this block manually by calling the createGenesisBlock function.
    return new Block(0, “02/01/2018”, “Genesis Block”, “0”);
    The function returns a block with an index value, date of creation, any data (in this case we choose a string called Genesis Block) and a starting previousHash value of 0. All these values can be anything you want.
  3. getlatestBlock
    This is a really simple method which returns the latest block from the chain.
    return this.chain[this.chain.length — 1];
  4. addBlock
    This method adds a new block to the chain. However, we need to do a few things before a block can be added.
    First we need to get the hash value of the previous block as follows:
    newBlock.previousHash = this.getlatestBlock().hash;
    Then we need calculate the hash of the new block
    newBlock.hash = newBlock.calculateHash();
    Now we can push this block to the chain
    Finally our method looks like this
    newBlock.previousHash = this.getlatestBlock().hash;
    newBlock.hash = newBlock.calculateHash();
  5. isChainValid
    The most important property of the blockchain is it’s immutability. We use this method to verify the integrity of the blockchain. The method returns true if the chain is valid and false if the integrity of the chain is compromised.
    In this method, we loop through the entire blockchain starting from the second block, since the first block is the genesis block and hence redundant.
    for(let i = 1; i < this.chain.length; i++)
    //if something is wrong, then return false
  6. //else return true
    We create two constants called currentBlock and previousBlock as follows in the for loop.
    const currentBlock = this.chain[i];
    const previousBlock = this.chain[i-1];

    In the for loop, we now check for validity of the hash calculations by tallying the currentBlock’s hash value in the chain with the calculated hash value of the currentBlock
    if(currentBlock.hash !== currentBlock.calculateHash())
    {return false;}
    Then we check whether the currentBlock points to the correct previousBlock. We do this by tallying the previousHash property of our current block with the previousBlock’s hash.
    if(currentBlock.previousHash !== previousBlock.hash)
    {return false;}

    If the blockchain passes through the for loop without returning a false value, we return true.
    return true;
    Finally, this is how the isChainValid method looks like:
    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;


The Blockchain class now looks like this:

Step 5: Create a Blockchain

let koreCoin = new Blockchain();

We will add a few blocks to the koreCoin blockchain

We’ve just created a Blockchain.

Now it’s time for a stress test

Stress test

In the terminal app, go to the folder where you’ve saved your blockchain code and type the following command
node main.js
Where main.js is the name of your blockchain file.

It will return a JSON somewhat like this

koreCoin returns a JSON string on the Terminal

Tampering with the chain

console.log(‘Is Blockchain valid? ‘ + koreCoin.isChainValid());

terminal log

Result. On tampering with the chain and changing one of the values, the isChainValid function returns false implying that the chain is not valid.

Tampering with the chain smartly

koreCoin.chain[1].data = { amount: 100 };
koreCoin.chain[1].hash = koreCoin.chain[1].calculateHash();

Result. On tampering with the chain and changing one of the values, the isChainValid function returns false implying that the chain is not valid. This is because even though we recalculate the hash value of the current block, it’s relationship with the previous block is broken. A hacker will have to recalculate the entire chain to edit or delete a value.

In case of a distributed blockchain like Bitcoin or Ethereum, the hacker would have to recalculate the hashes of all the blocks and it’s copies over the network to tamper with the blockchain even slightly. This would require the computing power of more than all the world’s supercomputers. This is practically impossible.

Read about Merkel trees to know more about how this works.

Congratulations! You have now implemented an almost immutable Blockchain on your machine.

Link to complete code

We will implement a proof of work going forward.

If you liked this article, please click the 👏 button (once, twice or more).
Share to help others find it!

Closet Zen master. Part cyborg.