JSFiddle - React, Tailwind, and code Playground
by msfrisbie
JavaScript
async function mine(block, difficulty) {
const encoder = new TextEncoder();
const bitmask = parseInt('1'.repeat(difficulty) + '0'.repeat(32 - difficulty), 2);
let nonce = 0;
while(1) {
const hash = await window.crypto.subtle.digest('SHA-256', encoder.encode(block + nonce));
const leftBits = (new Int32Array(hash))[0];
if ((leftBits & bitmask) === 0) {
console.log('block mined', nonce);
break;
} else {
++nonce;
if (nonce > 1000000) {
break;
}
}
}
}
mine('abcdefghij', 16);