Guest User

Untitled

a guest
Oct 22nd, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. const Block = require('./block');
  2.  
  3. class Blockchain{
  4. constructor(){
  5. this.chain = [Block.genesis()];
  6. }
  7.  
  8. addBlock(data){
  9. const block = Block.mineBlock(this.chain[this.chain.length-1],data);
  10. this.chain.push(block);
  11.  
  12. return block;
  13. }
  14.  
  15. isValidChain(chain){
  16. if(JSON.stringify(chain[0]) !== JSON.stringify(Block.genesis()))
  17. return false;
  18.  
  19. for(let i = 1 ; i<chain.length; i++){
  20. const block = chain[i];
  21. const lastBlock = chain[i-1];
  22. if((block.lastHash !== lastBlock.hash) || (
  23. block.hash !== Block.blockHash(block)))
  24. return false;
  25. }
  26.  
  27. return true;
  28.  
  29. }
  30.  
  31. replaceChain(newChain){
  32. if(newChain.length <= this.chain.length){
  33. console.log("Recieved chain is not longer than the current chain");
  34. return;
  35. }else if(!this.isValidChain(newChain)){
  36. console.log("Recieved chain is invalid");
  37. return;
  38. }
  39.  
  40. console.log("Replacing the current chain with new chain");
  41. this.chain = newChain;
  42. }
  43. }
  44.  
  45. module.exports = Blockchain;
Add Comment
Please, Sign In to add comment