Skip to content

Instantly share code, notes, and snippets.

@Dan-Nolan
Created June 4, 2020 19:05
Show Gist options
  • Save Dan-Nolan/b8aeb61264bd2d5098e4ad722c9a937c to your computer and use it in GitHub Desktop.
Save Dan-Nolan/b8aeb61264bd2d5098e4ad722c9a937c to your computer and use it in GitHub Desktop.
Miner
const SHA256 = require('crypto-js/sha256');
const TARGET_DIFFICULTY = BigInt(0x0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
const MAX_TRANSACTIONS = 10;
const mempool = [];
const blocks = [];
function addTransaction(transaction) {
mempool.push(transaction);
}
function mine() {
let transactions = [];
while (transactions.length < MAX_TRANSACTIONS && mempool.length > 0) {
transactions.push(mempool.pop());
}
const block = { id: blocks.length, transactions }
block.nonce = 0;
let hash;
while (true) {
hash = SHA256(JSON.stringify(block)).toString();
if (BigInt(`0x${hash}`) < TARGET_DIFFICULTY) {
break;
}
block.nonce++;
}
blocks.push({ ...block, hash });
}
module.exports = {
TARGET_DIFFICULTY,
MAX_TRANSACTIONS,
addTransaction,
mine,
mempool,
blocks,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment