Build your first blockchain with nodeJS

Your first blockchain with NodeJS

Blockchain is a big buzz word which is heard a lot these days. But it’s like the movie interstellar, everyone thinks its cool but no one really gets it. I personally also don’t clearly understand how blockchain is implemented to solve actual problems. But I know how the data structure works and that is what we will deal with in this blog post.


According to Wikipedia,

A blockchain is a continuously growing list of records, called blocks, which are linked and secured using cryptography.

So basically, a blockchain is a data structure like linked lists with a growing set of nodes or blocks. Most of us would have learned about linked lists in school. Each node has several attributes including id, data, next node’s address etc. So, the blockchain is a slightly more complex data structure.

In a blockchain, each node is called a “block” and each block has an index, timestamp, hash of itself, hash of the previous block and of course the data. The data can be anything. In a cryptocurrency, the data is the details of the transaction like sender’s username, receiver’s username and amount.

Blockchain was initially implemented in 1991 to timestamp digital documents, to make sure they are not backdated or tampered with. But it didn’t get much attention as timestamping documents is not as cool as bitcoins.

The concept

The special thing about the blockchain is that it cannot easily be tampered with. The hash of each block gives it a unique identity like a fingerprint. And this hash is generated only once when the block is created. It is generated using the values of all the other attributes of the block. So, if any of the values are changed, the hash will no more be valid and hence the entire block will be invalid. So, this way nobody can tamper with the values stored in the block.

Another thing is if the hash is also recalculated, then it will not be detected as tampering. To avoid this, we store the hash of the previous block. This creates a chain of the blocks and if the hash of any block changes, the chain will be broken and the entire thing will be invalid. So, to successfully hack a blockchain, the hacker has to know the location of all blocks and simultaneously change all their hashes and relink the whole blockchain. This is not impossible but extremely tedious as there is a mandatory gap of 10 minutes between each transaction. So it beats the whole purpose of life.

"Block" diagram

These blockchains are not stored in a centralized server. But the blocks are distributed across the internet and they are connected using a peer-to-peer network. When someone joins the network, they are given the full copy of the network. When they create a new block, the block is sent to all the peers and the validity of the chain is checked. If everything checks out, the block is connected to the chain.

Let’s get to the code

We will be building a simple cryptocurrency called “cilcoin” (coding is love coin). So let’s get started on building possibly your very first blockchain.

  1. Create an empty directory anywhere on your computer. In that, create a new file called main.js.
  2. Create a class called “Block” which will represent a block in the chain. Give it a constructor with arguments as index, data and previous hash. Store the values of the arguments in consequent local variables. Create another attribute called timestamp and store the actual timestamp in it.
    // click on view source icon to copy code.
    class Block{
    	constructor(index, data, prevHash){
    		this.index = index;
                    this.timestamp = Math.floor( / 1000); = data;
    		this.prevHash = prevHash;
  3. Create a function inside the class and name it getHash. We will be using the sha256 algorithm to generate the hash. So import the required files. Inside the function, calculate the hash by using the other attributes as salt. Salts are basically just arbitary string values used for generating hashes. Return the calculated hash. Also, create an attribute in the constructor and store the calculated value by calling our function.
    constructor(index, data, prevHash){
    	this.index = index;
    	this.timestamp = Math.floor( / 1000); = data;
    	this.prevHash = prevHash;
    	this.hash = this.getHash();
    	return sha(JSON.stringify( + this.prevHash + this.index + this.timestamp);
  4. Now, lets create a new class to represent the entire block chain. This class will have a single attribute called “chain” which will hold an array of blocks.
    class BlockChain{
    		this.chain = [];
  5. Create a function in this class called addBlock. This will be responsible for adding a new block to the chain and it will take the data as it’s argument. Inside the function, calculate the index of the new block by getting the length of the existing chain. Get the hash of the last block in the chain(If the chain is empty, use “0” by default). 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.
    	let index = this.chain.length;
    	let prevHash = this.chain.length !== 0 ? this.chain[this.chain.length - 1].hash : 0;
    	let block = new Block(index, data, prevHash);
  6. Create another method in the same class and name it chainIsValid. In this function, we will be checking if the blockchain is following all the rules. It should have two checks as mentioned above. One, the validity of the hash, which can be done by comparing the stored hash with a newly calculated hash. If they match, then the values haven’t been tampered with. Then two, checking if the previousHash attribute is storing the same value as the hash of the previous block. This has to be performed on all the blocks in the chain.
    	for(var i=0;i<this.chain.length;i++){
    		if(this.chain[i].hash !== this.chain[i].getHash()) 
    			return false;
    		if(i > 0 && this.chain[i].prevHash !== this.chain[i-1].hash)
    			return false;
    	return true;
  7. We are now done with building the blockchain. Now we only have to add new blocks and test it.

Testing it

First lets test if the block chain is working without any errors. So, outside both the classes, create an object of the BlockChain class and name it CILCoin. Then, add a few blocks to it using the addBlock function.

const CILCoin = new BlockChain();

CILCoin.addBlock({sender: "Bruce wayne", reciver: "Tony stark", amount: 100});
CILCoin.addBlock({sender: "Harrison wells", reciver: "Han solo", amount: 50});
CILCoin.addBlock({sender: "Tony stark", reciver: "Ned stark", amount: 75});

console.log(JSON.stringify(CILCoin, null, 4));

Go to your console and run this using the command “node main.js”. You should be getting an output like this:

Now, let’s test the validity checker. Log the validity of the blockchain without tampering any block. Then tamper one of the blocks by changing its data. Then log the validity again.

console.log("Validity: ", CILCoin.chainIsValid());
CILCoin.chain[0].data.reciver = "Joker";
console.log("Validity: ", CILCoin.chainIsValid());

In the first case it will be true and in the second it will be false.

This concludes the tutorial. Hope you understood how this works. Looking forward to decentralization.

Author: Arjun Mahishi

Human by birth, machine by behaviour, geek by choice.

4 Thoughts

  1. Thanks for this article. It’s nicely written and simply explains the basis.

    Though is there a more details post you know of which explains the more detailed understanding of book-keeping of more complicated usages like Bitcoin ?


  2. I’m just learning about Linked Lists and have a question. I thought that the LinkedList data structure was a series of nested objects. If the BlockChain Class described above is storing node objects within an array, is that still a linked list?


    1. In a linked list, we have data about the previous/next node. Likewise, we have the hash of the previous node stored in each node. So, you can say that they are linked. Hence, it is a linked list.

Leave a Reply

Your email address will not be published. Required fields are marked *