Guest User

Untitled

a guest
Jul 23rd, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. class BlockChain {
  2. constructor() {
  3. this.chain = [this.createGenesisBlock()];
  4. this.difficulty = 2;
  5. this.pendingTransactions = [];
  6. this.miningReward = 100;
  7. }
  8.  
  9. createGenesisBlock() {
  10. return new Block("2018-06-29", "Genesis Block", "0");
  11. }
  12.  
  13. getLatestBlock() {
  14. return this.chain[this.chain.length - 1];
  15. }
  16.  
  17. minePendingTransactions(miningRewardAdress) {
  18. const block = new Block(Date.now(), this.pendingTransactions);
  19. block.mineBlock(this.difficulty);
  20. console.log("Block mined!");
  21. this.chain.push(block);
  22. this.pendingTransactions = [
  23. new Transaction(null, miningRewardAdress, this.miningReward),
  24. ];
  25. }
  26.  
  27. createTransaction(transaction) {
  28. this.pendingTransactions.push(transaction);
  29. }
  30.  
  31. getBalanceOfAddres(address) {
  32. let balance = 0;
  33. for(const block of this.chain) {
  34. for(const transaction of block.transactions) {
  35. if(transaction.fromAddress === address)
  36. balance -= transaction.amount;
  37. if(transaction.toAddress === address)
  38. balance += transaction.amount;
  39. }
  40. }
  41. return balance;
  42. }
  43.  
  44. isChainValid() {
  45. for(let i = 1; i < this.chain.length; i++) {
  46. const currentBlock = this.chain[i];
  47. const prevBlock = this.chain[i - 1];
  48. if(currentBlock.hash !== currentBlock.calculateHash())
  49. return false;
  50. if(currentBlock.prevHash !== prevBlock.hash)
  51. return false;
  52. }
  53. return true;
  54. }
  55. }
  56.  
  57. export default BlockChain;
Add Comment
Please, Sign In to add comment