-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblock.js
64 lines (55 loc) · 1.48 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
53
54
55
56
57
58
59
60
61
62
63
64
const hexToBinary = require('hex-to-binary');
const cryptoHash = require('./crypto.hash');
const { GENESIS_BLOCK_DATA, MINE_RATE } = require('./config');
class Block {
constructor({ timestamp, lastHash, hash, nonce, difficulty, data }) {
this.timestamp = timestamp;
this.lastHash = lastHash;
this.hash = hash;
this.nonce = nonce;
this.difficulty = difficulty;
this.data = data;
}
// GENESIS BLOCK
static genesisBlock() {
return new Block(GENESIS_BLOCK_DATA);
}
// MINE A BLOCK
static mineBlock({ lastBlock, data }) {
let hash, timestamp;
const lastHash = lastBlock.hash;
let { difficulty } = lastBlock;
let nonce = 0;
// Proof of work
do {
nonce++;
timestamp = Date.now();
difficulty = Block.adjustDifficulty({
originalBlock: lastBlock,
timestamp
});
hash = cryptoHash(timestamp, lastHash, data, difficulty, nonce);
} while (
hexToBinary(hash).substring(0, difficulty) !== '0'.repeat(difficulty)
);
return new Block({
timestamp,
lastHash,
hash,
data,
nonce,
difficulty
});
}
// ADJUST THE MINE RATE OF BLOCKS
static adjustDifficulty({ originalBlock, timestamp }) {
const { difficulty } = originalBlock;
if (difficulty < 1) return 1;
const timeDifference = timestamp - originalBlock.timestamp;
if (timeDifference > MINE_RATE) {
return difficulty - 1;
}
return difficulty + 1;
}
}
module.exports = Block;