@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.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, shareSetId)=>{
96
+ onCeremonyComplete: ({ accountAddress, walletId, shareSetId })=>{
96
97
  const chainConfig = browser.getMPCChainConfig(this.chainName, buildBitcoinConfig);
97
98
  this.initializeWalletMapEntry({
98
99
  accountAddress,
@@ -135,7 +136,8 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
135
136
  accountAddress,
136
137
  clientKeyShares,
137
138
  password,
138
- signedSessionId
139
+ signedSessionId,
140
+ businessAccountId
139
141
  });
140
142
  const publicKeyHex = btcUtils.extractPublicKeyHex(rawPublicKey);
141
143
  return {
@@ -144,14 +146,16 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
144
146
  rawPublicKey
145
147
  };
146
148
  } catch (error) {
147
- // Re-throw password mismatch errors without wrapping
148
- 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)) {
149
151
  throw error;
150
152
  }
151
153
  if (onError) {
152
154
  onError(error);
153
155
  }
154
- throw new Error(browser.ERROR_CREATE_WALLET_ACCOUNT);
156
+ throw new Error(browser.ERROR_CREATE_WALLET_ACCOUNT, {
157
+ cause: error
158
+ });
155
159
  }
156
160
  }
157
161
  /**
@@ -172,6 +176,53 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
172
176
  };
173
177
  }
174
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
+ /**
175
226
  * Signs a message (BIP-322)
176
227
  * @param message - The message to sign
177
228
  * @param accountAddress - The account address
@@ -182,61 +233,17 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
182
233
  * @param context - Additional context
183
234
  * @param onError - Error callback
184
235
  * @returns The BIP-322 signature
185
- */ 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 }) {
186
237
  await this.verifyPassword({
187
238
  accountAddress,
188
239
  password,
189
240
  signedSessionId
190
241
  });
191
242
  try {
192
- if (!accountAddress) {
193
- throw new Error(browser.ERROR_ACCOUNT_ADDRESS_REQUIRED);
194
- }
195
- const walletProperties = this.getWalletFromMap(accountAddress);
196
- if (!walletProperties) {
197
- throw new Error('Wallet not found in walletMap');
198
- }
199
- const derivationPath = walletProperties.derivationPath;
200
- if (derivationPath === undefined || derivationPath === null) {
201
- throw new Error('Derivation path missing in walletMap');
202
- }
203
- let addressType = walletProperties.addressType;
204
- if (!addressType) {
205
- addressType = btcUtils.getAddressTypeFromDerivationPath(derivationPath);
206
- }
207
- const clientKeyShares = await this.getClientKeySharesFromStorage({
208
- accountAddress
209
- });
210
- if (!clientKeyShares || clientKeyShares.length === 0) {
211
- throw new Error('No key shares found');
212
- }
213
- const bitcoinConfig = {
214
- addressType,
243
+ const { addressType, completeBitcoinConfig, formattedMessage, pubKey, toSignPsbt } = await this.prepareBip322SignMessage({
244
+ accountAddress,
245
+ message,
215
246
  network
216
- };
217
- const walletDerivationPath = parseDerivationPath(derivationPath);
218
- const derivedPublicKey = await this.derivePublicKey({
219
- chainName: this.chainName,
220
- keyShare: clientKeyShares[0],
221
- derivationPath: walletDerivationPath,
222
- bitcoinConfig
223
- });
224
- if (!derivedPublicKey) {
225
- throw new Error('Failed to derive public key');
226
- }
227
- const pubKey = btcUtils.normalizePublicKey(derivedPublicKey, addressType);
228
- this.verifyWalletAddress(derivedPublicKey, addressType, network, accountAddress);
229
- // Prepare BIP-322 Transactions and calculate hash
230
- const { formattedMessage, toSignPsbt } = btcUtils.calculateBip322Hash(message, pubKey, addressType, network, ecc);
231
- // Prepare tweak for Taproot in case of BIP340
232
- let tweak;
233
- if (addressType === browser.BitcoinAddressType.TAPROOT) {
234
- tweak = btcUtils.calculateTaprootTweak(pubKey);
235
- }
236
- // Build complete bitcoinConfig with addressType and tweak
237
- const completeBitcoinConfig = _extends({}, bitcoinConfig, {
238
- addressType: addressType,
239
- tweak
240
247
  });
241
248
  // Sign the message using MPC
242
249
  const signature = await this.sign({
@@ -252,6 +259,7 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
252
259
  btcMessage: message
253
260
  },
254
261
  bitcoinConfig: completeBitcoinConfig,
262
+ approvalQuorum,
255
263
  onError
256
264
  });
257
265
  // Encode Final Result
@@ -264,8 +272,62 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
264
272
  if (onError) {
265
273
  onError(error);
266
274
  }
267
- 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');
268
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
+ };
269
331
  }
270
332
  /**
271
333
  * Verifies that the derived address matches the expected address
@@ -276,9 +338,19 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
276
338
  */ verifyWalletAddress(rawPublicKey, addressType, network, expectedAddress) {
277
339
  const normalizedKey = btcUtils.normalizePublicKey(rawPublicKey, addressType);
278
340
  const derivedAddress = btcUtils.publicKeyToBitcoinAddress(normalizedKey, addressType, network, ecc);
279
- if (derivedAddress !== expectedAddress) {
280
- 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
+ }
281
352
  }
353
+ throw new Error(`Address verification failed: expected ${expectedAddress}, got ${derivedAddress}`);
282
354
  }
