Created
June 4, 2020 19:05
-
-
Save Dan-Nolan/b8aeb61264bd2d5098e4ad722c9a937c to your computer and use it in GitHub Desktop.
Miner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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