First of all, I want to clearly mention that JavaScript has nothing to do with Java. Both of them are different languages. JavaScript is a Scripting language and Java is a Programming language. I don’t know why the heck was it named as JavaScript at the first place. Probably because they wanted to gain popularity while introducing a new language, cause at the time Java was at its boom! Reminds you of someone from this industry who’s done the same to a coin? [BTC – BCH!]

To start with, I’ll give you an example to understand the difference between both languages.

Let’s take CAR and CARPET, is there any similarity between them, absolutely NO. The only similarity is CARPET has the word CAR included in it. Similarly, JAVASCRIPT has the name JAVA in it and has nothing to do with Java.

Proceeding further, why are we exactly using JavaScript here to create a Blockchain?

This article will be divided into Pt.1, 2, 3 and 4. This is Pt. 1 where we are not going to create a complete Blockchain which contains Proof-of-Work, Miners Reward, Signing transactions, etc.. Just simple basics of how a blockchain works with blocks, data, and hashes in it.

In Pt. 2 and 3 I will include Proof-of-Work, Miners Reward, and Signing transactions and more. So stay tuned?

The first thing to know about a Blockchain is that it’s not only about the backend. It’s a combination of both frontend and backend. So at the initial stages of learning going with an easy scripting language like JS is a good decision.

Hold on! Before diving into the coding part, you should be familiar with some technical terms in Blockchain like Blocks, Hashes, Genesis Block, SHA256, etc.. I’ll explain some of them in a short manner.

Blockchain: An immutable ledger with a lot of Blocks connected like a chain.

Blocks: Consider Blocks as a Wooden Box, Which contain all your data’s.

Genesis Block: First Block in the Blockchain.

Hash: Assume hash as a fingerprint (we all know it’s unique), Making a change inside the block, will make the hash to change.

SHA256: I don’t want to go into its technical part, As of know just remember SHA256 as a hash algorithm.

So let’s start coding your first blockchain ever!

STEP 1: Setting up the necessary tools

For this project, the IDE (Integrated Development Environment) that we are going to use is called VS (Visual Studio). You can go with your fav IDE, no problem. [1] Install an IDE. Post this, [2] install node.js. Once the Installation process completed the IDE will look like this.

[3] I’ve named this as maheshcoin.js you’re welcome to name it whatever you want.

In node.js some libraries are not available by default which is why we have to install them manually.

[4] Open your command prompt and type the following npm install –save crypt-js

Once the process is done make sure your screen looks like this as shown in the picture below.

Now we are ready to [5] import the SHA256 library to our program.

#CODE

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

[6] Enter the above command in the first line of your program to import the library.

STEP 2: Creating “The Block”

[7] First create a ‘Class Block’ with four parameters in it namely: Index, Timestamp, Data, and Previous hash. This also includes one member function calculatehash().

Here the tricky part is calculatehash() function, it’s a little bit tough to understand for the first time, but don’t worry I am here to help you. What’s happening inside the block is simple, we are taking all the content and hashing them to get the hash of the particular block.[8] The JSON.stringify function is used to turn the data of block into a string to hash it.

#CODE

class Block{

  constructor(index,timestamp,data,previoushash=”)

  {

      this.BlockNO=index;

      this.timestamp=timestamp;

      this.maheshcoin=data;

      this.previoushash=previoushash;

      this.hash=this.calculatehash();

  }

  calculatehash()

  {

      return SHA256(this.index + this.previoushash + this.timestamp + JSON.stringify(this.data)).toString()

  }

}

Post this, we are good to go ahead. Now let’s connect the block to the blockchain.

STEP 3: Linking to the Blockchain

Once the block is created its ready to link in a chain with its previous block.

Before that let’s see what’s happening inside these functions

  1. creategenesisblock()
  2. getlatestblock()
  3. addblock()

[9] creategenesisblock(): Here we are creating the genesis block.

What’s special about genesis block?

The genesis block is the first block of the blockchain. While every block points to the previous block of it, the genesis block doesn’t point to any. So, the moment a new chain is created, the genesis block is invoked automatically.

[10] return new block(0,”01/01/2019”,” Genesis Block”,”0”)

With the above code, we are creating the Genesis Block inside creategenesisblock() function.

[11] getlatestblock(): The latest block is the last block of the blockchain, so to access the last block programmers uses the simple known trick length -1. The same trick we are using here to get the last block.

[12] addblock(): Every time when the new block is created, it should have the previous hash value. So in this function, we are calculating and implementing the previous hash value to the new block.

#CODE

class Blockchain{

  constructor(){

      this.chain = [this.creategenesisblock()];

  }

  creategenesisblock(){

      return new Block(0,”01/01/2017″,”Genesis Block”,”0″)

  }

  getlatestblock(){

      return this.chain[this.chain.length -1];

  }

