]> git.codecow.com Git - nano-pow.git/commitdiff
Extract equivalence test for cached work.
authorChris Duncan <chris@codecow.com>
Fri, 22 May 2026 18:27:31 +0000 (11:27 -0700)
committerChris Duncan <chris@codecow.com>
Fri, 22 May 2026 18:27:31 +0000 (11:27 -0700)
src/utils/cache.ts

index 779a227bed938030d56cbfefa566f9a9642e0d5b..6e86a3fe3335ee44cf884695e95b24edd0fe9c44 100644 (file)
@@ -5,7 +5,13 @@ import { WorkGenerateResponse } from 'nano-pow'
 
 const STORAGE_KEY = 'NanoPowCache'
 
-let storage: { [key: string]: string } = {}
+let storage: Record<string, string> = {}
+
+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 {