-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblock.js
52 lines (43 loc) · 1.42 KB
/
block.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
const Miner = require('./miner');
const CryptoJS = require("crypto-js");
module.exports = class Block {
constructor(data, previousHash = null, timestamp = null, hash = null, nonce = null) {
this.previousHash = previousHash;
this.timestamp = timestamp || Math.floor(Date.now() / 1000);
this.data = data;
this.hash = hash;
this.nonce = nonce;
}
static parse(json) {
return new Block(json.data, json.previousHash, json.timestamp, json.hash, json.nonce);
}
toJson() {
return {
previousHash: this.previousHash,
timestamp: this.timestamp,
data: this.data,
hash: this.hash,
nonce: this.nonce
}
}
calculateHash(nonce) {
nonce = nonce || this.nonce;
return CryptoJS.SHA256(this.previousHash +
this.timestamp +
this.data +
nonce).toString();
}
static validateHash(hash, complexity) {
return hash.startsWith(Array(complexity).fill('0').join(''));
}
mine(complexity) {
if(!this.miningPromise) {
this.miningPromise = Miner.mine(this, complexity).then(data => {
this.nonce = data.nonce;
this.hash = data.hash;
return this;
});
}
return this.miningPromise;
}
}