Articles → Blockchain → Create Your First Blockchain Program In Javascript

Create Your First Blockchain Program In Javascript






Software Requirement







Crypto-Js Installation




npm install crypto-js --save


Picture showing installation of crypto-js using npm
Click to Enlarge



Picture showing the files and folders created once crypto-js is installed
Click to Enlarge




Example




  1. Create a block class
  2. Create a blockchain class
  3. Add block into the block chain
  4. Display the blockchain


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;
  }

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




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

  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();
    this.chain.push(newBlock);
  }
}




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

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




console.log(JSON.stringify(demoChain));



Output




node index.js


Picture showing the output of first blockchain program
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;
  }

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

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

  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();
    this.chain.push(newBlock);
  }
}

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

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


console.log(JSON.stringify(demoChain));



Posted By  -  Karan Gupta
 
Posted On  -  Monday, May 4, 2020

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250