@onekeyfe/hwk-ledger-adapter 1.2.8-alpha.11 → 1.2.8-alpha.110
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/dist/index.d.mts +92 -52
- package/dist/index.d.ts +92 -52
- package/dist/index.js +1950 -965
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1889 -879
- package/dist/index.mjs.map +1 -1
- package/package.json +14 -11
package/dist/index.mjs
CHANGED
|
@@ -6,30 +6,43 @@ import {
|
|
|
6
6
|
DeviceJobQueue,
|
|
7
7
|
EConnectorInteraction,
|
|
8
8
|
HardwareErrorCode as HardwareErrorCode3,
|
|
9
|
+
OperationRegistry,
|
|
10
|
+
SDK,
|
|
9
11
|
TypedEventEmitter,
|
|
10
12
|
UI_REQUEST,
|
|
11
13
|
UI_REQUEST_PREEMPTED_TAG,
|
|
12
14
|
UiRequestRegistry,
|
|
15
|
+
canReplayHardwareMethodAfterTransportFailure,
|
|
13
16
|
createHwkError,
|
|
14
17
|
deriveDeviceFingerprint,
|
|
18
|
+
emitDeviceBindingStatus,
|
|
15
19
|
failure as failure2,
|
|
20
|
+
isHardwareOperationId,
|
|
21
|
+
isHwkRecoveryHint,
|
|
22
|
+
operationMayHaveCompletedParams,
|
|
23
|
+
pickConnectionContext,
|
|
16
24
|
rehydrateConnectorError,
|
|
17
|
-
|
|
25
|
+
requestBleDeviceSelection,
|
|
26
|
+
requestSaveDeviceBinding,
|
|
27
|
+
success as success2,
|
|
28
|
+
toPhysicalDeviceSearchTarget
|
|
18
29
|
} from "@onekeyfe/hwk-adapter-core";
|
|
19
30
|
|
|
20
31
|
// src/errors.ts
|
|
21
|
-
import {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
function ledgerFailure(code, error, appName, tag, params) {
|
|
32
|
+
import {
|
|
33
|
+
HardwareErrorCode,
|
|
34
|
+
defaultOriginForCode,
|
|
35
|
+
defaultRecoveryForCode,
|
|
36
|
+
enrichErrorMessage
|
|
37
|
+
} from "@onekeyfe/hwk-adapter-core";
|
|
38
|
+
function ledgerFailure(code, error, appName, tag, params, origin, recovery) {
|
|
29
39
|
const payload = { error, code };
|
|
30
40
|
if (appName !== void 0) payload.appName = appName;
|
|
31
41
|
if (tag !== void 0) payload._tag = tag;
|
|
32
42
|
if (params !== void 0) payload.params = params;
|
|
43
|
+
const resolvedOrigin = origin ?? defaultOriginForCode(code);
|
|
44
|
+
if (resolvedOrigin !== void 0) payload.origin = resolvedOrigin;
|
|
45
|
+
payload.recovery = recovery ?? defaultRecoveryForCode(code);
|
|
33
46
|
return { success: false, payload };
|
|
34
47
|
}
|
|
35
48
|
var LOCKED_ERROR_CODES = /* @__PURE__ */ new Set(["5515", "21781", "6982", "27010", "5303", "21251"]);
|
|
@@ -170,7 +183,10 @@ var ERROR_TAG = {
|
|
|
170
183
|
UnknownDevice: "UnknownDeviceError",
|
|
171
184
|
DeviceSessionRefresher: "DeviceSessionRefresherError",
|
|
172
185
|
DeviceNotInitialized: "DeviceNotInitializedError",
|
|
173
|
-
|
|
186
|
+
// DMK class OpeningConnectionError carries `_tag` "ConnectionOpeningError"; both
|
|
187
|
+
// spellings are kept so a DMK release that aligns them still classifies.
|
|
188
|
+
OpeningConnection: "ConnectionOpeningError",
|
|
189
|
+
OpeningConnectionLegacy: "OpeningConnectionError",
|
|
174
190
|
DeviceDisconnectedBeforeSendingApdu: "DeviceDisconnectedBeforeSendingApdu",
|
|
175
191
|
DeviceDisconnectedWhileSending: "DeviceDisconnectedWhileSendingError",
|
|
176
192
|
Disconnect: "DisconnectError",
|
|
@@ -183,7 +199,16 @@ var ERROR_TAG = {
|
|
|
183
199
|
// DMK remote-network failures (manager-api HTTP / secure-channel WS).
|
|
184
200
|
WebSocketConnection: "WebSocketConnectionError",
|
|
185
201
|
HttpFetch: "FetchError",
|
|
186
|
-
|
|
202
|
+
NetworkDA: "NetworkDAError",
|
|
203
|
+
InvalidFirmwareMetadataResponse: "InvalidGetFirmwareMetadataResponseError",
|
|
204
|
+
ApplicationsMetadataTask: "GetApplicationsMetadataTaskError",
|
|
205
|
+
// DMK OS device actions. SecureChannelError is what mapInstallDAErrors() leaves
|
|
206
|
+
// after splitting out device answers, i.e. the relay itself broke.
|
|
207
|
+
SecureChannel: "SecureChannelError",
|
|
208
|
+
RefusedByUserDA: "RefusedByUserDAError",
|
|
209
|
+
AppAlreadyInstalledDA: "AppAlreadyInstalledDAError",
|
|
210
|
+
OutOfMemoryDA: "OutOfMemoryDAError",
|
|
211
|
+
DeviceNotOnboarded: "DeviceNotOnboardedError"
|
|
187
212
|
};
|
|
188
213
|
function isDeviceLockedError(err) {
|
|
189
214
|
if (!err || typeof err !== "object") return false;
|
|
@@ -213,7 +238,6 @@ function isBlePairingFailureError(err) {
|
|
|
213
238
|
return false;
|
|
214
239
|
}
|
|
215
240
|
var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
|
|
216
|
-
ERROR_TAG.DeviceLocked,
|
|
217
241
|
ERROR_TAG.DeviceNotAdvertising,
|
|
218
242
|
ERROR_TAG.BlePairingTimeout,
|
|
219
243
|
ERROR_TAG.BleGattBondingFailed,
|
|
@@ -225,6 +249,7 @@ var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
|
|
|
225
249
|
ERROR_TAG.DeviceSessionRefresher,
|
|
226
250
|
ERROR_TAG.DeviceNotInitialized,
|
|
227
251
|
ERROR_TAG.OpeningConnection,
|
|
252
|
+
ERROR_TAG.OpeningConnectionLegacy,
|
|
228
253
|
ERROR_TAG.DeviceDisconnectedBeforeSendingApdu,
|
|
229
254
|
ERROR_TAG.DeviceDisconnectedWhileSending,
|
|
230
255
|
ERROR_TAG.Disconnect,
|
|
@@ -239,7 +264,10 @@ var DEVICE_NOT_FOUND_TAGS = /* @__PURE__ */ new Set([
|
|
|
239
264
|
// Map to DeviceNotFound so non-BLE-direct paths get a sensible error code.
|
|
240
265
|
ERROR_TAG.DeviceNotInDiscoveryCache
|
|
241
266
|
]);
|
|
242
|
-
var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
|
|
267
|
+
var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
|
|
268
|
+
ERROR_TAG.OpeningConnection,
|
|
269
|
+
ERROR_TAG.OpeningConnectionLegacy
|
|
270
|
+
]);
|
|
243
271
|
var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
|
|
244
272
|
ERROR_TAG.DeviceNotRecognized,
|
|
245
273
|
ERROR_TAG.DeviceSessionNotFound,
|
|
@@ -251,17 +279,18 @@ var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
|
|
|
251
279
|
ERROR_TAG.WebHIDDisconnect
|
|
252
280
|
]);
|
|
253
281
|
function isConnectionLevelError(err) {
|
|
254
|
-
|
|
255
|
-
const tag = err._tag;
|
|
256
|
-
if (tag && CONNECTION_LEVEL_TAGS.has(tag)) return true;
|
|
257
|
-
const e = err;
|
|
258
|
-
if (e.originalError != null && isConnectionLevelError(e.originalError)) return true;
|
|
259
|
-
if (e.error != null && e._tag && isConnectionLevelError(e.error)) return true;
|
|
260
|
-
return false;
|
|
282
|
+
return hasErrorTag(err, CONNECTION_LEVEL_TAGS);
|
|
261
283
|
}
|
|
262
284
|
function isKnownConnectionTag(tag) {
|
|
263
285
|
return typeof tag === "string" && CONNECTION_LEVEL_TAGS.has(tag);
|
|
264
286
|
}
|
|
287
|
+
var CONNECTION_OPENING_TAGS = /* @__PURE__ */ new Set([
|
|
288
|
+
ERROR_TAG.OpeningConnection,
|
|
289
|
+
ERROR_TAG.OpeningConnectionLegacy
|
|
290
|
+
]);
|
|
291
|
+
function isConnectionOpeningTag(tag) {
|
|
292
|
+
return typeof tag === "string" && CONNECTION_OPENING_TAGS.has(tag);
|
|
293
|
+
}
|
|
265
294
|
function hasStatusCode(err, codeSet) {
|
|
266
295
|
if (!err || typeof err !== "object") return false;
|
|
267
296
|
const e = err;
|
|
@@ -297,28 +326,28 @@ function hasInvalidArgumentCode(err) {
|
|
|
297
326
|
if (e.error != null && e._tag && hasInvalidArgumentCode(e.error)) return true;
|
|
298
327
|
return false;
|
|
299
328
|
}
|
|
300
|
-
function
|
|
329
|
+
function hasErrorTag(err, tags) {
|
|
301
330
|
if (!err || typeof err !== "object") return false;
|
|
302
|
-
const tag = err._tag;
|
|
303
|
-
if (tag && DEVICE_NOT_FOUND_TAGS.has(tag)) return true;
|
|
304
331
|
const e = err;
|
|
305
|
-
if (e.
|
|
306
|
-
if (e.
|
|
332
|
+
if (typeof e._tag === "string" && tags.has(e._tag)) return true;
|
|
333
|
+
if (e.originalError != null && hasErrorTag(e.originalError, tags)) return true;
|
|
334
|
+
if (e.error != null && e._tag && hasErrorTag(e.error, tags)) return true;
|
|
307
335
|
return false;
|
|
308
336
|
}
|
|
337
|
+
function isDeviceNotFoundError(err) {
|
|
338
|
+
return hasErrorTag(err, DEVICE_NOT_FOUND_TAGS);
|
|
339
|
+
}
|
|
309
340
|
function isDeviceBusyError(err) {
|
|
310
|
-
|
|
311
|
-
const tag = err._tag;
|
|
312
|
-
if (tag && DEVICE_BUSY_TAGS.has(tag)) return true;
|
|
313
|
-
const e = err;
|
|
314
|
-
if (e.originalError != null && isDeviceBusyError(e.originalError)) return true;
|
|
315
|
-
if (e.error != null && e._tag && isDeviceBusyError(e.error)) return true;
|
|
316
|
-
return false;
|
|
341
|
+
return hasErrorTag(err, DEVICE_BUSY_TAGS);
|
|
317
342
|
}
|
|
343
|
+
var USER_REJECTED_TAGS = /* @__PURE__ */ new Set([
|
|
344
|
+
ERROR_TAG.UserRefusedOnDevice,
|
|
345
|
+
ERROR_TAG.RefusedByUserDA
|
|
346
|
+
]);
|
|
318
347
|
function isUserRejectedError(err) {
|
|
319
348
|
if (!err || typeof err !== "object") return false;
|
|
320
349
|
const e = err;
|
|
321
|
-
if (
|
|
350
|
+
if (hasErrorTag(err, USER_REJECTED_TAGS)) return true;
|
|
322
351
|
if (typeof e.message === "string" && /denied|rejected|refused/i.test(e.message)) return true;
|
|
323
352
|
if (hasStatusCode(err, USER_REJECTED_CODES)) return true;
|
|
324
353
|
return false;
|
|
@@ -349,15 +378,33 @@ function isAppNotInstalledError(err) {
|
|
|
349
378
|
if (hasStatusCode(err, APP_NOT_INSTALLED_CODES)) return true;
|
|
350
379
|
return false;
|
|
351
380
|
}
|
|
381
|
+
var OUT_OF_MEMORY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OutOfMemoryDA]);
|
|
352
382
|
function isOutOfMemoryError(err) {
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
383
|
+
return hasErrorTag(err, OUT_OF_MEMORY_TAGS);
|
|
384
|
+
}
|
|
385
|
+
var APP_ALREADY_INSTALLED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.AppAlreadyInstalledDA]);
|
|
386
|
+
function isAppAlreadyInstalledError(err) {
|
|
387
|
+
return hasErrorTag(err, APP_ALREADY_INSTALLED_TAGS);
|
|
388
|
+
}
|
|
389
|
+
var DEVICE_NOT_ONBOARDED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.DeviceNotOnboarded]);
|
|
390
|
+
function isDeviceNotOnboardedError(err) {
|
|
391
|
+
return hasErrorTag(err, DEVICE_NOT_ONBOARDED_TAGS);
|
|
392
|
+
}
|
|
393
|
+
var FIRMWARE_METADATA_TAGS = /* @__PURE__ */ new Set([
|
|
394
|
+
ERROR_TAG.InvalidFirmwareMetadataResponse,
|
|
395
|
+
ERROR_TAG.ApplicationsMetadataTask
|
|
396
|
+
]);
|
|
397
|
+
function isFirmwareMetadataError(err) {
|
|
398
|
+
return hasErrorTag(err, FIRMWARE_METADATA_TAGS);
|
|
399
|
+
}
|
|
400
|
+
var SECURE_CHANNEL_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.SecureChannel]);
|
|
401
|
+
function isSecureChannelError(err) {
|
|
402
|
+
return hasErrorTag(err, SECURE_CHANNEL_TAGS);
|
|
356
403
|
}
|
|
357
404
|
var NETWORK_ERROR_TAGS = /* @__PURE__ */ new Set([
|
|
358
405
|
ERROR_TAG.WebSocketConnection,
|
|
359
406
|
ERROR_TAG.HttpFetch,
|
|
360
|
-
ERROR_TAG.
|
|
407
|
+
ERROR_TAG.NetworkDA
|
|
361
408
|
]);
|
|
362
409
|
function isNetworkError(err) {
|
|
363
410
|
if (!err || typeof err !== "object") return false;
|
|
@@ -407,23 +454,34 @@ function isTransportStuck(err) {
|
|
|
407
454
|
function isStuckAppStateError(err) {
|
|
408
455
|
return isAppStuckByApdu(err) || isTransportStuck(err);
|
|
409
456
|
}
|
|
457
|
+
var DMK_PLACEHOLDER_MESSAGE = "Unknown error.";
|
|
458
|
+
function nestedErrorMessage(nested) {
|
|
459
|
+
if (!nested || typeof nested !== "object") return void 0;
|
|
460
|
+
const { message } = nested;
|
|
461
|
+
if (typeof message !== "string") return void 0;
|
|
462
|
+
const trimmed = message.trim();
|
|
463
|
+
if (!trimmed || trimmed === DMK_PLACEHOLDER_MESSAGE) return void 0;
|
|
464
|
+
return message;
|
|
465
|
+
}
|
|
410
466
|
function mapLedgerError(err, opts) {
|
|
411
467
|
let originalMessage = "Unknown Ledger error";
|
|
412
468
|
if (err instanceof Error) {
|
|
413
469
|
originalMessage = err.message;
|
|
414
470
|
} else if (err && typeof err === "object") {
|
|
415
471
|
const e = err;
|
|
416
|
-
originalMessage = String(
|
|
472
|
+
originalMessage = String(
|
|
473
|
+
e.message ?? nestedErrorMessage(e.originalError) ?? e._tag ?? e.type ?? JSON.stringify(err)
|
|
474
|
+
);
|
|
417
475
|
}
|
|
418
476
|
let code;
|
|
419
477
|
if (isDeviceLockedError(err)) {
|
|
420
478
|
code = HardwareErrorCode.DeviceLocked;
|
|
421
479
|
} else if (isDeviceNotAdvertisingError(err) || isDeviceNotFoundError(err)) {
|
|
422
480
|
code = HardwareErrorCode.DeviceNotFound;
|
|
423
|
-
} else if (isDeviceBusyError(err)) {
|
|
424
|
-
code = HardwareErrorCode.DeviceBusy;
|
|
425
481
|
} else if (isBlePairingFailureError(err)) {
|
|
426
482
|
code = HardwareErrorCode.BlePairingTimeout;
|
|
483
|
+
} else if (isDeviceBusyError(err)) {
|
|
484
|
+
code = HardwareErrorCode.DeviceBusy;
|
|
427
485
|
} else if (isUserAbortedError(err)) {
|
|
428
486
|
code = HardwareErrorCode.UserAborted;
|
|
429
487
|
} else if (isUserRejectedError(err)) {
|
|
@@ -432,10 +490,18 @@ function mapLedgerError(err, opts) {
|
|
|
432
490
|
code = HardwareErrorCode.WrongApp;
|
|
433
491
|
} else if (isAppNotInstalledError(err)) {
|
|
434
492
|
code = HardwareErrorCode.AppNotInstalled;
|
|
493
|
+
} else if (isAppAlreadyInstalledError(err)) {
|
|
494
|
+
code = HardwareErrorCode.AppAlreadyInstalled;
|
|
435
495
|
} else if (isOutOfMemoryError(err)) {
|
|
436
496
|
code = HardwareErrorCode.DeviceOutOfMemory;
|
|
497
|
+
} else if (isDeviceNotOnboardedError(err)) {
|
|
498
|
+
code = HardwareErrorCode.DeviceNotInitialized;
|
|
499
|
+
} else if (isFirmwareMetadataError(err)) {
|
|
500
|
+
code = HardwareErrorCode.LedgerFirmwareMetadataError;
|
|
437
501
|
} else if (isNetworkError(err)) {
|
|
438
502
|
code = HardwareErrorCode.NetworkError;
|
|
503
|
+
} else if (isSecureChannelError(err)) {
|
|
504
|
+
code = HardwareErrorCode.LedgerSecureChannelError;
|
|
439
505
|
} else if (isDeviceDisconnectedError(err)) {
|
|
440
506
|
code = HardwareErrorCode.DeviceDisconnected;
|
|
441
507
|
} else if (isTimeoutError(err)) {
|
|
@@ -448,11 +514,35 @@ function mapLedgerError(err, opts) {
|
|
|
448
514
|
}
|
|
449
515
|
const errAppName = err && typeof err === "object" ? err.appName : void 0;
|
|
450
516
|
const appName = errAppName ?? opts?.defaultAppName;
|
|
451
|
-
return {
|
|
517
|
+
return {
|
|
518
|
+
code,
|
|
519
|
+
message: enrichErrorMessage(code, originalMessage),
|
|
520
|
+
origin: defaultOriginForCode(code),
|
|
521
|
+
appName
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// src/utils/queueKey.ts
|
|
526
|
+
var LEDGER_DEFAULT_QUEUE_KEY = "__ledger_default__";
|
|
527
|
+
function ledgerQueueKey({
|
|
528
|
+
operationId,
|
|
529
|
+
connectId
|
|
530
|
+
}) {
|
|
531
|
+
return (operationId ?? connectId) || LEDGER_DEFAULT_QUEUE_KEY;
|
|
452
532
|
}
|
|
453
533
|
|
|
454
534
|
// src/adapter/methods/allNetworkGetAddress.ts
|
|
455
|
-
import {
|
|
535
|
+
import {
|
|
536
|
+
HardwareErrorCode as HardwareErrorCode2,
|
|
537
|
+
buildAllNetworkCancelledFailure,
|
|
538
|
+
failure,
|
|
539
|
+
isConnectionLost,
|
|
540
|
+
isUserRefusal,
|
|
541
|
+
isWalletSafetyFailure,
|
|
542
|
+
resolveHardwareOperationTarget,
|
|
543
|
+
runAllNetworkGetAddress,
|
|
544
|
+
success
|
|
545
|
+
} from "@onekeyfe/hwk-adapter-core";
|
|
456
546
|
|
|
457
547
|
// src/utils/sdkEventBus.ts
|
|
458
548
|
var listeners = /* @__PURE__ */ new Set();
|
|
@@ -499,6 +589,32 @@ function debugError(...args) {
|
|
|
499
589
|
emitLog("error", ...args);
|
|
500
590
|
}
|
|
501
591
|
|
|
592
|
+
// src/utils/logSummary.ts
|
|
593
|
+
import { summarizeForLog as summarizeForLogCore } from "@onekeyfe/hwk-adapter-core";
|
|
594
|
+
import { Psbt, Transaction } from "bitcoinjs-lib";
|
|
595
|
+
var HEX_RE = /^(0x)?[0-9a-fA-F]+$/;
|
|
596
|
+
var BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
597
|
+
function parsePsbt(input) {
|
|
598
|
+
if (typeof input !== "string") return Psbt.fromBuffer(input);
|
|
599
|
+
if (HEX_RE.test(input)) return Psbt.fromHex(input.replace(/^0x/i, ""));
|
|
600
|
+
if (BASE64_RE.test(input)) return Psbt.fromBase64(input);
|
|
601
|
+
return void 0;
|
|
602
|
+
}
|
|
603
|
+
var describePsbtForLog = (key, value) => {
|
|
604
|
+
if (key !== "psbt") return void 0;
|
|
605
|
+
try {
|
|
606
|
+
const psbt = parsePsbt(value);
|
|
607
|
+
if (!psbt) return void 0;
|
|
608
|
+
const unsignedTx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());
|
|
609
|
+
return `inputs=${psbt.inputCount} outputs=${psbt.txOutputs.length} txid=${unsignedTx.getId()}`;
|
|
610
|
+
} catch {
|
|
611
|
+
return void 0;
|
|
612
|
+
}
|
|
613
|
+
};
|
|
614
|
+
function summarizeForLog(value, options = {}) {
|
|
615
|
+
return summarizeForLogCore(value, { ...options, describePayload: describePsbtForLog });
|
|
616
|
+
}
|
|
617
|
+
|
|
502
618
|
// src/adapter/methods/allNetworkGetAddress.ts
|
|
503
619
|
var LEDGER_BTC_NETWORK_COIN_MAP = {
|
|
504
620
|
tbtc: "Testnet",
|
|
@@ -509,57 +625,105 @@ var LEDGER_BTC_NETWORK_COIN_MAP = {
|
|
|
509
625
|
var LEDGER_UNSUPPORTED_ALLNETWORK_NETWORKS = /* @__PURE__ */ new Set(["doge", "dogecoin"]);
|
|
510
626
|
function createAllNetworkGetAddress({
|
|
511
627
|
callChain,
|
|
512
|
-
getChainFingerprint
|
|
628
|
+
getChainFingerprint,
|
|
629
|
+
retainOperation,
|
|
630
|
+
errorToFailure,
|
|
631
|
+
createCancelScope,
|
|
632
|
+
releaseBundle
|
|
513
633
|
}) {
|
|
514
634
|
return async function allNetworkGetAddress(connectId, _deviceId, params) {
|
|
515
|
-
debugLog("[LedgerAdapter][REQ]", {
|
|
516
|
-
|
|
635
|
+
debugLog("[LedgerAdapter][REQ]", {
|
|
636
|
+
method: "allNetworkGetAddress",
|
|
637
|
+
connectId,
|
|
638
|
+
itemCount: params.bundle.length
|
|
639
|
+
});
|
|
640
|
+
const target = resolveHardwareOperationTarget(connectId, params.operationId, "ledger");
|
|
641
|
+
if (!target.success) return target;
|
|
642
|
+
const effectiveTargetId = target.payload.targetId ?? "";
|
|
643
|
+
let releaseOperationRetention;
|
|
644
|
+
try {
|
|
645
|
+
releaseOperationRetention = target.payload.operationId ? retainOperation(target.payload.operationId) : void 0;
|
|
646
|
+
} catch (error) {
|
|
647
|
+
return errorToFailure(error);
|
|
648
|
+
}
|
|
649
|
+
const cancelScope = createCancelScope(
|
|
650
|
+
ledgerQueueKey({ operationId: target.payload.operationId, connectId: effectiveTargetId })
|
|
651
|
+
);
|
|
652
|
+
const installContext = {
|
|
653
|
+
walletCheck: { expected: params.bundle.some((item) => Boolean(getItemDeviceId(item))) }
|
|
654
|
+
};
|
|
517
655
|
const commonParams = {
|
|
518
|
-
autoInstallApp: params.autoInstallApp
|
|
656
|
+
autoInstallApp: params.autoInstallApp,
|
|
657
|
+
operationId: target.payload.operationId,
|
|
658
|
+
knownConnections: params.knownConnections,
|
|
659
|
+
extra: params.extra,
|
|
660
|
+
allowDeviceSelection: params.allowDeviceSelection,
|
|
661
|
+
supportedTransports: params.supportedTransports
|
|
519
662
|
};
|
|
520
663
|
const chainFingerprints = /* @__PURE__ */ new Map();
|
|
521
|
-
const
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
664
|
+
const order = params.bundle.map((_item, index) => index).sort(
|
|
665
|
+
(a, b) => Number(Boolean(getItemDeviceId(params.bundle[b]))) - Number(Boolean(getItemDeviceId(params.bundle[a])))
|
|
666
|
+
);
|
|
667
|
+
try {
|
|
668
|
+
const ordered = await runAllNetworkGetAddress({
|
|
669
|
+
connectId: effectiveTargetId,
|
|
670
|
+
deviceId: _deviceId,
|
|
671
|
+
params: { ...params, bundle: order.map((index) => params.bundle[index]) },
|
|
672
|
+
normalizeItem: normalizeLedgerAllNetworkItem,
|
|
673
|
+
buildUnsupportedNetworkResponse: (item) => isUnsupportedLedgerAllNetworkNetwork(item) ? buildUnsupportedNetworkResponse(item) : void 0,
|
|
674
|
+
callItem: async ({ method, chain, item }) => {
|
|
675
|
+
if (cancelScope.signal.aborted)
|
|
676
|
+
return buildAllNetworkCancelledFailure(cancelScope.signal);
|
|
677
|
+
const itemDeviceId = getItemDeviceId(item) ?? chainFingerprints.get(chain) ?? "";
|
|
678
|
+
return callAllNetworkMethod(
|
|
679
|
+
callChain,
|
|
680
|
+
effectiveTargetId,
|
|
681
|
+
itemDeviceId,
|
|
682
|
+
method,
|
|
683
|
+
item,
|
|
684
|
+
commonParams,
|
|
685
|
+
installContext
|
|
686
|
+
);
|
|
687
|
+
},
|
|
688
|
+
attachIdentity: async ({ item, chain, payload }) => attachLedgerIdentity(
|
|
689
|
+
getChainFingerprint,
|
|
690
|
+
effectiveTargetId,
|
|
534
691
|
item,
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
)
|
|
692
|
+
chain,
|
|
693
|
+
payload,
|
|
694
|
+
chainFingerprints,
|
|
695
|
+
installContext,
|
|
696
|
+
cancelScope.signal
|
|
697
|
+
),
|
|
698
|
+
shouldAbortBundle: isTopLevelAllNetworkFailure,
|
|
699
|
+
buildTopLevelFailure: (response) => {
|
|
700
|
+
const code = response.payload?.code ?? HardwareErrorCode2.DeviceMismatch;
|
|
701
|
+
return failure(
|
|
702
|
+
code,
|
|
703
|
+
response.payload?.error ?? "All-network get-address aborted",
|
|
704
|
+
response.payload?.params
|
|
705
|
+
);
|
|
706
|
+
}
|
|
707
|
+
});
|
|
708
|
+
let result = ordered;
|
|
709
|
+
if (ordered.success) {
|
|
710
|
+
const responses = [];
|
|
711
|
+
ordered.payload.forEach((response, position) => {
|
|
712
|
+
responses[order[position]] = response;
|
|
713
|
+
});
|
|
714
|
+
result = success(responses);
|
|
555
715
|
}
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
716
|
+
debugLog("[LedgerAdapter][RES]", {
|
|
717
|
+
method: "allNetworkGetAddress",
|
|
718
|
+
success: result.success,
|
|
719
|
+
payload: summarizeForLog(result, { method: "allNetworkGetAddress", role: "result" })
|
|
720
|
+
});
|
|
721
|
+
return result;
|
|
722
|
+
} finally {
|
|
723
|
+
await releaseBundle(installContext, cancelScope.signal).catch(() => void 0);
|
|
724
|
+
cancelScope.release();
|
|
725
|
+
releaseOperationRetention?.();
|
|
726
|
+
}
|
|
563
727
|
};
|
|
564
728
|
}
|
|
565
729
|
function isTopLevelAllNetworkFailure(response) {
|
|
@@ -567,7 +731,7 @@ function isTopLevelAllNetworkFailure(response) {
|
|
|
567
731
|
return false;
|
|
568
732
|
}
|
|
569
733
|
const code = response.payload?.code;
|
|
570
|
-
return code
|
|
734
|
+
return isWalletSafetyFailure(code) || isUserRefusal(code) || isConnectionLost(code);
|
|
571
735
|
}
|
|
572
736
|
function getItemDeviceId(item) {
|
|
573
737
|
const { deviceId } = item;
|
|
@@ -597,8 +761,18 @@ function normalizeLedgerAllNetworkItem(method, item) {
|
|
|
597
761
|
const coin = LEDGER_BTC_NETWORK_COIN_MAP[item.network];
|
|
598
762
|
return coin ? { ...item, coin } : item;
|
|
599
763
|
}
|
|
600
|
-
async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints) {
|
|
601
|
-
const
|
|
764
|
+
async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints, context, cancelSignal) {
|
|
765
|
+
const knownFingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || "";
|
|
766
|
+
if (!knownFingerprint && cancelSignal.aborted) {
|
|
767
|
+
const cancelled = buildAllNetworkCancelledFailure(cancelSignal);
|
|
768
|
+
return { ...item, success: false, payload: cancelled.payload };
|
|
769
|
+
}
|
|
770
|
+
const fingerprint = knownFingerprint || await bootstrapChainFingerprint(
|
|
771
|
+
getChainFingerprint,
|
|
772
|
+
context.connection?.connectId ?? connectId,
|
|
773
|
+
chain,
|
|
774
|
+
context
|
|
775
|
+
);
|
|
602
776
|
if (!fingerprint) {
|
|
603
777
|
return buildFingerprintBootstrapFailure(item, chain);
|
|
604
778
|
}
|
|
@@ -619,8 +793,8 @@ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain,
|
|
|
619
793
|
}
|
|
620
794
|
};
|
|
621
795
|
}
|
|
622
|
-
async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain) {
|
|
623
|
-
const response = await getChainFingerprint(connectId, chain);
|
|
796
|
+
async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain, context) {
|
|
797
|
+
const response = await getChainFingerprint(connectId, chain, context);
|
|
624
798
|
return response.success ? response.payload : "";
|
|
625
799
|
}
|
|
626
800
|
function buildFingerprintBootstrapFailure(item, chain) {
|
|
@@ -713,6 +887,9 @@ function isLedgerBleDescriptor(connectionType, descriptor) {
|
|
|
713
887
|
function formatDeviceMismatchError(expected, actual) {
|
|
714
888
|
return `Wrong device: expected ${expected}, got ${actual}`;
|
|
715
889
|
}
|
|
890
|
+
function isLostConnectionError(err) {
|
|
891
|
+
return isDeviceDisconnectedError(err) || isDeviceNotAdvertisingError(err) || isTimeoutError(err) || isConnectionLevelError(err);
|
|
892
|
+
}
|
|
716
893
|
var BTC_HIGH_INDEX_THRESHOLD = 100;
|
|
717
894
|
function btcAccountIndexFromPath(path) {
|
|
718
895
|
const segments = path.replace(/^m\//, "").split("/");
|
|
@@ -724,9 +901,35 @@ function btcAccountIndexFromPath(path) {
|
|
|
724
901
|
var _LedgerAdapter = class _LedgerAdapter {
|
|
725
902
|
constructor(connector, options) {
|
|
726
903
|
this.vendor = "ledger";
|
|
904
|
+
// Cancel frees the DMK action and its intent-queue slot, but cannot retract a
|
|
905
|
+
// confirmation screen the device is already showing.
|
|
906
|
+
this.cancelCapability = "stops-waiting";
|
|
727
907
|
this.emitter = new TypedEventEmitter();
|
|
908
|
+
this._operations = new OperationRegistry({
|
|
909
|
+
vendor: "ledger",
|
|
910
|
+
onEnded: (operation, reason) => {
|
|
911
|
+
this._discardPendingBinding(this._pendingOperationBindings.get(operation.operationId));
|
|
912
|
+
this._pendingOperationBindings.delete(operation.operationId);
|
|
913
|
+
this.emitter.emit(SDK.OPERATION_ENDED, {
|
|
914
|
+
type: SDK.OPERATION_ENDED,
|
|
915
|
+
payload: { operationId: operation.operationId, reason }
|
|
916
|
+
});
|
|
917
|
+
if (reason === "timeout" && !this._bareCallMayUseConnection(operation)) {
|
|
918
|
+
void this._releaseOperationConnection(operation);
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
});
|
|
728
922
|
this._discoveredDevices = /* @__PURE__ */ new Map();
|
|
729
923
|
this._sessions = /* @__PURE__ */ new Map();
|
|
924
|
+
// An operation's BLE pick is saved by its first call that gets past the wallet check.
|
|
925
|
+
this._pendingOperationBindings = /* @__PURE__ */ new Map();
|
|
926
|
+
// A one-shot call's unchecked BLE pick, by connectId. It outlives the call only
|
|
927
|
+
// through an unlock retry; any other failure drops it with its session.
|
|
928
|
+
this._pendingPickBindings = /* @__PURE__ */ new Map();
|
|
929
|
+
// Transport each session was opened on, by sessionId. The adapter-wide
|
|
930
|
+
// `_activeConnectionType` moves with every discovery and can go stale.
|
|
931
|
+
this._sessionTransports = /* @__PURE__ */ new Map();
|
|
932
|
+
this._selectedBleReconnectTargets = /* @__PURE__ */ new Map();
|
|
730
933
|
this._uiRegistry = new UiRequestRegistry();
|
|
731
934
|
// BTC App rejects account index >= 100 unless display=true. Cached per
|
|
732
935
|
// adapter instance: first 100+ path asks the user once via UI request,
|
|
@@ -740,21 +943,36 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
740
943
|
this._deviceAuthenticityQueueTail = Promise.resolve();
|
|
741
944
|
// Shared across concurrent callers — only `cancel()` aborts.
|
|
742
945
|
this._doConnectAbortController = null;
|
|
946
|
+
this._unsettledConnectorOperations = /* @__PURE__ */ new Map();
|
|
947
|
+
this._connectorIdleWaiters = /* @__PURE__ */ new Set();
|
|
948
|
+
this._resetPromise = null;
|
|
949
|
+
this._stateGeneration = 0;
|
|
950
|
+
this._connectorTeardownTail = Promise.resolve();
|
|
951
|
+
this._pendingConnectorTeardowns = 0;
|
|
952
|
+
this._activeOperationJobs = /* @__PURE__ */ new Set();
|
|
953
|
+
this._pendingOperationDisconnects = /* @__PURE__ */ new Set();
|
|
743
954
|
this._installProgressLastEmittedValue = -Infinity;
|
|
744
955
|
this.allNetworkGetAddress = createAllNetworkGetAddress({
|
|
745
956
|
callChain: this.callChain.bind(this),
|
|
746
|
-
getChainFingerprint: (connectId, chain) =>
|
|
957
|
+
getChainFingerprint: async (connectId, chain, context) => {
|
|
958
|
+
try {
|
|
959
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
960
|
+
chain,
|
|
961
|
+
(method, params) => this.connectorCall(connectId, method, params, void 0, void 0, void 0, context)
|
|
962
|
+
);
|
|
963
|
+
return success2(fingerprint);
|
|
964
|
+
} catch (error) {
|
|
965
|
+
return this.errorToFailure(error);
|
|
966
|
+
}
|
|
967
|
+
},
|
|
968
|
+
retainOperation: (operationId) => this._operations.retain(operationId),
|
|
969
|
+
errorToFailure: (error) => this.errorToFailure(error),
|
|
970
|
+
createCancelScope: (queueKey) => this._jobQueue.createCancelScope(queueKey),
|
|
971
|
+
releaseBundle: (context, signal) => this._dropUncheckedBundlePick(context, signal)
|
|
747
972
|
});
|
|
748
973
|
// ---------------------------------------------------------------------------
|
|
749
974
|
// Private helpers
|
|
750
975
|
// ---------------------------------------------------------------------------
|
|
751
|
-
/**
|
|
752
|
-
* Ensure at least one device is connected and return a valid connectId.
|
|
753
|
-
*
|
|
754
|
-
* - If a session already exists for the given connectId, reuse it.
|
|
755
|
-
* - If ANY session exists (Ledger IDs are ephemeral), reuse it.
|
|
756
|
-
* - Otherwise: search → exactly 1 USB device auto-connects; multiple or none throws.
|
|
757
|
-
*/
|
|
758
976
|
// Mutex for ensureConnected — prevents concurrent calls from establishing duplicate connections
|
|
759
977
|
this._connectingPromise = null;
|
|
760
978
|
// ---------------------------------------------------------------------------
|
|
@@ -770,6 +988,12 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
770
988
|
});
|
|
771
989
|
};
|
|
772
990
|
this.deviceDisconnectHandler = (data) => {
|
|
991
|
+
const activeOperation = this._operations.findActiveByConnectionKey(data.connectId);
|
|
992
|
+
if (activeOperation && this._activeOperationJobs.has(activeOperation.operationId)) {
|
|
993
|
+
this._pendingOperationDisconnects.add(activeOperation.operationId);
|
|
994
|
+
} else {
|
|
995
|
+
this._operations.endByConnectionKey(data.connectId, "disconnect");
|
|
996
|
+
}
|
|
773
997
|
this._discoveredDevices.delete(data.connectId);
|
|
774
998
|
this._sessions.delete(data.connectId);
|
|
775
999
|
this.emitter.emit(DEVICE.DISCONNECT, {
|
|
@@ -778,10 +1002,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
778
1002
|
});
|
|
779
1003
|
};
|
|
780
1004
|
// Forward connector `ui-event` to the public hw.emitter so consumers only
|
|
781
|
-
// need to subscribe in one place.
|
|
782
|
-
//
|
|
783
|
-
// exists (race during teardown) we drop. All other variants pass through
|
|
784
|
-
// unchanged.
|
|
1005
|
+
// need to subscribe in one place. The AppInstallProgress variant re-keys
|
|
1006
|
+
// sessionId to connectId via `_sessions`, and drops if no mapping exists.
|
|
785
1007
|
this.uiEventForwarder = (event) => {
|
|
786
1008
|
if (event.type === EConnectorInteraction.AppInstallProgress) {
|
|
787
1009
|
let connectId;
|
|
@@ -826,11 +1048,30 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
826
1048
|
this._jobQueue = new DeviceJobQueue();
|
|
827
1049
|
this.registerEventListeners();
|
|
828
1050
|
}
|
|
1051
|
+
_discardPendingBinding(owner, status = "cancelled") {
|
|
1052
|
+
const pending = owner?.pendingBinding;
|
|
1053
|
+
if (!owner || !pending) return;
|
|
1054
|
+
owner.pendingBinding = void 0;
|
|
1055
|
+
if (pending.requestId === this._bindingSelectionRequestId) this._finishBleBinding(status);
|
|
1056
|
+
}
|
|
1057
|
+
_finishBleBinding(status) {
|
|
1058
|
+
const selectionRequestId = this._bindingSelectionRequestId;
|
|
1059
|
+
this._bindingSelectionRequestId = void 0;
|
|
1060
|
+
if (selectionRequestId) emitDeviceBindingStatus(this.emitter, selectionRequestId, status);
|
|
1061
|
+
}
|
|
1062
|
+
_isBleConnection() {
|
|
1063
|
+
return isLedgerBleConnectionType(this._activeConnectionType ?? this.connector.connectionType);
|
|
1064
|
+
}
|
|
829
1065
|
// Transport
|
|
830
1066
|
get activeTransport() {
|
|
831
|
-
return
|
|
1067
|
+
return this._isBleConnection() ? "ble" : "hid";
|
|
832
1068
|
}
|
|
833
1069
|
getAvailableTransports() {
|
|
1070
|
+
if (this.connector.availableTransports) {
|
|
1071
|
+
return this.connector.availableTransports.map(
|
|
1072
|
+
(transport) => transport === "ble" ? "ble" : "hid"
|
|
1073
|
+
);
|
|
1074
|
+
}
|
|
834
1075
|
return this.activeTransport ? [this.activeTransport] : [];
|
|
835
1076
|
}
|
|
836
1077
|
// Connector is bound at construction; switching requires a new adapter.
|
|
@@ -847,21 +1088,42 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
847
1088
|
* The next operation will re-discover and re-connect automatically.
|
|
848
1089
|
*/
|
|
849
1090
|
resetState() {
|
|
1091
|
+
void this._resetStateAndDisconnectSessions();
|
|
1092
|
+
}
|
|
1093
|
+
_resetStateAndDisconnectSessions() {
|
|
1094
|
+
if (this._resetPromise) return this._resetPromise;
|
|
1095
|
+
const sessionIds = new Set(this._sessions.values());
|
|
1096
|
+
this._stateGeneration += 1;
|
|
1097
|
+
this._finishBleBinding("cancelled");
|
|
1098
|
+
this._operations.endAll("runtime-reset");
|
|
1099
|
+
this._doConnectAbortController?.abort();
|
|
850
1100
|
this._discoveredDevices.clear();
|
|
851
1101
|
this._sessions.clear();
|
|
1102
|
+
this._sessionTransports.clear();
|
|
1103
|
+
this._pendingOperationBindings.clear();
|
|
1104
|
+
this._pendingPickBindings.clear();
|
|
1105
|
+
this._selectedBleReconnectTargets.clear();
|
|
852
1106
|
this._connectingPromise = null;
|
|
1107
|
+
this._doConnectAbortController = null;
|
|
853
1108
|
this._uiRegistry.reset();
|
|
854
1109
|
this._jobQueue.clear();
|
|
855
1110
|
this._btcHighIndexConfirmedThisSession = false;
|
|
1111
|
+
const resetPromise = this._runConnectorTeardown(async () => {
|
|
1112
|
+
for (const sessionId of sessionIds) {
|
|
1113
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
1114
|
+
}
|
|
1115
|
+
});
|
|
1116
|
+
this._resetPromise = resetPromise;
|
|
1117
|
+
return resetPromise.finally(() => {
|
|
1118
|
+
if (this._resetPromise === resetPromise) {
|
|
1119
|
+
this._resetPromise = null;
|
|
1120
|
+
}
|
|
1121
|
+
});
|
|
856
1122
|
}
|
|
857
1123
|
async dispose() {
|
|
858
|
-
this.
|
|
859
|
-
this._jobQueue.clear();
|
|
1124
|
+
await this._resetStateAndDisconnectSessions();
|
|
860
1125
|
this.unregisterEventListeners();
|
|
861
1126
|
this.connector.reset();
|
|
862
|
-
this._discoveredDevices.clear();
|
|
863
|
-
this._sessions.clear();
|
|
864
|
-
this._btcHighIndexConfirmedThisSession = false;
|
|
865
1127
|
this.emitter.removeAllListeners();
|
|
866
1128
|
}
|
|
867
1129
|
uiResponse(response) {
|
|
@@ -871,17 +1133,32 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
871
1133
|
// Device management
|
|
872
1134
|
// ---------------------------------------------------------------------------
|
|
873
1135
|
async searchDevices(options) {
|
|
1136
|
+
return this._searchDevices(options);
|
|
1137
|
+
}
|
|
1138
|
+
async _searchDevices(options, signal) {
|
|
874
1139
|
debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
|
|
875
1140
|
try {
|
|
876
1141
|
if (options?.resetSession) {
|
|
877
|
-
this.
|
|
878
|
-
|
|
879
|
-
this.
|
|
880
|
-
|
|
881
|
-
|
|
1142
|
+
await this._resetStateAndDisconnectSessions();
|
|
1143
|
+
} else {
|
|
1144
|
+
await this._connectorTeardownTail;
|
|
1145
|
+
}
|
|
1146
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
1147
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1148
|
+
const stateGeneration = this._stateGeneration;
|
|
1149
|
+
const devices = await this.connector.searchDevices(
|
|
1150
|
+
options?.transportType ? {
|
|
1151
|
+
transportType: options.transportType,
|
|
1152
|
+
waitForAll: options.waitForAllTransports
|
|
1153
|
+
} : void 0
|
|
1154
|
+
);
|
|
1155
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1156
|
+
if (stateGeneration !== this._stateGeneration) {
|
|
1157
|
+
throw createHwkError({
|
|
1158
|
+
code: HardwareErrorCode3.UserAborted,
|
|
1159
|
+
message: "Ledger discovery was reset"
|
|
1160
|
+
});
|
|
882
1161
|
}
|
|
883
|
-
await this._ensureDevicePermission();
|
|
884
|
-
const devices = await this.connector.searchDevices();
|
|
885
1162
|
this._discoveredDevices.clear();
|
|
886
1163
|
for (const d of devices) {
|
|
887
1164
|
if (d.connectId) {
|
|
@@ -889,7 +1166,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
889
1166
|
}
|
|
890
1167
|
}
|
|
891
1168
|
if (this._discoveredDevices.size === 0) {
|
|
892
|
-
await this._ensureDevicePermission();
|
|
1169
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
893
1170
|
}
|
|
894
1171
|
const result = Array.from(this._discoveredDevices.values());
|
|
895
1172
|
debugLog("[LedgerAdapter][RES]", {
|
|
@@ -908,41 +1185,263 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
908
1185
|
throw err;
|
|
909
1186
|
}
|
|
910
1187
|
}
|
|
1188
|
+
async searchDeviceTargets(options) {
|
|
1189
|
+
const devices = await this.searchDevices(options);
|
|
1190
|
+
return devices.map((device) => toPhysicalDeviceSearchTarget("ledger", device));
|
|
1191
|
+
}
|
|
911
1192
|
// USB single-session invariant: evict all sessions, best-effort (see connectDevice).
|
|
912
|
-
async _evictAllSessions() {
|
|
1193
|
+
async _evictAllSessions(preserveOperationId) {
|
|
1194
|
+
this._operations.endAll("explicit", preserveOperationId);
|
|
913
1195
|
if (this._sessions.size === 0) return;
|
|
914
1196
|
const stale = [...this._sessions.values()];
|
|
915
1197
|
this._sessions.clear();
|
|
916
|
-
for (const sid of stale)
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
1198
|
+
for (const sid of stale) this._sessionTransports.delete(sid);
|
|
1199
|
+
await this._runConnectorTeardown(async () => {
|
|
1200
|
+
for (const sid of stale) {
|
|
1201
|
+
try {
|
|
1202
|
+
await this.connector.disconnect(sid);
|
|
1203
|
+
} catch {
|
|
1204
|
+
}
|
|
920
1205
|
}
|
|
921
|
-
}
|
|
1206
|
+
});
|
|
922
1207
|
}
|
|
923
1208
|
static _createDeviceBusyError(method) {
|
|
924
1209
|
return Object.assign(new Error(`Ledger device is busy while calling ${method}`), {
|
|
925
1210
|
code: HardwareErrorCode3.DeviceBusy
|
|
926
1211
|
});
|
|
927
1212
|
}
|
|
928
|
-
async connectDevice(
|
|
1213
|
+
async connectDevice(searchTargetId) {
|
|
1214
|
+
try {
|
|
1215
|
+
return await this._jobQueue.enqueue(
|
|
1216
|
+
searchTargetId || "__ledger_connect__",
|
|
1217
|
+
async (signal) => {
|
|
1218
|
+
const connected = await this._connectTarget(searchTargetId, void 0, signal);
|
|
1219
|
+
if (!connected.success) return connected;
|
|
1220
|
+
return this._createOperation(searchTargetId, connected.payload);
|
|
1221
|
+
},
|
|
1222
|
+
{
|
|
1223
|
+
label: "connectDevice",
|
|
1224
|
+
rejectIfBusy: true,
|
|
1225
|
+
busyError: _LedgerAdapter._createDeviceBusyError("connectDevice")
|
|
1226
|
+
}
|
|
1227
|
+
);
|
|
1228
|
+
} catch (error) {
|
|
1229
|
+
return this.errorToFailure(error);
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
/** Binds the picked BLE device; with a recorded wallet identity it must match first. */
|
|
1233
|
+
async bindBleDevice(params) {
|
|
1234
|
+
const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
|
|
1235
|
+
try {
|
|
1236
|
+
return await this._jobQueue.enqueue(
|
|
1237
|
+
"__ledger_bind_ble__",
|
|
1238
|
+
async (signal) => {
|
|
1239
|
+
if (!this.getAvailableTransports().includes("ble")) {
|
|
1240
|
+
throw createHwkError({
|
|
1241
|
+
code: HardwareErrorCode3.TransportNotAvailable,
|
|
1242
|
+
message: "Ledger Bluetooth transport is not available"
|
|
1243
|
+
});
|
|
1244
|
+
}
|
|
1245
|
+
this._activeConnectionType = "ble";
|
|
1246
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
1247
|
+
const attempt = {
|
|
1248
|
+
extra: params.extra,
|
|
1249
|
+
bindingReason: "manual-rebind",
|
|
1250
|
+
deferBindingSave: Boolean(identity)
|
|
1251
|
+
};
|
|
1252
|
+
try {
|
|
1253
|
+
const connectId = await this._connectFirstOrSelect(
|
|
1254
|
+
[],
|
|
1255
|
+
void 0,
|
|
1256
|
+
true,
|
|
1257
|
+
void 0,
|
|
1258
|
+
attempt,
|
|
1259
|
+
signal
|
|
1260
|
+
);
|
|
1261
|
+
const pending = attempt.pendingBinding;
|
|
1262
|
+
if (identity && pending) {
|
|
1263
|
+
attempt.pendingBinding = void 0;
|
|
1264
|
+
const sessionId = this._sessions.get(connectId);
|
|
1265
|
+
if (!sessionId) {
|
|
1266
|
+
throw createHwkError({
|
|
1267
|
+
code: HardwareErrorCode3.DeviceDisconnected,
|
|
1268
|
+
message: "Selected Ledger connection ended"
|
|
1269
|
+
});
|
|
1270
|
+
}
|
|
1271
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
1272
|
+
identity.chain,
|
|
1273
|
+
(method, callParams) => this._runConnectorCall(
|
|
1274
|
+
connectId,
|
|
1275
|
+
method,
|
|
1276
|
+
callParams,
|
|
1277
|
+
signal,
|
|
1278
|
+
void 0,
|
|
1279
|
+
void 0,
|
|
1280
|
+
{ autoInstallApp: true },
|
|
1281
|
+
{ connection: { connectId, sessionId } }
|
|
1282
|
+
)
|
|
1283
|
+
);
|
|
1284
|
+
if (fingerprint !== identity.value) {
|
|
1285
|
+
await this._dropSession(connectId, signal);
|
|
1286
|
+
throw createHwkError({
|
|
1287
|
+
code: HardwareErrorCode3.DeviceMismatch,
|
|
1288
|
+
message: formatDeviceMismatchError(identity.value, fingerprint)
|
|
1289
|
+
});
|
|
1290
|
+
}
|
|
1291
|
+
await this._saveSelectedBleBinding(
|
|
1292
|
+
connectId,
|
|
1293
|
+
pending.requestId,
|
|
1294
|
+
attempt,
|
|
1295
|
+
void 0,
|
|
1296
|
+
signal,
|
|
1297
|
+
identity
|
|
1298
|
+
);
|
|
1299
|
+
}
|
|
1300
|
+
if (!attempt.bindingSaved) {
|
|
1301
|
+
await this._dropSession(connectId, signal);
|
|
1302
|
+
throw createHwkError({
|
|
1303
|
+
code: HardwareErrorCode3.UnknownError,
|
|
1304
|
+
message: "Bluetooth binding could not be saved",
|
|
1305
|
+
origin: "host"
|
|
1306
|
+
});
|
|
1307
|
+
}
|
|
1308
|
+
return success2(connectId);
|
|
1309
|
+
} catch (error) {
|
|
1310
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
1311
|
+
throw error;
|
|
1312
|
+
}
|
|
1313
|
+
},
|
|
1314
|
+
{
|
|
1315
|
+
label: "bindBleDevice",
|
|
1316
|
+
rejectIfBusy: true,
|
|
1317
|
+
busyError: _LedgerAdapter._createDeviceBusyError("bindBleDevice")
|
|
1318
|
+
}
|
|
1319
|
+
);
|
|
1320
|
+
} catch (error) {
|
|
1321
|
+
return this.errorToFailure(error);
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
async acquireOperation(connectId, context) {
|
|
1325
|
+
try {
|
|
1326
|
+
return await this._jobQueue.enqueue(
|
|
1327
|
+
connectId || "__ledger_acquire__",
|
|
1328
|
+
async (signal) => {
|
|
1329
|
+
const transport = this._isBleConnection() ? "ble" : "usb";
|
|
1330
|
+
const hint = context.knownConnections?.find(
|
|
1331
|
+
(connection) => connection.transport === transport
|
|
1332
|
+
);
|
|
1333
|
+
const target = hint && hint.transport !== "qr" ? hint.connectId : connectId;
|
|
1334
|
+
await this._ensureDevicePermission(target, void 0, signal);
|
|
1335
|
+
const attempt = {
|
|
1336
|
+
...context,
|
|
1337
|
+
extra: context.extra ? { ...context.extra } : void 0,
|
|
1338
|
+
// The operation's calls decide whether the pick is the right wallet.
|
|
1339
|
+
deferBindingSave: true
|
|
1340
|
+
};
|
|
1341
|
+
try {
|
|
1342
|
+
const resolvedConnectId = await this.ensureConnected(
|
|
1343
|
+
target,
|
|
1344
|
+
signal,
|
|
1345
|
+
true,
|
|
1346
|
+
void 0,
|
|
1347
|
+
attempt
|
|
1348
|
+
);
|
|
1349
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1350
|
+
const result = this._createOperation(connectId, resolvedConnectId);
|
|
1351
|
+
if (result.success && attempt.pendingBinding) {
|
|
1352
|
+
this._pendingOperationBindings.set(result.payload, attempt);
|
|
1353
|
+
}
|
|
1354
|
+
return result;
|
|
1355
|
+
} catch (error) {
|
|
1356
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
1357
|
+
throw error;
|
|
1358
|
+
}
|
|
1359
|
+
},
|
|
1360
|
+
{
|
|
1361
|
+
label: "acquireOperation",
|
|
1362
|
+
rejectIfBusy: true,
|
|
1363
|
+
busyError: _LedgerAdapter._createDeviceBusyError("acquireOperation")
|
|
1364
|
+
}
|
|
1365
|
+
);
|
|
1366
|
+
} catch (error) {
|
|
1367
|
+
return this.errorToFailure(error);
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
_createOperation(searchTargetId, resolvedConnectId) {
|
|
1371
|
+
this._operations.endByConnectionKey(resolvedConnectId, "explicit");
|
|
1372
|
+
const sessionId = this._sessions.get(resolvedConnectId);
|
|
1373
|
+
if (sessionId) this._operations.endByConnectionKey(sessionId, "explicit");
|
|
1374
|
+
const connectionType = sessionId && this._sessionTransports.get(sessionId) || (this._isBleConnection() ? "ble" : "usb");
|
|
1375
|
+
const device = this._discoveredDevices.get(resolvedConnectId) ?? {
|
|
1376
|
+
vendor: "ledger",
|
|
1377
|
+
model: "unknown",
|
|
1378
|
+
firmwareVersion: "",
|
|
1379
|
+
deviceId: "",
|
|
1380
|
+
connectId: resolvedConnectId,
|
|
1381
|
+
connectionType
|
|
1382
|
+
};
|
|
1383
|
+
const operation = this._operations.create({
|
|
1384
|
+
searchTargetId,
|
|
1385
|
+
connectId: resolvedConnectId,
|
|
1386
|
+
device,
|
|
1387
|
+
connectionType,
|
|
1388
|
+
connectionKeys: [this._sessions.get(resolvedConnectId) ?? ""]
|
|
1389
|
+
});
|
|
1390
|
+
return success2(operation.operationId);
|
|
1391
|
+
}
|
|
1392
|
+
async _connectTarget(connectId, preserveOperationId, signal) {
|
|
929
1393
|
debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
|
|
930
1394
|
try {
|
|
931
|
-
|
|
1395
|
+
this._assertConnectorReady("connectDevice");
|
|
1396
|
+
const discoveredType = this._discoveredDevices.get(connectId)?.connectionType;
|
|
1397
|
+
if (discoveredType === "usb" || discoveredType === "ble") {
|
|
1398
|
+
this._activeConnectionType = discoveredType;
|
|
1399
|
+
}
|
|
1400
|
+
if (this._isBleConnection() && !connectId) {
|
|
932
1401
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
933
1402
|
code: HardwareErrorCode3.DeviceNotFound
|
|
934
1403
|
});
|
|
935
1404
|
}
|
|
936
|
-
|
|
937
|
-
|
|
1405
|
+
await this._ensureDevicePermission(connectId, void 0, signal);
|
|
1406
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1407
|
+
const isMultiTransport = (this.connector.availableTransports?.length ?? 0) > 1;
|
|
1408
|
+
if (!isMultiTransport && this._isBleConnection()) {
|
|
1409
|
+
const previousSessionId = this._sessions.get(connectId);
|
|
1410
|
+
this._operations.endByConnectionKey(connectId, "explicit", preserveOperationId);
|
|
1411
|
+
if (previousSessionId) {
|
|
1412
|
+
this._operations.endByConnectionKey(previousSessionId, "explicit", preserveOperationId);
|
|
1413
|
+
this._sessions.delete(connectId);
|
|
1414
|
+
await this.connector.disconnect(previousSessionId).catch(() => void 0);
|
|
1415
|
+
}
|
|
1416
|
+
} else {
|
|
1417
|
+
await this._evictAllSessions(preserveOperationId);
|
|
1418
|
+
}
|
|
1419
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1420
|
+
const stateGeneration = this._stateGeneration;
|
|
1421
|
+
const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
|
|
1422
|
+
let session;
|
|
1423
|
+
this._connectingConnectId = connectId;
|
|
1424
|
+
try {
|
|
1425
|
+
session = this.connector.availableTransports?.length ? await this.connector.connect(connectId, {
|
|
1426
|
+
transportType: this._activeConnectionType ?? "usb"
|
|
1427
|
+
}) : await this.connector.connect(connectId);
|
|
1428
|
+
if (signal?.aborted || stateGeneration !== this._stateGeneration) {
|
|
1429
|
+
await this.connector.disconnect(session.sessionId).catch(() => void 0);
|
|
1430
|
+
throw Object.assign(new Error("Ledger connection aborted"), {
|
|
1431
|
+
code: HardwareErrorCode3.UserAborted
|
|
1432
|
+
});
|
|
1433
|
+
}
|
|
1434
|
+
} finally {
|
|
1435
|
+
if (this._connectingConnectId === connectId) this._connectingConnectId = void 0;
|
|
1436
|
+
releaseOperation();
|
|
938
1437
|
}
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
this.
|
|
1438
|
+
const resolvedConnectId = session.deviceInfo?.connectId || connectId;
|
|
1439
|
+
this._sessions.set(resolvedConnectId, session.sessionId);
|
|
1440
|
+
this._sessionTransports.set(session.sessionId, this._isBleConnection() ? "ble" : "usb");
|
|
942
1441
|
if (session.deviceInfo) {
|
|
943
|
-
this._discoveredDevices.set(
|
|
1442
|
+
this._discoveredDevices.set(resolvedConnectId, session.deviceInfo);
|
|
944
1443
|
}
|
|
945
|
-
const result =
|
|
1444
|
+
const result = success2(resolvedConnectId);
|
|
946
1445
|
debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
|
|
947
1446
|
return result;
|
|
948
1447
|
} catch (err) {
|
|
@@ -955,30 +1454,84 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
955
1454
|
return failureResult;
|
|
956
1455
|
}
|
|
957
1456
|
}
|
|
958
|
-
async
|
|
1457
|
+
async releaseOperation(operationId) {
|
|
1458
|
+
const operation = this._operations.findActive(operationId);
|
|
1459
|
+
if (operation) this._cancelOperationWork(operation);
|
|
1460
|
+
const endedOperation = this._operations.release(operationId);
|
|
1461
|
+
if (!endedOperation || this._bareCallMayUseConnection(endedOperation)) return;
|
|
1462
|
+
const { connectId } = endedOperation;
|
|
959
1463
|
debugLog("[LedgerAdapter][REQ]", {
|
|
960
|
-
method: "
|
|
1464
|
+
method: "releaseOperation",
|
|
961
1465
|
connectId,
|
|
962
1466
|
params: { connectId }
|
|
963
1467
|
});
|
|
964
1468
|
try {
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
await this.connector.disconnect(sessionId);
|
|
968
|
-
this._sessions.delete(connectId);
|
|
969
|
-
}
|
|
970
|
-
debugLog("[LedgerAdapter][RES]", { method: "disconnectDevice", success: true });
|
|
1469
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1470
|
+
debugLog("[LedgerAdapter][RES]", { method: "releaseOperation", success: true });
|
|
971
1471
|
} catch (err) {
|
|
972
1472
|
const e = err;
|
|
973
1473
|
debugLog("[LedgerAdapter][RES]", {
|
|
974
|
-
method: "
|
|
1474
|
+
method: "releaseOperation",
|
|
975
1475
|
success: false,
|
|
976
1476
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
977
1477
|
});
|
|
978
1478
|
throw err;
|
|
979
1479
|
}
|
|
980
1480
|
}
|
|
981
|
-
|
|
1481
|
+
/**
|
|
1482
|
+
* Ends a released operation's calls and prompts before teardown, which otherwise waits on a call
|
|
1483
|
+
* that waits on a prompt nobody will answer. Device I/O already on the wire still drains.
|
|
1484
|
+
*/
|
|
1485
|
+
_cancelOperationWork(operation) {
|
|
1486
|
+
const { operationId } = operation;
|
|
1487
|
+
const reason = createHwkError({
|
|
1488
|
+
code: HardwareErrorCode3.OperationEnded,
|
|
1489
|
+
message: "Ledger operation was released",
|
|
1490
|
+
params: { operationId, reason: "explicit" }
|
|
1491
|
+
});
|
|
1492
|
+
const queueKey = ledgerQueueKey({ operationId });
|
|
1493
|
+
const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
|
|
1494
|
+
this._jobQueue.cancelActiveAndPending(queueKey, reason);
|
|
1495
|
+
if (!ownsRunningCall) return;
|
|
1496
|
+
this._uiRegistry.cancel(void 0, void 0, operationId);
|
|
1497
|
+
void this.connector.cancel(this._sessions.get(operation.connectId) ?? operation.connectId);
|
|
1498
|
+
}
|
|
1499
|
+
/**
|
|
1500
|
+
* A running call by bare connectId (or still resolving its device by identity) may be on this
|
|
1501
|
+
* connection, e.g. waiting for an unlock; its later stages need it, so it stays cached for that
|
|
1502
|
+
* caller like any bare call's session. A lost connection is torn down regardless.
|
|
1503
|
+
*/
|
|
1504
|
+
_bareCallMayUseConnection(operation) {
|
|
1505
|
+
const activeKey = this._jobQueue.getActiveJob()?.deviceId;
|
|
1506
|
+
return activeKey !== void 0 && !isHardwareOperationId(activeKey) && (activeKey === operation.connectId || activeKey === LEDGER_DEFAULT_QUEUE_KEY || operation.connectionKeys.includes(activeKey));
|
|
1507
|
+
}
|
|
1508
|
+
async _releaseOperationConnection(operation) {
|
|
1509
|
+
const sessionIds = /* @__PURE__ */ new Set();
|
|
1510
|
+
for (const [connectId, sessionId] of this._sessions) {
|
|
1511
|
+
if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
|
|
1512
|
+
this._sessions.delete(connectId);
|
|
1513
|
+
sessionIds.add(sessionId);
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
for (const sessionId of sessionIds) {
|
|
1517
|
+
await this._runConnectorTeardown(
|
|
1518
|
+
() => this.connector.disconnect(sessionId).catch(() => void 0)
|
|
1519
|
+
);
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
async _releaseLostOperationConnection(operationId) {
|
|
1523
|
+
const endedOperation = this._operations.end(operationId, "disconnect");
|
|
1524
|
+
if (!endedOperation) return;
|
|
1525
|
+
this._discoveredDevices.delete(endedOperation.connectId);
|
|
1526
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1527
|
+
}
|
|
1528
|
+
async getDeviceInfo(connectIdOrOperationId, deviceId) {
|
|
1529
|
+
let connectId;
|
|
1530
|
+
try {
|
|
1531
|
+
connectId = isHardwareOperationId(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
|
|
1532
|
+
} catch (error) {
|
|
1533
|
+
return this.errorToFailure(error);
|
|
1534
|
+
}
|
|
982
1535
|
debugLog("[LedgerAdapter][REQ]", {
|
|
983
1536
|
method: "getDeviceInfo",
|
|
984
1537
|
connectId,
|
|
@@ -988,7 +1541,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
988
1541
|
await this._ensureDevicePermission(connectId, deviceId);
|
|
989
1542
|
const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
|
|
990
1543
|
if (cached) {
|
|
991
|
-
const result =
|
|
1544
|
+
const result = success2(cached);
|
|
992
1545
|
debugLog("[LedgerAdapter][RES]", {
|
|
993
1546
|
method: "getDeviceInfo",
|
|
994
1547
|
success: true,
|
|
@@ -1013,11 +1566,19 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1013
1566
|
success: false,
|
|
1014
1567
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
1015
1568
|
});
|
|
1016
|
-
|
|
1569
|
+
return this.errorToFailure(err);
|
|
1017
1570
|
}
|
|
1018
1571
|
}
|
|
1019
|
-
|
|
1020
|
-
|
|
1572
|
+
/** A bundle's BLE pick that no item got past the wallet check is not kept. */
|
|
1573
|
+
async _dropUncheckedBundlePick(context, signal) {
|
|
1574
|
+
const { connection } = context;
|
|
1575
|
+
const owner = connection ? this._pendingPickBindings.get(connection.connectId) : void 0;
|
|
1576
|
+
if (!connection || !owner) return;
|
|
1577
|
+
this._pendingPickBindings.delete(connection.connectId);
|
|
1578
|
+
this._discardPendingBinding(owner, signal.aborted ? "cancelled" : "failed");
|
|
1579
|
+
if (this._sessions.get(connection.connectId) === connection.sessionId) {
|
|
1580
|
+
await this._dropSession(connection.connectId, signal);
|
|
1581
|
+
}
|
|
1021
1582
|
}
|
|
1022
1583
|
// ---------------------------------------------------------------------------
|
|
1023
1584
|
// Chain call helper
|
|
@@ -1037,7 +1598,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1037
1598
|
commonParams,
|
|
1038
1599
|
installContext
|
|
1039
1600
|
);
|
|
1040
|
-
return
|
|
1601
|
+
return success2(result);
|
|
1041
1602
|
} catch (err) {
|
|
1042
1603
|
return this.errorToFailure(err);
|
|
1043
1604
|
}
|
|
@@ -1053,13 +1614,25 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1053
1614
|
if (params && typeof params === "object") {
|
|
1054
1615
|
const {
|
|
1055
1616
|
autoInstallApp,
|
|
1617
|
+
operationId,
|
|
1056
1618
|
passphraseState: _passphraseState,
|
|
1057
1619
|
useEmptyPassphrase: _useEmptyPassphrase,
|
|
1620
|
+
knownConnections,
|
|
1621
|
+
extra,
|
|
1622
|
+
allowDeviceSelection,
|
|
1623
|
+
supportedTransports,
|
|
1058
1624
|
...rest
|
|
1059
1625
|
} = params;
|
|
1060
1626
|
return {
|
|
1061
1627
|
commonParams: {
|
|
1062
|
-
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
|
|
1628
|
+
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
|
|
1629
|
+
operationId: typeof operationId === "string" ? operationId : void 0,
|
|
1630
|
+
...pickConnectionContext({
|
|
1631
|
+
knownConnections,
|
|
1632
|
+
extra,
|
|
1633
|
+
allowDeviceSelection,
|
|
1634
|
+
supportedTransports
|
|
1635
|
+
})
|
|
1063
1636
|
},
|
|
1064
1637
|
rest
|
|
1065
1638
|
};
|
|
@@ -1225,7 +1798,13 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1225
1798
|
params
|
|
1226
1799
|
);
|
|
1227
1800
|
}
|
|
1228
|
-
tronSignMessage(connectId, deviceId, params) {
|
|
1801
|
+
async tronSignMessage(connectId, deviceId, params) {
|
|
1802
|
+
if (params?.messageType !== "V2") {
|
|
1803
|
+
return failure2(
|
|
1804
|
+
HardwareErrorCode3.MethodNotSupported,
|
|
1805
|
+
'Ledger signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
|
|
1806
|
+
);
|
|
1807
|
+
}
|
|
1229
1808
|
return this.callChainWithMergedParams(
|
|
1230
1809
|
connectId,
|
|
1231
1810
|
deviceId,
|
|
@@ -1235,14 +1814,33 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1235
1814
|
);
|
|
1236
1815
|
}
|
|
1237
1816
|
// ---------------------------------------------------------------------------
|
|
1238
|
-
//
|
|
1239
|
-
//
|
|
1240
|
-
|
|
1817
|
+
// Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
|
|
1818
|
+
// ---------------------------------------------------------------------------
|
|
1819
|
+
zcashGetFullViewingKey(connectId, deviceId, params) {
|
|
1820
|
+
return this.callChainWithMergedParams(
|
|
1821
|
+
connectId,
|
|
1822
|
+
deviceId,
|
|
1823
|
+
"zcash",
|
|
1824
|
+
"zcashGetFullViewingKey",
|
|
1825
|
+
params
|
|
1826
|
+
);
|
|
1827
|
+
}
|
|
1828
|
+
zcashGetShieldedAddress(connectId, deviceId, params) {
|
|
1829
|
+
return this.callChainWithMergedParams(
|
|
1830
|
+
connectId,
|
|
1831
|
+
deviceId,
|
|
1832
|
+
"zcash",
|
|
1833
|
+
"zcashGetShieldedAddress",
|
|
1834
|
+
params
|
|
1835
|
+
);
|
|
1836
|
+
}
|
|
1837
|
+
// ---------------------------------------------------------------------------
|
|
1838
|
+
// App management: OS-level app install/list, no fingerprint or chain dispatch.
|
|
1241
1839
|
// ---------------------------------------------------------------------------
|
|
1242
1840
|
async installApp(connectId, appName) {
|
|
1243
1841
|
try {
|
|
1244
1842
|
await this.connectorCall(connectId, "installApp", { appName });
|
|
1245
|
-
return
|
|
1843
|
+
return success2(void 0);
|
|
1246
1844
|
} catch (err) {
|
|
1247
1845
|
return this.errorToFailure(err);
|
|
1248
1846
|
}
|
|
@@ -1250,7 +1848,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1250
1848
|
async listInstalledApps(connectId) {
|
|
1251
1849
|
try {
|
|
1252
1850
|
const result = await this.connectorCall(connectId, "listInstalledApps", {});
|
|
1253
|
-
return
|
|
1851
|
+
return success2(result);
|
|
1254
1852
|
} catch (err) {
|
|
1255
1853
|
return this.errorToFailure(err);
|
|
1256
1854
|
}
|
|
@@ -1259,7 +1857,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1259
1857
|
async listInstalledNames(connectId) {
|
|
1260
1858
|
try {
|
|
1261
1859
|
const result = await this.connectorCall(connectId, "listInstalledNames", {});
|
|
1262
|
-
return
|
|
1860
|
+
return success2(result);
|
|
1263
1861
|
} catch (err) {
|
|
1264
1862
|
return this.errorToFailure(err);
|
|
1265
1863
|
}
|
|
@@ -1267,7 +1865,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1267
1865
|
async listAvailableApps(connectId) {
|
|
1268
1866
|
try {
|
|
1269
1867
|
const result = await this.connectorCall(connectId, "listAvailableApps", {});
|
|
1270
|
-
return
|
|
1868
|
+
return success2(result);
|
|
1271
1869
|
} catch (err) {
|
|
1272
1870
|
return this.errorToFailure(err);
|
|
1273
1871
|
}
|
|
@@ -1275,7 +1873,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1275
1873
|
async getLedgerFirmwareVersion(connectId) {
|
|
1276
1874
|
try {
|
|
1277
1875
|
const result = await this.connectorCall(connectId, "getFirmwareVersion", {});
|
|
1278
|
-
return
|
|
1876
|
+
return success2(result);
|
|
1279
1877
|
} catch (err) {
|
|
1280
1878
|
return this.errorToFailure(err);
|
|
1281
1879
|
}
|
|
@@ -1283,7 +1881,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1283
1881
|
async getLedgerDeviceInfo(connectId) {
|
|
1284
1882
|
try {
|
|
1285
1883
|
const result = await this.connectorCall(connectId, "getDeviceInfo", {});
|
|
1286
|
-
return
|
|
1884
|
+
return success2(result);
|
|
1287
1885
|
} catch (err) {
|
|
1288
1886
|
return this.errorToFailure(err);
|
|
1289
1887
|
}
|
|
@@ -1323,11 +1921,11 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1323
1921
|
);
|
|
1324
1922
|
}
|
|
1325
1923
|
await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
|
|
1326
|
-
this.
|
|
1924
|
+
await this._resetStateAndDisconnectSessions();
|
|
1327
1925
|
}
|
|
1328
1926
|
const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
|
|
1329
1927
|
if (!result.isGenuine) {
|
|
1330
|
-
return
|
|
1928
|
+
return success2({
|
|
1331
1929
|
vendor: "ledger",
|
|
1332
1930
|
verified: false
|
|
1333
1931
|
});
|
|
@@ -1338,7 +1936,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1338
1936
|
`Genuine check completed (isGenuine=${result.isGenuine}) but no deviceId was captured`
|
|
1339
1937
|
);
|
|
1340
1938
|
}
|
|
1341
|
-
return
|
|
1939
|
+
return success2({
|
|
1342
1940
|
vendor: "ledger",
|
|
1343
1941
|
verified: result.isGenuine,
|
|
1344
1942
|
deviceId: result.deviceId
|
|
@@ -1349,10 +1947,10 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1349
1947
|
if (relayUrl) {
|
|
1350
1948
|
try {
|
|
1351
1949
|
await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
|
|
1352
|
-
this.
|
|
1950
|
+
await this._resetStateAndDisconnectSessions();
|
|
1353
1951
|
} catch {
|
|
1354
1952
|
this.connector.reset();
|
|
1355
|
-
this.
|
|
1953
|
+
await this._resetStateAndDisconnectSessions();
|
|
1356
1954
|
}
|
|
1357
1955
|
}
|
|
1358
1956
|
}
|
|
@@ -1364,6 +1962,20 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1364
1962
|
this.emitter.off(event, listener);
|
|
1365
1963
|
}
|
|
1366
1964
|
cancel(connectId) {
|
|
1965
|
+
const namedOperationIsLive = (id) => {
|
|
1966
|
+
try {
|
|
1967
|
+
this._operations.resolve(id);
|
|
1968
|
+
return true;
|
|
1969
|
+
} catch {
|
|
1970
|
+
return false;
|
|
1971
|
+
}
|
|
1972
|
+
};
|
|
1973
|
+
if (isHardwareOperationId(connectId) && !namedOperationIsLive(connectId)) {
|
|
1974
|
+
debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
|
|
1975
|
+
connectId
|
|
1976
|
+
});
|
|
1977
|
+
return;
|
|
1978
|
+
}
|
|
1367
1979
|
const userAbortReason = Object.assign(new Error("User aborted operation"), {
|
|
1368
1980
|
code: HardwareErrorCode3.UserAborted,
|
|
1369
1981
|
_tag: ERROR_TAG.UserAborted
|
|
@@ -1374,60 +1986,143 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1374
1986
|
this._lastCancelReason = void 0;
|
|
1375
1987
|
}
|
|
1376
1988
|
}, 2e3);
|
|
1377
|
-
this.
|
|
1378
|
-
|
|
1379
|
-
|
|
1989
|
+
const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
|
|
1990
|
+
let operationId;
|
|
1991
|
+
if (isHardwareOperationId(connectId)) {
|
|
1992
|
+
operationId = connectId;
|
|
1993
|
+
} else if (!connectId && isHardwareOperationId(activeJobId)) {
|
|
1994
|
+
operationId = activeJobId;
|
|
1995
|
+
}
|
|
1996
|
+
let resolvedConnectId = connectId;
|
|
1997
|
+
if (operationId) {
|
|
1998
|
+
try {
|
|
1999
|
+
resolvedConnectId = this._operations.resolve(operationId).connectId;
|
|
2000
|
+
} catch {
|
|
2001
|
+
resolvedConnectId = void 0;
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
|
|
2005
|
+
const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
|
|
2006
|
+
if (!connectId) {
|
|
2007
|
+
this._uiRegistry.cancel();
|
|
2008
|
+
} else if (pendingOperationId) {
|
|
2009
|
+
this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
|
|
2010
|
+
}
|
|
2011
|
+
this._finishBleBinding("cancelled");
|
|
2012
|
+
if (!connectId) this._pendingOperationBindings.clear();
|
|
2013
|
+
else if (pendingOperationId) this._pendingOperationBindings.delete(pendingOperationId);
|
|
2014
|
+
const queueKeys = /* @__PURE__ */ new Set();
|
|
2015
|
+
if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
|
|
2016
|
+
if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
|
|
2017
|
+
if (queueKeys.size) {
|
|
2018
|
+
let cancelledAnyJob = false;
|
|
2019
|
+
for (const key of queueKeys) {
|
|
2020
|
+
cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
|
|
2021
|
+
}
|
|
2022
|
+
debugLog("[LedgerAdapter] cancel routed to queue keys", {
|
|
2023
|
+
queueKeys: [...queueKeys],
|
|
2024
|
+
cancelledAnyJob
|
|
2025
|
+
});
|
|
1380
2026
|
} else {
|
|
1381
2027
|
this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
|
|
1382
2028
|
}
|
|
1383
|
-
if (
|
|
1384
|
-
const sessionId = this._sessions.get(
|
|
2029
|
+
if (resolvedConnectId) {
|
|
2030
|
+
const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
|
|
1385
2031
|
void this.connector.cancel(sessionId);
|
|
1386
2032
|
} else {
|
|
1387
2033
|
for (const sid of this._sessions.values()) void this.connector.cancel(sid);
|
|
1388
2034
|
}
|
|
1389
|
-
|
|
2035
|
+
const connectingConnectId = this._connectingConnectId;
|
|
2036
|
+
const targetKeys = new Set(
|
|
2037
|
+
[
|
|
2038
|
+
connectId,
|
|
2039
|
+
resolvedConnectId,
|
|
2040
|
+
...pendingOperationId ? this._operations.find(pendingOperationId)?.connectionKeys ?? [] : []
|
|
2041
|
+
].filter(Boolean)
|
|
2042
|
+
);
|
|
2043
|
+
const ownsPendingConnect = !connectId || activeJobId !== void 0 && queueKeys.has(activeJobId) || connectingConnectId !== void 0 && targetKeys.has(connectingConnectId);
|
|
2044
|
+
if (this._connectingPromise && ownsPendingConnect) {
|
|
1390
2045
|
this._doConnectAbortController?.abort(userAbortReason);
|
|
1391
2046
|
}
|
|
2047
|
+
if (connectingConnectId && ownsPendingConnect) void this.connector.cancel(connectingConnectId);
|
|
1392
2048
|
}
|
|
1393
2049
|
// ---------------------------------------------------------------------------
|
|
1394
2050
|
// Chain fingerprint
|
|
1395
2051
|
// ---------------------------------------------------------------------------
|
|
2052
|
+
/** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
|
|
1396
2053
|
async getChainFingerprint(connectId, deviceId, chain) {
|
|
1397
2054
|
try {
|
|
1398
2055
|
const fingerprint = await this._computeChainFingerprint(
|
|
1399
2056
|
chain,
|
|
1400
2057
|
(method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
|
|
1401
2058
|
);
|
|
1402
|
-
|
|
2059
|
+
if (deviceId) {
|
|
2060
|
+
if (fingerprint !== deviceId) {
|
|
2061
|
+
return failure2(
|
|
2062
|
+
HardwareErrorCode3.DeviceMismatch,
|
|
2063
|
+
formatDeviceMismatchError(deviceId, fingerprint)
|
|
2064
|
+
);
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
return success2(fingerprint);
|
|
1403
2068
|
} catch (err) {
|
|
1404
2069
|
debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
|
|
1405
2070
|
return this.errorToFailure(err);
|
|
1406
2071
|
}
|
|
1407
2072
|
}
|
|
1408
|
-
/**
|
|
1409
|
-
|
|
1410
|
-
* Safe to call inside connectorCall without causing queue deadlock.
|
|
1411
|
-
*/
|
|
1412
|
-
async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
|
|
1413
|
-
if (!deviceId) return { success: true };
|
|
2073
|
+
/** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
|
|
2074
|
+
async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
|
|
1414
2075
|
try {
|
|
1415
|
-
const
|
|
1416
|
-
|
|
1417
|
-
|
|
2076
|
+
const outcome = await requestSaveDeviceBinding(
|
|
2077
|
+
this.emitter,
|
|
2078
|
+
this._uiRegistry,
|
|
2079
|
+
{
|
|
2080
|
+
selectionRequestId,
|
|
2081
|
+
connection: { transport: "ble", connectId },
|
|
2082
|
+
...identity ? { identity } : {},
|
|
2083
|
+
extra: context?.extra,
|
|
2084
|
+
operationId
|
|
2085
|
+
},
|
|
2086
|
+
signal
|
|
1418
2087
|
);
|
|
1419
|
-
if (
|
|
1420
|
-
|
|
2088
|
+
if (context) context.bindingSaved = outcome.saved;
|
|
2089
|
+
if (!outcome.saved) {
|
|
2090
|
+
debugLog("[LedgerAdapter] BLE binding not persisted by host", {
|
|
2091
|
+
connectId,
|
|
2092
|
+
reason: outcome.reason
|
|
2093
|
+
});
|
|
1421
2094
|
}
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
2095
|
+
} catch (error) {
|
|
2096
|
+
await this._dropSession(connectId, signal);
|
|
2097
|
+
throw error;
|
|
2098
|
+
} finally {
|
|
2099
|
+
if (this._bindingSelectionRequestId === selectionRequestId) {
|
|
2100
|
+
this._bindingSelectionRequestId = void 0;
|
|
1427
2101
|
}
|
|
1428
|
-
throw err;
|
|
1429
2102
|
}
|
|
1430
2103
|
}
|
|
2104
|
+
async _dropSession(connectId, signal) {
|
|
2105
|
+
const sessionId = this._sessions.get(connectId);
|
|
2106
|
+
this._sessions.delete(connectId);
|
|
2107
|
+
if (!sessionId) return;
|
|
2108
|
+
this._sessionTransports.delete(sessionId);
|
|
2109
|
+
const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
|
|
2110
|
+
() => void 0
|
|
2111
|
+
);
|
|
2112
|
+
if (!signal.aborted) await teardown;
|
|
2113
|
+
}
|
|
2114
|
+
/** Verify on the acquired session without re-entering the job queue. */
|
|
2115
|
+
async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
|
|
2116
|
+
if (!deviceId) return { success: true };
|
|
2117
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
2118
|
+
chain,
|
|
2119
|
+
(method, params) => this._callConnector(sessionId, method, params)
|
|
2120
|
+
);
|
|
2121
|
+
if (fingerprint === deviceId) {
|
|
2122
|
+
return { success: true };
|
|
2123
|
+
}
|
|
2124
|
+
return { success: false, expected: deviceId, actual: fingerprint };
|
|
2125
|
+
}
|
|
1431
2126
|
/**
|
|
1432
2127
|
* Compute the chain fingerprint via a caller-supplied call strategy.
|
|
1433
2128
|
*
|
|
@@ -1455,11 +2150,20 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1455
2150
|
address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
|
|
1456
2151
|
} else if (chain === "tron") {
|
|
1457
2152
|
address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
|
|
2153
|
+
} else if (chain === "zcash") {
|
|
2154
|
+
address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
|
|
1458
2155
|
} else {
|
|
1459
2156
|
throw new Error(`Unsupported chain for fingerprint: ${chain}`);
|
|
1460
2157
|
}
|
|
1461
2158
|
return deriveDeviceFingerprint(address);
|
|
1462
2159
|
}
|
|
2160
|
+
/**
|
|
2161
|
+
* Operation owning the running job, so a mid-call UI request can name it.
|
|
2162
|
+
* Undefined at cold start when no operation owns the job.
|
|
2163
|
+
*/
|
|
2164
|
+
_activeOperationId() {
|
|
2165
|
+
return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
|
|
2166
|
+
}
|
|
1463
2167
|
// Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
|
|
1464
2168
|
// The user must press Confirm after unlocking, which triggers a search retry.
|
|
1465
2169
|
// If `signal` is provided, an abort cancels the pending UI request so the
|
|
@@ -1469,15 +2173,18 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1469
2173
|
if (signal?.aborted) {
|
|
1470
2174
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1471
2175
|
}
|
|
2176
|
+
const operationId = this._activeOperationId();
|
|
1472
2177
|
const waitPromise = this._uiRegistry.wait(
|
|
1473
|
-
UI_REQUEST.REQUEST_DEVICE_CONNECT
|
|
2178
|
+
UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
2179
|
+
{ operationId }
|
|
1474
2180
|
);
|
|
1475
2181
|
this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_CONNECT, {
|
|
1476
2182
|
type: UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
1477
2183
|
payload: {
|
|
1478
2184
|
vendor: "ledger",
|
|
1479
2185
|
reason: "device-not-found",
|
|
1480
|
-
message: "Please connect and unlock your Ledger device"
|
|
2186
|
+
message: "Please connect and unlock your Ledger device",
|
|
2187
|
+
operationId
|
|
1481
2188
|
}
|
|
1482
2189
|
});
|
|
1483
2190
|
let payload;
|
|
@@ -1523,7 +2230,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1523
2230
|
* Returns the params to pass through (with `showOnDevice` possibly
|
|
1524
2231
|
* promoted), or `null` if the user declined.
|
|
1525
2232
|
*/
|
|
1526
|
-
async _gateBtcHighIndex(params) {
|
|
2233
|
+
async _gateBtcHighIndex(params, signal) {
|
|
1527
2234
|
const accountIndex = btcAccountIndexFromPath(params.path);
|
|
1528
2235
|
if (params.showOnDevice) return params;
|
|
1529
2236
|
if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
|
|
@@ -1532,25 +2239,32 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1532
2239
|
if (this._btcHighIndexConfirmedThisSession) {
|
|
1533
2240
|
return { ...params, showOnDevice: true };
|
|
1534
2241
|
}
|
|
1535
|
-
const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
|
|
2242
|
+
const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
|
|
1536
2243
|
if (!confirmed) return null;
|
|
1537
2244
|
this._btcHighIndexConfirmedThisSession = true;
|
|
1538
2245
|
return { ...params, showOnDevice: true };
|
|
1539
2246
|
}
|
|
1540
|
-
async _waitForBtcHighIndexConfirm(path, accountIndex) {
|
|
2247
|
+
async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
|
|
2248
|
+
const operationId = this._activeOperationId();
|
|
1541
2249
|
const waitPromise = this._uiRegistry.wait(
|
|
1542
|
-
UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM
|
|
2250
|
+
UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2251
|
+
{ operationId }
|
|
1543
2252
|
);
|
|
1544
2253
|
this.emitter.emit(UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
|
|
1545
2254
|
type: UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
1546
2255
|
payload: {
|
|
1547
2256
|
vendor: "ledger",
|
|
1548
2257
|
path,
|
|
1549
|
-
accountIndex
|
|
2258
|
+
accountIndex,
|
|
2259
|
+
operationId
|
|
1550
2260
|
}
|
|
1551
2261
|
});
|
|
1552
2262
|
try {
|
|
1553
|
-
const payload = await
|
|
2263
|
+
const payload = await this._awaitUiAnswer(
|
|
2264
|
+
UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2265
|
+
waitPromise,
|
|
2266
|
+
signal
|
|
2267
|
+
);
|
|
1554
2268
|
return !!payload?.confirmed;
|
|
1555
2269
|
} catch (err) {
|
|
1556
2270
|
this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
@@ -1560,18 +2274,35 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1560
2274
|
return false;
|
|
1561
2275
|
}
|
|
1562
2276
|
}
|
|
2277
|
+
/** A cancel of the job ends its open prompt, even when no operation names that prompt. */
|
|
2278
|
+
async _awaitUiAnswer(requestType, waitPromise, signal) {
|
|
2279
|
+
const onAbort = () => this._uiRegistry.cancel(requestType);
|
|
2280
|
+
if (signal.aborted) onAbort();
|
|
2281
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2282
|
+
try {
|
|
2283
|
+
return await waitPromise;
|
|
2284
|
+
} finally {
|
|
2285
|
+
signal.removeEventListener("abort", onAbort);
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
1563
2288
|
// Ask the user whether to install a missing app (autoInstallApp flow).
|
|
1564
2289
|
// Same register-then-emit ordering as the BTC high-index gate.
|
|
1565
|
-
async _waitForInstallAppConfirm(appName) {
|
|
2290
|
+
async _waitForInstallAppConfirm(appName, signal) {
|
|
2291
|
+
const operationId = this._activeOperationId();
|
|
1566
2292
|
const waitPromise = this._uiRegistry.wait(
|
|
1567
|
-
UI_REQUEST.REQUEST_INSTALL_APP
|
|
2293
|
+
UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2294
|
+
{ operationId }
|
|
1568
2295
|
);
|
|
1569
2296
|
this.emitter.emit(UI_REQUEST.REQUEST_INSTALL_APP, {
|
|
1570
2297
|
type: UI_REQUEST.REQUEST_INSTALL_APP,
|
|
1571
|
-
payload: { vendor: "ledger", appName }
|
|
2298
|
+
payload: { vendor: "ledger", appName, operationId }
|
|
1572
2299
|
});
|
|
1573
2300
|
try {
|
|
1574
|
-
const payload = await
|
|
2301
|
+
const payload = await this._awaitUiAnswer(
|
|
2302
|
+
UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2303
|
+
waitPromise,
|
|
2304
|
+
signal
|
|
2305
|
+
);
|
|
1575
2306
|
return !!payload?.confirmed;
|
|
1576
2307
|
} catch (err) {
|
|
1577
2308
|
this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
@@ -1584,16 +2315,17 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1584
2315
|
// Layer 1 entry. Caller signal only races the outer awaiter; the shared
|
|
1585
2316
|
// `_doConnect` runs under its own internal controller so caller A's cancel
|
|
1586
2317
|
// doesn't kill caller B's await.
|
|
1587
|
-
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
|
|
2318
|
+
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
1588
2319
|
if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
|
|
1589
|
-
|
|
2320
|
+
this._assertConnectorReady("connectDevice");
|
|
2321
|
+
if (this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
|
|
1590
2322
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1591
2323
|
code: HardwareErrorCode3.DeviceNotFound
|
|
1592
2324
|
});
|
|
1593
2325
|
}
|
|
1594
2326
|
if (connectId && this._sessions.has(connectId)) return connectId;
|
|
1595
2327
|
if (!connectId && this._sessions.size > 0) {
|
|
1596
|
-
if (!
|
|
2328
|
+
if (!this._isBleConnection() && this._sessions.size > 1) {
|
|
1597
2329
|
throw Object.assign(
|
|
1598
2330
|
new Error(
|
|
1599
2331
|
"Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
|
|
@@ -1603,15 +2335,24 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1603
2335
|
}
|
|
1604
2336
|
return this._sessions.keys().next().value;
|
|
1605
2337
|
}
|
|
1606
|
-
if (!this._connectingPromise) {
|
|
1607
|
-
|
|
1608
|
-
|
|
2338
|
+
if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
|
|
2339
|
+
const controller = new AbortController();
|
|
2340
|
+
this._doConnectAbortController = controller;
|
|
2341
|
+
const innerSignal = controller.signal;
|
|
1609
2342
|
this._connectingPromise = (async () => {
|
|
1610
2343
|
try {
|
|
1611
|
-
return await this._doConnect(
|
|
2344
|
+
return await this._doConnect(
|
|
2345
|
+
innerSignal,
|
|
2346
|
+
connectId,
|
|
2347
|
+
allowUsbEphemeralFallback,
|
|
2348
|
+
preserveOperationId,
|
|
2349
|
+
context
|
|
2350
|
+
);
|
|
1612
2351
|
} finally {
|
|
1613
|
-
this.
|
|
1614
|
-
|
|
2352
|
+
if (this._doConnectAbortController === controller) {
|
|
2353
|
+
this._connectingPromise = null;
|
|
2354
|
+
this._doConnectAbortController = null;
|
|
2355
|
+
}
|
|
1615
2356
|
}
|
|
1616
2357
|
})();
|
|
1617
2358
|
}
|
|
@@ -1620,22 +2361,57 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1620
2361
|
// Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
|
|
1621
2362
|
// Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
|
|
1622
2363
|
// throw DeviceNotFound so the user is kicked out of the loop.
|
|
1623
|
-
async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false) {
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
2364
|
+
async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
2365
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2366
|
+
if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
|
|
2367
|
+
this._activeConnectionType = "usb";
|
|
2368
|
+
const usbDevices = context?.supportedTransports && !context.supportedTransports.includes("usb") ? [] : await this._searchDevices({ transportType: "usb" }, internalSignal);
|
|
2369
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2370
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2371
|
+
(connection) => connection.transport === "usb"
|
|
2372
|
+
);
|
|
2373
|
+
const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
|
|
2374
|
+
if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback)) {
|
|
2375
|
+
return this._connectFirstOrSelect(
|
|
2376
|
+
usbDevices,
|
|
2377
|
+
usbTarget,
|
|
2378
|
+
allowUsbEphemeralFallback,
|
|
2379
|
+
preserveOperationId,
|
|
2380
|
+
context,
|
|
2381
|
+
internalSignal
|
|
2382
|
+
);
|
|
2383
|
+
}
|
|
2384
|
+
if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
|
|
2385
|
+
throw createHwkError({
|
|
2386
|
+
code: HardwareErrorCode3.DeviceNotFound,
|
|
2387
|
+
message: "This Ledger model has no Bluetooth transport; connect it over USB"
|
|
2388
|
+
});
|
|
1638
2389
|
}
|
|
2390
|
+
this._activeConnectionType = "ble";
|
|
2391
|
+
const knownBle = context?.knownConnections?.find(
|
|
2392
|
+
(connection) => connection.transport === "ble"
|
|
2393
|
+
);
|
|
2394
|
+
if (knownBle?.transport === "ble") {
|
|
2395
|
+
return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
|
|
2396
|
+
}
|
|
2397
|
+
if (targetConnectId && context?.knownConnections === void 0) {
|
|
2398
|
+
throw createHwkError({
|
|
2399
|
+
code: HardwareErrorCode3.DeviceNotFound,
|
|
2400
|
+
message: "Ledger connection metadata is required before starting Bluetooth binding"
|
|
2401
|
+
});
|
|
2402
|
+
}
|
|
2403
|
+
const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
|
|
2404
|
+
return this._connectFirstOrSelect(
|
|
2405
|
+
bleDevices,
|
|
2406
|
+
void 0,
|
|
2407
|
+
allowUsbEphemeralFallback,
|
|
2408
|
+
preserveOperationId,
|
|
2409
|
+
context,
|
|
2410
|
+
internalSignal
|
|
2411
|
+
);
|
|
2412
|
+
}
|
|
2413
|
+
if (this._isBleConnection() && targetConnectId) {
|
|
2414
|
+
return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
|
|
1639
2415
|
}
|
|
1640
2416
|
let confirms = 0;
|
|
1641
2417
|
while (!internalSignal.aborted) {
|
|
@@ -1643,22 +2419,28 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1643
2419
|
type: EConnectorInteraction.Searching,
|
|
1644
2420
|
payload: { sessionId: "" }
|
|
1645
2421
|
});
|
|
1646
|
-
let devices = await this.
|
|
2422
|
+
let devices = await this._searchDevices(void 0, internalSignal);
|
|
2423
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1647
2424
|
if (devices.length === 0) {
|
|
1648
2425
|
for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
|
|
1649
2426
|
await new Promise((resolve) => {
|
|
1650
2427
|
setTimeout(resolve, DEVICE_CONNECT_RETRY_DELAY_MS);
|
|
1651
2428
|
});
|
|
1652
|
-
|
|
2429
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2430
|
+
devices = await this._searchDevices(void 0, internalSignal);
|
|
2431
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1653
2432
|
if (devices.length > 0) break;
|
|
1654
2433
|
}
|
|
1655
2434
|
}
|
|
1656
|
-
if (devices.length > 0) {
|
|
2435
|
+
if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
|
|
1657
2436
|
try {
|
|
1658
2437
|
return await this._connectFirstOrSelect(
|
|
1659
2438
|
devices,
|
|
1660
2439
|
targetConnectId,
|
|
1661
|
-
allowUsbEphemeralFallback
|
|
2440
|
+
allowUsbEphemeralFallback,
|
|
2441
|
+
preserveOperationId,
|
|
2442
|
+
context,
|
|
2443
|
+
internalSignal
|
|
1662
2444
|
);
|
|
1663
2445
|
} catch (err) {
|
|
1664
2446
|
if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
|
|
@@ -1687,45 +2469,147 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1687
2469
|
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1688
2470
|
throw new Error("_doConnect aborted");
|
|
1689
2471
|
}
|
|
1690
|
-
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback
|
|
2472
|
+
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
|
|
2473
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1691
2474
|
if (targetConnectId) {
|
|
1692
2475
|
const target = devices.find(
|
|
1693
2476
|
(d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
|
|
1694
2477
|
);
|
|
1695
2478
|
if (target) {
|
|
1696
|
-
return this._connectDeviceOrThrow(target.connectId);
|
|
2479
|
+
return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
|
|
1697
2480
|
}
|
|
1698
|
-
if (!
|
|
2481
|
+
if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
|
|
1699
2482
|
debugLog(
|
|
1700
2483
|
`[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
|
|
1701
2484
|
);
|
|
1702
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2485
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1703
2486
|
}
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
2487
|
+
if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
|
|
2488
|
+
const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
|
|
2489
|
+
code: HardwareErrorCode3.DeviceNotFound
|
|
2490
|
+
});
|
|
2491
|
+
if (this._isBleConnection()) {
|
|
2492
|
+
err._tag = ERROR_TAG.DeviceNotAdvertising;
|
|
2493
|
+
}
|
|
2494
|
+
throw err;
|
|
1709
2495
|
}
|
|
1710
|
-
throw err;
|
|
1711
2496
|
}
|
|
1712
|
-
|
|
2497
|
+
const requiresBleSelection = this._isBleConnection();
|
|
2498
|
+
if (requiresBleSelection && !allowUsbEphemeralFallback) {
|
|
1713
2499
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1714
2500
|
code: HardwareErrorCode3.DeviceNotFound
|
|
1715
2501
|
});
|
|
1716
2502
|
}
|
|
1717
|
-
if (
|
|
1718
|
-
|
|
2503
|
+
if (requiresBleSelection && context?.allowDeviceSelection !== false) {
|
|
2504
|
+
const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
|
|
2505
|
+
if (context) context.bindingSessionId = bindingSessionId;
|
|
2506
|
+
const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb")) && (!context?.supportedTransports || context.supportedTransports.includes("usb"));
|
|
2507
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2508
|
+
(connection) => connection.transport === "usb"
|
|
2509
|
+
);
|
|
2510
|
+
const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : targetConnectId;
|
|
2511
|
+
const { device, requestId } = await requestBleDeviceSelection({
|
|
2512
|
+
emitter: this.emitter,
|
|
2513
|
+
registry: this._uiRegistry,
|
|
2514
|
+
signal,
|
|
2515
|
+
allowUsbFallback,
|
|
2516
|
+
scan: async () => {
|
|
2517
|
+
if (allowUsbFallback) {
|
|
2518
|
+
const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
|
|
2519
|
+
const candidate = usbDevices.find(
|
|
2520
|
+
(device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
|
|
2521
|
+
) ?? (usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
|
|
2522
|
+
if (candidate) return [candidate];
|
|
2523
|
+
}
|
|
2524
|
+
return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
|
|
2525
|
+
},
|
|
2526
|
+
request: {
|
|
2527
|
+
devices,
|
|
2528
|
+
bindingSessionId,
|
|
2529
|
+
context: {
|
|
2530
|
+
kind: "bind-connection",
|
|
2531
|
+
transport: "ble",
|
|
2532
|
+
reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
|
|
2533
|
+
},
|
|
2534
|
+
extra: context?.extra,
|
|
2535
|
+
operationId: preserveOperationId
|
|
2536
|
+
}
|
|
2537
|
+
});
|
|
2538
|
+
if (device.connectionType === "usb") {
|
|
2539
|
+
this._activeConnectionType = "usb";
|
|
2540
|
+
if (context) context.selectedConnection = void 0;
|
|
2541
|
+
this._bindingSelectionRequestId = requestId;
|
|
2542
|
+
this._finishBleBinding("cancelled");
|
|
2543
|
+
return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
|
|
2544
|
+
}
|
|
2545
|
+
this._bindingSelectionRequestId = requestId;
|
|
2546
|
+
const connected = await this._connectDeviceOrThrow(
|
|
2547
|
+
device.connectId,
|
|
2548
|
+
preserveOperationId,
|
|
2549
|
+
signal
|
|
2550
|
+
);
|
|
2551
|
+
if (context) context.selectedConnection = { connectId: connected, requestId };
|
|
2552
|
+
if (context?.deferBindingSave) {
|
|
2553
|
+
context.pendingBinding = { connectId: connected, requestId };
|
|
2554
|
+
} else {
|
|
2555
|
+
await this._saveSelectedBleBinding(
|
|
2556
|
+
connected,
|
|
2557
|
+
requestId,
|
|
2558
|
+
context,
|
|
2559
|
+
preserveOperationId,
|
|
2560
|
+
signal
|
|
2561
|
+
);
|
|
2562
|
+
}
|
|
2563
|
+
return connected;
|
|
2564
|
+
}
|
|
2565
|
+
if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
|
|
2566
|
+
if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(UI_REQUEST.REQUEST_SELECT_DEVICE)) {
|
|
2567
|
+
throw createHwkError({
|
|
2568
|
+
code: HardwareErrorCode3.DeviceNotFound,
|
|
2569
|
+
message: "Select a Ledger device before continuing"
|
|
2570
|
+
});
|
|
2571
|
+
}
|
|
2572
|
+
const requestId = this._uiRegistry.createRequestId();
|
|
2573
|
+
const operationId = this._activeOperationId();
|
|
2574
|
+
const waitPromise = this._uiRegistry.wait(
|
|
2575
|
+
UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2576
|
+
{ requestId, operationId }
|
|
2577
|
+
);
|
|
2578
|
+
this.emitter.emit(UI_REQUEST.REQUEST_SELECT_DEVICE, {
|
|
2579
|
+
type: UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2580
|
+
payload: {
|
|
2581
|
+
devices,
|
|
2582
|
+
requestId,
|
|
2583
|
+
operationId,
|
|
2584
|
+
context: requiresBleSelection ? {
|
|
2585
|
+
kind: "bind-connection",
|
|
2586
|
+
transport: "ble",
|
|
2587
|
+
reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
|
|
2588
|
+
} : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
|
|
2589
|
+
extra: context?.extra
|
|
2590
|
+
}
|
|
2591
|
+
});
|
|
2592
|
+
const { sdkConnectId } = await this._abortable(signal, waitPromise);
|
|
2593
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
2594
|
+
const selected = devices.find((device) => device.connectId === sdkConnectId);
|
|
2595
|
+
if (!selected) {
|
|
2596
|
+
throw Object.assign(new Error("Selected Ledger is no longer available"), {
|
|
2597
|
+
code: HardwareErrorCode3.DeviceNotFound
|
|
2598
|
+
});
|
|
2599
|
+
}
|
|
2600
|
+
if (context && requiresBleSelection)
|
|
2601
|
+
context.selectedConnection = { connectId: selected.connectId, requestId };
|
|
2602
|
+
return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
|
|
1719
2603
|
}
|
|
1720
2604
|
if (devices.length !== 1) {
|
|
1721
2605
|
throw Object.assign(new Error("Ledger device not found."), {
|
|
1722
2606
|
code: HardwareErrorCode3.DeviceNotFound
|
|
1723
2607
|
});
|
|
1724
2608
|
}
|
|
1725
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2609
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1726
2610
|
}
|
|
1727
|
-
async _connectDeviceOrThrow(chosenConnectId) {
|
|
1728
|
-
const result = await this.
|
|
2611
|
+
async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
|
|
2612
|
+
const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
|
|
1729
2613
|
if (!result.success) {
|
|
1730
2614
|
const payload = result.payload;
|
|
1731
2615
|
const rethrow = Object.assign(new Error(payload.error), {
|
|
@@ -1736,16 +2620,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1736
2620
|
}
|
|
1737
2621
|
throw rethrow;
|
|
1738
2622
|
}
|
|
1739
|
-
return
|
|
2623
|
+
return result.payload;
|
|
1740
2624
|
}
|
|
1741
|
-
/**
|
|
1742
|
-
* Call the connector with automatic session resolution and disconnect retry.
|
|
1743
|
-
*
|
|
1744
|
-
* 1. Resolves a valid connectId via ensureConnected()
|
|
1745
|
-
* 2. Looks up sessionId from _sessions
|
|
1746
|
-
* 3. Calls connector.call()
|
|
1747
|
-
* 4. On disconnect error: clears stale session, re-connects, retries once
|
|
1748
|
-
*/
|
|
1749
2625
|
/**
|
|
1750
2626
|
* Unwrap a `ConnectorCallResult` back into the throw-based control flow this
|
|
1751
2627
|
* class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
|
|
@@ -1766,33 +2642,145 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1766
2642
|
* lives in one place.
|
|
1767
2643
|
*/
|
|
1768
2644
|
async _callConnector(sessionId, method, params, signal) {
|
|
1769
|
-
|
|
2645
|
+
this._assertConnectorReady(method);
|
|
2646
|
+
if (signal?.aborted) throw this._abortReason(signal);
|
|
2647
|
+
const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
|
|
2648
|
+
let promise;
|
|
2649
|
+
try {
|
|
2650
|
+
promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
|
|
2651
|
+
} catch (error) {
|
|
2652
|
+
releaseOperation();
|
|
2653
|
+
throw error;
|
|
2654
|
+
}
|
|
1770
2655
|
const result = signal ? await this._abortable(signal, promise) : await promise;
|
|
1771
2656
|
return this._unwrapConnectorResult(result);
|
|
1772
2657
|
}
|
|
2658
|
+
_assertConnectorReady(method) {
|
|
2659
|
+
if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
|
|
2660
|
+
throw _LedgerAdapter._createDeviceBusyError(method);
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
_runConnectorTeardown(task) {
|
|
2664
|
+
const previous = this._connectorTeardownTail;
|
|
2665
|
+
let releaseTail = () => void 0;
|
|
2666
|
+
this._connectorTeardownTail = new Promise((resolve) => {
|
|
2667
|
+
releaseTail = resolve;
|
|
2668
|
+
});
|
|
2669
|
+
this._pendingConnectorTeardowns += 1;
|
|
2670
|
+
return (async () => {
|
|
2671
|
+
try {
|
|
2672
|
+
await previous;
|
|
2673
|
+
await this._waitForConnectorOperationsToDrain();
|
|
2674
|
+
await task();
|
|
2675
|
+
} finally {
|
|
2676
|
+
this._pendingConnectorTeardowns -= 1;
|
|
2677
|
+
releaseTail();
|
|
2678
|
+
}
|
|
2679
|
+
})();
|
|
2680
|
+
}
|
|
2681
|
+
_waitForConnectorOperationsToDrain() {
|
|
2682
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2683
|
+
return Promise.resolve();
|
|
2684
|
+
}
|
|
2685
|
+
return new Promise((resolve) => {
|
|
2686
|
+
this._connectorIdleWaiters.add(resolve);
|
|
2687
|
+
});
|
|
2688
|
+
}
|
|
2689
|
+
_retainConnectorOperation(key) {
|
|
2690
|
+
this._unsettledConnectorOperations.set(
|
|
2691
|
+
key,
|
|
2692
|
+
(this._unsettledConnectorOperations.get(key) ?? 0) + 1
|
|
2693
|
+
);
|
|
2694
|
+
let released = false;
|
|
2695
|
+
return () => {
|
|
2696
|
+
if (released) return;
|
|
2697
|
+
released = true;
|
|
2698
|
+
const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
|
|
2699
|
+
if (remaining > 0) {
|
|
2700
|
+
this._unsettledConnectorOperations.set(key, remaining);
|
|
2701
|
+
} else {
|
|
2702
|
+
this._unsettledConnectorOperations.delete(key);
|
|
2703
|
+
}
|
|
2704
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2705
|
+
for (const resolve of this._connectorIdleWaiters) resolve();
|
|
2706
|
+
this._connectorIdleWaiters.clear();
|
|
2707
|
+
}
|
|
2708
|
+
};
|
|
2709
|
+
}
|
|
1773
2710
|
async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
1774
|
-
|
|
1775
|
-
|
|
2711
|
+
const positionalOperationId = isHardwareOperationId(connectId) ? connectId : void 0;
|
|
2712
|
+
if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
|
|
2713
|
+
throw createHwkError({
|
|
2714
|
+
code: HardwareErrorCode3.InvalidParams,
|
|
2715
|
+
message: "Conflicting Ledger operation ids",
|
|
2716
|
+
params: {
|
|
2717
|
+
positionalOperationId,
|
|
2718
|
+
commonOperationId: commonParams.operationId
|
|
2719
|
+
}
|
|
2720
|
+
});
|
|
2721
|
+
}
|
|
2722
|
+
const operationId = commonParams?.operationId ?? positionalOperationId;
|
|
2723
|
+
const operation = operationId ? this._operations.resolve(operationId) : void 0;
|
|
2724
|
+
const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
|
|
2725
|
+
const effectiveConnectId = operation?.connectId ?? connectId;
|
|
2726
|
+
debugLog("[LedgerAdapter][REQ]", {
|
|
2727
|
+
method,
|
|
2728
|
+
connectId: effectiveConnectId || "(empty)",
|
|
2729
|
+
params: summarizeForLog(params, { method })
|
|
2730
|
+
});
|
|
2731
|
+
const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
|
|
1776
2732
|
try {
|
|
1777
2733
|
const result = await this._jobQueue.enqueue(
|
|
1778
2734
|
queueKey,
|
|
1779
|
-
async (signal) =>
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
2735
|
+
async (signal) => {
|
|
2736
|
+
if (operationId) this._activeOperationJobs.add(operationId);
|
|
2737
|
+
try {
|
|
2738
|
+
return await this._runConnectorCall(
|
|
2739
|
+
effectiveConnectId,
|
|
2740
|
+
method,
|
|
2741
|
+
params,
|
|
2742
|
+
signal,
|
|
2743
|
+
fingerprint,
|
|
2744
|
+
permissionDeviceId,
|
|
2745
|
+
commonParams,
|
|
2746
|
+
installContext ?? {},
|
|
2747
|
+
operationId
|
|
2748
|
+
);
|
|
2749
|
+
} catch (error) {
|
|
2750
|
+
const status = signal.aborted ? "cancelled" : "failed";
|
|
2751
|
+
const bundleConnectId = installContext?.connection?.connectId;
|
|
2752
|
+
let keptBundlePick = false;
|
|
2753
|
+
for (const [pickedConnectId, owner] of this._pendingPickBindings) {
|
|
2754
|
+
if (pickedConnectId === bundleConnectId) {
|
|
2755
|
+
keptBundlePick = true;
|
|
2756
|
+
} else {
|
|
2757
|
+
this._pendingPickBindings.delete(pickedConnectId);
|
|
2758
|
+
this._discardPendingBinding(owner, status);
|
|
2759
|
+
await this._dropSession(pickedConnectId, signal);
|
|
2760
|
+
}
|
|
2761
|
+
}
|
|
2762
|
+
if (!keptBundlePick) this._finishBleBinding(status);
|
|
2763
|
+
throw error;
|
|
2764
|
+
} finally {
|
|
2765
|
+
if (operationId) {
|
|
2766
|
+
this._activeOperationJobs.delete(operationId);
|
|
2767
|
+
if (this._pendingOperationDisconnects.delete(operationId)) {
|
|
2768
|
+
await this._releaseLostOperationConnection(operationId);
|
|
2769
|
+
}
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
},
|
|
1789
2773
|
{
|
|
1790
2774
|
label: method,
|
|
1791
2775
|
rejectIfBusy: true,
|
|
1792
2776
|
busyError: _LedgerAdapter._createDeviceBusyError(method)
|
|
1793
2777
|
}
|
|
1794
2778
|
);
|
|
1795
|
-
debugLog("[LedgerAdapter][RES]", {
|
|
2779
|
+
debugLog("[LedgerAdapter][RES]", {
|
|
2780
|
+
method,
|
|
2781
|
+
success: true,
|
|
2782
|
+
payload: summarizeForLog(result, { method, role: "result" })
|
|
2783
|
+
});
|
|
1796
2784
|
return result;
|
|
1797
2785
|
} catch (err) {
|
|
1798
2786
|
const e = err;
|
|
@@ -1806,15 +2794,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1806
2794
|
}
|
|
1807
2795
|
});
|
|
1808
2796
|
throw err;
|
|
2797
|
+
} finally {
|
|
2798
|
+
releaseOperationRetention?.();
|
|
1809
2799
|
}
|
|
1810
2800
|
}
|
|
2801
|
+
/** Hermes/RN polyfills don't always populate signal.reason; fall back. */
|
|
2802
|
+
_abortReason(signal) {
|
|
2803
|
+
return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
|
|
2804
|
+
}
|
|
1811
2805
|
/**
|
|
1812
2806
|
* Race a promise against an abort signal. On abort, rejects with
|
|
1813
2807
|
* signal.reason → instance _lastCancelReason → generic Error('Aborted').
|
|
1814
2808
|
*/
|
|
1815
2809
|
_abortable(signal, promise) {
|
|
1816
|
-
const getAbortReason = () =>
|
|
2810
|
+
const getAbortReason = () => this._abortReason(signal);
|
|
1817
2811
|
if (signal.aborted) {
|
|
2812
|
+
void promise.catch(() => void 0);
|
|
1818
2813
|
return Promise.reject(getAbortReason());
|
|
1819
2814
|
}
|
|
1820
2815
|
return new Promise((resolve, reject) => {
|
|
@@ -1841,17 +2836,19 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1841
2836
|
}
|
|
1842
2837
|
}
|
|
1843
2838
|
/** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
|
|
1844
|
-
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
2839
|
+
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
|
|
1845
2840
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
2841
|
+
if (!operationId) {
|
|
2842
|
+
await this._ensureDevicePermission(
|
|
2843
|
+
connectId,
|
|
2844
|
+
permissionDeviceId ?? fingerprint?.deviceId,
|
|
2845
|
+
signal
|
|
2846
|
+
);
|
|
2847
|
+
}
|
|
1851
2848
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1852
2849
|
let effectiveParams = params;
|
|
1853
2850
|
if (method === "btcGetPublicKey") {
|
|
1854
|
-
const gatedParams = await this._gateBtcHighIndex(params);
|
|
2851
|
+
const gatedParams = await this._gateBtcHighIndex(params, signal);
|
|
1855
2852
|
if (gatedParams === null) {
|
|
1856
2853
|
throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
|
|
1857
2854
|
_tag: ERROR_TAG.UserAborted,
|
|
@@ -1861,19 +2858,67 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1861
2858
|
effectiveParams = gatedParams;
|
|
1862
2859
|
}
|
|
1863
2860
|
const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
|
|
1864
|
-
|
|
1865
|
-
|
|
2861
|
+
let businessCallStarted = false;
|
|
2862
|
+
const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
|
|
2863
|
+
const knownTransport = this._isBleConnection() ? "ble" : "usb";
|
|
2864
|
+
const hintedConnectId = commonParams?.knownConnections?.find(
|
|
2865
|
+
(connection) => connection.transport === knownTransport
|
|
2866
|
+
);
|
|
2867
|
+
const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
|
|
2868
|
+
const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
|
|
2869
|
+
const checksWallet = Boolean(
|
|
2870
|
+
fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId
|
|
2871
|
+
);
|
|
2872
|
+
const connectionAttempt = {
|
|
2873
|
+
...commonParams,
|
|
2874
|
+
deferBindingSave: checksWallet
|
|
2875
|
+
};
|
|
2876
|
+
const bundleConnection = installContext?.connection;
|
|
2877
|
+
if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
|
|
2878
|
+
throw createHwkError({
|
|
2879
|
+
code: HardwareErrorCode3.DeviceDisconnected,
|
|
2880
|
+
message: "Ledger all-network connection ended"
|
|
2881
|
+
});
|
|
2882
|
+
}
|
|
2883
|
+
const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
|
|
2884
|
+
preferredConnectId,
|
|
1866
2885
|
signal,
|
|
1867
|
-
allowUsbEphemeralFallback
|
|
2886
|
+
allowUsbEphemeralFallback,
|
|
2887
|
+
void 0,
|
|
2888
|
+
connectionAttempt
|
|
1868
2889
|
);
|
|
2890
|
+
const walletCheck = installContext?.walletCheck;
|
|
2891
|
+
if (walletCheck && !checksWallet && (walletCheck.verified === false || walletCheck.expected && !walletCheck.verified)) {
|
|
2892
|
+
throw createHwkError({
|
|
2893
|
+
code: HardwareErrorCode3.DeviceMismatch,
|
|
2894
|
+
message: "Ledger wallet is not verified on this connection; refusing to derive an unverifiable address"
|
|
2895
|
+
});
|
|
2896
|
+
}
|
|
1869
2897
|
const sessionId = this._sessions.get(resolvedConnectId);
|
|
2898
|
+
if (sessionId && installContext && !installContext.connection) {
|
|
2899
|
+
installContext.connection = { connectId: resolvedConnectId, sessionId };
|
|
2900
|
+
}
|
|
1870
2901
|
if (!sessionId) {
|
|
2902
|
+
if (operationId) {
|
|
2903
|
+
this._operations.end(operationId, "disconnect");
|
|
2904
|
+
throw createHwkError({
|
|
2905
|
+
code: HardwareErrorCode3.OperationEnded,
|
|
2906
|
+
message: "Ledger operation connection is no longer active",
|
|
2907
|
+
params: { operationId, reason: "disconnect" }
|
|
2908
|
+
});
|
|
2909
|
+
}
|
|
1871
2910
|
throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
|
|
1872
2911
|
_tag: ERROR_TAG.DeviceSessionNotFound
|
|
1873
2912
|
});
|
|
1874
2913
|
}
|
|
1875
2914
|
try {
|
|
1876
|
-
|
|
2915
|
+
const isBleSession = this._sessionTransports.get(sessionId) === "ble";
|
|
2916
|
+
if (!operationId && connectionAttempt.pendingBinding) {
|
|
2917
|
+
this._pendingPickBindings.set(resolvedConnectId, connectionAttempt);
|
|
2918
|
+
}
|
|
2919
|
+
const bindingOwner = operationId ? this._pendingOperationBindings.get(operationId) : this._pendingPickBindings.get(resolvedConnectId);
|
|
2920
|
+
const pendingBinding = bindingOwner?.pendingBinding?.connectId === resolvedConnectId ? bindingOwner.pendingBinding : void 0;
|
|
2921
|
+
if (fingerprint && checksWallet) {
|
|
1877
2922
|
const fp = await this._abortable(
|
|
1878
2923
|
signal,
|
|
1879
2924
|
this._verifyDeviceFingerprintWithSession(
|
|
@@ -1883,14 +2928,68 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1883
2928
|
)
|
|
1884
2929
|
);
|
|
1885
2930
|
if (!fp.success) {
|
|
2931
|
+
if (pendingBinding) {
|
|
2932
|
+
this._discardPendingBinding(bindingOwner, "failed");
|
|
2933
|
+
this._pendingPickBindings.delete(resolvedConnectId);
|
|
2934
|
+
}
|
|
2935
|
+
if (operationId) {
|
|
2936
|
+
this._pendingOperationBindings.delete(operationId);
|
|
2937
|
+
this._operations.end(operationId, "explicit");
|
|
2938
|
+
await this._dropSession(resolvedConnectId, signal);
|
|
2939
|
+
}
|
|
1886
2940
|
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
1887
2941
|
code: HardwareErrorCode3.DeviceMismatch
|
|
1888
2942
|
});
|
|
1889
2943
|
}
|
|
2944
|
+
if (walletCheck) walletCheck.verified = true;
|
|
2945
|
+
}
|
|
2946
|
+
if (pendingBinding && bindingOwner) {
|
|
2947
|
+
bindingOwner.pendingBinding = void 0;
|
|
2948
|
+
if (operationId) this._pendingOperationBindings.delete(operationId);
|
|
2949
|
+
else this._pendingPickBindings.delete(resolvedConnectId);
|
|
2950
|
+
await this._saveSelectedBleBinding(
|
|
2951
|
+
pendingBinding.connectId,
|
|
2952
|
+
pendingBinding.requestId,
|
|
2953
|
+
bindingOwner,
|
|
2954
|
+
operationId,
|
|
2955
|
+
signal,
|
|
2956
|
+
fingerprint && checksWallet ? {
|
|
2957
|
+
vendor: "ledger",
|
|
2958
|
+
type: "chainFingerprint",
|
|
2959
|
+
chain: fingerprint.chain,
|
|
2960
|
+
value: fingerprint.deviceId
|
|
2961
|
+
} : void 0
|
|
2962
|
+
);
|
|
2963
|
+
}
|
|
2964
|
+
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
|
|
2965
|
+
this._selectedBleReconnectTargets.set(connectId, {
|
|
2966
|
+
connectId: resolvedConnectId,
|
|
2967
|
+
chain: fingerprint.chain,
|
|
2968
|
+
fingerprint: fingerprint.deviceId
|
|
2969
|
+
});
|
|
1890
2970
|
}
|
|
1891
|
-
|
|
2971
|
+
businessCallStarted = true;
|
|
2972
|
+
const result = await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
2973
|
+
if (walletCheck) walletCheck.derived = true;
|
|
2974
|
+
return result;
|
|
1892
2975
|
} catch (err) {
|
|
1893
2976
|
if (signal.aborted) throw err;
|
|
2977
|
+
if (isLostConnectionError(err)) {
|
|
2978
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
2979
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
2980
|
+
else {
|
|
2981
|
+
this._sessions.delete(resolvedConnectId);
|
|
2982
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
2983
|
+
}
|
|
2984
|
+
const ambiguous = businessCallStarted && !canReplayHardwareMethodAfterTransportFailure(method);
|
|
2985
|
+
const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
|
|
2986
|
+
throw createHwkError({
|
|
2987
|
+
code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(err).code,
|
|
2988
|
+
message: "Ledger operation connection was lost; start a new operation",
|
|
2989
|
+
params: ambiguous ? operationMayHaveCompletedParams(method, { operationId }) : interactionParams,
|
|
2990
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
2991
|
+
});
|
|
2992
|
+
}
|
|
1894
2993
|
const errObj = err;
|
|
1895
2994
|
debugLog("[LedgerAdapter] connectorCall error:", method, {
|
|
1896
2995
|
message: errObj?.message,
|
|
@@ -1902,6 +3001,64 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1902
3001
|
isNotAdvertising: isDeviceNotAdvertisingError(err),
|
|
1903
3002
|
isStuckApp: isStuckAppStateError(err)
|
|
1904
3003
|
});
|
|
3004
|
+
const assertSessionCurrent = (message) => {
|
|
3005
|
+
if (this._sessions.get(resolvedConnectId) === sessionId) return;
|
|
3006
|
+
throw createHwkError({
|
|
3007
|
+
code: operationId ? HardwareErrorCode3.OperationEnded : HardwareErrorCode3.DeviceDisconnected,
|
|
3008
|
+
message
|
|
3009
|
+
});
|
|
3010
|
+
};
|
|
3011
|
+
if ((isDeviceLockedError(err) || errObj?.code === HardwareErrorCode3.DeviceLocked) && lockedRetryBudget > 0) {
|
|
3012
|
+
await this._waitForDeviceConnect(signal);
|
|
3013
|
+
assertSessionCurrent("Ledger connection ended while waiting for unlock");
|
|
3014
|
+
if (walletCheck?.derived) walletCheck.verified = false;
|
|
3015
|
+
return this._runConnectorCall(
|
|
3016
|
+
resolvedConnectId,
|
|
3017
|
+
method,
|
|
3018
|
+
effectiveParams,
|
|
3019
|
+
signal,
|
|
3020
|
+
fingerprint,
|
|
3021
|
+
permissionDeviceId,
|
|
3022
|
+
commonParams,
|
|
3023
|
+
installContext,
|
|
3024
|
+
operationId,
|
|
3025
|
+
lockedRetryBudget - 1
|
|
3026
|
+
);
|
|
3027
|
+
}
|
|
3028
|
+
if (businessCallStarted && isStuckAppStateError(err)) {
|
|
3029
|
+
await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
|
|
3030
|
+
assertSessionCurrent("Ledger connection ended during the app transition");
|
|
3031
|
+
try {
|
|
3032
|
+
const retried = await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
3033
|
+
if (walletCheck) walletCheck.derived = true;
|
|
3034
|
+
return retried;
|
|
3035
|
+
} catch (retryErr) {
|
|
3036
|
+
if (isStuckAppStateError(retryErr)) throw err;
|
|
3037
|
+
if (isLostConnectionError(retryErr)) {
|
|
3038
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
3039
|
+
else {
|
|
3040
|
+
this._sessions.delete(resolvedConnectId);
|
|
3041
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3042
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3043
|
+
}
|
|
3044
|
+
const ambiguous = !canReplayHardwareMethodAfterTransportFailure(method);
|
|
3045
|
+
throw createHwkError({
|
|
3046
|
+
code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(retryErr).code,
|
|
3047
|
+
message: `Ledger ${method} may have completed before the connection was lost`,
|
|
3048
|
+
params: ambiguous ? operationMayHaveCompletedParams(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
|
|
3049
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
3050
|
+
});
|
|
3051
|
+
}
|
|
3052
|
+
throw retryErr;
|
|
3053
|
+
}
|
|
3054
|
+
}
|
|
3055
|
+
if (!operationId && errObj?.code === HardwareErrorCode3.DeviceMismatch) {
|
|
3056
|
+
this._sessions.delete(resolvedConnectId);
|
|
3057
|
+
this._sessionTransports.delete(sessionId);
|
|
3058
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3059
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3060
|
+
throw err;
|
|
3061
|
+
}
|
|
1905
3062
|
const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
|
|
1906
3063
|
const isAppMissing = isAppNotInstalledError(err) || err?.code === HardwareErrorCode3.AppNotInstalled;
|
|
1907
3064
|
if (autoInstallApp && isAppMissing) {
|
|
@@ -1918,7 +3075,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1918
3075
|
appName
|
|
1919
3076
|
});
|
|
1920
3077
|
}
|
|
1921
|
-
const confirmed = await this._waitForInstallAppConfirm(appName);
|
|
3078
|
+
const confirmed = await this._waitForInstallAppConfirm(appName, signal);
|
|
1922
3079
|
if (!confirmed) {
|
|
1923
3080
|
throw createHwkError({
|
|
1924
3081
|
code: HardwareErrorCode3.UserAborted,
|
|
@@ -1957,157 +3114,14 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1957
3114
|
fingerprint,
|
|
1958
3115
|
permissionDeviceId,
|
|
1959
3116
|
commonParams,
|
|
1960
|
-
installContext
|
|
1961
|
-
|
|
1962
|
-
}
|
|
1963
|
-
}
|
|
1964
|
-
if (isStuckAppStateError(err)) {
|
|
1965
|
-
try {
|
|
1966
|
-
this._sessions.delete(resolvedConnectId);
|
|
1967
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
1968
|
-
this.connector.reset?.();
|
|
1969
|
-
} catch {
|
|
1970
|
-
}
|
|
1971
|
-
debugLog(
|
|
1972
|
-
"[LedgerAdapter] stuck-app retry: method=",
|
|
1973
|
-
method,
|
|
1974
|
-
"delayMs=",
|
|
1975
|
-
_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS,
|
|
1976
|
-
"_tag=",
|
|
1977
|
-
err?._tag
|
|
1978
|
-
);
|
|
1979
|
-
try {
|
|
1980
|
-
const retryResult = await this._retryAfterStuckApp(
|
|
1981
|
-
resolvedConnectId,
|
|
1982
|
-
method,
|
|
1983
|
-
effectiveParams,
|
|
1984
|
-
signal,
|
|
1985
|
-
err,
|
|
1986
|
-
fingerprint
|
|
1987
|
-
);
|
|
1988
|
-
debugLog("[LedgerAdapter] stuck-app retry succeeded: method=", method);
|
|
1989
|
-
return retryResult;
|
|
1990
|
-
} catch (retryErr) {
|
|
1991
|
-
if (signal.aborted) throw retryErr;
|
|
1992
|
-
if (isStuckAppStateError(retryErr)) {
|
|
1993
|
-
debugLog("[LedgerAdapter] stuck-app retry exhausted (2nd 6901): method=", method);
|
|
1994
|
-
throw err;
|
|
1995
|
-
}
|
|
1996
|
-
debugLog(
|
|
1997
|
-
"[LedgerAdapter] stuck-app retry threw non-stuck error: method=",
|
|
1998
|
-
method,
|
|
1999
|
-
"retryErrTag=",
|
|
2000
|
-
retryErr?._tag
|
|
3117
|
+
installContext,
|
|
3118
|
+
operationId
|
|
2001
3119
|
);
|
|
2002
|
-
throw retryErr;
|
|
2003
|
-
}
|
|
2004
|
-
}
|
|
2005
|
-
if (isDeviceLockedError(err) || isDeviceNotAdvertisingError(err) || isDeviceDisconnectedError(err)) {
|
|
2006
|
-
let lastErr = err;
|
|
2007
|
-
for (let attempt = 0; attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET; attempt += 1) {
|
|
2008
|
-
if (signal.aborted) throw lastErr;
|
|
2009
|
-
try {
|
|
2010
|
-
this._sessions.delete(resolvedConnectId);
|
|
2011
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2012
|
-
if (isDeviceDisconnectedError(lastErr)) {
|
|
2013
|
-
try {
|
|
2014
|
-
this.connector.reset?.();
|
|
2015
|
-
} catch {
|
|
2016
|
-
}
|
|
2017
|
-
}
|
|
2018
|
-
const reConnectId = await this.ensureConnected(
|
|
2019
|
-
resolvedConnectId,
|
|
2020
|
-
signal,
|
|
2021
|
-
allowUsbEphemeralFallback
|
|
2022
|
-
);
|
|
2023
|
-
const reSessionId = this._sessions.get(reConnectId);
|
|
2024
|
-
if (!reSessionId) throw lastErr;
|
|
2025
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2026
|
-
const fp = await this._abortable(
|
|
2027
|
-
signal,
|
|
2028
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2029
|
-
reSessionId,
|
|
2030
|
-
fingerprint.deviceId,
|
|
2031
|
-
fingerprint.chain
|
|
2032
|
-
)
|
|
2033
|
-
);
|
|
2034
|
-
if (!fp.success) {
|
|
2035
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2036
|
-
code: HardwareErrorCode3.DeviceMismatch
|
|
2037
|
-
});
|
|
2038
|
-
}
|
|
2039
|
-
}
|
|
2040
|
-
return await this._callConnector(reSessionId, method, effectiveParams, signal);
|
|
2041
|
-
} catch (retryErr) {
|
|
2042
|
-
if (signal.aborted) throw retryErr;
|
|
2043
|
-
lastErr = retryErr;
|
|
2044
|
-
const canRetry = attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET - 1 && (isDeviceLockedError(retryErr) || isDeviceNotAdvertisingError(retryErr) || isDeviceDisconnectedError(retryErr));
|
|
2045
|
-
if (!canRetry) {
|
|
2046
|
-
throw retryErr;
|
|
2047
|
-
}
|
|
2048
|
-
}
|
|
2049
3120
|
}
|
|
2050
|
-
throw lastErr;
|
|
2051
|
-
}
|
|
2052
|
-
if (isTimeoutError(err)) {
|
|
2053
|
-
debugLog("[LedgerAdapter] timeout, retrying with fresh connection...");
|
|
2054
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2055
|
-
return this._retryWithFreshConnection(
|
|
2056
|
-
resolvedConnectId,
|
|
2057
|
-
method,
|
|
2058
|
-
effectiveParams,
|
|
2059
|
-
signal,
|
|
2060
|
-
err,
|
|
2061
|
-
fingerprint
|
|
2062
|
-
);
|
|
2063
|
-
}
|
|
2064
|
-
if (isConnectionLevelError(err)) {
|
|
2065
|
-
debugLog("[LedgerAdapter] connection-level fail-closed reset");
|
|
2066
|
-
this._sessions.delete(resolvedConnectId);
|
|
2067
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2068
|
-
this.connector.reset();
|
|
2069
|
-
const codeNum = err?.code;
|
|
2070
|
-
throw Object.assign(err, {
|
|
2071
|
-
code: codeNum ?? HardwareErrorCode3.DeviceDisconnected
|
|
2072
|
-
});
|
|
2073
3121
|
}
|
|
2074
3122
|
throw err;
|
|
2075
3123
|
}
|
|
2076
3124
|
}
|
|
2077
|
-
/**
|
|
2078
|
-
* Stuck-app recovery: pause for the device's UI transition, then retry once.
|
|
2079
|
-
*
|
|
2080
|
-
* Caller has already cleared the session + reset connector. We wait so Stax
|
|
2081
|
-
* finishes its post-CloseApp animation, then go through ensureConnected +
|
|
2082
|
-
* fingerprint check + call exactly once. Caller decides what to do on a
|
|
2083
|
-
* second stuck-app hit.
|
|
2084
|
-
*/
|
|
2085
|
-
async _retryAfterStuckApp(resolvedConnectId, method, params, signal, originalErr, fingerprint) {
|
|
2086
|
-
await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
|
|
2087
|
-
const retryConnectId = await this.ensureConnected(
|
|
2088
|
-
resolvedConnectId,
|
|
2089
|
-
signal,
|
|
2090
|
-
!!fingerprint?.deviceId && !fingerprint.skipFingerprint
|
|
2091
|
-
);
|
|
2092
|
-
const retrySessionId = this._sessions.get(retryConnectId);
|
|
2093
|
-
if (!retrySessionId) throw originalErr;
|
|
2094
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2095
|
-
const fp = await this._abortable(
|
|
2096
|
-
signal,
|
|
2097
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2098
|
-
retrySessionId,
|
|
2099
|
-
fingerprint.deviceId,
|
|
2100
|
-
fingerprint.chain
|
|
2101
|
-
)
|
|
2102
|
-
);
|
|
2103
|
-
if (!fp.success) {
|
|
2104
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2105
|
-
code: HardwareErrorCode3.DeviceMismatch
|
|
2106
|
-
});
|
|
2107
|
-
}
|
|
2108
|
-
}
|
|
2109
|
-
return this._callConnector(retrySessionId, method, params, signal);
|
|
2110
|
-
}
|
|
2111
3125
|
_sleepAbortable(ms, signal) {
|
|
2112
3126
|
return new Promise((resolve, reject) => {
|
|
2113
3127
|
if (signal.aborted) {
|
|
@@ -2126,111 +3140,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2126
3140
|
});
|
|
2127
3141
|
}
|
|
2128
3142
|
/**
|
|
2129
|
-
*
|
|
2130
|
-
*
|
|
2131
|
-
* Timeout recovery starts with a full connector reset. After an APDU
|
|
2132
|
-
* timeout, DMK/transport state may still emit malformed responses; retrying
|
|
2133
|
-
* on the same DMK can poison the next chain switch.
|
|
2134
|
-
*/
|
|
2135
|
-
async _retryWithFreshConnection(targetConnectId, method, params, signal, originalErr, fingerprint) {
|
|
2136
|
-
this.connector.reset();
|
|
2137
|
-
this._sessions.clear();
|
|
2138
|
-
this._discoveredDevices.clear();
|
|
2139
|
-
this._connectingPromise = null;
|
|
2140
|
-
const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
|
|
2141
|
-
const retryConnectId = await this.ensureConnected(
|
|
2142
|
-
targetConnectId,
|
|
2143
|
-
signal,
|
|
2144
|
-
allowUsbEphemeralFallback
|
|
2145
|
-
);
|
|
2146
|
-
const retrySessionId = this._sessions.get(retryConnectId);
|
|
2147
|
-
if (!retrySessionId) {
|
|
2148
|
-
throw originalErr;
|
|
2149
|
-
}
|
|
2150
|
-
try {
|
|
2151
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2152
|
-
const fp = await this._abortable(
|
|
2153
|
-
signal,
|
|
2154
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2155
|
-
retrySessionId,
|
|
2156
|
-
fingerprint.deviceId,
|
|
2157
|
-
fingerprint.chain
|
|
2158
|
-
)
|
|
2159
|
-
);
|
|
2160
|
-
if (!fp.success) {
|
|
2161
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2162
|
-
code: HardwareErrorCode3.DeviceMismatch
|
|
2163
|
-
});
|
|
2164
|
-
}
|
|
2165
|
-
}
|
|
2166
|
-
return await this._callConnector(retrySessionId, method, params, signal);
|
|
2167
|
-
} catch (retryErr) {
|
|
2168
|
-
if (signal.aborted) throw retryErr;
|
|
2169
|
-
this.connector.reset();
|
|
2170
|
-
this._sessions.clear();
|
|
2171
|
-
this._discoveredDevices.clear();
|
|
2172
|
-
this._connectingPromise = null;
|
|
2173
|
-
if (!isDeviceDisconnectedError(retryErr) && !isTimeoutError(retryErr)) {
|
|
2174
|
-
throw retryErr;
|
|
2175
|
-
}
|
|
2176
|
-
debugLog(
|
|
2177
|
-
"[LedgerAdapter] fresh-session retry still failed; resetting connector and rebuilding DMK"
|
|
2178
|
-
);
|
|
2179
|
-
this.connector.reset();
|
|
2180
|
-
this._sessions.clear();
|
|
2181
|
-
this._discoveredDevices.clear();
|
|
2182
|
-
this._connectingPromise = null;
|
|
2183
|
-
const finalConnectId = await this.ensureConnected(
|
|
2184
|
-
targetConnectId,
|
|
2185
|
-
signal,
|
|
2186
|
-
allowUsbEphemeralFallback
|
|
2187
|
-
);
|
|
2188
|
-
const finalSessionId = this._sessions.get(finalConnectId);
|
|
2189
|
-
if (!finalSessionId) {
|
|
2190
|
-
throw originalErr;
|
|
2191
|
-
}
|
|
2192
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2193
|
-
const fp = await this._abortable(
|
|
2194
|
-
signal,
|
|
2195
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2196
|
-
finalSessionId,
|
|
2197
|
-
fingerprint.deviceId,
|
|
2198
|
-
fingerprint.chain
|
|
2199
|
-
)
|
|
2200
|
-
);
|
|
2201
|
-
if (!fp.success) {
|
|
2202
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2203
|
-
code: HardwareErrorCode3.DeviceMismatch
|
|
2204
|
-
});
|
|
2205
|
-
}
|
|
2206
|
-
}
|
|
2207
|
-
return this._callConnector(finalSessionId, method, params, signal);
|
|
2208
|
-
}
|
|
2209
|
-
}
|
|
2210
|
-
/**
|
|
2211
|
-
* Ensure OS-level device permission (Bluetooth / USB) before proceeding.
|
|
2212
|
-
*
|
|
2213
|
-
* Emits `REQUEST_DEVICE_PERMISSION` and awaits the consumer's
|
|
2214
|
-
* `RECEIVE_DEVICE_PERMISSION` reply (60s budget covers "probe → system
|
|
2215
|
-
* prompt → user tap" plus a generous margin). If the consumer never wires
|
|
2216
|
-
* a handler or never replies, the wait times out and the operation fails
|
|
2217
|
-
* fast so scanners/callers don't hang silently.
|
|
2218
|
-
*
|
|
2219
|
-
* - No connectId (searchDevices): environment-level permission
|
|
2220
|
-
* - With connectId (business methods): device-level permission
|
|
3143
|
+
* Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
|
|
3144
|
+
* replies. Without connectId the request is environment-level, else device-level.
|
|
2221
3145
|
*/
|
|
2222
3146
|
async _ensureDevicePermission(connectId, deviceId, signal) {
|
|
2223
3147
|
if (signal?.aborted) {
|
|
2224
3148
|
_LedgerAdapter._throwIfAborted(signal);
|
|
2225
3149
|
}
|
|
2226
3150
|
const transportType = this.activeTransport ?? "hid";
|
|
3151
|
+
const operationId = this._activeOperationId();
|
|
2227
3152
|
const waitPromise = this._uiRegistry.wait(
|
|
2228
3153
|
UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
2229
|
-
{ timeoutMs: 6e4 }
|
|
3154
|
+
{ timeoutMs: 6e4, operationId }
|
|
2230
3155
|
);
|
|
2231
3156
|
this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
|
|
2232
3157
|
type: UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
2233
|
-
payload: { transportType, connectId, deviceId }
|
|
3158
|
+
payload: { transportType, connectId, deviceId, operationId }
|
|
2234
3159
|
});
|
|
2235
3160
|
let response;
|
|
2236
3161
|
const onAbort = () => {
|
|
@@ -2276,7 +3201,15 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2276
3201
|
if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
|
|
2277
3202
|
const e = err;
|
|
2278
3203
|
const params = e.code === HardwareErrorCode3.DevicePermissionDenied && e.reason ? { permissionDeniedReason: e.reason } : e.params;
|
|
2279
|
-
return ledgerFailure(
|
|
3204
|
+
return ledgerFailure(
|
|
3205
|
+
e.code,
|
|
3206
|
+
e.message ?? "Unknown error",
|
|
3207
|
+
e.appName,
|
|
3208
|
+
tag,
|
|
3209
|
+
params,
|
|
3210
|
+
void 0,
|
|
3211
|
+
isHwkRecoveryHint(e.recovery) ? e.recovery : void 0
|
|
3212
|
+
);
|
|
2280
3213
|
}
|
|
2281
3214
|
const mapped = mapLedgerError(err);
|
|
2282
3215
|
return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
|
|
@@ -2303,7 +3236,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2303
3236
|
deviceId: device.deviceId,
|
|
2304
3237
|
connectId: device.connectId,
|
|
2305
3238
|
label: device.name,
|
|
2306
|
-
connectionType: this.connector.connectionType,
|
|
3239
|
+
connectionType: device.connectionType ?? this.connector.connectionType,
|
|
2307
3240
|
rssi: device.rssi,
|
|
2308
3241
|
isConnectable: device.isConnectable,
|
|
2309
3242
|
serialNumber: device.serialNumber,
|
|
@@ -2329,8 +3262,8 @@ var LedgerAdapter = _LedgerAdapter;
|
|
|
2329
3262
|
|
|
2330
3263
|
// src/connector/LedgerConnectorBase.ts
|
|
2331
3264
|
import {
|
|
2332
|
-
EConnectorInteraction as
|
|
2333
|
-
HardwareErrorCode as
|
|
3265
|
+
EConnectorInteraction as EConnectorInteraction3,
|
|
3266
|
+
HardwareErrorCode as HardwareErrorCode7,
|
|
2334
3267
|
isKnownNonTargetHardwareVendor,
|
|
2335
3268
|
serializeConnectorError
|
|
2336
3269
|
} from "@onekeyfe/hwk-adapter-core";
|
|
@@ -2603,7 +3536,7 @@ var LedgerDeviceManager = class {
|
|
|
2603
3536
|
|
|
2604
3537
|
// src/signer/SignerManager.ts
|
|
2605
3538
|
import { SignerEthBuilder } from "@ledgerhq/device-signer-kit-ethereum";
|
|
2606
|
-
import { ContextModuleBuilder } from "@ledgerhq/context-module";
|
|
3539
|
+
import { ContextModuleBuilder, ContextModuleChainID } from "@ledgerhq/context-module";
|
|
2607
3540
|
|
|
2608
3541
|
// src/signer/SignerEth.ts
|
|
2609
3542
|
import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
|
|
@@ -2611,6 +3544,7 @@ import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
|
|
|
2611
3544
|
// src/signer/deviceActionToPromise.ts
|
|
2612
3545
|
import { DeviceActionStatus } from "@ledgerhq/device-management-kit";
|
|
2613
3546
|
var IDLE_WATCHDOG_MS = 65e3;
|
|
3547
|
+
var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
|
|
2614
3548
|
function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
|
|
2615
3549
|
return new Promise((resolve, reject) => {
|
|
2616
3550
|
let settled = false;
|
|
@@ -2798,7 +3732,6 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
|
|
|
2798
3732
|
}
|
|
2799
3733
|
|
|
2800
3734
|
// src/signer/SignerEth.ts
|
|
2801
|
-
var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
|
|
2802
3735
|
var SignerEth = class {
|
|
2803
3736
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
2804
3737
|
constructor(_sdk) {
|
|
@@ -2869,7 +3802,7 @@ var SignerManager = class _SignerManager {
|
|
|
2869
3802
|
return (args) => new SignerEthBuilder(args);
|
|
2870
3803
|
}
|
|
2871
3804
|
static _createContextModule() {
|
|
2872
|
-
const contextModule = new ContextModuleBuilder({}).removeDefaultLoaders().build();
|
|
3805
|
+
const contextModule = new ContextModuleBuilder({}).setChain(ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
|
|
2873
3806
|
return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
|
|
2874
3807
|
}
|
|
2875
3808
|
static wrapBlindSigningReportNonBlocking(contextModule) {
|
|
@@ -2907,6 +3840,27 @@ function collapseSignerInteraction(interaction) {
|
|
|
2907
3840
|
return EConnectorInteraction2.ConfirmOnDevice;
|
|
2908
3841
|
}
|
|
2909
3842
|
}
|
|
3843
|
+
function wireSignerToSession(ctx, sessionId, chain, signer) {
|
|
3844
|
+
signer.onInteraction = (interaction) => {
|
|
3845
|
+
debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
|
|
3846
|
+
ctx.emit("ui-event", {
|
|
3847
|
+
type: collapseSignerInteraction(interaction),
|
|
3848
|
+
payload: { sessionId }
|
|
3849
|
+
});
|
|
3850
|
+
};
|
|
3851
|
+
signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
|
|
3852
|
+
return signer;
|
|
3853
|
+
}
|
|
3854
|
+
async function runSignerCall(ctx, sessionId, call) {
|
|
3855
|
+
try {
|
|
3856
|
+
return await call();
|
|
3857
|
+
} catch (err) {
|
|
3858
|
+
ctx.invalidateSession(sessionId);
|
|
3859
|
+
throw ctx.wrapError(err);
|
|
3860
|
+
} finally {
|
|
3861
|
+
ctx.clearCanceller(sessionId);
|
|
3862
|
+
}
|
|
3863
|
+
}
|
|
2910
3864
|
|
|
2911
3865
|
// src/connector/chains/evm.ts
|
|
2912
3866
|
async function evmGetAddress(ctx, sessionId, params) {
|
|
@@ -3007,14 +3961,13 @@ async function _getEthSigner(ctx, sessionId) {
|
|
|
3007
3961
|
|
|
3008
3962
|
// src/connector/chains/btc.ts
|
|
3009
3963
|
import { HardwareErrorCode as HardwareErrorCode5, stripHex as stripHex2 } from "@onekeyfe/hwk-adapter-core";
|
|
3010
|
-
import { Psbt } from "bitcoinjs-lib";
|
|
3964
|
+
import { Psbt as Psbt2 } from "bitcoinjs-lib";
|
|
3011
3965
|
|
|
3012
3966
|
// src/signer/SignerBtc.ts
|
|
3013
3967
|
import { hexToBytes as hexToBytes2 } from "@onekeyfe/hwk-adapter-core";
|
|
3014
3968
|
function hexToUtf8(hex) {
|
|
3015
3969
|
return new TextDecoder().decode(hexToBytes2(hex));
|
|
3016
3970
|
}
|
|
3017
|
-
var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
|
|
3018
3971
|
var SignerBtc = class {
|
|
3019
3972
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
3020
3973
|
constructor(_sdk) {
|
|
@@ -3028,7 +3981,7 @@ var SignerBtc = class {
|
|
|
3028
3981
|
return deviceActionToPromise(
|
|
3029
3982
|
action,
|
|
3030
3983
|
this.onInteraction,
|
|
3031
|
-
void 0,
|
|
3984
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3032
3985
|
this.onRegisterCanceller
|
|
3033
3986
|
);
|
|
3034
3987
|
}
|
|
@@ -3046,14 +3999,14 @@ var SignerBtc = class {
|
|
|
3046
3999
|
const result = await deviceActionToPromise(
|
|
3047
4000
|
action,
|
|
3048
4001
|
this.onInteraction,
|
|
3049
|
-
void 0,
|
|
4002
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3050
4003
|
this.onRegisterCanceller
|
|
3051
4004
|
);
|
|
3052
4005
|
debugLog(
|
|
3053
4006
|
"[SignerBtc] getExtendedPublicKey result type:",
|
|
3054
4007
|
typeof result,
|
|
3055
4008
|
"value:",
|
|
3056
|
-
|
|
4009
|
+
summarizeForLog(result)
|
|
3057
4010
|
);
|
|
3058
4011
|
if (typeof result === "string") return result;
|
|
3059
4012
|
return result.extendedPublicKey;
|
|
@@ -3082,7 +4035,7 @@ var SignerBtc = class {
|
|
|
3082
4035
|
return deviceActionToPromise(
|
|
3083
4036
|
action,
|
|
3084
4037
|
this.onInteraction,
|
|
3085
|
-
|
|
4038
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3086
4039
|
this.onRegisterCanceller
|
|
3087
4040
|
);
|
|
3088
4041
|
}
|
|
@@ -3095,7 +4048,7 @@ var SignerBtc = class {
|
|
|
3095
4048
|
return deviceActionToPromise(
|
|
3096
4049
|
action,
|
|
3097
4050
|
this.onInteraction,
|
|
3098
|
-
|
|
4051
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3099
4052
|
this.onRegisterCanceller
|
|
3100
4053
|
);
|
|
3101
4054
|
}
|
|
@@ -3108,7 +4061,7 @@ var SignerBtc = class {
|
|
|
3108
4061
|
return deviceActionToPromise(
|
|
3109
4062
|
action,
|
|
3110
4063
|
this.onInteraction,
|
|
3111
|
-
|
|
4064
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3112
4065
|
this.onRegisterCanceller
|
|
3113
4066
|
);
|
|
3114
4067
|
}
|
|
@@ -3131,7 +4084,21 @@ function _purposeToTemplate(purpose, DDT) {
|
|
|
3131
4084
|
});
|
|
3132
4085
|
}
|
|
3133
4086
|
}
|
|
4087
|
+
function assertBitcoinMainnet(coin) {
|
|
4088
|
+
if (coin !== void 0 && !["btc", "bitcoin"].includes(coin.toLowerCase())) {
|
|
4089
|
+
throw Object.assign(new Error(`Ledger BTC supports Bitcoin mainnet only, not ${coin}`), {
|
|
4090
|
+
code: HardwareErrorCode5.ChainNotSupported
|
|
4091
|
+
});
|
|
4092
|
+
}
|
|
4093
|
+
}
|
|
3134
4094
|
async function btcGetAddress(ctx, sessionId, params) {
|
|
4095
|
+
assertBitcoinMainnet(params.coin);
|
|
4096
|
+
if (normalizePath(params.path).split("/").length !== 3) {
|
|
4097
|
+
throw Object.assign(
|
|
4098
|
+
new Error("Ledger btcGetAddress takes an account path (e.g. m/84'/0'/0') plus addressIndex"),
|
|
4099
|
+
{ code: HardwareErrorCode5.InvalidParams }
|
|
4100
|
+
);
|
|
4101
|
+
}
|
|
3135
4102
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
3136
4103
|
const path = normalizePath(params.path);
|
|
3137
4104
|
try {
|
|
@@ -3162,6 +4129,7 @@ async function btcGetAddress(ctx, sessionId, params) {
|
|
|
3162
4129
|
}
|
|
3163
4130
|
}
|
|
3164
4131
|
async function btcGetPublicKey(ctx, sessionId, params) {
|
|
4132
|
+
assertBitcoinMainnet(params.coin);
|
|
3165
4133
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
3166
4134
|
const path = normalizePath(params.path);
|
|
3167
4135
|
debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
|
|
@@ -3169,7 +4137,7 @@ async function btcGetPublicKey(ctx, sessionId, params) {
|
|
|
3169
4137
|
const xpub = await btcSigner.getExtendedPublicKey(path, {
|
|
3170
4138
|
checkOnDevice: params.showOnDevice ?? false
|
|
3171
4139
|
});
|
|
3172
|
-
debugLog("[LedgerConnector] btcGetPublicKey success, xpub:",
|
|
4140
|
+
debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", summarizeForLog(xpub));
|
|
3173
4141
|
return { xpub, path: params.path };
|
|
3174
4142
|
} catch (err) {
|
|
3175
4143
|
debugError("[LedgerConnector] btcGetPublicKey error, path:", path, "err:", err);
|
|
@@ -3290,7 +4258,7 @@ function _isScriptPathInput(input) {
|
|
|
3290
4258
|
return !!(input.tapLeafScript && input.tapLeafScript.length > 0);
|
|
3291
4259
|
}
|
|
3292
4260
|
function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
3293
|
-
const psbt =
|
|
4261
|
+
const psbt = Psbt2.fromHex(psbtHex);
|
|
3294
4262
|
for (const sig of signatures) {
|
|
3295
4263
|
const input = psbt.data.inputs[sig.inputIndex];
|
|
3296
4264
|
if (!input) {
|
|
@@ -3339,7 +4307,8 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
|
3339
4307
|
}
|
|
3340
4308
|
|
|
3341
4309
|
// src/connector/chains/sol.ts
|
|
3342
|
-
import { bytesToHex, hexToBytes as hexToBytes3 } from "@onekeyfe/hwk-adapter-core";
|
|
4310
|
+
import { bytesToHex, hexToBytes as hexToBytes3, prepareSolanaOffchainMessageV1 } from "@onekeyfe/hwk-adapter-core";
|
|
4311
|
+
import bs58 from "bs58";
|
|
3343
4312
|
|
|
3344
4313
|
// src/signer/SignerSol.ts
|
|
3345
4314
|
var SignerSol = class {
|
|
@@ -3357,7 +4326,7 @@ var SignerSol = class {
|
|
|
3357
4326
|
return deviceActionToPromise(
|
|
3358
4327
|
action,
|
|
3359
4328
|
this.onInteraction,
|
|
3360
|
-
void 0,
|
|
4329
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3361
4330
|
this.onRegisterCanceller
|
|
3362
4331
|
);
|
|
3363
4332
|
}
|
|
@@ -3369,7 +4338,7 @@ var SignerSol = class {
|
|
|
3369
4338
|
return deviceActionToPromise(
|
|
3370
4339
|
action,
|
|
3371
4340
|
this.onInteraction,
|
|
3372
|
-
|
|
4341
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3373
4342
|
this.onRegisterCanceller
|
|
3374
4343
|
);
|
|
3375
4344
|
}
|
|
@@ -3382,7 +4351,7 @@ var SignerSol = class {
|
|
|
3382
4351
|
return deviceActionToPromise(
|
|
3383
4352
|
action,
|
|
3384
4353
|
this.onInteraction,
|
|
3385
|
-
|
|
4354
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3386
4355
|
this.onRegisterCanceller
|
|
3387
4356
|
);
|
|
3388
4357
|
}
|
|
@@ -3423,8 +4392,21 @@ async function solSignMessage(ctx, sessionId, params) {
|
|
|
3423
4392
|
const path = normalizePath(params.path);
|
|
3424
4393
|
const messageBytes = hexToBytes3(params.message);
|
|
3425
4394
|
try {
|
|
4395
|
+
if (params.messageVersion === 1) {
|
|
4396
|
+
const preparedMessage = prepareSolanaOffchainMessageV1({
|
|
4397
|
+
message: messageBytes,
|
|
4398
|
+
requiredSigners: params.requiredSigners
|
|
4399
|
+
});
|
|
4400
|
+
const { SignMessageVersion } = await ctx.importLedgerKit(
|
|
4401
|
+
"@ledgerhq/device-signer-kit-solana"
|
|
4402
|
+
);
|
|
4403
|
+
const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
|
|
4404
|
+
version: SignMessageVersion.Raw
|
|
4405
|
+
});
|
|
4406
|
+
return { signature: decodeBase58Signature(result2.signature) };
|
|
4407
|
+
}
|
|
3426
4408
|
const result = await solSigner.signMessage(path, messageBytes);
|
|
3427
|
-
return { signature: result.signature };
|
|
4409
|
+
return { signature: decodeBase58EnvelopeSignature(result.signature) };
|
|
3428
4410
|
} catch (err) {
|
|
3429
4411
|
ctx.invalidateSession(sessionId);
|
|
3430
4412
|
throw ctx.wrapError(err);
|
|
@@ -3432,11 +4414,27 @@ async function solSignMessage(ctx, sessionId, params) {
|
|
|
3432
4414
|
ctx.clearCanceller(sessionId);
|
|
3433
4415
|
}
|
|
3434
4416
|
}
|
|
4417
|
+
function decodeBase58Signature(signature) {
|
|
4418
|
+
const bytes = bs58.decode(signature);
|
|
4419
|
+
if (bytes.length !== 64) {
|
|
4420
|
+
throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
|
|
4421
|
+
}
|
|
4422
|
+
return bytesToHex(bytes);
|
|
4423
|
+
}
|
|
4424
|
+
function decodeBase58EnvelopeSignature(envelope) {
|
|
4425
|
+
const bytes = bs58.decode(envelope);
|
|
4426
|
+
if (bytes.length < 65 || bytes[0] !== 1) {
|
|
4427
|
+
throw new Error("Ledger Solana signature envelope is invalid");
|
|
4428
|
+
}
|
|
4429
|
+
return bytesToHex(bytes.subarray(1, 65));
|
|
4430
|
+
}
|
|
3435
4431
|
async function _createSolSigner(ctx, sessionId) {
|
|
3436
4432
|
const dmk = await ctx.getOrCreateDmk();
|
|
3437
|
-
const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit(
|
|
4433
|
+
const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
|
|
4434
|
+
"@ledgerhq/context-module"
|
|
4435
|
+
);
|
|
3438
4436
|
const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
|
|
3439
|
-
const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
|
|
4437
|
+
const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
|
|
3440
4438
|
const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
|
|
3441
4439
|
const signer = new SignerSol(sdkSigner);
|
|
3442
4440
|
signer.onInteraction = (interaction) => {
|
|
@@ -3452,361 +4450,147 @@ async function _createSolSigner(ctx, sessionId) {
|
|
|
3452
4450
|
return signer;
|
|
3453
4451
|
}
|
|
3454
4452
|
|
|
3455
|
-
// src/connector/chains/
|
|
3456
|
-
import {
|
|
3457
|
-
import Trx from "@ledgerhq/hw-app-trx";
|
|
3458
|
-
|
|
3459
|
-
// src/connector/chains/legacyChainCall.ts
|
|
3460
|
-
import { EConnectorInteraction as EConnectorInteraction3 } from "@onekeyfe/hwk-adapter-core";
|
|
4453
|
+
// src/connector/chains/zcash.ts
|
|
4454
|
+
import { bytesToHex as bytesToHex2 } from "@onekeyfe/hwk-adapter-core";
|
|
3461
4455
|
|
|
3462
|
-
// src/
|
|
3463
|
-
|
|
3464
|
-
|
|
3465
|
-
|
|
3466
|
-
|
|
3467
|
-
isSuccessCommandResult
|
|
3468
|
-
} from "@ledgerhq/device-management-kit";
|
|
3469
|
-
import { HardwareErrorCode as HardwareErrorCode6 } from "@onekeyfe/hwk-adapter-core";
|
|
3470
|
-
var APP_NAME_MAP = {
|
|
3471
|
-
ETH: "Ethereum",
|
|
3472
|
-
BTC: "Bitcoin",
|
|
3473
|
-
SOL: "Solana",
|
|
3474
|
-
TRX: "Tron",
|
|
3475
|
-
XRP: "XRP",
|
|
3476
|
-
ADA: "Cardano",
|
|
3477
|
-
DOT: "Polkadot",
|
|
3478
|
-
ATOM: "Cosmos"
|
|
3479
|
-
};
|
|
3480
|
-
var DASHBOARD_APP_NAME = "BOLOS";
|
|
3481
|
-
var AppManager = class {
|
|
3482
|
-
constructor(dmk, options) {
|
|
3483
|
-
this._dmk = dmk;
|
|
3484
|
-
this._waitMs = options?.waitMs ?? 1e3;
|
|
3485
|
-
this._maxRetries = options?.maxRetries ?? 10;
|
|
3486
|
-
}
|
|
3487
|
-
/**
|
|
3488
|
-
* Return the Ledger app name for a given chain ticker,
|
|
3489
|
-
* or undefined if the chain is not supported.
|
|
3490
|
-
*/
|
|
3491
|
-
static getAppName(chain) {
|
|
3492
|
-
return APP_NAME_MAP[chain];
|
|
3493
|
-
}
|
|
3494
|
-
/**
|
|
3495
|
-
* Ensure the target app is open on the device identified by `sessionId`.
|
|
3496
|
-
*
|
|
3497
|
-
* Flow:
|
|
3498
|
-
* 1. Check the currently running app.
|
|
3499
|
-
* 2. If it is already the target, return immediately.
|
|
3500
|
-
* 3. If a different app is running (not dashboard), close it first.
|
|
3501
|
-
* 4. Open the target app.
|
|
3502
|
-
* 5. Poll until the device confirms the target app is running.
|
|
3503
|
-
*/
|
|
3504
|
-
/**
|
|
3505
|
-
* @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
|
|
3506
|
-
* device is about to display "Open <app>" on screen and wait for the
|
|
3507
|
-
* user's button press. UI consumers should show their "open app" prompt
|
|
3508
|
-
* in response. NOT called when the target app is already open (no user
|
|
3509
|
-
* interaction needed in that case).
|
|
3510
|
-
*
|
|
3511
|
-
* Important: OpenAppCommand is blocking. It does not resolve until the user
|
|
3512
|
-
* has physically confirmed on the device, so anything that runs AFTER
|
|
3513
|
-
* `await this._openApp(...)` lands AFTER the prompt is already gone.
|
|
3514
|
-
* Hence the callback must fire BEFORE that await.
|
|
3515
|
-
*/
|
|
3516
|
-
async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
|
|
3517
|
-
const currentApp = await this._getCurrentApp(sessionId);
|
|
3518
|
-
if (currentApp === targetAppName) {
|
|
3519
|
-
return;
|
|
3520
|
-
}
|
|
3521
|
-
if (!this._isDashboard(currentApp)) {
|
|
3522
|
-
await this._closeCurrentApp(sessionId);
|
|
3523
|
-
await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
|
|
3524
|
-
}
|
|
3525
|
-
onConfirmOnDevice?.();
|
|
3526
|
-
await this._openApp(sessionId, targetAppName);
|
|
3527
|
-
await this._waitForApp(sessionId, targetAppName);
|
|
4456
|
+
// src/signer/SignerZcash.ts
|
|
4457
|
+
var SignerZcash = class {
|
|
4458
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4459
|
+
constructor(_sdk) {
|
|
4460
|
+
this._sdk = _sdk;
|
|
3528
4461
|
}
|
|
3529
|
-
|
|
3530
|
-
|
|
3531
|
-
|
|
3532
|
-
|
|
3533
|
-
|
|
3534
|
-
|
|
3535
|
-
|
|
3536
|
-
|
|
3537
|
-
if (isSuccessCommandResult(result)) {
|
|
3538
|
-
debugLog("[AppManager] currentApp:", result.data.name);
|
|
3539
|
-
return result.data.name;
|
|
3540
|
-
}
|
|
3541
|
-
const errResult = result;
|
|
3542
|
-
const dmkErr = errResult.error ?? {};
|
|
3543
|
-
const original = dmkErr.originalError;
|
|
3544
|
-
debugLog(
|
|
3545
|
-
"[AppManager] _getCurrentApp failed sessionId=",
|
|
3546
|
-
sessionId,
|
|
3547
|
-
"tag=",
|
|
3548
|
-
dmkErr._tag,
|
|
3549
|
-
"errorCode=",
|
|
3550
|
-
dmkErr.errorCode,
|
|
3551
|
-
"message=",
|
|
3552
|
-
dmkErr.message,
|
|
3553
|
-
"originalErrorMessage=",
|
|
3554
|
-
original?.message ?? String(original ?? "")
|
|
3555
|
-
);
|
|
3556
|
-
throw Object.assign(
|
|
3557
|
-
new Error(
|
|
3558
|
-
dmkErr.message ?? "Failed to get current app from device"
|
|
3559
|
-
),
|
|
3560
|
-
{
|
|
3561
|
-
_tag: dmkErr._tag,
|
|
3562
|
-
errorCode: dmkErr.errorCode,
|
|
3563
|
-
originalError: original
|
|
3564
|
-
}
|
|
4462
|
+
/** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
|
|
4463
|
+
async getFullViewingKey(derivationPath, options) {
|
|
4464
|
+
const action = this._sdk.getFullViewingKey(derivationPath, options);
|
|
4465
|
+
return deviceActionToPromise(
|
|
4466
|
+
action,
|
|
4467
|
+
this.onInteraction,
|
|
4468
|
+
void 0,
|
|
4469
|
+
this.onRegisterCanceller
|
|
3565
4470
|
);
|
|
3566
4471
|
}
|
|
3567
|
-
|
|
3568
|
-
|
|
3569
|
-
|
|
3570
|
-
|
|
3571
|
-
|
|
3572
|
-
|
|
3573
|
-
|
|
3574
|
-
|
|
3575
|
-
const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
|
|
3576
|
-
debugLog(
|
|
3577
|
-
"[AppManager] openApp failed:",
|
|
3578
|
-
appName,
|
|
3579
|
-
"errorCode:",
|
|
3580
|
-
errorCode,
|
|
3581
|
-
"tag:",
|
|
3582
|
-
dmkErr._tag
|
|
3583
|
-
);
|
|
3584
|
-
let code;
|
|
3585
|
-
if (errorCode === "6807" || /unknown application/i.test(message)) {
|
|
3586
|
-
code = HardwareErrorCode6.AppNotInstalled;
|
|
3587
|
-
} else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
|
|
3588
|
-
code = HardwareErrorCode6.UserRejected;
|
|
3589
|
-
}
|
|
3590
|
-
throw Object.assign(new Error(`Failed to open "${appName}"`), {
|
|
3591
|
-
_tag: ERROR_TAG.OpenAppCommand,
|
|
3592
|
-
code,
|
|
3593
|
-
errorCode,
|
|
3594
|
-
statusCode: errorCode,
|
|
3595
|
-
appName,
|
|
3596
|
-
originalError: dmkErr
|
|
3597
|
-
});
|
|
3598
|
-
}
|
|
3599
|
-
}
|
|
3600
|
-
async _closeCurrentApp(sessionId) {
|
|
3601
|
-
debugLog("[AppManager] closeCurrentApp");
|
|
3602
|
-
await this._dmk.sendCommand({
|
|
3603
|
-
sessionId,
|
|
3604
|
-
command: new CloseAppCommand()
|
|
3605
|
-
});
|
|
3606
|
-
}
|
|
3607
|
-
/**
|
|
3608
|
-
* Poll the device until the expected app is reported as running,
|
|
3609
|
-
* or throw after `_maxRetries` attempts.
|
|
3610
|
-
*/
|
|
3611
|
-
async _waitForApp(sessionId, expectedAppName) {
|
|
3612
|
-
let lastSeen = "";
|
|
3613
|
-
for (let i = 0; i < this._maxRetries; i++) {
|
|
3614
|
-
await this._wait();
|
|
3615
|
-
const current = await this._getCurrentApp(sessionId);
|
|
3616
|
-
lastSeen = current;
|
|
3617
|
-
if (current === expectedAppName) {
|
|
3618
|
-
return;
|
|
3619
|
-
}
|
|
3620
|
-
}
|
|
3621
|
-
debugLog(
|
|
3622
|
-
"[AppManager] waitForApp exhausted: expected=",
|
|
3623
|
-
expectedAppName,
|
|
3624
|
-
"lastSeen=",
|
|
3625
|
-
lastSeen
|
|
3626
|
-
);
|
|
3627
|
-
throw new Error(
|
|
3628
|
-
`Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
|
|
4472
|
+
/** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
|
|
4473
|
+
async getShieldedAddress(derivationPath, options) {
|
|
4474
|
+
const action = this._sdk.getShieldedAddress(derivationPath, options);
|
|
4475
|
+
return deviceActionToPromise(
|
|
4476
|
+
action,
|
|
4477
|
+
this.onInteraction,
|
|
4478
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
4479
|
+
this.onRegisterCanceller
|
|
3629
4480
|
);
|
|
3630
4481
|
}
|
|
3631
|
-
_isDashboard(appName) {
|
|
3632
|
-
return appName === DASHBOARD_APP_NAME;
|
|
3633
|
-
}
|
|
3634
|
-
_wait() {
|
|
3635
|
-
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
3636
|
-
}
|
|
3637
4482
|
};
|
|
3638
4483
|
|
|
3639
|
-
// src/connector/chains/
|
|
3640
|
-
function
|
|
3641
|
-
|
|
4484
|
+
// src/connector/chains/zcash.ts
|
|
4485
|
+
async function zcashGetFullViewingKey(ctx, sessionId, params) {
|
|
4486
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4487
|
+
const path = normalizePath(params.path);
|
|
4488
|
+
const mode = params.mode ?? "ufvk";
|
|
4489
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4490
|
+
const result = await signer.getFullViewingKey(path, { mode });
|
|
4491
|
+
if (result.mode === "ufvk") {
|
|
4492
|
+
return { path: params.path, mode, ufvk: result.fullViewingKey };
|
|
4493
|
+
}
|
|
4494
|
+
return { path: params.path, mode, orchardFvk: bytesToHex2(result.fullViewingKey) };
|
|
4495
|
+
});
|
|
3642
4496
|
}
|
|
3643
|
-
async function
|
|
3644
|
-
const
|
|
3645
|
-
|
|
3646
|
-
|
|
3647
|
-
|
|
3648
|
-
|
|
3649
|
-
type: EConnectorInteraction3.ConfirmOpenApp,
|
|
3650
|
-
payload: { sessionId }
|
|
4497
|
+
async function zcashGetShieldedAddress(ctx, sessionId, params) {
|
|
4498
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4499
|
+
const path = normalizePath(params.path);
|
|
4500
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4501
|
+
const result = await signer.getShieldedAddress(path, {
|
|
4502
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
3651
4503
|
});
|
|
3652
|
-
|
|
3653
|
-
|
|
3654
|
-
if (openAppPromptShown) {
|
|
3655
|
-
ctx.emit("ui-event", {
|
|
3656
|
-
type: EConnectorInteraction3.InteractionComplete,
|
|
3657
|
-
payload: { sessionId }
|
|
3658
|
-
});
|
|
3659
|
-
openAppPromptShown = false;
|
|
3660
|
-
}
|
|
3661
|
-
};
|
|
3662
|
-
try {
|
|
3663
|
-
await _ensureAppOpen(ctx, sessionId, appName, onAppOpenPrompt);
|
|
3664
|
-
} catch (err) {
|
|
3665
|
-
debugLog(
|
|
3666
|
-
"[LegacyChainCall] pre-flight ensureAppOpen failed:",
|
|
3667
|
-
appName,
|
|
3668
|
-
err?.message
|
|
3669
|
-
);
|
|
3670
|
-
closeOpenAppUiIfShown();
|
|
3671
|
-
throw ctx.wrapError(err, { defaultAppName: appName });
|
|
3672
|
-
}
|
|
3673
|
-
const runOnce = async () => {
|
|
3674
|
-
let confirmEmitted = false;
|
|
3675
|
-
if (needsConfirmation) {
|
|
3676
|
-
ctx.emit("ui-event", {
|
|
3677
|
-
type: EConnectorInteraction3.ConfirmOnDevice,
|
|
3678
|
-
payload: { sessionId }
|
|
3679
|
-
});
|
|
3680
|
-
confirmEmitted = true;
|
|
3681
|
-
}
|
|
3682
|
-
try {
|
|
3683
|
-
return await action(sessionId);
|
|
3684
|
-
} finally {
|
|
3685
|
-
if (confirmEmitted || openAppPromptShown) {
|
|
3686
|
-
ctx.emit("ui-event", {
|
|
3687
|
-
type: EConnectorInteraction3.InteractionComplete,
|
|
3688
|
-
payload: { sessionId }
|
|
3689
|
-
});
|
|
3690
|
-
openAppPromptShown = false;
|
|
3691
|
-
}
|
|
3692
|
-
}
|
|
3693
|
-
};
|
|
3694
|
-
try {
|
|
3695
|
-
return await runOnce();
|
|
3696
|
-
} catch (err) {
|
|
3697
|
-
if (!isLegacyWrongAppError(err, appName)) {
|
|
3698
|
-
debugLog("[LegacyChainCall] non-wrong-app failure:", appName, err?.message);
|
|
3699
|
-
ctx.invalidateSession(sessionId);
|
|
3700
|
-
throw ctx.wrapError(err, { defaultAppName: appName });
|
|
3701
|
-
}
|
|
3702
|
-
debugLog("[LegacyChainCall] wrong-app detected, retrying:", appName);
|
|
3703
|
-
try {
|
|
3704
|
-
await _ensureAppOpen(ctx, sessionId, appName, onAppOpenPrompt);
|
|
3705
|
-
} catch (switchErr) {
|
|
3706
|
-
debugLog(
|
|
3707
|
-
"[LegacyChainCall] retry ensureAppOpen failed:",
|
|
3708
|
-
appName,
|
|
3709
|
-
switchErr?.message
|
|
3710
|
-
);
|
|
3711
|
-
closeOpenAppUiIfShown();
|
|
3712
|
-
throw ctx.wrapError(switchErr, { defaultAppName: appName });
|
|
3713
|
-
}
|
|
3714
|
-
ctx.clearAllSigners();
|
|
3715
|
-
const result = await runOnce();
|
|
3716
|
-
debugLog("[LegacyChainCall] retry succeeded:", appName);
|
|
3717
|
-
return result;
|
|
3718
|
-
}
|
|
4504
|
+
return { address: result.address, path: params.path };
|
|
4505
|
+
});
|
|
3719
4506
|
}
|
|
3720
|
-
async function
|
|
4507
|
+
async function _createZcashSigner(ctx, sessionId) {
|
|
3721
4508
|
const dmk = await ctx.getOrCreateDmk();
|
|
3722
|
-
const
|
|
3723
|
-
|
|
4509
|
+
const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
|
|
4510
|
+
const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
|
|
4511
|
+
return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
|
|
3724
4512
|
}
|
|
3725
4513
|
|
|
3726
|
-
// src/
|
|
3727
|
-
import
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
|
|
3731
|
-
|
|
3732
|
-
|
|
4514
|
+
// src/connector/chains/tron.ts
|
|
4515
|
+
import { HardwareErrorCode as HardwareErrorCode6, bytesToHex as bytesToHex3, hexToBytes as hexToBytes4 } from "@onekeyfe/hwk-adapter-core";
|
|
4516
|
+
|
|
4517
|
+
// src/signer/SignerTron.ts
|
|
4518
|
+
var SignerTron = class {
|
|
4519
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4520
|
+
constructor(_sdk) {
|
|
4521
|
+
this._sdk = _sdk;
|
|
4522
|
+
}
|
|
4523
|
+
/** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
|
|
4524
|
+
async getAddress(derivationPath, options) {
|
|
4525
|
+
const action = this._sdk.getAddress(derivationPath, options);
|
|
4526
|
+
const result = await deviceActionToPromise(
|
|
4527
|
+
action,
|
|
4528
|
+
this.onInteraction,
|
|
4529
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
4530
|
+
this.onRegisterCanceller
|
|
4531
|
+
);
|
|
4532
|
+
return { address: result.address, publicKey: result.publicKey };
|
|
3733
4533
|
}
|
|
3734
|
-
|
|
3735
|
-
|
|
3736
|
-
|
|
3737
|
-
|
|
3738
|
-
|
|
3739
|
-
|
|
3740
|
-
|
|
3741
|
-
|
|
3742
|
-
|
|
3743
|
-
}
|
|
3744
|
-
result.set(statusCode, data.length);
|
|
3745
|
-
return result;
|
|
4534
|
+
/** Sign a protobuf-encoded raw transaction. */
|
|
4535
|
+
async signTransaction(derivationPath, transaction, options) {
|
|
4536
|
+
const action = this._sdk.signTransaction(derivationPath, transaction, options);
|
|
4537
|
+
return deviceActionToPromise(
|
|
4538
|
+
action,
|
|
4539
|
+
this.onInteraction,
|
|
4540
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
4541
|
+
this.onRegisterCanceller
|
|
4542
|
+
);
|
|
3746
4543
|
}
|
|
3747
|
-
|
|
4544
|
+
/** Sign a personal message (TIP-191). */
|
|
4545
|
+
async signPersonalMessage(derivationPath, message, options) {
|
|
4546
|
+
const action = this._sdk.signPersonalMessage(derivationPath, message, options);
|
|
4547
|
+
return deviceActionToPromise(
|
|
4548
|
+
action,
|
|
4549
|
+
this.onInteraction,
|
|
4550
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
4551
|
+
this.onRegisterCanceller
|
|
4552
|
+
);
|
|
3748
4553
|
}
|
|
3749
4554
|
};
|
|
3750
4555
|
|
|
3751
4556
|
// src/connector/chains/tron.ts
|
|
3752
4557
|
async function tronGetAddress(ctx, sessionId, params) {
|
|
4558
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3753
4559
|
const path = normalizePath(params.path);
|
|
3754
|
-
|
|
3755
|
-
|
|
3756
|
-
|
|
3757
|
-
|
|
3758
|
-
{
|
|
3759
|
-
|
|
3760
|
-
// Only show "confirm on device" UI when the device is actually going
|
|
3761
|
-
// to display the address for the user to verify.
|
|
3762
|
-
needsConfirmation: showOnDevice
|
|
3763
|
-
},
|
|
3764
|
-
async (sid) => {
|
|
3765
|
-
const trx = await _createTrx(ctx, sid);
|
|
3766
|
-
const result = await trx.getAddress(path, showOnDevice);
|
|
3767
|
-
return { address: result.address, publicKey: result.publicKey, path: params.path };
|
|
3768
|
-
}
|
|
3769
|
-
);
|
|
4560
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4561
|
+
const result = await tronSigner.getAddress(path, {
|
|
4562
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
4563
|
+
});
|
|
4564
|
+
return { address: result.address, publicKey: result.publicKey, path: params.path };
|
|
4565
|
+
});
|
|
3770
4566
|
}
|
|
3771
4567
|
async function tronSignTransaction(ctx, sessionId, params) {
|
|
3772
4568
|
if (!params.rawTxHex) {
|
|
3773
4569
|
throw Object.assign(
|
|
3774
4570
|
new Error("TRON signing requires a protobuf-encoded raw transaction hex (rawTxHex)."),
|
|
3775
|
-
{ code:
|
|
4571
|
+
{ code: HardwareErrorCode6.InvalidParams }
|
|
3776
4572
|
);
|
|
3777
4573
|
}
|
|
4574
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3778
4575
|
const path = normalizePath(params.path);
|
|
3779
|
-
return
|
|
3780
|
-
|
|
3781
|
-
|
|
3782
|
-
|
|
3783
|
-
async (sid) => {
|
|
3784
|
-
const trx = await _createTrx(ctx, sid);
|
|
3785
|
-
const signature = await trx.signTransaction(
|
|
3786
|
-
path,
|
|
3787
|
-
params.rawTxHex,
|
|
3788
|
-
params.tokenSignatures ?? []
|
|
3789
|
-
);
|
|
3790
|
-
return { signature };
|
|
3791
|
-
}
|
|
3792
|
-
);
|
|
4576
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4577
|
+
const signature = await tronSigner.signTransaction(path, hexToBytes4(params.rawTxHex));
|
|
4578
|
+
return { signature: bytesToHex3(signature) };
|
|
4579
|
+
});
|
|
3793
4580
|
}
|
|
3794
4581
|
async function tronSignMessage(ctx, sessionId, params) {
|
|
4582
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3795
4583
|
const path = normalizePath(params.path);
|
|
3796
|
-
return
|
|
3797
|
-
|
|
3798
|
-
|
|
3799
|
-
|
|
3800
|
-
async (sid) => {
|
|
3801
|
-
const trx = await _createTrx(ctx, sid);
|
|
3802
|
-
const signature = await trx.signPersonalMessage(path, params.messageHex);
|
|
3803
|
-
return { signature };
|
|
3804
|
-
}
|
|
3805
|
-
);
|
|
4584
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4585
|
+
const signature = await tronSigner.signPersonalMessage(path, hexToBytes4(params.messageHex));
|
|
4586
|
+
return { signature: bytesToHex3(signature) };
|
|
4587
|
+
});
|
|
3806
4588
|
}
|
|
3807
|
-
async function
|
|
4589
|
+
async function _createTronSigner(ctx, sessionId) {
|
|
3808
4590
|
const dmk = await ctx.getOrCreateDmk();
|
|
3809
|
-
|
|
4591
|
+
const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
|
|
4592
|
+
const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
|
|
4593
|
+
return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
|
|
3810
4594
|
}
|
|
3811
4595
|
|
|
3812
4596
|
// src/device-apps/customActions.ts
|
|
@@ -3985,7 +4769,7 @@ var DeviceApps = class {
|
|
|
3985
4769
|
seTargetId: v.seTargetId,
|
|
3986
4770
|
mcuTargetId: v.mcuTargetId,
|
|
3987
4771
|
seVersion: v.seVersion,
|
|
3988
|
-
seFlagsHex:
|
|
4772
|
+
seFlagsHex: bytesToHex4(v.seFlags),
|
|
3989
4773
|
mcuSephVersion: v.mcuSephVersion,
|
|
3990
4774
|
mcuBootloaderVersion: v.mcuBootloaderVersion,
|
|
3991
4775
|
hwVersion: v.hwVersion
|
|
@@ -4059,7 +4843,7 @@ var DeviceApps = class {
|
|
|
4059
4843
|
}
|
|
4060
4844
|
}
|
|
4061
4845
|
};
|
|
4062
|
-
function
|
|
4846
|
+
function bytesToHex4(bytes) {
|
|
4063
4847
|
if (!bytes) return "";
|
|
4064
4848
|
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
4065
4849
|
}
|
|
@@ -4102,10 +4886,11 @@ var METHOD_PREFIX_TO_APP_NAME = {
|
|
|
4102
4886
|
evm: "Ethereum",
|
|
4103
4887
|
btc: "Bitcoin",
|
|
4104
4888
|
sol: "Solana",
|
|
4105
|
-
tron: "Tron"
|
|
4889
|
+
tron: "Tron",
|
|
4890
|
+
zcash: "Zcash"
|
|
4106
4891
|
};
|
|
4107
4892
|
var HARDWARE_ERROR_CODE_VALUES = new Set(
|
|
4108
|
-
Object.values(
|
|
4893
|
+
Object.values(HardwareErrorCode7).filter((value) => typeof value === "number")
|
|
4109
4894
|
);
|
|
4110
4895
|
var BLE_CONNECT_SCAN_TIMEOUT_MS = 1500;
|
|
4111
4896
|
var LEDGER_RELAY_ALLOWED_ROOT_DOMAINS = ["onekeytest.com", "onekey.com"];
|
|
@@ -4142,6 +4927,10 @@ async function defaultLedgerKitImporter(pkg) {
|
|
|
4142
4927
|
return import("@ledgerhq/device-signer-kit-bitcoin");
|
|
4143
4928
|
case "@ledgerhq/device-signer-kit-solana":
|
|
4144
4929
|
return import("@ledgerhq/device-signer-kit-solana");
|
|
4930
|
+
case "@ledgerhq/device-signer-kit-tron":
|
|
4931
|
+
return import("@ledgerhq/device-signer-kit-tron");
|
|
4932
|
+
case "@ledgerhq/device-signer-kit-zcash":
|
|
4933
|
+
return import("@ledgerhq/device-signer-kit-zcash");
|
|
4145
4934
|
case "@ledgerhq/context-module":
|
|
4146
4935
|
return import("@ledgerhq/context-module");
|
|
4147
4936
|
default:
|
|
@@ -4201,6 +4990,7 @@ var LedgerConnectorBase = class {
|
|
|
4201
4990
|
this._ctx = {
|
|
4202
4991
|
emit: (event, data) => this._emit(event, data),
|
|
4203
4992
|
invalidateSession: (sid) => this._invalidateSession(sid),
|
|
4993
|
+
teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
|
|
4204
4994
|
wrapError: (err, opts) => this._wrapError(err, opts),
|
|
4205
4995
|
getOrCreateDmk: () => this._getOrCreateDmk(),
|
|
4206
4996
|
getDeviceManager: () => this._getDeviceManager(),
|
|
@@ -4300,7 +5090,7 @@ var LedgerConnectorBase = class {
|
|
|
4300
5090
|
`Ledger BLE connect did not return within ${HANG_CEILING_MS / 6e4}min \u2014 DMK hang fallback.`
|
|
4301
5091
|
);
|
|
4302
5092
|
err._tag = ERROR_TAG.BlePairingTimeout;
|
|
4303
|
-
err.code =
|
|
5093
|
+
err.code = HardwareErrorCode7.BlePairingTimeout;
|
|
4304
5094
|
reject(err);
|
|
4305
5095
|
}, HANG_CEILING_MS);
|
|
4306
5096
|
});
|
|
@@ -4333,7 +5123,7 @@ var LedgerConnectorBase = class {
|
|
|
4333
5123
|
"Ledger device is not currently advertising. Wake up and unlock the device, keep it nearby, then try again."
|
|
4334
5124
|
);
|
|
4335
5125
|
err._tag = ERROR_TAG.DeviceNotAdvertising;
|
|
4336
|
-
err.code =
|
|
5126
|
+
err.code = HardwareErrorCode7.DeviceNotFound;
|
|
4337
5127
|
throw err;
|
|
4338
5128
|
};
|
|
4339
5129
|
const doConnect = async (path) => {
|
|
@@ -4390,14 +5180,14 @@ var LedgerConnectorBase = class {
|
|
|
4390
5180
|
this._resetSignersAndSessions();
|
|
4391
5181
|
if (isLedgerBleConnectionType(this.connectionType)) {
|
|
4392
5182
|
const tag = err?._tag;
|
|
4393
|
-
if (isKnownConnectionTag(tag)) {
|
|
5183
|
+
if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
|
|
4394
5184
|
throw err;
|
|
4395
5185
|
}
|
|
4396
5186
|
const wrapped = new Error(
|
|
4397
5187
|
"Ledger Bluetooth pairing failed. Make sure the device is unlocked and nearby, then try again."
|
|
4398
5188
|
);
|
|
4399
5189
|
wrapped._tag = ERROR_TAG.BleGattBondingFailed;
|
|
4400
|
-
wrapped.code =
|
|
5190
|
+
wrapped.code = HardwareErrorCode7.BlePairingTimeout;
|
|
4401
5191
|
wrapped.originalError = err;
|
|
4402
5192
|
throw wrapped;
|
|
4403
5193
|
}
|
|
@@ -4475,7 +5265,7 @@ var LedgerConnectorBase = class {
|
|
|
4475
5265
|
this._unwatchSessionState(sessionId);
|
|
4476
5266
|
this._signerManager?.invalidate(sessionId);
|
|
4477
5267
|
this._cancellers.get(sessionId)?.({
|
|
4478
|
-
code:
|
|
5268
|
+
code: HardwareErrorCode7.DeviceDisconnected,
|
|
4479
5269
|
tag: "DeviceDisconnected",
|
|
4480
5270
|
message: "Device disconnected"
|
|
4481
5271
|
});
|
|
@@ -4491,7 +5281,7 @@ var LedgerConnectorBase = class {
|
|
|
4491
5281
|
// whitelist (`toPlainError`). The SW-side adapter rehydrates and re-throws
|
|
4492
5282
|
// locally (see LedgerAdapter._unwrapConnectorResult).
|
|
4493
5283
|
async call(sessionId, method, params) {
|
|
4494
|
-
debugLog("[DMK] call:", method, JSON.stringify(params));
|
|
5284
|
+
debugLog("[DMK] call:", method, JSON.stringify(summarizeForLog(params, { method })));
|
|
4495
5285
|
try {
|
|
4496
5286
|
const payload = await this._dispatch(sessionId, method, params);
|
|
4497
5287
|
return { success: true, payload };
|
|
@@ -4501,7 +5291,7 @@ var LedgerConnectorBase = class {
|
|
|
4501
5291
|
success: false,
|
|
4502
5292
|
error: serializeConnectorError(
|
|
4503
5293
|
Object.assign(new Error("Ledger app is unresponsive"), {
|
|
4504
|
-
code:
|
|
5294
|
+
code: HardwareErrorCode7.DeviceAppStuck,
|
|
4505
5295
|
_tag: ERROR_TAG.DeviceAppStuck,
|
|
4506
5296
|
originalError: err
|
|
4507
5297
|
})
|
|
@@ -4513,7 +5303,7 @@ var LedgerConnectorBase = class {
|
|
|
4513
5303
|
success: false,
|
|
4514
5304
|
error: serializeConnectorError(
|
|
4515
5305
|
Object.assign(new Error("Device communication interrupted, please retry"), {
|
|
4516
|
-
code:
|
|
5306
|
+
code: HardwareErrorCode7.TransportError,
|
|
4517
5307
|
_tag: ERROR_TAG.DeviceTransportStuck,
|
|
4518
5308
|
originalError: err
|
|
4519
5309
|
})
|
|
@@ -4559,6 +5349,11 @@ var LedgerConnectorBase = class {
|
|
|
4559
5349
|
return solSignTransaction(ctx, sessionId, params);
|
|
4560
5350
|
case "solSignMessage":
|
|
4561
5351
|
return solSignMessage(ctx, sessionId, params);
|
|
5352
|
+
// ZCASH
|
|
5353
|
+
case "zcashGetFullViewingKey":
|
|
5354
|
+
return zcashGetFullViewingKey(ctx, sessionId, params);
|
|
5355
|
+
case "zcashGetShieldedAddress":
|
|
5356
|
+
return zcashGetShieldedAddress(ctx, sessionId, params);
|
|
4562
5357
|
// TRON
|
|
4563
5358
|
case "tronGetAddress":
|
|
4564
5359
|
return tronGetAddress(ctx, sessionId, params);
|
|
@@ -4583,7 +5378,7 @@ var LedgerConnectorBase = class {
|
|
|
4583
5378
|
try {
|
|
4584
5379
|
return await apps.install(p.appName, ({ progress }) => {
|
|
4585
5380
|
ctx.emit("ui-event", {
|
|
4586
|
-
type:
|
|
5381
|
+
type: EConnectorInteraction3.AppInstallProgress,
|
|
4587
5382
|
payload: {
|
|
4588
5383
|
sessionId,
|
|
4589
5384
|
appName: p.appName,
|
|
@@ -4592,7 +5387,7 @@ var LedgerConnectorBase = class {
|
|
|
4592
5387
|
});
|
|
4593
5388
|
});
|
|
4594
5389
|
} catch (err) {
|
|
4595
|
-
ctx.
|
|
5390
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4596
5391
|
throw ctx.wrapError(err);
|
|
4597
5392
|
} finally {
|
|
4598
5393
|
ctx.clearCanceller(sessionId);
|
|
@@ -4682,7 +5477,7 @@ var LedgerConnectorBase = class {
|
|
|
4682
5477
|
);
|
|
4683
5478
|
return { isGenuine: output.isGenuine, deviceId };
|
|
4684
5479
|
} catch (err) {
|
|
4685
|
-
ctx.
|
|
5480
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4686
5481
|
throw ctx.wrapError(err);
|
|
4687
5482
|
} finally {
|
|
4688
5483
|
ctx.clearCanceller(sessionId);
|
|
@@ -4804,6 +5599,17 @@ var LedgerConnectorBase = class {
|
|
|
4804
5599
|
_invalidateSession(sessionId) {
|
|
4805
5600
|
this._signerManager?.invalidate(sessionId);
|
|
4806
5601
|
}
|
|
5602
|
+
_teardownSecureChannelSession(sessionId) {
|
|
5603
|
+
const cancel = this._cancellers.get(sessionId);
|
|
5604
|
+
this._cancellers.delete(sessionId);
|
|
5605
|
+
if (cancel) {
|
|
5606
|
+
try {
|
|
5607
|
+
cancel();
|
|
5608
|
+
} catch {
|
|
5609
|
+
}
|
|
5610
|
+
}
|
|
5611
|
+
this._invalidateSession(sessionId);
|
|
5612
|
+
}
|
|
4807
5613
|
/**
|
|
4808
5614
|
* Replace an old session with a new one after app switch.
|
|
4809
5615
|
* Emits device-connect so the adapter updates its _sessions Map.
|
|
@@ -4888,7 +5694,7 @@ var LedgerConnectorBase = class {
|
|
|
4888
5694
|
* at every catch site. Falls through unchanged for unknown methods.
|
|
4889
5695
|
*/
|
|
4890
5696
|
_ctxForMethod(method) {
|
|
4891
|
-
const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
|
|
5697
|
+
const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
|
|
4892
5698
|
const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
|
|
4893
5699
|
if (!defaultAppName) return this._ctx;
|
|
4894
5700
|
return {
|
|
@@ -4922,6 +5728,209 @@ var LedgerConnectorBase = class {
|
|
|
4922
5728
|
return error;
|
|
4923
5729
|
}
|
|
4924
5730
|
};
|
|
5731
|
+
|
|
5732
|
+
// src/transport/DmkTransport.ts
|
|
5733
|
+
import Transport from "@ledgerhq/hw-transport";
|
|
5734
|
+
var DmkTransport = class extends Transport {
|
|
5735
|
+
constructor(dmk, sessionId) {
|
|
5736
|
+
super();
|
|
5737
|
+
this._dmk = dmk;
|
|
5738
|
+
this._sessionId = sessionId;
|
|
5739
|
+
}
|
|
5740
|
+
async exchange(apdu) {
|
|
5741
|
+
const response = await this._dmk.sendApdu({
|
|
5742
|
+
sessionId: this._sessionId,
|
|
5743
|
+
apdu: new Uint8Array(apdu)
|
|
5744
|
+
});
|
|
5745
|
+
const { data, statusCode } = response;
|
|
5746
|
+
const result = Buffer.alloc(data.length + 2);
|
|
5747
|
+
if (data.length > 0) {
|
|
5748
|
+
result.set(data, 0);
|
|
5749
|
+
}
|
|
5750
|
+
result.set(statusCode, data.length);
|
|
5751
|
+
return result;
|
|
5752
|
+
}
|
|
5753
|
+
async close() {
|
|
5754
|
+
}
|
|
5755
|
+
};
|
|
5756
|
+
|
|
5757
|
+
// src/app/AppManager.ts
|
|
5758
|
+
import {
|
|
5759
|
+
CloseAppCommand,
|
|
5760
|
+
GetAppAndVersionCommand,
|
|
5761
|
+
OpenAppCommand,
|
|
5762
|
+
isSuccessCommandResult
|
|
5763
|
+
} from "@ledgerhq/device-management-kit";
|
|
5764
|
+
import { HardwareErrorCode as HardwareErrorCode8 } from "@onekeyfe/hwk-adapter-core";
|
|
5765
|
+
var APP_NAME_MAP = {
|
|
5766
|
+
ETH: "Ethereum",
|
|
5767
|
+
BTC: "Bitcoin",
|
|
5768
|
+
SOL: "Solana",
|
|
5769
|
+
TRX: "Tron",
|
|
5770
|
+
ZEC: "Zcash",
|
|
5771
|
+
XRP: "XRP",
|
|
5772
|
+
ADA: "Cardano",
|
|
5773
|
+
DOT: "Polkadot",
|
|
5774
|
+
ATOM: "Cosmos"
|
|
5775
|
+
};
|
|
5776
|
+
var DASHBOARD_APP_NAME = "BOLOS";
|
|
5777
|
+
var AppManager = class {
|
|
5778
|
+
constructor(dmk, options) {
|
|
5779
|
+
this._dmk = dmk;
|
|
5780
|
+
this._waitMs = options?.waitMs ?? 1e3;
|
|
5781
|
+
this._maxRetries = options?.maxRetries ?? 10;
|
|
5782
|
+
}
|
|
5783
|
+
/**
|
|
5784
|
+
* Return the Ledger app name for a given chain ticker,
|
|
5785
|
+
* or undefined if the chain is not supported.
|
|
5786
|
+
*/
|
|
5787
|
+
static getAppName(chain) {
|
|
5788
|
+
return APP_NAME_MAP[chain];
|
|
5789
|
+
}
|
|
5790
|
+
/**
|
|
5791
|
+
* Ensure the target app is open on the device identified by `sessionId`.
|
|
5792
|
+
*
|
|
5793
|
+
* Flow:
|
|
5794
|
+
* 1. Check the currently running app.
|
|
5795
|
+
* 2. If it is already the target, return immediately.
|
|
5796
|
+
* 3. If a different app is running (not dashboard), close it first.
|
|
5797
|
+
* 4. Open the target app.
|
|
5798
|
+
* 5. Poll until the device confirms the target app is running.
|
|
5799
|
+
*/
|
|
5800
|
+
/**
|
|
5801
|
+
* @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
|
|
5802
|
+
* device is about to display "Open <app>" on screen and wait for the
|
|
5803
|
+
* user's button press. UI consumers should show their "open app" prompt
|
|
5804
|
+
* in response. NOT called when the target app is already open (no user
|
|
5805
|
+
* interaction needed in that case).
|
|
5806
|
+
*
|
|
5807
|
+
* Important: OpenAppCommand is blocking. It does not resolve until the user
|
|
5808
|
+
* has physically confirmed on the device, so anything that runs AFTER
|
|
5809
|
+
* `await this._openApp(...)` lands AFTER the prompt is already gone.
|
|
5810
|
+
* Hence the callback must fire BEFORE that await.
|
|
5811
|
+
*/
|
|
5812
|
+
async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
|
|
5813
|
+
const currentApp = await this._getCurrentApp(sessionId);
|
|
5814
|
+
if (currentApp === targetAppName) {
|
|
5815
|
+
return;
|
|
5816
|
+
}
|
|
5817
|
+
if (!this._isDashboard(currentApp)) {
|
|
5818
|
+
await this._closeCurrentApp(sessionId);
|
|
5819
|
+
await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
|
|
5820
|
+
}
|
|
5821
|
+
onConfirmOnDevice?.();
|
|
5822
|
+
await this._openApp(sessionId, targetAppName);
|
|
5823
|
+
await this._waitForApp(sessionId, targetAppName);
|
|
5824
|
+
}
|
|
5825
|
+
// ---------------------------------------------------------------------------
|
|
5826
|
+
// Private helpers
|
|
5827
|
+
// ---------------------------------------------------------------------------
|
|
5828
|
+
async _getCurrentApp(sessionId) {
|
|
5829
|
+
const result = await this._dmk.sendCommand({
|
|
5830
|
+
sessionId,
|
|
5831
|
+
command: new GetAppAndVersionCommand()
|
|
5832
|
+
});
|
|
5833
|
+
if (isSuccessCommandResult(result)) {
|
|
5834
|
+
debugLog("[AppManager] currentApp:", result.data.name);
|
|
5835
|
+
return result.data.name;
|
|
5836
|
+
}
|
|
5837
|
+
const errResult = result;
|
|
5838
|
+
const dmkErr = errResult.error ?? {};
|
|
5839
|
+
const original = dmkErr.originalError;
|
|
5840
|
+
debugLog(
|
|
5841
|
+
"[AppManager] _getCurrentApp failed sessionId=",
|
|
5842
|
+
sessionId,
|
|
5843
|
+
"tag=",
|
|
5844
|
+
dmkErr._tag,
|
|
5845
|
+
"errorCode=",
|
|
5846
|
+
dmkErr.errorCode,
|
|
5847
|
+
"message=",
|
|
5848
|
+
dmkErr.message,
|
|
5849
|
+
"originalErrorMessage=",
|
|
5850
|
+
original?.message ?? String(original ?? "")
|
|
5851
|
+
);
|
|
5852
|
+
throw Object.assign(
|
|
5853
|
+
new Error(
|
|
5854
|
+
dmkErr.message ?? "Failed to get current app from device"
|
|
5855
|
+
),
|
|
5856
|
+
{
|
|
5857
|
+
_tag: dmkErr._tag,
|
|
5858
|
+
errorCode: dmkErr.errorCode,
|
|
5859
|
+
originalError: original
|
|
5860
|
+
}
|
|
5861
|
+
);
|
|
5862
|
+
}
|
|
5863
|
+
async _openApp(sessionId, appName) {
|
|
5864
|
+
const result = await this._dmk.sendCommand({
|
|
5865
|
+
sessionId,
|
|
5866
|
+
command: new OpenAppCommand({ appName })
|
|
5867
|
+
});
|
|
5868
|
+
if (!isSuccessCommandResult(result)) {
|
|
5869
|
+
const dmkErr = result.error;
|
|
5870
|
+
const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
|
|
5871
|
+
const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
|
|
5872
|
+
debugLog(
|
|
5873
|
+
"[AppManager] openApp failed:",
|
|
5874
|
+
appName,
|
|
5875
|
+
"errorCode:",
|
|
5876
|
+
errorCode,
|
|
5877
|
+
"tag:",
|
|
5878
|
+
dmkErr._tag
|
|
5879
|
+
);
|
|
5880
|
+
let code;
|
|
5881
|
+
if (errorCode === "6807" || /unknown application/i.test(message)) {
|
|
5882
|
+
code = HardwareErrorCode8.AppNotInstalled;
|
|
5883
|
+
} else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
|
|
5884
|
+
code = HardwareErrorCode8.UserRejected;
|
|
5885
|
+
}
|
|
5886
|
+
throw Object.assign(new Error(`Failed to open "${appName}"`), {
|
|
5887
|
+
_tag: ERROR_TAG.OpenAppCommand,
|
|
5888
|
+
code,
|
|
5889
|
+
errorCode,
|
|
5890
|
+
statusCode: errorCode,
|
|
5891
|
+
appName,
|
|
5892
|
+
originalError: dmkErr
|
|
5893
|
+
});
|
|
5894
|
+
}
|
|
5895
|
+
}
|
|
5896
|
+
async _closeCurrentApp(sessionId) {
|
|
5897
|
+
debugLog("[AppManager] closeCurrentApp");
|
|
5898
|
+
await this._dmk.sendCommand({
|
|
5899
|
+
sessionId,
|
|
5900
|
+
command: new CloseAppCommand()
|
|
5901
|
+
});
|
|
5902
|
+
}
|
|
5903
|
+
/**
|
|
5904
|
+
* Poll the device until the expected app is reported as running,
|
|
5905
|
+
* or throw after `_maxRetries` attempts.
|
|
5906
|
+
*/
|
|
5907
|
+
async _waitForApp(sessionId, expectedAppName) {
|
|
5908
|
+
let lastSeen = "";
|
|
5909
|
+
for (let i = 0; i < this._maxRetries; i++) {
|
|
5910
|
+
await this._wait();
|
|
5911
|
+
const current = await this._getCurrentApp(sessionId);
|
|
5912
|
+
lastSeen = current;
|
|
5913
|
+
if (current === expectedAppName) {
|
|
5914
|
+
return;
|
|
5915
|
+
}
|
|
5916
|
+
}
|
|
5917
|
+
debugLog(
|
|
5918
|
+
"[AppManager] waitForApp exhausted: expected=",
|
|
5919
|
+
expectedAppName,
|
|
5920
|
+
"lastSeen=",
|
|
5921
|
+
lastSeen
|
|
5922
|
+
);
|
|
5923
|
+
throw new Error(
|
|
5924
|
+
`Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
|
|
5925
|
+
);
|
|
5926
|
+
}
|
|
5927
|
+
_isDashboard(appName) {
|
|
5928
|
+
return appName === DASHBOARD_APP_NAME;
|
|
5929
|
+
}
|
|
5930
|
+
_wait() {
|
|
5931
|
+
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
5932
|
+
}
|
|
5933
|
+
};
|
|
4925
5934
|
export {
|
|
4926
5935
|
AppManager,
|
|
4927
5936
|
DmkTransport,
|
|
@@ -4932,6 +5941,7 @@ export {
|
|
|
4932
5941
|
SignerEth,
|
|
4933
5942
|
SignerManager,
|
|
4934
5943
|
SignerSol,
|
|
5944
|
+
SignerZcash,
|
|
4935
5945
|
debugLog,
|
|
4936
5946
|
deviceActionToPromise,
|
|
4937
5947
|
isDeviceLockedError,
|