forked from matheusml/blockchain-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblock.js
More file actions
29 lines (23 loc) · 762 Bytes
/
Copy pathblock.js
File metadata and controls
29 lines (23 loc) · 762 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
const sha256 = require('crypto-js/sha256')
class Block {
constructor(index = 0, previousHash = null, data = 'Genesis block', difficulty = 1) {
this.index = index
this.previousHash = previousHash
this.data = data
this.timestamp = new Date()
this.difficulty = difficulty
this.nonce = 0
this.mine()
}
generateHash() {
return sha256(this.index + this.previousHash + JSON.stringify(this.data) + this.timestamp + this.nonce).toString()
}
mine() {
this.hash = this.generateHash()
while (!(/^0*$/.test(this.hash.substring(0, this.difficulty)))) {
this.nonce++
this.hash = this.generateHash()
}
}
}
module.exports = Block