-
Notifications
You must be signed in to change notification settings - Fork 0
/
Blockchain.js
33 lines (27 loc) · 951 Bytes
/
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
const Block = require('./Block');
module.exports = class Blockchain {
constructor() {
this.chain = [new Block()];
this.nextIndex = 1;
}
getLastHash() {
return this.chain[this.chain.length - 1].hash;
}
addBlock(data) {
const block = new Block(this.nextIndex, data, this.getLastHash());
this.chain.push(block);
this.nextIndex++;
}
isValid() {
for (let i = this.chain.length - 1; i !== 0; i--) {
const currentBlock = this.chain[i];
const previousBlock = this.chain[i - 1];
let isvalidBlock = currentBlock.index === previousBlock.index + 1
&& currentBlock.hash === currentBlock.generateHash()
&& currentBlock.previousHash === previousBlock.hash
&& currentBlock.timestamp > previousBlock.timestamp;
if (!isvalidBlock) return false;
}
return true;
}
}