Articles → Blockchain → Adding A Block In Blockchain Using Javascript

Adding A Block In Blockchain Using Javascript






Adding A Mineblock Function


mineBlock(difficulty) {
 while (this.hash.toString().substring(0, difficulty) !== Array(difficulty + 1).join("0")) {
  this.nonce++;
  this.hash = this.calculateHash();
 }
 console.log("Block Successfully hashed: " + this.hash);
 console.log("Nonce: " + this.nonce);
}




  1. Comparing the block hash with target hash.
  2. If hash is not matched then calculate the hash again by adding the nonce.
  3. Compare again till the time hash is not matched.

Output


Picture showing the output of adding a block in blockchain
Click to Enlarge


Full Code


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

class Block {
 constructor(index, timestamp, data, previousHash) {
  this.index = index;
  this.timestamp = timestamp;
  this.data = data;
  this.previousHash = previousHash;
  this.nonce = 0;
  this.hash = this.calculateHash();
 }

 calculateHash() {
  return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce);
 }

 mineBlock(difficulty) {
  while (this.hash.toString().substring(0, difficulty) !== Array(difficulty + 1).join("0")) {
   this.nonce++;
   this.hash = this.calculateHash();
  }
  console.log("Block Successfully hashed: " + this.hash);
  console.log("Nonce: " + this.nonce);
 }
}

class Blockchain {
 constructor() {
  this.chain = [this.createGenesisBlock()];
  this.difficulty = 3;
 }

 createGenesisBlock() {
  return new Block(0, '02/05/2020', 'Genesis Block', "0");
 }

 getlatestBlock() {
  return this.chain[this.chain.length - 1];
 }

 addBlock(newBlock) {
  newBlock.previousHash = this.getlatestBlock().previousHash;
  //newBlock.hash = newBlock.calculateHash();
  newBlock.mineBlock(this.difficulty);
  this.chain.push(newBlock);
 }
}

let demoChain = new Blockchain();

console.log("Starting................");

demoChain.addBlock(
 new Block(1, '02/05/2020', {
  amount: 10
 }));

console.log("Secondly................");

demoChain.addBlock(
 new Block(2, '02/05/2020', {
  amount: 25
 }));



Posted By  -  Karan Gupta
 
Posted On  -  Thursday, May 7, 2020

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250