How To Build Your Own Blockchain Using Node.js

How To Build Your Own Blockchain Using Node.js
A blockchain is just a chain of blocks, a collection of records, and each record is linked with other blocks. The blocks are digital information that is stored in the database. We can also say that the blockchain itself a database.

A blockchain is just a chain of blocks, a collection of records, and each record is linked with other blocks. The blocks are digital information that is stored in the database. We can also say that the blockchain itself a database.

Blocks can store the following information:

  • Transaction records.
  • Participants of transactions.
  • An index or something that distinguishes it from other records.

In this article, we will implement a small blockchain using Node.js. In our blockchain, blocks will contain the following things:

  • Index
  • Timestamp
  • Data
  • Previous hash
  • Block hash

And each block will be connected with another block using that block’s hash. Blocks will be protected by cryptography.

We will also see if we change the information of any block, then we can detect the block that was changed.

Let’s Start Coding

Create a directory called blockchain and in this folder, create a file with the name package.json and add the code below:

//package.json:
{
 "name": "blockchain",
 "version": "1.0.0",
 "description": "",
 "main": "main.js",
 "scripts": {
   "test": "echo \"Error: no test specified\" && exit 1"
 },
 "author": "Shubham Verma",
 "license": "ISC",
 "dependencies": {
   "crypto": "^1.0.1"
 }
}

package.json

Now, go to that package.json location in your terminal and run npm install which will install the dependencies of this implementation:

This is image title

Snapshot: npm install

Now create another file, main.js, in the same directory and paste the below code:

//main.js
const crypto = require('crypto');
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.getHash();
   }

   getHash() {
       var encript=JSON.stringify(this.data) + this.prevHash + this.index + this.timestamp;
       var hash=crypto.createHmac('sha256', "secret")
       .update(encript)
       .digest('hex');
       // return sha(JSON.stringify(this.data) + this.prevHash + this.index + this.timestamp);
       return hash;
   }
}


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


const BChain = new BlockChain();
BChain.addBlock({sender: "Bruce wayne", reciver: "Tony stark", amount: 100});
BChain.addBlock({sender: "Harrison wells", reciver: "Han solo", amount: 50});
BChain.addBlock({sender: "Tony stark", reciver: "Ned stark", amount: 75});
console.dir(BChain,{depth:null})

console.log("******** Validity of this blockchain: ", BChain.chainIsValid());

main.js

Let’s understand the above code (main.js):

const crypto = require('crypto');

The above line is to import the crypto module into our app to encrypt the data.

class Block { }

The above code will create a class with the name Block.

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

The above code decides what the block contains, it means our block will contain things that we have decided in our constructor.

getHash() {                              
var encript=JSON.stringify(this.data) + this.prevHash + this.index + this.timestamp;                              
var hash=crypto.createHmac('sha256', "secret")                              .update(encript)                              
.digest('hex');                              
// return sha(JSON.stringify(this.data) + this.prevHash + this.index + this.timestamp);                              
return hash;                          
}

The above function will return the hash of data, it will encrypt all the data.
The above function will use the SHA256 algorithm to encrypt.

class BlockChain { }

The above code will have all the blockchain, the actual blockchain.

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

The above constructor will create a chain where we will keep all our blocks.

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);                          
}

The above code will create a new block and add it to 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;                              
}

The above code will detect the validity of the block.

const BCoin = new BlockChain();

The above line will create an object of BlockChain.

BChain.addBlock({sender: "Bruce wayne", reciver: "Tony stark", amount: 100});

The above code will create a block with the given data.

Now it’s time to run the file main.jsusing the below command:

node main.js

This is image title

Output: main.js

In the above snapshots, you can see that the validity of this blockchain is true.
It means that the above blocks are correct and the data is correct and they are not altered.

This is image title

Let’s do some altering. I am going to change block 0, changing the name “Bruce wayne” to “Joker”.

To do this, add the below code to the last line in file main.js.

BChain.chain[0].data.receiver = "Joker";
console.log("******** Validity of this blockchain: ", BChain.chainIsValid());

And run themain.js file using the below command:

node main.js

Now you can see the validity:

This is image title

It’s false, it shows that someone altered the data in our chain and we have detected that.

Congratulations, now you have better clarity on how basic blockchains work.

Note: Even though this piece uses some basic cryptography, the concepts in this article do not demonstrate a truly secure blockchain.

Thanks for reading.

Suggest:

JavaScript Programming Tutorial Full Course for Beginners

Learn JavaScript - Become a Zero to Hero

Javascript Project Tutorial: Budget App

Top 10 JavaScript Questions

E-Commerce JavaScript Tutorial - Shopping Cart from Scratch

JavaScript for React Developers | Mosh