@dynamic-labs-wallet/btc 0.0.353 → 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.cjs CHANGED
@@ -58,7 +58,7 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
58
58
  * @param signedSessionId - The signed session ID to use for the wallet
59
59
  * @param addressType - The type of address to use for the wallet
60
60
  * @returns The account address, public key hex, and raw public key
61
- */ async createWalletAccount({ thresholdSignatureScheme, password = undefined, onError, signedSessionId, bitcoinConfig }) {
61
+ */ async createWalletAccount({ thresholdSignatureScheme, password = undefined, onError, signedSessionId, bitcoinConfig, businessAccountId }) {
62
62
  const network = browser.BitcoinNetwork.MAINNET;
63
63
  var _bitcoinConfig_addressType;
64
64
  const addressType = (_bitcoinConfig_addressType = bitcoinConfig == null ? void 0 : bitcoinConfig.addressType) != null ? _bitcoinConfig_addressType : browser.BitcoinAddressType.NATIVE_SEGWIT;
@@ -86,13 +86,14 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
86
86
  // Use 'BTC' as chain name, derivation path and signing algorithm will be resolved from addressType
87
87
  const { rawPublicKey, clientKeyShares } = await this.keyGen({
88
88
  chainName: this.chainName,
89
+ businessAccountId,
89
90
  thresholdSignatureScheme,
90
91
  bitcoinConfig: buildBitcoinConfig,
91
92
  onError: (error)=>{
92
93
  this.logger.error(browser.ERROR_CREATE_WALLET_ACCOUNT, error);
93
94
  onError == null ? void 0 : onError(error);
94
95
  },
95
- onCeremonyComplete: (accountAddress, walletId)=>{
96
+ onCeremonyComplete: ({ accountAddress, walletId, shareSetId })=>{
96
97
  const chainConfig = browser.getMPCChainConfig(this.chainName, buildBitcoinConfig);
97
98
  this.initializeWalletMapEntry({
98
99
  accountAddress,
@@ -103,6 +104,7 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
103
104
  index,
104
105
  value
105
106
  ]))),
107
+ shareSetId,
106
108
  additionalProps: {
107
109
  addressType
108
110
  }
@@ -134,7 +136,8 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
134
136
  accountAddress,
135
137
  clientKeyShares,
136
138
  password,
137
- signedSessionId
139
+ signedSessionId,
140
+ businessAccountId
138
141
  });
139
142
  const publicKeyHex = btcUtils.extractPublicKeyHex(rawPublicKey);
140
143
  return {
@@ -143,14 +146,16 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
143
146
  rawPublicKey
144
147
  };
145
148
  } catch (error) {
146
- // Re-throw password mismatch errors without wrapping
147
- if (error instanceof Error && error.message === browser.ERROR_PASSWORD_MISMATCH) {
149
+ // Re-throw known business-rule rejections without wrapping
150
+ if (error instanceof Error && (error.message === browser.ERROR_PASSWORD_MISMATCH || error.message === browser.ERROR_MULTIPLE_WALLETS_PER_CHAIN)) {
148
151
  throw error;
149
152
  }
150
153
  if (onError) {
151
154
  onError(error);
152
155
  }
153
- throw new Error(browser.ERROR_CREATE_WALLET_ACCOUNT);
156
+ throw new Error(browser.ERROR_CREATE_WALLET_ACCOUNT, {
157
+ cause: error
158
+ });
154
159
  }
155
160
  }
156
161
  /**
@@ -171,6 +176,53 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
171
176
  };
172
177
  }
173
178
  /**
179
+ * Raw digest signing.
180
+ *
181
+ * Overridden so BTC can supply what getMPCChainConfig needs. The address
182
+ * type selects the derivation path and the signing algorithm, and taproot
183
+ * additionally needs the BIP-341 tweak: BIP340 signs under the tweaked
184
+ * output key, so a signature produced from the internal key alone would not
185
+ * verify against the wallet's own address. Computing it needs the derived
186
+ * public key, which only this layer has, so callers cannot supply it and the
187
+ * generic implementation cannot derive it.
188
+ *
189
+ * @param params - Raw sign parameters; bitcoinConfig is resolved here
190
+ * @returns The signature, Schnorr for taproot and ECDSA otherwise
191
+ */ async sign(params) {
192
+ const { accountAddress, bitcoinConfig } = params;
193
+ const walletProperties = this.getWalletFromMap(accountAddress);
194
+ const addressType = btcUtils.resolveBitcoinAddressType({
195
+ accountAddress,
196
+ addressType: bitcoinConfig == null ? void 0 : bitcoinConfig.addressType,
197
+ derivationPath: walletProperties == null ? void 0 : walletProperties.derivationPath
198
+ });
199
+ let tweak = bitcoinConfig == null ? void 0 : bitcoinConfig.tweak;
200
+ if (addressType === browser.BitcoinAddressType.TAPROOT && !tweak) {
201
+ const clientKeyShares = await this.getClientKeySharesFromStorage({
202
+ accountAddress
203
+ });
204
+ var _walletProperties_derivationPath;
205
+ const derivedPublicKey = await this.derivePublicKey({
206
+ chainName: this.chainName,
207
+ keyShare: clientKeyShares[0],
208
+ derivationPath: parseDerivationPath((_walletProperties_derivationPath = walletProperties == null ? void 0 : walletProperties.derivationPath) != null ? _walletProperties_derivationPath : ''),
209
+ bitcoinConfig: _extends({}, bitcoinConfig, {
210
+ addressType
211
+ })
212
+ });
213
+ if (!derivedPublicKey) {
214
+ throw new Error('Failed to derive public key');
215
+ }
216
+ tweak = btcUtils.calculateTaprootTweak(btcUtils.normalizePublicKey(derivedPublicKey, addressType));
217
+ }
218
+ return super.sign(_extends({}, params, {
219
+ bitcoinConfig: _extends({}, bitcoinConfig, {
220
+ addressType,
221
+ tweak
222
+ })
223
+ }));
224
+ }
225
+ /**
174
226
  * Signs a message (BIP-322)
175
227
  * @param message - The message to sign
176
228
  * @param accountAddress - The account address
@@ -181,61 +233,17 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
181
233
  * @param context - Additional context
182
234
  * @param onError - Error callback
183
235
  * @returns The BIP-322 signature
184
- */ async signMessage({ message, accountAddress, network, password = undefined, signedSessionId, mfaToken, elevatedAccessToken, context, onError }) {
236
+ */ async signMessage({ message, accountAddress, network, password = undefined, signedSessionId, mfaToken, elevatedAccessToken, context, approvalQuorum, onError }) {
185
237
  await this.verifyPassword({
186
238
  accountAddress,
187
239
  password,
188
240
  signedSessionId
189
241
  });
190
242
  try {
191
- if (!accountAddress) {
192
- throw new Error(browser.ERROR_ACCOUNT_ADDRESS_REQUIRED);
193
- }
194
- const walletProperties = this.getWalletFromMap(accountAddress);
195
- if (!walletProperties) {
196
- throw new Error('Wallet not found in walletMap');
197
- }
198
- const derivationPath = walletProperties.derivationPath;
199
- if (derivationPath === undefined || derivationPath === null) {
200
- throw new Error('Derivation path missing in walletMap');
201
- }
202
- let addressType = walletProperties.addressType;
203
- if (!addressType) {
204
- addressType = btcUtils.getAddressTypeFromDerivationPath(derivationPath);
205
- }
206
- const clientKeyShares = await this.getClientKeySharesFromStorage({
207
- accountAddress
208
- });
209
- if (!clientKeyShares || clientKeyShares.length === 0) {
210
- throw new Error('No key shares found');
211
- }
212
- const bitcoinConfig = {
213
- addressType,
243
+ const { addressType, completeBitcoinConfig, formattedMessage, pubKey, toSignPsbt } = await this.prepareBip322SignMessage({
244
+ accountAddress,
245
+ message,
214
246
  network
215
- };
216
- const walletDerivationPath = parseDerivationPath(derivationPath);
217
- const derivedPublicKey = await this.derivePublicKey({
218
- chainName: this.chainName,
219
- keyShare: clientKeyShares[0],
220
- derivationPath: walletDerivationPath,
221
- bitcoinConfig
222
- });
223
- if (!derivedPublicKey) {
224
- throw new Error('Failed to derive public key');
225
- }
226
- const pubKey = btcUtils.normalizePublicKey(derivedPublicKey, addressType);
227
- this.verifyWalletAddress(derivedPublicKey, addressType, network, accountAddress);
228
- // Prepare BIP-322 Transactions and calculate hash
229
- const { formattedMessage, toSignPsbt } = btcUtils.calculateBip322Hash(message, pubKey, addressType, network, ecc);
230
- // Prepare tweak for Taproot in case of BIP340
231
- let tweak;
232
- if (addressType === browser.BitcoinAddressType.TAPROOT) {
233
- tweak = btcUtils.calculateTaprootTweak(pubKey);
234
- }
235
- // Build complete bitcoinConfig with addressType and tweak
236
- const completeBitcoinConfig = _extends({}, bitcoinConfig, {
237
- addressType: addressType,
238
- tweak
239
247
  });
240
248
  // Sign the message using MPC
241
249
  const signature = await this.sign({
@@ -251,6 +259,7 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
251
259
  btcMessage: message
252
260
  },
253
261
  bitcoinConfig: completeBitcoinConfig,
262
+ approvalQuorum,
254
263
  onError
255
264
  });
256
265
  // Encode Final Result
@@ -263,8 +272,62 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
263
272
  if (onError) {
264
273
  onError(error);
265
274
  }
266
- throw new Error(browser.ERROR_SIGN_MESSAGE);
275
+ throw new Error(browser.ERROR_SIGN_MESSAGE, {
276
+ cause: error
277
+ });
278
+ }
279
+ }
280
+ async prepareSignMessage({ accountAddress, message, network }) {
281
+ const { formattedMessage } = await this.prepareBip322SignMessage({
282
+ accountAddress,
283
+ message,
284
+ network
285
+ });
286
+ return `0x${Buffer.from(formattedMessage).toString('hex')}`;
287
+ }
288
+ async prepareBip322SignMessage({ accountAddress, message, network }) {
289
+ if (!accountAddress) throw new Error(browser.ERROR_ACCOUNT_ADDRESS_REQUIRED);
290
+ const walletProperties = this.getWalletFromMap(accountAddress);
291
+ if (!walletProperties) throw new Error('Wallet not found in walletMap');
292
+ const derivationPath = walletProperties.derivationPath;
293
+ if (derivationPath === undefined || derivationPath === null) {
294
+ throw new Error('Derivation path missing in walletMap');
267
295
  }
296
+ const addressType = btcUtils.resolveBitcoinAddressType({
297
+ accountAddress,
298
+ addressType: walletProperties.addressType,
299
+ derivationPath
300
+ });
301
+ const clientKeyShares = await this.getClientKeySharesFromStorage({
302
+ accountAddress
303
+ });
304
+ if (!clientKeyShares || clientKeyShares.length === 0) throw new Error('No key shares found');
305
+ const bitcoinConfig = {
306
+ addressType,
307
+ network
308
+ };
309
+ const derivedPublicKey = await this.derivePublicKey({
310
+ chainName: this.chainName,
311
+ keyShare: clientKeyShares[0],
312
+ derivationPath: parseDerivationPath(derivationPath),
313
+ bitcoinConfig
314
+ });
315
+ if (!derivedPublicKey) throw new Error('Failed to derive public key');
316
+ const pubKey = btcUtils.normalizePublicKey(derivedPublicKey, addressType);
317
+ this.verifyWalletAddress(derivedPublicKey, addressType, network, accountAddress);
318
+ const { formattedMessage, toSignPsbt } = btcUtils.calculateBip322Hash(message, pubKey, addressType, network, ecc);
319
+ const tweak = addressType === browser.BitcoinAddressType.TAPROOT ? btcUtils.calculateTaprootTweak(pubKey) : undefined;
320
+ const completeBitcoinConfig = _extends({}, bitcoinConfig, {
321
+ addressType: addressType,
322
+ tweak
323
+ });
324
+ return {
325
+ addressType,
326
+ completeBitcoinConfig,
327
+ formattedMessage,
328
+ pubKey,
329
+ toSignPsbt
330
+ };
268
331
  }
269
332
  /**
270
333
  * Verifies that the derived address matches the expected address
@@ -275,9 +338,19 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
275
338
  */ verifyWalletAddress(rawPublicKey, addressType, network, expectedAddress) {
276
339
  const normalizedKey = btcUtils.normalizePublicKey(rawPublicKey, addressType);
277
340
  const derivedAddress = btcUtils.publicKeyToBitcoinAddress(normalizedKey, addressType, network, ecc);
278
- if (derivedAddress !== expectedAddress) {
279
- throw new Error(`Address verification failed: expected ${expectedAddress}, got ${derivedAddress}`);
341
+ if (derivedAddress === expectedAddress) {
342
+ return;
343
+ }
344
+ // Callers pass the wallet identity address (the mainnet encoding that
345
+ // keys the wallet map) even when signing for another network — the same
346
+ // key encodes differently per network, so accept the identity encoding.
347
+ if (network !== browser.BitcoinNetwork.MAINNET) {
348
+ const identityAddress = btcUtils.publicKeyToBitcoinAddress(normalizedKey, addressType, browser.BitcoinNetwork.MAINNET, ecc);
349
+ if (identityAddress === expectedAddress) {
350
+ return;
351
+ }
280
352
  }
353
+ throw new Error(`Address verification failed: expected ${expectedAddress}, got ${derivedAddress}`);
281
354
  }
282
355
  /**
283
356
  * Exports the private key for a given account
@@ -287,7 +360,29 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
287
360
  * @param mfaToken - The MFA token to use for the private key
288
361
  * @param network - The network to use for the private key
289
362
  * @returns The private key
290
- */ async exportPrivateKey({ accountAddress, password = undefined, signedSessionId, mfaToken, elevatedAccessToken }) {
363
+ */ /**
364
+ * Builds the export Intent for a BTC wallet.
365
+ *
366
+ * Overridden so BTC can supply the address type the signer needs. It selects
367
+ * the derivation path, so without it the export id cannot be computed. It is
368
+ * resolved from the wallet exactly as `exportPrivateKey` does, so the Intent
369
+ * binds the same export id the export itself will compute.
370
+ */ async prepareExportIntent(params) {
371
+ var _params_bitcoinConfig;
372
+ const walletProperties = this.getWalletFromMap(params.accountAddress);
373
+ var _params_bitcoinConfig_addressType;
374
+ const addressType = btcUtils.resolveBitcoinAddressType({
375
+ accountAddress: params.accountAddress,
376
+ addressType: (_params_bitcoinConfig_addressType = (_params_bitcoinConfig = params.bitcoinConfig) == null ? void 0 : _params_bitcoinConfig.addressType) != null ? _params_bitcoinConfig_addressType : walletProperties == null ? void 0 : walletProperties.addressType,
377
+ derivationPath: walletProperties == null ? void 0 : walletProperties.derivationPath
378
+ });
379
+ return await super.prepareExportIntent(_extends({}, params, {
380
+ bitcoinConfig: {
381
+ addressType
382
+ }
383
+ }));
384
+ }
385
+ async exportPrivateKey({ accountAddress, password = undefined, signedSessionId, mfaToken, elevatedAccessToken, approvalQuorum, proposalId, bitcoinConfig }) {
291
386
  await this.verifyPassword({
292
387
  accountAddress,
293
388
  password,
@@ -302,17 +397,11 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
302
397
  if (derivationPath === undefined || derivationPath === null) {
303
398
  throw new Error('Derivation path missing in walletMap');
304
399
  }
305
- let addressType = walletProperties.addressType;
306
- if (!addressType && walletProperties.derivationPath) {
307
- try {
308
- addressType = btcUtils.getAddressTypeFromDerivationPath(walletProperties.derivationPath);
309
- } catch (e) {
310
- this.logger.warn('Failed to infer address type from derivation path', e);
311
- }
312
- }
313
- if (!addressType) {
314
- throw new Error('Address type not found in walletMap');
315
- }
400
+ const addressType = btcUtils.resolveBitcoinAddressType({
401
+ accountAddress,
402
+ addressType: walletProperties.addressType,
403
+ derivationPath: walletProperties.derivationPath
404
+ });
316
405
  const { derivedPrivateKey } = await this.exportKey({
317
406
  accountAddress: accountAddress,
318
407
  chainName: this.chainName,
@@ -322,13 +411,16 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
322
411
  password,
323
412
  signedSessionId,
324
413
  mfaToken,
325
- elevatedAccessToken
414
+ elevatedAccessToken,
415
+ approvalQuorum,
416
+ proposalId
326
417
  });
327
418
  if (!derivedPrivateKey) {
328
419
  throw new Error('Failed to derive private key');
329
420
  }
421
+ var _bitcoinConfig_network;
330
422
  // Convert MPC private key to Bitcoin WIF format
331
- return this.convertPrivateKeyToBitcoinFormat(derivedPrivateKey, browser.BitcoinNetwork.MAINNET);
423
+ return this.convertPrivateKeyToBitcoinFormat(derivedPrivateKey, (_bitcoinConfig_network = bitcoinConfig == null ? void 0 : bitcoinConfig.network) != null ? _bitcoinConfig_network : browser.BitcoinNetwork.MAINNET);
332
424
  }
333
425
  /**
334
426
  * Imports a private key and creates a Bitcoin wallet account
@@ -377,7 +469,7 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
377
469
  addressType: addressTypeEnum,
378
470
  network
379
471
  },
380
- onCeremonyComplete: (accountAddress, walletId)=>{
472
+ onCeremonyComplete: ({ accountAddress, walletId, shareSetId })=>{
381
473
  ceremonyAccountAddress = accountAddress;
382
474
  // For imported BTC wallets, use empty derivation path
383
475
  // The server returns "[]" for imported wallets (raw key, not derived)
@@ -387,6 +479,7 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
387
479
  chainName: this.chainName,
388
480
  thresholdSignatureScheme,
389
481
  derivationPath: JSON.stringify([]),
482
+ shareSetId,
390
483
  additionalProps: {
391
484
  addressType: addressTypeEnum
392
485
  }
@@ -436,7 +529,7 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
436
529
  } catch (error) {
437
530
  this.logger.error(browser.ERROR_IMPORT_PRIVATE_KEY, error);
438
531
  onError == null ? void 0 : onError(error);
439
- throw new Error(browser.ERROR_IMPORT_PRIVATE_KEY);
532
+ throw error;
440
533
  }
441
534
  }
442
535
  /**
@@ -472,6 +565,14 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
472
565
  /**
473
566
  * Sign a Bitcoin Transaction (PSBT)
474
567
  *
568
+ * ECDSA wallets can also co-sign P2WSH multisig inputs, but only opt-in: pass the
569
+ * hex-encoded witnessScripts you constructed via `allowedWitnessScripts`. An input
570
+ * is signed when its witnessScript is allowlisted, hashes to the scriptPubKey
571
+ * commitment, and is a canonical multisig containing this wallet's public key.
572
+ * Omitting `allowedWitnessScripts` disables P2WSH signing entirely. The returned
573
+ * PSBT carries this wallet's partialSig and is NOT finalized — remaining
574
+ * co-signers add their signatures before finalizing.
575
+ *
475
576
  * @param transaction - The PSBT to sign in hex format
476
577
  * @param senderAddress - The address of the sender
477
578
  * @param password - The password to use for the transaction
@@ -480,8 +581,12 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
480
581
  * @param mfaToken - The MFA token to use for the transaction
481
582
  * @param context - The context to use for the transaction
482
583
  * @param onError - The error handler
584
+ * @param signingIndexes - Optional subset of PSBT input indexes to sign (must belong to senderAddress)
585
+ * @param allowedSighash - Optional allow-list of sighash types. The type itself is read
586
+ * from the PSBT; this only restricts which declared types are accepted. An empty
587
+ * array permits nothing; omit the parameter to permit any declared type
483
588
  * @returns The signed PSBT
484
- */ async signTransaction({ transaction, senderAddress, network, password, signedSessionId, mfaToken, elevatedAccessToken, context, onError }) {
589
+ */ async signTransaction({ transaction, senderAddress, network, password, signedSessionId, mfaToken, elevatedAccessToken, context, approvalQuorum, onError, signingIndexes, allowedSighash, allowedWitnessScripts }) {
485
590
  try {
486
591
  await this.verifyPassword({
487
592
  accountAddress: senderAddress,
@@ -499,10 +604,11 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
499
604
  if (derivationPath === undefined || derivationPath === null) {
500
605
  throw new Error('Derivation path missing in walletMap');
501
606
  }
502
- let addressType = walletProperties.addressType;
503
- if (!addressType) {
504
- addressType = btcUtils.getAddressTypeFromDerivationPath(derivationPath);
505
- }
607
+ const addressType = btcUtils.resolveBitcoinAddressType({
608
+ accountAddress: senderAddress,
609
+ addressType: walletProperties.addressType,
610
+ derivationPath
611
+ });
506
612
  const bitcoinConfig = {
507
613
  addressType,
508
614
  network
@@ -526,23 +632,31 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
526
632
  }
527
633
  const pubKey = btcUtils.normalizePublicKey(derivedPublicKey, addressType);
528
634
  const tx = psbt.__CACHE.__TX;
529
- // Filter inputs to only sign those that belong to the current address
530
- const inputsToSign = psbt.data.inputs.map((input, i)=>({
635
+ const isTaproot = addressType === browser.BitcoinAddressType.TAPROOT;
636
+ // Filter inputs to only sign those that belong to the current address.
637
+ // P2WSH (multisig) inputs are opt-in: matched only when the caller
638
+ // allowlisted the witnessScript and it contains this wallet's key —
639
+ // ECDSA wallets only.
640
+ const walletPubKey = isTaproot ? undefined : pubKey;
641
+ const p2wshAllowlist = isTaproot ? undefined : allowedWitnessScripts;
642
+ let inputsToSign = psbt.data.inputs.map((input, i)=>({
531
643
  input,
532
644
  index: i
533
- })).filter(({ input })=>btcUtils.doesInputBelongToAddress(input, senderAddress, network));
645
+ })).filter(({ input })=>btcUtils.doesInputBelongToAddress(input, senderAddress, network, walletPubKey, p2wshAllowlist));
534
646
  this.logger.debug('[BTC Client] signTransaction - Filtering inputs', {
535
647
  totalInputs: psbt.data.inputs.length,
536
648
  inputsToSign: inputsToSign.length,
537
649
  senderAddress
538
650
  });
651
+ inputsToSign = btcUtils.filterInputsBySigningIndexes(inputsToSign, signingIndexes);
539
652
  if (inputsToSign.length === 0) {
540
653
  this.logger.warn('[BTC Client] signTransaction - No inputs found for address', {
541
654
  senderAddress,
542
655
  totalInputs: psbt.data.inputs.length
543
656
  });
544
657
  }
545
- if (addressType === browser.BitcoinAddressType.TAPROOT) {
658
+ btcUtils.assertSighashAllowed(inputsToSign, isTaproot, allowedSighash);
659
+ if (isTaproot) {
546
660
  const tweak = btcUtils.calculateTaprootTweak(pubKey);
547
661
  const completeBitcoinConfig = _extends({}, bitcoinConfig, {
548
662
  addressType: addressType,
@@ -553,7 +667,8 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
553
667
  if (!input.witnessUtxo) {
554
668
  throw new Error(`Input ${i} missing witnessUtxo`);
555
669
  }
556
- const hash = Buffer.from(tx.hashForWitnessV1(i, prevOutScripts, values, bitcoin__namespace.Transaction.SIGHASH_DEFAULT));
670
+ const sigHashType = btcUtils.getSigHashType(input, true);
671
+ const hash = Buffer.from(tx.hashForWitnessV1(i, prevOutScripts, values, sigHashType));
557
672
  const signature = await this.sign({
558
673
  message: new Uint8Array(hash),
559
674
  accountAddress: senderAddress,
@@ -566,13 +681,14 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
566
681
  context: _extends({}, context, {
567
682
  btcTransaction: {
568
683
  psbt: transaction,
569
- chainId: '1'
684
+ chainId: network === browser.BitcoinNetwork.TESTNET ? '2' : '1'
570
685
  }
571
686
  }),
572
687
  bitcoinConfig: completeBitcoinConfig,
688
+ approvalQuorum,
573
689
  onError
574
690
  });
575
- const sigBuffer = btcUtils.convertSignatureToTaprootBuffer(signature);
691
+ const sigBuffer = btcUtils.convertSignatureToTaprootBuffer(signature, sigHashType);
576
692
  psbt.updateInput(i, {
577
693
  tapKeySig: sigBuffer
578
694
  });
@@ -589,13 +705,11 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
589
705
  throw new Error(`Input ${i} missing witnessUtxo`);
590
706
  }
591
707
  const { script, value } = input.witnessUtxo;
592
- const p2pkh = bitcoin__namespace.payments.p2pkh({
593
- hash: script.slice(2),
594
- network: btcUtils.getBitcoinNetwork(network)
595
- });
596
- const scriptCode = p2pkh.output;
597
- if (!scriptCode) throw new Error('Failed to generate scriptCode');
598
- const hash = tx.hashForWitnessV0(i, scriptCode, value, bitcoin__namespace.Transaction.SIGHASH_ALL);
708
+ // Shared with extractPsbtSighashes; re-verifies the P2WSH
709
+ // commitment at the signer, independent of the ownership filter.
710
+ const scriptCode = btcUtils.getSegwitV0ScriptCode(input, script, i, btcUtils.getBitcoinNetwork(network));
711
+ const sigHashType = btcUtils.getSigHashType(input, false);
712
+ const hash = tx.hashForWitnessV0(i, scriptCode, value, sigHashType);
599
713
  const signature = await this.sign({
600
714
  message: new Uint8Array(hash),
601
715
  accountAddress: senderAddress,
@@ -608,13 +722,14 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
608
722
  context: _extends({}, context, {
609
723
  btcTransaction: {
610
724
  psbt: transaction,
611
- chainId: '1'
725
+ chainId: network === browser.BitcoinNetwork.TESTNET ? '2' : '1'
612
726
  }
613
727
  }),
614
728
  bitcoinConfig: completeBitcoinConfig,
729
+ approvalQuorum,
615
730
  onError
616
731
  });
617
- const derSignature = btcUtils.convertSignatureToDER(signature);
732
+ const derSignature = btcUtils.convertSignatureToDER(signature, sigHashType);
618
733
  psbt.updateInput(i, {
619
734
  partialSig: [
620
735
  {
@@ -645,16 +760,26 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
645
760
  * @param amount - The amount to send in satoshis
646
761
  * @param senderAddress - The address to send funds from
647
762
  * @param network - The network to use (mainnet/testnet)
648
- * @param feeRateLevel - The fee rate level to use (fast, medium, slow)
763
+ * @param feeRateLevel - The fee rate level to use (fast, medium, slow). Ignored when feeRate is set
764
+ * @param feeRate - Explicit fee rate in sat/vByte; skips the fee lookup entirely
765
+ * @param rpcUrl - Custom Esplora-compatible API base URL (e.g. a self-hosted Esplora/electrs/mempool)
766
+ * used for fee rates, UTXOs and raw transactions instead of mempool.space. Must be https
767
+ * (http only for localhost). Fee rates use `/v1/fees/recommended`, falling back to `/fee-estimates`
649
768
  * @returns The PSBT in hex format
650
- */ async createTransaction({ receiverAddress, amount, senderAddress, network, feeRateLevel = 'medium' }) {
769
+ */ async createTransaction({ receiverAddress, amount, senderAddress, network, feeRateLevel = 'medium', feeRate: feeRateOverride, rpcUrl }) {
770
+ // rpcUrl is deliberately not logged: custom endpoints may embed API keys.
651
771
  this.logger.debug('[BTC Client] Creating transaction', {
652
772
  receiverAddress,
653
773
  amount,
654
774
  senderAddress,
655
775
  network,
656
- feeRateLevel
776
+ feeRateLevel,
777
+ feeRate: feeRateOverride,
778
+ hasCustomRpcUrl: Boolean(rpcUrl)
657
779
  });
780
+ if (feeRateOverride !== undefined && (!Number.isFinite(feeRateOverride) || feeRateOverride <= 0)) {
781
+ throw new Error('feeRate must be a positive number (sat/vByte)');
782
+ }
658
783
  if (!senderAddress) {
659
784
  throw new Error(browser.ERROR_ACCOUNT_ADDRESS_REQUIRED);
660
785
  }
@@ -662,26 +787,24 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
662
787
  if (!walletProperties) {
663
788
  throw new Error('Wallet not found in walletMap');
664
789
  }
665
- let addressType = walletProperties.addressType;
666
- if (!addressType && walletProperties.derivationPath) {
667
- addressType = btcUtils.getAddressTypeFromDerivationPath(walletProperties.derivationPath);
668
- }
669
- if (!addressType) {
670
- throw new Error('Address type not determined');
671
- }
790
+ const addressType = btcUtils.resolveBitcoinAddressType({
791
+ accountAddress: senderAddress,
792
+ addressType: walletProperties.addressType,
793
+ derivationPath: walletProperties.derivationPath
794
+ });
672
795
  if (addressType === browser.BitcoinAddressType.TAPROOT) {
673
796
  throw new Error('Taproot transaction creation not yet supported');
674
797
  }
675
798
  const bitcoinNetwork = network === 'testnet' ? bitcoin__namespace.networks.testnet : bitcoin__namespace.networks.bitcoin;
676
- // Fetch fee rates
677
- const feeRates = await btcUtils.getFeeRates({
678
- network
679
- });
680
- const feeRate = feeRates[feeRateLevel];
799
+ const feeRate = feeRateOverride != null ? feeRateOverride : (await btcUtils.getFeeRates({
800
+ network,
801
+ rpcUrl
802
+ }))[feeRateLevel];
681
803
  // Fetch UTXOs
682
804
  const utxos = await btcUtils.getUTXOs({
683
805
  address: senderAddress,
684
- network
806
+ network,
807
+ rpcUrl
685
808
  });
686
809
  // Select UTXOs
687
810
  const { inputs, change, fee } = btcUtils.selectUTXOs({
@@ -694,7 +817,7 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
694
817
  });
695
818
  // Prepare inputs
696
819
  await Promise.all(inputs.map(async (utxo)=>{
697
- const txHex = await this.getTxHex(utxo.txid, network);
820
+ const txHex = await this.getTxHex(utxo.txid, network, rpcUrl);
698
821
  const inputData = {
699
822
  hash: utxo.txid,
700
823
  index: utxo.vout,
@@ -740,10 +863,14 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
740
863
  * Fetches the raw transaction hex for a given transaction ID
741
864
  * @param txid - The transaction ID
742
865
  * @param network - The network
866
+ * @param rpcUrl - Optional custom Esplora-compatible API base URL
743
867
  * @returns The transaction hex
744
- */ async getTxHex(txid, network) {
745
- const baseUrl = btcUtils.getDefaultRpcUrl(network);
746
- const response = await fetch(`${baseUrl}/tx/${txid}/hex`);
868
+ */ async getTxHex(txid, network, rpcUrl) {
869
+ const baseUrl = btcUtils.resolveRpcUrl({
870
+ network,
871
+ rpcUrl
872
+ });
873
+ const response = await btcUtils.rpcFetch(`${baseUrl}/tx/${txid}/hex`, rpcUrl);
747
874
  if (!response.ok) {
748
875
  throw new Error(`Failed to fetch TX hex: ${response.statusText}`);
749
876
  }
@@ -760,23 +887,76 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
760
887
  /**
761
888
  * Creates a new instance of DynamicBtcWalletClient
762
889
  * @param props - The client properties
763
- */ constructor({ environmentId, authToken, baseApiUrl, baseMPCRelayApiUrl, storageKey, debug, featureFlags, authMode = browser.AuthMode.HEADER, sdkVersion, forwardMPCClient, logger }, internalOptions){
764
- super({
765
- environmentId,
766
- authToken,
767
- baseApiUrl,
768
- baseMPCRelayApiUrl,
769
- storageKey,
770
- debug,
771
- featureFlags,
772
- authMode,
773
- sdkVersion,
774
- forwardMPCClient,
775
- logger
776
- }, internalOptions), this.chainName = 'BTC';
890
+ */ constructor(props, internalOptions){
891
+ super(props, internalOptions), this.chainName = 'BTC';
777
892
  // Initialize ECC library for bitcoinjs-lib
778
893
  btcUtils.initEccLib(ecc);
779
894
  }
780
895
  }
781
896
 
897
+ const { SIGHASH_ALL, SIGHASH_DEFAULT } = bitcoin__namespace.Transaction;
898
+ const isP2trScript = (script)=>script.length === 34 && script[0] === 0x51 && script[1] === 0x20;
899
+ // Only these types commit to every output, so only they let one approval stand
900
+ // for the whole transaction: SIGHASH_DEFAULT and SIGHASH_ALL for Taproot, SIGHASH_ALL otherwise.
901
+ const committingSighashTypes = (isTaproot)=>isTaproot ? [
902
+ SIGHASH_DEFAULT,
903
+ SIGHASH_ALL
904
+ ] : [
905
+ SIGHASH_ALL
906
+ ];
907
+ /**
908
+ * Describes a PSBT for a signing-quorum intent: its txid, fee, outputs and the
909
+ * sighashes of the inputs the wallet signs, so one approval covers a signature
910
+ * for each of them.
911
+ *
912
+ * The inputs are chosen as `signTransaction` chooses them: the ones that belong
913
+ * to `accountAddress`, narrowed to `signingIndexes` when given. P2WSH co-signing
914
+ * is not part of the intent, so `allowedWitnessScripts` is rejected.
915
+ */ const prepareBtcTransactionSigningOperation = ({ transaction, accountAddress, bitcoinConfig, signingIndexes, allowedSighash, allowedWitnessScripts })=>{
916
+ btcUtils.initEccLib(ecc);
917
+ if (allowedWitnessScripts == null ? void 0 : allowedWitnessScripts.length) throw new Error('BTC signing intent does not support P2WSH co-signing');
918
+ var _bitcoinConfig_network;
919
+ const network = btcUtils.toBitcoinNetwork((_bitcoinConfig_network = bitcoinConfig == null ? void 0 : bitcoinConfig.network) != null ? _bitcoinConfig_network : 'mainnet');
920
+ const psbt = bitcoin__namespace.Psbt.fromBase64(transaction);
921
+ const ownedInputs = psbt.data.inputs.map((input, index)=>({
922
+ input,
923
+ index
924
+ })).filter(({ input })=>btcUtils.doesInputBelongToAddress(input, accountAddress, network));
925
+ const inputsToSign = btcUtils.filterInputsBySigningIndexes(ownedInputs, signingIndexes);
926
+ if (inputsToSign.length === 0) throw new Error('No input of the transaction belongs to the signing account');
927
+ inputsToSign.forEach(({ input, index })=>{
928
+ const isTaproot = Boolean(input.tapInternalKey);
929
+ if (!isTaproot && input.witnessUtxo && isP2trScript(input.witnessUtxo.script)) {
930
+ throw new Error(`Input ${index} is a Taproot input without tapInternalKey`);
931
+ }
932
+ btcUtils.assertSighashAllowed([
933
+ {
934
+ input,
935
+ index
936
+ }
937
+ ], isTaproot, allowedSighash);
938
+ const sighashType = btcUtils.getSigHashType(input, isTaproot);
939
+ if (!committingSighashTypes(isTaproot).includes(sighashType)) {
940
+ throw new Error(`Input ${index} declares sighash type ${sighashType}, which a signing intent does not allow`);
941
+ }
942
+ });
943
+ const { txid, feeSats, outputs, sighashes } = btcUtils.extractPsbtIntentOperation({
944
+ psbtBase64: transaction,
945
+ network,
946
+ inputIndexes: inputsToSign.map(({ index })=>index)
947
+ });
948
+ return {
949
+ operation: {
950
+ kind: 'transaction',
951
+ chainName: 'BTC',
952
+ chainId: btcUtils.getBtcChainId(network),
953
+ txid,
954
+ feeSats,
955
+ outputs,
956
+ sighashes
957
+ }
958
+ };
959
+ };
960
+
782
961
  exports.DynamicBtcWalletClient = DynamicBtcWalletClient;
962
+ exports.prepareBtcTransactionSigningOperation = prepareBtcTransactionSigningOperation;