How to create a Blockchain using Node.js

December 22, 2018
157 Views

In this article, I will talk about the basics of Blockchain. We will discuss the fundamental concepts of the blockchain. Also, I will tell you what you need to know to create a blockchain using nodejs.

 

1. What is Blockchain?

Long, long time ago when I first heard about Bitcoin. You what I used to think? I thought bitcoin is nothing but a Blockchain. Little did I know, Bitcoin is created using the Blockchain. So what is blockchain,

As the name suggests, it’s a chain of blocks linked with SHA256 hash. Also, these blocks contain some sort of data.

The below image is a representation of a Blockchain in human-readable format. As you can see, there are a few blocks linked by a chain. These chains are nothing but the reference to the previous block. Now I have a question, how do they refer to the previous block?

 

They refer to the previous block with the help of the SHA256 hash key. The block itself stores these SHA256 hash keys. I mean each block has its own hash and another hash which refers to the previous block. Now let’s take a closer look at a Single block in the blockchain. As I said earlier, a Block contains some amount of data. What is this data? What does a block hold as data?

Well, each block has a few fields inside them, as shown in the above image. The fields are Nonce, Timestamp, Data, Hash and Previous Hash respectively. Let’s understand each field and why they are important.

Nonce: A nonce is a 32-bit number, which is used by miners to add a new block in the Blockchain.

Timestamp: It represents the timestamp when the block is added to the blockchain. Also, it should be greater than the previous block’s timestamps.

Data: It can be anything or any data. In the case of cryptocurrency, the data is nothing but transactions between people.

Hash: It’s a SHA256 hash of the block. Every block has its own hash.

Previous Hash: It’s a SHA256 hash of the previous block. And that’s how each block are linked with another block.

Now you know the very basics of a Blockchain. let me tell you something, Each point discussed above is capable of having it’s own 3000 words blog post. And this applies to whatever concept, I will discuss here from this point.

Before going any further, let’s take a look at the final outcome of the application.

 

 

2. Creating a new Nodejs project and setting up the project goals

Let’s start off by creating a new Nodejs project by using npm init command. This command will create a new package.json file.

After that copy the dependencies from below package.json and paste it in your file and run npm install.

Below is my package.json file for this application.

package.json:

{
  "name": "blockchain-using-nodejs",
  "version": "1.0.0",
  "description": "A simple blockchain using Nodejs.",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Shashank Tiwari",
  "license": "MIT",
  "dependencies": {
    "body-parser": "^1.18.3",
    "crypto-js": "^3.1.9-1",
    "express": "^4.16.3"
  }
}

The goal of this Project is very simple, here we will do three operations which are listed below,

  1. We will create the genesis block.
  2. We will create a method to add a new block in the blockchain.
  3. We will implement a method to check the validity of the

 

3. Project structure and Files and Setting Up the Nodejs server

Since this project is Tiny, hence we have only two files in which we will code first is server.js and blockchain.js.

So here we will first set up the nodejs and then we will initialize the routes of the application. As I said in the last section we will do our setup in the server.js file.

So open the server.js file and add the below code

server.js:

/* 
 * @author Shashank Tiwari
 * Create your first Blockchain using Nodejs
 */
'use strict';

const express = require("express");
const http = require('http');
const bodyParser = require('body-parser');

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

class Server {

    constructor() {
        this.port = process.env.PORT || 4000;
        this.host = `localhost`;

        this.app = express();
        this.http = http.Server(this.app);
    }

    appConfig() {
        this.app.use(
            bodyParser.json()
        );
        this.app.use(require("express").static('client'));
    }

    /* Including app Routes starts*/    includeRoutes(app) {
        
        /* Blockchain related routes will go here */        
        app.get("**", function (req, response) {
            response.status(200).json({
                message: '404, Not Found.'
            });
        });
    }
    /* Including app Routes ends*/
    appExecute() {

        this.appConfig();
        this.includeRoutes(this.app);

        this.http.listen(this.port, this.host, () => {
            console.log(`Listening on http://${this.host}:${this.port}`);
        });
    }

}

const app = new Server();
app.appExecute();

4. Create the first block in the blockchain using nodejs

Now in the blockchain term, the first block of the blockchain is known as Genesis Block. So first, we will create a Genesis block and you won’t believe how easy to create the first block is.

Open the blockchain.js and add the below code into it.

blockchain.js:

/* 
 * @author Shashank Tiwari
 * Create your first Blockchain using Nodejs
 */
