Files
minibin/static/js/pow-worker.js
T
whoswhip 5c2427b096 reports!!!! and PoW!!!!!!!
this has taken quite a while (8 ish hours) but reports and proof of work challenges are completely implemented

the proof of work challenges are bit iffy and could be gpu accelerated which is bad, so i plan to eventually switch to something memory hard like argon2id

references used for pow:
https://dev.to/ratmd/simple-proof-of-work-in-javascript-3kgm
https://anubis.techaro.lol/docs/design/how-anubis-works
https://anubis.techaro.lol/docs/design/why-proof-of-work

as well as some other posts or repos found when searching
2026-11-20 21:31:37 -05:00

32 lines
1.5 KiB
JavaScript

function hasLeadingZeroBits(bytes, requiredBits) {
const whole = Math.floor(requiredBits / 8);
const remaining = requiredBits % 8;
for (let i = 0; i < whole; i++) {
if (bytes[i] !== 0) return false;
}
return remaining === 0 || bytes[whole] >>> (8 - remaining) === 0;
}
self.onmessage = async ({ data }) => {
const { challenge, difficulty, startNonce = 0 } = data;
if (difficulty < 0 || difficulty > 256 || !Number.isInteger(difficulty)) {
throw new Error("Invalid difficulty");
}
console.log(`[PoW] Difficulty: ${difficulty}, Starting Nonce: ${startNonce}, Challenge: ${challenge}`)
const startTime = performance.now();
const encoder = new TextEncoder();
for (let nonce = startNonce; ; nonce++) {
const input = encoder.encode(`${challenge}${nonce}`);
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", input));
if (hasLeadingZeroBits(digest, difficulty)) {
const hashHex = Array.from(digest).map((b) => b.toString(16).padStart(2, "0")).join("");
const elapsed = performance.now() - startTime;
const attempts = nonce - startNonce + 1;
console.log(`[PoW] took ${elapsed} ms to solve challenge`)
console.log(`[PoW] ${(attempts / (elapsed / 1000)).toFixed(0)} hashes/s`)
console.log(`[PoW] Result: ${hashHex}, Nonce: ${nonce}`)
self.postMessage({ nonce: nonce, hash: hashHex, });
return;
}
}
};