node-csfd-api
Version:
ČSFD API in JavaScript. Amazing NPM library for scrapping csfd.cz :)
40 lines (39 loc) • 1.56 kB
JavaScript
const require_sha256 = require("./sha256.cjs");
//#region src/anubis/proof-of-work.ts
const DEFAULT_TIME_BUDGET_MS = 1e4;
const YIELD_INTERVAL = 4096;
const scheduleImmediate = globalThis.setImmediate;
const yieldToEventLoop = scheduleImmediate ? () => new Promise((resolve) => scheduleImmediate(() => resolve())) : () => new Promise((resolve) => setTimeout(() => resolve(), 0));
/**
* Find a nonce whose `sha256(data + nonce)` digest starts with `difficulty`
* zero nibbles, mirroring Anubis' own worker: whole zero bytes first, then the
* high nibble of the next byte when difficulty is odd.
*
* Resolves `null` if no nonce is found within the time budget.
*/
const solveProofOfWork = async (data, difficulty, timeBudgetMs = DEFAULT_TIME_BUDGET_MS) => {
const requiredZeroBytes = Math.floor(difficulty / 2);
const isDifficultyOdd = difficulty % 2 !== 0;
const deadline = Date.now() + timeBudgetMs;
for (let nonce = 0;; nonce++) {
if (nonce > 0 && nonce % YIELD_INTERVAL === 0) {
if (Date.now() > deadline) return null;
await yieldToEventLoop();
}
const digest = require_sha256.sha256(data + nonce);
let valid = true;
for (let i = 0; i < requiredZeroBytes; i++) if (digest[i] !== 0) {
valid = false;
break;
}
if (valid && isDifficultyOdd && digest[requiredZeroBytes] >> 4 !== 0) valid = false;
if (valid) return {
hash: require_sha256.toHex(digest),
nonce
};
}
};
//#endregion
exports.DEFAULT_TIME_BUDGET_MS = DEFAULT_TIME_BUDGET_MS;
exports.solveProofOfWork = solveProofOfWork;
//# sourceMappingURL=proof-of-work.cjs.map