-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathblockchain.js
More file actions
46 lines (36 loc) · 1.1 KB
/
Copy pathblockchain.js
File metadata and controls
46 lines (36 loc) · 1.1 KB
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
const Block = require('./block')
class Blockchain {
constructor(difficulty = 1) {
this.blocks = [new Block()]
this.index = 1
this.difficulty = difficulty
}
getLastBlock() {
return this.blocks[this.blocks.length - 1]
}
addBlock(data) {
const index = this.index
const difficulty = this.difficulty
const previousHash = this.getLastBlock().hash
const block = new Block(index, previousHash, data, difficulty)
this.index++
this.blocks.push(block)
}
isValid() {
for (let i = 1; i < this.blocks.length; i++) {
const currentBlock = this.blocks[i]
const previousBlock = this.blocks[i - 1]
if (currentBlock.hash !== currentBlock.generateHash()) {
return false
}
if (currentBlock.index !== previousBlock.index + 1) {
return false
}
if (currentBlock.previousHash !== previousBlock.hash) {
return false
}
}
return true
}
}
module.exports = Blockchain