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