nip13: use a simpler implementation

This commit is contained in:
Alex Gleason
2023-09-10 10:51:50 -05:00
committed by fiatjaf_
parent c18f050468
commit c890e29290

View File

@@ -1,42 +1,16 @@
import { hexToBytes } from '@noble/hashes/utils'
/** Get POW difficulty from a Nostr hex ID. */ /** Get POW difficulty from a Nostr hex ID. */
export function getPow(id: string): number { export function getPow(hex: string): number {
return getLeadingZeroBits(hexToBytes(id)) let count = 0
}
/** for (let i = 0; i < hex.length; i++) {
* Get number of leading 0 bits. Adapted from nostream. const nibble = parseInt(hex[i], 16)
* https://github.com/Cameri/nostream/blob/fb6948fd83ca87ce552f39f9b5eb780ea07e272e/src/utils/proof-of-work.ts if (nibble === 0) {
*/ count += 4
function getLeadingZeroBits(hash: Uint8Array): number { } else {
let total: number, i: number, bits: number count += Math.clz32(nibble) - 28
for (i = 0, total = 0; i < hash.length; i++) {
bits = msb(hash[i])
total += bits
if (bits !== 8) {
break break
} }
} }
return total
} return count
/**
* 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
} }