|
5 | 5 | */ |
6 | 6 |
|
7 | 7 | import * as bitcoin from "bitcoinjs-lib" |
8 | | -import * as ecc from 'tiny-secp256k1'; |
9 | 8 | import { toXOnly } from 'bitcoinjs-lib/src/psbt/bip371'; |
10 | 9 | import { deriveChildPublicKey, networkData, Network } from "@caravan/bitcoin" |
11 | 10 | import { fullDerivationPath, partialKeyDerivationPath } from "./paths" |
@@ -35,7 +34,20 @@ const DEFAULT_NETWORK = Network.TESTNET |
35 | 34 | * */ |
36 | 35 | const DEFAULT_PURPOSE = Purpose.P2WPKH |
37 | 36 |
|
38 | | -bitcoin.initEccLib(ecc); |
| 37 | +/** |
| 38 | + * The secp256k1 interface to use for Taproot address derivation. |
| 39 | + */ |
| 40 | +let eccInstance = null; |
| 41 | + |
| 42 | +/** |
| 43 | + * Initialize the ECC library for Taproot address derivation. |
| 44 | + * |
| 45 | + * @param {object} eccLib - The secp256k1 interface to use. |
| 46 | + */ |
| 47 | +function initEccLib(eccLib) { |
| 48 | + eccInstance = eccLib; |
| 49 | + bitcoin.initEccLib(eccInstance); |
| 50 | +} |
39 | 51 |
|
40 | 52 | /** |
41 | 53 | * Derive a single address from a public key. |
@@ -73,7 +85,9 @@ function deriveAddress({ purpose, pubkey, network }) { |
73 | 85 | return bc1qAddress |
74 | 86 | } |
75 | 87 | case Purpose.P2TR: { |
76 | | - // Context: https://bitcoinops.org/en/topics/x-only-public-keys/ |
| 88 | + if (!eccInstance) { |
| 89 | + throw new Error("An instance of an ECC library implementing the secp256k1 curve must be initialized to generate taproot addresses. You must first call initEccLib()."); |
| 90 | + } |
77 | 91 | const xOnlyPubkey = toXOnly(pubkey) |
78 | 92 | const { address: bc1pAddress } = bitcoin.payments.p2tr({ |
79 | 93 | internalPubkey: xOnlyPubkey, |
@@ -176,4 +190,4 @@ function addressesFromExtPubKey({ |
176 | 190 | return addresses |
177 | 191 | } |
178 | 192 |
|
179 | | -export { addressFromExtPubKey, addressesFromExtPubKey } |
| 193 | +export { addressFromExtPubKey, addressesFromExtPubKey, initEccLib } |
0 commit comments