chaingate
Version:
A complete TypeScript library for connecting to and making transactions on different blockchains
82 lines • 3.23 kB
JavaScript
import { UtxoCurrencyUtils } from '../UtxoCurrencyUtils/UtxoCurrencyUtils';
import { PublicKey } from '../../../../Wallet/entities/PublicKey';
import * as btc from '@scure/btc-signer';
import { getSignedMessagePublicKey, signMessage, } from '../../../CurrencyWallet/abstract/UtxoWallet/MessageSigner';
export class Bech32UtxoCurrencyUtils extends UtxoCurrencyUtils {
constructor(client, currencyInfo, markets, network, networkParams, signHeader) {
super(client, currencyInfo, markets, network, networkParams, signHeader);
}
publicKeyToAddress(publicKey, addressType = 'segwit-p2wpkh') {
let publicKeyRaw = publicKey.raw;
switch (addressType) {
case 'legacy-p2pkh':
return btc.p2pkh(publicKeyRaw, this.networkParams).address;
case 'legacy-p2pk':
return btc.p2pkh(publicKeyRaw).address;
case 'segwit-p2wpkh':
return btc.p2wpkh(publicKeyRaw, this.networkParams).address;
case 'taproot-p2tr':
if (publicKeyRaw.length === 33)
publicKeyRaw = publicKeyRaw.slice(1);
return btc.p2tr(publicKeyRaw, undefined, this.networkParams).address;
default:
throw new Error(`Address type "${addressType}" not supported`);
}
}
identifyAddressType(address) {
try {
const addr = btc.Address(this.networkParams).decode(address);
switch (addr.type) {
case 'pkh':
return 'legacy-p2pkh';
case 'sh':
return 'legacy-p2sh';
case 'pk':
return 'legacy-p2pk';
case 'ms':
return 'legacy-p2ms';
case 'wpkh':
return 'segwit-p2wpkh';
case 'wsh':
return 'segwit-p2wsh';
case 'tr':
return 'taproot-p2tr';
case 'tr_ns':
return 'taproot-n-of-n';
case 'tr_ms':
return 'taproot-m-of-n';
case 'p2a':
return 'anchor';
default:
return 'unknown';
}
}
catch {
return 'unknown';
}
}
signMessage(message, privateKey) {
return signMessage(message, privateKey, this.signHeader);
}
async verifySignedMessage(message, signature, address) {
const publicKeyRaw = await getSignedMessagePublicKey(message, signature, this.signHeader);
const publicKey = new PublicKey(publicKeyRaw);
const addressType = this.identifyAddressType(address);
const supportedTypes = [
'legacy-p2pkh',
'legacy-p2pk',
'segwit-p2wpkh',
'taproot-p2tr',
];
if (!supportedTypes.includes(addressType))
return false;
try {
const derivedAddress = this.publicKeyToAddress(publicKey, addressType);
return derivedAddress === address;
}
catch {
return false;
}
}
}
//# sourceMappingURL=Bech32UtxoCurrencyUtils.js.map