From 626b821e2e3e8444934e443a1ddc9d1274f33ecb Mon Sep 17 00:00:00 2001 From: Polybius93 Date: Wed, 18 Sep 2024 14:21:37 +0200 Subject: [PATCH] feat: add function to retrieve bitcoin address from extended public key --- package.json | 2 +- src/functions/bitcoin/bitcoin-functions.ts | 22 ++++++++++++++++++++++ src/functions/bitcoin/index.ts | 2 ++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index cc888ae..58c6ea0 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "type": "module", "name": "dlc-btc-lib", - "version": "2.2.6", + "version": "2.2.7", "description": "This library provides a comprehensive set of interfaces and functions for minting dlcBTC tokens on supported blockchains.", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/src/functions/bitcoin/bitcoin-functions.ts b/src/functions/bitcoin/bitcoin-functions.ts index 3ce87b4..fc466fe 100644 --- a/src/functions/bitcoin/bitcoin-functions.ts +++ b/src/functions/bitcoin/bitcoin-functions.ts @@ -481,3 +481,25 @@ export function ecdsaPublicKeyToSchnorr(publicKey: Buffer): Buffer { throw new Error('Invalid Public Key Length'); return publicKey.subarray(1); } + +export function getBitcoinAddressFromExtendedPublicKey( + bitcoinExtendedPublicKey: string, + bitcoinNetwork: Network, + bitcoinAddressIndex: number, + paymentType: 'wpkh' | 'tr' +): string { + const derivedPublicKey = deriveUnhardenedPublicKey( + bitcoinExtendedPublicKey, + bitcoinNetwork, + bitcoinAddressIndex + ); + + const bitcoinAddress = + paymentType === 'wpkh' + ? p2wpkh(derivedPublicKey, bitcoinNetwork).address + : p2tr(ecdsaPublicKeyToSchnorr(derivedPublicKey), undefined, bitcoinNetwork).address; + + if (!bitcoinAddress) throw new Error('Could not create Bitcoin Address'); + + return bitcoinAddress; +} diff --git a/src/functions/bitcoin/index.ts b/src/functions/bitcoin/index.ts index 8755d3a..80c546a 100644 --- a/src/functions/bitcoin/index.ts +++ b/src/functions/bitcoin/index.ts @@ -1,5 +1,6 @@ import { finalizeUserInputs, + getBitcoinAddressFromExtendedPublicKey, getFeeAmount, getFeeRecipientAddressFromPublicKey, getInputIndicesByScript, @@ -28,4 +29,5 @@ export { getBalance, getFeeRecipientAddressFromPublicKey, getInputIndicesByScript, + getBitcoinAddressFromExtendedPublicKey, };