UNPKG

aiascs-blockchain

Version:

Sample Module for blockchain status of entities relate to each other

47 lines (38 loc) 1.28 kB
const BlockChainSchema = require('../src/model/BlockSchema'); const Block = require("./Block"); class BlockChain { constructor(){ //this is collection of block this.chain = BlockChainSchema(this.createGenesisBlock()) this.difficult = 1; } createGenesisBlock(){ return new Block("01/01/2021", "Genesis Block", "0"); } getLatestBlock(){ return this.chain[this.chain.length - 1]; } addBlock(newBlock){ // set the previous hash newBlock.previousHash = this.getLatestBlock().hash; newBlock.mineBlock(this.difficult); //newBlock.hash = newBlock.calculateHash(); this.chain.push(newBlock); } isChainValid() { for (let blockIndex = 1; blockIndex < this.chain.length; blockIndex++) { const currentBlock = this.chain[blockIndex]; const previousBlock = this.chain[blockIndex - 1]; //check if hash of the block is still valid if (currentBlock.hash != currentBlock.calculateHash()) { return false; } //check if current block point to previous block if (currentBlock.previousHash != previousBlock.hash) { return false; } } return true; } } module.exports = BlockChain;