-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockchain.js
39 lines (28 loc) · 844 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
34
35
36
37
38
39
const Block = require("./block");
const cryptoHash = require("./crypto-hash");
class Blockchain {
constructor() {
this.chain = [Block.genesis()];
}
addBlock({ data }) {
const newBlock = Block.mineBlock({
lastBlock: this.chain[this.chain.length - 1],
data,
});
this.chain.push(newBlock);
}
static isValidChain(chain) {
if (JSON.stringify(chain[0]) !== JSON.stringify(Block.genesis())) {
return false;
}
for (let i = 1; i < chain.length; i++) {
const { timestamp, lastHash, hash, data } = chain[i];
const actualLastHash = chain[i - 1].hash;
if (lastHash !== actualLastHash) return false;
const validatedHash = cryptoHash(timestamp, lastHash, data);
if (hash !== validatedHash) return false;
}
return true;
}
}
module.exports = Blockchain;