-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlock.js
More file actions
70 lines (62 loc) · 1.33 KB
/
Block.js
File metadata and controls
70 lines (62 loc) · 1.33 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
'use strict'
const sha256 = require('sha256')
module.exports = class Block {
constructor(data, prevHash) {
this.id = 0
this._timestamp = Date.now()
this._data = data
this._prevHash = prevHash
this.nonce = 0;
this._hash = this.calcHash()
}
get hash() {
return this._hash
}
set hash(hash) {
this._hash = hash
}
set timestamp(timestamp) {
this._timestamp = timestamp
}
get timestamp() {
return this._timestamp
}
set data(data) {
this._data = data
}
get data() {
return this._data
}
set prevHash(prevHash) {
this._prevHash = prevHash
}
get prevHash() {
return this._prevHash
}
calcHash() {
this._hash = sha256(
this.id + this._prevHash + this._timestamp + this._data + this.nonce
).toString()
}
mineBlock(difficulty) {
const builCrit = function(numberOfZeros) {
var crit = ''
for (var i = 0; i < numberOfZeros; i++) {
crit = crit + '0'
}
return crit
}
var crit = builCrit(difficulty)
var ok = false
while (!ok) {
var comp = this._hash.substring(0, difficulty).localeCompare(crit)
if (comp === 0) {
ok = true
} else {
this.nonce = this.nonce + 1
this.calcHash()
}
}
console.log('BLOCK MINED:' + this._hash + "\nnonce: " + this.nonce)
}
}