@dynamic-labs-wallet/btc 0.0.354 → 0.1.0-request-signing

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.esm.js CHANGED
@@ -1,7 +1,7 @@
1
- import { DynamicWalletClient, BitcoinNetwork, BitcoinAddressType, getMPCChainConfig, ERROR_CREATE_WALLET_ACCOUNT, ERROR_PASSWORD_MISMATCH, ERROR_ACCOUNT_ADDRESS_REQUIRED, ERROR_SIGN_MESSAGE, ERROR_IMPORT_PRIVATE_KEY, AuthMode } from '@dynamic-labs-wallet/browser';
1
+ import { DynamicWalletClient, BitcoinNetwork, BitcoinAddressType, getMPCChainConfig, ERROR_CREATE_WALLET_ACCOUNT, ERROR_PASSWORD_MISMATCH, ERROR_MULTIPLE_WALLETS_PER_CHAIN, ERROR_SIGN_MESSAGE, ERROR_ACCOUNT_ADDRESS_REQUIRED, ERROR_IMPORT_PRIVATE_KEY } from '@dynamic-labs-wallet/browser';
2
2
  import * as bitcoin from 'bitcoinjs-lib';
3
3
  import ecc from '@bitcoinerlab/secp256k1';
4
- import { extractPublicKeyHex, normalizePublicKey, publicKeyToBitcoinAddress, getAddressTypeFromDerivationPath, calculateBip322Hash, calculateTaprootTweak, encodeBip322Signature, wifToPrivateKey, getPublicKeyFromPrivateKey, privateKeyToWIF, doesInputBelongToAddress, collectPSBTInputData, convertSignatureToTaprootBuffer, getBitcoinNetwork, convertSignatureToDER, getFeeRates, getUTXOs, selectUTXOs, getDefaultRpcUrl, initEccLib } from '@dynamic-labs-wallet/btc-utils';
4
+ import { extractPublicKeyHex, normalizePublicKey, publicKeyToBitcoinAddress, resolveBitcoinAddressType, calculateTaprootTweak, encodeBip322Signature, calculateBip322Hash, wifToPrivateKey, getPublicKeyFromPrivateKey, privateKeyToWIF, doesInputBelongToAddress, filterInputsBySigningIndexes, assertSighashAllowed, collectPSBTInputData, getSigHashType, convertSignatureToTaprootBuffer, getSegwitV0ScriptCode, getBitcoinNetwork, convertSignatureToDER, getFeeRates, getUTXOs, selectUTXOs, resolveRpcUrl, rpcFetch, initEccLib, toBitcoinNetwork, extractPsbtIntentOperation, getBtcChainId } from '@dynamic-labs-wallet/btc-utils';
5
5
 
