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














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 04, 2020

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250