import { PoolErrorException } from '../error/pool.error'; import { p2tr } from '@scure/btc-signer'; import { Message, MessageUtil, SanitizedMessage, SanitizedMessageUtil, } from '@saturnbtcio/arch-sdk'; import { toXOnly } from '@saturnbtcio/psbt'; import { hex } from '@scure/base'; import { NETWORK } from '@scure/btc-signer'; import { Verifier as BIP322Verifier } from '@saturnbtcio/bip322-js'; import { PoolErrorType } from '../error/pool.error'; export const verifyBip322Signature = ( signature: string, message: SanitizedMessage, pubkey: string, network: typeof NETWORK, ) => { const toXPubkey = toXOnly(hex.decode(pubkey)); const address = p2tr(toXPubkey, undefined, network).address; if (!address) { throw new PoolErrorException({ message: `Invalid pubkey`, type: PoolErrorType.InvalidSignature, }); } const isValid = BIP322Verifier.verifySignature( address, new TextDecoder().decode(SanitizedMessageUtil.hash(message)), signature, ); if (!isValid) { throw new PoolErrorException({ message: `Invalid signature`, type: PoolErrorType.InvalidSignature, }); } };