'use strict';

const SHA256 = require("crypto-js/sha256");

class Blockchain {

    constructor() {
        this.chain = [];
        this.createBlock({previousHash: 0, proof: 1});
    }

    createBlock({ previousHash, proof }) {
        const block = {
            index: this.chain.length + 1,
            timestamp: (+new Date()).toString(),
            data: Math.random(),
            proof: proof,
            previous_hash: previousHash
        }
        this.chain.push(block);
        return block;
    }
}

Explanation:

  1. The first thing to notice is the constructor function. Inside the constructor function, I have created a property called chain having data type as an array.
  2. Then we have called createBlock() method to create the Genesis block.
  3. Later, we have created createBlock() method to add a new block in the Blockchain.
  4. There are two parameters in this method i.e. previousHash and proof.
  5. Then we have created ablockblock object which has few properties, I assume all the properties are self-explanatory expectproof property. Think of it as a nonce of the block, which will be used in the process of adding/mining new block.

5. Mining (Adding) a new block in the Blockchain

In this section, we will add a new block in the blockchain. In the term of the Cryptocurrency and the Blockchain Adding a new block means Mining a new block. I have divided this section into two parts. First, you need to understand how this mining process works and then we will implement the same process in Nodejs.

1. How does mining work?

In the real world, mining a new block is a very very very expensive and time taking process. Just to give an idea, take a look at these images it’s one of the world largest Bitcoin mines. Anyways we will move ahead, but the more you will learn about the Blockchain and Cryptocurrency, it will surprise you more.

So to add a new block in the blockchain, there are specific steps miner have to follow. As I said earlier, a miner can only change the nonce of the block.

So using the nonce of a block miner generates the hash, which should be lower than the target hash. When hash generated by miner matches the criteria of Target Hash, then that nonce is called as the Golden nonce.

In the real world, mining a new block is a very complex and expensive process. And since we are implementing a very tiny blockchain, hence we won’t be going into the detailing of every step involved in it.

So our steps to mine a new block will be very simple, which I am listing down below,

  1. We will get the last block of the blockchain.
  2. We will try to find the Golden Nonce by using Proof of Work concept.
  3. Then we will add a new block.

2. Mining a new block using Nodejs

So we will start from where we left in the last section. Here we will create three more methods in the Blockchain class. These methods are listed below with their purpose,

1. getLastBlock(): Gives the last block of the blockchain.
2. proofOfWork(): Gives the golden nonce by finding the Hash below to the target Hash.
3. generateHash(): Generate the SHA256 hash of the given block.

Open the blockchain.js and add below code into it.

blockchain.js:

/* 
 * @author Shashank Tiwari
 * Create your first Blockchain using Nodejs
 */
getLastBlock() {
    return this.chain[this.chain.length - 1] !== undefined ? this.chain[this.chain.length - 1] :  null;
}

proofOfWork(previousProof) {
    let newProof = 1;
    let checkProof = false;
    while (!checkProof) {
        const blockHash = SHA256((Math.pow(newProof, 5) - Math.pow(previousProof, 5)).toString()).toString();
        if (blockHash.substring(0, 5) === '00000') {
            checkProof = true;
        } else {
            newProof++;
        }
    }
    return newProof;
}

generateHash(block) {
    return SHA256(JSON.stringify(block)).toString();
}

Explanation:

  1. The first and the last methods are very easy and simple, we won’t talk about it.
  2. The next method isproofOfWork() method, which expects one parameter i.e. proof of the last block of the blockchain.
  3. We have created a while loop, inside this loop two things are happening.
  4. First, we are creating a random alphanumeric string by using previous block’s proof.
  5. Then we are encrypting it to the SHA256 hash.
  6. Second, We are check if the encrypted hash has five leading Zeros.
  7. If this condition comes true, then we break the while loop and return the Golden Nonce.

After creating these methods now it’s time to put them at work. So let’s add the express route to mine a new block.

Here we will add our routes inside the server.js file under includeRoutes() method. Open the server.js file and add the below code into it.

server.js:

/* 
 * @author Shashank Tiwari
 * Create your first Blockchain using Nodejs
 */
