@onekeyfe/hwk-ledger-adapter 1.2.5-alpha.3 → 1.2.5-alpha.4
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 +81 -39
- package/dist/index.d.ts +81 -39
- package/dist/index.js +1614 -831
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1634 -831
- package/dist/index.mjs.map +1 -1
- package/package.json +14 -11
package/dist/index.mjs
CHANGED
|
@@ -6,30 +6,41 @@ 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,
|
|
15
18
|
failure as failure2,
|
|
19
|
+
isHardwareOperationId,
|
|
20
|
+
isHwkRecoveryHint,
|
|
21
|
+
operationMayHaveCompletedParams,
|
|
16
22
|
rehydrateConnectorError,
|
|
23
|
+
requestBleDeviceSelection,
|
|
24
|
+
requestSaveDeviceBinding,
|
|
25
|
+
resolveSearchTargetReusePolicy,
|
|
17
26
|
success
|
|
18
27
|
} from "@onekeyfe/hwk-adapter-core";
|
|
19
28
|
|
|
20
29
|
// src/errors.ts
|
|
21
|
-
import {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
function ledgerFailure(code, error, appName, tag, params) {
|
|
30
|
+
import {
|
|
31
|
+
HardwareErrorCode,
|
|
32
|
+
defaultOriginForCode,
|
|
33
|
+
defaultRecoveryForCode,
|
|
34
|
+
enrichErrorMessage
|
|
35
|
+
} from "@onekeyfe/hwk-adapter-core";
|
|
36
|
+
function ledgerFailure(code, error, appName, tag, params, origin, recovery) {
|
|
29
37
|
const payload = { error, code };
|
|
30
38
|
if (appName !== void 0) payload.appName = appName;
|
|
31
39
|
if (tag !== void 0) payload._tag = tag;
|
|
32
40
|
if (params !== void 0) payload.params = params;
|
|
41
|
+
const resolvedOrigin = origin ?? defaultOriginForCode(code);
|
|
42
|
+
if (resolvedOrigin !== void 0) payload.origin = resolvedOrigin;
|
|
43
|
+
payload.recovery = recovery ?? defaultRecoveryForCode(code);
|
|
33
44
|
return { success: false, payload };
|
|
34
45
|
}
|
|
35
46
|
var LOCKED_ERROR_CODES = /* @__PURE__ */ new Set(["5515", "21781", "6982", "27010", "5303", "21251"]);
|
|
@@ -170,7 +181,10 @@ var ERROR_TAG = {
|
|
|
170
181
|
UnknownDevice: "UnknownDeviceError",
|
|
171
182
|
DeviceSessionRefresher: "DeviceSessionRefresherError",
|
|
172
183
|
DeviceNotInitialized: "DeviceNotInitializedError",
|
|
173
|
-
|
|
184
|
+
// DMK class OpeningConnectionError carries `_tag` "ConnectionOpeningError"; both
|
|
185
|
+
// spellings are kept so a DMK release that aligns them still classifies.
|
|
186
|
+
OpeningConnection: "ConnectionOpeningError",
|
|
187
|
+
OpeningConnectionLegacy: "OpeningConnectionError",
|
|
174
188
|
DeviceDisconnectedBeforeSendingApdu: "DeviceDisconnectedBeforeSendingApdu",
|
|
175
189
|
DeviceDisconnectedWhileSending: "DeviceDisconnectedWhileSendingError",
|
|
176
190
|
Disconnect: "DisconnectError",
|
|
@@ -183,7 +197,16 @@ var ERROR_TAG = {
|
|
|
183
197
|
// DMK remote-network failures (manager-api HTTP / secure-channel WS).
|
|
184
198
|
WebSocketConnection: "WebSocketConnectionError",
|
|
185
199
|
HttpFetch: "FetchError",
|
|
186
|
-
|
|
200
|
+
NetworkDA: "NetworkDAError",
|
|
201
|
+
InvalidFirmwareMetadataResponse: "InvalidGetFirmwareMetadataResponseError",
|
|
202
|
+
ApplicationsMetadataTask: "GetApplicationsMetadataTaskError",
|
|
203
|
+
// DMK OS device actions. SecureChannelError is what mapInstallDAErrors() leaves
|
|
204
|
+
// after splitting out device answers, i.e. the relay itself broke.
|
|
205
|
+
SecureChannel: "SecureChannelError",
|
|
206
|
+
RefusedByUserDA: "RefusedByUserDAError",
|
|
207
|
+
AppAlreadyInstalledDA: "AppAlreadyInstalledDAError",
|
|
208
|
+
OutOfMemoryDA: "OutOfMemoryDAError",
|
|
209
|
+
DeviceNotOnboarded: "DeviceNotOnboardedError"
|
|
187
210
|
};
|
|
188
211
|
function isDeviceLockedError(err) {
|
|
189
212
|
if (!err || typeof err !== "object") return false;
|
|
@@ -213,7 +236,6 @@ function isBlePairingFailureError(err) {
|
|
|
213
236
|
return false;
|
|
214
237
|
}
|
|
215
238
|
var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
|
|
216
|
-
ERROR_TAG.DeviceLocked,
|
|
217
239
|
ERROR_TAG.DeviceNotAdvertising,
|
|
218
240
|
ERROR_TAG.BlePairingTimeout,
|
|
219
241
|
ERROR_TAG.BleGattBondingFailed,
|
|
@@ -225,6 +247,7 @@ var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
|
|
|
225
247
|
ERROR_TAG.DeviceSessionRefresher,
|
|
226
248
|
ERROR_TAG.DeviceNotInitialized,
|
|
227
249
|
ERROR_TAG.OpeningConnection,
|
|
250
|
+
ERROR_TAG.OpeningConnectionLegacy,
|
|
228
251
|
ERROR_TAG.DeviceDisconnectedBeforeSendingApdu,
|
|
229
252
|
ERROR_TAG.DeviceDisconnectedWhileSending,
|
|
230
253
|
ERROR_TAG.Disconnect,
|
|
@@ -239,7 +262,10 @@ var DEVICE_NOT_FOUND_TAGS = /* @__PURE__ */ new Set([
|
|
|
239
262
|
// Map to DeviceNotFound so non-BLE-direct paths get a sensible error code.
|
|
240
263
|
ERROR_TAG.DeviceNotInDiscoveryCache
|
|
241
264
|
]);
|
|
242
|
-
var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
|
|
265
|
+
var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
|
|
266
|
+
ERROR_TAG.OpeningConnection,
|
|
267
|
+
ERROR_TAG.OpeningConnectionLegacy
|
|
268
|
+
]);
|
|
243
269
|
var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
|
|
244
270
|
ERROR_TAG.DeviceNotRecognized,
|
|
245
271
|
ERROR_TAG.DeviceSessionNotFound,
|
|
@@ -251,17 +277,18 @@ var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
|
|
|
251
277
|
ERROR_TAG.WebHIDDisconnect
|
|
252
278
|
]);
|
|
253
279
|
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;
|
|
280
|
+
return hasErrorTag(err, CONNECTION_LEVEL_TAGS);
|
|
261
281
|
}
|
|
262
282
|
function isKnownConnectionTag(tag) {
|
|
263
283
|
return typeof tag === "string" && CONNECTION_LEVEL_TAGS.has(tag);
|
|
264
284
|
}
|
|
285
|
+
var CONNECTION_OPENING_TAGS = /* @__PURE__ */ new Set([
|
|
286
|
+
ERROR_TAG.OpeningConnection,
|
|
287
|
+
ERROR_TAG.OpeningConnectionLegacy
|
|
288
|
+
]);
|
|
289
|
+
function isConnectionOpeningTag(tag) {
|
|
290
|
+
return typeof tag === "string" && CONNECTION_OPENING_TAGS.has(tag);
|
|
291
|
+
}
|
|
265
292
|
function hasStatusCode(err, codeSet) {
|
|
266
293
|
if (!err || typeof err !== "object") return false;
|
|
267
294
|
const e = err;
|
|
@@ -297,28 +324,28 @@ function hasInvalidArgumentCode(err) {
|
|
|
297
324
|
if (e.error != null && e._tag && hasInvalidArgumentCode(e.error)) return true;
|
|
298
325
|
return false;
|
|
299
326
|
}
|
|
300
|
-
function
|
|
327
|
+
function hasErrorTag(err, tags) {
|
|
301
328
|
if (!err || typeof err !== "object") return false;
|
|
302
|
-
const tag = err._tag;
|
|
303
|
-
if (tag && DEVICE_NOT_FOUND_TAGS.has(tag)) return true;
|
|
304
329
|
const e = err;
|
|
305
|
-
if (e.
|
|
306
|
-
if (e.
|
|
330
|
+
if (typeof e._tag === "string" && tags.has(e._tag)) return true;
|
|
331
|
+
if (e.originalError != null && hasErrorTag(e.originalError, tags)) return true;
|
|
332
|
+
if (e.error != null && e._tag && hasErrorTag(e.error, tags)) return true;
|
|
307
333
|
return false;
|
|
308
334
|
}
|
|
335
|
+
function isDeviceNotFoundError(err) {
|
|
336
|
+
return hasErrorTag(err, DEVICE_NOT_FOUND_TAGS);
|
|
337
|
+
}
|
|
309
338
|
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;
|
|
339
|
+
return hasErrorTag(err, DEVICE_BUSY_TAGS);
|
|
317
340
|
}
|
|
341
|
+
var USER_REJECTED_TAGS = /* @__PURE__ */ new Set([
|
|
342
|
+
ERROR_TAG.UserRefusedOnDevice,
|
|
343
|
+
ERROR_TAG.RefusedByUserDA
|
|
344
|
+
]);
|
|
318
345
|
function isUserRejectedError(err) {
|
|
319
346
|
if (!err || typeof err !== "object") return false;
|
|
320
347
|
const e = err;
|
|
321
|
-
if (
|
|
348
|
+
if (hasErrorTag(err, USER_REJECTED_TAGS)) return true;
|
|
322
349
|
if (typeof e.message === "string" && /denied|rejected|refused/i.test(e.message)) return true;
|
|
323
350
|
if (hasStatusCode(err, USER_REJECTED_CODES)) return true;
|
|
324
351
|
return false;
|
|
@@ -349,15 +376,33 @@ function isAppNotInstalledError(err) {
|
|
|
349
376
|
if (hasStatusCode(err, APP_NOT_INSTALLED_CODES)) return true;
|
|
350
377
|
return false;
|
|
351
378
|
}
|
|
379
|
+
var OUT_OF_MEMORY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OutOfMemoryDA]);
|
|
352
380
|
function isOutOfMemoryError(err) {
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
381
|
+
return hasErrorTag(err, OUT_OF_MEMORY_TAGS);
|
|
382
|
+
}
|
|
383
|
+
var APP_ALREADY_INSTALLED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.AppAlreadyInstalledDA]);
|
|
384
|
+
function isAppAlreadyInstalledError(err) {
|
|
385
|
+
return hasErrorTag(err, APP_ALREADY_INSTALLED_TAGS);
|
|
386
|
+
}
|
|
387
|
+
var DEVICE_NOT_ONBOARDED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.DeviceNotOnboarded]);
|
|
388
|
+
function isDeviceNotOnboardedError(err) {
|
|
389
|
+
return hasErrorTag(err, DEVICE_NOT_ONBOARDED_TAGS);
|
|
390
|
+
}
|
|
391
|
+
var FIRMWARE_METADATA_TAGS = /* @__PURE__ */ new Set([
|
|
392
|
+
ERROR_TAG.InvalidFirmwareMetadataResponse,
|
|
393
|
+
ERROR_TAG.ApplicationsMetadataTask
|
|
394
|
+
]);
|
|
395
|
+
function isFirmwareMetadataError(err) {
|
|
396
|
+
return hasErrorTag(err, FIRMWARE_METADATA_TAGS);
|
|
397
|
+
}
|
|
398
|
+
var SECURE_CHANNEL_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.SecureChannel]);
|
|
399
|
+
function isSecureChannelError(err) {
|
|
400
|
+
return hasErrorTag(err, SECURE_CHANNEL_TAGS);
|
|
356
401
|
}
|
|
357
402
|
var NETWORK_ERROR_TAGS = /* @__PURE__ */ new Set([
|
|
358
403
|
ERROR_TAG.WebSocketConnection,
|
|
359
404
|
ERROR_TAG.HttpFetch,
|
|
360
|
-
ERROR_TAG.
|
|
405
|
+
ERROR_TAG.NetworkDA
|
|
361
406
|
]);
|
|
362
407
|
function isNetworkError(err) {
|
|
363
408
|
if (!err || typeof err !== "object") return false;
|
|
@@ -407,23 +452,34 @@ function isTransportStuck(err) {
|
|
|
407
452
|
function isStuckAppStateError(err) {
|
|
408
453
|
return isAppStuckByApdu(err) || isTransportStuck(err);
|
|
409
454
|
}
|
|
455
|
+
var DMK_PLACEHOLDER_MESSAGE = "Unknown error.";
|
|
456
|
+
function nestedErrorMessage(nested) {
|
|
457
|
+
if (!nested || typeof nested !== "object") return void 0;
|
|
458
|
+
const { message } = nested;
|
|
459
|
+
if (typeof message !== "string") return void 0;
|
|
460
|
+
const trimmed = message.trim();
|
|
461
|
+
if (!trimmed || trimmed === DMK_PLACEHOLDER_MESSAGE) return void 0;
|
|
462
|
+
return message;
|
|
463
|
+
}
|
|
410
464
|
function mapLedgerError(err, opts) {
|
|
411
465
|
let originalMessage = "Unknown Ledger error";
|
|
412
466
|
if (err instanceof Error) {
|
|
413
467
|
originalMessage = err.message;
|
|
414
468
|
} else if (err && typeof err === "object") {
|
|
415
469
|
const e = err;
|
|
416
|
-
originalMessage = String(
|
|
470
|
+
originalMessage = String(
|
|
471
|
+
e.message ?? nestedErrorMessage(e.originalError) ?? e._tag ?? e.type ?? JSON.stringify(err)
|
|
472
|
+
);
|
|
417
473
|
}
|
|
418
474
|
let code;
|
|
419
475
|
if (isDeviceLockedError(err)) {
|
|
420
476
|
code = HardwareErrorCode.DeviceLocked;
|
|
421
477
|
} else if (isDeviceNotAdvertisingError(err) || isDeviceNotFoundError(err)) {
|
|
422
478
|
code = HardwareErrorCode.DeviceNotFound;
|
|
423
|
-
} else if (isDeviceBusyError(err)) {
|
|
424
|
-
code = HardwareErrorCode.DeviceBusy;
|
|
425
479
|
} else if (isBlePairingFailureError(err)) {
|
|
426
480
|
code = HardwareErrorCode.BlePairingTimeout;
|
|
481
|
+
} else if (isDeviceBusyError(err)) {
|
|
482
|
+
code = HardwareErrorCode.DeviceBusy;
|
|
427
483
|
} else if (isUserAbortedError(err)) {
|
|
428
484
|
code = HardwareErrorCode.UserAborted;
|
|
429
485
|
} else if (isUserRejectedError(err)) {
|
|
@@ -432,10 +488,18 @@ function mapLedgerError(err, opts) {
|
|
|
432
488
|
code = HardwareErrorCode.WrongApp;
|
|
433
489
|
} else if (isAppNotInstalledError(err)) {
|
|
434
490
|
code = HardwareErrorCode.AppNotInstalled;
|
|
491
|
+
} else if (isAppAlreadyInstalledError(err)) {
|
|
492
|
+
code = HardwareErrorCode.AppAlreadyInstalled;
|
|
435
493
|
} else if (isOutOfMemoryError(err)) {
|
|
436
494
|
code = HardwareErrorCode.DeviceOutOfMemory;
|
|
495
|
+
} else if (isDeviceNotOnboardedError(err)) {
|
|
496
|
+
code = HardwareErrorCode.DeviceNotInitialized;
|
|
497
|
+
} else if (isFirmwareMetadataError(err)) {
|
|
498
|
+
code = HardwareErrorCode.LedgerFirmwareMetadataError;
|
|
437
499
|
} else if (isNetworkError(err)) {
|
|
438
500
|
code = HardwareErrorCode.NetworkError;
|
|
501
|
+
} else if (isSecureChannelError(err)) {
|
|
502
|
+
code = HardwareErrorCode.LedgerSecureChannelError;
|
|
439
503
|
} else if (isDeviceDisconnectedError(err)) {
|
|
440
504
|
code = HardwareErrorCode.DeviceDisconnected;
|
|
441
505
|
} else if (isTimeoutError(err)) {
|
|
@@ -448,11 +512,32 @@ function mapLedgerError(err, opts) {
|
|
|
448
512
|
}
|
|
449
513
|
const errAppName = err && typeof err === "object" ? err.appName : void 0;
|
|
450
514
|
const appName = errAppName ?? opts?.defaultAppName;
|
|
451
|
-
return {
|
|
515
|
+
return {
|
|
516
|
+
code,
|
|
517
|
+
message: enrichErrorMessage(code, originalMessage),
|
|
518
|
+
origin: defaultOriginForCode(code),
|
|
519
|
+
appName
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// src/utils/queueKey.ts
|
|
524
|
+
var LEDGER_DEFAULT_QUEUE_KEY = "__ledger_default__";
|
|
525
|
+
function ledgerQueueKey({
|
|
526
|
+
operationId,
|
|
527
|
+
connectId
|
|
528
|
+
}) {
|
|
529
|
+
return (operationId ?? connectId) || LEDGER_DEFAULT_QUEUE_KEY;
|
|
452
530
|
}
|
|
453
531
|
|
|
454
532
|
// src/adapter/methods/allNetworkGetAddress.ts
|
|
455
|
-
import {
|
|
533
|
+
import {
|
|
534
|
+
HardwareErrorCode as HardwareErrorCode2,
|
|
535
|
+
failure,
|
|
536
|
+
isConnectionLost,
|
|
537
|
+
isUserRefusal,
|
|
538
|
+
resolveHardwareOperationTarget,
|
|
539
|
+
runAllNetworkGetAddress
|
|
540
|
+
} from "@onekeyfe/hwk-adapter-core";
|
|
456
541
|
|
|
457
542
|
// src/utils/sdkEventBus.ts
|
|
458
543
|
var listeners = /* @__PURE__ */ new Set();
|
|
@@ -509,65 +594,103 @@ var LEDGER_BTC_NETWORK_COIN_MAP = {
|
|
|
509
594
|
var LEDGER_UNSUPPORTED_ALLNETWORK_NETWORKS = /* @__PURE__ */ new Set(["doge", "dogecoin"]);
|
|
510
595
|
function createAllNetworkGetAddress({
|
|
511
596
|
callChain,
|
|
512
|
-
getChainFingerprint
|
|
597
|
+
getChainFingerprint,
|
|
598
|
+
retainOperation,
|
|
599
|
+
errorToFailure,
|
|
600
|
+
createCancelScope
|
|
513
601
|
}) {
|
|
514
602
|
return async function allNetworkGetAddress(connectId, _deviceId, params) {
|
|
515
|
-
debugLog("[LedgerAdapter][REQ]", {
|
|
603
|
+
debugLog("[LedgerAdapter][REQ]", {
|
|
604
|
+
method: "allNetworkGetAddress",
|
|
605
|
+
connectId,
|
|
606
|
+
itemCount: params.bundle.length
|
|
607
|
+
});
|
|
608
|
+
const target = resolveHardwareOperationTarget(connectId, params.operationId, "ledger");
|
|
609
|
+
if (!target.success) return target;
|
|
610
|
+
const effectiveTargetId = target.payload.targetId ?? "";
|
|
611
|
+
let releaseOperationRetention;
|
|
612
|
+
try {
|
|
613
|
+
releaseOperationRetention = target.payload.operationId ? retainOperation(target.payload.operationId) : void 0;
|
|
614
|
+
} catch (error) {
|
|
615
|
+
return errorToFailure(error);
|
|
616
|
+
}
|
|
617
|
+
const cancelScope = createCancelScope(
|
|
618
|
+
ledgerQueueKey({ operationId: target.payload.operationId, connectId: effectiveTargetId })
|
|
619
|
+
);
|
|
516
620
|
const installContext = {};
|
|
517
621
|
const commonParams = {
|
|
518
|
-
autoInstallApp: params.autoInstallApp
|
|
622
|
+
autoInstallApp: params.autoInstallApp,
|
|
623
|
+
operationId: target.payload.operationId,
|
|
624
|
+
knownConnections: params.knownConnections,
|
|
625
|
+
extra: params.extra,
|
|
626
|
+
allowDeviceSelection: params.allowDeviceSelection,
|
|
627
|
+
supportedTransports: params.supportedTransports
|
|
519
628
|
};
|
|
520
629
|
const chainFingerprints = /* @__PURE__ */ new Map();
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
630
|
+
try {
|
|
631
|
+
const result = await runAllNetworkGetAddress({
|
|
632
|
+
connectId: effectiveTargetId,
|
|
633
|
+
deviceId: _deviceId,
|
|
634
|
+
params,
|
|
635
|
+
normalizeItem: normalizeLedgerAllNetworkItem,
|
|
636
|
+
buildUnsupportedNetworkResponse: (item) => isUnsupportedLedgerAllNetworkNetwork(item) ? buildUnsupportedNetworkResponse(item) : void 0,
|
|
637
|
+
callItem: async ({ method, chain, item }) => {
|
|
638
|
+
if (cancelScope.signal.aborted) return buildCancelledFailure(cancelScope.signal);
|
|
639
|
+
const itemDeviceId = getItemDeviceId(item) ?? chainFingerprints.get(chain) ?? "";
|
|
640
|
+
return callAllNetworkMethod(
|
|
641
|
+
callChain,
|
|
642
|
+
effectiveTargetId,
|
|
643
|
+
itemDeviceId,
|
|
644
|
+
method,
|
|
645
|
+
item,
|
|
646
|
+
commonParams,
|
|
647
|
+
installContext
|
|
648
|
+
);
|
|
649
|
+
},
|
|
650
|
+
attachIdentity: async ({ item, chain, payload }) => attachLedgerIdentity(
|
|
651
|
+
getChainFingerprint,
|
|
652
|
+
effectiveTargetId,
|
|
534
653
|
item,
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
});
|
|
562
|
-
return result;
|
|
654
|
+
chain,
|
|
655
|
+
payload,
|
|
656
|
+
chainFingerprints,
|
|
657
|
+
installContext,
|
|
658
|
+
cancelScope.signal
|
|
659
|
+
),
|
|
660
|
+
shouldAbortBundle: isTopLevelAllNetworkFailure,
|
|
661
|
+
buildTopLevelFailure: (response) => {
|
|
662
|
+
const code = response.payload?.code ?? HardwareErrorCode2.DeviceMismatch;
|
|
663
|
+
return failure(
|
|
664
|
+
code,
|
|
665
|
+
response.payload?.error ?? "All-network get-address aborted",
|
|
666
|
+
response.payload?.params
|
|
667
|
+
);
|
|
668
|
+
}
|
|
669
|
+
});
|
|
670
|
+
debugLog("[LedgerAdapter][RES]", {
|
|
671
|
+
method: "allNetworkGetAddress",
|
|
672
|
+
success: result.success,
|
|
673
|
+
payload: result
|
|
674
|
+
});
|
|
675
|
+
return result;
|
|
676
|
+
} finally {
|
|
677
|
+
cancelScope.release();
|
|
678
|
+
releaseOperationRetention?.();
|
|
679
|
+
}
|
|
563
680
|
};
|
|
564
681
|
}
|
|
682
|
+
function buildCancelledFailure(signal) {
|
|
683
|
+
const reason = signal.reason;
|
|
684
|
+
const code = typeof reason?.code === "number" ? reason.code : HardwareErrorCode2.UserAborted;
|
|
685
|
+
const message = typeof reason?.message === "string" ? reason.message : "";
|
|
686
|
+
return failure(code, message || "All-network get-address cancelled");
|
|
687
|
+
}
|
|
565
688
|
function isTopLevelAllNetworkFailure(response) {
|
|
566
689
|
if (response.success) {
|
|
567
690
|
return false;
|
|
568
691
|
}
|
|
569
692
|
const code = response.payload?.code;
|
|
570
|
-
return code === HardwareErrorCode2.DeviceMismatch || code
|
|
693
|
+
return code === HardwareErrorCode2.DeviceMismatch || isUserRefusal(code) || isConnectionLost(code);
|
|
571
694
|
}
|
|
572
695
|
function getItemDeviceId(item) {
|
|
573
696
|
const { deviceId } = item;
|
|
@@ -597,8 +720,18 @@ function normalizeLedgerAllNetworkItem(method, item) {
|
|
|
597
720
|
const coin = LEDGER_BTC_NETWORK_COIN_MAP[item.network];
|
|
598
721
|
return coin ? { ...item, coin } : item;
|
|
599
722
|
}
|
|
600
|
-
async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints) {
|
|
601
|
-
const
|
|
723
|
+
async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints, context, cancelSignal) {
|
|
724
|
+
const knownFingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || "";
|
|
725
|
+
if (!knownFingerprint && cancelSignal.aborted) {
|
|
726
|
+
const cancelled = buildCancelledFailure(cancelSignal);
|
|
727
|
+
return { ...item, success: false, payload: cancelled.payload };
|
|
728
|
+
}
|
|
729
|
+
const fingerprint = knownFingerprint || await bootstrapChainFingerprint(
|
|
730
|
+
getChainFingerprint,
|
|
731
|
+
context.connection?.connectId ?? connectId,
|
|
732
|
+
chain,
|
|
733
|
+
context
|
|
734
|
+
);
|
|
602
735
|
if (!fingerprint) {
|
|
603
736
|
return buildFingerprintBootstrapFailure(item, chain);
|
|
604
737
|
}
|
|
@@ -619,8 +752,8 @@ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain,
|
|
|
619
752
|
}
|
|
620
753
|
};
|
|
621
754
|
}
|
|
622
|
-
async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain) {
|
|
623
|
-
const response = await getChainFingerprint(connectId, chain);
|
|
755
|
+
async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain, context) {
|
|
756
|
+
const response = await getChainFingerprint(connectId, chain, context);
|
|
624
757
|
return response.success ? response.payload : "";
|
|
625
758
|
}
|
|
626
759
|
function buildFingerprintBootstrapFailure(item, chain) {
|
|
@@ -713,6 +846,16 @@ function isLedgerBleDescriptor(connectionType, descriptor) {
|
|
|
713
846
|
function formatDeviceMismatchError(expected, actual) {
|
|
714
847
|
return `Wrong device: expected ${expected}, got ${actual}`;
|
|
715
848
|
}
|
|
849
|
+
var LOG_REDACTED_RESULT_KEYS = ["ufvk", "orchardFvk"];
|
|
850
|
+
function redactResultForLog(result) {
|
|
851
|
+
if (!result || typeof result !== "object") return result;
|
|
852
|
+
const keys = LOG_REDACTED_RESULT_KEYS.filter((key) => key in result);
|
|
853
|
+
if (!keys.length) return result;
|
|
854
|
+
return { ...result, ...Object.fromEntries(keys.map((key) => [key, "[redacted]"])) };
|
|
855
|
+
}
|
|
856
|
+
function isLostConnectionError(err) {
|
|
857
|
+
return isDeviceDisconnectedError(err) || isDeviceNotAdvertisingError(err) || isTimeoutError(err) || isConnectionLevelError(err);
|
|
858
|
+
}
|
|
716
859
|
var BTC_HIGH_INDEX_THRESHOLD = 100;
|
|
717
860
|
function btcAccountIndexFromPath(path) {
|
|
718
861
|
const segments = path.replace(/^m\//, "").split("/");
|
|
@@ -724,9 +867,28 @@ function btcAccountIndexFromPath(path) {
|
|
|
724
867
|
var _LedgerAdapter = class _LedgerAdapter {
|
|
725
868
|
constructor(connector, options) {
|
|
726
869
|
this.vendor = "ledger";
|
|
870
|
+
// Cancel frees the DMK action and its intent-queue slot, but cannot retract a
|
|
871
|
+
// confirmation screen the device is already showing.
|
|
872
|
+
this.cancelCapability = "stops-waiting";
|
|
727
873
|
this.emitter = new TypedEventEmitter();
|
|
874
|
+
this._operations = new OperationRegistry({
|
|
875
|
+
vendor: "ledger",
|
|
876
|
+
onEnded: (operation, reason) => {
|
|
877
|
+
this.emitter.emit(SDK.OPERATION_ENDED, {
|
|
878
|
+
type: SDK.OPERATION_ENDED,
|
|
879
|
+
payload: { operationId: operation.operationId, reason }
|
|
880
|
+
});
|
|
881
|
+
if (reason === "timeout") {
|
|
882
|
+
void this._releaseOperationConnection(operation);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
});
|
|
728
886
|
this._discoveredDevices = /* @__PURE__ */ new Map();
|
|
729
887
|
this._sessions = /* @__PURE__ */ new Map();
|
|
888
|
+
// Transport each session was opened on, by sessionId. The adapter-wide
|
|
889
|
+
// `_activeConnectionType` moves with every discovery and can go stale.
|
|
890
|
+
this._sessionTransports = /* @__PURE__ */ new Map();
|
|
891
|
+
this._selectedBleReconnectTargets = /* @__PURE__ */ new Map();
|
|
730
892
|
this._uiRegistry = new UiRequestRegistry();
|
|
731
893
|
// BTC App rejects account index >= 100 unless display=true. Cached per
|
|
732
894
|
// adapter instance: first 100+ path asks the user once via UI request,
|
|
@@ -740,10 +902,31 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
740
902
|
this._deviceAuthenticityQueueTail = Promise.resolve();
|
|
741
903
|
// Shared across concurrent callers — only `cancel()` aborts.
|
|
742
904
|
this._doConnectAbortController = null;
|
|
905
|
+
this._unsettledConnectorOperations = /* @__PURE__ */ new Map();
|
|
906
|
+
this._connectorIdleWaiters = /* @__PURE__ */ new Set();
|
|
907
|
+
this._resetPromise = null;
|
|
908
|
+
this._stateGeneration = 0;
|
|
909
|
+
this._connectorTeardownTail = Promise.resolve();
|
|
910
|
+
this._pendingConnectorTeardowns = 0;
|
|
911
|
+
this._activeOperationJobs = /* @__PURE__ */ new Set();
|
|
912
|
+
this._pendingOperationDisconnects = /* @__PURE__ */ new Set();
|
|
743
913
|
this._installProgressLastEmittedValue = -Infinity;
|
|
744
914
|
this.allNetworkGetAddress = createAllNetworkGetAddress({
|
|
745
915
|
callChain: this.callChain.bind(this),
|
|
746
|
-
getChainFingerprint: (connectId, chain) =>
|
|
916
|
+
getChainFingerprint: async (connectId, chain, context) => {
|
|
917
|
+
try {
|
|
918
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
919
|
+
chain,
|
|
920
|
+
(method, params) => this.connectorCall(connectId, method, params, void 0, void 0, void 0, context)
|
|
921
|
+
);
|
|
922
|
+
return success(fingerprint);
|
|
923
|
+
} catch (error) {
|
|
924
|
+
return this.errorToFailure(error);
|
|
925
|
+
}
|
|
926
|
+
},
|
|
927
|
+
retainOperation: (operationId) => this._operations.retain(operationId),
|
|
928
|
+
errorToFailure: (error) => this.errorToFailure(error),
|
|
929
|
+
createCancelScope: (queueKey) => this._jobQueue.createCancelScope(queueKey)
|
|
747
930
|
});
|
|
748
931
|
// ---------------------------------------------------------------------------
|
|
749
932
|
// Private helpers
|
|
@@ -753,7 +936,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
753
936
|
*
|
|
754
937
|
* - If a session already exists for the given connectId, reuse it.
|
|
755
938
|
* - If ANY session exists (Ledger IDs are ephemeral), reuse it.
|
|
756
|
-
* - Otherwise: search →
|
|
939
|
+
* - Otherwise: search → one USB device auto-connects; multiple asks the host to choose.
|
|
757
940
|
*/
|
|
758
941
|
// Mutex for ensureConnected — prevents concurrent calls from establishing duplicate connections
|
|
759
942
|
this._connectingPromise = null;
|
|
@@ -770,6 +953,12 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
770
953
|
});
|
|
771
954
|
};
|
|
772
955
|
this.deviceDisconnectHandler = (data) => {
|
|
956
|
+
const activeOperation = this._operations.findActiveByConnectionKey(data.connectId);
|
|
957
|
+
if (activeOperation && this._activeOperationJobs.has(activeOperation.operationId)) {
|
|
958
|
+
this._pendingOperationDisconnects.add(activeOperation.operationId);
|
|
959
|
+
} else {
|
|
960
|
+
this._operations.endByConnectionKey(data.connectId, "disconnect");
|
|
961
|
+
}
|
|
773
962
|
this._discoveredDevices.delete(data.connectId);
|
|
774
963
|
this._sessions.delete(data.connectId);
|
|
775
964
|
this.emitter.emit(DEVICE.DISCONNECT, {
|
|
@@ -778,10 +967,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
778
967
|
});
|
|
779
968
|
};
|
|
780
969
|
// 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.
|
|
970
|
+
// need to subscribe in one place. The AppInstallProgress variant re-keys
|
|
971
|
+
// sessionId to connectId via `_sessions`, and drops if no mapping exists.
|
|
785
972
|
this.uiEventForwarder = (event) => {
|
|
786
973
|
if (event.type === EConnectorInteraction.AppInstallProgress) {
|
|
787
974
|
let connectId;
|
|
@@ -826,11 +1013,28 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
826
1013
|
this._jobQueue = new DeviceJobQueue();
|
|
827
1014
|
this.registerEventListeners();
|
|
828
1015
|
}
|
|
1016
|
+
_finishBleBinding(status) {
|
|
1017
|
+
const selectionRequestId = this._bindingSelectionRequestId;
|
|
1018
|
+
this._bindingSelectionRequestId = void 0;
|
|
1019
|
+
if (selectionRequestId)
|
|
1020
|
+
this.emitter.emit(UI_REQUEST.DEVICE_BINDING_STATUS, {
|
|
1021
|
+
type: UI_REQUEST.DEVICE_BINDING_STATUS,
|
|
1022
|
+
payload: { selectionRequestId, status }
|
|
1023
|
+
});
|
|
1024
|
+
}
|
|
1025
|
+
_isBleConnection() {
|
|
1026
|
+
return isLedgerBleConnectionType(this._activeConnectionType ?? this.connector.connectionType);
|
|
1027
|
+
}
|
|
829
1028
|
// Transport
|
|
830
1029
|
get activeTransport() {
|
|
831
|
-
return
|
|
1030
|
+
return this._isBleConnection() ? "ble" : "hid";
|
|
832
1031
|
}
|
|
833
1032
|
getAvailableTransports() {
|
|
1033
|
+
if (this.connector.availableTransports) {
|
|
1034
|
+
return this.connector.availableTransports.map(
|
|
1035
|
+
(transport) => transport === "ble" ? "ble" : "hid"
|
|
1036
|
+
);
|
|
1037
|
+
}
|
|
834
1038
|
return this.activeTransport ? [this.activeTransport] : [];
|
|
835
1039
|
}
|
|
836
1040
|
// Connector is bound at construction; switching requires a new adapter.
|
|
@@ -847,21 +1051,40 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
847
1051
|
* The next operation will re-discover and re-connect automatically.
|
|
848
1052
|
*/
|
|
849
1053
|
resetState() {
|
|
1054
|
+
void this._resetStateAndDisconnectSessions();
|
|
1055
|
+
}
|
|
1056
|
+
_resetStateAndDisconnectSessions() {
|
|
1057
|
+
if (this._resetPromise) return this._resetPromise;
|
|
1058
|
+
const sessionIds = new Set(this._sessions.values());
|
|
1059
|
+
this._stateGeneration += 1;
|
|
1060
|
+
this._finishBleBinding("cancelled");
|
|
1061
|
+
this._operations.endAll("runtime-reset");
|
|
1062
|
+
this._doConnectAbortController?.abort();
|
|
850
1063
|
this._discoveredDevices.clear();
|
|
851
1064
|
this._sessions.clear();
|
|
1065
|
+
this._sessionTransports.clear();
|
|
1066
|
+
this._selectedBleReconnectTargets.clear();
|
|
852
1067
|
this._connectingPromise = null;
|
|
1068
|
+
this._doConnectAbortController = null;
|
|
853
1069
|
this._uiRegistry.reset();
|
|
854
1070
|
this._jobQueue.clear();
|
|
855
1071
|
this._btcHighIndexConfirmedThisSession = false;
|
|
1072
|
+
const resetPromise = this._runConnectorTeardown(async () => {
|
|
1073
|
+
for (const sessionId of sessionIds) {
|
|
1074
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
1075
|
+
}
|
|
1076
|
+
});
|
|
1077
|
+
this._resetPromise = resetPromise;
|
|
1078
|
+
return resetPromise.finally(() => {
|
|
1079
|
+
if (this._resetPromise === resetPromise) {
|
|
1080
|
+
this._resetPromise = null;
|
|
1081
|
+
}
|
|
1082
|
+
});
|
|
856
1083
|
}
|
|
857
1084
|
async dispose() {
|
|
858
|
-
this.
|
|
859
|
-
this._jobQueue.clear();
|
|
1085
|
+
await this._resetStateAndDisconnectSessions();
|
|
860
1086
|
this.unregisterEventListeners();
|
|
861
1087
|
this.connector.reset();
|
|
862
|
-
this._discoveredDevices.clear();
|
|
863
|
-
this._sessions.clear();
|
|
864
|
-
this._btcHighIndexConfirmedThisSession = false;
|
|
865
1088
|
this.emitter.removeAllListeners();
|
|
866
1089
|
}
|
|
867
1090
|
uiResponse(response) {
|
|
@@ -871,17 +1094,32 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
871
1094
|
// Device management
|
|
872
1095
|
// ---------------------------------------------------------------------------
|
|
873
1096
|
async searchDevices(options) {
|
|
1097
|
+
return this._searchDevices(options);
|
|
1098
|
+
}
|
|
1099
|
+
async _searchDevices(options, signal) {
|
|
874
1100
|
debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
|
|
875
1101
|
try {
|
|
876
1102
|
if (options?.resetSession) {
|
|
877
|
-
this.
|
|
878
|
-
|
|
879
|
-
this.
|
|
880
|
-
|
|
881
|
-
|
|
1103
|
+
await this._resetStateAndDisconnectSessions();
|
|
1104
|
+
} else {
|
|
1105
|
+
await this._connectorTeardownTail;
|
|
1106
|
+
}
|
|
1107
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
1108
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1109
|
+
const stateGeneration = this._stateGeneration;
|
|
1110
|
+
const devices = await this.connector.searchDevices(
|
|
1111
|
+
options?.transportType ? {
|
|
1112
|
+
transportType: options.transportType,
|
|
1113
|
+
waitForAll: options.waitForAllTransports
|
|
1114
|
+
} : void 0
|
|
1115
|
+
);
|
|
1116
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1117
|
+
if (stateGeneration !== this._stateGeneration) {
|
|
1118
|
+
throw createHwkError({
|
|
1119
|
+
code: HardwareErrorCode3.UserAborted,
|
|
1120
|
+
message: "Ledger discovery was reset"
|
|
1121
|
+
});
|
|
882
1122
|
}
|
|
883
|
-
await this._ensureDevicePermission();
|
|
884
|
-
const devices = await this.connector.searchDevices();
|
|
885
1123
|
this._discoveredDevices.clear();
|
|
886
1124
|
for (const d of devices) {
|
|
887
1125
|
if (d.connectId) {
|
|
@@ -889,7 +1127,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
889
1127
|
}
|
|
890
1128
|
}
|
|
891
1129
|
if (this._discoveredDevices.size === 0) {
|
|
892
|
-
await this._ensureDevicePermission();
|
|
1130
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
893
1131
|
}
|
|
894
1132
|
const result = Array.from(this._discoveredDevices.values());
|
|
895
1133
|
debugLog("[LedgerAdapter][RES]", {
|
|
@@ -908,41 +1146,233 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
908
1146
|
throw err;
|
|
909
1147
|
}
|
|
910
1148
|
}
|
|
1149
|
+
async searchDeviceTargets(options) {
|
|
1150
|
+
const devices = await this.searchDevices(options);
|
|
1151
|
+
return devices.map((device) => ({
|
|
1152
|
+
searchTargetId: device.connectId,
|
|
1153
|
+
searchTargetReusePolicy: resolveSearchTargetReusePolicy(device),
|
|
1154
|
+
vendor: "ledger",
|
|
1155
|
+
connectionType: device.connectionType,
|
|
1156
|
+
kind: "physical",
|
|
1157
|
+
label: device.label,
|
|
1158
|
+
model: device.model,
|
|
1159
|
+
modelName: device.modelName,
|
|
1160
|
+
serialNumber: device.serialNumber
|
|
1161
|
+
}));
|
|
1162
|
+
}
|
|
1163
|
+
async listConnectionTargets(options) {
|
|
1164
|
+
const targets = await this.searchDeviceTargets(options);
|
|
1165
|
+
return targets.map(({ searchTargetId, ...target }) => ({
|
|
1166
|
+
...target,
|
|
1167
|
+
targetId: searchTargetId
|
|
1168
|
+
}));
|
|
1169
|
+
}
|
|
911
1170
|
// USB single-session invariant: evict all sessions, best-effort (see connectDevice).
|
|
912
|
-
async _evictAllSessions() {
|
|
1171
|
+
async _evictAllSessions(preserveOperationId) {
|
|
1172
|
+
this._operations.endAll("explicit", preserveOperationId);
|
|
913
1173
|
if (this._sessions.size === 0) return;
|
|
914
1174
|
const stale = [...this._sessions.values()];
|
|
915
1175
|
this._sessions.clear();
|
|
916
|
-
for (const sid of stale)
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
1176
|
+
for (const sid of stale) this._sessionTransports.delete(sid);
|
|
1177
|
+
await this._runConnectorTeardown(async () => {
|
|
1178
|
+
for (const sid of stale) {
|
|
1179
|
+
try {
|
|
1180
|
+
await this.connector.disconnect(sid);
|
|
1181
|
+
} catch {
|
|
1182
|
+
}
|
|
920
1183
|
}
|
|
921
|
-
}
|
|
1184
|
+
});
|
|
922
1185
|
}
|
|
923
1186
|
static _createDeviceBusyError(method) {
|
|
924
1187
|
return Object.assign(new Error(`Ledger device is busy while calling ${method}`), {
|
|
925
1188
|
code: HardwareErrorCode3.DeviceBusy
|
|
926
1189
|
});
|
|
927
1190
|
}
|
|
928
|
-
async connectDevice(
|
|
1191
|
+
async connectDevice(searchTargetId) {
|
|
1192
|
+
try {
|
|
1193
|
+
return await this._jobQueue.enqueue(
|
|
1194
|
+
searchTargetId || "__ledger_connect__",
|
|
1195
|
+
async (signal) => {
|
|
1196
|
+
const connected = await this._connectTarget(searchTargetId, void 0, signal);
|
|
1197
|
+
if (!connected.success) return connected;
|
|
1198
|
+
return this._createOperation(searchTargetId, connected.payload);
|
|
1199
|
+
},
|
|
1200
|
+
{
|
|
1201
|
+
label: "connectDevice",
|
|
1202
|
+
rejectIfBusy: true,
|
|
1203
|
+
busyError: _LedgerAdapter._createDeviceBusyError("connectDevice")
|
|
1204
|
+
}
|
|
1205
|
+
);
|
|
1206
|
+
} catch (error) {
|
|
1207
|
+
return this.errorToFailure(error);
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
/** Ledger binds whichever BLE device the user picks; its wallet is not checked. */
|
|
1211
|
+
async bindBleDevice(params) {
|
|
1212
|
+
try {
|
|
1213
|
+
return await this._jobQueue.enqueue(
|
|
1214
|
+
"__ledger_bind_ble__",
|
|
1215
|
+
async (signal) => {
|
|
1216
|
+
if (!this.getAvailableTransports().includes("ble")) {
|
|
1217
|
+
throw createHwkError({
|
|
1218
|
+
code: HardwareErrorCode3.TransportNotAvailable,
|
|
1219
|
+
message: "Ledger Bluetooth transport is not available"
|
|
1220
|
+
});
|
|
1221
|
+
}
|
|
1222
|
+
this._activeConnectionType = "ble";
|
|
1223
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
1224
|
+
const attempt = {
|
|
1225
|
+
extra: params.extra,
|
|
1226
|
+
bindingReason: "manual-rebind"
|
|
1227
|
+
};
|
|
1228
|
+
try {
|
|
1229
|
+
const connectId = await this._connectFirstOrSelect(
|
|
1230
|
+
[],
|
|
1231
|
+
void 0,
|
|
1232
|
+
true,
|
|
1233
|
+
void 0,
|
|
1234
|
+
attempt,
|
|
1235
|
+
signal
|
|
1236
|
+
);
|
|
1237
|
+
if (!attempt.bindingSaved) {
|
|
1238
|
+
await this._dropSession(connectId, signal);
|
|
1239
|
+
throw createHwkError({
|
|
1240
|
+
code: HardwareErrorCode3.UnknownError,
|
|
1241
|
+
message: "Bluetooth binding could not be saved",
|
|
1242
|
+
origin: "host"
|
|
1243
|
+
});
|
|
1244
|
+
}
|
|
1245
|
+
return success(connectId);
|
|
1246
|
+
} catch (error) {
|
|
1247
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
1248
|
+
throw error;
|
|
1249
|
+
}
|
|
1250
|
+
},
|
|
1251
|
+
{
|
|
1252
|
+
label: "bindBleDevice",
|
|
1253
|
+
rejectIfBusy: true,
|
|
1254
|
+
busyError: _LedgerAdapter._createDeviceBusyError("bindBleDevice")
|
|
1255
|
+
}
|
|
1256
|
+
);
|
|
1257
|
+
} catch (error) {
|
|
1258
|
+
return this.errorToFailure(error);
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
async acquireOperation(connectId, context) {
|
|
1262
|
+
try {
|
|
1263
|
+
return await this._jobQueue.enqueue(
|
|
1264
|
+
connectId || "__ledger_acquire__",
|
|
1265
|
+
async (signal) => {
|
|
1266
|
+
const transport = this._isBleConnection() ? "ble" : "usb";
|
|
1267
|
+
const hint = context.knownConnections?.find(
|
|
1268
|
+
(connection) => connection.transport === transport
|
|
1269
|
+
);
|
|
1270
|
+
const target = hint && hint.transport !== "qr" ? hint.connectId : connectId;
|
|
1271
|
+
await this._ensureDevicePermission(target, void 0, signal);
|
|
1272
|
+
const attempt = {
|
|
1273
|
+
...context,
|
|
1274
|
+
extra: context.extra ? { ...context.extra } : void 0
|
|
1275
|
+
};
|
|
1276
|
+
try {
|
|
1277
|
+
const resolvedConnectId = await this.ensureConnected(
|
|
1278
|
+
target,
|
|
1279
|
+
signal,
|
|
1280
|
+
true,
|
|
1281
|
+
void 0,
|
|
1282
|
+
attempt
|
|
1283
|
+
);
|
|
1284
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1285
|
+
return this._createOperation(connectId, resolvedConnectId);
|
|
1286
|
+
} catch (error) {
|
|
1287
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
1288
|
+
throw error;
|
|
1289
|
+
}
|
|
1290
|
+
},
|
|
1291
|
+
{
|
|
1292
|
+
label: "acquireOperation",
|
|
1293
|
+
rejectIfBusy: true,
|
|
1294
|
+
busyError: _LedgerAdapter._createDeviceBusyError("acquireOperation")
|
|
1295
|
+
}
|
|
1296
|
+
);
|
|
1297
|
+
} catch (error) {
|
|
1298
|
+
return this.errorToFailure(error);
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
_createOperation(searchTargetId, resolvedConnectId) {
|
|
1302
|
+
this._operations.endByConnectionKey(resolvedConnectId, "explicit");
|
|
1303
|
+
const sessionId = this._sessions.get(resolvedConnectId);
|
|
1304
|
+
if (sessionId) this._operations.endByConnectionKey(sessionId, "explicit");
|
|
1305
|
+
const connectionType = sessionId && this._sessionTransports.get(sessionId) || (this._isBleConnection() ? "ble" : "usb");
|
|
1306
|
+
const device = this._discoveredDevices.get(resolvedConnectId) ?? {
|
|
1307
|
+
vendor: "ledger",
|
|
1308
|
+
model: "unknown",
|
|
1309
|
+
firmwareVersion: "",
|
|
1310
|
+
deviceId: "",
|
|
1311
|
+
connectId: resolvedConnectId,
|
|
1312
|
+
connectionType
|
|
1313
|
+
};
|
|
1314
|
+
const operation = this._operations.create({
|
|
1315
|
+
searchTargetId,
|
|
1316
|
+
connectId: resolvedConnectId,
|
|
1317
|
+
device,
|
|
1318
|
+
connectionType,
|
|
1319
|
+
connectionKeys: [this._sessions.get(resolvedConnectId) ?? ""]
|
|
1320
|
+
});
|
|
1321
|
+
return success(operation.operationId);
|
|
1322
|
+
}
|
|
1323
|
+
async _connectTarget(connectId, preserveOperationId, signal) {
|
|
929
1324
|
debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
|
|
930
1325
|
try {
|
|
931
|
-
|
|
1326
|
+
this._assertConnectorReady("connectDevice");
|
|
1327
|
+
const discoveredType = this._discoveredDevices.get(connectId)?.connectionType;
|
|
1328
|
+
if (discoveredType === "usb" || discoveredType === "ble") {
|
|
1329
|
+
this._activeConnectionType = discoveredType;
|
|
1330
|
+
}
|
|
1331
|
+
if (this._isBleConnection() && !connectId) {
|
|
932
1332
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
933
1333
|
code: HardwareErrorCode3.DeviceNotFound
|
|
934
1334
|
});
|
|
935
1335
|
}
|
|
936
|
-
|
|
937
|
-
|
|
1336
|
+
await this._ensureDevicePermission(connectId, void 0, signal);
|
|
1337
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1338
|
+
const isMultiTransport = (this.connector.availableTransports?.length ?? 0) > 1;
|
|
1339
|
+
if (!isMultiTransport && this._isBleConnection()) {
|
|
1340
|
+
const previousSessionId = this._sessions.get(connectId);
|
|
1341
|
+
this._operations.endByConnectionKey(connectId, "explicit", preserveOperationId);
|
|
1342
|
+
if (previousSessionId) {
|
|
1343
|
+
this._operations.endByConnectionKey(previousSessionId, "explicit", preserveOperationId);
|
|
1344
|
+
this._sessions.delete(connectId);
|
|
1345
|
+
await this.connector.disconnect(previousSessionId).catch(() => void 0);
|
|
1346
|
+
}
|
|
1347
|
+
} else {
|
|
1348
|
+
await this._evictAllSessions(preserveOperationId);
|
|
1349
|
+
}
|
|
1350
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1351
|
+
const stateGeneration = this._stateGeneration;
|
|
1352
|
+
const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
|
|
1353
|
+
let session;
|
|
1354
|
+
this._connectingConnectId = connectId;
|
|
1355
|
+
try {
|
|
1356
|
+
session = this.connector.availableTransports?.length ? await this.connector.connect(connectId, {
|
|
1357
|
+
transportType: this._activeConnectionType ?? "usb"
|
|
1358
|
+
}) : await this.connector.connect(connectId);
|
|
1359
|
+
if (signal?.aborted || stateGeneration !== this._stateGeneration) {
|
|
1360
|
+
await this.connector.disconnect(session.sessionId).catch(() => void 0);
|
|
1361
|
+
throw Object.assign(new Error("Ledger connection aborted"), {
|
|
1362
|
+
code: HardwareErrorCode3.UserAborted
|
|
1363
|
+
});
|
|
1364
|
+
}
|
|
1365
|
+
} finally {
|
|
1366
|
+
if (this._connectingConnectId === connectId) this._connectingConnectId = void 0;
|
|
1367
|
+
releaseOperation();
|
|
938
1368
|
}
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
this.
|
|
1369
|
+
const resolvedConnectId = session.deviceInfo?.connectId || connectId;
|
|
1370
|
+
this._sessions.set(resolvedConnectId, session.sessionId);
|
|
1371
|
+
this._sessionTransports.set(session.sessionId, this._isBleConnection() ? "ble" : "usb");
|
|
942
1372
|
if (session.deviceInfo) {
|
|
943
|
-
this._discoveredDevices.set(
|
|
1373
|
+
this._discoveredDevices.set(resolvedConnectId, session.deviceInfo);
|
|
944
1374
|
}
|
|
945
|
-
const result = success(
|
|
1375
|
+
const result = success(resolvedConnectId);
|
|
946
1376
|
debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
|
|
947
1377
|
return result;
|
|
948
1378
|
} catch (err) {
|
|
@@ -955,30 +1385,60 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
955
1385
|
return failureResult;
|
|
956
1386
|
}
|
|
957
1387
|
}
|
|
958
|
-
async
|
|
1388
|
+
async releaseOperation(operationId) {
|
|
1389
|
+
const operation = this._operations.find(operationId);
|
|
1390
|
+
if (!operation) {
|
|
1391
|
+
this._operations.resolve(operationId);
|
|
1392
|
+
return;
|
|
1393
|
+
}
|
|
1394
|
+
const endedOperation = this._operations.end(operationId, "explicit");
|
|
1395
|
+
if (!endedOperation) return;
|
|
1396
|
+
const { connectId } = operation;
|
|
959
1397
|
debugLog("[LedgerAdapter][REQ]", {
|
|
960
|
-
method: "
|
|
1398
|
+
method: "releaseOperation",
|
|
961
1399
|
connectId,
|
|
962
1400
|
params: { connectId }
|
|
963
1401
|
});
|
|
964
1402
|
try {
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
await this.connector.disconnect(sessionId);
|
|
968
|
-
this._sessions.delete(connectId);
|
|
969
|
-
}
|
|
970
|
-
debugLog("[LedgerAdapter][RES]", { method: "disconnectDevice", success: true });
|
|
1403
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1404
|
+
debugLog("[LedgerAdapter][RES]", { method: "releaseOperation", success: true });
|
|
971
1405
|
} catch (err) {
|
|
972
1406
|
const e = err;
|
|
973
1407
|
debugLog("[LedgerAdapter][RES]", {
|
|
974
|
-
method: "
|
|
1408
|
+
method: "releaseOperation",
|
|
975
1409
|
success: false,
|
|
976
1410
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
977
1411
|
});
|
|
978
1412
|
throw err;
|
|
979
1413
|
}
|
|
980
1414
|
}
|
|
981
|
-
async
|
|
1415
|
+
async _releaseOperationConnection(operation) {
|
|
1416
|
+
const sessionIds = /* @__PURE__ */ new Set();
|
|
1417
|
+
for (const [connectId, sessionId] of this._sessions) {
|
|
1418
|
+
if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
|
|
1419
|
+
this._sessions.delete(connectId);
|
|
1420
|
+
sessionIds.add(sessionId);
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
for (const sessionId of sessionIds) {
|
|
1424
|
+
await this._runConnectorTeardown(
|
|
1425
|
+
() => this.connector.disconnect(sessionId).catch(() => void 0)
|
|
1426
|
+
);
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
async _releaseLostOperationConnection(operationId) {
|
|
1430
|
+
const endedOperation = this._operations.end(operationId, "disconnect");
|
|
1431
|
+
if (!endedOperation) return;
|
|
1432
|
+
this._discoveredDevices.delete(endedOperation.connectId);
|
|
1433
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1434
|
+
}
|
|
1435
|
+
async getDeviceInfo(connectIdOrOperationId, deviceId) {
|
|
1436
|
+
let connectId;
|
|
1437
|
+
try {
|
|
1438
|
+
connectId = isHardwareOperationId(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
|
|
1439
|
+
} catch (error) {
|
|
1440
|
+
return this.errorToFailure(error);
|
|
1441
|
+
}
|
|
982
1442
|
debugLog("[LedgerAdapter][REQ]", {
|
|
983
1443
|
method: "getDeviceInfo",
|
|
984
1444
|
connectId,
|
|
@@ -1013,12 +1473,9 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1013
1473
|
success: false,
|
|
1014
1474
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
1015
1475
|
});
|
|
1016
|
-
|
|
1476
|
+
return this.errorToFailure(err);
|
|
1017
1477
|
}
|
|
1018
1478
|
}
|
|
1019
|
-
getSupportedChains() {
|
|
1020
|
-
return ["evm", "btc", "sol", "tron"];
|
|
1021
|
-
}
|
|
1022
1479
|
// ---------------------------------------------------------------------------
|
|
1023
1480
|
// Chain call helper
|
|
1024
1481
|
// ---------------------------------------------------------------------------
|
|
@@ -1053,13 +1510,23 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1053
1510
|
if (params && typeof params === "object") {
|
|
1054
1511
|
const {
|
|
1055
1512
|
autoInstallApp,
|
|
1513
|
+
operationId,
|
|
1056
1514
|
passphraseState: _passphraseState,
|
|
1057
1515
|
useEmptyPassphrase: _useEmptyPassphrase,
|
|
1516
|
+
knownConnections,
|
|
1517
|
+
extra,
|
|
1518
|
+
allowDeviceSelection,
|
|
1519
|
+
supportedTransports,
|
|
1058
1520
|
...rest
|
|
1059
1521
|
} = params;
|
|
1060
1522
|
return {
|
|
1061
1523
|
commonParams: {
|
|
1062
|
-
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
|
|
1524
|
+
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
|
|
1525
|
+
operationId: typeof operationId === "string" ? operationId : void 0,
|
|
1526
|
+
knownConnections,
|
|
1527
|
+
extra,
|
|
1528
|
+
allowDeviceSelection: typeof allowDeviceSelection === "boolean" ? allowDeviceSelection : void 0,
|
|
1529
|
+
supportedTransports
|
|
1063
1530
|
},
|
|
1064
1531
|
rest
|
|
1065
1532
|
};
|
|
@@ -1235,9 +1702,28 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1235
1702
|
);
|
|
1236
1703
|
}
|
|
1237
1704
|
// ---------------------------------------------------------------------------
|
|
1238
|
-
//
|
|
1239
|
-
//
|
|
1240
|
-
|
|
1705
|
+
// Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
|
|
1706
|
+
// ---------------------------------------------------------------------------
|
|
1707
|
+
zcashGetFullViewingKey(connectId, deviceId, params) {
|
|
1708
|
+
return this.callChainWithMergedParams(
|
|
1709
|
+
connectId,
|
|
1710
|
+
deviceId,
|
|
1711
|
+
"zcash",
|
|
1712
|
+
"zcashGetFullViewingKey",
|
|
1713
|
+
params
|
|
1714
|
+
);
|
|
1715
|
+
}
|
|
1716
|
+
zcashGetShieldedAddress(connectId, deviceId, params) {
|
|
1717
|
+
return this.callChainWithMergedParams(
|
|
1718
|
+
connectId,
|
|
1719
|
+
deviceId,
|
|
1720
|
+
"zcash",
|
|
1721
|
+
"zcashGetShieldedAddress",
|
|
1722
|
+
params
|
|
1723
|
+
);
|
|
1724
|
+
}
|
|
1725
|
+
// ---------------------------------------------------------------------------
|
|
1726
|
+
// App management: OS-level app install/list, no fingerprint or chain dispatch.
|
|
1241
1727
|
// ---------------------------------------------------------------------------
|
|
1242
1728
|
async installApp(connectId, appName) {
|
|
1243
1729
|
try {
|
|
@@ -1323,7 +1809,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1323
1809
|
);
|
|
1324
1810
|
}
|
|
1325
1811
|
await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
|
|
1326
|
-
this.
|
|
1812
|
+
await this._resetStateAndDisconnectSessions();
|
|
1327
1813
|
}
|
|
1328
1814
|
const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
|
|
1329
1815
|
if (!result.isGenuine) {
|
|
@@ -1349,10 +1835,10 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1349
1835
|
if (relayUrl) {
|
|
1350
1836
|
try {
|
|
1351
1837
|
await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
|
|
1352
|
-
this.
|
|
1838
|
+
await this._resetStateAndDisconnectSessions();
|
|
1353
1839
|
} catch {
|
|
1354
1840
|
this.connector.reset();
|
|
1355
|
-
this.
|
|
1841
|
+
await this._resetStateAndDisconnectSessions();
|
|
1356
1842
|
}
|
|
1357
1843
|
}
|
|
1358
1844
|
}
|
|
@@ -1364,6 +1850,20 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1364
1850
|
this.emitter.off(event, listener);
|
|
1365
1851
|
}
|
|
1366
1852
|
cancel(connectId) {
|
|
1853
|
+
const namedOperationIsLive = (id) => {
|
|
1854
|
+
try {
|
|
1855
|
+
this._operations.resolve(id);
|
|
1856
|
+
return true;
|
|
1857
|
+
} catch {
|
|
1858
|
+
return false;
|
|
1859
|
+
}
|
|
1860
|
+
};
|
|
1861
|
+
if (isHardwareOperationId(connectId) && !namedOperationIsLive(connectId)) {
|
|
1862
|
+
debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
|
|
1863
|
+
connectId
|
|
1864
|
+
});
|
|
1865
|
+
return;
|
|
1866
|
+
}
|
|
1367
1867
|
const userAbortReason = Object.assign(new Error("User aborted operation"), {
|
|
1368
1868
|
code: HardwareErrorCode3.UserAborted,
|
|
1369
1869
|
_tag: ERROR_TAG.UserAborted
|
|
@@ -1374,14 +1874,46 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1374
1874
|
this._lastCancelReason = void 0;
|
|
1375
1875
|
}
|
|
1376
1876
|
}, 2e3);
|
|
1377
|
-
this.
|
|
1378
|
-
|
|
1379
|
-
|
|
1877
|
+
const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
|
|
1878
|
+
let operationId;
|
|
1879
|
+
if (isHardwareOperationId(connectId)) {
|
|
1880
|
+
operationId = connectId;
|
|
1881
|
+
} else if (!connectId && isHardwareOperationId(activeJobId)) {
|
|
1882
|
+
operationId = activeJobId;
|
|
1883
|
+
}
|
|
1884
|
+
let resolvedConnectId = connectId;
|
|
1885
|
+
if (operationId) {
|
|
1886
|
+
try {
|
|
1887
|
+
resolvedConnectId = this._operations.resolve(operationId).connectId;
|
|
1888
|
+
} catch {
|
|
1889
|
+
resolvedConnectId = void 0;
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
|
|
1893
|
+
const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
|
|
1894
|
+
if (!connectId) {
|
|
1895
|
+
this._uiRegistry.cancel();
|
|
1896
|
+
} else if (pendingOperationId) {
|
|
1897
|
+
this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
|
|
1898
|
+
}
|
|
1899
|
+
this._finishBleBinding("cancelled");
|
|
1900
|
+
const queueKeys = /* @__PURE__ */ new Set();
|
|
1901
|
+
if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
|
|
1902
|
+
if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
|
|
1903
|
+
if (queueKeys.size) {
|
|
1904
|
+
let cancelledAnyJob = false;
|
|
1905
|
+
for (const key of queueKeys) {
|
|
1906
|
+
cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
|
|
1907
|
+
}
|
|
1908
|
+
debugLog("[LedgerAdapter] cancel routed to queue keys", {
|
|
1909
|
+
queueKeys: [...queueKeys],
|
|
1910
|
+
cancelledAnyJob
|
|
1911
|
+
});
|
|
1380
1912
|
} else {
|
|
1381
1913
|
this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
|
|
1382
1914
|
}
|
|
1383
|
-
if (
|
|
1384
|
-
const sessionId = this._sessions.get(
|
|
1915
|
+
if (resolvedConnectId) {
|
|
1916
|
+
const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
|
|
1385
1917
|
void this.connector.cancel(sessionId);
|
|
1386
1918
|
} else {
|
|
1387
1919
|
for (const sid of this._sessions.values()) void this.connector.cancel(sid);
|
|
@@ -1389,45 +1921,85 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1389
1921
|
if (this._connectingPromise) {
|
|
1390
1922
|
this._doConnectAbortController?.abort(userAbortReason);
|
|
1391
1923
|
}
|
|
1924
|
+
const connectingConnectId = this._connectingConnectId;
|
|
1925
|
+
if (connectingConnectId) void this.connector.cancel(connectingConnectId);
|
|
1392
1926
|
}
|
|
1393
1927
|
// ---------------------------------------------------------------------------
|
|
1394
1928
|
// Chain fingerprint
|
|
1395
1929
|
// ---------------------------------------------------------------------------
|
|
1930
|
+
/** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
|
|
1396
1931
|
async getChainFingerprint(connectId, deviceId, chain) {
|
|
1397
1932
|
try {
|
|
1398
1933
|
const fingerprint = await this._computeChainFingerprint(
|
|
1399
1934
|
chain,
|
|
1400
1935
|
(method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
|
|
1401
1936
|
);
|
|
1937
|
+
if (deviceId) {
|
|
1938
|
+
if (fingerprint !== deviceId) {
|
|
1939
|
+
return failure2(
|
|
1940
|
+
HardwareErrorCode3.DeviceMismatch,
|
|
1941
|
+
formatDeviceMismatchError(deviceId, fingerprint)
|
|
1942
|
+
);
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1402
1945
|
return success(fingerprint);
|
|
1403
1946
|
} catch (err) {
|
|
1404
1947
|
debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
|
|
1405
1948
|
return this.errorToFailure(err);
|
|
1406
1949
|
}
|
|
1407
1950
|
}
|
|
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 };
|
|
1951
|
+
/** Ledger takes the selected BLE endpoint as the device and binds it right away. */
|
|
1952
|
+
async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal) {
|
|
1414
1953
|
try {
|
|
1415
|
-
const
|
|
1416
|
-
|
|
1417
|
-
|
|
1954
|
+
const outcome = await requestSaveDeviceBinding(
|
|
1955
|
+
this.emitter,
|
|
1956
|
+
this._uiRegistry,
|
|
1957
|
+
{
|
|
1958
|
+
selectionRequestId,
|
|
1959
|
+
connection: { transport: "ble", connectId },
|
|
1960
|
+
extra: context?.extra,
|
|
1961
|
+
operationId
|
|
1962
|
+
},
|
|
1963
|
+
signal
|
|
1418
1964
|
);
|
|
1419
|
-
if (
|
|
1420
|
-
|
|
1965
|
+
if (context) context.bindingSaved = outcome.saved;
|
|
1966
|
+
if (!outcome.saved) {
|
|
1967
|
+
debugLog("[LedgerAdapter] BLE binding not persisted by host", {
|
|
1968
|
+
connectId,
|
|
1969
|
+
reason: outcome.reason
|
|
1970
|
+
});
|
|
1421
1971
|
}
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1972
|
+
} catch (error) {
|
|
1973
|
+
await this._dropSession(connectId, signal);
|
|
1974
|
+
throw error;
|
|
1975
|
+
} finally {
|
|
1976
|
+
if (this._bindingSelectionRequestId === selectionRequestId) {
|
|
1977
|
+
this._bindingSelectionRequestId = void 0;
|
|
1427
1978
|
}
|
|
1428
|
-
throw err;
|
|
1429
1979
|
}
|
|
1430
1980
|
}
|
|
1981
|
+
async _dropSession(connectId, signal) {
|
|
1982
|
+
const sessionId = this._sessions.get(connectId);
|
|
1983
|
+
this._sessions.delete(connectId);
|
|
1984
|
+
if (!sessionId) return;
|
|
1985
|
+
this._sessionTransports.delete(sessionId);
|
|
1986
|
+
const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
|
|
1987
|
+
() => void 0
|
|
1988
|
+
);
|
|
1989
|
+
if (!signal.aborted) await teardown;
|
|
1990
|
+
}
|
|
1991
|
+
/** Verify on the acquired session without re-entering the job queue. */
|
|
1992
|
+
async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
|
|
1993
|
+
if (!deviceId) return { success: true };
|
|
1994
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
1995
|
+
chain,
|
|
1996
|
+
(method, params) => this._callConnector(sessionId, method, params)
|
|
1997
|
+
);
|
|
1998
|
+
if (fingerprint === deviceId) {
|
|
1999
|
+
return { success: true };
|
|
2000
|
+
}
|
|
2001
|
+
return { success: false, expected: deviceId, actual: fingerprint };
|
|
2002
|
+
}
|
|
1431
2003
|
/**
|
|
1432
2004
|
* Compute the chain fingerprint via a caller-supplied call strategy.
|
|
1433
2005
|
*
|
|
@@ -1455,12 +2027,24 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1455
2027
|
address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
|
|
1456
2028
|
} else if (chain === "tron") {
|
|
1457
2029
|
address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
|
|
2030
|
+
} else if (chain === "zcash") {
|
|
2031
|
+
address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
|
|
1458
2032
|
} else {
|
|
1459
2033
|
throw new Error(`Unsupported chain for fingerprint: ${chain}`);
|
|
1460
2034
|
}
|
|
1461
2035
|
return deriveDeviceFingerprint(address);
|
|
1462
2036
|
}
|
|
1463
|
-
|
|
2037
|
+
/**
|
|
2038
|
+
* Operation owning the running job, so a mid-call UI request can name it.
|
|
2039
|
+
* Undefined at cold start when no operation owns the job.
|
|
2040
|
+
*/
|
|
2041
|
+
_activeOperationId() {
|
|
2042
|
+
const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
|
|
2043
|
+
if (!activeJobId) return void 0;
|
|
2044
|
+
if (isHardwareOperationId(activeJobId)) return activeJobId;
|
|
2045
|
+
return this._operations.findActiveByConnectionKey(activeJobId)?.operationId;
|
|
2046
|
+
}
|
|
2047
|
+
// Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
|
|
1464
2048
|
// The user must press Confirm after unlocking, which triggers a search retry.
|
|
1465
2049
|
// If `signal` is provided, an abort cancels the pending UI request so the
|
|
1466
2050
|
// registry slot is released and a stale RECEIVE_DEVICE_CONNECT won't land in
|
|
@@ -1469,15 +2053,18 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1469
2053
|
if (signal?.aborted) {
|
|
1470
2054
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1471
2055
|
}
|
|
2056
|
+
const operationId = this._activeOperationId();
|
|
1472
2057
|
const waitPromise = this._uiRegistry.wait(
|
|
1473
|
-
UI_REQUEST.REQUEST_DEVICE_CONNECT
|
|
2058
|
+
UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
2059
|
+
{ operationId }
|
|
1474
2060
|
);
|
|
1475
2061
|
this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_CONNECT, {
|
|
1476
2062
|
type: UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
1477
2063
|
payload: {
|
|
1478
2064
|
vendor: "ledger",
|
|
1479
2065
|
reason: "device-not-found",
|
|
1480
|
-
message: "Please connect and unlock your Ledger device"
|
|
2066
|
+
message: "Please connect and unlock your Ledger device",
|
|
2067
|
+
operationId
|
|
1481
2068
|
}
|
|
1482
2069
|
});
|
|
1483
2070
|
let payload;
|
|
@@ -1538,15 +2125,18 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1538
2125
|
return { ...params, showOnDevice: true };
|
|
1539
2126
|
}
|
|
1540
2127
|
async _waitForBtcHighIndexConfirm(path, accountIndex) {
|
|
2128
|
+
const operationId = this._activeOperationId();
|
|
1541
2129
|
const waitPromise = this._uiRegistry.wait(
|
|
1542
|
-
UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM
|
|
2130
|
+
UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2131
|
+
{ operationId }
|
|
1543
2132
|
);
|
|
1544
2133
|
this.emitter.emit(UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
|
|
1545
2134
|
type: UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
1546
2135
|
payload: {
|
|
1547
2136
|
vendor: "ledger",
|
|
1548
2137
|
path,
|
|
1549
|
-
accountIndex
|
|
2138
|
+
accountIndex,
|
|
2139
|
+
operationId
|
|
1550
2140
|
}
|
|
1551
2141
|
});
|
|
1552
2142
|
try {
|
|
@@ -1563,12 +2153,14 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1563
2153
|
// Ask the user whether to install a missing app (autoInstallApp flow).
|
|
1564
2154
|
// Same register-then-emit ordering as the BTC high-index gate.
|
|
1565
2155
|
async _waitForInstallAppConfirm(appName) {
|
|
2156
|
+
const operationId = this._activeOperationId();
|
|
1566
2157
|
const waitPromise = this._uiRegistry.wait(
|
|
1567
|
-
UI_REQUEST.REQUEST_INSTALL_APP
|
|
2158
|
+
UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2159
|
+
{ operationId }
|
|
1568
2160
|
);
|
|
1569
2161
|
this.emitter.emit(UI_REQUEST.REQUEST_INSTALL_APP, {
|
|
1570
2162
|
type: UI_REQUEST.REQUEST_INSTALL_APP,
|
|
1571
|
-
payload: { vendor: "ledger", appName }
|
|
2163
|
+
payload: { vendor: "ledger", appName, operationId }
|
|
1572
2164
|
});
|
|
1573
2165
|
try {
|
|
1574
2166
|
const payload = await waitPromise;
|
|
@@ -1584,16 +2176,17 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1584
2176
|
// Layer 1 entry. Caller signal only races the outer awaiter; the shared
|
|
1585
2177
|
// `_doConnect` runs under its own internal controller so caller A's cancel
|
|
1586
2178
|
// doesn't kill caller B's await.
|
|
1587
|
-
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
|
|
2179
|
+
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
1588
2180
|
if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
|
|
1589
|
-
|
|
2181
|
+
this._assertConnectorReady("connectDevice");
|
|
2182
|
+
if (this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
|
|
1590
2183
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1591
2184
|
code: HardwareErrorCode3.DeviceNotFound
|
|
1592
2185
|
});
|
|
1593
2186
|
}
|
|
1594
2187
|
if (connectId && this._sessions.has(connectId)) return connectId;
|
|
1595
2188
|
if (!connectId && this._sessions.size > 0) {
|
|
1596
|
-
if (!
|
|
2189
|
+
if (!this._isBleConnection() && this._sessions.size > 1) {
|
|
1597
2190
|
throw Object.assign(
|
|
1598
2191
|
new Error(
|
|
1599
2192
|
"Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
|
|
@@ -1603,15 +2196,24 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1603
2196
|
}
|
|
1604
2197
|
return this._sessions.keys().next().value;
|
|
1605
2198
|
}
|
|
1606
|
-
if (!this._connectingPromise) {
|
|
1607
|
-
|
|
1608
|
-
|
|
2199
|
+
if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
|
|
2200
|
+
const controller = new AbortController();
|
|
2201
|
+
this._doConnectAbortController = controller;
|
|
2202
|
+
const innerSignal = controller.signal;
|
|
1609
2203
|
this._connectingPromise = (async () => {
|
|
1610
2204
|
try {
|
|
1611
|
-
return await this._doConnect(
|
|
2205
|
+
return await this._doConnect(
|
|
2206
|
+
innerSignal,
|
|
2207
|
+
connectId,
|
|
2208
|
+
allowUsbEphemeralFallback,
|
|
2209
|
+
preserveOperationId,
|
|
2210
|
+
context
|
|
2211
|
+
);
|
|
1612
2212
|
} finally {
|
|
1613
|
-
this.
|
|
1614
|
-
|
|
2213
|
+
if (this._doConnectAbortController === controller) {
|
|
2214
|
+
this._connectingPromise = null;
|
|
2215
|
+
this._doConnectAbortController = null;
|
|
2216
|
+
}
|
|
1615
2217
|
}
|
|
1616
2218
|
})();
|
|
1617
2219
|
}
|
|
@@ -1620,22 +2222,57 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1620
2222
|
// Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
|
|
1621
2223
|
// Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
|
|
1622
2224
|
// 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
|
-
|
|
2225
|
+
async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
2226
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2227
|
+
if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
|
|
2228
|
+
this._activeConnectionType = "usb";
|
|
2229
|
+
const usbDevices = await this._searchDevices({ transportType: "usb" }, internalSignal);
|
|
2230
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2231
|
+
if (usbDevices.length > 0) {
|
|
2232
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2233
|
+
(connection) => connection.transport === "usb"
|
|
2234
|
+
);
|
|
2235
|
+
const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
|
|
2236
|
+
return this._connectFirstOrSelect(
|
|
2237
|
+
usbDevices,
|
|
2238
|
+
usbTarget,
|
|
2239
|
+
allowUsbEphemeralFallback,
|
|
2240
|
+
preserveOperationId,
|
|
2241
|
+
context,
|
|
2242
|
+
internalSignal
|
|
2243
|
+
);
|
|
2244
|
+
}
|
|
2245
|
+
if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
|
|
2246
|
+
throw createHwkError({
|
|
2247
|
+
code: HardwareErrorCode3.DeviceNotFound,
|
|
2248
|
+
message: "This Ledger model has no Bluetooth transport; connect it over USB"
|
|
2249
|
+
});
|
|
2250
|
+
}
|
|
2251
|
+
this._activeConnectionType = "ble";
|
|
2252
|
+
const knownBle = context?.knownConnections?.find(
|
|
2253
|
+
(connection) => connection.transport === "ble"
|
|
2254
|
+
);
|
|
2255
|
+
if (knownBle?.transport === "ble") {
|
|
2256
|
+
return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
|
|
2257
|
+
}
|
|
2258
|
+
if (targetConnectId && context?.knownConnections === void 0) {
|
|
2259
|
+
throw createHwkError({
|
|
2260
|
+
code: HardwareErrorCode3.DeviceNotFound,
|
|
2261
|
+
message: "Ledger connection metadata is required before starting Bluetooth binding"
|
|
2262
|
+
});
|
|
1638
2263
|
}
|
|
2264
|
+
const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
|
|
2265
|
+
return this._connectFirstOrSelect(
|
|
2266
|
+
bleDevices,
|
|
2267
|
+
void 0,
|
|
2268
|
+
allowUsbEphemeralFallback,
|
|
2269
|
+
preserveOperationId,
|
|
2270
|
+
context,
|
|
2271
|
+
internalSignal
|
|
2272
|
+
);
|
|
2273
|
+
}
|
|
2274
|
+
if (this._isBleConnection() && targetConnectId) {
|
|
2275
|
+
return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
|
|
1639
2276
|
}
|
|
1640
2277
|
let confirms = 0;
|
|
1641
2278
|
while (!internalSignal.aborted) {
|
|
@@ -1643,22 +2280,28 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1643
2280
|
type: EConnectorInteraction.Searching,
|
|
1644
2281
|
payload: { sessionId: "" }
|
|
1645
2282
|
});
|
|
1646
|
-
let devices = await this.
|
|
2283
|
+
let devices = await this._searchDevices(void 0, internalSignal);
|
|
2284
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1647
2285
|
if (devices.length === 0) {
|
|
1648
2286
|
for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
|
|
1649
2287
|
await new Promise((resolve) => {
|
|
1650
2288
|
setTimeout(resolve, DEVICE_CONNECT_RETRY_DELAY_MS);
|
|
1651
2289
|
});
|
|
1652
|
-
|
|
2290
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2291
|
+
devices = await this._searchDevices(void 0, internalSignal);
|
|
2292
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1653
2293
|
if (devices.length > 0) break;
|
|
1654
2294
|
}
|
|
1655
2295
|
}
|
|
1656
|
-
if (devices.length > 0) {
|
|
2296
|
+
if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
|
|
1657
2297
|
try {
|
|
1658
2298
|
return await this._connectFirstOrSelect(
|
|
1659
2299
|
devices,
|
|
1660
2300
|
targetConnectId,
|
|
1661
|
-
allowUsbEphemeralFallback
|
|
2301
|
+
allowUsbEphemeralFallback,
|
|
2302
|
+
preserveOperationId,
|
|
2303
|
+
context,
|
|
2304
|
+
internalSignal
|
|
1662
2305
|
);
|
|
1663
2306
|
} catch (err) {
|
|
1664
2307
|
if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
|
|
@@ -1687,45 +2330,143 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1687
2330
|
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1688
2331
|
throw new Error("_doConnect aborted");
|
|
1689
2332
|
}
|
|
1690
|
-
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback
|
|
2333
|
+
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
|
|
2334
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1691
2335
|
if (targetConnectId) {
|
|
1692
2336
|
const target = devices.find(
|
|
1693
2337
|
(d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
|
|
1694
2338
|
);
|
|
1695
2339
|
if (target) {
|
|
1696
|
-
return this._connectDeviceOrThrow(target.connectId);
|
|
2340
|
+
return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
|
|
1697
2341
|
}
|
|
1698
|
-
if (!
|
|
2342
|
+
if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
|
|
1699
2343
|
debugLog(
|
|
1700
2344
|
`[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
|
|
1701
2345
|
);
|
|
1702
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2346
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1703
2347
|
}
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
2348
|
+
if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
|
|
2349
|
+
const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
|
|
2350
|
+
code: HardwareErrorCode3.DeviceNotFound
|
|
2351
|
+
});
|
|
2352
|
+
if (this._isBleConnection()) {
|
|
2353
|
+
err._tag = ERROR_TAG.DeviceNotAdvertising;
|
|
2354
|
+
}
|
|
2355
|
+
throw err;
|
|
1709
2356
|
}
|
|
1710
|
-
throw err;
|
|
1711
2357
|
}
|
|
1712
|
-
|
|
2358
|
+
const requiresBleSelection = this._isBleConnection();
|
|
2359
|
+
if (requiresBleSelection && !allowUsbEphemeralFallback) {
|
|
1713
2360
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1714
2361
|
code: HardwareErrorCode3.DeviceNotFound
|
|
1715
2362
|
});
|
|
1716
2363
|
}
|
|
1717
|
-
if (
|
|
1718
|
-
|
|
2364
|
+
if (requiresBleSelection && context?.allowDeviceSelection !== false) {
|
|
2365
|
+
const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
|
|
2366
|
+
if (context) context.bindingSessionId = bindingSessionId;
|
|
2367
|
+
const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb"));
|
|
2368
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2369
|
+
(connection) => connection.transport === "usb"
|
|
2370
|
+
);
|
|
2371
|
+
const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : targetConnectId;
|
|
2372
|
+
const { device, requestId } = await requestBleDeviceSelection({
|
|
2373
|
+
emitter: this.emitter,
|
|
2374
|
+
registry: this._uiRegistry,
|
|
2375
|
+
signal,
|
|
2376
|
+
allowUsbFallback,
|
|
2377
|
+
scan: async () => {
|
|
2378
|
+
if (allowUsbFallback) {
|
|
2379
|
+
const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
|
|
2380
|
+
const candidate = usbDevices.find(
|
|
2381
|
+
(device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
|
|
2382
|
+
) ?? (usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
|
|
2383
|
+
if (candidate) return [candidate];
|
|
2384
|
+
}
|
|
2385
|
+
return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
|
|
2386
|
+
},
|
|
2387
|
+
request: {
|
|
2388
|
+
devices,
|
|
2389
|
+
bindingSessionId,
|
|
2390
|
+
context: {
|
|
2391
|
+
kind: "bind-connection",
|
|
2392
|
+
transport: "ble",
|
|
2393
|
+
reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
|
|
2394
|
+
},
|
|
2395
|
+
extra: context?.extra,
|
|
2396
|
+
operationId: preserveOperationId
|
|
2397
|
+
}
|
|
2398
|
+
});
|
|
2399
|
+
if (device.connectionType === "usb") {
|
|
2400
|
+
this._activeConnectionType = "usb";
|
|
2401
|
+
if (context) context.selectedConnection = void 0;
|
|
2402
|
+
this._bindingSelectionRequestId = requestId;
|
|
2403
|
+
this._finishBleBinding("cancelled");
|
|
2404
|
+
return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
|
|
2405
|
+
}
|
|
2406
|
+
this._bindingSelectionRequestId = requestId;
|
|
2407
|
+
const connected = await this._connectDeviceOrThrow(
|
|
2408
|
+
device.connectId,
|
|
2409
|
+
preserveOperationId,
|
|
2410
|
+
signal
|
|
2411
|
+
);
|
|
2412
|
+
if (context) context.selectedConnection = { connectId: connected, requestId };
|
|
2413
|
+
await this._saveSelectedBleBinding(
|
|
2414
|
+
connected,
|
|
2415
|
+
requestId,
|
|
2416
|
+
context,
|
|
2417
|
+
preserveOperationId,
|
|
2418
|
+
signal
|
|
2419
|
+
);
|
|
2420
|
+
return connected;
|
|
2421
|
+
}
|
|
2422
|
+
if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
|
|
2423
|
+
if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(UI_REQUEST.REQUEST_SELECT_DEVICE)) {
|
|
2424
|
+
throw createHwkError({
|
|
2425
|
+
code: HardwareErrorCode3.DeviceNotFound,
|
|
2426
|
+
message: "Select a Ledger device before continuing"
|
|
2427
|
+
});
|
|
2428
|
+
}
|
|
2429
|
+
const requestId = this._uiRegistry.createRequestId();
|
|
2430
|
+
const operationId = this._activeOperationId();
|
|
2431
|
+
const waitPromise = this._uiRegistry.wait(
|
|
2432
|
+
UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2433
|
+
{ requestId, operationId }
|
|
2434
|
+
);
|
|
2435
|
+
this.emitter.emit(UI_REQUEST.REQUEST_SELECT_DEVICE, {
|
|
2436
|
+
type: UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2437
|
+
payload: {
|
|
2438
|
+
devices,
|
|
2439
|
+
requestId,
|
|
2440
|
+
operationId,
|
|
2441
|
+
context: requiresBleSelection ? {
|
|
2442
|
+
kind: "bind-connection",
|
|
2443
|
+
transport: "ble",
|
|
2444
|
+
reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
|
|
2445
|
+
} : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
|
|
2446
|
+
extra: context?.extra
|
|
2447
|
+
}
|
|
2448
|
+
});
|
|
2449
|
+
const { sdkConnectId } = await this._abortable(signal, waitPromise);
|
|
2450
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
2451
|
+
const selected = devices.find((device) => device.connectId === sdkConnectId);
|
|
2452
|
+
if (!selected) {
|
|
2453
|
+
throw Object.assign(new Error("Selected Ledger is no longer available"), {
|
|
2454
|
+
code: HardwareErrorCode3.DeviceNotFound
|
|
2455
|
+
});
|
|
2456
|
+
}
|
|
2457
|
+
if (context && requiresBleSelection)
|
|
2458
|
+
context.selectedConnection = { connectId: selected.connectId, requestId };
|
|
2459
|
+
return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
|
|
1719
2460
|
}
|
|
1720
2461
|
if (devices.length !== 1) {
|
|
1721
2462
|
throw Object.assign(new Error("Ledger device not found."), {
|
|
1722
2463
|
code: HardwareErrorCode3.DeviceNotFound
|
|
1723
2464
|
});
|
|
1724
2465
|
}
|
|
1725
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2466
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1726
2467
|
}
|
|
1727
|
-
async _connectDeviceOrThrow(chosenConnectId) {
|
|
1728
|
-
const result = await this.
|
|
2468
|
+
async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
|
|
2469
|
+
const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
|
|
1729
2470
|
if (!result.success) {
|
|
1730
2471
|
const payload = result.payload;
|
|
1731
2472
|
const rethrow = Object.assign(new Error(payload.error), {
|
|
@@ -1736,7 +2477,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1736
2477
|
}
|
|
1737
2478
|
throw rethrow;
|
|
1738
2479
|
}
|
|
1739
|
-
return
|
|
2480
|
+
return result.payload;
|
|
1740
2481
|
}
|
|
1741
2482
|
/**
|
|
1742
2483
|
* Call the connector with automatic session resolution and disconnect retry.
|
|
@@ -1766,33 +2507,133 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1766
2507
|
* lives in one place.
|
|
1767
2508
|
*/
|
|
1768
2509
|
async _callConnector(sessionId, method, params, signal) {
|
|
1769
|
-
|
|
2510
|
+
this._assertConnectorReady(method);
|
|
2511
|
+
if (signal?.aborted) throw this._abortReason(signal);
|
|
2512
|
+
const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
|
|
2513
|
+
let promise;
|
|
2514
|
+
try {
|
|
2515
|
+
promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
|
|
2516
|
+
} catch (error) {
|
|
2517
|
+
releaseOperation();
|
|
2518
|
+
throw error;
|
|
2519
|
+
}
|
|
1770
2520
|
const result = signal ? await this._abortable(signal, promise) : await promise;
|
|
1771
2521
|
return this._unwrapConnectorResult(result);
|
|
1772
2522
|
}
|
|
2523
|
+
_assertConnectorReady(method) {
|
|
2524
|
+
if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
|
|
2525
|
+
throw _LedgerAdapter._createDeviceBusyError(method);
|
|
2526
|
+
}
|
|
2527
|
+
}
|
|
2528
|
+
_runConnectorTeardown(task) {
|
|
2529
|
+
const previous = this._connectorTeardownTail;
|
|
2530
|
+
let releaseTail = () => void 0;
|
|
2531
|
+
this._connectorTeardownTail = new Promise((resolve) => {
|
|
2532
|
+
releaseTail = resolve;
|
|
2533
|
+
});
|
|
2534
|
+
this._pendingConnectorTeardowns += 1;
|
|
2535
|
+
return (async () => {
|
|
2536
|
+
try {
|
|
2537
|
+
await previous;
|
|
2538
|
+
await this._waitForConnectorOperationsToDrain();
|
|
2539
|
+
await task();
|
|
2540
|
+
} finally {
|
|
2541
|
+
this._pendingConnectorTeardowns -= 1;
|
|
2542
|
+
releaseTail();
|
|
2543
|
+
}
|
|
2544
|
+
})();
|
|
2545
|
+
}
|
|
2546
|
+
_waitForConnectorOperationsToDrain() {
|
|
2547
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2548
|
+
return Promise.resolve();
|
|
2549
|
+
}
|
|
2550
|
+
return new Promise((resolve) => {
|
|
2551
|
+
this._connectorIdleWaiters.add(resolve);
|
|
2552
|
+
});
|
|
2553
|
+
}
|
|
2554
|
+
_retainConnectorOperation(key) {
|
|
2555
|
+
this._unsettledConnectorOperations.set(
|
|
2556
|
+
key,
|
|
2557
|
+
(this._unsettledConnectorOperations.get(key) ?? 0) + 1
|
|
2558
|
+
);
|
|
2559
|
+
let released = false;
|
|
2560
|
+
return () => {
|
|
2561
|
+
if (released) return;
|
|
2562
|
+
released = true;
|
|
2563
|
+
const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
|
|
2564
|
+
if (remaining > 0) {
|
|
2565
|
+
this._unsettledConnectorOperations.set(key, remaining);
|
|
2566
|
+
} else {
|
|
2567
|
+
this._unsettledConnectorOperations.delete(key);
|
|
2568
|
+
}
|
|
2569
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2570
|
+
for (const resolve of this._connectorIdleWaiters) resolve();
|
|
2571
|
+
this._connectorIdleWaiters.clear();
|
|
2572
|
+
}
|
|
2573
|
+
};
|
|
2574
|
+
}
|
|
1773
2575
|
async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
1774
|
-
|
|
1775
|
-
|
|
2576
|
+
const positionalOperationId = isHardwareOperationId(connectId) ? connectId : void 0;
|
|
2577
|
+
if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
|
|
2578
|
+
throw createHwkError({
|
|
2579
|
+
code: HardwareErrorCode3.InvalidParams,
|
|
2580
|
+
message: "Conflicting Ledger operation ids",
|
|
2581
|
+
params: {
|
|
2582
|
+
positionalOperationId,
|
|
2583
|
+
commonOperationId: commonParams.operationId
|
|
2584
|
+
}
|
|
2585
|
+
});
|
|
2586
|
+
}
|
|
2587
|
+
const operationId = commonParams?.operationId ?? positionalOperationId;
|
|
2588
|
+
const operation = operationId ? this._operations.resolve(operationId) : void 0;
|
|
2589
|
+
const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
|
|
2590
|
+
const effectiveConnectId = operation?.connectId ?? connectId;
|
|
2591
|
+
debugLog("[LedgerAdapter][REQ]", {
|
|
2592
|
+
method,
|
|
2593
|
+
connectId: effectiveConnectId || "(empty)",
|
|
2594
|
+
params
|
|
2595
|
+
});
|
|
2596
|
+
const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
|
|
1776
2597
|
try {
|
|
1777
2598
|
const result = await this._jobQueue.enqueue(
|
|
1778
2599
|
queueKey,
|
|
1779
|
-
async (signal) =>
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
2600
|
+
async (signal) => {
|
|
2601
|
+
if (operationId) this._activeOperationJobs.add(operationId);
|
|
2602
|
+
try {
|
|
2603
|
+
return await this._runConnectorCall(
|
|
2604
|
+
effectiveConnectId,
|
|
2605
|
+
method,
|
|
2606
|
+
params,
|
|
2607
|
+
signal,
|
|
2608
|
+
fingerprint,
|
|
2609
|
+
permissionDeviceId,
|
|
2610
|
+
commonParams,
|
|
2611
|
+
installContext ?? {},
|
|
2612
|
+
operationId
|
|
2613
|
+
);
|
|
2614
|
+
} catch (error) {
|
|
2615
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
2616
|
+
throw error;
|
|
2617
|
+
} finally {
|
|
2618
|
+
if (operationId) {
|
|
2619
|
+
this._activeOperationJobs.delete(operationId);
|
|
2620
|
+
if (this._pendingOperationDisconnects.delete(operationId)) {
|
|
2621
|
+
await this._releaseLostOperationConnection(operationId);
|
|
2622
|
+
}
|
|
2623
|
+
}
|
|
2624
|
+
}
|
|
2625
|
+
},
|
|
1789
2626
|
{
|
|
1790
2627
|
label: method,
|
|
1791
2628
|
rejectIfBusy: true,
|
|
1792
2629
|
busyError: _LedgerAdapter._createDeviceBusyError(method)
|
|
1793
2630
|
}
|
|
1794
2631
|
);
|
|
1795
|
-
debugLog("[LedgerAdapter][RES]", {
|
|
2632
|
+
debugLog("[LedgerAdapter][RES]", {
|
|
2633
|
+
method,
|
|
2634
|
+
success: true,
|
|
2635
|
+
payload: redactResultForLog(result)
|
|
2636
|
+
});
|
|
1796
2637
|
return result;
|
|
1797
2638
|
} catch (err) {
|
|
1798
2639
|
const e = err;
|
|
@@ -1806,15 +2647,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1806
2647
|
}
|
|
1807
2648
|
});
|
|
1808
2649
|
throw err;
|
|
2650
|
+
} finally {
|
|
2651
|
+
releaseOperationRetention?.();
|
|
1809
2652
|
}
|
|
1810
2653
|
}
|
|
2654
|
+
/** Hermes/RN polyfills don't always populate signal.reason; fall back. */
|
|
2655
|
+
_abortReason(signal) {
|
|
2656
|
+
return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
|
|
2657
|
+
}
|
|
1811
2658
|
/**
|
|
1812
2659
|
* Race a promise against an abort signal. On abort, rejects with
|
|
1813
2660
|
* signal.reason → instance _lastCancelReason → generic Error('Aborted').
|
|
1814
2661
|
*/
|
|
1815
2662
|
_abortable(signal, promise) {
|
|
1816
|
-
const getAbortReason = () =>
|
|
2663
|
+
const getAbortReason = () => this._abortReason(signal);
|
|
1817
2664
|
if (signal.aborted) {
|
|
2665
|
+
void promise.catch(() => void 0);
|
|
1818
2666
|
return Promise.reject(getAbortReason());
|
|
1819
2667
|
}
|
|
1820
2668
|
return new Promise((resolve, reject) => {
|
|
@@ -1841,13 +2689,15 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1841
2689
|
}
|
|
1842
2690
|
}
|
|
1843
2691
|
/** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
|
|
1844
|
-
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
2692
|
+
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
|
|
1845
2693
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
2694
|
+
if (!operationId) {
|
|
2695
|
+
await this._ensureDevicePermission(
|
|
2696
|
+
connectId,
|
|
2697
|
+
permissionDeviceId ?? fingerprint?.deviceId,
|
|
2698
|
+
signal
|
|
2699
|
+
);
|
|
2700
|
+
}
|
|
1851
2701
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1852
2702
|
let effectiveParams = params;
|
|
1853
2703
|
if (method === "btcGetPublicKey") {
|
|
@@ -1861,19 +2711,49 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1861
2711
|
effectiveParams = gatedParams;
|
|
1862
2712
|
}
|
|
1863
2713
|
const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
|
|
1864
|
-
|
|
1865
|
-
|
|
2714
|
+
let businessCallStarted = false;
|
|
2715
|
+
const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
|
|
2716
|
+
const knownTransport = this._isBleConnection() ? "ble" : "usb";
|
|
2717
|
+
const hintedConnectId = commonParams?.knownConnections?.find(
|
|
2718
|
+
(connection) => connection.transport === knownTransport
|
|
2719
|
+
);
|
|
2720
|
+
const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
|
|
2721
|
+
const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
|
|
2722
|
+
const connectionAttempt = { ...commonParams };
|
|
2723
|
+
const bundleConnection = installContext?.connection;
|
|
2724
|
+
if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
|
|
2725
|
+
throw createHwkError({
|
|
2726
|
+
code: HardwareErrorCode3.DeviceDisconnected,
|
|
2727
|
+
message: "Ledger all-network connection ended"
|
|
2728
|
+
});
|
|
2729
|
+
}
|
|
2730
|
+
const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
|
|
2731
|
+
preferredConnectId,
|
|
1866
2732
|
signal,
|
|
1867
|
-
allowUsbEphemeralFallback
|
|
2733
|
+
allowUsbEphemeralFallback,
|
|
2734
|
+
void 0,
|
|
2735
|
+
connectionAttempt
|
|
1868
2736
|
);
|
|
1869
2737
|
const sessionId = this._sessions.get(resolvedConnectId);
|
|
2738
|
+
if (sessionId && installContext && !installContext.connection) {
|
|
2739
|
+
installContext.connection = { connectId: resolvedConnectId, sessionId };
|
|
2740
|
+
}
|
|
1870
2741
|
if (!sessionId) {
|
|
2742
|
+
if (operationId) {
|
|
2743
|
+
this._operations.end(operationId, "disconnect");
|
|
2744
|
+
throw createHwkError({
|
|
2745
|
+
code: HardwareErrorCode3.OperationEnded,
|
|
2746
|
+
message: "Ledger operation connection is no longer active",
|
|
2747
|
+
params: { operationId, reason: "disconnect" }
|
|
2748
|
+
});
|
|
2749
|
+
}
|
|
1871
2750
|
throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
|
|
1872
2751
|
_tag: ERROR_TAG.DeviceSessionNotFound
|
|
1873
2752
|
});
|
|
1874
2753
|
}
|
|
1875
2754
|
try {
|
|
1876
|
-
|
|
2755
|
+
const isBleSession = this._sessionTransports.get(sessionId) === "ble";
|
|
2756
|
+
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !isBleSession) {
|
|
1877
2757
|
const fp = await this._abortable(
|
|
1878
2758
|
signal,
|
|
1879
2759
|
this._verifyDeviceFingerprintWithSession(
|
|
@@ -1888,9 +2768,33 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1888
2768
|
});
|
|
1889
2769
|
}
|
|
1890
2770
|
}
|
|
2771
|
+
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
|
|
2772
|
+
this._selectedBleReconnectTargets.set(connectId, {
|
|
2773
|
+
connectId: resolvedConnectId,
|
|
2774
|
+
chain: fingerprint.chain,
|
|
2775
|
+
fingerprint: fingerprint.deviceId
|
|
2776
|
+
});
|
|
2777
|
+
}
|
|
2778
|
+
businessCallStarted = true;
|
|
1891
2779
|
return await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
1892
2780
|
} catch (err) {
|
|
1893
2781
|
if (signal.aborted) throw err;
|
|
2782
|
+
if (isLostConnectionError(err)) {
|
|
2783
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
2784
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
2785
|
+
else {
|
|
2786
|
+
this._sessions.delete(resolvedConnectId);
|
|
2787
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
2788
|
+
}
|
|
2789
|
+
const ambiguous = businessCallStarted && !canReplayHardwareMethodAfterTransportFailure(method);
|
|
2790
|
+
const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
|
|
2791
|
+
throw createHwkError({
|
|
2792
|
+
code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(err).code,
|
|
2793
|
+
message: "Ledger operation connection was lost; start a new operation",
|
|
2794
|
+
params: ambiguous ? operationMayHaveCompletedParams(method, { operationId }) : interactionParams,
|
|
2795
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
2796
|
+
});
|
|
2797
|
+
}
|
|
1894
2798
|
const errObj = err;
|
|
1895
2799
|
debugLog("[LedgerAdapter] connectorCall error:", method, {
|
|
1896
2800
|
message: errObj?.message,
|
|
@@ -1902,6 +2806,60 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1902
2806
|
isNotAdvertising: isDeviceNotAdvertisingError(err),
|
|
1903
2807
|
isStuckApp: isStuckAppStateError(err)
|
|
1904
2808
|
});
|
|
2809
|
+
const assertSessionCurrent = (message) => {
|
|
2810
|
+
if (this._sessions.get(resolvedConnectId) === sessionId) return;
|
|
2811
|
+
throw createHwkError({
|
|
2812
|
+
code: operationId ? HardwareErrorCode3.OperationEnded : HardwareErrorCode3.DeviceDisconnected,
|
|
2813
|
+
message
|
|
2814
|
+
});
|
|
2815
|
+
};
|
|
2816
|
+
if ((isDeviceLockedError(err) || errObj?.code === HardwareErrorCode3.DeviceLocked) && lockedRetryBudget > 0) {
|
|
2817
|
+
await this._waitForDeviceConnect(signal);
|
|
2818
|
+
assertSessionCurrent("Ledger connection ended while waiting for unlock");
|
|
2819
|
+
return this._runConnectorCall(
|
|
2820
|
+
resolvedConnectId,
|
|
2821
|
+
method,
|
|
2822
|
+
effectiveParams,
|
|
2823
|
+
signal,
|
|
2824
|
+
fingerprint,
|
|
2825
|
+
permissionDeviceId,
|
|
2826
|
+
commonParams,
|
|
2827
|
+
installContext,
|
|
2828
|
+
operationId,
|
|
2829
|
+
lockedRetryBudget - 1
|
|
2830
|
+
);
|
|
2831
|
+
}
|
|
2832
|
+
if (businessCallStarted && isStuckAppStateError(err)) {
|
|
2833
|
+
await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
|
|
2834
|
+
assertSessionCurrent("Ledger connection ended during the app transition");
|
|
2835
|
+
try {
|
|
2836
|
+
return await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
2837
|
+
} catch (retryErr) {
|
|
2838
|
+
if (isStuckAppStateError(retryErr)) throw err;
|
|
2839
|
+
if (isLostConnectionError(retryErr)) {
|
|
2840
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
2841
|
+
else {
|
|
2842
|
+
this._sessions.delete(resolvedConnectId);
|
|
2843
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
2844
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
2845
|
+
}
|
|
2846
|
+
const ambiguous = !canReplayHardwareMethodAfterTransportFailure(method);
|
|
2847
|
+
throw createHwkError({
|
|
2848
|
+
code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(retryErr).code,
|
|
2849
|
+
message: `Ledger ${method} may have completed before the connection was lost`,
|
|
2850
|
+
params: ambiguous ? operationMayHaveCompletedParams(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
|
|
2851
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
2852
|
+
});
|
|
2853
|
+
}
|
|
2854
|
+
throw retryErr;
|
|
2855
|
+
}
|
|
2856
|
+
}
|
|
2857
|
+
if (!operationId && errObj?.code === HardwareErrorCode3.DeviceMismatch) {
|
|
2858
|
+
this._sessions.delete(resolvedConnectId);
|
|
2859
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
2860
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
2861
|
+
throw err;
|
|
2862
|
+
}
|
|
1905
2863
|
const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
|
|
1906
2864
|
const isAppMissing = isAppNotInstalledError(err) || err?.code === HardwareErrorCode3.AppNotInstalled;
|
|
1907
2865
|
if (autoInstallApp && isAppMissing) {
|
|
@@ -1957,157 +2915,14 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1957
2915
|
fingerprint,
|
|
1958
2916
|
permissionDeviceId,
|
|
1959
2917
|
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
|
|
2918
|
+
installContext,
|
|
2919
|
+
operationId
|
|
2001
2920
|
);
|
|
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
2921
|
}
|
|
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
2922
|
}
|
|
2074
2923
|
throw err;
|
|
2075
2924
|
}
|
|
2076
2925
|
}
|
|
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
2926
|
_sleepAbortable(ms, signal) {
|
|
2112
2927
|
return new Promise((resolve, reject) => {
|
|
2113
2928
|
if (signal.aborted) {
|
|
@@ -2126,111 +2941,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2126
2941
|
});
|
|
2127
2942
|
}
|
|
2128
2943
|
/**
|
|
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
|
|
2944
|
+
* Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
|
|
2945
|
+
* replies. Without connectId the request is environment-level, else device-level.
|
|
2221
2946
|
*/
|
|
2222
2947
|
async _ensureDevicePermission(connectId, deviceId, signal) {
|
|
2223
2948
|
if (signal?.aborted) {
|
|
2224
2949
|
_LedgerAdapter._throwIfAborted(signal);
|
|
2225
2950
|
}
|
|
2226
2951
|
const transportType = this.activeTransport ?? "hid";
|
|
2952
|
+
const operationId = this._activeOperationId();
|
|
2227
2953
|
const waitPromise = this._uiRegistry.wait(
|
|
2228
2954
|
UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
2229
|
-
{ timeoutMs: 6e4 }
|
|
2955
|
+
{ timeoutMs: 6e4, operationId }
|
|
2230
2956
|
);
|
|
2231
2957
|
this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
|
|
2232
2958
|
type: UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
2233
|
-
payload: { transportType, connectId, deviceId }
|
|
2959
|
+
payload: { transportType, connectId, deviceId, operationId }
|
|
2234
2960
|
});
|
|
2235
2961
|
let response;
|
|
2236
2962
|
const onAbort = () => {
|
|
@@ -2276,7 +3002,15 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2276
3002
|
if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
|
|
2277
3003
|
const e = err;
|
|
2278
3004
|
const params = e.code === HardwareErrorCode3.DevicePermissionDenied && e.reason ? { permissionDeniedReason: e.reason } : e.params;
|
|
2279
|
-
return ledgerFailure(
|
|
3005
|
+
return ledgerFailure(
|
|
3006
|
+
e.code,
|
|
3007
|
+
e.message ?? "Unknown error",
|
|
3008
|
+
e.appName,
|
|
3009
|
+
tag,
|
|
3010
|
+
params,
|
|
3011
|
+
void 0,
|
|
3012
|
+
isHwkRecoveryHint(e.recovery) ? e.recovery : void 0
|
|
3013
|
+
);
|
|
2280
3014
|
}
|
|
2281
3015
|
const mapped = mapLedgerError(err);
|
|
2282
3016
|
return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
|
|
@@ -2303,7 +3037,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2303
3037
|
deviceId: device.deviceId,
|
|
2304
3038
|
connectId: device.connectId,
|
|
2305
3039
|
label: device.name,
|
|
2306
|
-
connectionType: this.connector.connectionType,
|
|
3040
|
+
connectionType: device.connectionType ?? this.connector.connectionType,
|
|
2307
3041
|
rssi: device.rssi,
|
|
2308
3042
|
isConnectable: device.isConnectable,
|
|
2309
3043
|
serialNumber: device.serialNumber,
|
|
@@ -2329,8 +3063,8 @@ var LedgerAdapter = _LedgerAdapter;
|
|
|
2329
3063
|
|
|
2330
3064
|
// src/connector/LedgerConnectorBase.ts
|
|
2331
3065
|
import {
|
|
2332
|
-
EConnectorInteraction as
|
|
2333
|
-
HardwareErrorCode as
|
|
3066
|
+
EConnectorInteraction as EConnectorInteraction3,
|
|
3067
|
+
HardwareErrorCode as HardwareErrorCode7,
|
|
2334
3068
|
isKnownNonTargetHardwareVendor,
|
|
2335
3069
|
serializeConnectorError
|
|
2336
3070
|
} from "@onekeyfe/hwk-adapter-core";
|
|
@@ -2603,7 +3337,7 @@ var LedgerDeviceManager = class {
|
|
|
2603
3337
|
|
|
2604
3338
|
// src/signer/SignerManager.ts
|
|
2605
3339
|
import { SignerEthBuilder } from "@ledgerhq/device-signer-kit-ethereum";
|
|
2606
|
-
import { ContextModuleBuilder } from "@ledgerhq/context-module";
|
|
3340
|
+
import { ContextModuleBuilder, ContextModuleChainID } from "@ledgerhq/context-module";
|
|
2607
3341
|
|
|
2608
3342
|
// src/signer/SignerEth.ts
|
|
2609
3343
|
import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
|
|
@@ -2869,7 +3603,7 @@ var SignerManager = class _SignerManager {
|
|
|
2869
3603
|
return (args) => new SignerEthBuilder(args);
|
|
2870
3604
|
}
|
|
2871
3605
|
static _createContextModule() {
|
|
2872
|
-
const contextModule = new ContextModuleBuilder({}).removeDefaultLoaders().build();
|
|
3606
|
+
const contextModule = new ContextModuleBuilder({}).setChain(ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
|
|
2873
3607
|
return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
|
|
2874
3608
|
}
|
|
2875
3609
|
static wrapBlindSigningReportNonBlocking(contextModule) {
|
|
@@ -2907,8 +3641,29 @@ function collapseSignerInteraction(interaction) {
|
|
|
2907
3641
|
return EConnectorInteraction2.ConfirmOnDevice;
|
|
2908
3642
|
}
|
|
2909
3643
|
}
|
|
2910
|
-
|
|
2911
|
-
|
|
3644
|
+
function wireSignerToSession(ctx, sessionId, chain, signer) {
|
|
3645
|
+
signer.onInteraction = (interaction) => {
|
|
3646
|
+
debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
|
|
3647
|
+
ctx.emit("ui-event", {
|
|
3648
|
+
type: collapseSignerInteraction(interaction),
|
|
3649
|
+
payload: { sessionId }
|
|
3650
|
+
});
|
|
3651
|
+
};
|
|
3652
|
+
signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
|
|
3653
|
+
return signer;
|
|
3654
|
+
}
|
|
3655
|
+
async function runSignerCall(ctx, sessionId, call) {
|
|
3656
|
+
try {
|
|
3657
|
+
return await call();
|
|
3658
|
+
} catch (err) {
|
|
3659
|
+
ctx.invalidateSession(sessionId);
|
|
3660
|
+
throw ctx.wrapError(err);
|
|
3661
|
+
} finally {
|
|
3662
|
+
ctx.clearCanceller(sessionId);
|
|
3663
|
+
}
|
|
3664
|
+
}
|
|
3665
|
+
|
|
3666
|
+
// src/connector/chains/evm.ts
|
|
2912
3667
|
async function evmGetAddress(ctx, sessionId, params) {
|
|
2913
3668
|
const signer = await _getEthSigner(ctx, sessionId);
|
|
2914
3669
|
const path = normalizePath(params.path);
|
|
@@ -3339,7 +4094,8 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
|
3339
4094
|
}
|
|
3340
4095
|
|
|
3341
4096
|
// src/connector/chains/sol.ts
|
|
3342
|
-
import { bytesToHex, hexToBytes as hexToBytes3 } from "@onekeyfe/hwk-adapter-core";
|
|
4097
|
+
import { bytesToHex, hexToBytes as hexToBytes3, prepareSolanaOffchainMessageV1 } from "@onekeyfe/hwk-adapter-core";
|
|
4098
|
+
import bs58 from "bs58";
|
|
3343
4099
|
|
|
3344
4100
|
// src/signer/SignerSol.ts
|
|
3345
4101
|
var SignerSol = class {
|
|
@@ -3423,8 +4179,21 @@ async function solSignMessage(ctx, sessionId, params) {
|
|
|
3423
4179
|
const path = normalizePath(params.path);
|
|
3424
4180
|
const messageBytes = hexToBytes3(params.message);
|
|
3425
4181
|
try {
|
|
4182
|
+
if (params.messageVersion === 1) {
|
|
4183
|
+
const preparedMessage = prepareSolanaOffchainMessageV1({
|
|
4184
|
+
message: messageBytes,
|
|
4185
|
+
requiredSigners: params.requiredSigners
|
|
4186
|
+
});
|
|
4187
|
+
const { SignMessageVersion } = await ctx.importLedgerKit(
|
|
4188
|
+
"@ledgerhq/device-signer-kit-solana"
|
|
4189
|
+
);
|
|
4190
|
+
const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
|
|
4191
|
+
version: SignMessageVersion.Raw
|
|
4192
|
+
});
|
|
4193
|
+
return { signature: decodeBase58Signature(result2.signature) };
|
|
4194
|
+
}
|
|
3426
4195
|
const result = await solSigner.signMessage(path, messageBytes);
|
|
3427
|
-
return { signature: result.signature };
|
|
4196
|
+
return { signature: decodeBase58EnvelopeSignature(result.signature) };
|
|
3428
4197
|
} catch (err) {
|
|
3429
4198
|
ctx.invalidateSession(sessionId);
|
|
3430
4199
|
throw ctx.wrapError(err);
|
|
@@ -3432,11 +4201,27 @@ async function solSignMessage(ctx, sessionId, params) {
|
|
|
3432
4201
|
ctx.clearCanceller(sessionId);
|
|
3433
4202
|
}
|
|
3434
4203
|
}
|
|
4204
|
+
function decodeBase58Signature(signature) {
|
|
4205
|
+
const bytes = bs58.decode(signature);
|
|
4206
|
+
if (bytes.length !== 64) {
|
|
4207
|
+
throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
|
|
4208
|
+
}
|
|
4209
|
+
return bytesToHex(bytes);
|
|
4210
|
+
}
|
|
4211
|
+
function decodeBase58EnvelopeSignature(envelope) {
|
|
4212
|
+
const bytes = bs58.decode(envelope);
|
|
4213
|
+
if (bytes.length < 65 || bytes[0] !== 1) {
|
|
4214
|
+
throw new Error("Ledger Solana signature envelope is invalid");
|
|
4215
|
+
}
|
|
4216
|
+
return bytesToHex(bytes.subarray(1, 65));
|
|
4217
|
+
}
|
|
3435
4218
|
async function _createSolSigner(ctx, sessionId) {
|
|
3436
4219
|
const dmk = await ctx.getOrCreateDmk();
|
|
3437
|
-
const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit(
|
|
4220
|
+
const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
|
|
4221
|
+
"@ledgerhq/context-module"
|
|
4222
|
+
);
|
|
3438
4223
|
const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
|
|
3439
|
-
const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
|
|
4224
|
+
const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
|
|
3440
4225
|
const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
|
|
3441
4226
|
const signer = new SignerSol(sdkSigner);
|
|
3442
4227
|
signer.onInteraction = (interaction) => {
|
|
@@ -3452,361 +4237,147 @@ async function _createSolSigner(ctx, sessionId) {
|
|
|
3452
4237
|
return signer;
|
|
3453
4238
|
}
|
|
3454
4239
|
|
|
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";
|
|
4240
|
+
// src/connector/chains/zcash.ts
|
|
4241
|
+
import { bytesToHex as bytesToHex2 } from "@onekeyfe/hwk-adapter-core";
|
|
3461
4242
|
|
|
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);
|
|
4243
|
+
// src/signer/SignerZcash.ts
|
|
4244
|
+
var SignerZcash = class {
|
|
4245
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4246
|
+
constructor(_sdk) {
|
|
4247
|
+
this._sdk = _sdk;
|
|
3528
4248
|
}
|
|
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
|
-
}
|
|
4249
|
+
/** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
|
|
4250
|
+
async getFullViewingKey(derivationPath, options) {
|
|
4251
|
+
const action = this._sdk.getFullViewingKey(derivationPath, options);
|
|
4252
|
+
return deviceActionToPromise(
|
|
4253
|
+
action,
|
|
4254
|
+
this.onInteraction,
|
|
4255
|
+
void 0,
|
|
4256
|
+
this.onRegisterCanceller
|
|
3565
4257
|
);
|
|
3566
4258
|
}
|
|
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})`
|
|
4259
|
+
/** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
|
|
4260
|
+
async getShieldedAddress(derivationPath, options) {
|
|
4261
|
+
const action = this._sdk.getShieldedAddress(derivationPath, options);
|
|
4262
|
+
return deviceActionToPromise(
|
|
4263
|
+
action,
|
|
4264
|
+
this.onInteraction,
|
|
4265
|
+
void 0,
|
|
4266
|
+
this.onRegisterCanceller
|
|
3629
4267
|
);
|
|
3630
4268
|
}
|
|
3631
|
-
_isDashboard(appName) {
|
|
3632
|
-
return appName === DASHBOARD_APP_NAME;
|
|
3633
|
-
}
|
|
3634
|
-
_wait() {
|
|
3635
|
-
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
3636
|
-
}
|
|
3637
4269
|
};
|
|
3638
4270
|
|
|
3639
|
-
// src/connector/chains/
|
|
3640
|
-
function
|
|
3641
|
-
|
|
4271
|
+
// src/connector/chains/zcash.ts
|
|
4272
|
+
async function zcashGetFullViewingKey(ctx, sessionId, params) {
|
|
4273
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4274
|
+
const path = normalizePath(params.path);
|
|
4275
|
+
const mode = params.mode ?? "ufvk";
|
|
4276
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4277
|
+
const result = await signer.getFullViewingKey(path, { mode });
|
|
4278
|
+
if (result.mode === "ufvk") {
|
|
4279
|
+
return { path: params.path, mode, ufvk: result.fullViewingKey };
|
|
4280
|
+
}
|
|
4281
|
+
return { path: params.path, mode, orchardFvk: bytesToHex2(result.fullViewingKey) };
|
|
4282
|
+
});
|
|
3642
4283
|
}
|
|
3643
|
-
async function
|
|
3644
|
-
const
|
|
3645
|
-
|
|
3646
|
-
|
|
3647
|
-
|
|
3648
|
-
|
|
3649
|
-
type: EConnectorInteraction3.ConfirmOpenApp,
|
|
3650
|
-
payload: { sessionId }
|
|
4284
|
+
async function zcashGetShieldedAddress(ctx, sessionId, params) {
|
|
4285
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4286
|
+
const path = normalizePath(params.path);
|
|
4287
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4288
|
+
const result = await signer.getShieldedAddress(path, {
|
|
4289
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
3651
4290
|
});
|
|
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
|
-
}
|
|
4291
|
+
return { address: result.address, path: params.path };
|
|
4292
|
+
});
|
|
3719
4293
|
}
|
|
3720
|
-
async function
|
|
4294
|
+
async function _createZcashSigner(ctx, sessionId) {
|
|
3721
4295
|
const dmk = await ctx.getOrCreateDmk();
|
|
3722
|
-
const
|
|
3723
|
-
|
|
4296
|
+
const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
|
|
4297
|
+
const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
|
|
4298
|
+
return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
|
|
3724
4299
|
}
|
|
3725
4300
|
|
|
3726
|
-
// src/
|
|
3727
|
-
import
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
|
|
3731
|
-
|
|
3732
|
-
|
|
4301
|
+
// src/connector/chains/tron.ts
|
|
4302
|
+
import { HardwareErrorCode as HardwareErrorCode6, bytesToHex as bytesToHex3, hexToBytes as hexToBytes4 } from "@onekeyfe/hwk-adapter-core";
|
|
4303
|
+
|
|
4304
|
+
// src/signer/SignerTron.ts
|
|
4305
|
+
var SignerTron = class {
|
|
4306
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4307
|
+
constructor(_sdk) {
|
|
4308
|
+
this._sdk = _sdk;
|
|
4309
|
+
}
|
|
4310
|
+
/** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
|
|
4311
|
+
async getAddress(derivationPath, options) {
|
|
4312
|
+
const action = this._sdk.getAddress(derivationPath, options);
|
|
4313
|
+
const result = await deviceActionToPromise(
|
|
4314
|
+
action,
|
|
4315
|
+
this.onInteraction,
|
|
4316
|
+
void 0,
|
|
4317
|
+
this.onRegisterCanceller
|
|
4318
|
+
);
|
|
4319
|
+
return { address: result.address, publicKey: result.publicKey };
|
|
3733
4320
|
}
|
|
3734
|
-
|
|
3735
|
-
|
|
3736
|
-
|
|
3737
|
-
|
|
3738
|
-
|
|
3739
|
-
|
|
3740
|
-
|
|
3741
|
-
|
|
3742
|
-
|
|
3743
|
-
}
|
|
3744
|
-
result.set(statusCode, data.length);
|
|
3745
|
-
return result;
|
|
4321
|
+
/** Sign a protobuf-encoded raw transaction. */
|
|
4322
|
+
async signTransaction(derivationPath, transaction, options) {
|
|
4323
|
+
const action = this._sdk.signTransaction(derivationPath, transaction, options);
|
|
4324
|
+
return deviceActionToPromise(
|
|
4325
|
+
action,
|
|
4326
|
+
this.onInteraction,
|
|
4327
|
+
void 0,
|
|
4328
|
+
this.onRegisterCanceller
|
|
4329
|
+
);
|
|
3746
4330
|
}
|
|
3747
|
-
|
|
4331
|
+
/** Sign a personal message (TIP-191). */
|
|
4332
|
+
async signPersonalMessage(derivationPath, message, options) {
|
|
4333
|
+
const action = this._sdk.signPersonalMessage(derivationPath, message, options);
|
|
4334
|
+
return deviceActionToPromise(
|
|
4335
|
+
action,
|
|
4336
|
+
this.onInteraction,
|
|
4337
|
+
void 0,
|
|
4338
|
+
this.onRegisterCanceller
|
|
4339
|
+
);
|
|
3748
4340
|
}
|
|
3749
4341
|
};
|
|
3750
4342
|
|
|
3751
4343
|
// src/connector/chains/tron.ts
|
|
3752
4344
|
async function tronGetAddress(ctx, sessionId, params) {
|
|
4345
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3753
4346
|
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
|
-
);
|
|
4347
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4348
|
+
const result = await tronSigner.getAddress(path, {
|
|
4349
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
4350
|
+
});
|
|
4351
|
+
return { address: result.address, publicKey: result.publicKey, path: params.path };
|
|
4352
|
+
});
|
|
3770
4353
|
}
|
|
3771
4354
|
async function tronSignTransaction(ctx, sessionId, params) {
|
|
3772
4355
|
if (!params.rawTxHex) {
|
|
3773
4356
|
throw Object.assign(
|
|
3774
4357
|
new Error("TRON signing requires a protobuf-encoded raw transaction hex (rawTxHex)."),
|
|
3775
|
-
{ code:
|
|
4358
|
+
{ code: HardwareErrorCode6.InvalidParams }
|
|
3776
4359
|
);
|
|
3777
4360
|
}
|
|
4361
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3778
4362
|
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
|
-
);
|
|
4363
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4364
|
+
const signature = await tronSigner.signTransaction(path, hexToBytes4(params.rawTxHex));
|
|
4365
|
+
return { signature: bytesToHex3(signature) };
|
|
4366
|
+
});
|
|
3793
4367
|
}
|
|
3794
4368
|
async function tronSignMessage(ctx, sessionId, params) {
|
|
4369
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3795
4370
|
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
|
-
);
|
|
4371
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4372
|
+
const signature = await tronSigner.signPersonalMessage(path, hexToBytes4(params.messageHex));
|
|
4373
|
+
return { signature: bytesToHex3(signature) };
|
|
4374
|
+
});
|
|
3806
4375
|
}
|
|
3807
|
-
async function
|
|
4376
|
+
async function _createTronSigner(ctx, sessionId) {
|
|
3808
4377
|
const dmk = await ctx.getOrCreateDmk();
|
|
3809
|
-
|
|
4378
|
+
const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
|
|
4379
|
+
const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
|
|
4380
|
+
return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
|
|
3810
4381
|
}
|
|
3811
4382
|
|
|
3812
4383
|
// src/device-apps/customActions.ts
|
|
@@ -3985,7 +4556,7 @@ var DeviceApps = class {
|
|
|
3985
4556
|
seTargetId: v.seTargetId,
|
|
3986
4557
|
mcuTargetId: v.mcuTargetId,
|
|
3987
4558
|
seVersion: v.seVersion,
|
|
3988
|
-
seFlagsHex:
|
|
4559
|
+
seFlagsHex: bytesToHex4(v.seFlags),
|
|
3989
4560
|
mcuSephVersion: v.mcuSephVersion,
|
|
3990
4561
|
mcuBootloaderVersion: v.mcuBootloaderVersion,
|
|
3991
4562
|
hwVersion: v.hwVersion
|
|
@@ -4059,7 +4630,7 @@ var DeviceApps = class {
|
|
|
4059
4630
|
}
|
|
4060
4631
|
}
|
|
4061
4632
|
};
|
|
4062
|
-
function
|
|
4633
|
+
function bytesToHex4(bytes) {
|
|
4063
4634
|
if (!bytes) return "";
|
|
4064
4635
|
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
4065
4636
|
}
|
|
@@ -4102,10 +4673,11 @@ var METHOD_PREFIX_TO_APP_NAME = {
|
|
|
4102
4673
|
evm: "Ethereum",
|
|
4103
4674
|
btc: "Bitcoin",
|
|
4104
4675
|
sol: "Solana",
|
|
4105
|
-
tron: "Tron"
|
|
4676
|
+
tron: "Tron",
|
|
4677
|
+
zcash: "Zcash"
|
|
4106
4678
|
};
|
|
4107
4679
|
var HARDWARE_ERROR_CODE_VALUES = new Set(
|
|
4108
|
-
Object.values(
|
|
4680
|
+
Object.values(HardwareErrorCode7).filter((value) => typeof value === "number")
|
|
4109
4681
|
);
|
|
4110
4682
|
var BLE_CONNECT_SCAN_TIMEOUT_MS = 1500;
|
|
4111
4683
|
var LEDGER_RELAY_ALLOWED_ROOT_DOMAINS = ["onekeytest.com", "onekey.com"];
|
|
@@ -4142,6 +4714,10 @@ async function defaultLedgerKitImporter(pkg) {
|
|
|
4142
4714
|
return import("@ledgerhq/device-signer-kit-bitcoin");
|
|
4143
4715
|
case "@ledgerhq/device-signer-kit-solana":
|
|
4144
4716
|
return import("@ledgerhq/device-signer-kit-solana");
|
|
4717
|
+
case "@ledgerhq/device-signer-kit-tron":
|
|
4718
|
+
return import("@ledgerhq/device-signer-kit-tron");
|
|
4719
|
+
case "@ledgerhq/device-signer-kit-zcash":
|
|
4720
|
+
return import("@ledgerhq/device-signer-kit-zcash");
|
|
4145
4721
|
case "@ledgerhq/context-module":
|
|
4146
4722
|
return import("@ledgerhq/context-module");
|
|
4147
4723
|
default:
|
|
@@ -4201,6 +4777,7 @@ var LedgerConnectorBase = class {
|
|
|
4201
4777
|
this._ctx = {
|
|
4202
4778
|
emit: (event, data) => this._emit(event, data),
|
|
4203
4779
|
invalidateSession: (sid) => this._invalidateSession(sid),
|
|
4780
|
+
teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
|
|
4204
4781
|
wrapError: (err, opts) => this._wrapError(err, opts),
|
|
4205
4782
|
getOrCreateDmk: () => this._getOrCreateDmk(),
|
|
4206
4783
|
getDeviceManager: () => this._getDeviceManager(),
|
|
@@ -4300,7 +4877,7 @@ var LedgerConnectorBase = class {
|
|
|
4300
4877
|
`Ledger BLE connect did not return within ${HANG_CEILING_MS / 6e4}min \u2014 DMK hang fallback.`
|
|
4301
4878
|
);
|
|
4302
4879
|
err._tag = ERROR_TAG.BlePairingTimeout;
|
|
4303
|
-
err.code =
|
|
4880
|
+
err.code = HardwareErrorCode7.BlePairingTimeout;
|
|
4304
4881
|
reject(err);
|
|
4305
4882
|
}, HANG_CEILING_MS);
|
|
4306
4883
|
});
|
|
@@ -4333,7 +4910,7 @@ var LedgerConnectorBase = class {
|
|
|
4333
4910
|
"Ledger device is not currently advertising. Wake up and unlock the device, keep it nearby, then try again."
|
|
4334
4911
|
);
|
|
4335
4912
|
err._tag = ERROR_TAG.DeviceNotAdvertising;
|
|
4336
|
-
err.code =
|
|
4913
|
+
err.code = HardwareErrorCode7.DeviceNotFound;
|
|
4337
4914
|
throw err;
|
|
4338
4915
|
};
|
|
4339
4916
|
const doConnect = async (path) => {
|
|
@@ -4390,14 +4967,14 @@ var LedgerConnectorBase = class {
|
|
|
4390
4967
|
this._resetSignersAndSessions();
|
|
4391
4968
|
if (isLedgerBleConnectionType(this.connectionType)) {
|
|
4392
4969
|
const tag = err?._tag;
|
|
4393
|
-
if (isKnownConnectionTag(tag)) {
|
|
4970
|
+
if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
|
|
4394
4971
|
throw err;
|
|
4395
4972
|
}
|
|
4396
4973
|
const wrapped = new Error(
|
|
4397
4974
|
"Ledger Bluetooth pairing failed. Make sure the device is unlocked and nearby, then try again."
|
|
4398
4975
|
);
|
|
4399
4976
|
wrapped._tag = ERROR_TAG.BleGattBondingFailed;
|
|
4400
|
-
wrapped.code =
|
|
4977
|
+
wrapped.code = HardwareErrorCode7.BlePairingTimeout;
|
|
4401
4978
|
wrapped.originalError = err;
|
|
4402
4979
|
throw wrapped;
|
|
4403
4980
|
}
|
|
@@ -4475,7 +5052,7 @@ var LedgerConnectorBase = class {
|
|
|
4475
5052
|
this._unwatchSessionState(sessionId);
|
|
4476
5053
|
this._signerManager?.invalidate(sessionId);
|
|
4477
5054
|
this._cancellers.get(sessionId)?.({
|
|
4478
|
-
code:
|
|
5055
|
+
code: HardwareErrorCode7.DeviceDisconnected,
|
|
4479
5056
|
tag: "DeviceDisconnected",
|
|
4480
5057
|
message: "Device disconnected"
|
|
4481
5058
|
});
|
|
@@ -4501,7 +5078,7 @@ var LedgerConnectorBase = class {
|
|
|
4501
5078
|
success: false,
|
|
4502
5079
|
error: serializeConnectorError(
|
|
4503
5080
|
Object.assign(new Error("Ledger app is unresponsive"), {
|
|
4504
|
-
code:
|
|
5081
|
+
code: HardwareErrorCode7.DeviceAppStuck,
|
|
4505
5082
|
_tag: ERROR_TAG.DeviceAppStuck,
|
|
4506
5083
|
originalError: err
|
|
4507
5084
|
})
|
|
@@ -4513,7 +5090,7 @@ var LedgerConnectorBase = class {
|
|
|
4513
5090
|
success: false,
|
|
4514
5091
|
error: serializeConnectorError(
|
|
4515
5092
|
Object.assign(new Error("Device communication interrupted, please retry"), {
|
|
4516
|
-
code:
|
|
5093
|
+
code: HardwareErrorCode7.TransportError,
|
|
4517
5094
|
_tag: ERROR_TAG.DeviceTransportStuck,
|
|
4518
5095
|
originalError: err
|
|
4519
5096
|
})
|
|
@@ -4559,6 +5136,11 @@ var LedgerConnectorBase = class {
|
|
|
4559
5136
|
return solSignTransaction(ctx, sessionId, params);
|
|
4560
5137
|
case "solSignMessage":
|
|
4561
5138
|
return solSignMessage(ctx, sessionId, params);
|
|
5139
|
+
// ZCASH
|
|
5140
|
+
case "zcashGetFullViewingKey":
|
|
5141
|
+
return zcashGetFullViewingKey(ctx, sessionId, params);
|
|
5142
|
+
case "zcashGetShieldedAddress":
|
|
5143
|
+
return zcashGetShieldedAddress(ctx, sessionId, params);
|
|
4562
5144
|
// TRON
|
|
4563
5145
|
case "tronGetAddress":
|
|
4564
5146
|
return tronGetAddress(ctx, sessionId, params);
|
|
@@ -4583,7 +5165,7 @@ var LedgerConnectorBase = class {
|
|
|
4583
5165
|
try {
|
|
4584
5166
|
return await apps.install(p.appName, ({ progress }) => {
|
|
4585
5167
|
ctx.emit("ui-event", {
|
|
4586
|
-
type:
|
|
5168
|
+
type: EConnectorInteraction3.AppInstallProgress,
|
|
4587
5169
|
payload: {
|
|
4588
5170
|
sessionId,
|
|
4589
5171
|
appName: p.appName,
|
|
@@ -4592,7 +5174,7 @@ var LedgerConnectorBase = class {
|
|
|
4592
5174
|
});
|
|
4593
5175
|
});
|
|
4594
5176
|
} catch (err) {
|
|
4595
|
-
ctx.
|
|
5177
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4596
5178
|
throw ctx.wrapError(err);
|
|
4597
5179
|
} finally {
|
|
4598
5180
|
ctx.clearCanceller(sessionId);
|
|
@@ -4682,7 +5264,7 @@ var LedgerConnectorBase = class {
|
|
|
4682
5264
|
);
|
|
4683
5265
|
return { isGenuine: output.isGenuine, deviceId };
|
|
4684
5266
|
} catch (err) {
|
|
4685
|
-
ctx.
|
|
5267
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4686
5268
|
throw ctx.wrapError(err);
|
|
4687
5269
|
} finally {
|
|
4688
5270
|
ctx.clearCanceller(sessionId);
|
|
@@ -4801,9 +5383,26 @@ var LedgerConnectorBase = class {
|
|
|
4801
5383
|
}
|
|
4802
5384
|
return this._deviceAppsManager;
|
|
4803
5385
|
}
|
|
5386
|
+
// DeviceAppsManager is a per-call factory with no cached session state, so
|
|
5387
|
+
// there is nothing to invalidate for it here.
|
|
4804
5388
|
_invalidateSession(sessionId) {
|
|
4805
5389
|
this._signerManager?.invalidate(sessionId);
|
|
4806
5390
|
}
|
|
5391
|
+
/**
|
|
5392
|
+
* Fire the canceller so DMK closes the secure-channel WebSocket. The DMK device
|
|
5393
|
+
* session is kept: unlock/retry recovery reuses it.
|
|
5394
|
+
*/
|
|
5395
|
+
_teardownSecureChannelSession(sessionId) {
|
|
5396
|
+
const cancel = this._cancellers.get(sessionId);
|
|
5397
|
+
this._cancellers.delete(sessionId);
|
|
5398
|
+
if (cancel) {
|
|
5399
|
+
try {
|
|
5400
|
+
cancel();
|
|
5401
|
+
} catch {
|
|
5402
|
+
}
|
|
5403
|
+
}
|
|
5404
|
+
this._invalidateSession(sessionId);
|
|
5405
|
+
}
|
|
4807
5406
|
/**
|
|
4808
5407
|
* Replace an old session with a new one after app switch.
|
|
4809
5408
|
* Emits device-connect so the adapter updates its _sessions Map.
|
|
@@ -4888,7 +5487,7 @@ var LedgerConnectorBase = class {
|
|
|
4888
5487
|
* at every catch site. Falls through unchanged for unknown methods.
|
|
4889
5488
|
*/
|
|
4890
5489
|
_ctxForMethod(method) {
|
|
4891
|
-
const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
|
|
5490
|
+
const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
|
|
4892
5491
|
const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
|
|
4893
5492
|
if (!defaultAppName) return this._ctx;
|
|
4894
5493
|
return {
|
|
@@ -4922,6 +5521,209 @@ var LedgerConnectorBase = class {
|
|
|
4922
5521
|
return error;
|
|
4923
5522
|
}
|
|
4924
5523
|
};
|
|
5524
|
+
|
|
5525
|
+
// src/transport/DmkTransport.ts
|
|
5526
|
+
import Transport from "@ledgerhq/hw-transport";
|
|
5527
|
+
var DmkTransport = class extends Transport {
|
|
5528
|
+
constructor(dmk, sessionId) {
|
|
5529
|
+
super();
|
|
5530
|
+
this._dmk = dmk;
|
|
5531
|
+
this._sessionId = sessionId;
|
|
5532
|
+
}
|
|
5533
|
+
async exchange(apdu) {
|
|
5534
|
+
const response = await this._dmk.sendApdu({
|
|
5535
|
+
sessionId: this._sessionId,
|
|
5536
|
+
apdu: new Uint8Array(apdu)
|
|
5537
|
+
});
|
|
5538
|
+
const { data, statusCode } = response;
|
|
5539
|
+
const result = Buffer.alloc(data.length + 2);
|
|
5540
|
+
if (data.length > 0) {
|
|
5541
|
+
result.set(data, 0);
|
|
5542
|
+
}
|
|
5543
|
+
result.set(statusCode, data.length);
|
|
5544
|
+
return result;
|
|
5545
|
+
}
|
|
5546
|
+
async close() {
|
|
5547
|
+
}
|
|
5548
|
+
};
|
|
5549
|
+
|
|
5550
|
+
// src/app/AppManager.ts
|
|
5551
|
+
import {
|
|
5552
|
+
CloseAppCommand,
|
|
5553
|
+
GetAppAndVersionCommand,
|
|
5554
|
+
OpenAppCommand,
|
|
5555
|
+
isSuccessCommandResult
|
|
5556
|
+
} from "@ledgerhq/device-management-kit";
|
|
5557
|
+
import { HardwareErrorCode as HardwareErrorCode8 } from "@onekeyfe/hwk-adapter-core";
|
|
5558
|
+
var APP_NAME_MAP = {
|
|
5559
|
+
ETH: "Ethereum",
|
|
5560
|
+
BTC: "Bitcoin",
|
|
5561
|
+
SOL: "Solana",
|
|
5562
|
+
TRX: "Tron",
|
|
5563
|
+
ZEC: "Zcash",
|
|
5564
|
+
XRP: "XRP",
|
|
5565
|
+
ADA: "Cardano",
|
|
5566
|
+
DOT: "Polkadot",
|
|
5567
|
+
ATOM: "Cosmos"
|
|
5568
|
+
};
|
|
5569
|
+
var DASHBOARD_APP_NAME = "BOLOS";
|
|
5570
|
+
var AppManager = class {
|
|
5571
|
+
constructor(dmk, options) {
|
|
5572
|
+
this._dmk = dmk;
|
|
5573
|
+
this._waitMs = options?.waitMs ?? 1e3;
|
|
5574
|
+
this._maxRetries = options?.maxRetries ?? 10;
|
|
5575
|
+
}
|
|
5576
|
+
/**
|
|
5577
|
+
* Return the Ledger app name for a given chain ticker,
|
|
5578
|
+
* or undefined if the chain is not supported.
|
|
5579
|
+
*/
|
|
5580
|
+
static getAppName(chain) {
|
|
5581
|
+
return APP_NAME_MAP[chain];
|
|
5582
|
+
}
|
|
5583
|
+
/**
|
|
5584
|
+
* Ensure the target app is open on the device identified by `sessionId`.
|
|
5585
|
+
*
|
|
5586
|
+
* Flow:
|
|
5587
|
+
* 1. Check the currently running app.
|
|
5588
|
+
* 2. If it is already the target, return immediately.
|
|
5589
|
+
* 3. If a different app is running (not dashboard), close it first.
|
|
5590
|
+
* 4. Open the target app.
|
|
5591
|
+
* 5. Poll until the device confirms the target app is running.
|
|
5592
|
+
*/
|
|
5593
|
+
/**
|
|
5594
|
+
* @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
|
|
5595
|
+
* device is about to display "Open <app>" on screen and wait for the
|
|
5596
|
+
* user's button press. UI consumers should show their "open app" prompt
|
|
5597
|
+
* in response. NOT called when the target app is already open (no user
|
|
5598
|
+
* interaction needed in that case).
|
|
5599
|
+
*
|
|
5600
|
+
* Important: OpenAppCommand is blocking. It does not resolve until the user
|
|
5601
|
+
* has physically confirmed on the device, so anything that runs AFTER
|
|
5602
|
+
* `await this._openApp(...)` lands AFTER the prompt is already gone.
|
|
5603
|
+
* Hence the callback must fire BEFORE that await.
|
|
5604
|
+
*/
|
|
5605
|
+
async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
|
|
5606
|
+
const currentApp = await this._getCurrentApp(sessionId);
|
|
5607
|
+
if (currentApp === targetAppName) {
|
|
5608
|
+
return;
|
|
5609
|
+
}
|
|
5610
|
+
if (!this._isDashboard(currentApp)) {
|
|
5611
|
+
await this._closeCurrentApp(sessionId);
|
|
5612
|
+
await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
|
|
5613
|
+
}
|
|
5614
|
+
onConfirmOnDevice?.();
|
|
5615
|
+
await this._openApp(sessionId, targetAppName);
|
|
5616
|
+
await this._waitForApp(sessionId, targetAppName);
|
|
5617
|
+
}
|
|
5618
|
+
// ---------------------------------------------------------------------------
|
|
5619
|
+
// Private helpers
|
|
5620
|
+
// ---------------------------------------------------------------------------
|
|
5621
|
+
async _getCurrentApp(sessionId) {
|
|
5622
|
+
const result = await this._dmk.sendCommand({
|
|
5623
|
+
sessionId,
|
|
5624
|
+
command: new GetAppAndVersionCommand()
|
|
5625
|
+
});
|
|
5626
|
+
if (isSuccessCommandResult(result)) {
|
|
5627
|
+
debugLog("[AppManager] currentApp:", result.data.name);
|
|
5628
|
+
return result.data.name;
|
|
5629
|
+
}
|
|
5630
|
+
const errResult = result;
|
|
5631
|
+
const dmkErr = errResult.error ?? {};
|
|
5632
|
+
const original = dmkErr.originalError;
|
|
5633
|
+
debugLog(
|
|
5634
|
+
"[AppManager] _getCurrentApp failed sessionId=",
|
|
5635
|
+
sessionId,
|
|
5636
|
+
"tag=",
|
|
5637
|
+
dmkErr._tag,
|
|
5638
|
+
"errorCode=",
|
|
5639
|
+
dmkErr.errorCode,
|
|
5640
|
+
"message=",
|
|
5641
|
+
dmkErr.message,
|
|
5642
|
+
"originalErrorMessage=",
|
|
5643
|
+
original?.message ?? String(original ?? "")
|
|
5644
|
+
);
|
|
5645
|
+
throw Object.assign(
|
|
5646
|
+
new Error(
|
|
5647
|
+
dmkErr.message ?? "Failed to get current app from device"
|
|
5648
|
+
),
|
|
5649
|
+
{
|
|
5650
|
+
_tag: dmkErr._tag,
|
|
5651
|
+
errorCode: dmkErr.errorCode,
|
|
5652
|
+
originalError: original
|
|
5653
|
+
}
|
|
5654
|
+
);
|
|
5655
|
+
}
|
|
5656
|
+
async _openApp(sessionId, appName) {
|
|
5657
|
+
const result = await this._dmk.sendCommand({
|
|
5658
|
+
sessionId,
|
|
5659
|
+
command: new OpenAppCommand({ appName })
|
|
5660
|
+
});
|
|
5661
|
+
if (!isSuccessCommandResult(result)) {
|
|
5662
|
+
const dmkErr = result.error;
|
|
5663
|
+
const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
|
|
5664
|
+
const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
|
|
5665
|
+
debugLog(
|
|
5666
|
+
"[AppManager] openApp failed:",
|
|
5667
|
+
appName,
|
|
5668
|
+
"errorCode:",
|
|
5669
|
+
errorCode,
|
|
5670
|
+
"tag:",
|
|
5671
|
+
dmkErr._tag
|
|
5672
|
+
);
|
|
5673
|
+
let code;
|
|
5674
|
+
if (errorCode === "6807" || /unknown application/i.test(message)) {
|
|
5675
|
+
code = HardwareErrorCode8.AppNotInstalled;
|
|
5676
|
+
} else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
|
|
5677
|
+
code = HardwareErrorCode8.UserRejected;
|
|
5678
|
+
}
|
|
5679
|
+
throw Object.assign(new Error(`Failed to open "${appName}"`), {
|
|
5680
|
+
_tag: ERROR_TAG.OpenAppCommand,
|
|
5681
|
+
code,
|
|
5682
|
+
errorCode,
|
|
5683
|
+
statusCode: errorCode,
|
|
5684
|
+
appName,
|
|
5685
|
+
originalError: dmkErr
|
|
5686
|
+
});
|
|
5687
|
+
}
|
|
5688
|
+
}
|
|
5689
|
+
async _closeCurrentApp(sessionId) {
|
|
5690
|
+
debugLog("[AppManager] closeCurrentApp");
|
|
5691
|
+
await this._dmk.sendCommand({
|
|
5692
|
+
sessionId,
|
|
5693
|
+
command: new CloseAppCommand()
|
|
5694
|
+
});
|
|
5695
|
+
}
|
|
5696
|
+
/**
|
|
5697
|
+
* Poll the device until the expected app is reported as running,
|
|
5698
|
+
* or throw after `_maxRetries` attempts.
|
|
5699
|
+
*/
|
|
5700
|
+
async _waitForApp(sessionId, expectedAppName) {
|
|
5701
|
+
let lastSeen = "";
|
|
5702
|
+
for (let i = 0; i < this._maxRetries; i++) {
|
|
5703
|
+
await this._wait();
|
|
5704
|
+
const current = await this._getCurrentApp(sessionId);
|
|
5705
|
+
lastSeen = current;
|
|
5706
|
+
if (current === expectedAppName) {
|
|
5707
|
+
return;
|
|
5708
|
+
}
|
|
5709
|
+
}
|
|
5710
|
+
debugLog(
|
|
5711
|
+
"[AppManager] waitForApp exhausted: expected=",
|
|
5712
|
+
expectedAppName,
|
|
5713
|
+
"lastSeen=",
|
|
5714
|
+
lastSeen
|
|
5715
|
+
);
|
|
5716
|
+
throw new Error(
|
|
5717
|
+
`Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
|
|
5718
|
+
);
|
|
5719
|
+
}
|
|
5720
|
+
_isDashboard(appName) {
|
|
5721
|
+
return appName === DASHBOARD_APP_NAME;
|
|
5722
|
+
}
|
|
5723
|
+
_wait() {
|
|
5724
|
+
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
5725
|
+
}
|
|
5726
|
+
};
|
|
4925
5727
|
export {
|
|
4926
5728
|
AppManager,
|
|
4927
5729
|
DmkTransport,
|
|
@@ -4932,6 +5734,7 @@ export {
|
|
|
4932
5734
|
SignerEth,
|
|
4933
5735
|
SignerManager,
|
|
4934
5736
|
SignerSol,
|
|
5737
|
+
SignerZcash,
|
|
4935
5738
|
debugLog,
|
|
4936
5739
|
deviceActionToPromise,
|
|
4937
5740
|
isDeviceLockedError,
|