-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathblockchain.js
59 lines (39 loc) · 950 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const sha256 = require('js-sha256')
const Block = require ('./block');
class Blockchain {
constructor(genesisBlock) {
this.blocks = []
this.addBlock(genesisBlock)
}
addBlock(block){
if(this.blocks.length === 0){
block.previousHash="0000000000000000"
block.hash = this.generateHash(block)
}
this.blocks.push(block)
}
getNextBlock(transactions){
const block = new Block()
transactions.forEach(function(transaction){
block.addTransaction(transaction)
})
const previousBlock = this.getPreviousBlock()
block.index = this.blocks.length
block.previousHash = previousBlock.hash
block.hash = this.generateHash(block)
return block
}
getPreviousBlock(){
return this.blocks[this.blocks.length - 1]
}
generateHash(block){
let hash = sha256(block.key);
while(!hash.startsWith("000")){
block.nonce += 1
hash = sha256(block.key)
// console.log(hash)
}
return hash
}
}
module.exports = Blockchain