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