-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockchain.js
More file actions
42 lines (35 loc) · 985 Bytes
/
Blockchain.js
File metadata and controls
42 lines (35 loc) · 985 Bytes
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
const Block = require("./Block");
class Blockchain {
constructor() {
this.chain = [new Block(Date.toString())];
this.difficulty = 1;
this.blockTime = 30000;
}
getLastBlock() {
return this.chain[this.chain.length - 1];
}
addBlock(block) {
block.prevHash = this.getLastBlock().hash;
block.hash = block.getHash();
block.mine(this.difficulty);
this.chain.push(block);
this.difficulty +=
Date.now() - parseInt(this.getLastBlock().timestamp) < this.blockTime
? 1
: -1;
}
isValid(blockchain = this) {
for (var i = 1; i <= blockchain.chain.length; i++) {
const currentBlock = blockchain.chain[i];
const prevBlock = blockchain.chain[i - 1];
if (
currentBlock.hash !== currentBlock.getHash() ||
currentBlock.prevHash !== prevBlock.hash
) {
return false;
}
return true;
}
}
}
module.exports = Blockchain;