-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockchain.js
61 lines (54 loc) · 1.57 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const Block = require("./block");
const cryptoHash = require("./crypto-hash");
class Blockchain {
constructor() {
this.chain = [Block.genesis()];
}
addBlock({ data }) {
const newBlock = Block.mineBlock({
prevBlock: this.chain[this.chain.length - 1],
data,
});
this.chain.push(newBlock);
}
replaceChain(chain) {
if (chain.length <= this.chain.length) {
console.error("The incoming chain is not longer");
return;
}
if (!Blockchain.isValidChain(chain)) {
console.error("The incoming chain is not valid");
return;
}
this.chain = chain;
}
static isValidChain(chain) {
if (JSON.stringify(chain[0]) !== JSON.stringify(Block.genesis())) {
return false;
}
for (let i = 1; i < chain.length; i++) {
const { timestamp, prevHash, hash, nonce, difficulty, data } = chain[i];
const lastDifficulty = chain[i - 1].difficulty;
const realLastHash = chain[i - 1].hash;
if (prevHash !== realLastHash) return false;
const validatedHash = cryptoHash(
timestamp,
prevHash,
nonce,
difficulty,
data
);
if (hash !== validatedHash) return false;
if (Math.abs(lastDifficulty - difficulty) > 1) return false;
}
return true;
}
}
// const blockchain = new Blockchain();
// blockchain.addBlock({ data: "Block1" });
// blockchain.addBlock({ data: "Block2" });
// const result = Blockchain.isValidChain(blockchain.chain);
// console.log(blockchain.chain);
// console.log(result);
// //console.log(blockchain);
module.exports = Blockchain;