TLDR; 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.
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.
Download
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.
This slideshow requires JavaScript.
=>Let’s start off by creating a new Nodejs project by usingnpm initcommand. This command will create a new package.json file.
npm init
=>After that copy the dependencies from below package.json and paste it in your file and runnpm install.
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,
So let’s get our hands dirty.
If you have followed my previousNodejs articles, you might familiar with folder structure I create. I try to keep the file structure as realistic as they can be so that you can easily integrate them into your projects. Also, we follow the object-oriented style, so that makes our code more elegant and clean.
=> Since this project is Tiny, hence we have only two files in which we will code first isserver.jsand blockchain.js.
server.js
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 theserver.jsfile.
=>So open theserver.js file and add the below code, the below code is very straightforward and easy to understand so I will leave to up to you. Let me know in the comment box if you don’t understand something.
=> 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();
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:
chain
createBlock()
previousHash
proof
block
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.
=> 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,
Read and understand how and what is proof of work in the Blockchain and Cryptocurrency world.
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.
getLastBlock()
proofOfWork()
generateHash()
Open the blockchain.js and add below code into it.
/* * @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(); }
=> 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.
includeRoutes()
/* * @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.' }); }); }
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.
/* * @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; }
previousBlock
blockIndex
True
if
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.
If you have any suggestion, Question or feature request, let me know in the below comment box, I would be happy to help. If you like this article, do spread a word about it and share with others.
TypeError: blockchain.getLastBlock is not a function
Your email address will not be published. Required fields are marked *
Comment *
Name *
Email *
Website
Notify me of follow-up comments by email.
Δ
www.codershood.info is licensed under a Creative Commons Attribution 4.0 International License.
TypeError: blockchain.getLastBlock is not a function