283
355
  /**
284
356
  * Exports the private key for a given account
@@ -288,7 +360,29 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
288
360
  * @param mfaToken - The MFA token to use for the private key
289
361
  * @param network - The network to use for the private key
290
362
  * @returns The private key
291
- */ 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 }) {
292
386
  await this.verifyPassword({
293
387
  accountAddress,
294
388
  password,
@@ -303,17 +397,11 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
303
397
  if (derivationPath === undefined || derivationPath === null) {
304
398
  throw new Error('Derivation path missing in walletMap');
305
399
  }
306
- let addressType = walletProperties.addressType;
307
- if (!addressType && walletProperties.derivationPath) {
308
- try {
309
- addressType = btcUtils.getAddressTypeFromDerivationPath(walletProperties.derivationPath);
310
- } catch (e) {
311
- this.logger.warn('Failed to infer address type from derivation path', e);
312
- }
313
- }
314
- if (!addressType) {
315
- throw new Error('Address type not found in walletMap');
316
- }
400
+ const addressType = btcUtils.resolveBitcoinAddressType({
401
+ accountAddress,
402
+ addressType: walletProperties.addressType,
403
+ derivationPath: walletProperties.derivationPath
404
+ });
317
405
  const { derivedPrivateKey } = await this.exportKey({
318
406
  accountAddress: accountAddress,
319
407
  chainName: this.chainName,
@@ -323,13 +411,16 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
323
411
  password,
324
412
  signedSessionId,
325
413
  mfaToken,
326
- elevatedAccessToken
414
+ elevatedAccessToken,
415
+ approvalQuorum,
416
+ proposalId
327
417
  });
328
418
  if (!derivedPrivateKey) {
329
419
  throw new Error('Failed to derive private key');
330
420
  }
421
+ var _bitcoinConfig_network;
331
422
  // Convert MPC private key to Bitcoin WIF format
332
- 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);
333
424
  }
334
425
  /**
335
426
  * Imports a private key and creates a Bitcoin wallet account
@@ -378,7 +469,7 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
378
469
  addressType: addressTypeEnum,
379
470
  network
380
471
  },
381
- onCeremonyComplete: (accountAddress, walletId, shareSetId)=>{
472
+ onCeremonyComplete: ({ accountAddress, walletId, shareSetId })=>{
382
473
  ceremonyAccountAddress = accountAddress;
383
474
  // For imported BTC wallets, use empty derivation path
384
475
  // The server returns "[]" for imported wallets (raw key, not derived)
@@ -438,7 +529,7 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
438
529
  } catch (error) {
439
530
  this.logger.error(browser.ERROR_IMPORT_PRIVATE_KEY, error);
440
531
  onError == null ? void 0 : onError(error);
441
- throw new Error(browser.ERROR_IMPORT_PRIVATE_KEY);
532
+ throw error;
442
533
  }
443
534
  }
444
535
  /**
@@ -474,6 +565,14 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
474
565
  /**
475
566
  * Sign a Bitcoin Transaction (PSBT)
476
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
+ *
477
576
  * @param transaction - The PSBT to sign in hex format
478
577
  * @param senderAddress - The address of the sender
479
578
  * @param password - The password to use for the transaction
@@ -482,8 +581,12 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
482
581
  * @param mfaToken - The MFA token to use for the transaction
483
582
  * @param context - The context to use for the transaction
484
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
485
588
  * @returns The signed PSBT
486
- */ 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 }) {
487
590
  try {
488
591
  await this.verifyPassword({
489
592
  accountAddress: senderAddress,
@@ -501,10 +604,11 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
501
604
  if (derivationPath === undefined || derivationPath === null) {
502
605
  throw new Error('Derivation path missing in walletMap');
503
606
  }
504
- let addressType = walletProperties.addressType;
505
- if (!addressType) {
506
- addressType = btcUtils.getAddressTypeFromDerivationPath(derivationPath);
507
- }
607
+ const addressType = btcUtils.resolveBitcoinAddressType({
608
+ accountAddress: senderAddress,
609
+ addressType: walletProperties.addressType,
610
+ derivationPath
611
+ });
508
612
  const bitcoinConfig = {
509
613
  addressType,
510
614
  network
@@ -528,23 +632,31 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
528
632
  }
529
633
  const pubKey = btcUtils.normalizePublicKey(derivedPublicKey, addressType);
530
634
  const tx = psbt.__CACHE.__TX;
531
- // Filter inputs to only sign those that belong to the current address
532
- 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)=>({
533
643
  input,
534
644
  index: i
535
- })).filter(({ input })=>btcUtils.doesInputBelongToAddress(input, senderAddress, network));
645
+ })).filter(({ input })=>btcUtils.doesInputBelongToAddress(input, senderAddress, network, walletPubKey, p2wshAllowlist));
536
646
  this.logger.debug('[BTC Client] signTransaction - Filtering inputs', {
537
647
  totalInputs: psbt.data.inputs.length,
538
648
  inputsToSign: inputsToSign.length,
539
649
  senderAddress
540
650
  });