includeRoutes(app) {
    
    app.get("/mine_block", function (request, response) {
        const previousBlock = blockchain.getLastBlock();
        const proof = blockchain.proofOfWork(previousBlock.proof);
        const previousHash = blockchain.generateHash(previousBlock);
        const block = blockchain.createBlock({
            previousHash: previousHash,
            proof: proof
        });
        const jsonResponse = {
            message: 'You mined a new Block.',
            index: block.index,
            timestamp: block.timestamp,
            data: block.data,
            proof: block.proof,
            previous_hash: block.previous_hash
        }
        response.status(200).json(jsonResponse);
    });

    app.get("**", function (req, response) {
        response.status(200).json({
            message: '404, Not Found.'
        });
    });
}

Explanation:

  1. Here we have called getLastBlock() method to fetch the last block of the blockchain.
  2. Then we have calledproofOfWork() method, which will give the golden nonce.
  3. Later, we are generating the SHA256 hash of the previous block.
  4. After doing all, we call createBlock() method which adds a new block into the blockchain.
  5. And lastly, we are returning the response to client by accessing the newly mined block.

6. Check if the Blockchain is valid

Now that you have created a brand new blockchain using nodejs, let’s check if your blockchain is valid or not. Here we will match two criteria to check the validity of the blockchain.

The first criteria is related to the Hash key. The hash of the current block should be equal to its next block’s Previous Key property.

The second criteria is, all the Hash key of all the blocks should start with 5 leading Zeros.

Open the blockchain.js and add the below, the below method will check the validity of the blockchain.

blockchain.js:

/* 
 * @author Shashank Tiwari
 * Create your first blockchain using nodejs
 */
isChainValid() {
    const chain = this.chain;
    let previousBlock = chain[0];
    let blockIndex = 1;
    while (blockIndex < chain.length) {
        const currentBlock = chain[blockIndex];
        if (currentBlock.previous_hash !== this.generateHash(previousBlock)) {
            return false;
        }
        const previousProof = previousBlock.proof;
        const currentProof = currentBlock.proof;
        const blockHash = SHA256((Math.pow(currentProof, 5) - Math.pow(previousProof, 5)).toString()).toString();
        if (blockHash.substring(0, 5) !== '00000') {
            return false;
        }
        previousBlock = currentBlock;
        blockIndex += 1;
    }
    return true;
}

Explanation:

  1. Let’s start with the variables and constants that we have defined,
    chain: This constant will hold the entire blockchain.
    previousBlock: The variable previousBlock will be updated every time whenever while loop will increment.
    blockIndex: This variable will be incremented by one every time.
  2. The while loop is against the length of the chain, as soon as the blockIndex variable reaches to the length of the blockchain the while loop will be stopped. And then it will return True, which means your blockchain is valid.
  3. Inside the while loop, we have two if blocks. That’s because we are verifying two conditions to be your blockchain valid.
  4. Inside the first if block we are checking the hash of the current block with the previous hash of the next block. If these two hashes are identical for rest of the blocks in the blockchain, Then your blockchain is valid.
  5. In the next if block, we are again creating a block hash based on Nonce of the blocks. Once the has is generated, we will check is the hash starts with 5 leading zeros.
  6. If these two conditions are satisfied, then the while loop will be increment. Hence, the blockIndex will be incremented by one and the previousBlock variable will point to the next block.

 

7. Conclusion

So that’s a wrap for now. In this tutorial, you understood how to create a tiny blockchain using nodejs. Honestly, this tutorial barely scratches the surface of the blockchain. Am telling you again there is much much more to learn in the field of the blockchain.

However, if you are completely new and trying to learn what is blockchain and how to get started then, this tutorial will give you a good start.

 

Author: Shashank Tiwari

Source : http://www.codershood.info/2018/09/12/create-your-first-blockchain-using-nodejs/

License : Attribution 4.0 International

You may be interested

Top 15 resources for learning JavaScript
Articles
119 views
Articles
119 views

Top 15 resources for learning JavaScript

simoneadmin - December 23, 2018

HTML, cascading stylesheets (CSS), and JavaScript have experienced massive growth and evolution over the past two decades, which should come…

Introduction to PWA and Angular 6
Angular
175 views
Angular
175 views

Introduction to PWA and Angular 6

simoneadmin - October 19, 2018

Progressive web apps are the new standard for web development. using Html , Css and JavaScript web apps can feel…

How to deploy Angular on Azure
Angular
929 views
Angular
929 views

How to deploy Angular on Azure

simoneadmin - February 5, 2018

The Angular CLI makes it easy to build a production ready Angular app. The next step is getting that app…

Leave a Comment

Your email address will not be published.