-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmine.js
48 lines (36 loc) · 1.03 KB
/
mine.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
const Block = require('./models/Block');
const Transaction = require('./models/Transaction');
const UTXO = require('./models/UTXO');
const db = require('./db');
const {PUBLIC_KEY} = require('./config');
const TARGET_DIFFICULTY = BigInt("0x0" + "F".repeat(63));
const BLOCK_REWARD = 10;
//Auto Mining off.
let mining = false;
// mine();
function startMining() {
mining = true;
mine();
}
function stopMining() {
mining = false;
}
function mine() {
if(!mining) return;
const block = new Block();
// Dan's Todo: add transactions from the mempool
const coinbaseUTXO = new UTXO(PUBLIC_KEY, BLOCK_REWARD);
const coinbaseTX = new Transaction([], [coinbaseUTXO]);
block.addTransaction(coinbaseTX);
while(BigInt('0x' + block.hash()) >= TARGET_DIFFICULTY) {
block.nonce++;
}
block.execute();
db.blockchain.addBlock(block);
console.log(`Mined block #${db.blockchain.blockHeight()} with a hash of ${block.hash()} at nonce ${block.nonce}`);
setTimeout(mine, 2500);
}
module.exports = {
startMining,
stopMining,
};