651
+ inputsToSign = btcUtils.filterInputsBySigningIndexes(inputsToSign, signingIndexes);
541
652
  if (inputsToSign.length === 0) {
542
653
  this.logger.warn('[BTC Client] signTransaction - No inputs found for address', {
543
654
  senderAddress,
544
655
  totalInputs: psbt.data.inputs.length
545
656
  });
546
657
  }
547
- if (addressType === browser.BitcoinAddressType.TAPROOT) {
658
+ btcUtils.assertSighashAllowed(inputsToSign, isTaproot, allowedSighash);
659
+ if (isTaproot) {
548
660
  const tweak = btcUtils.calculateTaprootTweak(pubKey);
549
661
  const completeBitcoinConfig = _extends({}, bitcoinConfig, {
550
662
  addressType: addressType,
@@ -555,7 +667,8 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
555
667
  if (!input.witnessUtxo) {
556
668
  throw new Error(`Input ${i} missing witnessUtxo`);
557
669
  }
558
- 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));
559
672
  const signature = await this.sign({
560
673
  message: new Uint8Array(hash),
561
674
  accountAddress: senderAddress,
@@ -568,13 +681,14 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
568
681
  context: _extends({}, context, {
569
682
  btcTransaction: {
570
683
  psbt: transaction,
571
- chainId: '1'
684
+ chainId: network === browser.BitcoinNetwork.TESTNET ? '2' : '1'
572
685
  }
573
686
  }),
574
687
  bitcoinConfig: completeBitcoinConfig,
688
+ approvalQuorum,
575
689
  onError
576
690
  });
577
- const sigBuffer = btcUtils.convertSignatureToTaprootBuffer(signature);
691
+ const sigBuffer = btcUtils.convertSignatureToTaprootBuffer(signature, sigHashType);
578
692
  psbt.updateInput(i, {
579
693
  tapKeySig: sigBuffer
580
694
  });
@@ -591,13 +705,11 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
591
705
  throw new Error(`Input ${i} missing witnessUtxo`);
592
706
  }
593
707
  const { script, value } = input.witnessUtxo;
594
- const p2pkh = bitcoin__namespace.payments.p2pkh({
595
- hash: script.slice(2),
596
- network: btcUtils.getBitcoinNetwork(network)
597
- });
598
- const scriptCode = p2pkh.output;
599
- if (!scriptCode) throw new Error('Failed to generate scriptCode');
600
- 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);
601
713
  const signature = await this.sign({
602
714
  message: new Uint8Array(hash),
603
715
  accountAddress: senderAddress,
@@ -610,13 +722,14 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
610
722
  context: _extends({}, context, {
611
723
  btcTransaction: {
612
724
  psbt: transaction,
613
- chainId: '1'
725
+ chainId: network === browser.BitcoinNetwork.TESTNET ? '2' : '1'
614
726
  }
615
727
  }),
616
728
  bitcoinConfig: completeBitcoinConfig,
729
+ approvalQuorum,
617
730
  onError
618
731
  });
619
- const derSignature = btcUtils.convertSignatureToDER(signature);
732
+ const derSignature = btcUtils.convertSignatureToDER(signature, sigHashType);
620
733
  psbt.updateInput(i, {
621
734
  partialSig: [
622
735
  {
@@ -647,16 +760,26 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
647
760
  * @param amount - The amount to send in satoshis
648
761
  * @param senderAddress - The address to send funds from
649
762
  * @param network - The network to use (mainnet/testnet)
650
- * @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`
651
768
  * @returns The PSBT in hex format
652
- */ 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.
653
771
  this.logger.debug('[BTC Client] Creating transaction', {
654
772
  receiverAddress,
655
773
  amount,
656
774
  senderAddress,
657
775
  network,
658
- feeRateLevel
776
+ feeRateLevel,
777
+ feeRate: feeRateOverride,
778
+ hasCustomRpcUrl: Boolean(rpcUrl)
659
779
  });
780
+ if (feeRateOverride !== undefined && (!Number.isFinite(feeRateOverride) || feeRateOverride <= 0)) {
781
+ throw new Error('feeRate must be a positive number (sat/vByte)');
782
+ }
660
783
  if (!senderAddress) {
661
784
  throw new Error(browser.ERROR_ACCOUNT_ADDRESS_REQUIRED);
662
785
  }
@@ -664,26 +787,24 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
664
787
  if (!walletProperties) {
665
788
  throw new Error('Wallet not found in walletMap');
666
789
  }
667
- let addressType = walletProperties.addressType;
668
- if (!addressType && walletProperties.derivationPath) {
669
- addressType = btcUtils.getAddressTypeFromDerivationPath(walletProperties.derivationPath);
670
- }
671
- if (!addressType) {
672
- throw new Error('Address type not determined');
673
- }
790
+ const addressType = btcUtils.resolveBitcoinAddressType({
791
+ accountAddress: senderAddress,
792
+ addressType: walletProperties.addressType,
793
+ derivationPath: walletProperties.derivationPath
794
+ });
674
795
  if (addressType === browser.BitcoinAddressType.TAPROOT) {
675
796
  throw new Error('Taproot transaction creation not yet supported');
676
797
  }
677
798
  const bitcoinNetwork = network === 'testnet' ? bitcoin__namespace.networks.testnet : bitcoin__namespace.networks.bitcoin;
678
- // Fetch fee rates
679
- const feeRates = await btcUtils.getFeeRates({
680
- network
681
- });
682
- const feeRate = feeRates[feeRateLevel];
799
+ const feeRate = feeRateOverride != null ? feeRateOverride : (await btcUtils.getFeeRates({
800
+ network,
801
+ rpcUrl
802
+ }))[feeRateLevel];
683
803
  // Fetch UTXOs
684
804
  const utxos = await btcUtils.getUTXOs({
685
805
  address: senderAddress,
686
- network
806
+ network,
807
+ rpcUrl
687
808
  });
688
809
  // Select UTXOs
689
810
  const { inputs, change, fee } = btcUtils.selectUTXOs({
@@ -696,7 +817,7 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
696
817
  });
697
818
  // Prepare inputs
698
819
  await Promise.all(inputs.map(async (utxo)=>{
699
- const txHex = await this.getTxHex(utxo.txid, network);
820
+ const txHex = await this.getTxHex(utxo.txid, network, rpcUrl);
700
821
  const inputData = {
701
822
  hash: utxo.txid,
702
823
  index: utxo.vout,
@@ -742,10 +863,14 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
742
863
  * Fetches the raw transaction hex for a given transaction ID
743
864
  * @param txid - The transaction ID
744
865
  * @param network - The network
866
+ * @param rpcUrl - Optional custom Esplora-compatible API base URL
745
867
  * @returns The transaction hex
746
- */ async getTxHex(txid, network) {
747
- const baseUrl = btcUtils.getDefaultRpcUrl(network);
748
- 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);
749
874
  if (!response.ok) {
750
875
  throw new Error(`Failed to fetch TX hex: ${response.statusText}`);
751
876
  }
@@ -762,23 +887,76 @@ class DynamicBtcWalletClient extends browser.DynamicWalletClient {
762
887
  /**
763
888
  * Creates a new instance of DynamicBtcWalletClient
764
889
  * @param props - The client properties
765
- */ constructor({ environmentId, authToken, baseApiUrl, baseMPCRelayApiUrl, storageKey, debug, featureFlags, authMode = browser.AuthMode.HEADER, sdkVersion, forwardMPCClient, logger }, internalOptions){
766
- super({
767
- environmentId,
768
- authToken,
769
- baseApiUrl,
770
- baseMPCRelayApiUrl,
771
- storageKey,
772
- debug,
773
- featureFlags,
774
- authMode,
775
- sdkVersion,
776
- forwardMPCClient,
777
- logger
778
- }, internalOptions), this.chainName = 'BTC';
890
+ */ constructor(props, internalOptions){
891
+ super(props, internalOptions), this.chainName = 'BTC';
779
892
  // Initialize ECC library for bitcoinjs-lib
780
893
  btcUtils.initEccLib(ecc);
781
894
  }
782
895
  }
783
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
+
784
961
  exports.DynamicBtcWalletClient = DynamicBtcWalletClient;
962
+ exports.prepareBtcTransactionSigningOperation = prepareBtcTransactionSigningOperation;