UNPKG

node-csfd-api

Version:

ČSFD API in JavaScript. Amazing NPM library for scrapping csfd.cz :)

39 lines (38 loc) 1.48 kB
import { sha256, toHex } from "./sha256.js"; //#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 = 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: toHex(digest), nonce }; } }; //#endregion export { DEFAULT_TIME_BUDGET_MS, solveProofOfWork }; //# sourceMappingURL=proof-of-work.js.map