From: Chris Duncan Date: Fri, 22 May 2026 18:27:31 +0000 (-0700) Subject: Extract equivalence test for cached work. X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=ea835367660946dfa37f1fa68361601bc82c75ad;p=nano-pow.git Extract equivalence test for cached work. --- diff --git a/src/utils/cache.ts b/src/utils/cache.ts index 779a227..6e86a3f 100644 --- a/src/utils/cache.ts +++ b/src/utils/cache.ts @@ -5,7 +5,13 @@ import { WorkGenerateResponse } from 'nano-pow' const STORAGE_KEY = 'NanoPowCache' -let storage: { [key: string]: string } = {} +let storage: Record = {} + +function eq (a: unknown, b: bigint): boolean { + return typeof a === 'string' + && /^([a-f0-9]{2})+$/i.test(a) + && BigInt(`0x${a}`) === b +} function getItem (key: string): string | null { if (globalThis?.localStorage) return globalThis.localStorage.getItem(key) @@ -30,12 +36,8 @@ export function get (hash: bigint, difficulty: bigint): WorkGenerateResponse | n const item = getItem(STORAGE_KEY) if (item == null) return null const cache: WorkGenerateResponse[] = JSON.parse(item) - for (const c of cache) { - if (BigInt(`0x${c.hash}`) === hash && BigInt(`0x${c.difficulty}`) >= difficulty) { - return c - } - } - return null + const match = cache.find(c => eq(c.hash, hash) && eq(c.difficulty, difficulty)) + return match ?? null } export function remove (hash: bigint): void { @@ -43,11 +45,11 @@ export function remove (hash: bigint): void { if (item == null) return const cache = JSON.parse(item) as WorkGenerateResponse[] for (let i = 0; i < cache.length; i++) { - if (BigInt(`0x${cache[i].hash}`) === hash) { + if (eq(cache[i].hash, hash)) { cache.splice(i, 1) } } - setItem('NanoPowCache', JSON.stringify(cache)) + setItem(STORAGE_KEY, JSON.stringify(cache)) } export function set (result: WorkGenerateResponse): WorkGenerateResponse {