JSFiddle - React, Tailwind, and code Playground
by msfrisbie
JavaScript
function miningWorkerScript() {
async function mine(lastBlock, difficulty, nonce=0) {
const encoder = new TextEncoder();
const bitmask = parseInt('1'.repeat(difficulty) +
'0'.repeat(32 - difficulty), 2);
while(1) {
const hash = await self.crypto.subtle.digest(
'SHA-256', encoder.encode(lastBlock + nonce));
const leftBits = (new Int32Array(hash))[0];
if ((leftBits & bitmask) === 0) {
self.postMessage(nonce);
break;
} else if (++nonce > 2**10) {
break;
}
}
}
self.onmessage = ({data}) => {
mine(data.lastBlock, data.difficulty, data.initialNonce);
};
}
const workerScript = URL.createObjectURL(
new Blob([`(${miningWorkerScript.toString()})()`]))
const workerPool = [];
for (let i = 0; i < 4; ++i) {
workerPool.push(new Worker(workerScript));
workerPool[i].onmessage = ({data}) => {
console.log(`Found ${data} in ${performance.now() - startTime}ms`);
};
}
const startTime = performance.now();
worker.postMessage({lastBlock: 'abcdefghij', difficulty: 16});
// blob worker script
/* mine('abcdefghij', 16); */