6
6
  function _extends() {
7
7
  _extends = Object.assign || function assign(target) {
@@ -37,7 +37,7 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
37
37
  * @param signedSessionId - The signed session ID to use for the wallet
38
38
  * @param addressType - The type of address to use for the wallet
39
39
  * @returns The account address, public key hex, and raw public key
40
- */ async createWalletAccount({ thresholdSignatureScheme, password = undefined, onError, signedSessionId, bitcoinConfig }) {
40
+ */ async createWalletAccount({ thresholdSignatureScheme, password = undefined, onError, signedSessionId, bitcoinConfig, businessAccountId }) {
41
41
  const network = BitcoinNetwork.MAINNET;
42
42
  var _bitcoinConfig_addressType;
43
43
  const addressType = (_bitcoinConfig_addressType = bitcoinConfig == null ? void 0 : bitcoinConfig.addressType) != null ? _bitcoinConfig_addressType : BitcoinAddressType.NATIVE_SEGWIT;
@@ -65,13 +65,14 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
65
65
  // Use 'BTC' as chain name, derivation path and signing algorithm will be resolved from addressType
66
66
  const { rawPublicKey, clientKeyShares } = await this.keyGen({
67
67
  chainName: this.chainName,
68
+ businessAccountId,
68
69
  thresholdSignatureScheme,
69
70
  bitcoinConfig: buildBitcoinConfig,
70
71
  onError: (error)=>{
71
72
  this.logger.error(ERROR_CREATE_WALLET_ACCOUNT, error);
72
73
  onError == null ? void 0 : onError(error);
73
74
  },
74
- onCeremonyComplete: (accountAddress, walletId, shareSetId)=>{
75
+ onCeremonyComplete: ({ accountAddress, walletId, shareSetId })=>{
75
76
  const chainConfig = getMPCChainConfig(this.chainName, buildBitcoinConfig);
76
77
  this.initializeWalletMapEntry({
77
78
  accountAddress,
@@ -114,7 +115,8 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
114
115
  accountAddress,
115
116
  clientKeyShares,
116
117
  password,
117
- signedSessionId
118
+ signedSessionId,
119
+ businessAccountId
118
120
  });
119
121
  const publicKeyHex = extractPublicKeyHex(rawPublicKey);
120
122
  return {
@@ -123,14 +125,16 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
123
125
  rawPublicKey
124
126
  };
125
127
  } catch (error) {
126
- // Re-throw password mismatch errors without wrapping
127
- if (error instanceof Error && error.message === ERROR_PASSWORD_MISMATCH) {
128
+ // Re-throw known business-rule rejections without wrapping
129
+ if (error instanceof Error && (error.message === ERROR_PASSWORD_MISMATCH || error.message === ERROR_MULTIPLE_WALLETS_PER_CHAIN)) {
128
130
  throw error;
129
131
  }
130
132
  if (onError) {
131
133
  onError(error);
132
134
  }
133
- throw new Error(ERROR_CREATE_WALLET_ACCOUNT);
135
+ throw new Error(ERROR_CREATE_WALLET_ACCOUNT, {
136
+ cause: error
137
+ });
134
138
  }
135
139
  }
136
140
  /**
@@ -151,6 +155,53 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
151
155
  };
152
156
  }
153
157
  /**
158
+ * Raw digest signing.
159
+ *
160
+ * Overridden so BTC can supply what getMPCChainConfig needs. The address
161
+ * type selects the derivation path and the signing algorithm, and taproot
162
+ * additionally needs the BIP-341 tweak: BIP340 signs under the tweaked
163
+ * output key, so a signature produced from the internal key alone would not
164
+ * verify against the wallet's own address. Computing it needs the derived
165
+ * public key, which only this layer has, so callers cannot supply it and the
166
+ * generic implementation cannot derive it.
167
+ *
168
+ * @param params - Raw sign parameters; bitcoinConfig is resolved here
169
+ * @returns The signature, Schnorr for taproot and ECDSA otherwise
170
+ */ async sign(params) {
171
+ const { accountAddress, bitcoinConfig } = params;
172
+ const walletProperties = this.getWalletFromMap(accountAddress);
173
+ const addressType = resolveBitcoinAddressType({
174
+ accountAddress,
175
+ addressType: bitcoinConfig == null ? void 0 : bitcoinConfig.addressType,
176
+ derivationPath: walletProperties == null ? void 0 : walletProperties.derivationPath
177
+ });
178
+ let tweak = bitcoinConfig == null ? void 0 : bitcoinConfig.tweak;
179
+ if (addressType === BitcoinAddressType.TAPROOT && !tweak) {
180
+ const clientKeyShares = await this.getClientKeySharesFromStorage({
181
+ accountAddress
182
+ });
183
+ var _walletProperties_derivationPath;
184
+ const derivedPublicKey = await this.derivePublicKey({
185
+ chainName: this.chainName,
186
+ keyShare: clientKeyShares[0],
187
+ derivationPath: parseDerivationPath((_walletProperties_derivationPath = walletProperties == null ? void 0 : walletProperties.derivationPath) != null ? _walletProperties_derivationPath : ''),
188
+ bitcoinConfig: _extends({}, bitcoinConfig, {
189
+ addressType
190
+ })
191
+ });
192
+ if (!derivedPublicKey) {
193
+ throw new Error('Failed to derive public key');
194
+ }
195
+ tweak = calculateTaprootTweak(normalizePublicKey(derivedPublicKey, addressType));
196
+ }
197
+ return super.sign(_extends({}, params, {
198
+ bitcoinConfig: _extends({}, bitcoinConfig, {
199
+ addressType,
200
+ tweak
201
+ })
202
+ }));
203
+ }
204
+ /**
154
205
  * Signs a message (BIP-322)
155
206
  * @param message - The message to sign
156
207
  * @param accountAddress - The account address
@@ -161,61 +212,17 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
161
212
  * @param context - Additional context
162
213
  * @param onError - Error callback
163
214
  * @returns The BIP-322 signature
164
- */ async signMessage({ message, accountAddress, network, password = undefined, signedSessionId, mfaToken, elevatedAccessToken, context, onError }) {
215
+ */ async signMessage({ message, accountAddress, network, password = undefined, signedSessionId, mfaToken, elevatedAccessToken, context, approvalQuorum, onError }) {
165
216
  await this.verifyPassword({
166
217
  accountAddress,
167
218
  password,
168
219
  signedSessionId
169
220
  });
170
221
  try {
171
- if (!accountAddress) {
172
- throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
173
- }
174
- const walletProperties = this.getWalletFromMap(accountAddress);
175
- if (!walletProperties) {
176
- throw new Error('Wallet not found in walletMap');
177
- }
178
- const derivationPath = walletProperties.derivationPath;
179
- if (derivationPath === undefined || derivationPath === null) {
180
- throw new Error('Derivation path missing in walletMap');
181
- }
182
- let addressType = walletProperties.addressType;
183
- if (!addressType) {
184
- addressType = getAddressTypeFromDerivationPath(derivationPath);
185
- }
186
- const clientKeyShares = await this.getClientKeySharesFromStorage({
187
- accountAddress
188
- });
189
- if (!clientKeyShares || clientKeyShares.length === 0) {
190
- throw new Error('No key shares found');
191
- }
192
- const bitcoinConfig = {
193
- addressType,
222
+ const { addressType, completeBitcoinConfig, formattedMessage, pubKey, toSignPsbt } = await this.prepareBip322SignMessage({
223
+ accountAddress,
224
+ message,
194
225
  network
195
- };
196
- const walletDerivationPath = parseDerivationPath(derivationPath);
197
- const derivedPublicKey = await this.derivePublicKey({
198
- chainName: this.chainName,
199
- keyShare: clientKeyShares[0],
200
- derivationPath: walletDerivationPath,
201
- bitcoinConfig
202
- });
203
- if (!derivedPublicKey) {
204
- throw new Error('Failed to derive public key');
205
- }
206
- const pubKey = normalizePublicKey(derivedPublicKey, addressType);
207
- this.verifyWalletAddress(derivedPublicKey, addressType, network, accountAddress);
208
- // Prepare BIP-322 Transactions and calculate hash
209
- const { formattedMessage, toSignPsbt } = calculateBip322Hash(message, pubKey, addressType, network, ecc);
210
- // Prepare tweak for Taproot in case of BIP340
211
- let tweak;
212
- if (addressType === BitcoinAddressType.TAPROOT) {
213
- tweak = calculateTaprootTweak(pubKey);
214
- }
215
- // Build complete bitcoinConfig with addressType and tweak
216
- const completeBitcoinConfig = _extends({}, bitcoinConfig, {
217
- addressType: addressType,
218
- tweak
219
226
  });
220
227
  // Sign the message using MPC
221
228
  const signature = await this.sign({
@@ -231,6 +238,7 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
231
238
  btcMessage: message
232
239
  },
233
240
  bitcoinConfig: completeBitcoinConfig,
241
+ approvalQuorum,
234
242
  onError
235
243
  });
236
244
  // Encode Final Result
@@ -243,8 +251,62 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
243
251
  if (onError) {
244
252
  onError(error);
245
253
  }
246
- throw new Error(ERROR_SIGN_MESSAGE);
254
+ throw new Error(ERROR_SIGN_MESSAGE, {
255
+ cause: error
256
+ });
257
+ }
258
+ }
259
+ async prepareSignMessage({ accountAddress, message, network }) {
260
+ const { formattedMessage } = await this.prepareBip322SignMessage({
261
+ accountAddress,
262
+ message,
263
+ network
264
+ });
265
+ return `0x${Buffer.from(formattedMessage).toString('hex')}`;
266
+ }
267
+ async prepareBip322SignMessage({ accountAddress, message, network }) {
268
+ if (!accountAddress) throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
269
+ const walletProperties = this.getWalletFromMap(accountAddress);
270
+ if (!walletProperties) throw new Error('Wallet not found in walletMap');
271
+ const derivationPath = walletProperties.derivationPath;
272
+ if (derivationPath === undefined || derivationPath === null) {
273
+ throw new Error('Derivation path missing in walletMap');
247
274
  }
275
+ const addressType = resolveBitcoinAddressType({
276
+ accountAddress,
277
+ addressType: walletProperties.addressType,
278
+ derivationPath
279
+ });
280
+ const clientKeyShares = await this.getClientKeySharesFromStorage({
281
+ accountAddress
282
+ });
283
+ if (!clientKeyShares || clientKeyShares.length === 0) throw new Error('No key shares found');
284
+ const bitcoinConfig = {
285
+ addressType,
286
+ network
287
+ };
288
+ const derivedPublicKey = await this.derivePublicKey({
289
+ chainName: this.chainName,
290
+ keyShare: clientKeyShares[0],
291
+ derivationPath: parseDerivationPath(derivationPath),
292
+ bitcoinConfig
293
+ });
294
+ if (!derivedPublicKey) throw new Error('Failed to derive public key');
295
+ const pubKey = normalizePublicKey(derivedPublicKey, addressType);
296
+ this.verifyWalletAddress(derivedPublicKey, addressType, network, accountAddress);
297
+ const { formattedMessage, toSignPsbt } = calculateBip322Hash(message, pubKey, addressType, network, ecc);
298
+ const tweak = addressType === BitcoinAddressType.TAPROOT ? calculateTaprootTweak(pubKey) : undefined;
299
+ const completeBitcoinConfig = _extends({}, bitcoinConfig, {
300
+ addressType: addressType,
301
+ tweak
302
+ });
303
+ return {
304
+ addressType,
305
+ completeBitcoinConfig,
306
+ formattedMessage,
307
+ pubKey,
308
+ toSignPsbt
309
+ };
248
310
  }
249
311
  /**
250
312
  * Verifies that the derived address matches the expected address
@@ -255,9 +317,19 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
255
317
  */ verifyWalletAddress(rawPublicKey, addressType, network, expectedAddress) {
256
318
  const normalizedKey = normalizePublicKey(rawPublicKey, addressType);
257
319
  const derivedAddress = publicKeyToBitcoinAddress(normalizedKey, addressType, network, ecc);
258
- if (derivedAddress !== expectedAddress) {
259
- throw new Error(`Address verification failed: expected ${expectedAddress}, got ${derivedAddress}`);
320
+ if (derivedAddress === expectedAddress) {
321
+ return;
322
+ }
323
+ // Callers pass the wallet identity address (the mainnet encoding that
324
+ // keys the wallet map) even when signing for another network — the same
325
+ // key encodes differently per network, so accept the identity encoding.
326
+ if (network !== BitcoinNetwork.MAINNET) {
327
+ const identityAddress = publicKeyToBitcoinAddress(normalizedKey, addressType, BitcoinNetwork.MAINNET, ecc);
328
+ if (identityAddress === expectedAddress) {
329
+ return;
330
+ }
260
331
  }
332
+ throw new Error(`Address verification failed: expected ${expectedAddress}, got ${derivedAddress}`);
261
333
  }
262
334
  /**
263
335
  * Exports the private key for a given account
@@ -267,7 +339,29 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
267
339
  * @param mfaToken - The MFA token to use for the private key
268
340
  * @param network - The network to use for the private key
269
341
  * @returns The private key
270
- */ async exportPrivateKey({ accountAddress, password = undefined, signedSessionId, mfaToken, elevatedAccessToken }) {
342
+ */ /**
343
+ * Builds the export Intent for a BTC wallet.
344
+ *
345
+ * Overridden so BTC can supply the address type the signer needs. It selects
346
+ * the derivation path, so without it the export id cannot be computed. It is
347
+ * resolved from the wallet exactly as `exportPrivateKey` does, so the Intent
348
+ * binds the same export id the export itself will compute.
349
+ */ async prepareExportIntent(params) {
350
+ var _params_bitcoinConfig;
351
+ const walletProperties = this.getWalletFromMap(params.accountAddress);
352
+ var _params_bitcoinConfig_addressType;
353
+ const addressType = resolveBitcoinAddressType({
354
+ accountAddress: params.accountAddress,
355
+ addressType: (_params_bitcoinConfig_addressType = (_params_bitcoinConfig = params.bitcoinConfig) == null ? void 0 : _params_bitcoinConfig.addressType) != null ? _params_bitcoinConfig_addressType : walletProperties == null ? void 0 : walletProperties.addressType,
356
+ derivationPath: walletProperties == null ? void 0 : walletProperties.derivationPath
357
+ });
358
+ return await super.prepareExportIntent(_extends({}, params, {
359
+ bitcoinConfig: {
360
+ addressType
361
+ }
362
+ }));
363
+ }
364
+ async exportPrivateKey({ accountAddress, password = undefined, signedSessionId, mfaToken, elevatedAccessToken, approvalQuorum, proposalId, bitcoinConfig }) {
271
365
  await this.verifyPassword({
272
366
  accountAddress,
273
367
  password,
@@ -282,17 +376,11 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
282
376
  if (derivationPath === undefined || derivationPath === null) {
283
377
  throw new Error('Derivation path missing in walletMap');
284
378
  }
285
- let addressType = walletProperties.addressType;
286
- if (!addressType && walletProperties.derivationPath) {
287
- try {
288
- addressType = getAddressTypeFromDerivationPath(walletProperties.derivationPath);
289
- } catch (e) {
290
- this.logger.warn('Failed to infer address type from derivation path', e);
291
- }
292
- }
293
- if (!addressType) {
294
- throw new Error('Address type not found in walletMap');
295
- }
379
+ const addressType = resolveBitcoinAddressType({
380
+ accountAddress,
381
+ addressType: walletProperties.addressType,
382
+ derivationPath: walletProperties.derivationPath
383
+ });
296
384
  const { derivedPrivateKey } = await this.exportKey({
297
385
  accountAddress: accountAddress,
298
386
  chainName: this.chainName,
@@ -302,13 +390,16 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
302
390
  password,
303
391
  signedSessionId,
304
392
  mfaToken,
305
- elevatedAccessToken
393
+ elevatedAccessToken,
394
+ approvalQuorum,
395
+ proposalId
306
396
  });
307
397
  if (!derivedPrivateKey) {
308
398
  throw new Error('Failed to derive private key');
309
399
  }
400
+ var _bitcoinConfig_network;
310
401
  // Convert MPC private key to Bitcoin WIF format
311
- return this.convertPrivateKeyToBitcoinFormat(derivedPrivateKey, BitcoinNetwork.MAINNET);
402
+ return this.convertPrivateKeyToBitcoinFormat(derivedPrivateKey, (_bitcoinConfig_network = bitcoinConfig == null ? void 0 : bitcoinConfig.network) != null ? _bitcoinConfig_network : BitcoinNetwork.MAINNET);
312
403
  }
313
404
  /**
314
405
  * Imports a private key and creates a Bitcoin wallet account
@@ -357,7 +448,7 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
357
448
  addressType: addressTypeEnum,
358
449
  network
359
450
  },
360
- onCeremonyComplete: (accountAddress, walletId, shareSetId)=>{
451
+ onCeremonyComplete: ({ accountAddress, walletId, shareSetId })=>{
361
452
  ceremonyAccountAddress = accountAddress;
362
453
  // For imported BTC wallets, use empty derivation path
363
454
  // The server returns "[]" for imported wallets (raw key, not derived)
@@ -417,7 +508,7 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
417
508
  } catch (error) {
418
509
  this.logger.error(ERROR_IMPORT_PRIVATE_KEY, error);
419
510
  onError == null ? void 0 : onError(error);
420
- throw new Error(ERROR_IMPORT_PRIVATE_KEY);
511
+ throw error;
421
512
  }
422
513
  }
423
514
  /**
@@ -453,6 +544,14 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
453
544
  /**
454
545
  * Sign a Bitcoin Transaction (PSBT)
455
546
  *
547
+ * ECDSA wallets can also co-sign P2WSH multisig inputs, but only opt-in: pass the
548
+ * hex-encoded witnessScripts you constructed via `allowedWitnessScripts`. An input
549
+ * is signed when its witnessScript is allowlisted, hashes to the scriptPubKey
550
+ * commitment, and is a canonical multisig containing this wallet's public key.
551
+ * Omitting `allowedWitnessScripts` disables P2WSH signing entirely. The returned
552
+ * PSBT carries this wallet's partialSig and is NOT finalized — remaining
553
+ * co-signers add their signatures before finalizing.
554
+ *
456
555
  * @param transaction - The PSBT to sign in hex format
457
556
  * @param senderAddress - The address of the sender
458
557
  * @param password - The password to use for the transaction
@@ -461,8 +560,12 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
461
560
  * @param mfaToken - The MFA token to use for the transaction
462
561
  * @param context - The context to use for the transaction
463
562
  * @param onError - The error handler
563
+ * @param signingIndexes - Optional subset of PSBT input indexes to sign (must belong to senderAddress)
564
+ * @param allowedSighash - Optional allow-list of sighash types. The type itself is read
565
+ * from the PSBT; this only restricts which declared types are accepted. An empty
566
+ * array permits nothing; omit the parameter to permit any declared type
464
567
  * @returns The signed PSBT
465
- */ async signTransaction({ transaction, senderAddress, network, password, signedSessionId, mfaToken, elevatedAccessToken, context, onError }) {
568
+ */ async signTransaction({ transaction, senderAddress, network, password, signedSessionId, mfaToken, elevatedAccessToken, context, approvalQuorum, onError, signingIndexes, allowedSighash, allowedWitnessScripts }) {
466
569
  try {
467
570
  await this.verifyPassword({
468
571
  accountAddress: senderAddress,
@@ -480,10 +583,11 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
480
583
  if (derivationPath === undefined || derivationPath === null) {
481
584
  throw new Error('Derivation path missing in walletMap');
482
585
  }
483
- let addressType = walletProperties.addressType;
484
- if (!addressType) {
485
- addressType = getAddressTypeFromDerivationPath(derivationPath);
486
- }
586
+ const addressType = resolveBitcoinAddressType({
587
+ accountAddress: senderAddress,
588
+ addressType: walletProperties.addressType,
589
+ derivationPath
590
+ });
487
591
  const bitcoinConfig = {
488
592
  addressType,
489
593
  network
@@ -507,23 +611,31 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
507
611
  }
508
612
  const pubKey = normalizePublicKey(derivedPublicKey, addressType);
509
613
  const tx = psbt.__CACHE.__TX;
510
- // Filter inputs to only sign those that belong to the current address
511
- const inputsToSign = psbt.data.inputs.map((input, i)=>({
614
+ const isTaproot = addressType === BitcoinAddressType.TAPROOT;
615
+ // Filter inputs to only sign those that belong to the current address.
616
+ // P2WSH (multisig) inputs are opt-in: matched only when the caller
617
+ // allowlisted the witnessScript and it contains this wallet's key —
618
+ // ECDSA wallets only.
619
+ const walletPubKey = isTaproot ? undefined : pubKey;
620
+ const p2wshAllowlist = isTaproot ? undefined : allowedWitnessScripts;
621
+ let inputsToSign = psbt.data.inputs.map((input, i)=>({
512
622
  input,
513
623
  index: i
514
- })).filter(({ input })=>doesInputBelongToAddress(input, senderAddress, network));
624
+ })).filter(({ input })=>doesInputBelongToAddress(input, senderAddress, network, walletPubKey, p2wshAllowlist));
515
625
  this.logger.debug('[BTC Client] signTransaction - Filtering inputs', {
516
626
  totalInputs: psbt.data.inputs.length,
517
627
  inputsToSign: inputsToSign.length,
518
628
  senderAddress
519
629
  });
630
+ inputsToSign = filterInputsBySigningIndexes(inputsToSign, signingIndexes);
520
631
  if (inputsToSign.length === 0) {
521
632
  this.logger.warn('[BTC Client] signTransaction - No inputs found for address', {
522
633
  senderAddress,
523
634
  totalInputs: psbt.data.inputs.length
524
635
  });
525
636
  }
526
- if (addressType === BitcoinAddressType.TAPROOT) {
637
+ assertSighashAllowed(inputsToSign, isTaproot, allowedSighash);
638
+ if (isTaproot) {
527
639
  const tweak = calculateTaprootTweak(pubKey);
528
640
  const completeBitcoinConfig = _extends({}, bitcoinConfig, {
529
641
  addressType: addressType,
@@ -534,7 +646,8 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
534
646
  if (!input.witnessUtxo) {
535
647
  throw new Error(`Input ${i} missing witnessUtxo`);
536
648
  }
537
- const hash = Buffer.from(tx.hashForWitnessV1(i, prevOutScripts, values, bitcoin.Transaction.SIGHASH_DEFAULT));
649
+ const sigHashType = getSigHashType(input, true);
650
+ const hash = Buffer.from(tx.hashForWitnessV1(i, prevOutScripts, values, sigHashType));
538
651
  const signature = await this.sign({
539
652
  message: new Uint8Array(hash),
540
653
  accountAddress: senderAddress,
@@ -547,13 +660,14 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
547
660
  context: _extends({}, context, {
548
661
  btcTransaction: {
549
662
  psbt: transaction,
550
- chainId: '1'
663
+ chainId: network === BitcoinNetwork.TESTNET ? '2' : '1'
551
664
  }
552
665
  }),
553
666
  bitcoinConfig: completeBitcoinConfig,
667
+ approvalQuorum,
554
668
  onError
555
669
  });
556
- const sigBuffer = convertSignatureToTaprootBuffer(signature);
670
+ const sigBuffer = convertSignatureToTaprootBuffer(signature, sigHashType);
557
671
  psbt.updateInput(i, {
558
672
  tapKeySig: sigBuffer
559
673
  });
@@ -570,13 +684,11 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
570
684
  throw new Error(`Input ${i} missing witnessUtxo`);
571
685
  }
572
686
  const { script, value } = input.witnessUtxo;
573
- const p2pkh = bitcoin.payments.p2pkh({
574
- hash: script.slice(2),
575
- network: getBitcoinNetwork(network)
576
- });
577
- const scriptCode = p2pkh.output;
578
- if (!scriptCode) throw new Error('Failed to generate scriptCode');
579
- const hash = tx.hashForWitnessV0(i, scriptCode, value, bitcoin.Transaction.SIGHASH_ALL);
687
+ // Shared with extractPsbtSighashes; re-verifies the P2WSH
688
+ // commitment at the signer, independent of the ownership filter.
689
+ const scriptCode = getSegwitV0ScriptCode(input, script, i, getBitcoinNetwork(network));
690
+ const sigHashType = getSigHashType(input, false);
691
+ const hash = tx.hashForWitnessV0(i, scriptCode, value, sigHashType);
580
692
  const signature = await this.sign({
581
693
  message: new Uint8Array(hash),
582
694
  accountAddress: senderAddress,
@@ -589,13 +701,14 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
589
701
  context: _extends({}, context, {
590
702
  btcTransaction: {
591
703
  psbt: transaction,
592
- chainId: '1'
704
+ chainId: network === BitcoinNetwork.TESTNET ? '2' : '1'
593
705
  }
594
706
  }),
595
707
  bitcoinConfig: completeBitcoinConfig,
708
+ approvalQuorum,
596
709
  onError
597
710
  });
598
- const derSignature = convertSignatureToDER(signature);
711
+ const derSignature = convertSignatureToDER(signature, sigHashType);
599
712
  psbt.updateInput(i, {
600
713
  partialSig: [
601
714
  {
@@ -626,16 +739,26 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
626
739
  * @param amount - The amount to send in satoshis
627
740
  * @param senderAddress - The address to send funds from
628
741
  * @param network - The network to use (mainnet/testnet)
629
- * @param feeRateLevel - The fee rate level to use (fast, medium, slow)
742
+ * @param feeRateLevel - The fee rate level to use (fast, medium, slow). Ignored when feeRate is set
743
+ * @param feeRate - Explicit fee rate in sat/vByte; skips the fee lookup entirely
744
+ * @param rpcUrl - Custom Esplora-compatible API base URL (e.g. a self-hosted Esplora/electrs/mempool)
745
+ * used for fee rates, UTXOs and raw transactions instead of mempool.space. Must be https
746
+ * (http only for localhost). Fee rates use `/v1/fees/recommended`, falling back to `/fee-estimates`
630
747
  * @returns The PSBT in hex format
631
- */ async createTransaction({ receiverAddress, amount, senderAddress, network, feeRateLevel = 'medium' }) {
748
+ */ async createTransaction({ receiverAddress, amount, senderAddress, network, feeRateLevel = 'medium', feeRate: feeRateOverride, rpcUrl }) {
749
+ // rpcUrl is deliberately not logged: custom endpoints may embed API keys.
632
750
  this.logger.debug('[BTC Client] Creating transaction', {
633
751
  receiverAddress,
634
752
  amount,
635
753
  senderAddress,
636
754
  network,
637
- feeRateLevel
755
+ feeRateLevel,
756
+ feeRate: feeRateOverride,
757
+ hasCustomRpcUrl: Boolean(rpcUrl)
638
758
  });
759
+ if (feeRateOverride !== undefined && (!Number.isFinite(feeRateOverride) || feeRateOverride <= 0)) {
760
+ throw new Error('feeRate must be a positive number (sat/vByte)');
761
+ }
639
762
  if (!senderAddress) {
640
763
  throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
641
764
  }
@@ -643,26 +766,24 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
643
766
  if (!walletProperties) {
644
767
  throw new Error('Wallet not found in walletMap');
645
768
  }
646
- let addressType = walletProperties.addressType;
647
- if (!addressType && walletProperties.derivationPath) {
648
- addressType = getAddressTypeFromDerivationPath(walletProperties.derivationPath);
649
- }
650
- if (!addressType) {
651
- throw new Error('Address type not determined');
652
- }
769
+ const addressType = resolveBitcoinAddressType({
770
+ accountAddress: senderAddress,
771
+ addressType: walletProperties.addressType,
772
+ derivationPath: walletProperties.derivationPath
773
+ });
653
774
  if (addressType === BitcoinAddressType.TAPROOT) {
654
775
  throw new Error('Taproot transaction creation not yet supported');
655
776
  }
656
777
  const bitcoinNetwork = network === 'testnet' ? bitcoin.networks.testnet : bitcoin.networks.bitcoin;
657
- // Fetch fee rates
658
- const feeRates = await getFeeRates({
659
- network
660
- });
661
- const feeRate = feeRates[feeRateLevel];
778
+ const feeRate = feeRateOverride != null ? feeRateOverride : (await getFeeRates({
779
+ network,
780
+ rpcUrl
781
+ }))[feeRateLevel];
662
782
  // Fetch UTXOs
663
783
  const utxos = await getUTXOs({
664
784
  address: senderAddress,
665
- network
785
+ network,
786
+ rpcUrl
666
787
  });
667
788
  // Select UTXOs
668
789
  const { inputs, change, fee } = selectUTXOs({
@@ -675,7 +796,7 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
675
796
  });
676
797
  // Prepare inputs
677
798
  await Promise.all(inputs.map(async (utxo)=>{
678
- const txHex = await this.getTxHex(utxo.txid, network);
799
+ const txHex = await this.getTxHex(utxo.txid, network, rpcUrl);
679
800
  const inputData = {
680
801
  hash: utxo.txid,
681
802
  index: utxo.vout,
@@ -721,10 +842,14 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
721
842
  * Fetches the raw transaction hex for a given transaction ID
722
843
  * @param txid - The transaction ID
723
844
  * @param network - The network
845
+ * @param rpcUrl - Optional custom Esplora-compatible API base URL
724
846
  * @returns The transaction hex
725
- */ async getTxHex(txid, network) {
726
- const baseUrl = getDefaultRpcUrl(network);
727
- const response = await fetch(`${baseUrl}/tx/${txid}/hex`);
847
+ */ async getTxHex(txid, network, rpcUrl) {
848
+ const baseUrl = resolveRpcUrl({
849
+ network,
850
+ rpcUrl
851
+ });
852
+ const response = await rpcFetch(`${baseUrl}/tx/${txid}/hex`, rpcUrl);
728
853
  if (!response.ok) {
729
854
  throw new Error(`Failed to fetch TX hex: ${response.statusText}`);
730
855
  }
@@ -741,23 +866,75 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
741
866
  /**
742
867
  * Creates a new instance of DynamicBtcWalletClient
743
868
  * @param props - The client properties
744
- */ constructor({ environmentId, authToken, baseApiUrl, baseMPCRelayApiUrl, storageKey, debug, featureFlags, authMode = AuthMode.HEADER, sdkVersion, forwardMPCClient, logger }, internalOptions){
745
- super({
746
- environmentId,
747
- authToken,
748
- baseApiUrl,
749
- baseMPCRelayApiUrl,
750
- storageKey,
751
- debug,
752
- featureFlags,
753
- authMode,
754
- sdkVersion,
755
- forwardMPCClient,
756
- logger
757
- }, internalOptions), this.chainName = 'BTC';
869
+ */ constructor(props, internalOptions){
870
+ super(props, internalOptions), this.chainName = 'BTC';
758
871
  // Initialize ECC library for bitcoinjs-lib
759
872
  initEccLib(ecc);
760
873
  }
761
874
  }
762
875
 
763
- export { DynamicBtcWalletClient };
876
+ const { SIGHASH_ALL, SIGHASH_DEFAULT } = bitcoin.Transaction;
877
+ const isP2trScript = (script)=>script.length === 34 && script[0] === 0x51 && script[1] === 0x20;
878
+ // Only these types commit to every output, so only they let one approval stand
879
+ // for the whole transaction: SIGHASH_DEFAULT and SIGHASH_ALL for Taproot, SIGHASH_ALL otherwise.
880
+ const committingSighashTypes = (isTaproot)=>isTaproot ? [
881
+ SIGHASH_DEFAULT,
882
+ SIGHASH_ALL
883
+ ] : [
884
+ SIGHASH_ALL
885
+ ];
886
+ /**
887
+ * Describes a PSBT for a signing-quorum intent: its txid, fee, outputs and the
888
+ * sighashes of the inputs the wallet signs, so one approval covers a signature
889
+ * for each of them.
890
+ *
891
+ * The inputs are chosen as `signTransaction` chooses them: the ones that belong
892
+ * to `accountAddress`, narrowed to `signingIndexes` when given. P2WSH co-signing
893
+ * is not part of the intent, so `allowedWitnessScripts` is rejected.
894
+ */ const prepareBtcTransactionSigningOperation = ({ transaction, accountAddress, bitcoinConfig, signingIndexes, allowedSighash, allowedWitnessScripts })=>{
895
+ initEccLib(ecc);
896
+ if (allowedWitnessScripts == null ? void 0 : allowedWitnessScripts.length) throw new Error('BTC signing intent does not support P2WSH co-signing');
897
+ var _bitcoinConfig_network;
898
+ const network = toBitcoinNetwork((_bitcoinConfig_network = bitcoinConfig == null ? void 0 : bitcoinConfig.network) != null ? _bitcoinConfig_network : 'mainnet');
899
+ const psbt = bitcoin.Psbt.fromBase64(transaction);
900
+ const ownedInputs = psbt.data.inputs.map((input, index)=>({
901
+ input,
902
+ index
903
+ })).filter(({ input })=>doesInputBelongToAddress(input, accountAddress, network));
904
+ const inputsToSign = filterInputsBySigningIndexes(ownedInputs, signingIndexes);
905
+ if (inputsToSign.length === 0) throw new Error('No input of the transaction belongs to the signing account');
906
+ inputsToSign.forEach(({ input, index })=>{
907
+ const isTaproot = Boolean(input.tapInternalKey);
908
+ if (!isTaproot && input.witnessUtxo && isP2trScript(input.witnessUtxo.script)) {
909
+ throw new Error(`Input ${index} is a Taproot input without tapInternalKey`);
910
+ }
911
+ assertSighashAllowed([
912
+ {
913
+ input,
914
+ index
915
+ }
916
+ ], isTaproot, allowedSighash);
917
+ const sighashType = getSigHashType(input, isTaproot);
918
+ if (!committingSighashTypes(isTaproot).includes(sighashType)) {
919
+ throw new Error(`Input ${index} declares sighash type ${sighashType}, which a signing intent does not allow`);
920
+ }
921
+ });
922
+ const { txid, feeSats, outputs, sighashes } = extractPsbtIntentOperation({
923
+ psbtBase64: transaction,
924
+ network,
925
+ inputIndexes: inputsToSign.map(({ index })=>index)
926
+ });
927
+ return {
928
+ operation: {
929
+ kind: 'transaction',
930
+ chainName: 'BTC',
931
+ chainId: getBtcChainId(network),
932
+ txid,
933
+ feeSats,
934
+ outputs,
935
+ sighashes
936
+ }
937
+ };
938
+ };
939
+
940
+ export { DynamicBtcWalletClient, prepareBtcTransactionSigningOperation };