From 0c2c2cd4d871dfb47ae5f5d0add758dffb57d214 Mon Sep 17 00:00:00 2001 From: fiatjaf Date: Sun, 8 Feb 2026 01:06:01 -0300 Subject: [PATCH] nip13: improve mining by skipping hex. --- nip13.ts | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/nip13.ts b/nip13.ts index ce786ad..8b078a4 100644 --- a/nip13.ts +++ b/nip13.ts @@ -21,6 +21,23 @@ export function getPow(hex: string): number { return count } +/** Get POW difficulty directly from a Uint8Array hash. */ +function getPowFromBytes(hash: Uint8Array): number { + let count = 0 + + for (let i = 0; i < hash.length; i++) { + const byte = hash[i] + if (byte === 0) { + count += 8 + } else { + count += Math.clz32(byte) - 24 + break + } + } + + return count +} + /** * Mine an event with the desired POW. This function mutates the event. * Note that this operation is synchronous and should be run in a worker context to avoid blocking the main thread. @@ -43,18 +60,15 @@ export function minePow(unsigned: UnsignedEvent, difficulty: number): Omit= difficulty) { + if (getPowFromBytes(hash) >= difficulty) { + event.id = bytesToHex(hash) break } } return event } - -export function fastEventHash(evt: UnsignedEvent): string { - return bytesToHex( - sha256(utf8Encoder.encode(JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]))), - ) -}