-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlock.js
More file actions
61 lines (54 loc) · 1.92 KB
/
Block.js
File metadata and controls
61 lines (54 loc) · 1.92 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
const crypto = require('crypto');
class Block {
constructor(index, transactionSet, previousHash, difficulty) {
this.index = index;
this.timestamp = Date.now();
this.transactionSet = transactionSet;
this.previousHash = previousHash;
this.salt = crypto.randomBytes(16).toString('hex');
this.difficulty = difficulty;
this.hash = null;
}
calculateHash() {
return new Promise((resolve, reject) => {
if (this.index === undefined || this.timestamp === undefined || this.transactionSet === undefined || this.previousHash === undefined || this.salt === undefined || this.difficulty === undefined) {
return reject(new Error('bad_request'));
}
try {
const data = this.index + this.timestamp + JSON.stringify(this.transactionSet) + this.previousHash + this.salt + this.difficulty;
const hash = crypto.createHash('sha256').update(data).digest('hex');
resolve(hash);
} catch (err) {
reject(err);
}
});
}
getHash() {
return new Promise((resolve, reject) => {
if (!this.hash) {
return reject(new Error('bad_hash'));
}
resolve(this.hash);
});
}
mineBlock() {
return new Promise(async (resolve, reject) => {
if (this.index === undefined || this.timestamp === undefined || this.transactionSet === undefined || this.previousHash === undefined || this.salt === undefined || this.difficulty === undefined) {
return reject(new Error('bad_request'));
}
try {
let hash;
do {
this.salt = crypto.randomBytes(16).toString('hex');
hash = await this.calculateHash();
if (typeof hash !== 'string') throw new Error('hash_not_string');
} while (hash.substring(0, this.difficulty) !== '0'.repeat(this.difficulty));
this.hash = hash;
resolve(this.hash);
} catch (err) {
reject(err);
}
});
}
}
module.exports = Block;