-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblockchain.js
More file actions
72 lines (50 loc) · 1.37 KB
/
blockchain.js
File metadata and controls
72 lines (50 loc) · 1.37 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
let sha256 = require('js-sha256')
let Block = require('./block')
class Blockchain {
constructor(genesisBlock) {
this.blocks = []
this.addBlock(genesisBlock)
}
transactionsByDrivingLicenseNumber(driverLicenseNumber){
let transactions = []
this.blocks.forEach((block)=>{
block.transactions.forEach((transaction)=>{
if(transaction.driverLicenseNumber == driverLicenseNumber){
transactions.push(transaction)
}
})
})
return transactions;
}
addBlock(block) {
if(this.blocks.length == 0) {
block.previousHash = "0000000000000000"
block.hash = this.generateHash(block)
}
this.blocks.push(block)
}
getNextBlock(transactions) {
let block = new Block()
transactions.forEach(function(transaction){
block.addTransaction(transaction)
})
let 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