Attempt to speed up signature verification

This commit is contained in:
Jon Staab
2024-11-21 15:33:13 -08:00
parent 81bf3bec10
commit 2bc575dc21
4 changed files with 24 additions and 11 deletions
+2 -1
View File
@@ -32,6 +32,7 @@
},
"dependencies": {
"@welshman/lib": "~0.0.25",
"nostr-tools": "^2.7.2"
"nostr-tools": "^2.7.2",
"nostr-wasm": "^0.1.0"
}
}
+12 -4
View File
@@ -1,10 +1,16 @@
import {verifiedSymbol} from 'nostr-tools'
import {verifyEvent, getEventHash} from 'nostr-tools'
import {initNostrWasm, type Nostr} from 'nostr-wasm'
import {verifiedSymbol, getEventHash, verifyEvent} from 'nostr-tools'
import {cached, pick, now} from '@welshman/lib'
import {Tags} from './Tags'
import {getAddress} from './Address'
import {isEphemeralKind, isReplaceableKind, isPlainReplaceableKind, isParameterizedReplaceableKind} from './Kinds'
let nw: Nostr
initNostrWasm().then(nostrWasm => {
nw = nostrWasm
})
export type EventContent = {
tags: string[][]
content: string
@@ -92,7 +98,7 @@ export const asUnwrappedEvent = (e: UnwrappedEvent): UnwrappedEvent =>
export const asTrustedEvent = (e: TrustedEvent): TrustedEvent =>
pick(['kind', 'tags', 'content', 'created_at', 'pubkey', 'id', 'sig', 'wrap'], e)
export const hasValidSignature = cached<string, boolean, [SignedEvent]>({
const _hasValidSignature = cached<string, boolean, [SignedEvent]>({
maxSize: 10000,
getKey: ([e]: [SignedEvent]) => {
try {
@@ -103,7 +109,7 @@ export const hasValidSignature = cached<string, boolean, [SignedEvent]>({
},
getValue: ([e]: [SignedEvent]) => {
try {
verifyEvent(e)
nw ? nw.verifyEvent(e) : verifyEvent(e)
} catch (err) {
return false
}
@@ -112,6 +118,8 @@ export const hasValidSignature = cached<string, boolean, [SignedEvent]>({
},
})
export const hasValidSignature = (e: SignedEvent) => e[verifiedSymbol] || _hasValidSignature(e)
export const getIdentifier = (e: EventTemplate) => e.tags.find(t => t[0] === 'd')?.[1]
export const getIdOrAddress = (e: HashedEvent) => isReplaceable(e) ? getAddress(e) : e.id