From c890e29290020224a6c1f43870167261a0733672 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 10 Sep 2023 10:51:50 -0500 Subject: [PATCH] nip13: use a simpler implementation --- nip13.ts | 46 ++++++++++------------------------------------ 1 file changed, 10 insertions(+), 36 deletions(-) diff --git a/nip13.ts b/nip13.ts index 654df22..3472162 100644 --- a/nip13.ts +++ b/nip13.ts @@ -1,42 +1,16 @@ -import { hexToBytes } from '@noble/hashes/utils' - /** Get POW difficulty from a Nostr hex ID. */ -export function getPow(id: string): number { - return getLeadingZeroBits(hexToBytes(id)) -} +export function getPow(hex: string): number { + let count = 0 -/** - * Get number of leading 0 bits. Adapted from nostream. - * https://github.com/Cameri/nostream/blob/fb6948fd83ca87ce552f39f9b5eb780ea07e272e/src/utils/proof-of-work.ts - */ -function getLeadingZeroBits(hash: Uint8Array): number { - let total: number, i: number, bits: number - - for (i = 0, total = 0; i < hash.length; i++) { - bits = msb(hash[i]) - total += bits - if (bits !== 8) { + for (let i = 0; i < hex.length; i++) { + const nibble = parseInt(hex[i], 16) + if (nibble === 0) { + count += 4 + } else { + count += Math.clz32(nibble) - 28 break } } - return total -} - -/** - * Adapted from nostream. - * https://github.com/Cameri/nostream/blob/fb6948fd83ca87ce552f39f9b5eb780ea07e272e/src/utils/proof-of-work.ts - */ -function msb(b: number) { - let n = 0 - - if (b === 0) { - return 8 - } - - // eslint-disable-next-line no-cond-assign - while ((b >>= 1)) { - n++ - } - - return 7 - n + + return count }