How do I evaluate blockchain implemented in JavaScript?


Blockchain is a chain of blocks that contains information. In year 2009 this technology later adapted by Satoshi Nakamoto to create digital crypto-currency bitcoin. This is completely open to anyone who want to develop or analyse. This technology has a feature which make it very complex to make changes once some data has been recorded in the block of chain.

Here are some terms which is used in the blockchain program to evaluate.

  • Block − The block in the block chain contains information like data, Hash value and previous block hash value.

  • Data − This data is completely dependent on type of the block like crypto has information like transactions from which person it has transacted and to which person this has been transacted and how much amount of coin has been transacted.

  • Hash − This is a unique string id, like Aadhar number is there which can have used to locate a person details same way this hash is used to identify the block details. Once a block will get created its hash value will be created. Changing the block hash can easily be identified. Once a block hash is changed it no longer will be the same block.

  • Previous hash − This is previous block hash value which is used to connect or make the chain of the block.

Here in the above image, you can observe previous hash is having hash value of previous block. First block is also known as Genesis block as it can't point to previous block. In case you change the hash value then next block which is having previous hash value will not be valid due to change.

The package we will use is crypto.js. This is a JavaScript library that provides cryptographic algorithms and functions. It can be used to perform various cryptographic operations such as hashing, encryption, decryption, and key generation in a web browser or server-side JavaScript environment like Node.js.

The library is widely used in web applications to provide secure communication, data protection, and user authentication. For example, it can be used to encrypt sensitive data before sending it over the internet, or to generate secure password hashes for user authentication.

Let’s understand by a program using the Crypto.JS library for hashing and proof of work.

Here two classes Block and Blockchain are there.

class Block{
   constructor(prev_hashValue, data){
      this.data=data;
      this.hash=this.calculateHash();
      this.prev_hashValue=prev_hashValue;
      this.time_stamp= new Date();
      this.pf_work=0;
   }
}

The Block class has five properties −

  • data − This will store the data in the block.

  • hash − This will store of the hash of the block by calling calculateHash method.

  • prev_hashValue − This will store the hash of the previous block.

  • time_stamp − The timestamp will contain time when the block was created.

  • pf_work − A number that is incremented during the mining process.

Block class contains two methods −

calculateHash(){
   return SHA256(this.pf_work + this.prev_hashValue + this.timestamp + JSON.stringify(this.data)).toString();
}

This function will Calculate the hash of the block by concatenating the pf_work, prev_hashValue time_stamp and data, by passing it through the SHA256 hash function using the CryptoJS library.

mine(difficulty){
   while(!this.hash.startsWith("0".repeat(difficulty))){
      this.pf_work++;
      this.hash=this.calculateHash();
   }
}

This function Uses proof of work to find a hash that starts with a certain number of zeroes. The number of zeroes is determined by the difficulty parameter passed to the method. The pf_work property is incremented until a valid hash is found.

class Blockchain{
   constructor(){
      let genesisBlock=new Block("0", {isGenesisBlock: true});
      this.chain=[genesisBlock];
   }
}

chain − This is an array of Block objects which make the chain of a block.

The Blockchain class has two methods −

addNewBlock(data){
   let lastBlock=this.chain[this.chain.length-1];
   let newBlock=new Block(lastBlock.hash, data);
   newBlock.mine(2); //find a hash for new block
   this.chain.push(newBlock);
}

This method Creates a new Block object in which the data passed as a parameter, mines is used to find a valid hash, and adds it to the chain array.

isValid_hash(){
      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.prev_hashValue!=previousBlock.hash) return false;
      }
      return true;
}

This method Checks the validity of the blockchain by iterating over each block in the chain array and verifying that its hash property matches the calculated hash.

let blockchain=new Blockchain();
blockchain.addNewBlock({
   from: "joe",
   to:"Juhi",
   amount: 100,
});
blockchain.addNewBlock({
   from: "martin",
   to: "Genny",
   amount: 150,
});

Here an object will be created with two blocks which will have property of the blockchain class.

This implementation can be used as a starting point for building more complex blockchain applications that require secure and immutable data storage. However, it is important to note that this is just a basic implementation and many additional features, such as transaction verification, consensus mechanisms, and security measures, are required for a fully functional blockchain system.

Example: Complete Code

Blockchain.js

const SHA256 = require('crypto-js/sha256');
class Block{
   constructor(prev_hashValue, data){
      this.data=data;
      this.hash=this.calculateHash();
      this.prev_hashValue=prev_hashValue;
      this.time_stamp= new Date();
      this.pf_work=0;
   }

   calculateHash(){
      return SHA256(this.pf_work + this.prev_hashValue + this.time_stamp + JSON.stringify(this.data)).toString();
   }

   mine(difficulty){
      while(!this.hash.startsWith("0".repeat(difficulty))){
         this.pf_work++;
         this.hash=this.calculateHash();
      }
   }
}

class Blockchain{
   constructor(){
      let genesisBlock=new Block("0", {isGenesisBlock: true});
      this.chain=[genesisBlock];
   }

   addNewBlock(data){
      let lastBlock=this.chain[this.chain.length-1];
      let newBlock=new Block(lastBlock.hash, data);
      newBlock.mine(2); //find a hash for new block
      this.chain.push(newBlock);
   }

   isValid_hash(){
      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.prev_hashValue!=previousBlock.hash) return false;
      }
      return true;
   }
}
//test
let blockchain=new Blockchain();

blockchain.addNewBlock({
   from: "joe",
   to:"Juhi",
   amount: 100,
});

blockchain.addNewBlock({
   from: "martin",
   to: "Genny",
   amount: 150,
});

console.log(blockchain);
console.log("Blockchain is valid: "+blockchain.isValid_hash());

To compile the program, you will have to install the node.js. Use this article (Node.js - Environment Setup )for installation of Node.js. Afterward install the crypto.js library using following command.

npm install crypto-js

Then compile the JavaScript program file. Here, filename is blockchain.

node blockchain.js

Output

Updated on: 14-Jul-2023

33 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements