@dynamic-labs-wallet/node-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,6 +1,6 @@
1
- import { createLogError, DynamicWalletClient, getMPCChainConfig, getExternalServerKeyShareBackupInfo, WalletOperation } from '@dynamic-labs-wallet/node';
2
- import { BitcoinAddressType, BitcoinNetwork } from '@dynamic-labs-wallet/core';
3
- import { initEccLib, normalizePublicKey, publicKeyToBitcoinAddress, getAddressTypeFromDerivationPath, extractPublicKeyHex, calculateBip322Hash, calculateTaprootTweak, encodeBip322Signature, doesInputBelongToAddress, collectPSBTInputData, convertSignatureToTaprootBuffer, getBitcoinNetwork, convertSignatureToDER, privateKeyToWIF, wifToPrivateKey, getPublicKeyFromPrivateKey } from '@dynamic-labs-wallet/btc-utils';
1
+ import { createLogError, DynamicWalletClient, getMPCChainConfig, WalletOperation } from '@dynamic-labs-wallet/node';
2
+ import { BitcoinNetwork, BitcoinAddressType } from '@dynamic-labs-wallet/core';
3
+ import { initEccLib, normalizePublicKey, publicKeyToBitcoinAddress, resolveBitcoinAddressType, extractPublicKeyHex, calculateBip322Hash, calculateTaprootTweak, encodeBip322Signature, doesInputBelongToAddress, filterInputsBySigningIndexes, assertSighashAllowed, collectPSBTInputData, getSigHashType, convertSignatureToTaprootBuffer, getSegwitV0ScriptCode, getBitcoinNetwork, convertSignatureToDER, privateKeyToWIF, wifToPrivateKey, getPublicKeyFromPrivateKey } from '@dynamic-labs-wallet/btc-utils';
4
4
  import * as bitcoin from 'bitcoinjs-lib';
5
5
  import * as ecc from 'tiny-secp256k1';
6
6
 
@@ -44,22 +44,36 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
44
44
  };
45
45
  }
46
46
  /**
47
- * Gets wallet properties and derivation info for a given account address
48
- * @param accountAddress - The account address
49
- * @returns The wallet properties, derivation path, and address type
50
- */ getWalletDerivationInfo(accountAddress) {
51
- const walletProperties = this.walletMap[accountAddress];
52
- if (!walletProperties) {
53
- throw new Error('Wallet not found in walletMap');
54
- }
55
- const derivationPath = walletProperties.derivationPath;
47
+ * Extracts derivation path and address type from walletMetadata.
48
+ * @param walletMetadata - The wallet metadata
49
+ * @returns The derivation path and derived address type
50
+ */ getDerivationInfoFromMetadata(walletMetadata) {
51
+ const derivationPath = walletMetadata.derivationPath;
56
52
  if (!derivationPath) {
57
- throw new Error('Derivation path missing in walletMap');
53
+ throw new Error('Derivation path missing in walletMetadata');
58
54
  }
59
55
  return {
60
- walletProperties,
61
56
  derivationPath,
62
- addressType: getAddressTypeFromDerivationPath(derivationPath)
57
+ addressType: resolveBitcoinAddressType({
58
+ accountAddress: walletMetadata.accountAddress,
59
+ addressType: walletMetadata.addressType,
60
+ derivationPath
61
+ })
62
+ };
63
+ }
64
+ buildWalletMetadata({ walletId, accountAddress, thresholdSignatureScheme, addressType, bitcoinConfig, shareSetId }) {
65
+ const chainConfig = getMPCChainConfig(this.chainName, bitcoinConfig);
66
+ return {
67
+ walletId,
68
+ accountAddress,
69
+ chainName: this.chainName,
70
+ thresholdSignatureScheme,
71
+ derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map((value, index)=>[
72
+ index,
73
+ value
74
+ ]))),
75
+ addressType,
76
+ shareSetId
63
77
  };
64
78
  }
65
79
  /**
@@ -71,19 +85,29 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
71
85
  */ verifyWalletAddress(rawPublicKey, addressType, network, expectedAddress) {
72
86
  const normalizedKey = normalizePublicKey(rawPublicKey, addressType);
73
87
  const derivedAddress = publicKeyToBitcoinAddress(normalizedKey, addressType, network);
74
- if (derivedAddress !== expectedAddress) {
75
- throw new Error(`Address verification failed: expected ${expectedAddress}, got ${derivedAddress}`);
88
+ if (derivedAddress === expectedAddress) {
89
+ return;
90
+ }
91
+ // Callers pass the wallet identity address (the mainnet encoding that
92
+ // keys the wallet map) even when signing for another network — the same
93
+ // key encodes differently per network, so accept the identity encoding.
94
+ if (network !== BitcoinNetwork.MAINNET) {
95
+ const identityAddress = publicKeyToBitcoinAddress(normalizedKey, addressType, BitcoinNetwork.MAINNET);
96
+ if (identityAddress === expectedAddress) {
97
+ return;
98
+ }
76
99
  }
100
+ throw new Error(`Address verification failed: expected ${expectedAddress}, got ${derivedAddress}`);
77
101
  }
78
102
  /**
79
103
  * Creates a new wallet account and stores the key shares in the wallet map.
80
104
  * @param thresholdSignatureScheme - The threshold signature scheme to use for the wallet.
81
105
  * @param password - The password to use for the wallet.
82
106
  * @param onError - The function to call if an error occurs.
83
- * @param backUpToClientShareService - Whether to back up the external server key shares to the client share service. By default, it is false.
107
+ * @param backUpToDynamic - Whether to back up the external server key shares to the client share service. By default, it is false.
84
108
  * @param bitcoinConfig - Bitcoin configuration (addressType, network)
85
109
  * @returns The account address, public key, raw public key, external server key shares, and wallet id.
86
- */ async createWalletAccount({ thresholdSignatureScheme, password = undefined, onError, backUpToClientShareService = false, bitcoinConfig }) {
110
+ */ async createWalletAccount({ thresholdSignatureScheme, password, onError, backUpToDynamic = false, bitcoinConfig }) {
87
111
  try {
88
112
  if (!(bitcoinConfig == null ? void 0 : bitcoinConfig.addressType)) {
89
113
  this.logger.warn('[BTC Node Client] addressType not provided for createWalletAccount, defaulting to native_segwit');
@@ -96,46 +120,21 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
96
120
  addressType,
97
121
  network
98
122
  };
99
- let ceremonyCeremonyCompleteResolver;
100
- let ceremonyAccountAddress;
101
- const ceremonyCompletePromise = new Promise((resolve)=>{
102
- ceremonyCeremonyCompleteResolver = resolve;
103
- });
123
+ const ceremony = this.createCeremonyCompletionTracker();
104
124
  // Generate key shares for given threshold signature scheme (TSS)
105
125
  const { rawPublicKey, externalServerKeyShares } = await this.keyGen({
106
126
  chainName: this.chainName,
107
127
  thresholdSignatureScheme,
108
128
  skipLock: true,
109
129
  bitcoinConfig: resolvedBitcoinConfig,
130
+ password,
131
+ backUpToDynamic,
110
132
  onError,
111
- onCeremonyComplete: (accountAddress, walletId)=>{
112
- // Store the ceremony account address to ensure consistency
113
- ceremonyAccountAddress = accountAddress;
114
- // update wallet map
115
- const chainConfig = getMPCChainConfig(this.chainName, resolvedBitcoinConfig);
116
- this.walletMap[accountAddress] = _extends({}, this.walletMap[accountAddress], {
117
- accountAddress,
118
- walletId,
119
- chainName: this.chainName,
120
- thresholdSignatureScheme,
121
- derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map((value, index)=>[
122
- index,
123
- value
124
- ]))),
125
- externalServerKeySharesBackupInfo: getExternalServerKeyShareBackupInfo()
126
- });
127
- this.logger.debug('walletMap updated for wallet', {
128
- context: {
129
- accountAddress,
130
- walletId,
131
- walletMap: this.walletMap
132
- }
133
- });
134
- ceremonyCeremonyCompleteResolver(undefined);
135
- }
133
+ onCeremonyComplete: ceremony.onCeremonyComplete
136
134
  });
137
- await ceremonyCompletePromise;
138
- if (!rawPublicKey || !externalServerKeyShares) {
135
+ await ceremony.promise;
136
+ const { accountAddress: ceremonyAccountAddress, walletId: resolvedWalletId, shareSetId: resolvedShareSetId } = ceremony.completion;
137
+ if (!rawPublicKey || !externalServerKeyShares || !resolvedWalletId) {
139
138
  throw new Error(ERROR_KEYGEN_FAILED);
140
139
  }
141
140
  const accountAddress = ceremonyAccountAddress || this.deriveAccountAddress({
@@ -143,19 +142,31 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
143
142
  addressType,
144
143
  network
145
144
  }).accountAddress;
146
- const externalKeySharesWithBackupStatus = await this.storeEncryptedBackupByWalletWithRetry({
145
+ const walletMetadata = this.buildWalletMetadata({
146
+ walletId: resolvedWalletId,
147
+ accountAddress,
148
+ thresholdSignatureScheme,
149
+ addressType,
150
+ bitcoinConfig: resolvedBitcoinConfig,
151
+ shareSetId: resolvedShareSetId
152
+ });
153
+ const { keySharesWithBackupStatus, backupInfo } = await this.storeEncryptedBackupByWalletWithRetry({
147
154
  accountAddress,
148
155
  externalServerKeyShares,
149
156
  password,
150
- backUpToClientShareService
157
+ backUpToDynamic,
158
+ walletMetadata
151
159
  });
160
+ walletMetadata.externalServerKeySharesBackupInfo = backupInfo;
152
161
  const publicKeyHex = extractPublicKeyHex(rawPublicKey);
162
+ var _ceremony_completion_encryptedWalletApiKey;
153
163
  return {
154
- accountAddress,
164
+ walletMetadata,
155
165
  rawPublicKey,
156
166
  publicKeyHex,
157
167
  externalServerKeyShares,
158
- externalKeySharesWithBackupStatus
168
+ externalKeySharesWithBackupStatus: keySharesWithBackupStatus,
169
+ encryptedWalletApiKey: (_ceremony_completion_encryptedWalletApiKey = ceremony.completion.encryptedWalletApiKey) != null ? _ceremony_completion_encryptedWalletApiKey : undefined
159
170
  };
160
171
  } catch (error) {
161
172
  logError({
@@ -163,7 +174,9 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
163
174
  error: error,
164
175
  context: {}
165
176
  });
166
- throw new Error(ERROR_CREATE_WALLET_ACCOUNT);
177
+ throw new Error(ERROR_CREATE_WALLET_ACCOUNT, {
178
+ cause: error
179
+ });
167
180
  }
168
181
  }
169
182
  /**
@@ -181,32 +194,29 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
181
194
  * @param onError - Optional. Error callback function
182
195
  * @returns Promise resolving to the BIP-322 signature as a base64 string
183
196
  * @throws Error if required parameters are missing, derivation path is invalid, or signing fails
184
- */ async signMessage({ message, accountAddress, network, password = undefined, externalServerKeyShares, context, onError }) {
197
+ */ async signMessage({ message, walletMetadata, network, password = undefined, externalServerKeyShares, context, onError }) {
198
+ const { accountAddress } = walletMetadata;
185
199
  try {
186
- var _this_walletMap_accountAddress;
187
200
  if (!accountAddress) {
188
201
  throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
189
202
  }
190
- const { derivationPath, addressType } = this.getWalletDerivationInfo(accountAddress);
191
- // Attempt to recover key shares from backup if not provided
192
- await this.ensureKeySharesRecovered({
203
+ const { derivationPath, addressType } = this.getDerivationInfoFromMetadata(walletMetadata);
204
+ // Resolve key shares from param or backup
205
+ const resolvedKeyShares = await this.resolveKeyShares({
193
206
  accountAddress,
194
207
  password,
195
208
  walletOperation: WalletOperation.SIGN_MESSAGE,
196
209
  externalServerKeyShares,
197
- errorMessage: 'External server key shares are required to sign a message. No backup shares available for recovery.'
210
+ errorMessage: 'External server key shares are required to sign a message. No backup shares available for recovery.',
211
+ walletMetadata
198
212
  });
199
- const resolvedExternalServerKeyShares = externalServerKeyShares != null ? externalServerKeyShares : (_this_walletMap_accountAddress = this.walletMap[accountAddress]) == null ? void 0 : _this_walletMap_accountAddress.externalServerKeyShares;
200
- if (!resolvedExternalServerKeyShares || resolvedExternalServerKeyShares.length === 0) {
201
- throw new Error('External server key shares are required to sign a message');
202
- }
203
213
  const bitcoinConfig = {
204
214
  addressType,
205
215
  network
206
216
  };
207
217
  const derivedPublicKey = await this.derivePublicKey({
208
218
  chainName: this.chainName,
209
- keyShare: resolvedExternalServerKeyShares[0],
219
+ keyShare: resolvedKeyShares[0],
210
220
  derivationPath: new Uint32Array(Object.values(JSON.parse(derivationPath))),
211
221
  bitcoinConfig
212
222
  });
@@ -233,13 +243,15 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
233
243
  accountAddress,
234
244
  chainName: this.chainName,
235
245
  password,
236
- externalServerKeyShares: resolvedExternalServerKeyShares,
246
+ externalServerKeyShares: resolvedKeyShares,
237
247
  isFormatted: true,
238
248
  context: context != null ? context : {
239
249
  btcMessage: message
240
250
  },
241
251
  bitcoinConfig: completeBitcoinConfig,
242
- onError
252
+ onError,
253
+ walletMetadata,
254
+ passwordPreVerified: !(externalServerKeyShares == null ? void 0 : externalServerKeyShares.length) && !!password
243
255
  });
244
256
  const bip322Signature = encodeBip322Signature(toSignPsbt, pubKey, signature, addressType);
245
257
  return bip322Signature;
@@ -254,51 +266,51 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
254
266
  if (onError) {
255
267
  onError(error);
256
268
  }
257
- throw new Error(ERROR_SIGN_MESSAGE);
269
+ throw new Error(ERROR_SIGN_MESSAGE, {
270
+ cause: error
271
+ });
258
272
  }
259
273
  }
260
274
  /**
261
275
  * Signs a Bitcoin transaction (PSBT)
262
276
  *
263
277
  * The address type is automatically derived from the wallet's derivation path.
264
- * Only inputs belonging to the sender address are signed. Supports both TAPROOT
278
+ * Only inputs belonging to the account address are signed. Supports both TAPROOT
265
279
  * (BIP-341) and Native SegWit (BIP-143) signing methods.
266
280
  *
281
+ * ECDSA wallets can also co-sign P2WSH multisig inputs, but only opt-in: pass the
282
+ * hex-encoded witnessScripts you constructed via `allowedWitnessScripts`. An input
283
+ * is signed when its witnessScript is allowlisted, hashes to the scriptPubKey
284
+ * commitment, and is a canonical multisig containing this wallet's public key.
285
+ * Omitting `allowedWitnessScripts` disables P2WSH signing entirely. The returned
286
+ * PSBT carries this wallet's partialSig and is NOT finalized — remaining
287
+ * co-signers add their signatures before finalizing.
288
+ *
267
289
  * @param transaction - The PSBT to sign as a base64 string
268
- * @param senderAddress - The sender address (must match inputs to be signed)
290
+ * @param accountAddress - The account address (must match inputs to be signed)
269
291
  * @param network - The Bitcoin network (MAINNET or TESTNET)
270
292
  * @param password - Optional password for encrypted backup shares
271
293
  * @param externalServerKeyShares - Optional external server key shares
272
294
  * @param context - Optional. Sign message context for API tracking
273
295
  * @param onError - Optional. Error callback function
274
296
  * @returns Promise resolving to the signed PSBT as a base64 string
275
- * @throws Error if required parameters are missing, no inputs belong to sender address, or signing fails
276
- */ async signTransaction({ transaction, senderAddress, network, password = undefined, externalServerKeyShares, context, onError }) {
297
+ * @throws Error if required parameters are missing, no inputs belong to account address, or signing fails
298
+ */ async signTransaction({ transaction, walletMetadata, network, password = undefined, externalServerKeyShares, context, onError, signingIndexes, allowedSighash, allowedWitnessScripts }) {
299
+ const { accountAddress } = walletMetadata;
277
300
  try {
278
- await this.verifyPassword({
279
- accountAddress: senderAddress,
280
- password
281
- });
282
- if (!senderAddress) {
301
+ if (!accountAddress) {
283
302
  throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
284
303
  }
285
- const { derivationPath, addressType } = this.getWalletDerivationInfo(senderAddress);
286
- // Attempt to recover key shares from backup if not provided
287
- await this.ensureKeySharesRecovered({
288
- accountAddress: senderAddress,
304
+ const { derivationPath, addressType } = this.getDerivationInfoFromMetadata(walletMetadata);
305
+ // Resolve key shares from param or backup
306
+ const resolvedKeyShares = await this.resolveKeyShares({
307
+ accountAddress,
289
308
  password,
290
309
  walletOperation: WalletOperation.SIGN_TRANSACTION,
291
310
  externalServerKeyShares,
292
- errorMessage: 'External server key shares are required to sign transaction. No backup shares available for recovery.'
311
+ errorMessage: 'External server key shares are required to sign transaction. No backup shares available for recovery.',
312
+ walletMetadata
293
313
  });
294
- const updatedWalletProperties = this.walletMap[senderAddress];
295
- if (!updatedWalletProperties) {
296
- throw new Error('Wallet not found in walletMap after key share recovery');
297
- }
298
- const resolvedExternalServerKeyShares = externalServerKeyShares || updatedWalletProperties.externalServerKeyShares;
299
- if (!resolvedExternalServerKeyShares || resolvedExternalServerKeyShares.length === 0) {
300
- throw new Error('External server key shares are required to sign transaction. No backup shares available for recovery.');
301
- }
302
314
  const bitcoinConfig = {
303
315
  addressType,
304
316
  network
@@ -306,7 +318,7 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
306
318
  const psbt = bitcoin.Psbt.fromBase64(transaction);
307
319
  const derivedPublicKey = await this.derivePublicKey({
308
320
  chainName: this.chainName,
309
- keyShare: resolvedExternalServerKeyShares[0],
321
+ keyShare: resolvedKeyShares[0],
310
322
  derivationPath: new Uint32Array(Object.values(JSON.parse(derivationPath))),
311
323
  bitcoinConfig
312
324
  });
@@ -315,15 +327,23 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
315
327
  }
316
328
  const pubKey = normalizePublicKey(derivedPublicKey, addressType);
317
329
  const tx = psbt.__CACHE.__TX;
318
- // Filter inputs to only sign those that belong to the current address
319
- const inputsToSign = psbt.data.inputs.map((input, i)=>({
330
+ const isTaproot = addressType === BitcoinAddressType.TAPROOT;
331
+ // Filter inputs to only sign those that belong to the current address.
332
+ // P2WSH (multisig) inputs are opt-in: matched only when the caller
333
+ // allowlisted the witnessScript and it contains this wallet's key —
334
+ // ECDSA wallets only.
335
+ const walletPubKey = isTaproot ? undefined : pubKey;
336
+ const p2wshAllowlist = isTaproot ? undefined : allowedWitnessScripts;
337
+ let inputsToSign = psbt.data.inputs.map((input, i)=>({
320
338
  input,
321
339
  index: i
322
- })).filter(({ input })=>doesInputBelongToAddress(input, senderAddress, network));
340
+ })).filter(({ input })=>doesInputBelongToAddress(input, accountAddress, network, walletPubKey, p2wshAllowlist));
341
+ inputsToSign = filterInputsBySigningIndexes(inputsToSign, signingIndexes);
323
342
  if (inputsToSign.length === 0) {
324
- throw new Error('No inputs found that belong to the sender address');
343
+ throw new Error('No inputs found that belong to the account address');
325
344
  }
326
- if (addressType === BitcoinAddressType.TAPROOT) {
345
+ assertSighashAllowed(inputsToSign, isTaproot, allowedSighash);
346
+ if (isTaproot) {
327
347
  const tweak = calculateTaprootTweak(pubKey);
328
348
  const completeBitcoinConfig = _extends({}, bitcoinConfig, {
329
349
  addressType,
@@ -334,19 +354,27 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
334
354
  if (!input.witnessUtxo) {
335
355
  throw new Error(`Input ${i} missing witnessUtxo`);
336
356
  }
337
- const hash = Buffer.from(tx.hashForWitnessV1(i, prevOutScripts, values, bitcoin.Transaction.SIGHASH_DEFAULT));
357
+ const sigHashType = getSigHashType(input, true);
358
+ const hash = Buffer.from(tx.hashForWitnessV1(i, prevOutScripts, values, sigHashType));
338
359
  const signature = await this.sign({
339
360
  message: new Uint8Array(hash),
340
- accountAddress: senderAddress,
361
+ accountAddress,
341
362
  chainName: this.chainName,
342
363
  password,
343
- externalServerKeyShares: resolvedExternalServerKeyShares,
364
+ externalServerKeyShares: resolvedKeyShares,
344
365
  isFormatted: true,
345
- context,
366
+ context: _extends({}, context, {
367
+ btcTransaction: {
368
+ psbt: transaction,
369
+ chainId: network === BitcoinNetwork.TESTNET ? '2' : '1'
370
+ }
371
+ }),
346
372
  bitcoinConfig: completeBitcoinConfig,
347
- onError
373
+ onError,
374
+ walletMetadata,
375
+ passwordPreVerified: !(externalServerKeyShares == null ? void 0 : externalServerKeyShares.length) && !!password
348
376
  });
349
- const sigBuffer = convertSignatureToTaprootBuffer(signature);
377
+ const sigBuffer = convertSignatureToTaprootBuffer(signature, sigHashType);
350
378
  psbt.updateInput(i, {
351
379
  tapKeySig: sigBuffer
352
380
  });
@@ -361,27 +389,30 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
361
389
  throw new Error(`Input ${i} missing witnessUtxo`);
362
390
  }
363
391
  const { script, value } = input.witnessUtxo;
364
- const p2pkh = bitcoin.payments.p2pkh({
365
- hash: script.slice(2),
366
- network: getBitcoinNetwork(network)
367
- });
368
- const scriptCode = p2pkh.output;
369
- if (!scriptCode) {
370
- throw new Error('Failed to generate scriptCode');
371
- }
372
- const hash = tx.hashForWitnessV0(i, scriptCode, value, bitcoin.Transaction.SIGHASH_ALL);
392
+ // Shared with extractPsbtSighashes; re-verifies the P2WSH
393
+ // commitment at the signer, independent of the ownership filter.
394
+ const scriptCode = getSegwitV0ScriptCode(input, script, i, getBitcoinNetwork(network));
395
+ const sigHashType = getSigHashType(input, false);
396
+ const hash = tx.hashForWitnessV0(i, scriptCode, value, sigHashType);
373
397
  const signature = await this.sign({
374
398
  message: new Uint8Array(hash),
375
- accountAddress: senderAddress,
399
+ accountAddress,
376
400
  chainName: this.chainName,
377
401
  password,
378
- externalServerKeyShares: resolvedExternalServerKeyShares,
402
+ externalServerKeyShares: resolvedKeyShares,
379
403
  isFormatted: true,
380
- context,
404
+ context: _extends({}, context, {
405
+ btcTransaction: {
406
+ psbt: transaction,
407
+ chainId: network === BitcoinNetwork.TESTNET ? '2' : '1'
408
+ }
409
+ }),
381
410
  bitcoinConfig: completeBitcoinConfig,
382
- onError
411
+ onError,
412
+ walletMetadata,
413
+ passwordPreVerified: !(externalServerKeyShares == null ? void 0 : externalServerKeyShares.length) && !!password
383
414
  });
384
- const derSignature = convertSignatureToDER(signature);
415
+ const derSignature = convertSignatureToDER(signature, sigHashType);
385
416
  psbt.updateInput(i, {
386
417
  partialSig: [
387
418
  {
@@ -399,7 +430,7 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
399
430
  message: ERROR_SIGN_TRANSACTION,
400
431
  error: error,
401
432
  context: {
402
- senderAddress
433
+ accountAddress
403
434
  }
404
435
  });
405
436
  if (onError) {
@@ -410,47 +441,25 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
410
441
  }
411
442
  /**
412
443
  * Exports the private key for a wallet
413
- * @param accountAddress - The account address to export the private key for
444
+ * @param walletMetadata - The wallet metadata of the wallet to export
414
445
  * @param password - The password for encrypted backup shares
415
446
  * @param externalServerKeyShares - Optional external server key shares
447
+ * @param network - Network the WIF is encoded for. Defaults to mainnet. `walletMetadata` does not record a network, so pass `BitcoinNetwork.TESTNET` for a wallet you use on testnet
416
448
  * @returns The private key in WIF format
417
- */ async exportPrivateKey({ accountAddress, password = undefined, externalServerKeyShares }) {
418
- await this.verifyPassword({
419
- accountAddress,
420
- password
421
- });
422
- // Attempt to recover key shares from backup if not provided
423
- await this.ensureKeySharesRecovered({
424
- accountAddress,
425
- password,
426
- walletOperation: WalletOperation.EXPORT_PRIVATE_KEY,
427
- externalServerKeyShares,
428
- errorMessage: 'External server key shares are required to export private key. No backup shares available for recovery.'
429
- });
430
- // Re-read wallet from map after recovery (it may have been updated with recovered shares)
431
- const updatedWalletProperties = this.walletMap[accountAddress];
432
- if (!updatedWalletProperties) {
433
- throw new Error('Wallet not found in walletMap after recovery');
434
- }
435
- const derivationPath = updatedWalletProperties.derivationPath;
436
- if (!derivationPath) {
437
- throw new Error('Derivation path missing in walletMap');
438
- }
439
- // Derive address type from derivation path for bitcoinConfig
440
- const addressType = getAddressTypeFromDerivationPath(derivationPath);
441
- const network = BitcoinNetwork.MAINNET; // Default to mainnet, could be derived from wallet
449
+ */ async exportPrivateKey({ walletMetadata, password = undefined, externalServerKeyShares, network = BitcoinNetwork.MAINNET }) {
450
+ const { accountAddress } = walletMetadata;
451
+ const { addressType } = this.getDerivationInfoFromMetadata(walletMetadata);
442
452
  const bitcoinConfig = {
443
453
  addressType,
444
454
  network
445
455
  };
446
- // Get key shares from wallet map if not provided (recovered from backup)
447
- const resolvedExternalServerKeyShares = externalServerKeyShares != null ? externalServerKeyShares : updatedWalletProperties.externalServerKeyShares;
448
456
  const { derivedPrivateKey } = await this.exportKey({
449
457
  accountAddress,
450
458
  chainName: this.chainName,
451
459
  password,
452
- externalServerKeyShares: resolvedExternalServerKeyShares,
453
- bitcoinConfig
460
+ externalServerKeyShares,
461
+ bitcoinConfig,
462
+ walletMetadata
454
463
  });
455
464
  if (!derivedPrivateKey) {
456
465
  throw new Error('Derived private key is undefined');
@@ -464,12 +473,19 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
464
473
  * @param keyShares - The key shares to export the private key for
465
474
  * @param derivationPath - Optional derivation path
466
475
  * @param bitcoinConfig - Bitcoin configuration (address type, network)
476
+ * @param thresholdSignatureScheme - The wallet's scheme. When given, at least that scheme's threshold of shares is required (2 for TWO_OF_TWO and TWO_OF_THREE, 3 for THREE_OF_FIVE). A TWO_OF_TWO wallet cannot be exported offline from the external server's shares alone, because it holds only one of the two
467
477
  * @returns The private key in WIF format
468
- */ async offlineExportPrivateKey({ keyShares, derivationPath, bitcoinConfig }) {
478
+ *
479
+ * `derivationPath` is the JSON-serialized index map that
480
+ * `walletMetadata.derivationPath` carries (e.g. `'{"0":44,"1":60,"2":0,"3":0,"4":0}'`
481
+ * or `'[44,60,0,0,0]'`). BIP-32 strings such as `"m/44'/60'/0'/0/0"` are rejected.
482
+ * Omit it to export without path derivation.
483
+ */ async offlineExportPrivateKey({ keyShares, derivationPath, bitcoinConfig, thresholdSignatureScheme }) {
469
484
  const { derivedPrivateKey } = await this.offlineExportKey({
470
485
  chainName: this.chainName,
471
486
  keyShares,
472
- derivationPath
487
+ derivationPath,
488
+ thresholdSignatureScheme
473
489
  });
474
490
  if (!derivedPrivateKey) {
475
491
  throw new Error('Derived private key is undefined');
@@ -486,10 +502,10 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
486
502
  * @param thresholdSignatureScheme - The threshold signature scheme to use for the wallet
487
503
  * @param password - The password to use for the wallet
488
504
  * @param onError - The function to call if an error occurs
489
- * @param backUpToClientShareService - Whether to back up the external server key shares to the client share service. By default, it is false.
505
+ * @param backUpToDynamic - Whether to back up the external server key shares to the client share service. By default, it is false.
490
506
  * @param bitcoinConfig - Bitcoin configuration (addressType, network)
491
507
  * @returns The account address, public key, raw public key, external server key shares
492
- */ async importPrivateKey({ privateKey, chainName, thresholdSignatureScheme, password = undefined, backUpToClientShareService = false, onError, bitcoinConfig }) {
508
+ */ async importPrivateKey({ privateKey, chainName, thresholdSignatureScheme, password, backUpToDynamic = false, onError, bitcoinConfig }) {
493
509
  try {
494
510
  const { addressType, network = BitcoinNetwork.MAINNET } = bitcoinConfig;
495
511
  if (!addressType) {
@@ -498,11 +514,16 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
498
514
  if (addressType !== BitcoinAddressType.NATIVE_SEGWIT && addressType !== BitcoinAddressType.TAPROOT) {
499
515
  throw new Error(`Invalid addressType: ${addressType}. Must be one of: ${BitcoinAddressType.NATIVE_SEGWIT}, ${BitcoinAddressType.TAPROOT}`);
500
516
  }
517
+ let resolvedWalletId;
518
+ let resolvedShareSetId;
501
519
  let ceremonyCeremonyCompleteResolver;
520
+ let ceremonyCeremonyCompleteRejecter;
502
521
  let ceremonyAccountAddress;
503
- const ceremonyCompletePromise = new Promise((resolve)=>{
522
+ const ceremonyCompletePromise = new Promise((resolve, reject)=>{
504
523
  ceremonyCeremonyCompleteResolver = resolve;
524
+ ceremonyCeremonyCompleteRejecter = reject;
505
525
  });
526
+ ceremonyCompletePromise.catch(()=>undefined);
506
527
  // Convert WIF to private key hex
507
528
  const formattedPrivateKey = wifToPrivateKey(privateKey, network);
508
529
  // Get public key from private key to verify address
@@ -512,38 +533,38 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
512
533
  addressType,
513
534
  network
514
535
  });
536
+ const { accountAddress: identityAddress } = this.deriveAccountAddress({
537
+ rawPublicKey: derivedPublicKey,
538
+ addressType,
539
+ network: BitcoinNetwork.MAINNET
540
+ });
541
+ const isExpectedAddress = (address)=>address === expectedAddress || address === identityAddress;
515
542
  const { rawPublicKey, externalServerKeyShares } = await this.importRawPrivateKey({
516
543
  chainName,
517
544
  privateKey: formattedPrivateKey,
518
545
  thresholdSignatureScheme,
519
546
  bitcoinConfig,
520
- onError,
521
- onCeremonyComplete: (accountAddress, walletId)=>{
522
- // Store the ceremony account address to ensure consistency
547
+ password,
548
+ backUpToDynamic,
549
+ onError: (error)=>{
550
+ ceremonyCeremonyCompleteRejecter(error);
551
+ onError == null ? void 0 : onError(error);
552
+ },
553
+ onCeremonyComplete: ({ accountAddress, walletId, shareSetId })=>{
523
554
  ceremonyAccountAddress = accountAddress;
524
- // Verify address matches
525
- if (accountAddress !== expectedAddress) {
526
- throw new Error(`Public address mismatch: derived address ${accountAddress} !== expected address ${expectedAddress}`);
555
+ resolvedWalletId = walletId;
556
+ resolvedShareSetId = shareSetId;
557
+ if (!isExpectedAddress(accountAddress)) {
558
+ const mismatch = new Error(`Public address mismatch: derived address ${accountAddress} !== expected address ${expectedAddress}`);
559
+ ceremonyCeremonyCompleteRejecter(mismatch);
560
+ throw mismatch;
527
561
  }
528
- // update wallet map
529
- const chainConfig = getMPCChainConfig(this.chainName, bitcoinConfig);
530
- this.walletMap[accountAddress] = _extends({}, this.walletMap[accountAddress], {
531
- accountAddress,
532
- walletId,
533
- chainName: this.chainName,
534
- thresholdSignatureScheme,
535
- derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map((value, index)=>[
536
- index,
537
- value
538
- ]))),
539
- externalServerKeySharesBackupInfo: getExternalServerKeyShareBackupInfo()
540
- });
541
562
  ceremonyCeremonyCompleteResolver(undefined);
542
563
  }
543
564
  });
544
565
  // Wait for the ceremony to complete before proceeding
545
566
  await ceremonyCompletePromise;
546
- if (!rawPublicKey || !externalServerKeyShares) {
567
+ if (!rawPublicKey || !externalServerKeyShares || !resolvedWalletId) {
547
568
  throw new Error('Error creating wallet account');
548
569
  }
549
570
  // Use the ceremony account address if available, otherwise derive it from raw public key
@@ -552,22 +573,32 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
552
573
  addressType,
553
574
  network
554
575
  }).accountAddress;
555
- if (accountAddress !== expectedAddress) {
576
+ if (!isExpectedAddress(accountAddress)) {
556
577
  throw new Error(`Public address mismatch: derived address ${accountAddress} !== expected address ${expectedAddress}`);
557
578
  }
558
- const externalKeySharesWithBackupStatus = await this.storeEncryptedBackupByWalletWithRetry({
579
+ const walletMetadata = this.buildWalletMetadata({
580
+ walletId: resolvedWalletId,
581
+ accountAddress,
582
+ thresholdSignatureScheme,
583
+ addressType,
584
+ bitcoinConfig,
585
+ shareSetId: resolvedShareSetId
586
+ });
587
+ const { keySharesWithBackupStatus, backupInfo } = await this.storeEncryptedBackupByWalletWithRetry({
559
588
  accountAddress,
560
589
  externalServerKeyShares,
561
590
  password,
562
- backUpToClientShareService
591
+ backUpToDynamic,
592
+ walletMetadata
563
593
  });
594
+ walletMetadata.externalServerKeySharesBackupInfo = backupInfo;
564
595
  const publicKeyHex = extractPublicKeyHex(rawPublicKey);
565
596
  return {
566
- accountAddress,
597
+ walletMetadata,
567
598
  rawPublicKey,
568
599
  publicKeyHex,
569
600
  externalServerKeyShares,
570
- externalKeySharesWithBackupStatus
601
+ externalKeySharesWithBackupStatus: keySharesWithBackupStatus
571
602
  };
572
603
  } catch (error) {
573
604
  logError({
@@ -590,13 +621,14 @@ class DynamicBtcWalletClient extends DynamicWalletClient {
590
621
  });
591
622
  return btcWallets;
592
623
  }
593
- constructor({ environmentId, baseApiUrl, baseMPCRelayApiUrl, enableMPCAccelerator, logger, debug }){
624
+ constructor({ environmentId, baseApiUrl, baseMPCRelayApiUrl, enableMPCAccelerator, logger, requestSigning, debug }){
594
625
  super({
595
626
  environmentId,
596
627
  baseApiUrl,
597
628
  baseMPCRelayApiUrl,
598
629
  enableMPCAccelerator,
599
630
  logger,
631
+ requestSigning,
600
632
  debug
601
633
  }), this.chainName = 'BTC';
602
634
  }