  addblock(newblock){

      newblock.previoushash = this.getlatestblock().hash

      newblock.hash = newblock.calculatehash();

      this.chain.push(newblock);

  }

STEP 4: Validating the Chain

ischainvalid(): So what’s happening inside this function?

[13] Here the process is simple we are just validating the ‘previous hash value’ with the ‘current hash value’. If these two hashes match, then it means that the new block is legit and it’s ready to get added to the blockchain.

Don’t feel bad, If you didn’t get this concept, in the upcoming steps I am going to explain them better.

#CODE

ischainvalid(){

      for(let i = 1; i<this.chain.length; i++){

          const currentblock = this.chain[i];

          const previousblock = this.chain[i-1];

          if(currentblock.hash != currentblock.calculatehash())

          {

              return false;

          }

          if(currentblock.previoushash != previousblock.hash){

              return true;

          }

      }

      return true;

  }

}

STEP 5: Passing the data

Here we are going to pass the data into the blocks.

Maheshcoin.addblock(new Block(1,”10/07/2019”,{amount: 4}));

Maheshcoin.addblock(new Block(2,”12/07/2019”,{amount: 10}));

[14] So by the above code, we are trying to pass three parameters

  1. Block index (eg:1)
  2. timestamp (eg: 10/07/2019)
  3. Data(eg: {amount: 4} ).

Note: You can pass any type of data and can also name it the way you want. But please remember that the format should not be changed.

#CODE

let maheshcoin = new Blockchain();

maheshcoin.addblock(new Block(1,”10/07/2017″,{amount: 4}));

maheshcoin.addblock(new Block(2,”12/07/2017″,{amount: 10}));

console.log(JSON.stringify(maheshcoin,null,4))

console.log(‘Is blockchain valid?’ + maheshcoin.ischainvalid())

maheshcoin.chain[1].data = {amount: 100};

//maheshcoin.chain[1].hash = maheshcoin.chain[1].calculatehash()

console.log(‘Is blockchain valid?’ + maheshcoin.ischainvalid())

STEP 6: Output

The output was the tricky part, The output shows three blocks which includes its data and hash functions in it. And one true statement and one false statement. So, what does this all mean?

Let’s say,  

BlockNo: 0          Coin value: “Genesis Block”

BlockNo: 1          Coin value: “4”

BlockNo: 2          Coin value: “10”

[15] console.log(‘Is blockchain valid?’ + maheshcoin.ischainvalid())

The above code is responsible for the “true” statement, that we are getting in the above image. Here what happens inside the ischainvaild() function? It’s simply comparing the current block hash value and the previous block hash value. If both of them matches it will return the value true, if not it throws the value false. So obviously you know why we are getting the value true.

[16]  maheshcoin.chain[1].data = {amount:100};

The above code line is the reason behind the “false” statement that we are getting in the output screen. So what’s went wrong there? Let me explain, as mentioned earlier Block 1 has the coin value 4  (BlockNo: 1 Coin value: “4”)

Here by using the above code, we are trying to change the coin value from 4  to 100. As we all know, we are not able to change the data inside the blockchain, which is why it now shows a “false” value. This is a better example to understand chain validation in a practical manner.

“A real learning happens, once you started implementing them practically.”

As a programmer learn to build blockchain by building one!

[If you have any doubt while building this, feel free to ‘comment’ below our Tech Merge team is always available to help you.]

#Here is the Full Code

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

class Block{

  constructor(index,timestamp,data,previoushash=”)

  {

      this.BlockNO=index;

      this.timestamp=timestamp;

      this.maheshcoin=data;

      this.previoushash=previoushash;

      this.hash=this.calculatehash();

  }

  calculatehash()

  {

      return SHA256(this.index + this.previoushash + this.timestamp + JSON.stringify(this.data)).toString()

  }

}

class Blockchain{

  constructor(){

      this.chain = [this.creategenesisblock()];

  }

  creategenesisblock(){

      return new Block(0,”01/01/2017″,”Genesis Block”,”0″)

  }

  getlatestblock(){

      return this.chain[this.chain.length -1];

  }

  addblock(newblock){

      newblock.previoushash = this.getlatestblock().hash

      newblock.hash = newblock.calculatehash();

      this.chain.push(newblock);

  }

  ischainvalid(){

      for(let i = 1; i<this.chain.length; i++){

          const currentblock = this.chain[i];

          const previousblock = this.chain[i-1];

          if(currentblock.hash != currentblock.calculatehash())

          {

              return false;

          }

          if(currentblock.previoushash != previousblock.hash){

              return true;

          }

      }

      return true;

  }

}

let maheshcoin = new Blockchain();

maheshcoin.addblock(new Block(1,”10/07/2017″,{amount: 4}));

maheshcoin.addblock(new Block(2,”12/07/2017″,{amount: 10}));

console.log(JSON.stringify(maheshcoin,null,4))

console.log(‘Is blockchain valid?’ + maheshcoin.ischainvalid())

maheshcoin.chain[1].data = {amount: 100};

//maheshcoin.chain[1].hash = maheshcoin.chain[1].calculatehash()

console.log(‘Is blockchain valid?’ + maheshcoin.ischainvalid())

Go code your first blockchain now, Happy learning guys!

Leave a comment

My Newsletter

Sign Up For Updates & Newsletters