-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBlockchain.js
38 lines (30 loc) · 1.03 KB
/
Blockchain.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const Block = require('./Block');
const dateFormat = require('dateformat');
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock() {
return new Block(0, dateFormat(new Date(), "dddd, mmmm dS, yyyy, h:MM:ss TT"), { from: "Ashish", to: "Shrey", amount: 100 }, "0000");
}
getLatestBlock() {
return this.chain[this.chain.length - 1];
}
addNewBlock(newBlock) {
newBlock.previousHash = this.getLatestBlock().hash;
newBlock.hash = newBlock.calculateHash();
this.chain.push(newBlock);
}
isChainValid() {
for(let i=1; i<this.chain.length; i++){
let currentBlock = this.chain[i];
let previousBlock = this.chain[i-1];
if(currentBlock.previousHash !== previousBlock.hash)
return false;
if(currentBlock.hash !== currentBlock.calculateHash())
return false;
}
return true;
}
}
module.exports = Blockchain;