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.

Introduction

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(Date.now() / 1000);
    		this.data = 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(Date.now() / 1000);
    	this.data = data;
    	this.prevHash = prevHash;
    	this.hash = this.getHash();
    }
    
    getHash(){
    	return sha(JSON.stringify(this.data) + 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{
    	constructor(){
    		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.
    addBlock(data){
    	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);
    
    	this.chain.push(block);
    }
    
  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.
    chainIsValid(){
    
    	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:
Output

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.

Arjun Mahishi
1 1 vote
Article Rating
Subscribe
Notify of
guest

19 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
JP
JP
6 years ago

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 ?

JP

Brian H
Brian H
6 years ago

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?

Thanks!

Prateek
6 years ago
Reply to  Arjun Mahishi

no it is not linked list , as for every merkel data in original blockchain it is different .

for more info check blockchain transactions and the height of the trees there is change in the number of front zero very time ..

starting was done with 00000 zero now it reached a height of 21 zeros .

Kannan D
Kannan D
6 years ago

how to inject sha() function and in node, we are using class structure which is not executed as expected and please share the real snippet for injecting for sha().

Kannan D
Kannan D
6 years ago

“use strict”;
var sha1 = require(‘sha256’);
class Block {
constructor(index, data, prevHash) {
this.index = index;
this.data = data;
this.preHash = prevHash;
this.timestamp = Math.floor(Date.now() / 1000);
this.hash = this.getHash();
}

getHash() {
return sha1(JSON.stringify(this.data) + this.preHash + this.index + this.timestamp);
}

}

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

addBlock(data) {
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);
this.chain.pop(block);
}

ChainIsValid() {
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].preHash !== this.chain[i - 1].hash)
return false;
}
return true;
}

}

const CILCoin = new BlockChain();
CILCoin.addBlock({sender:”Kannan”, receiver:”YYYY”, amount :1000});
CILCoin.addBlock({sender:”Kannan1″, receiver:”ZZZZ”, amount :2000});
CILCoin.addBlock({sender:”Kannan2″, receiver:”AAAA”, amount :3000});
console.log(JSON.stringify(CILCoin, null,4));

OUTPUT:
am getting:
{
“chain”: []
}
Please help for this and am not getting the real data as you have mentioned the article.

Kannan D
Kannan D
6 years ago
Reply to  Kannan D

typo error: this.chain.pop(block); i have got the response strutucre.

Mohd Javed
Mohd Javed
6 years ago

getting the error when running node main.js file
module.js:549
throw err;
^

Error: Cannot find module ‘sha256’
at Function.Module._resolveFilename (module.js:547:15)
at Function.Module._load (module.js:474:25)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object. (C:\Users\Dev 3\Desktop\ccoin\main.js:2:12)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)

Puvi
Puvi
6 years ago

hi, you have to install npm package crypto-js

Dev
Dev
6 years ago

It would be better if you put a working demo of the same.

Juliette
6 years ago

Thank you for this awesome tutorial Arjun!

I just wanted to mention (for anyone who is getting the Error: Cannot find module 'sha256' function) that NPM is not needed for the Crypto module because it is a native module that is available via Node.js. To include Crypto and to create the hash, all that is needed is this code:

‘use strict’;

const crypto = require(‘crypto’);

const secret = ‘abcdefg’;
const sha1 = crypto.createHmac(‘sha256’, secret)//create the hash
.update(‘I love cupcakes’)
.digest(‘hex’);
console.log(sha1);

Then in the constructor function that is within the Block class, instead of calling the getHash() function to create the hash simply append sha1 (hash) to the constructor like so:

this.hash = this.sha1;
…instead of this.hash = this.getHash();

This is what worked for me.

Thanks for helping me to gain a better understanding of what Blockchain is!

Cheers!

Juliette

chris
chris
6 years ago

thanks for your article.do you have any other materials to study blockchain.some deep learning of it.

Aum Patel
3 years ago

i like this blog this is very help full for me 

Akeo Blockchain Consultancy

Blockchain technology has become more than a buzzword. It is enabling the development of digital currencies that can stand tall against the fiat currency world we live in. We just need to explore the technology to its full potential and see what we can make out of it. Innovation is the key.

Andy Globe
1 year ago

Build a blockchain with Node.js using cryptography, proof of work, and transaction verification. Test & ensure security before deployment.

Aesha Shah
1 year ago

Thanks for sharing such useful content

Herbert
1 year ago

Wow, this tutorial on building a blockchain with Node.js is fantastic! The step-by-step instructions and clear explanations made it easy for me to understand the core concepts of blockchain technology. Node.js’s simplicity and efficiency combined with the power of blockchain is a game-changer. I can’t wait to explore more possibilities and unleash the potential of decentralized applications. Thank you for this valuable resource!