@onekeyfe/hwk-ledger-adapter 1.2.8-alpha.51 → 1.2.8-alpha.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +92 -52
- package/dist/index.d.ts +92 -52
- package/dist/index.js +1943 -964
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1882 -878
- package/dist/index.mjs.map +1 -1
- package/package.json +14 -11
package/dist/index.js
CHANGED
|
@@ -39,6 +39,7 @@ __export(index_exports, {
|
|
|
39
39
|
SignerEth: () => SignerEth,
|
|
40
40
|
SignerManager: () => SignerManager,
|
|
41
41
|
SignerSol: () => SignerSol,
|
|
42
|
+
SignerZcash: () => SignerZcash,
|
|
42
43
|
debugLog: () => debugLog,
|
|
43
44
|
deviceActionToPromise: () => deviceActionToPromise,
|
|
44
45
|
isDeviceLockedError: () => isDeviceLockedError,
|
|
@@ -53,21 +54,18 @@ __export(index_exports, {
|
|
|
53
54
|
module.exports = __toCommonJS(index_exports);
|
|
54
55
|
|
|
55
56
|
// src/adapter/LedgerAdapter.ts
|
|
56
|
-
var
|
|
57
|
+
var import_hwk_adapter_core4 = require("@onekeyfe/hwk-adapter-core");
|
|
57
58
|
|
|
58
59
|
// src/errors.ts
|
|
59
60
|
var import_hwk_adapter_core = require("@onekeyfe/hwk-adapter-core");
|
|
60
|
-
|
|
61
|
-
function createMultipleUsbLedgerDevicesError() {
|
|
62
|
-
return Object.assign(new Error(MULTIPLE_USB_LEDGER_DEVICES_ERROR_MESSAGE), {
|
|
63
|
-
code: import_hwk_adapter_core.HardwareErrorCode.DeviceOneDeviceOnly
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
function ledgerFailure(code, error, appName, tag, params) {
|
|
61
|
+
function ledgerFailure(code, error, appName, tag, params, origin, recovery) {
|
|
67
62
|
const payload = { error, code };
|
|
68
63
|
if (appName !== void 0) payload.appName = appName;
|
|
69
64
|
if (tag !== void 0) payload._tag = tag;
|
|
70
65
|
if (params !== void 0) payload.params = params;
|
|
66
|
+
const resolvedOrigin = origin ?? (0, import_hwk_adapter_core.defaultOriginForCode)(code);
|
|
67
|
+
if (resolvedOrigin !== void 0) payload.origin = resolvedOrigin;
|
|
68
|
+
payload.recovery = recovery ?? (0, import_hwk_adapter_core.defaultRecoveryForCode)(code);
|
|
71
69
|
return { success: false, payload };
|
|
72
70
|
}
|
|
73
71
|
var LOCKED_ERROR_CODES = /* @__PURE__ */ new Set(["5515", "21781", "6982", "27010", "5303", "21251"]);
|
|
@@ -208,7 +206,10 @@ var ERROR_TAG = {
|
|
|
208
206
|
UnknownDevice: "UnknownDeviceError",
|
|
209
207
|
DeviceSessionRefresher: "DeviceSessionRefresherError",
|
|
210
208
|
DeviceNotInitialized: "DeviceNotInitializedError",
|
|
211
|
-
|
|
209
|
+
// DMK class OpeningConnectionError carries `_tag` "ConnectionOpeningError"; both
|
|
210
|
+
// spellings are kept so a DMK release that aligns them still classifies.
|
|
211
|
+
OpeningConnection: "ConnectionOpeningError",
|
|
212
|
+
OpeningConnectionLegacy: "OpeningConnectionError",
|
|
212
213
|
DeviceDisconnectedBeforeSendingApdu: "DeviceDisconnectedBeforeSendingApdu",
|
|
213
214
|
DeviceDisconnectedWhileSending: "DeviceDisconnectedWhileSendingError",
|
|
214
215
|
Disconnect: "DisconnectError",
|
|
@@ -221,7 +222,16 @@ var ERROR_TAG = {
|
|
|
221
222
|
// DMK remote-network failures (manager-api HTTP / secure-channel WS).
|
|
222
223
|
WebSocketConnection: "WebSocketConnectionError",
|
|
223
224
|
HttpFetch: "FetchError",
|
|
224
|
-
|
|
225
|
+
NetworkDA: "NetworkDAError",
|
|
226
|
+
InvalidFirmwareMetadataResponse: "InvalidGetFirmwareMetadataResponseError",
|
|
227
|
+
ApplicationsMetadataTask: "GetApplicationsMetadataTaskError",
|
|
228
|
+
// DMK OS device actions. SecureChannelError is what mapInstallDAErrors() leaves
|
|
229
|
+
// after splitting out device answers, i.e. the relay itself broke.
|
|
230
|
+
SecureChannel: "SecureChannelError",
|
|
231
|
+
RefusedByUserDA: "RefusedByUserDAError",
|
|
232
|
+
AppAlreadyInstalledDA: "AppAlreadyInstalledDAError",
|
|
233
|
+
OutOfMemoryDA: "OutOfMemoryDAError",
|
|
234
|
+
DeviceNotOnboarded: "DeviceNotOnboardedError"
|
|
225
235
|
};
|
|
226
236
|
function isDeviceLockedError(err) {
|
|
227
237
|
if (!err || typeof err !== "object") return false;
|
|
@@ -251,7 +261,6 @@ function isBlePairingFailureError(err) {
|
|
|
251
261
|
return false;
|
|
252
262
|
}
|
|
253
263
|
var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
|
|
254
|
-
ERROR_TAG.DeviceLocked,
|
|
255
264
|
ERROR_TAG.DeviceNotAdvertising,
|
|
256
265
|
ERROR_TAG.BlePairingTimeout,
|
|
257
266
|
ERROR_TAG.BleGattBondingFailed,
|
|
@@ -263,6 +272,7 @@ var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
|
|
|
263
272
|
ERROR_TAG.DeviceSessionRefresher,
|
|
264
273
|
ERROR_TAG.DeviceNotInitialized,
|
|
265
274
|
ERROR_TAG.OpeningConnection,
|
|
275
|
+
ERROR_TAG.OpeningConnectionLegacy,
|
|
266
276
|
ERROR_TAG.DeviceDisconnectedBeforeSendingApdu,
|
|
267
277
|
ERROR_TAG.DeviceDisconnectedWhileSending,
|
|
268
278
|
ERROR_TAG.Disconnect,
|
|
@@ -277,7 +287,10 @@ var DEVICE_NOT_FOUND_TAGS = /* @__PURE__ */ new Set([
|
|
|
277
287
|
// Map to DeviceNotFound so non-BLE-direct paths get a sensible error code.
|
|
278
288
|
ERROR_TAG.DeviceNotInDiscoveryCache
|
|
279
289
|
]);
|
|
280
|
-
var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
|
|
290
|
+
var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
|
|
291
|
+
ERROR_TAG.OpeningConnection,
|
|
292
|
+
ERROR_TAG.OpeningConnectionLegacy
|
|
293
|
+
]);
|
|
281
294
|
var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
|
|
282
295
|
ERROR_TAG.DeviceNotRecognized,
|
|
283
296
|
ERROR_TAG.DeviceSessionNotFound,
|
|
@@ -289,17 +302,18 @@ var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
|
|
|
289
302
|
ERROR_TAG.WebHIDDisconnect
|
|
290
303
|
]);
|
|
291
304
|
function isConnectionLevelError(err) {
|
|
292
|
-
|
|
293
|
-
const tag = err._tag;
|
|
294
|
-
if (tag && CONNECTION_LEVEL_TAGS.has(tag)) return true;
|
|
295
|
-
const e = err;
|
|
296
|
-
if (e.originalError != null && isConnectionLevelError(e.originalError)) return true;
|
|
297
|
-
if (e.error != null && e._tag && isConnectionLevelError(e.error)) return true;
|
|
298
|
-
return false;
|
|
305
|
+
return hasErrorTag(err, CONNECTION_LEVEL_TAGS);
|
|
299
306
|
}
|
|
300
307
|
function isKnownConnectionTag(tag) {
|
|
301
308
|
return typeof tag === "string" && CONNECTION_LEVEL_TAGS.has(tag);
|
|
302
309
|
}
|
|
310
|
+
var CONNECTION_OPENING_TAGS = /* @__PURE__ */ new Set([
|
|
311
|
+
ERROR_TAG.OpeningConnection,
|
|
312
|
+
ERROR_TAG.OpeningConnectionLegacy
|
|
313
|
+
]);
|
|
314
|
+
function isConnectionOpeningTag(tag) {
|
|
315
|
+
return typeof tag === "string" && CONNECTION_OPENING_TAGS.has(tag);
|
|
316
|
+
}
|
|
303
317
|
function hasStatusCode(err, codeSet) {
|
|
304
318
|
if (!err || typeof err !== "object") return false;
|
|
305
319
|
const e = err;
|
|
@@ -335,28 +349,28 @@ function hasInvalidArgumentCode(err) {
|
|
|
335
349
|
if (e.error != null && e._tag && hasInvalidArgumentCode(e.error)) return true;
|
|
336
350
|
return false;
|
|
337
351
|
}
|
|
338
|
-
function
|
|
352
|
+
function hasErrorTag(err, tags) {
|
|
339
353
|
if (!err || typeof err !== "object") return false;
|
|
340
|
-
const tag = err._tag;
|
|
341
|
-
if (tag && DEVICE_NOT_FOUND_TAGS.has(tag)) return true;
|
|
342
354
|
const e = err;
|
|
343
|
-
if (e.
|
|
344
|
-
if (e.
|
|
355
|
+
if (typeof e._tag === "string" && tags.has(e._tag)) return true;
|
|
356
|
+
if (e.originalError != null && hasErrorTag(e.originalError, tags)) return true;
|
|
357
|
+
if (e.error != null && e._tag && hasErrorTag(e.error, tags)) return true;
|
|
345
358
|
return false;
|
|
346
359
|
}
|
|
360
|
+
function isDeviceNotFoundError(err) {
|
|
361
|
+
return hasErrorTag(err, DEVICE_NOT_FOUND_TAGS);
|
|
362
|
+
}
|
|
347
363
|
function isDeviceBusyError(err) {
|
|
348
|
-
|
|
349
|
-
const tag = err._tag;
|
|
350
|
-
if (tag && DEVICE_BUSY_TAGS.has(tag)) return true;
|
|
351
|
-
const e = err;
|
|
352
|
-
if (e.originalError != null && isDeviceBusyError(e.originalError)) return true;
|
|
353
|
-
if (e.error != null && e._tag && isDeviceBusyError(e.error)) return true;
|
|
354
|
-
return false;
|
|
364
|
+
return hasErrorTag(err, DEVICE_BUSY_TAGS);
|
|
355
365
|
}
|
|
366
|
+
var USER_REJECTED_TAGS = /* @__PURE__ */ new Set([
|
|
367
|
+
ERROR_TAG.UserRefusedOnDevice,
|
|
368
|
+
ERROR_TAG.RefusedByUserDA
|
|
369
|
+
]);
|
|
356
370
|
function isUserRejectedError(err) {
|
|
357
371
|
if (!err || typeof err !== "object") return false;
|
|
358
372
|
const e = err;
|
|
359
|
-
if (
|
|
373
|
+
if (hasErrorTag(err, USER_REJECTED_TAGS)) return true;
|
|
360
374
|
if (typeof e.message === "string" && /denied|rejected|refused/i.test(e.message)) return true;
|
|
361
375
|
if (hasStatusCode(err, USER_REJECTED_CODES)) return true;
|
|
362
376
|
return false;
|
|
@@ -387,15 +401,33 @@ function isAppNotInstalledError(err) {
|
|
|
387
401
|
if (hasStatusCode(err, APP_NOT_INSTALLED_CODES)) return true;
|
|
388
402
|
return false;
|
|
389
403
|
}
|
|
404
|
+
var OUT_OF_MEMORY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OutOfMemoryDA]);
|
|
390
405
|
function isOutOfMemoryError(err) {
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
406
|
+
return hasErrorTag(err, OUT_OF_MEMORY_TAGS);
|
|
407
|
+
}
|
|
408
|
+
var APP_ALREADY_INSTALLED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.AppAlreadyInstalledDA]);
|
|
409
|
+
function isAppAlreadyInstalledError(err) {
|
|
410
|
+
return hasErrorTag(err, APP_ALREADY_INSTALLED_TAGS);
|
|
411
|
+
}
|
|
412
|
+
var DEVICE_NOT_ONBOARDED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.DeviceNotOnboarded]);
|
|
413
|
+
function isDeviceNotOnboardedError(err) {
|
|
414
|
+
return hasErrorTag(err, DEVICE_NOT_ONBOARDED_TAGS);
|
|
415
|
+
}
|
|
416
|
+
var FIRMWARE_METADATA_TAGS = /* @__PURE__ */ new Set([
|
|
417
|
+
ERROR_TAG.InvalidFirmwareMetadataResponse,
|
|
418
|
+
ERROR_TAG.ApplicationsMetadataTask
|
|
419
|
+
]);
|
|
420
|
+
function isFirmwareMetadataError(err) {
|
|
421
|
+
return hasErrorTag(err, FIRMWARE_METADATA_TAGS);
|
|
422
|
+
}
|
|
423
|
+
var SECURE_CHANNEL_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.SecureChannel]);
|
|
424
|
+
function isSecureChannelError(err) {
|
|
425
|
+
return hasErrorTag(err, SECURE_CHANNEL_TAGS);
|
|
394
426
|
}
|
|
395
427
|
var NETWORK_ERROR_TAGS = /* @__PURE__ */ new Set([
|
|
396
428
|
ERROR_TAG.WebSocketConnection,
|
|
397
429
|
ERROR_TAG.HttpFetch,
|
|
398
|
-
ERROR_TAG.
|
|
430
|
+
ERROR_TAG.NetworkDA
|
|
399
431
|
]);
|
|
400
432
|
function isNetworkError(err) {
|
|
401
433
|
if (!err || typeof err !== "object") return false;
|
|
@@ -445,23 +477,34 @@ function isTransportStuck(err) {
|
|
|
445
477
|
function isStuckAppStateError(err) {
|
|
446
478
|
return isAppStuckByApdu(err) || isTransportStuck(err);
|
|
447
479
|
}
|
|
480
|
+
var DMK_PLACEHOLDER_MESSAGE = "Unknown error.";
|
|
481
|
+
function nestedErrorMessage(nested) {
|
|
482
|
+
if (!nested || typeof nested !== "object") return void 0;
|
|
483
|
+
const { message } = nested;
|
|
484
|
+
if (typeof message !== "string") return void 0;
|
|
485
|
+
const trimmed = message.trim();
|
|
486
|
+
if (!trimmed || trimmed === DMK_PLACEHOLDER_MESSAGE) return void 0;
|
|
487
|
+
return message;
|
|
488
|
+
}
|
|
448
489
|
function mapLedgerError(err, opts) {
|
|
449
490
|
let originalMessage = "Unknown Ledger error";
|
|
450
491
|
if (err instanceof Error) {
|
|
451
492
|
originalMessage = err.message;
|
|
452
493
|
} else if (err && typeof err === "object") {
|
|
453
494
|
const e = err;
|
|
454
|
-
originalMessage = String(
|
|
495
|
+
originalMessage = String(
|
|
496
|
+
e.message ?? nestedErrorMessage(e.originalError) ?? e._tag ?? e.type ?? JSON.stringify(err)
|
|
497
|
+
);
|
|
455
498
|
}
|
|
456
499
|
let code;
|
|
457
500
|
if (isDeviceLockedError(err)) {
|
|
458
501
|
code = import_hwk_adapter_core.HardwareErrorCode.DeviceLocked;
|
|
459
502
|
} else if (isDeviceNotAdvertisingError(err) || isDeviceNotFoundError(err)) {
|
|
460
503
|
code = import_hwk_adapter_core.HardwareErrorCode.DeviceNotFound;
|
|
461
|
-
} else if (isDeviceBusyError(err)) {
|
|
462
|
-
code = import_hwk_adapter_core.HardwareErrorCode.DeviceBusy;
|
|
463
504
|
} else if (isBlePairingFailureError(err)) {
|
|
464
505
|
code = import_hwk_adapter_core.HardwareErrorCode.BlePairingTimeout;
|
|
506
|
+
} else if (isDeviceBusyError(err)) {
|
|
507
|
+
code = import_hwk_adapter_core.HardwareErrorCode.DeviceBusy;
|
|
465
508
|
} else if (isUserAbortedError(err)) {
|
|
466
509
|
code = import_hwk_adapter_core.HardwareErrorCode.UserAborted;
|
|
467
510
|
} else if (isUserRejectedError(err)) {
|
|
@@ -470,10 +513,18 @@ function mapLedgerError(err, opts) {
|
|
|
470
513
|
code = import_hwk_adapter_core.HardwareErrorCode.WrongApp;
|
|
471
514
|
} else if (isAppNotInstalledError(err)) {
|
|
472
515
|
code = import_hwk_adapter_core.HardwareErrorCode.AppNotInstalled;
|
|
516
|
+
} else if (isAppAlreadyInstalledError(err)) {
|
|
517
|
+
code = import_hwk_adapter_core.HardwareErrorCode.AppAlreadyInstalled;
|
|
473
518
|
} else if (isOutOfMemoryError(err)) {
|
|
474
519
|
code = import_hwk_adapter_core.HardwareErrorCode.DeviceOutOfMemory;
|
|
520
|
+
} else if (isDeviceNotOnboardedError(err)) {
|
|
521
|
+
code = import_hwk_adapter_core.HardwareErrorCode.DeviceNotInitialized;
|
|
522
|
+
} else if (isFirmwareMetadataError(err)) {
|
|
523
|
+
code = import_hwk_adapter_core.HardwareErrorCode.LedgerFirmwareMetadataError;
|
|
475
524
|
} else if (isNetworkError(err)) {
|
|
476
525
|
code = import_hwk_adapter_core.HardwareErrorCode.NetworkError;
|
|
526
|
+
} else if (isSecureChannelError(err)) {
|
|
527
|
+
code = import_hwk_adapter_core.HardwareErrorCode.LedgerSecureChannelError;
|
|
477
528
|
} else if (isDeviceDisconnectedError(err)) {
|
|
478
529
|
code = import_hwk_adapter_core.HardwareErrorCode.DeviceDisconnected;
|
|
479
530
|
} else if (isTimeoutError(err)) {
|
|
@@ -486,11 +537,25 @@ function mapLedgerError(err, opts) {
|
|
|
486
537
|
}
|
|
487
538
|
const errAppName = err && typeof err === "object" ? err.appName : void 0;
|
|
488
539
|
const appName = errAppName ?? opts?.defaultAppName;
|
|
489
|
-
return {
|
|
540
|
+
return {
|
|
541
|
+
code,
|
|
542
|
+
message: (0, import_hwk_adapter_core.enrichErrorMessage)(code, originalMessage),
|
|
543
|
+
origin: (0, import_hwk_adapter_core.defaultOriginForCode)(code),
|
|
544
|
+
appName
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// src/utils/queueKey.ts
|
|
549
|
+
var LEDGER_DEFAULT_QUEUE_KEY = "__ledger_default__";
|
|
550
|
+
function ledgerQueueKey({
|
|
551
|
+
operationId,
|
|
552
|
+
connectId
|
|
553
|
+
}) {
|
|
554
|
+
return (operationId ?? connectId) || LEDGER_DEFAULT_QUEUE_KEY;
|
|
490
555
|
}
|
|
491
556
|
|
|
492
557
|
// src/adapter/methods/allNetworkGetAddress.ts
|
|
493
|
-
var
|
|
558
|
+
var import_hwk_adapter_core3 = require("@onekeyfe/hwk-adapter-core");
|
|
494
559
|
|
|
495
560
|
// src/utils/sdkEventBus.ts
|
|
496
561
|
var listeners = /* @__PURE__ */ new Set();
|
|
@@ -537,6 +602,32 @@ function debugError(...args) {
|
|
|
537
602
|
emitLog("error", ...args);
|
|
538
603
|
}
|
|
539
604
|
|
|
605
|
+
// src/utils/logSummary.ts
|
|
606
|
+
var import_hwk_adapter_core2 = require("@onekeyfe/hwk-adapter-core");
|
|
607
|
+
var import_bitcoinjs_lib = require("bitcoinjs-lib");
|
|
608
|
+
var HEX_RE = /^(0x)?[0-9a-fA-F]+$/;
|
|
609
|
+
var BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
610
|
+
function parsePsbt(input) {
|
|
611
|
+
if (typeof input !== "string") return import_bitcoinjs_lib.Psbt.fromBuffer(input);
|
|
612
|
+
if (HEX_RE.test(input)) return import_bitcoinjs_lib.Psbt.fromHex(input.replace(/^0x/i, ""));
|
|
613
|
+
if (BASE64_RE.test(input)) return import_bitcoinjs_lib.Psbt.fromBase64(input);
|
|
614
|
+
return void 0;
|
|
615
|
+
}
|
|
616
|
+
var describePsbtForLog = (key, value) => {
|
|
617
|
+
if (key !== "psbt") return void 0;
|
|
618
|
+
try {
|
|
619
|
+
const psbt = parsePsbt(value);
|
|
620
|
+
if (!psbt) return void 0;
|
|
621
|
+
const unsignedTx = import_bitcoinjs_lib.Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());
|
|
622
|
+
return `inputs=${psbt.inputCount} outputs=${psbt.txOutputs.length} txid=${unsignedTx.getId()}`;
|
|
623
|
+
} catch {
|
|
624
|
+
return void 0;
|
|
625
|
+
}
|
|
626
|
+
};
|
|
627
|
+
function summarizeForLog(value, options = {}) {
|
|
628
|
+
return (0, import_hwk_adapter_core2.summarizeForLog)(value, { ...options, describePayload: describePsbtForLog });
|
|
629
|
+
}
|
|
630
|
+
|
|
540
631
|
// src/adapter/methods/allNetworkGetAddress.ts
|
|
541
632
|
var LEDGER_BTC_NETWORK_COIN_MAP = {
|
|
542
633
|
tbtc: "Testnet",
|
|
@@ -547,57 +638,105 @@ var LEDGER_BTC_NETWORK_COIN_MAP = {
|
|
|
547
638
|
var LEDGER_UNSUPPORTED_ALLNETWORK_NETWORKS = /* @__PURE__ */ new Set(["doge", "dogecoin"]);
|
|
548
639
|
function createAllNetworkGetAddress({
|
|
549
640
|
callChain,
|
|
550
|
-
getChainFingerprint
|
|
641
|
+
getChainFingerprint,
|
|
642
|
+
retainOperation,
|
|
643
|
+
errorToFailure,
|
|
644
|
+
createCancelScope,
|
|
645
|
+
releaseBundle
|
|
551
646
|
}) {
|
|
552
647
|
return async function allNetworkGetAddress(connectId, _deviceId, params) {
|
|
553
|
-
debugLog("[LedgerAdapter][REQ]", {
|
|
554
|
-
|
|
648
|
+
debugLog("[LedgerAdapter][REQ]", {
|
|
649
|
+
method: "allNetworkGetAddress",
|
|
650
|
+
connectId,
|
|
651
|
+
itemCount: params.bundle.length
|
|
652
|
+
});
|
|
653
|
+
const target = (0, import_hwk_adapter_core3.resolveHardwareOperationTarget)(connectId, params.operationId, "ledger");
|
|
654
|
+
if (!target.success) return target;
|
|
655
|
+
const effectiveTargetId = target.payload.targetId ?? "";
|
|
656
|
+
let releaseOperationRetention;
|
|
657
|
+
try {
|
|
658
|
+
releaseOperationRetention = target.payload.operationId ? retainOperation(target.payload.operationId) : void 0;
|
|
659
|
+
} catch (error) {
|
|
660
|
+
return errorToFailure(error);
|
|
661
|
+
}
|
|
662
|
+
const cancelScope = createCancelScope(
|
|
663
|
+
ledgerQueueKey({ operationId: target.payload.operationId, connectId: effectiveTargetId })
|
|
664
|
+
);
|
|
665
|
+
const installContext = {
|
|
666
|
+
walletCheck: { expected: params.bundle.some((item) => Boolean(getItemDeviceId(item))) }
|
|
667
|
+
};
|
|
555
668
|
const commonParams = {
|
|
556
|
-
autoInstallApp: params.autoInstallApp
|
|
669
|
+
autoInstallApp: params.autoInstallApp,
|
|
670
|
+
operationId: target.payload.operationId,
|
|
671
|
+
knownConnections: params.knownConnections,
|
|
672
|
+
extra: params.extra,
|
|
673
|
+
allowDeviceSelection: params.allowDeviceSelection,
|
|
674
|
+
supportedTransports: params.supportedTransports
|
|
557
675
|
};
|
|
558
676
|
const chainFingerprints = /* @__PURE__ */ new Map();
|
|
559
|
-
const
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
677
|
+
const order = params.bundle.map((_item, index) => index).sort(
|
|
678
|
+
(a, b) => Number(Boolean(getItemDeviceId(params.bundle[b]))) - Number(Boolean(getItemDeviceId(params.bundle[a])))
|
|
679
|
+
);
|
|
680
|
+
try {
|
|
681
|
+
const ordered = await (0, import_hwk_adapter_core3.runAllNetworkGetAddress)({
|
|
682
|
+
connectId: effectiveTargetId,
|
|
683
|
+
deviceId: _deviceId,
|
|
684
|
+
params: { ...params, bundle: order.map((index) => params.bundle[index]) },
|
|
685
|
+
normalizeItem: normalizeLedgerAllNetworkItem,
|
|
686
|
+
buildUnsupportedNetworkResponse: (item) => isUnsupportedLedgerAllNetworkNetwork(item) ? buildUnsupportedNetworkResponse(item) : void 0,
|
|
687
|
+
callItem: async ({ method, chain, item }) => {
|
|
688
|
+
if (cancelScope.signal.aborted)
|
|
689
|
+
return (0, import_hwk_adapter_core3.buildAllNetworkCancelledFailure)(cancelScope.signal);
|
|
690
|
+
const itemDeviceId = getItemDeviceId(item) ?? chainFingerprints.get(chain) ?? "";
|
|
691
|
+
return callAllNetworkMethod(
|
|
692
|
+
callChain,
|
|
693
|
+
effectiveTargetId,
|
|
694
|
+
itemDeviceId,
|
|
695
|
+
method,
|
|
696
|
+
item,
|
|
697
|
+
commonParams,
|
|
698
|
+
installContext
|
|
699
|
+
);
|
|
700
|
+
},
|
|
701
|
+
attachIdentity: async ({ item, chain, payload }) => attachLedgerIdentity(
|
|
702
|
+
getChainFingerprint,
|
|
703
|
+
effectiveTargetId,
|
|
572
704
|
item,
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
)
|
|
705
|
+
chain,
|
|
706
|
+
payload,
|
|
707
|
+
chainFingerprints,
|
|
708
|
+
installContext,
|
|
709
|
+
cancelScope.signal
|
|
710
|
+
),
|
|
711
|
+
shouldAbortBundle: isTopLevelAllNetworkFailure,
|
|
712
|
+
buildTopLevelFailure: (response) => {
|
|
713
|
+
const code = response.payload?.code ?? import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch;
|
|
714
|
+
return (0, import_hwk_adapter_core3.failure)(
|
|
715
|
+
code,
|
|
716
|
+
response.payload?.error ?? "All-network get-address aborted",
|
|
717
|
+
response.payload?.params
|
|
718
|
+
);
|
|
719
|
+
}
|
|
720
|
+
});
|
|
721
|
+
let result = ordered;
|
|
722
|
+
if (ordered.success) {
|
|
723
|
+
const responses = [];
|
|
724
|
+
ordered.payload.forEach((response, position) => {
|
|
725
|
+
responses[order[position]] = response;
|
|
726
|
+
});
|
|
727
|
+
result = (0, import_hwk_adapter_core3.success)(responses);
|
|
593
728
|
}
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
729
|
+
debugLog("[LedgerAdapter][RES]", {
|
|
730
|
+
method: "allNetworkGetAddress",
|
|
731
|
+
success: result.success,
|
|
732
|
+
payload: summarizeForLog(result, { method: "allNetworkGetAddress", role: "result" })
|
|
733
|
+
});
|
|
734
|
+
return result;
|
|
735
|
+
} finally {
|
|
736
|
+
await releaseBundle(installContext, cancelScope.signal).catch(() => void 0);
|
|
737
|
+
cancelScope.release();
|
|
738
|
+
releaseOperationRetention?.();
|
|
739
|
+
}
|
|
601
740
|
};
|
|
602
741
|
}
|
|
603
742
|
function isTopLevelAllNetworkFailure(response) {
|
|
@@ -605,7 +744,7 @@ function isTopLevelAllNetworkFailure(response) {
|
|
|
605
744
|
return false;
|
|
606
745
|
}
|
|
607
746
|
const code = response.payload?.code;
|
|
608
|
-
return
|
|
747
|
+
return (0, import_hwk_adapter_core3.isWalletSafetyFailure)(code) || (0, import_hwk_adapter_core3.isUserRefusal)(code) || (0, import_hwk_adapter_core3.isConnectionLost)(code);
|
|
609
748
|
}
|
|
610
749
|
function getItemDeviceId(item) {
|
|
611
750
|
const { deviceId } = item;
|
|
@@ -619,7 +758,7 @@ function buildUnsupportedNetworkResponse(item) {
|
|
|
619
758
|
...item,
|
|
620
759
|
success: false,
|
|
621
760
|
payload: {
|
|
622
|
-
code:
|
|
761
|
+
code: import_hwk_adapter_core3.HardwareErrorCode.ChainNotSupported,
|
|
623
762
|
error: `Ledger allNetwork does not support ${item.network.toLowerCase() === "doge" ? "Dogecoin" : item.network}`
|
|
624
763
|
}
|
|
625
764
|
};
|
|
@@ -635,8 +774,18 @@ function normalizeLedgerAllNetworkItem(method, item) {
|
|
|
635
774
|
const coin = LEDGER_BTC_NETWORK_COIN_MAP[item.network];
|
|
636
775
|
return coin ? { ...item, coin } : item;
|
|
637
776
|
}
|
|
638
|
-
async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints) {
|
|
639
|
-
const
|
|
777
|
+
async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints, context, cancelSignal) {
|
|
778
|
+
const knownFingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || "";
|
|
779
|
+
if (!knownFingerprint && cancelSignal.aborted) {
|
|
780
|
+
const cancelled = (0, import_hwk_adapter_core3.buildAllNetworkCancelledFailure)(cancelSignal);
|
|
781
|
+
return { ...item, success: false, payload: cancelled.payload };
|
|
782
|
+
}
|
|
783
|
+
const fingerprint = knownFingerprint || await bootstrapChainFingerprint(
|
|
784
|
+
getChainFingerprint,
|
|
785
|
+
context.connection?.connectId ?? connectId,
|
|
786
|
+
chain,
|
|
787
|
+
context
|
|
788
|
+
);
|
|
640
789
|
if (!fingerprint) {
|
|
641
790
|
return buildFingerprintBootstrapFailure(item, chain);
|
|
642
791
|
}
|
|
@@ -657,8 +806,8 @@ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain,
|
|
|
657
806
|
}
|
|
658
807
|
};
|
|
659
808
|
}
|
|
660
|
-
async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain) {
|
|
661
|
-
const response = await getChainFingerprint(connectId, chain);
|
|
809
|
+
async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain, context) {
|
|
810
|
+
const response = await getChainFingerprint(connectId, chain, context);
|
|
662
811
|
return response.success ? response.payload : "";
|
|
663
812
|
}
|
|
664
813
|
function buildFingerprintBootstrapFailure(item, chain) {
|
|
@@ -666,7 +815,7 @@ function buildFingerprintBootstrapFailure(item, chain) {
|
|
|
666
815
|
...item,
|
|
667
816
|
success: false,
|
|
668
817
|
payload: {
|
|
669
|
-
code:
|
|
818
|
+
code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
|
|
670
819
|
error: `Could not establish chain fingerprint for ${chain} after device call; refusing to return unverifiable result. Please retry.`
|
|
671
820
|
}
|
|
672
821
|
};
|
|
@@ -730,7 +879,7 @@ async function callAllNetworkMethod(callChain, connectId, deviceId, method, item
|
|
|
730
879
|
);
|
|
731
880
|
default:
|
|
732
881
|
throw Object.assign(new Error(`Unsupported allNetwork method: ${method}`), {
|
|
733
|
-
code:
|
|
882
|
+
code: import_hwk_adapter_core3.HardwareErrorCode.InvalidParams
|
|
734
883
|
});
|
|
735
884
|
}
|
|
736
885
|
}
|
|
@@ -751,6 +900,9 @@ function isLedgerBleDescriptor(connectionType, descriptor) {
|
|
|
751
900
|
function formatDeviceMismatchError(expected, actual) {
|
|
752
901
|
return `Wrong device: expected ${expected}, got ${actual}`;
|
|
753
902
|
}
|
|
903
|
+
function isLostConnectionError(err) {
|
|
904
|
+
return isDeviceDisconnectedError(err) || isDeviceNotAdvertisingError(err) || isTimeoutError(err) || isConnectionLevelError(err);
|
|
905
|
+
}
|
|
754
906
|
var BTC_HIGH_INDEX_THRESHOLD = 100;
|
|
755
907
|
function btcAccountIndexFromPath(path) {
|
|
756
908
|
const segments = path.replace(/^m\//, "").split("/");
|
|
@@ -762,10 +914,36 @@ function btcAccountIndexFromPath(path) {
|
|
|
762
914
|
var _LedgerAdapter = class _LedgerAdapter {
|
|
763
915
|
constructor(connector, options) {
|
|
764
916
|
this.vendor = "ledger";
|
|
765
|
-
|
|
917
|
+
// Cancel frees the DMK action and its intent-queue slot, but cannot retract a
|
|
918
|
+
// confirmation screen the device is already showing.
|
|
919
|
+
this.cancelCapability = "stops-waiting";
|
|
920
|
+
this.emitter = new import_hwk_adapter_core4.TypedEventEmitter();
|
|
921
|
+
this._operations = new import_hwk_adapter_core4.OperationRegistry({
|
|
922
|
+
vendor: "ledger",
|
|
923
|
+
onEnded: (operation, reason) => {
|
|
924
|
+
this._discardPendingBinding(this._pendingOperationBindings.get(operation.operationId));
|
|
925
|
+
this._pendingOperationBindings.delete(operation.operationId);
|
|
926
|
+
this.emitter.emit(import_hwk_adapter_core4.SDK.OPERATION_ENDED, {
|
|
927
|
+
type: import_hwk_adapter_core4.SDK.OPERATION_ENDED,
|
|
928
|
+
payload: { operationId: operation.operationId, reason }
|
|
929
|
+
});
|
|
930
|
+
if (reason === "timeout" && !this._bareCallMayUseConnection(operation)) {
|
|
931
|
+
void this._releaseOperationConnection(operation);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
});
|
|
766
935
|
this._discoveredDevices = /* @__PURE__ */ new Map();
|
|
767
936
|
this._sessions = /* @__PURE__ */ new Map();
|
|
768
|
-
|
|
937
|
+
// An operation's BLE pick is saved by its first call that gets past the wallet check.
|
|
938
|
+
this._pendingOperationBindings = /* @__PURE__ */ new Map();
|
|
939
|
+
// A one-shot call's unchecked BLE pick, by connectId. It outlives the call only
|
|
940
|
+
// through an unlock retry; any other failure drops it with its session.
|
|
941
|
+
this._pendingPickBindings = /* @__PURE__ */ new Map();
|
|
942
|
+
// Transport each session was opened on, by sessionId. The adapter-wide
|
|
943
|
+
// `_activeConnectionType` moves with every discovery and can go stale.
|
|
944
|
+
this._sessionTransports = /* @__PURE__ */ new Map();
|
|
945
|
+
this._selectedBleReconnectTargets = /* @__PURE__ */ new Map();
|
|
946
|
+
this._uiRegistry = new import_hwk_adapter_core4.UiRequestRegistry();
|
|
769
947
|
// BTC App rejects account index >= 100 unless display=true. Cached per
|
|
770
948
|
// adapter instance: first 100+ path asks the user once via UI request,
|
|
771
949
|
// subsequent 100+ paths in the same session auto-promote silently.
|
|
@@ -778,21 +956,36 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
778
956
|
this._deviceAuthenticityQueueTail = Promise.resolve();
|
|
779
957
|
// Shared across concurrent callers — only `cancel()` aborts.
|
|
780
958
|
this._doConnectAbortController = null;
|
|
959
|
+
this._unsettledConnectorOperations = /* @__PURE__ */ new Map();
|
|
960
|
+
this._connectorIdleWaiters = /* @__PURE__ */ new Set();
|
|
961
|
+
this._resetPromise = null;
|
|
962
|
+
this._stateGeneration = 0;
|
|
963
|
+
this._connectorTeardownTail = Promise.resolve();
|
|
964
|
+
this._pendingConnectorTeardowns = 0;
|
|
965
|
+
this._activeOperationJobs = /* @__PURE__ */ new Set();
|
|
966
|
+
this._pendingOperationDisconnects = /* @__PURE__ */ new Set();
|
|
781
967
|
this._installProgressLastEmittedValue = -Infinity;
|
|
782
968
|
this.allNetworkGetAddress = createAllNetworkGetAddress({
|
|
783
969
|
callChain: this.callChain.bind(this),
|
|
784
|
-
getChainFingerprint: (connectId, chain) =>
|
|
970
|
+
getChainFingerprint: async (connectId, chain, context) => {
|
|
971
|
+
try {
|
|
972
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
973
|
+
chain,
|
|
974
|
+
(method, params) => this.connectorCall(connectId, method, params, void 0, void 0, void 0, context)
|
|
975
|
+
);
|
|
976
|
+
return (0, import_hwk_adapter_core4.success)(fingerprint);
|
|
977
|
+
} catch (error) {
|
|
978
|
+
return this.errorToFailure(error);
|
|
979
|
+
}
|
|
980
|
+
},
|
|
981
|
+
retainOperation: (operationId) => this._operations.retain(operationId),
|
|
982
|
+
errorToFailure: (error) => this.errorToFailure(error),
|
|
983
|
+
createCancelScope: (queueKey) => this._jobQueue.createCancelScope(queueKey),
|
|
984
|
+
releaseBundle: (context, signal) => this._dropUncheckedBundlePick(context, signal)
|
|
785
985
|
});
|
|
786
986
|
// ---------------------------------------------------------------------------
|
|
787
987
|
// Private helpers
|
|
788
988
|
// ---------------------------------------------------------------------------
|
|
789
|
-
/**
|
|
790
|
-
* Ensure at least one device is connected and return a valid connectId.
|
|
791
|
-
*
|
|
792
|
-
* - If a session already exists for the given connectId, reuse it.
|
|
793
|
-
* - If ANY session exists (Ledger IDs are ephemeral), reuse it.
|
|
794
|
-
* - Otherwise: search → exactly 1 USB device auto-connects; multiple or none throws.
|
|
795
|
-
*/
|
|
796
989
|
// Mutex for ensureConnected — prevents concurrent calls from establishing duplicate connections
|
|
797
990
|
this._connectingPromise = null;
|
|
798
991
|
// ---------------------------------------------------------------------------
|
|
@@ -802,26 +995,30 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
802
995
|
const deviceInfo = this.connectorDeviceToDeviceInfo(data.device);
|
|
803
996
|
this._discoveredDevices.set(deviceInfo.connectId, deviceInfo);
|
|
804
997
|
this._sessions.delete(deviceInfo.connectId);
|
|
805
|
-
this.emitter.emit(
|
|
806
|
-
type:
|
|
998
|
+
this.emitter.emit(import_hwk_adapter_core4.DEVICE.CONNECT, {
|
|
999
|
+
type: import_hwk_adapter_core4.DEVICE.CONNECT,
|
|
807
1000
|
payload: deviceInfo
|
|
808
1001
|
});
|
|
809
1002
|
};
|
|
810
1003
|
this.deviceDisconnectHandler = (data) => {
|
|
1004
|
+
const activeOperation = this._operations.findActiveByConnectionKey(data.connectId);
|
|
1005
|
+
if (activeOperation && this._activeOperationJobs.has(activeOperation.operationId)) {
|
|
1006
|
+
this._pendingOperationDisconnects.add(activeOperation.operationId);
|
|
1007
|
+
} else {
|
|
1008
|
+
this._operations.endByConnectionKey(data.connectId, "disconnect");
|
|
1009
|
+
}
|
|
811
1010
|
this._discoveredDevices.delete(data.connectId);
|
|
812
1011
|
this._sessions.delete(data.connectId);
|
|
813
|
-
this.emitter.emit(
|
|
814
|
-
type:
|
|
1012
|
+
this.emitter.emit(import_hwk_adapter_core4.DEVICE.DISCONNECT, {
|
|
1013
|
+
type: import_hwk_adapter_core4.DEVICE.DISCONNECT,
|
|
815
1014
|
payload: { connectId: data.connectId }
|
|
816
1015
|
});
|
|
817
1016
|
};
|
|
818
1017
|
// Forward connector `ui-event` to the public hw.emitter so consumers only
|
|
819
|
-
// need to subscribe in one place.
|
|
820
|
-
//
|
|
821
|
-
// exists (race during teardown) we drop. All other variants pass through
|
|
822
|
-
// unchanged.
|
|
1018
|
+
// need to subscribe in one place. The AppInstallProgress variant re-keys
|
|
1019
|
+
// sessionId to connectId via `_sessions`, and drops if no mapping exists.
|
|
823
1020
|
this.uiEventForwarder = (event) => {
|
|
824
|
-
if (event.type ===
|
|
1021
|
+
if (event.type === import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress) {
|
|
825
1022
|
let connectId;
|
|
826
1023
|
for (const [cid, sid] of this._sessions) {
|
|
827
1024
|
if (sid === event.payload.sessionId) {
|
|
@@ -848,7 +1045,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
848
1045
|
}
|
|
849
1046
|
this._installProgressLastEmittedValue = progress;
|
|
850
1047
|
this.emitter.emit("ui-event", {
|
|
851
|
-
type:
|
|
1048
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress,
|
|
852
1049
|
payload: {
|
|
853
1050
|
connectId,
|
|
854
1051
|
appName,
|
|
@@ -861,14 +1058,33 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
861
1058
|
};
|
|
862
1059
|
this.connector = connector;
|
|
863
1060
|
this._defaultAutoInstallApp = options?.autoInstallApp ?? false;
|
|
864
|
-
this._jobQueue = new
|
|
1061
|
+
this._jobQueue = new import_hwk_adapter_core4.DeviceJobQueue();
|
|
865
1062
|
this.registerEventListeners();
|
|
866
1063
|
}
|
|
1064
|
+
_discardPendingBinding(owner, status = "cancelled") {
|
|
1065
|
+
const pending = owner?.pendingBinding;
|
|
1066
|
+
if (!owner || !pending) return;
|
|
1067
|
+
owner.pendingBinding = void 0;
|
|
1068
|
+
if (pending.requestId === this._bindingSelectionRequestId) this._finishBleBinding(status);
|
|
1069
|
+
}
|
|
1070
|
+
_finishBleBinding(status) {
|
|
1071
|
+
const selectionRequestId = this._bindingSelectionRequestId;
|
|
1072
|
+
this._bindingSelectionRequestId = void 0;
|
|
1073
|
+
if (selectionRequestId) (0, import_hwk_adapter_core4.emitDeviceBindingStatus)(this.emitter, selectionRequestId, status);
|
|
1074
|
+
}
|
|
1075
|
+
_isBleConnection() {
|
|
1076
|
+
return isLedgerBleConnectionType(this._activeConnectionType ?? this.connector.connectionType);
|
|
1077
|
+
}
|
|
867
1078
|
// Transport
|
|
868
1079
|
get activeTransport() {
|
|
869
|
-
return
|
|
1080
|
+
return this._isBleConnection() ? "ble" : "hid";
|
|
870
1081
|
}
|
|
871
1082
|
getAvailableTransports() {
|
|
1083
|
+
if (this.connector.availableTransports) {
|
|
1084
|
+
return this.connector.availableTransports.map(
|
|
1085
|
+
(transport) => transport === "ble" ? "ble" : "hid"
|
|
1086
|
+
);
|
|
1087
|
+
}
|
|
872
1088
|
return this.activeTransport ? [this.activeTransport] : [];
|
|
873
1089
|
}
|
|
874
1090
|
// Connector is bound at construction; switching requires a new adapter.
|
|
@@ -885,21 +1101,42 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
885
1101
|
* The next operation will re-discover and re-connect automatically.
|
|
886
1102
|
*/
|
|
887
1103
|
resetState() {
|
|
1104
|
+
void this._resetStateAndDisconnectSessions();
|
|
1105
|
+
}
|
|
1106
|
+
_resetStateAndDisconnectSessions() {
|
|
1107
|
+
if (this._resetPromise) return this._resetPromise;
|
|
1108
|
+
const sessionIds = new Set(this._sessions.values());
|
|
1109
|
+
this._stateGeneration += 1;
|
|
1110
|
+
this._finishBleBinding("cancelled");
|
|
1111
|
+
this._operations.endAll("runtime-reset");
|
|
1112
|
+
this._doConnectAbortController?.abort();
|
|
888
1113
|
this._discoveredDevices.clear();
|
|
889
1114
|
this._sessions.clear();
|
|
1115
|
+
this._sessionTransports.clear();
|
|
1116
|
+
this._pendingOperationBindings.clear();
|
|
1117
|
+
this._pendingPickBindings.clear();
|
|
1118
|
+
this._selectedBleReconnectTargets.clear();
|
|
890
1119
|
this._connectingPromise = null;
|
|
1120
|
+
this._doConnectAbortController = null;
|
|
891
1121
|
this._uiRegistry.reset();
|
|
892
1122
|
this._jobQueue.clear();
|
|
893
1123
|
this._btcHighIndexConfirmedThisSession = false;
|
|
1124
|
+
const resetPromise = this._runConnectorTeardown(async () => {
|
|
1125
|
+
for (const sessionId of sessionIds) {
|
|
1126
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
1127
|
+
}
|
|
1128
|
+
});
|
|
1129
|
+
this._resetPromise = resetPromise;
|
|
1130
|
+
return resetPromise.finally(() => {
|
|
1131
|
+
if (this._resetPromise === resetPromise) {
|
|
1132
|
+
this._resetPromise = null;
|
|
1133
|
+
}
|
|
1134
|
+
});
|
|
894
1135
|
}
|
|
895
1136
|
async dispose() {
|
|
896
|
-
this.
|
|
897
|
-
this._jobQueue.clear();
|
|
1137
|
+
await this._resetStateAndDisconnectSessions();
|
|
898
1138
|
this.unregisterEventListeners();
|
|
899
1139
|
this.connector.reset();
|
|
900
|
-
this._discoveredDevices.clear();
|
|
901
|
-
this._sessions.clear();
|
|
902
|
-
this._btcHighIndexConfirmedThisSession = false;
|
|
903
1140
|
this.emitter.removeAllListeners();
|
|
904
1141
|
}
|
|
905
1142
|
uiResponse(response) {
|
|
@@ -909,17 +1146,32 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
909
1146
|
// Device management
|
|
910
1147
|
// ---------------------------------------------------------------------------
|
|
911
1148
|
async searchDevices(options) {
|
|
1149
|
+
return this._searchDevices(options);
|
|
1150
|
+
}
|
|
1151
|
+
async _searchDevices(options, signal) {
|
|
912
1152
|
debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
|
|
913
1153
|
try {
|
|
914
1154
|
if (options?.resetSession) {
|
|
915
|
-
this.
|
|
916
|
-
|
|
917
|
-
this.
|
|
918
|
-
|
|
919
|
-
|
|
1155
|
+
await this._resetStateAndDisconnectSessions();
|
|
1156
|
+
} else {
|
|
1157
|
+
await this._connectorTeardownTail;
|
|
1158
|
+
}
|
|
1159
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
1160
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1161
|
+
const stateGeneration = this._stateGeneration;
|
|
1162
|
+
const devices = await this.connector.searchDevices(
|
|
1163
|
+
options?.transportType ? {
|
|
1164
|
+
transportType: options.transportType,
|
|
1165
|
+
waitForAll: options.waitForAllTransports
|
|
1166
|
+
} : void 0
|
|
1167
|
+
);
|
|
1168
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1169
|
+
if (stateGeneration !== this._stateGeneration) {
|
|
1170
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1171
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1172
|
+
message: "Ledger discovery was reset"
|
|
1173
|
+
});
|
|
920
1174
|
}
|
|
921
|
-
await this._ensureDevicePermission();
|
|
922
|
-
const devices = await this.connector.searchDevices();
|
|
923
1175
|
this._discoveredDevices.clear();
|
|
924
1176
|
for (const d of devices) {
|
|
925
1177
|
if (d.connectId) {
|
|
@@ -927,7 +1179,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
927
1179
|
}
|
|
928
1180
|
}
|
|
929
1181
|
if (this._discoveredDevices.size === 0) {
|
|
930
|
-
await this._ensureDevicePermission();
|
|
1182
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
931
1183
|
}
|
|
932
1184
|
const result = Array.from(this._discoveredDevices.values());
|
|
933
1185
|
debugLog("[LedgerAdapter][RES]", {
|
|
@@ -946,41 +1198,263 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
946
1198
|
throw err;
|
|
947
1199
|
}
|
|
948
1200
|
}
|
|
1201
|
+
async searchDeviceTargets(options) {
|
|
1202
|
+
const devices = await this.searchDevices(options);
|
|
1203
|
+
return devices.map((device) => (0, import_hwk_adapter_core4.toPhysicalDeviceSearchTarget)("ledger", device));
|
|
1204
|
+
}
|
|
949
1205
|
// USB single-session invariant: evict all sessions, best-effort (see connectDevice).
|
|
950
|
-
async _evictAllSessions() {
|
|
1206
|
+
async _evictAllSessions(preserveOperationId) {
|
|
1207
|
+
this._operations.endAll("explicit", preserveOperationId);
|
|
951
1208
|
if (this._sessions.size === 0) return;
|
|
952
1209
|
const stale = [...this._sessions.values()];
|
|
953
1210
|
this._sessions.clear();
|
|
954
|
-
for (const sid of stale)
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
1211
|
+
for (const sid of stale) this._sessionTransports.delete(sid);
|
|
1212
|
+
await this._runConnectorTeardown(async () => {
|
|
1213
|
+
for (const sid of stale) {
|
|
1214
|
+
try {
|
|
1215
|
+
await this.connector.disconnect(sid);
|
|
1216
|
+
} catch {
|
|
1217
|
+
}
|
|
958
1218
|
}
|
|
959
|
-
}
|
|
1219
|
+
});
|
|
960
1220
|
}
|
|
961
1221
|
static _createDeviceBusyError(method) {
|
|
962
1222
|
return Object.assign(new Error(`Ledger device is busy while calling ${method}`), {
|
|
963
|
-
code:
|
|
1223
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceBusy
|
|
1224
|
+
});
|
|
1225
|
+
}
|
|
1226
|
+
async connectDevice(searchTargetId) {
|
|
1227
|
+
try {
|
|
1228
|
+
return await this._jobQueue.enqueue(
|
|
1229
|
+
searchTargetId || "__ledger_connect__",
|
|
1230
|
+
async (signal) => {
|
|
1231
|
+
const connected = await this._connectTarget(searchTargetId, void 0, signal);
|
|
1232
|
+
if (!connected.success) return connected;
|
|
1233
|
+
return this._createOperation(searchTargetId, connected.payload);
|
|
1234
|
+
},
|
|
1235
|
+
{
|
|
1236
|
+
label: "connectDevice",
|
|
1237
|
+
rejectIfBusy: true,
|
|
1238
|
+
busyError: _LedgerAdapter._createDeviceBusyError("connectDevice")
|
|
1239
|
+
}
|
|
1240
|
+
);
|
|
1241
|
+
} catch (error) {
|
|
1242
|
+
return this.errorToFailure(error);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
/** Binds the picked BLE device; with a recorded wallet identity it must match first. */
|
|
1246
|
+
async bindBleDevice(params) {
|
|
1247
|
+
const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
|
|
1248
|
+
try {
|
|
1249
|
+
return await this._jobQueue.enqueue(
|
|
1250
|
+
"__ledger_bind_ble__",
|
|
1251
|
+
async (signal) => {
|
|
1252
|
+
if (!this.getAvailableTransports().includes("ble")) {
|
|
1253
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1254
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.TransportNotAvailable,
|
|
1255
|
+
message: "Ledger Bluetooth transport is not available"
|
|
1256
|
+
});
|
|
1257
|
+
}
|
|
1258
|
+
this._activeConnectionType = "ble";
|
|
1259
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
1260
|
+
const attempt = {
|
|
1261
|
+
extra: params.extra,
|
|
1262
|
+
bindingReason: "manual-rebind",
|
|
1263
|
+
deferBindingSave: Boolean(identity)
|
|
1264
|
+
};
|
|
1265
|
+
try {
|
|
1266
|
+
const connectId = await this._connectFirstOrSelect(
|
|
1267
|
+
[],
|
|
1268
|
+
void 0,
|
|
1269
|
+
true,
|
|
1270
|
+
void 0,
|
|
1271
|
+
attempt,
|
|
1272
|
+
signal
|
|
1273
|
+
);
|
|
1274
|
+
const pending = attempt.pendingBinding;
|
|
1275
|
+
if (identity && pending) {
|
|
1276
|
+
attempt.pendingBinding = void 0;
|
|
1277
|
+
const sessionId = this._sessions.get(connectId);
|
|
1278
|
+
if (!sessionId) {
|
|
1279
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1280
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
1281
|
+
message: "Selected Ledger connection ended"
|
|
1282
|
+
});
|
|
1283
|
+
}
|
|
1284
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
1285
|
+
identity.chain,
|
|
1286
|
+
(method, callParams) => this._runConnectorCall(
|
|
1287
|
+
connectId,
|
|
1288
|
+
method,
|
|
1289
|
+
callParams,
|
|
1290
|
+
signal,
|
|
1291
|
+
void 0,
|
|
1292
|
+
void 0,
|
|
1293
|
+
{ autoInstallApp: true },
|
|
1294
|
+
{ connection: { connectId, sessionId } }
|
|
1295
|
+
)
|
|
1296
|
+
);
|
|
1297
|
+
if (fingerprint !== identity.value) {
|
|
1298
|
+
await this._dropSession(connectId, signal);
|
|
1299
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1300
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
1301
|
+
message: formatDeviceMismatchError(identity.value, fingerprint)
|
|
1302
|
+
});
|
|
1303
|
+
}
|
|
1304
|
+
await this._saveSelectedBleBinding(
|
|
1305
|
+
connectId,
|
|
1306
|
+
pending.requestId,
|
|
1307
|
+
attempt,
|
|
1308
|
+
void 0,
|
|
1309
|
+
signal,
|
|
1310
|
+
identity
|
|
1311
|
+
);
|
|
1312
|
+
}
|
|
1313
|
+
if (!attempt.bindingSaved) {
|
|
1314
|
+
await this._dropSession(connectId, signal);
|
|
1315
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1316
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UnknownError,
|
|
1317
|
+
message: "Bluetooth binding could not be saved",
|
|
1318
|
+
origin: "host"
|
|
1319
|
+
});
|
|
1320
|
+
}
|
|
1321
|
+
return (0, import_hwk_adapter_core4.success)(connectId);
|
|
1322
|
+
} catch (error) {
|
|
1323
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
1324
|
+
throw error;
|
|
1325
|
+
}
|
|
1326
|
+
},
|
|
1327
|
+
{
|
|
1328
|
+
label: "bindBleDevice",
|
|
1329
|
+
rejectIfBusy: true,
|
|
1330
|
+
busyError: _LedgerAdapter._createDeviceBusyError("bindBleDevice")
|
|
1331
|
+
}
|
|
1332
|
+
);
|
|
1333
|
+
} catch (error) {
|
|
1334
|
+
return this.errorToFailure(error);
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
async acquireOperation(connectId, context) {
|
|
1338
|
+
try {
|
|
1339
|
+
return await this._jobQueue.enqueue(
|
|
1340
|
+
connectId || "__ledger_acquire__",
|
|
1341
|
+
async (signal) => {
|
|
1342
|
+
const transport = this._isBleConnection() ? "ble" : "usb";
|
|
1343
|
+
const hint = context.knownConnections?.find(
|
|
1344
|
+
(connection) => connection.transport === transport
|
|
1345
|
+
);
|
|
1346
|
+
const target = hint && hint.transport !== "qr" ? hint.connectId : connectId;
|
|
1347
|
+
await this._ensureDevicePermission(target, void 0, signal);
|
|
1348
|
+
const attempt = {
|
|
1349
|
+
...context,
|
|
1350
|
+
extra: context.extra ? { ...context.extra } : void 0,
|
|
1351
|
+
// The operation's calls decide whether the pick is the right wallet.
|
|
1352
|
+
deferBindingSave: true
|
|
1353
|
+
};
|
|
1354
|
+
try {
|
|
1355
|
+
const resolvedConnectId = await this.ensureConnected(
|
|
1356
|
+
target,
|
|
1357
|
+
signal,
|
|
1358
|
+
true,
|
|
1359
|
+
void 0,
|
|
1360
|
+
attempt
|
|
1361
|
+
);
|
|
1362
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1363
|
+
const result = this._createOperation(connectId, resolvedConnectId);
|
|
1364
|
+
if (result.success && attempt.pendingBinding) {
|
|
1365
|
+
this._pendingOperationBindings.set(result.payload, attempt);
|
|
1366
|
+
}
|
|
1367
|
+
return result;
|
|
1368
|
+
} catch (error) {
|
|
1369
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
1370
|
+
throw error;
|
|
1371
|
+
}
|
|
1372
|
+
},
|
|
1373
|
+
{
|
|
1374
|
+
label: "acquireOperation",
|
|
1375
|
+
rejectIfBusy: true,
|
|
1376
|
+
busyError: _LedgerAdapter._createDeviceBusyError("acquireOperation")
|
|
1377
|
+
}
|
|
1378
|
+
);
|
|
1379
|
+
} catch (error) {
|
|
1380
|
+
return this.errorToFailure(error);
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
_createOperation(searchTargetId, resolvedConnectId) {
|
|
1384
|
+
this._operations.endByConnectionKey(resolvedConnectId, "explicit");
|
|
1385
|
+
const sessionId = this._sessions.get(resolvedConnectId);
|
|
1386
|
+
if (sessionId) this._operations.endByConnectionKey(sessionId, "explicit");
|
|
1387
|
+
const connectionType = sessionId && this._sessionTransports.get(sessionId) || (this._isBleConnection() ? "ble" : "usb");
|
|
1388
|
+
const device = this._discoveredDevices.get(resolvedConnectId) ?? {
|
|
1389
|
+
vendor: "ledger",
|
|
1390
|
+
model: "unknown",
|
|
1391
|
+
firmwareVersion: "",
|
|
1392
|
+
deviceId: "",
|
|
1393
|
+
connectId: resolvedConnectId,
|
|
1394
|
+
connectionType
|
|
1395
|
+
};
|
|
1396
|
+
const operation = this._operations.create({
|
|
1397
|
+
searchTargetId,
|
|
1398
|
+
connectId: resolvedConnectId,
|
|
1399
|
+
device,
|
|
1400
|
+
connectionType,
|
|
1401
|
+
connectionKeys: [this._sessions.get(resolvedConnectId) ?? ""]
|
|
964
1402
|
});
|
|
1403
|
+
return (0, import_hwk_adapter_core4.success)(operation.operationId);
|
|
965
1404
|
}
|
|
966
|
-
async
|
|
1405
|
+
async _connectTarget(connectId, preserveOperationId, signal) {
|
|
967
1406
|
debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
|
|
968
1407
|
try {
|
|
969
|
-
|
|
1408
|
+
this._assertConnectorReady("connectDevice");
|
|
1409
|
+
const discoveredType = this._discoveredDevices.get(connectId)?.connectionType;
|
|
1410
|
+
if (discoveredType === "usb" || discoveredType === "ble") {
|
|
1411
|
+
this._activeConnectionType = discoveredType;
|
|
1412
|
+
}
|
|
1413
|
+
if (this._isBleConnection() && !connectId) {
|
|
970
1414
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
971
|
-
code:
|
|
1415
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
972
1416
|
});
|
|
973
1417
|
}
|
|
974
|
-
|
|
975
|
-
|
|
1418
|
+
await this._ensureDevicePermission(connectId, void 0, signal);
|
|
1419
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1420
|
+
const isMultiTransport = (this.connector.availableTransports?.length ?? 0) > 1;
|
|
1421
|
+
if (!isMultiTransport && this._isBleConnection()) {
|
|
1422
|
+
const previousSessionId = this._sessions.get(connectId);
|
|
1423
|
+
this._operations.endByConnectionKey(connectId, "explicit", preserveOperationId);
|
|
1424
|
+
if (previousSessionId) {
|
|
1425
|
+
this._operations.endByConnectionKey(previousSessionId, "explicit", preserveOperationId);
|
|
1426
|
+
this._sessions.delete(connectId);
|
|
1427
|
+
await this.connector.disconnect(previousSessionId).catch(() => void 0);
|
|
1428
|
+
}
|
|
1429
|
+
} else {
|
|
1430
|
+
await this._evictAllSessions(preserveOperationId);
|
|
1431
|
+
}
|
|
1432
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1433
|
+
const stateGeneration = this._stateGeneration;
|
|
1434
|
+
const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
|
|
1435
|
+
let session;
|
|
1436
|
+
this._connectingConnectId = connectId;
|
|
1437
|
+
try {
|
|
1438
|
+
session = this.connector.availableTransports?.length ? await this.connector.connect(connectId, {
|
|
1439
|
+
transportType: this._activeConnectionType ?? "usb"
|
|
1440
|
+
}) : await this.connector.connect(connectId);
|
|
1441
|
+
if (signal?.aborted || stateGeneration !== this._stateGeneration) {
|
|
1442
|
+
await this.connector.disconnect(session.sessionId).catch(() => void 0);
|
|
1443
|
+
throw Object.assign(new Error("Ledger connection aborted"), {
|
|
1444
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1445
|
+
});
|
|
1446
|
+
}
|
|
1447
|
+
} finally {
|
|
1448
|
+
if (this._connectingConnectId === connectId) this._connectingConnectId = void 0;
|
|
1449
|
+
releaseOperation();
|
|
976
1450
|
}
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
this.
|
|
1451
|
+
const resolvedConnectId = session.deviceInfo?.connectId || connectId;
|
|
1452
|
+
this._sessions.set(resolvedConnectId, session.sessionId);
|
|
1453
|
+
this._sessionTransports.set(session.sessionId, this._isBleConnection() ? "ble" : "usb");
|
|
980
1454
|
if (session.deviceInfo) {
|
|
981
|
-
this._discoveredDevices.set(
|
|
1455
|
+
this._discoveredDevices.set(resolvedConnectId, session.deviceInfo);
|
|
982
1456
|
}
|
|
983
|
-
const result = (0,
|
|
1457
|
+
const result = (0, import_hwk_adapter_core4.success)(resolvedConnectId);
|
|
984
1458
|
debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
|
|
985
1459
|
return result;
|
|
986
1460
|
} catch (err) {
|
|
@@ -993,30 +1467,84 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
993
1467
|
return failureResult;
|
|
994
1468
|
}
|
|
995
1469
|
}
|
|
996
|
-
async
|
|
1470
|
+
async releaseOperation(operationId) {
|
|
1471
|
+
const operation = this._operations.findActive(operationId);
|
|
1472
|
+
if (operation) this._cancelOperationWork(operation);
|
|
1473
|
+
const endedOperation = this._operations.release(operationId);
|
|
1474
|
+
if (!endedOperation || this._bareCallMayUseConnection(endedOperation)) return;
|
|
1475
|
+
const { connectId } = endedOperation;
|
|
997
1476
|
debugLog("[LedgerAdapter][REQ]", {
|
|
998
|
-
method: "
|
|
1477
|
+
method: "releaseOperation",
|
|
999
1478
|
connectId,
|
|
1000
1479
|
params: { connectId }
|
|
1001
1480
|
});
|
|
1002
1481
|
try {
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
await this.connector.disconnect(sessionId);
|
|
1006
|
-
this._sessions.delete(connectId);
|
|
1007
|
-
}
|
|
1008
|
-
debugLog("[LedgerAdapter][RES]", { method: "disconnectDevice", success: true });
|
|
1482
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1483
|
+
debugLog("[LedgerAdapter][RES]", { method: "releaseOperation", success: true });
|
|
1009
1484
|
} catch (err) {
|
|
1010
1485
|
const e = err;
|
|
1011
1486
|
debugLog("[LedgerAdapter][RES]", {
|
|
1012
|
-
method: "
|
|
1487
|
+
method: "releaseOperation",
|
|
1013
1488
|
success: false,
|
|
1014
1489
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
1015
1490
|
});
|
|
1016
1491
|
throw err;
|
|
1017
1492
|
}
|
|
1018
1493
|
}
|
|
1019
|
-
|
|
1494
|
+
/**
|
|
1495
|
+
* Ends a released operation's calls and prompts before teardown, which otherwise waits on a call
|
|
1496
|
+
* that waits on a prompt nobody will answer. Device I/O already on the wire still drains.
|
|
1497
|
+
*/
|
|
1498
|
+
_cancelOperationWork(operation) {
|
|
1499
|
+
const { operationId } = operation;
|
|
1500
|
+
const reason = (0, import_hwk_adapter_core4.createHwkError)({
|
|
1501
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.OperationEnded,
|
|
1502
|
+
message: "Ledger operation was released",
|
|
1503
|
+
params: { operationId, reason: "explicit" }
|
|
1504
|
+
});
|
|
1505
|
+
const queueKey = ledgerQueueKey({ operationId });
|
|
1506
|
+
const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
|
|
1507
|
+
this._jobQueue.cancelActiveAndPending(queueKey, reason);
|
|
1508
|
+
if (!ownsRunningCall) return;
|
|
1509
|
+
this._uiRegistry.cancel(void 0, void 0, operationId);
|
|
1510
|
+
void this.connector.cancel(this._sessions.get(operation.connectId) ?? operation.connectId);
|
|
1511
|
+
}
|
|
1512
|
+
/**
|
|
1513
|
+
* A running call by bare connectId (or still resolving its device by identity) may be on this
|
|
1514
|
+
* connection, e.g. waiting for an unlock; its later stages need it, so it stays cached for that
|
|
1515
|
+
* caller like any bare call's session. A lost connection is torn down regardless.
|
|
1516
|
+
*/
|
|
1517
|
+
_bareCallMayUseConnection(operation) {
|
|
1518
|
+
const activeKey = this._jobQueue.getActiveJob()?.deviceId;
|
|
1519
|
+
return activeKey !== void 0 && !(0, import_hwk_adapter_core4.isHardwareOperationId)(activeKey) && (activeKey === operation.connectId || activeKey === LEDGER_DEFAULT_QUEUE_KEY || operation.connectionKeys.includes(activeKey));
|
|
1520
|
+
}
|
|
1521
|
+
async _releaseOperationConnection(operation) {
|
|
1522
|
+
const sessionIds = /* @__PURE__ */ new Set();
|
|
1523
|
+
for (const [connectId, sessionId] of this._sessions) {
|
|
1524
|
+
if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
|
|
1525
|
+
this._sessions.delete(connectId);
|
|
1526
|
+
sessionIds.add(sessionId);
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
for (const sessionId of sessionIds) {
|
|
1530
|
+
await this._runConnectorTeardown(
|
|
1531
|
+
() => this.connector.disconnect(sessionId).catch(() => void 0)
|
|
1532
|
+
);
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
async _releaseLostOperationConnection(operationId) {
|
|
1536
|
+
const endedOperation = this._operations.end(operationId, "disconnect");
|
|
1537
|
+
if (!endedOperation) return;
|
|
1538
|
+
this._discoveredDevices.delete(endedOperation.connectId);
|
|
1539
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1540
|
+
}
|
|
1541
|
+
async getDeviceInfo(connectIdOrOperationId, deviceId) {
|
|
1542
|
+
let connectId;
|
|
1543
|
+
try {
|
|
1544
|
+
connectId = (0, import_hwk_adapter_core4.isHardwareOperationId)(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
|
|
1545
|
+
} catch (error) {
|
|
1546
|
+
return this.errorToFailure(error);
|
|
1547
|
+
}
|
|
1020
1548
|
debugLog("[LedgerAdapter][REQ]", {
|
|
1021
1549
|
method: "getDeviceInfo",
|
|
1022
1550
|
connectId,
|
|
@@ -1026,7 +1554,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1026
1554
|
await this._ensureDevicePermission(connectId, deviceId);
|
|
1027
1555
|
const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
|
|
1028
1556
|
if (cached) {
|
|
1029
|
-
const result = (0,
|
|
1557
|
+
const result = (0, import_hwk_adapter_core4.success)(cached);
|
|
1030
1558
|
debugLog("[LedgerAdapter][RES]", {
|
|
1031
1559
|
method: "getDeviceInfo",
|
|
1032
1560
|
success: true,
|
|
@@ -1034,8 +1562,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1034
1562
|
});
|
|
1035
1563
|
return result;
|
|
1036
1564
|
}
|
|
1037
|
-
const notFound = (0,
|
|
1038
|
-
|
|
1565
|
+
const notFound = (0, import_hwk_adapter_core4.failure)(
|
|
1566
|
+
import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
1039
1567
|
"Device not found in cache. Call searchDevices() or wait for a device-connected event first."
|
|
1040
1568
|
);
|
|
1041
1569
|
debugLog("[LedgerAdapter][RES]", {
|
|
@@ -1051,11 +1579,19 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1051
1579
|
success: false,
|
|
1052
1580
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
1053
1581
|
});
|
|
1054
|
-
|
|
1582
|
+
return this.errorToFailure(err);
|
|
1055
1583
|
}
|
|
1056
1584
|
}
|
|
1057
|
-
|
|
1058
|
-
|
|
1585
|
+
/** A bundle's BLE pick that no item got past the wallet check is not kept. */
|
|
1586
|
+
async _dropUncheckedBundlePick(context, signal) {
|
|
1587
|
+
const { connection } = context;
|
|
1588
|
+
const owner = connection ? this._pendingPickBindings.get(connection.connectId) : void 0;
|
|
1589
|
+
if (!connection || !owner) return;
|
|
1590
|
+
this._pendingPickBindings.delete(connection.connectId);
|
|
1591
|
+
this._discardPendingBinding(owner, signal.aborted ? "cancelled" : "failed");
|
|
1592
|
+
if (this._sessions.get(connection.connectId) === connection.sessionId) {
|
|
1593
|
+
await this._dropSession(connection.connectId, signal);
|
|
1594
|
+
}
|
|
1059
1595
|
}
|
|
1060
1596
|
// ---------------------------------------------------------------------------
|
|
1061
1597
|
// Chain call helper
|
|
@@ -1075,7 +1611,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1075
1611
|
commonParams,
|
|
1076
1612
|
installContext
|
|
1077
1613
|
);
|
|
1078
|
-
return (0,
|
|
1614
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1079
1615
|
} catch (err) {
|
|
1080
1616
|
return this.errorToFailure(err);
|
|
1081
1617
|
}
|
|
@@ -1091,13 +1627,25 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1091
1627
|
if (params && typeof params === "object") {
|
|
1092
1628
|
const {
|
|
1093
1629
|
autoInstallApp,
|
|
1630
|
+
operationId,
|
|
1094
1631
|
passphraseState: _passphraseState,
|
|
1095
1632
|
useEmptyPassphrase: _useEmptyPassphrase,
|
|
1633
|
+
knownConnections,
|
|
1634
|
+
extra,
|
|
1635
|
+
allowDeviceSelection,
|
|
1636
|
+
supportedTransports,
|
|
1096
1637
|
...rest
|
|
1097
1638
|
} = params;
|
|
1098
1639
|
return {
|
|
1099
1640
|
commonParams: {
|
|
1100
|
-
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
|
|
1641
|
+
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
|
|
1642
|
+
operationId: typeof operationId === "string" ? operationId : void 0,
|
|
1643
|
+
...(0, import_hwk_adapter_core4.pickConnectionContext)({
|
|
1644
|
+
knownConnections,
|
|
1645
|
+
extra,
|
|
1646
|
+
allowDeviceSelection,
|
|
1647
|
+
supportedTransports
|
|
1648
|
+
})
|
|
1101
1649
|
},
|
|
1102
1650
|
rest
|
|
1103
1651
|
};
|
|
@@ -1273,14 +1821,33 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1273
1821
|
);
|
|
1274
1822
|
}
|
|
1275
1823
|
// ---------------------------------------------------------------------------
|
|
1276
|
-
//
|
|
1277
|
-
//
|
|
1278
|
-
|
|
1824
|
+
// Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
|
|
1825
|
+
// ---------------------------------------------------------------------------
|
|
1826
|
+
zcashGetFullViewingKey(connectId, deviceId, params) {
|
|
1827
|
+
return this.callChainWithMergedParams(
|
|
1828
|
+
connectId,
|
|
1829
|
+
deviceId,
|
|
1830
|
+
"zcash",
|
|
1831
|
+
"zcashGetFullViewingKey",
|
|
1832
|
+
params
|
|
1833
|
+
);
|
|
1834
|
+
}
|
|
1835
|
+
zcashGetShieldedAddress(connectId, deviceId, params) {
|
|
1836
|
+
return this.callChainWithMergedParams(
|
|
1837
|
+
connectId,
|
|
1838
|
+
deviceId,
|
|
1839
|
+
"zcash",
|
|
1840
|
+
"zcashGetShieldedAddress",
|
|
1841
|
+
params
|
|
1842
|
+
);
|
|
1843
|
+
}
|
|
1844
|
+
// ---------------------------------------------------------------------------
|
|
1845
|
+
// App management: OS-level app install/list, no fingerprint or chain dispatch.
|
|
1279
1846
|
// ---------------------------------------------------------------------------
|
|
1280
1847
|
async installApp(connectId, appName) {
|
|
1281
1848
|
try {
|
|
1282
1849
|
await this.connectorCall(connectId, "installApp", { appName });
|
|
1283
|
-
return (0,
|
|
1850
|
+
return (0, import_hwk_adapter_core4.success)(void 0);
|
|
1284
1851
|
} catch (err) {
|
|
1285
1852
|
return this.errorToFailure(err);
|
|
1286
1853
|
}
|
|
@@ -1288,7 +1855,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1288
1855
|
async listInstalledApps(connectId) {
|
|
1289
1856
|
try {
|
|
1290
1857
|
const result = await this.connectorCall(connectId, "listInstalledApps", {});
|
|
1291
|
-
return (0,
|
|
1858
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1292
1859
|
} catch (err) {
|
|
1293
1860
|
return this.errorToFailure(err);
|
|
1294
1861
|
}
|
|
@@ -1297,7 +1864,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1297
1864
|
async listInstalledNames(connectId) {
|
|
1298
1865
|
try {
|
|
1299
1866
|
const result = await this.connectorCall(connectId, "listInstalledNames", {});
|
|
1300
|
-
return (0,
|
|
1867
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1301
1868
|
} catch (err) {
|
|
1302
1869
|
return this.errorToFailure(err);
|
|
1303
1870
|
}
|
|
@@ -1305,7 +1872,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1305
1872
|
async listAvailableApps(connectId) {
|
|
1306
1873
|
try {
|
|
1307
1874
|
const result = await this.connectorCall(connectId, "listAvailableApps", {});
|
|
1308
|
-
return (0,
|
|
1875
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1309
1876
|
} catch (err) {
|
|
1310
1877
|
return this.errorToFailure(err);
|
|
1311
1878
|
}
|
|
@@ -1313,7 +1880,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1313
1880
|
async getLedgerFirmwareVersion(connectId) {
|
|
1314
1881
|
try {
|
|
1315
1882
|
const result = await this.connectorCall(connectId, "getFirmwareVersion", {});
|
|
1316
|
-
return (0,
|
|
1883
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1317
1884
|
} catch (err) {
|
|
1318
1885
|
return this.errorToFailure(err);
|
|
1319
1886
|
}
|
|
@@ -1321,7 +1888,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1321
1888
|
async getLedgerDeviceInfo(connectId) {
|
|
1322
1889
|
try {
|
|
1323
1890
|
const result = await this.connectorCall(connectId, "getDeviceInfo", {});
|
|
1324
|
-
return (0,
|
|
1891
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1325
1892
|
} catch (err) {
|
|
1326
1893
|
return this.errorToFailure(err);
|
|
1327
1894
|
}
|
|
@@ -1355,28 +1922,28 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1355
1922
|
try {
|
|
1356
1923
|
if (relayUrl) {
|
|
1357
1924
|
if (!this.connector.configure) {
|
|
1358
|
-
return (0,
|
|
1359
|
-
|
|
1925
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
1926
|
+
import_hwk_adapter_core4.HardwareErrorCode.MethodNotSupported,
|
|
1360
1927
|
"This Ledger connector does not support genuine-check relay configuration"
|
|
1361
1928
|
);
|
|
1362
1929
|
}
|
|
1363
1930
|
await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
|
|
1364
|
-
this.
|
|
1931
|
+
await this._resetStateAndDisconnectSessions();
|
|
1365
1932
|
}
|
|
1366
1933
|
const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
|
|
1367
1934
|
if (!result.isGenuine) {
|
|
1368
|
-
return (0,
|
|
1935
|
+
return (0, import_hwk_adapter_core4.success)({
|
|
1369
1936
|
vendor: "ledger",
|
|
1370
1937
|
verified: false
|
|
1371
1938
|
});
|
|
1372
1939
|
}
|
|
1373
1940
|
if (!result.deviceId) {
|
|
1374
|
-
return (0,
|
|
1375
|
-
|
|
1941
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
1942
|
+
import_hwk_adapter_core4.HardwareErrorCode.UnknownError,
|
|
1376
1943
|
`Genuine check completed (isGenuine=${result.isGenuine}) but no deviceId was captured`
|
|
1377
1944
|
);
|
|
1378
1945
|
}
|
|
1379
|
-
return (0,
|
|
1946
|
+
return (0, import_hwk_adapter_core4.success)({
|
|
1380
1947
|
vendor: "ledger",
|
|
1381
1948
|
verified: result.isGenuine,
|
|
1382
1949
|
deviceId: result.deviceId
|
|
@@ -1387,10 +1954,10 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1387
1954
|
if (relayUrl) {
|
|
1388
1955
|
try {
|
|
1389
1956
|
await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
|
|
1390
|
-
this.
|
|
1957
|
+
await this._resetStateAndDisconnectSessions();
|
|
1391
1958
|
} catch {
|
|
1392
1959
|
this.connector.reset();
|
|
1393
|
-
this.
|
|
1960
|
+
await this._resetStateAndDisconnectSessions();
|
|
1394
1961
|
}
|
|
1395
1962
|
}
|
|
1396
1963
|
}
|
|
@@ -1402,8 +1969,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1402
1969
|
this.emitter.off(event, listener);
|
|
1403
1970
|
}
|
|
1404
1971
|
cancel(connectId) {
|
|
1972
|
+
const namedOperationIsLive = (id) => {
|
|
1973
|
+
try {
|
|
1974
|
+
this._operations.resolve(id);
|
|
1975
|
+
return true;
|
|
1976
|
+
} catch {
|
|
1977
|
+
return false;
|
|
1978
|
+
}
|
|
1979
|
+
};
|
|
1980
|
+
if ((0, import_hwk_adapter_core4.isHardwareOperationId)(connectId) && !namedOperationIsLive(connectId)) {
|
|
1981
|
+
debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
|
|
1982
|
+
connectId
|
|
1983
|
+
});
|
|
1984
|
+
return;
|
|
1985
|
+
}
|
|
1405
1986
|
const userAbortReason = Object.assign(new Error("User aborted operation"), {
|
|
1406
|
-
code:
|
|
1987
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1407
1988
|
_tag: ERROR_TAG.UserAborted
|
|
1408
1989
|
});
|
|
1409
1990
|
this._lastCancelReason = userAbortReason;
|
|
@@ -1412,60 +1993,143 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1412
1993
|
this._lastCancelReason = void 0;
|
|
1413
1994
|
}
|
|
1414
1995
|
}, 2e3);
|
|
1415
|
-
this.
|
|
1416
|
-
|
|
1417
|
-
|
|
1996
|
+
const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
|
|
1997
|
+
let operationId;
|
|
1998
|
+
if ((0, import_hwk_adapter_core4.isHardwareOperationId)(connectId)) {
|
|
1999
|
+
operationId = connectId;
|
|
2000
|
+
} else if (!connectId && (0, import_hwk_adapter_core4.isHardwareOperationId)(activeJobId)) {
|
|
2001
|
+
operationId = activeJobId;
|
|
2002
|
+
}
|
|
2003
|
+
let resolvedConnectId = connectId;
|
|
2004
|
+
if (operationId) {
|
|
2005
|
+
try {
|
|
2006
|
+
resolvedConnectId = this._operations.resolve(operationId).connectId;
|
|
2007
|
+
} catch {
|
|
2008
|
+
resolvedConnectId = void 0;
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
2011
|
+
const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
|
|
2012
|
+
const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
|
|
2013
|
+
if (!connectId) {
|
|
2014
|
+
this._uiRegistry.cancel();
|
|
2015
|
+
} else if (pendingOperationId) {
|
|
2016
|
+
this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
|
|
2017
|
+
}
|
|
2018
|
+
this._finishBleBinding("cancelled");
|
|
2019
|
+
if (!connectId) this._pendingOperationBindings.clear();
|
|
2020
|
+
else if (pendingOperationId) this._pendingOperationBindings.delete(pendingOperationId);
|
|
2021
|
+
const queueKeys = /* @__PURE__ */ new Set();
|
|
2022
|
+
if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
|
|
2023
|
+
if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
|
|
2024
|
+
if (queueKeys.size) {
|
|
2025
|
+
let cancelledAnyJob = false;
|
|
2026
|
+
for (const key of queueKeys) {
|
|
2027
|
+
cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
|
|
2028
|
+
}
|
|
2029
|
+
debugLog("[LedgerAdapter] cancel routed to queue keys", {
|
|
2030
|
+
queueKeys: [...queueKeys],
|
|
2031
|
+
cancelledAnyJob
|
|
2032
|
+
});
|
|
1418
2033
|
} else {
|
|
1419
2034
|
this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
|
|
1420
2035
|
}
|
|
1421
|
-
if (
|
|
1422
|
-
const sessionId = this._sessions.get(
|
|
2036
|
+
if (resolvedConnectId) {
|
|
2037
|
+
const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
|
|
1423
2038
|
void this.connector.cancel(sessionId);
|
|
1424
2039
|
} else {
|
|
1425
2040
|
for (const sid of this._sessions.values()) void this.connector.cancel(sid);
|
|
1426
2041
|
}
|
|
1427
|
-
|
|
2042
|
+
const connectingConnectId = this._connectingConnectId;
|
|
2043
|
+
const targetKeys = new Set(
|
|
2044
|
+
[
|
|
2045
|
+
connectId,
|
|
2046
|
+
resolvedConnectId,
|
|
2047
|
+
...pendingOperationId ? this._operations.find(pendingOperationId)?.connectionKeys ?? [] : []
|
|
2048
|
+
].filter(Boolean)
|
|
2049
|
+
);
|
|
2050
|
+
const ownsPendingConnect = !connectId || activeJobId !== void 0 && queueKeys.has(activeJobId) || connectingConnectId !== void 0 && targetKeys.has(connectingConnectId);
|
|
2051
|
+
if (this._connectingPromise && ownsPendingConnect) {
|
|
1428
2052
|
this._doConnectAbortController?.abort(userAbortReason);
|
|
1429
2053
|
}
|
|
2054
|
+
if (connectingConnectId && ownsPendingConnect) void this.connector.cancel(connectingConnectId);
|
|
1430
2055
|
}
|
|
1431
2056
|
// ---------------------------------------------------------------------------
|
|
1432
2057
|
// Chain fingerprint
|
|
1433
2058
|
// ---------------------------------------------------------------------------
|
|
2059
|
+
/** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
|
|
1434
2060
|
async getChainFingerprint(connectId, deviceId, chain) {
|
|
1435
2061
|
try {
|
|
1436
2062
|
const fingerprint = await this._computeChainFingerprint(
|
|
1437
2063
|
chain,
|
|
1438
2064
|
(method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
|
|
1439
2065
|
);
|
|
1440
|
-
|
|
2066
|
+
if (deviceId) {
|
|
2067
|
+
if (fingerprint !== deviceId) {
|
|
2068
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
2069
|
+
import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
2070
|
+
formatDeviceMismatchError(deviceId, fingerprint)
|
|
2071
|
+
);
|
|
2072
|
+
}
|
|
2073
|
+
}
|
|
2074
|
+
return (0, import_hwk_adapter_core4.success)(fingerprint);
|
|
1441
2075
|
} catch (err) {
|
|
1442
2076
|
debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
|
|
1443
2077
|
return this.errorToFailure(err);
|
|
1444
2078
|
}
|
|
1445
2079
|
}
|
|
1446
|
-
/**
|
|
1447
|
-
|
|
1448
|
-
* Safe to call inside connectorCall without causing queue deadlock.
|
|
1449
|
-
*/
|
|
1450
|
-
async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
|
|
1451
|
-
if (!deviceId) return { success: true };
|
|
2080
|
+
/** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
|
|
2081
|
+
async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
|
|
1452
2082
|
try {
|
|
1453
|
-
const
|
|
1454
|
-
|
|
1455
|
-
|
|
2083
|
+
const outcome = await (0, import_hwk_adapter_core4.requestSaveDeviceBinding)(
|
|
2084
|
+
this.emitter,
|
|
2085
|
+
this._uiRegistry,
|
|
2086
|
+
{
|
|
2087
|
+
selectionRequestId,
|
|
2088
|
+
connection: { transport: "ble", connectId },
|
|
2089
|
+
...identity ? { identity } : {},
|
|
2090
|
+
extra: context?.extra,
|
|
2091
|
+
operationId
|
|
2092
|
+
},
|
|
2093
|
+
signal
|
|
1456
2094
|
);
|
|
1457
|
-
if (
|
|
1458
|
-
|
|
2095
|
+
if (context) context.bindingSaved = outcome.saved;
|
|
2096
|
+
if (!outcome.saved) {
|
|
2097
|
+
debugLog("[LedgerAdapter] BLE binding not persisted by host", {
|
|
2098
|
+
connectId,
|
|
2099
|
+
reason: outcome.reason
|
|
2100
|
+
});
|
|
1459
2101
|
}
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
2102
|
+
} catch (error) {
|
|
2103
|
+
await this._dropSession(connectId, signal);
|
|
2104
|
+
throw error;
|
|
2105
|
+
} finally {
|
|
2106
|
+
if (this._bindingSelectionRequestId === selectionRequestId) {
|
|
2107
|
+
this._bindingSelectionRequestId = void 0;
|
|
1465
2108
|
}
|
|
1466
|
-
throw err;
|
|
1467
2109
|
}
|
|
1468
2110
|
}
|
|
2111
|
+
async _dropSession(connectId, signal) {
|
|
2112
|
+
const sessionId = this._sessions.get(connectId);
|
|
2113
|
+
this._sessions.delete(connectId);
|
|
2114
|
+
if (!sessionId) return;
|
|
2115
|
+
this._sessionTransports.delete(sessionId);
|
|
2116
|
+
const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
|
|
2117
|
+
() => void 0
|
|
2118
|
+
);
|
|
2119
|
+
if (!signal.aborted) await teardown;
|
|
2120
|
+
}
|
|
2121
|
+
/** Verify on the acquired session without re-entering the job queue. */
|
|
2122
|
+
async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
|
|
2123
|
+
if (!deviceId) return { success: true };
|
|
2124
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
2125
|
+
chain,
|
|
2126
|
+
(method, params) => this._callConnector(sessionId, method, params)
|
|
2127
|
+
);
|
|
2128
|
+
if (fingerprint === deviceId) {
|
|
2129
|
+
return { success: true };
|
|
2130
|
+
}
|
|
2131
|
+
return { success: false, expected: deviceId, actual: fingerprint };
|
|
2132
|
+
}
|
|
1469
2133
|
/**
|
|
1470
2134
|
* Compute the chain fingerprint via a caller-supplied call strategy.
|
|
1471
2135
|
*
|
|
@@ -1485,7 +2149,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1485
2149
|
const result = await callMethod("btcGetMasterFingerprint", {});
|
|
1486
2150
|
return result.masterFingerprint;
|
|
1487
2151
|
}
|
|
1488
|
-
const path =
|
|
2152
|
+
const path = import_hwk_adapter_core4.CHAIN_FINGERPRINT_PATHS[chain];
|
|
1489
2153
|
let address;
|
|
1490
2154
|
if (chain === "evm") {
|
|
1491
2155
|
address = (await callMethod("evmGetAddress", { path, showOnDevice: false })).address.toLowerCase();
|
|
@@ -1493,10 +2157,19 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1493
2157
|
address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
|
|
1494
2158
|
} else if (chain === "tron") {
|
|
1495
2159
|
address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
|
|
2160
|
+
} else if (chain === "zcash") {
|
|
2161
|
+
address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
|
|
1496
2162
|
} else {
|
|
1497
2163
|
throw new Error(`Unsupported chain for fingerprint: ${chain}`);
|
|
1498
2164
|
}
|
|
1499
|
-
return (0,
|
|
2165
|
+
return (0, import_hwk_adapter_core4.deriveDeviceFingerprint)(address);
|
|
2166
|
+
}
|
|
2167
|
+
/**
|
|
2168
|
+
* Operation owning the running job, so a mid-call UI request can name it.
|
|
2169
|
+
* Undefined at cold start when no operation owns the job.
|
|
2170
|
+
*/
|
|
2171
|
+
_activeOperationId() {
|
|
2172
|
+
return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
|
|
1500
2173
|
}
|
|
1501
2174
|
// Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
|
|
1502
2175
|
// The user must press Confirm after unlocking, which triggers a search retry.
|
|
@@ -1507,22 +2180,25 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1507
2180
|
if (signal?.aborted) {
|
|
1508
2181
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1509
2182
|
}
|
|
2183
|
+
const operationId = this._activeOperationId();
|
|
1510
2184
|
const waitPromise = this._uiRegistry.wait(
|
|
1511
|
-
|
|
2185
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
2186
|
+
{ operationId }
|
|
1512
2187
|
);
|
|
1513
|
-
this.emitter.emit(
|
|
1514
|
-
type:
|
|
2188
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT, {
|
|
2189
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
1515
2190
|
payload: {
|
|
1516
2191
|
vendor: "ledger",
|
|
1517
2192
|
reason: "device-not-found",
|
|
1518
|
-
message: "Please connect and unlock your Ledger device"
|
|
2193
|
+
message: "Please connect and unlock your Ledger device",
|
|
2194
|
+
operationId
|
|
1519
2195
|
}
|
|
1520
2196
|
});
|
|
1521
2197
|
let payload;
|
|
1522
2198
|
try {
|
|
1523
2199
|
if (signal) {
|
|
1524
2200
|
const onAbort = () => {
|
|
1525
|
-
this._uiRegistry.cancel(
|
|
2201
|
+
this._uiRegistry.cancel(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT);
|
|
1526
2202
|
};
|
|
1527
2203
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
1528
2204
|
try {
|
|
@@ -1534,20 +2210,20 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1534
2210
|
payload = await waitPromise;
|
|
1535
2211
|
}
|
|
1536
2212
|
} catch (err) {
|
|
1537
|
-
this.emitter.emit(
|
|
1538
|
-
type:
|
|
2213
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2214
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1539
2215
|
payload: {}
|
|
1540
2216
|
});
|
|
1541
2217
|
throw Object.assign(new Error("User cancelled Ledger connection"), {
|
|
1542
2218
|
_tag: ERROR_TAG.UserAborted,
|
|
1543
|
-
code:
|
|
2219
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1544
2220
|
cause: err
|
|
1545
2221
|
});
|
|
1546
2222
|
}
|
|
1547
2223
|
if (!payload?.confirmed) {
|
|
1548
2224
|
throw Object.assign(new Error("User cancelled Ledger connection"), {
|
|
1549
2225
|
_tag: ERROR_TAG.UserAborted,
|
|
1550
|
-
code:
|
|
2226
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1551
2227
|
});
|
|
1552
2228
|
}
|
|
1553
2229
|
await new Promise((resolve) => {
|
|
@@ -1561,7 +2237,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1561
2237
|
* Returns the params to pass through (with `showOnDevice` possibly
|
|
1562
2238
|
* promoted), or `null` if the user declined.
|
|
1563
2239
|
*/
|
|
1564
|
-
async _gateBtcHighIndex(params) {
|
|
2240
|
+
async _gateBtcHighIndex(params, signal) {
|
|
1565
2241
|
const accountIndex = btcAccountIndexFromPath(params.path);
|
|
1566
2242
|
if (params.showOnDevice) return params;
|
|
1567
2243
|
if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
|
|
@@ -1570,50 +2246,74 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1570
2246
|
if (this._btcHighIndexConfirmedThisSession) {
|
|
1571
2247
|
return { ...params, showOnDevice: true };
|
|
1572
2248
|
}
|
|
1573
|
-
const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
|
|
2249
|
+
const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
|
|
1574
2250
|
if (!confirmed) return null;
|
|
1575
2251
|
this._btcHighIndexConfirmedThisSession = true;
|
|
1576
2252
|
return { ...params, showOnDevice: true };
|
|
1577
2253
|
}
|
|
1578
|
-
async _waitForBtcHighIndexConfirm(path, accountIndex) {
|
|
2254
|
+
async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
|
|
2255
|
+
const operationId = this._activeOperationId();
|
|
1579
2256
|
const waitPromise = this._uiRegistry.wait(
|
|
1580
|
-
|
|
2257
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2258
|
+
{ operationId }
|
|
1581
2259
|
);
|
|
1582
|
-
this.emitter.emit(
|
|
1583
|
-
type:
|
|
2260
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
|
|
2261
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
1584
2262
|
payload: {
|
|
1585
2263
|
vendor: "ledger",
|
|
1586
2264
|
path,
|
|
1587
|
-
accountIndex
|
|
2265
|
+
accountIndex,
|
|
2266
|
+
operationId
|
|
1588
2267
|
}
|
|
1589
2268
|
});
|
|
1590
2269
|
try {
|
|
1591
|
-
const payload = await
|
|
2270
|
+
const payload = await this._awaitUiAnswer(
|
|
2271
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2272
|
+
waitPromise,
|
|
2273
|
+
signal
|
|
2274
|
+
);
|
|
1592
2275
|
return !!payload?.confirmed;
|
|
1593
2276
|
} catch (err) {
|
|
1594
|
-
this.emitter.emit(
|
|
1595
|
-
type:
|
|
2277
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2278
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1596
2279
|
payload: {}
|
|
1597
2280
|
});
|
|
1598
2281
|
return false;
|
|
1599
2282
|
}
|
|
1600
2283
|
}
|
|
2284
|
+
/** A cancel of the job ends its open prompt, even when no operation names that prompt. */
|
|
2285
|
+
async _awaitUiAnswer(requestType, waitPromise, signal) {
|
|
2286
|
+
const onAbort = () => this._uiRegistry.cancel(requestType);
|
|
2287
|
+
if (signal.aborted) onAbort();
|
|
2288
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2289
|
+
try {
|
|
2290
|
+
return await waitPromise;
|
|
2291
|
+
} finally {
|
|
2292
|
+
signal.removeEventListener("abort", onAbort);
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
1601
2295
|
// Ask the user whether to install a missing app (autoInstallApp flow).
|
|
1602
2296
|
// Same register-then-emit ordering as the BTC high-index gate.
|
|
1603
|
-
async _waitForInstallAppConfirm(appName) {
|
|
2297
|
+
async _waitForInstallAppConfirm(appName, signal) {
|
|
2298
|
+
const operationId = this._activeOperationId();
|
|
1604
2299
|
const waitPromise = this._uiRegistry.wait(
|
|
1605
|
-
|
|
2300
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2301
|
+
{ operationId }
|
|
1606
2302
|
);
|
|
1607
|
-
this.emitter.emit(
|
|
1608
|
-
type:
|
|
1609
|
-
payload: { vendor: "ledger", appName }
|
|
2303
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP, {
|
|
2304
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2305
|
+
payload: { vendor: "ledger", appName, operationId }
|
|
1610
2306
|
});
|
|
1611
2307
|
try {
|
|
1612
|
-
const payload = await
|
|
2308
|
+
const payload = await this._awaitUiAnswer(
|
|
2309
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2310
|
+
waitPromise,
|
|
2311
|
+
signal
|
|
2312
|
+
);
|
|
1613
2313
|
return !!payload?.confirmed;
|
|
1614
2314
|
} catch (err) {
|
|
1615
|
-
this.emitter.emit(
|
|
1616
|
-
type:
|
|
2315
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2316
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1617
2317
|
payload: {}
|
|
1618
2318
|
});
|
|
1619
2319
|
return false;
|
|
@@ -1622,34 +2322,44 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1622
2322
|
// Layer 1 entry. Caller signal only races the outer awaiter; the shared
|
|
1623
2323
|
// `_doConnect` runs under its own internal controller so caller A's cancel
|
|
1624
2324
|
// doesn't kill caller B's await.
|
|
1625
|
-
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
|
|
2325
|
+
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
1626
2326
|
if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
|
|
1627
|
-
|
|
2327
|
+
this._assertConnectorReady("connectDevice");
|
|
2328
|
+
if (this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
|
|
1628
2329
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1629
|
-
code:
|
|
2330
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
1630
2331
|
});
|
|
1631
2332
|
}
|
|
1632
2333
|
if (connectId && this._sessions.has(connectId)) return connectId;
|
|
1633
2334
|
if (!connectId && this._sessions.size > 0) {
|
|
1634
|
-
if (!
|
|
2335
|
+
if (!this._isBleConnection() && this._sessions.size > 1) {
|
|
1635
2336
|
throw Object.assign(
|
|
1636
2337
|
new Error(
|
|
1637
2338
|
"Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
|
|
1638
2339
|
),
|
|
1639
|
-
{ code:
|
|
2340
|
+
{ code: import_hwk_adapter_core4.HardwareErrorCode.DeviceOneDeviceOnly }
|
|
1640
2341
|
);
|
|
1641
2342
|
}
|
|
1642
2343
|
return this._sessions.keys().next().value;
|
|
1643
2344
|
}
|
|
1644
|
-
if (!this._connectingPromise) {
|
|
1645
|
-
|
|
1646
|
-
|
|
2345
|
+
if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
|
|
2346
|
+
const controller = new AbortController();
|
|
2347
|
+
this._doConnectAbortController = controller;
|
|
2348
|
+
const innerSignal = controller.signal;
|
|
1647
2349
|
this._connectingPromise = (async () => {
|
|
1648
2350
|
try {
|
|
1649
|
-
return await this._doConnect(
|
|
2351
|
+
return await this._doConnect(
|
|
2352
|
+
innerSignal,
|
|
2353
|
+
connectId,
|
|
2354
|
+
allowUsbEphemeralFallback,
|
|
2355
|
+
preserveOperationId,
|
|
2356
|
+
context
|
|
2357
|
+
);
|
|
1650
2358
|
} finally {
|
|
1651
|
-
this.
|
|
1652
|
-
|
|
2359
|
+
if (this._doConnectAbortController === controller) {
|
|
2360
|
+
this._connectingPromise = null;
|
|
2361
|
+
this._doConnectAbortController = null;
|
|
2362
|
+
}
|
|
1653
2363
|
}
|
|
1654
2364
|
})();
|
|
1655
2365
|
}
|
|
@@ -1658,45 +2368,86 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1658
2368
|
// Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
|
|
1659
2369
|
// Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
|
|
1660
2370
|
// throw DeviceNotFound so the user is kicked out of the loop.
|
|
1661
|
-
async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false) {
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
2371
|
+
async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
2372
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2373
|
+
if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
|
|
2374
|
+
this._activeConnectionType = "usb";
|
|
2375
|
+
const usbDevices = context?.supportedTransports && !context.supportedTransports.includes("usb") ? [] : await this._searchDevices({ transportType: "usb" }, internalSignal);
|
|
2376
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2377
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2378
|
+
(connection) => connection.transport === "usb"
|
|
2379
|
+
);
|
|
2380
|
+
const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
|
|
2381
|
+
if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback)) {
|
|
2382
|
+
return this._connectFirstOrSelect(
|
|
2383
|
+
usbDevices,
|
|
2384
|
+
usbTarget,
|
|
2385
|
+
allowUsbEphemeralFallback,
|
|
2386
|
+
preserveOperationId,
|
|
2387
|
+
context,
|
|
2388
|
+
internalSignal
|
|
2389
|
+
);
|
|
2390
|
+
}
|
|
2391
|
+
if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
|
|
2392
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2393
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
2394
|
+
message: "This Ledger model has no Bluetooth transport; connect it over USB"
|
|
2395
|
+
});
|
|
2396
|
+
}
|
|
2397
|
+
this._activeConnectionType = "ble";
|
|
2398
|
+
const knownBle = context?.knownConnections?.find(
|
|
2399
|
+
(connection) => connection.transport === "ble"
|
|
2400
|
+
);
|
|
2401
|
+
if (knownBle?.transport === "ble") {
|
|
2402
|
+
return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
|
|
1676
2403
|
}
|
|
2404
|
+
if (targetConnectId && context?.knownConnections === void 0) {
|
|
2405
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2406
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
2407
|
+
message: "Ledger connection metadata is required before starting Bluetooth binding"
|
|
2408
|
+
});
|
|
2409
|
+
}
|
|
2410
|
+
const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
|
|
2411
|
+
return this._connectFirstOrSelect(
|
|
2412
|
+
bleDevices,
|
|
2413
|
+
void 0,
|
|
2414
|
+
allowUsbEphemeralFallback,
|
|
2415
|
+
preserveOperationId,
|
|
2416
|
+
context,
|
|
2417
|
+
internalSignal
|
|
2418
|
+
);
|
|
2419
|
+
}
|
|
2420
|
+
if (this._isBleConnection() && targetConnectId) {
|
|
2421
|
+
return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
|
|
1677
2422
|
}
|
|
1678
2423
|
let confirms = 0;
|
|
1679
2424
|
while (!internalSignal.aborted) {
|
|
1680
2425
|
this.emitter.emit("ui-event", {
|
|
1681
|
-
type:
|
|
2426
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.Searching,
|
|
1682
2427
|
payload: { sessionId: "" }
|
|
1683
2428
|
});
|
|
1684
|
-
let devices = await this.
|
|
2429
|
+
let devices = await this._searchDevices(void 0, internalSignal);
|
|
2430
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1685
2431
|
if (devices.length === 0) {
|
|
1686
2432
|
for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
|
|
1687
2433
|
await new Promise((resolve) => {
|
|
1688
|
-
setTimeout(resolve,
|
|
2434
|
+
setTimeout(resolve, import_hwk_adapter_core4.DEVICE_CONNECT_RETRY_DELAY_MS);
|
|
1689
2435
|
});
|
|
1690
|
-
|
|
2436
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2437
|
+
devices = await this._searchDevices(void 0, internalSignal);
|
|
2438
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1691
2439
|
if (devices.length > 0) break;
|
|
1692
2440
|
}
|
|
1693
2441
|
}
|
|
1694
|
-
if (devices.length > 0) {
|
|
2442
|
+
if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
|
|
1695
2443
|
try {
|
|
1696
2444
|
return await this._connectFirstOrSelect(
|
|
1697
2445
|
devices,
|
|
1698
2446
|
targetConnectId,
|
|
1699
|
-
allowUsbEphemeralFallback
|
|
2447
|
+
allowUsbEphemeralFallback,
|
|
2448
|
+
preserveOperationId,
|
|
2449
|
+
context,
|
|
2450
|
+
internalSignal
|
|
1700
2451
|
);
|
|
1701
2452
|
} catch (err) {
|
|
1702
2453
|
if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
|
|
@@ -1716,7 +2467,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1716
2467
|
new Error(
|
|
1717
2468
|
"Device not connected after multiple attempts. Please ensure your Ledger is awake, unlocked, and in range, then try again."
|
|
1718
2469
|
),
|
|
1719
|
-
{ code:
|
|
2470
|
+
{ code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound }
|
|
1720
2471
|
);
|
|
1721
2472
|
}
|
|
1722
2473
|
await this._waitForDeviceConnect(internalSignal);
|
|
@@ -1725,45 +2476,147 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1725
2476
|
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1726
2477
|
throw new Error("_doConnect aborted");
|
|
1727
2478
|
}
|
|
1728
|
-
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback
|
|
2479
|
+
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
|
|
2480
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1729
2481
|
if (targetConnectId) {
|
|
1730
2482
|
const target = devices.find(
|
|
1731
2483
|
(d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
|
|
1732
2484
|
);
|
|
1733
2485
|
if (target) {
|
|
1734
|
-
return this._connectDeviceOrThrow(target.connectId);
|
|
2486
|
+
return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
|
|
1735
2487
|
}
|
|
1736
|
-
if (!
|
|
2488
|
+
if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
|
|
1737
2489
|
debugLog(
|
|
1738
2490
|
`[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
|
|
1739
2491
|
);
|
|
1740
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2492
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1741
2493
|
}
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
2494
|
+
if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
|
|
2495
|
+
const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
|
|
2496
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
2497
|
+
});
|
|
2498
|
+
if (this._isBleConnection()) {
|
|
2499
|
+
err._tag = ERROR_TAG.DeviceNotAdvertising;
|
|
2500
|
+
}
|
|
2501
|
+
throw err;
|
|
1747
2502
|
}
|
|
1748
|
-
throw err;
|
|
1749
2503
|
}
|
|
1750
|
-
|
|
2504
|
+
const requiresBleSelection = this._isBleConnection();
|
|
2505
|
+
if (requiresBleSelection && !allowUsbEphemeralFallback) {
|
|
1751
2506
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1752
|
-
code:
|
|
2507
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
2508
|
+
});
|
|
2509
|
+
}
|
|
2510
|
+
if (requiresBleSelection && context?.allowDeviceSelection !== false) {
|
|
2511
|
+
const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
|
|
2512
|
+
if (context) context.bindingSessionId = bindingSessionId;
|
|
2513
|
+
const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb")) && (!context?.supportedTransports || context.supportedTransports.includes("usb"));
|
|
2514
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2515
|
+
(connection) => connection.transport === "usb"
|
|
2516
|
+
);
|
|
2517
|
+
const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : targetConnectId;
|
|
2518
|
+
const { device, requestId } = await (0, import_hwk_adapter_core4.requestBleDeviceSelection)({
|
|
2519
|
+
emitter: this.emitter,
|
|
2520
|
+
registry: this._uiRegistry,
|
|
2521
|
+
signal,
|
|
2522
|
+
allowUsbFallback,
|
|
2523
|
+
scan: async () => {
|
|
2524
|
+
if (allowUsbFallback) {
|
|
2525
|
+
const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
|
|
2526
|
+
const candidate = usbDevices.find(
|
|
2527
|
+
(device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
|
|
2528
|
+
) ?? (usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
|
|
2529
|
+
if (candidate) return [candidate];
|
|
2530
|
+
}
|
|
2531
|
+
return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
|
|
2532
|
+
},
|
|
2533
|
+
request: {
|
|
2534
|
+
devices,
|
|
2535
|
+
bindingSessionId,
|
|
2536
|
+
context: {
|
|
2537
|
+
kind: "bind-connection",
|
|
2538
|
+
transport: "ble",
|
|
2539
|
+
reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
|
|
2540
|
+
},
|
|
2541
|
+
extra: context?.extra,
|
|
2542
|
+
operationId: preserveOperationId
|
|
2543
|
+
}
|
|
1753
2544
|
});
|
|
2545
|
+
if (device.connectionType === "usb") {
|
|
2546
|
+
this._activeConnectionType = "usb";
|
|
2547
|
+
if (context) context.selectedConnection = void 0;
|
|
2548
|
+
this._bindingSelectionRequestId = requestId;
|
|
2549
|
+
this._finishBleBinding("cancelled");
|
|
2550
|
+
return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
|
|
2551
|
+
}
|
|
2552
|
+
this._bindingSelectionRequestId = requestId;
|
|
2553
|
+
const connected = await this._connectDeviceOrThrow(
|
|
2554
|
+
device.connectId,
|
|
2555
|
+
preserveOperationId,
|
|
2556
|
+
signal
|
|
2557
|
+
);
|
|
2558
|
+
if (context) context.selectedConnection = { connectId: connected, requestId };
|
|
2559
|
+
if (context?.deferBindingSave) {
|
|
2560
|
+
context.pendingBinding = { connectId: connected, requestId };
|
|
2561
|
+
} else {
|
|
2562
|
+
await this._saveSelectedBleBinding(
|
|
2563
|
+
connected,
|
|
2564
|
+
requestId,
|
|
2565
|
+
context,
|
|
2566
|
+
preserveOperationId,
|
|
2567
|
+
signal
|
|
2568
|
+
);
|
|
2569
|
+
}
|
|
2570
|
+
return connected;
|
|
1754
2571
|
}
|
|
1755
|
-
if (devices.length > 1) {
|
|
1756
|
-
|
|
2572
|
+
if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
|
|
2573
|
+
if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE)) {
|
|
2574
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2575
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
2576
|
+
message: "Select a Ledger device before continuing"
|
|
2577
|
+
});
|
|
2578
|
+
}
|
|
2579
|
+
const requestId = this._uiRegistry.createRequestId();
|
|
2580
|
+
const operationId = this._activeOperationId();
|
|
2581
|
+
const waitPromise = this._uiRegistry.wait(
|
|
2582
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2583
|
+
{ requestId, operationId }
|
|
2584
|
+
);
|
|
2585
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE, {
|
|
2586
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2587
|
+
payload: {
|
|
2588
|
+
devices,
|
|
2589
|
+
requestId,
|
|
2590
|
+
operationId,
|
|
2591
|
+
context: requiresBleSelection ? {
|
|
2592
|
+
kind: "bind-connection",
|
|
2593
|
+
transport: "ble",
|
|
2594
|
+
reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
|
|
2595
|
+
} : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
|
|
2596
|
+
extra: context?.extra
|
|
2597
|
+
}
|
|
2598
|
+
});
|
|
2599
|
+
const { sdkConnectId } = await this._abortable(signal, waitPromise);
|
|
2600
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
2601
|
+
const selected = devices.find((device) => device.connectId === sdkConnectId);
|
|
2602
|
+
if (!selected) {
|
|
2603
|
+
throw Object.assign(new Error("Selected Ledger is no longer available"), {
|
|
2604
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
2605
|
+
});
|
|
2606
|
+
}
|
|
2607
|
+
if (context && requiresBleSelection)
|
|
2608
|
+
context.selectedConnection = { connectId: selected.connectId, requestId };
|
|
2609
|
+
return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
|
|
1757
2610
|
}
|
|
1758
2611
|
if (devices.length !== 1) {
|
|
1759
2612
|
throw Object.assign(new Error("Ledger device not found."), {
|
|
1760
|
-
code:
|
|
2613
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
1761
2614
|
});
|
|
1762
2615
|
}
|
|
1763
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2616
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1764
2617
|
}
|
|
1765
|
-
async _connectDeviceOrThrow(chosenConnectId) {
|
|
1766
|
-
const result = await this.
|
|
2618
|
+
async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
|
|
2619
|
+
const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
|
|
1767
2620
|
if (!result.success) {
|
|
1768
2621
|
const payload = result.payload;
|
|
1769
2622
|
const rethrow = Object.assign(new Error(payload.error), {
|
|
@@ -1774,16 +2627,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1774
2627
|
}
|
|
1775
2628
|
throw rethrow;
|
|
1776
2629
|
}
|
|
1777
|
-
return
|
|
2630
|
+
return result.payload;
|
|
1778
2631
|
}
|
|
1779
|
-
/**
|
|
1780
|
-
* Call the connector with automatic session resolution and disconnect retry.
|
|
1781
|
-
*
|
|
1782
|
-
* 1. Resolves a valid connectId via ensureConnected()
|
|
1783
|
-
* 2. Looks up sessionId from _sessions
|
|
1784
|
-
* 3. Calls connector.call()
|
|
1785
|
-
* 4. On disconnect error: clears stale session, re-connects, retries once
|
|
1786
|
-
*/
|
|
1787
2632
|
/**
|
|
1788
2633
|
* Unwrap a `ConnectorCallResult` back into the throw-based control flow this
|
|
1789
2634
|
* class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
|
|
@@ -1795,7 +2640,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1795
2640
|
*/
|
|
1796
2641
|
_unwrapConnectorResult(result) {
|
|
1797
2642
|
if (result.success) return result.payload;
|
|
1798
|
-
throw (0,
|
|
2643
|
+
throw (0, import_hwk_adapter_core4.rehydrateConnectorError)(result.error);
|
|
1799
2644
|
}
|
|
1800
2645
|
/**
|
|
1801
2646
|
* `connector.call` + result unwrap, optionally raced against an abort
|
|
@@ -1804,33 +2649,145 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1804
2649
|
* lives in one place.
|
|
1805
2650
|
*/
|
|
1806
2651
|
async _callConnector(sessionId, method, params, signal) {
|
|
1807
|
-
|
|
2652
|
+
this._assertConnectorReady(method);
|
|
2653
|
+
if (signal?.aborted) throw this._abortReason(signal);
|
|
2654
|
+
const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
|
|
2655
|
+
let promise;
|
|
2656
|
+
try {
|
|
2657
|
+
promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
|
|
2658
|
+
} catch (error) {
|
|
2659
|
+
releaseOperation();
|
|
2660
|
+
throw error;
|
|
2661
|
+
}
|
|
1808
2662
|
const result = signal ? await this._abortable(signal, promise) : await promise;
|
|
1809
2663
|
return this._unwrapConnectorResult(result);
|
|
1810
2664
|
}
|
|
2665
|
+
_assertConnectorReady(method) {
|
|
2666
|
+
if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
|
|
2667
|
+
throw _LedgerAdapter._createDeviceBusyError(method);
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
_runConnectorTeardown(task) {
|
|
2671
|
+
const previous = this._connectorTeardownTail;
|
|
2672
|
+
let releaseTail = () => void 0;
|
|
2673
|
+
this._connectorTeardownTail = new Promise((resolve) => {
|
|
2674
|
+
releaseTail = resolve;
|
|
2675
|
+
});
|
|
2676
|
+
this._pendingConnectorTeardowns += 1;
|
|
2677
|
+
return (async () => {
|
|
2678
|
+
try {
|
|
2679
|
+
await previous;
|
|
2680
|
+
await this._waitForConnectorOperationsToDrain();
|
|
2681
|
+
await task();
|
|
2682
|
+
} finally {
|
|
2683
|
+
this._pendingConnectorTeardowns -= 1;
|
|
2684
|
+
releaseTail();
|
|
2685
|
+
}
|
|
2686
|
+
})();
|
|
2687
|
+
}
|
|
2688
|
+
_waitForConnectorOperationsToDrain() {
|
|
2689
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2690
|
+
return Promise.resolve();
|
|
2691
|
+
}
|
|
2692
|
+
return new Promise((resolve) => {
|
|
2693
|
+
this._connectorIdleWaiters.add(resolve);
|
|
2694
|
+
});
|
|
2695
|
+
}
|
|
2696
|
+
_retainConnectorOperation(key) {
|
|
2697
|
+
this._unsettledConnectorOperations.set(
|
|
2698
|
+
key,
|
|
2699
|
+
(this._unsettledConnectorOperations.get(key) ?? 0) + 1
|
|
2700
|
+
);
|
|
2701
|
+
let released = false;
|
|
2702
|
+
return () => {
|
|
2703
|
+
if (released) return;
|
|
2704
|
+
released = true;
|
|
2705
|
+
const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
|
|
2706
|
+
if (remaining > 0) {
|
|
2707
|
+
this._unsettledConnectorOperations.set(key, remaining);
|
|
2708
|
+
} else {
|
|
2709
|
+
this._unsettledConnectorOperations.delete(key);
|
|
2710
|
+
}
|
|
2711
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2712
|
+
for (const resolve of this._connectorIdleWaiters) resolve();
|
|
2713
|
+
this._connectorIdleWaiters.clear();
|
|
2714
|
+
}
|
|
2715
|
+
};
|
|
2716
|
+
}
|
|
1811
2717
|
async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
1812
|
-
|
|
1813
|
-
|
|
2718
|
+
const positionalOperationId = (0, import_hwk_adapter_core4.isHardwareOperationId)(connectId) ? connectId : void 0;
|
|
2719
|
+
if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
|
|
2720
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2721
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.InvalidParams,
|
|
2722
|
+
message: "Conflicting Ledger operation ids",
|
|
2723
|
+
params: {
|
|
2724
|
+
positionalOperationId,
|
|
2725
|
+
commonOperationId: commonParams.operationId
|
|
2726
|
+
}
|
|
2727
|
+
});
|
|
2728
|
+
}
|
|
2729
|
+
const operationId = commonParams?.operationId ?? positionalOperationId;
|
|
2730
|
+
const operation = operationId ? this._operations.resolve(operationId) : void 0;
|
|
2731
|
+
const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
|
|
2732
|
+
const effectiveConnectId = operation?.connectId ?? connectId;
|
|
2733
|
+
debugLog("[LedgerAdapter][REQ]", {
|
|
2734
|
+
method,
|
|
2735
|
+
connectId: effectiveConnectId || "(empty)",
|
|
2736
|
+
params: summarizeForLog(params, { method })
|
|
2737
|
+
});
|
|
2738
|
+
const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
|
|
1814
2739
|
try {
|
|
1815
2740
|
const result = await this._jobQueue.enqueue(
|
|
1816
2741
|
queueKey,
|
|
1817
|
-
async (signal) =>
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
2742
|
+
async (signal) => {
|
|
2743
|
+
if (operationId) this._activeOperationJobs.add(operationId);
|
|
2744
|
+
try {
|
|
2745
|
+
return await this._runConnectorCall(
|
|
2746
|
+
effectiveConnectId,
|
|
2747
|
+
method,
|
|
2748
|
+
params,
|
|
2749
|
+
signal,
|
|
2750
|
+
fingerprint,
|
|
2751
|
+
permissionDeviceId,
|
|
2752
|
+
commonParams,
|
|
2753
|
+
installContext ?? {},
|
|
2754
|
+
operationId
|
|
2755
|
+
);
|
|
2756
|
+
} catch (error) {
|
|
2757
|
+
const status = signal.aborted ? "cancelled" : "failed";
|
|
2758
|
+
const bundleConnectId = installContext?.connection?.connectId;
|
|
2759
|
+
let keptBundlePick = false;
|
|
2760
|
+
for (const [pickedConnectId, owner] of this._pendingPickBindings) {
|
|
2761
|
+
if (pickedConnectId === bundleConnectId) {
|
|
2762
|
+
keptBundlePick = true;
|
|
2763
|
+
} else {
|
|
2764
|
+
this._pendingPickBindings.delete(pickedConnectId);
|
|
2765
|
+
this._discardPendingBinding(owner, status);
|
|
2766
|
+
await this._dropSession(pickedConnectId, signal);
|
|
2767
|
+
}
|
|
2768
|
+
}
|
|
2769
|
+
if (!keptBundlePick) this._finishBleBinding(status);
|
|
2770
|
+
throw error;
|
|
2771
|
+
} finally {
|
|
2772
|
+
if (operationId) {
|
|
2773
|
+
this._activeOperationJobs.delete(operationId);
|
|
2774
|
+
if (this._pendingOperationDisconnects.delete(operationId)) {
|
|
2775
|
+
await this._releaseLostOperationConnection(operationId);
|
|
2776
|
+
}
|
|
2777
|
+
}
|
|
2778
|
+
}
|
|
2779
|
+
},
|
|
1827
2780
|
{
|
|
1828
2781
|
label: method,
|
|
1829
2782
|
rejectIfBusy: true,
|
|
1830
2783
|
busyError: _LedgerAdapter._createDeviceBusyError(method)
|
|
1831
2784
|
}
|
|
1832
2785
|
);
|
|
1833
|
-
debugLog("[LedgerAdapter][RES]", {
|
|
2786
|
+
debugLog("[LedgerAdapter][RES]", {
|
|
2787
|
+
method,
|
|
2788
|
+
success: true,
|
|
2789
|
+
payload: summarizeForLog(result, { method, role: "result" })
|
|
2790
|
+
});
|
|
1834
2791
|
return result;
|
|
1835
2792
|
} catch (err) {
|
|
1836
2793
|
const e = err;
|
|
@@ -1844,15 +2801,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1844
2801
|
}
|
|
1845
2802
|
});
|
|
1846
2803
|
throw err;
|
|
2804
|
+
} finally {
|
|
2805
|
+
releaseOperationRetention?.();
|
|
1847
2806
|
}
|
|
1848
2807
|
}
|
|
2808
|
+
/** Hermes/RN polyfills don't always populate signal.reason; fall back. */
|
|
2809
|
+
_abortReason(signal) {
|
|
2810
|
+
return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
|
|
2811
|
+
}
|
|
1849
2812
|
/**
|
|
1850
2813
|
* Race a promise against an abort signal. On abort, rejects with
|
|
1851
2814
|
* signal.reason → instance _lastCancelReason → generic Error('Aborted').
|
|
1852
2815
|
*/
|
|
1853
2816
|
_abortable(signal, promise) {
|
|
1854
|
-
const getAbortReason = () =>
|
|
2817
|
+
const getAbortReason = () => this._abortReason(signal);
|
|
1855
2818
|
if (signal.aborted) {
|
|
2819
|
+
void promise.catch(() => void 0);
|
|
1856
2820
|
return Promise.reject(getAbortReason());
|
|
1857
2821
|
}
|
|
1858
2822
|
return new Promise((resolve, reject) => {
|
|
@@ -1879,39 +2843,89 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1879
2843
|
}
|
|
1880
2844
|
}
|
|
1881
2845
|
/** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
|
|
1882
|
-
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
2846
|
+
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
|
|
1883
2847
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
2848
|
+
if (!operationId) {
|
|
2849
|
+
await this._ensureDevicePermission(
|
|
2850
|
+
connectId,
|
|
2851
|
+
permissionDeviceId ?? fingerprint?.deviceId,
|
|
2852
|
+
signal
|
|
2853
|
+
);
|
|
2854
|
+
}
|
|
1889
2855
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1890
2856
|
let effectiveParams = params;
|
|
1891
2857
|
if (method === "btcGetPublicKey") {
|
|
1892
|
-
const gatedParams = await this._gateBtcHighIndex(params);
|
|
2858
|
+
const gatedParams = await this._gateBtcHighIndex(params, signal);
|
|
1893
2859
|
if (gatedParams === null) {
|
|
1894
2860
|
throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
|
|
1895
2861
|
_tag: ERROR_TAG.UserAborted,
|
|
1896
|
-
code:
|
|
2862
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1897
2863
|
});
|
|
1898
2864
|
}
|
|
1899
2865
|
effectiveParams = gatedParams;
|
|
1900
2866
|
}
|
|
1901
2867
|
const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
|
|
1902
|
-
|
|
1903
|
-
|
|
2868
|
+
let businessCallStarted = false;
|
|
2869
|
+
const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
|
|
2870
|
+
const knownTransport = this._isBleConnection() ? "ble" : "usb";
|
|
2871
|
+
const hintedConnectId = commonParams?.knownConnections?.find(
|
|
2872
|
+
(connection) => connection.transport === knownTransport
|
|
2873
|
+
);
|
|
2874
|
+
const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
|
|
2875
|
+
const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
|
|
2876
|
+
const checksWallet = Boolean(
|
|
2877
|
+
fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId
|
|
2878
|
+
);
|
|
2879
|
+
const connectionAttempt = {
|
|
2880
|
+
...commonParams,
|
|
2881
|
+
deferBindingSave: checksWallet
|
|
2882
|
+
};
|
|
2883
|
+
const bundleConnection = installContext?.connection;
|
|
2884
|
+
if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
|
|
2885
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2886
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
2887
|
+
message: "Ledger all-network connection ended"
|
|
2888
|
+
});
|
|
2889
|
+
}
|
|
2890
|
+
const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
|
|
2891
|
+
preferredConnectId,
|
|
1904
2892
|
signal,
|
|
1905
|
-
allowUsbEphemeralFallback
|
|
2893
|
+
allowUsbEphemeralFallback,
|
|
2894
|
+
void 0,
|
|
2895
|
+
connectionAttempt
|
|
1906
2896
|
);
|
|
2897
|
+
const walletCheck = installContext?.walletCheck;
|
|
2898
|
+
if (walletCheck && !checksWallet && (walletCheck.verified === false || walletCheck.expected && !walletCheck.verified)) {
|
|
2899
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2900
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
2901
|
+
message: "Ledger wallet is not verified on this connection; refusing to derive an unverifiable address"
|
|
2902
|
+
});
|
|
2903
|
+
}
|
|
1907
2904
|
const sessionId = this._sessions.get(resolvedConnectId);
|
|
2905
|
+
if (sessionId && installContext && !installContext.connection) {
|
|
2906
|
+
installContext.connection = { connectId: resolvedConnectId, sessionId };
|
|
2907
|
+
}
|
|
1908
2908
|
if (!sessionId) {
|
|
2909
|
+
if (operationId) {
|
|
2910
|
+
this._operations.end(operationId, "disconnect");
|
|
2911
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2912
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.OperationEnded,
|
|
2913
|
+
message: "Ledger operation connection is no longer active",
|
|
2914
|
+
params: { operationId, reason: "disconnect" }
|
|
2915
|
+
});
|
|
2916
|
+
}
|
|
1909
2917
|
throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
|
|
1910
2918
|
_tag: ERROR_TAG.DeviceSessionNotFound
|
|
1911
2919
|
});
|
|
1912
2920
|
}
|
|
1913
2921
|
try {
|
|
1914
|
-
|
|
2922
|
+
const isBleSession = this._sessionTransports.get(sessionId) === "ble";
|
|
2923
|
+
if (!operationId && connectionAttempt.pendingBinding) {
|
|
2924
|
+
this._pendingPickBindings.set(resolvedConnectId, connectionAttempt);
|
|
2925
|
+
}
|
|
2926
|
+
const bindingOwner = operationId ? this._pendingOperationBindings.get(operationId) : this._pendingPickBindings.get(resolvedConnectId);
|
|
2927
|
+
const pendingBinding = bindingOwner?.pendingBinding?.connectId === resolvedConnectId ? bindingOwner.pendingBinding : void 0;
|
|
2928
|
+
if (fingerprint && checksWallet) {
|
|
1915
2929
|
const fp = await this._abortable(
|
|
1916
2930
|
signal,
|
|
1917
2931
|
this._verifyDeviceFingerprintWithSession(
|
|
@@ -1921,14 +2935,68 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1921
2935
|
)
|
|
1922
2936
|
);
|
|
1923
2937
|
if (!fp.success) {
|
|
2938
|
+
if (pendingBinding) {
|
|
2939
|
+
this._discardPendingBinding(bindingOwner, "failed");
|
|
2940
|
+
this._pendingPickBindings.delete(resolvedConnectId);
|
|
2941
|
+
}
|
|
2942
|
+
if (operationId) {
|
|
2943
|
+
this._pendingOperationBindings.delete(operationId);
|
|
2944
|
+
this._operations.end(operationId, "explicit");
|
|
2945
|
+
await this._dropSession(resolvedConnectId, signal);
|
|
2946
|
+
}
|
|
1924
2947
|
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
1925
|
-
code:
|
|
2948
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch
|
|
1926
2949
|
});
|
|
1927
2950
|
}
|
|
2951
|
+
if (walletCheck) walletCheck.verified = true;
|
|
2952
|
+
}
|
|
2953
|
+
if (pendingBinding && bindingOwner) {
|
|
2954
|
+
bindingOwner.pendingBinding = void 0;
|
|
2955
|
+
if (operationId) this._pendingOperationBindings.delete(operationId);
|
|
2956
|
+
else this._pendingPickBindings.delete(resolvedConnectId);
|
|
2957
|
+
await this._saveSelectedBleBinding(
|
|
2958
|
+
pendingBinding.connectId,
|
|
2959
|
+
pendingBinding.requestId,
|
|
2960
|
+
bindingOwner,
|
|
2961
|
+
operationId,
|
|
2962
|
+
signal,
|
|
2963
|
+
fingerprint && checksWallet ? {
|
|
2964
|
+
vendor: "ledger",
|
|
2965
|
+
type: "chainFingerprint",
|
|
2966
|
+
chain: fingerprint.chain,
|
|
2967
|
+
value: fingerprint.deviceId
|
|
2968
|
+
} : void 0
|
|
2969
|
+
);
|
|
1928
2970
|
}
|
|
1929
|
-
|
|
2971
|
+
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
|
|
2972
|
+
this._selectedBleReconnectTargets.set(connectId, {
|
|
2973
|
+
connectId: resolvedConnectId,
|
|
2974
|
+
chain: fingerprint.chain,
|
|
2975
|
+
fingerprint: fingerprint.deviceId
|
|
2976
|
+
});
|
|
2977
|
+
}
|
|
2978
|
+
businessCallStarted = true;
|
|
2979
|
+
const result = await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
2980
|
+
if (walletCheck) walletCheck.derived = true;
|
|
2981
|
+
return result;
|
|
1930
2982
|
} catch (err) {
|
|
1931
2983
|
if (signal.aborted) throw err;
|
|
2984
|
+
if (isLostConnectionError(err)) {
|
|
2985
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
2986
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
2987
|
+
else {
|
|
2988
|
+
this._sessions.delete(resolvedConnectId);
|
|
2989
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
2990
|
+
}
|
|
2991
|
+
const ambiguous = businessCallStarted && !(0, import_hwk_adapter_core4.canReplayHardwareMethodAfterTransportFailure)(method);
|
|
2992
|
+
const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
|
|
2993
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2994
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : mapLedgerError(err).code,
|
|
2995
|
+
message: "Ledger operation connection was lost; start a new operation",
|
|
2996
|
+
params: ambiguous ? (0, import_hwk_adapter_core4.operationMayHaveCompletedParams)(method, { operationId }) : interactionParams,
|
|
2997
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
2998
|
+
});
|
|
2999
|
+
}
|
|
1932
3000
|
const errObj = err;
|
|
1933
3001
|
debugLog("[LedgerAdapter] connectorCall error:", method, {
|
|
1934
3002
|
message: errObj?.message,
|
|
@@ -1940,8 +3008,66 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1940
3008
|
isNotAdvertising: isDeviceNotAdvertisingError(err),
|
|
1941
3009
|
isStuckApp: isStuckAppStateError(err)
|
|
1942
3010
|
});
|
|
3011
|
+
const assertSessionCurrent = (message) => {
|
|
3012
|
+
if (this._sessions.get(resolvedConnectId) === sessionId) return;
|
|
3013
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3014
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
3015
|
+
message
|
|
3016
|
+
});
|
|
3017
|
+
};
|
|
3018
|
+
if ((isDeviceLockedError(err) || errObj?.code === import_hwk_adapter_core4.HardwareErrorCode.DeviceLocked) && lockedRetryBudget > 0) {
|
|
3019
|
+
await this._waitForDeviceConnect(signal);
|
|
3020
|
+
assertSessionCurrent("Ledger connection ended while waiting for unlock");
|
|
3021
|
+
if (walletCheck?.derived) walletCheck.verified = false;
|
|
3022
|
+
return this._runConnectorCall(
|
|
3023
|
+
resolvedConnectId,
|
|
3024
|
+
method,
|
|
3025
|
+
effectiveParams,
|
|
3026
|
+
signal,
|
|
3027
|
+
fingerprint,
|
|
3028
|
+
permissionDeviceId,
|
|
3029
|
+
commonParams,
|
|
3030
|
+
installContext,
|
|
3031
|
+
operationId,
|
|
3032
|
+
lockedRetryBudget - 1
|
|
3033
|
+
);
|
|
3034
|
+
}
|
|
3035
|
+
if (businessCallStarted && isStuckAppStateError(err)) {
|
|
3036
|
+
await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
|
|
3037
|
+
assertSessionCurrent("Ledger connection ended during the app transition");
|
|
3038
|
+
try {
|
|
3039
|
+
const retried = await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
3040
|
+
if (walletCheck) walletCheck.derived = true;
|
|
3041
|
+
return retried;
|
|
3042
|
+
} catch (retryErr) {
|
|
3043
|
+
if (isStuckAppStateError(retryErr)) throw err;
|
|
3044
|
+
if (isLostConnectionError(retryErr)) {
|
|
3045
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
3046
|
+
else {
|
|
3047
|
+
this._sessions.delete(resolvedConnectId);
|
|
3048
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3049
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3050
|
+
}
|
|
3051
|
+
const ambiguous = !(0, import_hwk_adapter_core4.canReplayHardwareMethodAfterTransportFailure)(method);
|
|
3052
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3053
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : mapLedgerError(retryErr).code,
|
|
3054
|
+
message: `Ledger ${method} may have completed before the connection was lost`,
|
|
3055
|
+
params: ambiguous ? (0, import_hwk_adapter_core4.operationMayHaveCompletedParams)(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
|
|
3056
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
3057
|
+
});
|
|
3058
|
+
}
|
|
3059
|
+
throw retryErr;
|
|
3060
|
+
}
|
|
3061
|
+
}
|
|
3062
|
+
if (!operationId && errObj?.code === import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch) {
|
|
3063
|
+
this._sessions.delete(resolvedConnectId);
|
|
3064
|
+
this._sessionTransports.delete(sessionId);
|
|
3065
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3066
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3067
|
+
throw err;
|
|
3068
|
+
}
|
|
1943
3069
|
const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
|
|
1944
|
-
const isAppMissing = isAppNotInstalledError(err) || err?.code ===
|
|
3070
|
+
const isAppMissing = isAppNotInstalledError(err) || err?.code === import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled;
|
|
1945
3071
|
if (autoInstallApp && isAppMissing) {
|
|
1946
3072
|
if (installContext?.deviceOutOfMemoryError) {
|
|
1947
3073
|
throw installContext.deviceOutOfMemoryError;
|
|
@@ -1949,30 +3075,30 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1949
3075
|
const appName = err?.appName ?? mapLedgerError(err).appName;
|
|
1950
3076
|
if (appName) {
|
|
1951
3077
|
if (installContext?.installAttemptedAppNames?.has(appName)) {
|
|
1952
|
-
throw (0,
|
|
1953
|
-
code:
|
|
3078
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3079
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled,
|
|
1954
3080
|
message: `${appName} install reported success but the app is still missing on device`,
|
|
1955
3081
|
_tag: ERROR_TAG.AppInstallVerifyFailed,
|
|
1956
3082
|
appName
|
|
1957
3083
|
});
|
|
1958
3084
|
}
|
|
1959
|
-
const confirmed = await this._waitForInstallAppConfirm(appName);
|
|
3085
|
+
const confirmed = await this._waitForInstallAppConfirm(appName, signal);
|
|
1960
3086
|
if (!confirmed) {
|
|
1961
|
-
throw (0,
|
|
1962
|
-
code:
|
|
3087
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3088
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1963
3089
|
message: `User declined to install ${appName}`,
|
|
1964
3090
|
_tag: ERROR_TAG.UserAborted,
|
|
1965
3091
|
appName
|
|
1966
3092
|
});
|
|
1967
3093
|
}
|
|
1968
3094
|
this.emitter.emit("ui-event", {
|
|
1969
|
-
type:
|
|
3095
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress,
|
|
1970
3096
|
payload: { connectId: resolvedConnectId, appName, progress: 0 }
|
|
1971
3097
|
});
|
|
1972
3098
|
try {
|
|
1973
3099
|
await this._callConnector(sessionId, "installApp", { appName }, signal);
|
|
1974
3100
|
} catch (installErr) {
|
|
1975
|
-
if (mapLedgerError(installErr).code ===
|
|
3101
|
+
if (mapLedgerError(installErr).code === import_hwk_adapter_core4.HardwareErrorCode.DeviceOutOfMemory) {
|
|
1976
3102
|
if (installContext) {
|
|
1977
3103
|
installContext.deviceOutOfMemoryError = installErr;
|
|
1978
3104
|
}
|
|
@@ -1983,8 +3109,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1983
3109
|
installContext.installAttemptedAppNames = installContext.installAttemptedAppNames ?? /* @__PURE__ */ new Set();
|
|
1984
3110
|
installContext.installAttemptedAppNames.add(appName);
|
|
1985
3111
|
}
|
|
1986
|
-
this.emitter.emit(
|
|
1987
|
-
type:
|
|
3112
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
3113
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1988
3114
|
payload: {}
|
|
1989
3115
|
});
|
|
1990
3116
|
return await this._runConnectorCall(
|
|
@@ -1995,157 +3121,14 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1995
3121
|
fingerprint,
|
|
1996
3122
|
permissionDeviceId,
|
|
1997
3123
|
commonParams,
|
|
1998
|
-
installContext
|
|
3124
|
+
installContext,
|
|
3125
|
+
operationId
|
|
1999
3126
|
);
|
|
2000
3127
|
}
|
|
2001
3128
|
}
|
|
2002
|
-
if (isStuckAppStateError(err)) {
|
|
2003
|
-
try {
|
|
2004
|
-
this._sessions.delete(resolvedConnectId);
|
|
2005
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2006
|
-
this.connector.reset?.();
|
|
2007
|
-
} catch {
|
|
2008
|
-
}
|
|
2009
|
-
debugLog(
|
|
2010
|
-
"[LedgerAdapter] stuck-app retry: method=",
|
|
2011
|
-
method,
|
|
2012
|
-
"delayMs=",
|
|
2013
|
-
_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS,
|
|
2014
|
-
"_tag=",
|
|
2015
|
-
err?._tag
|
|
2016
|
-
);
|
|
2017
|
-
try {
|
|
2018
|
-
const retryResult = await this._retryAfterStuckApp(
|
|
2019
|
-
resolvedConnectId,
|
|
2020
|
-
method,
|
|
2021
|
-
effectiveParams,
|
|
2022
|
-
signal,
|
|
2023
|
-
err,
|
|
2024
|
-
fingerprint
|
|
2025
|
-
);
|
|
2026
|
-
debugLog("[LedgerAdapter] stuck-app retry succeeded: method=", method);
|
|
2027
|
-
return retryResult;
|
|
2028
|
-
} catch (retryErr) {
|
|
2029
|
-
if (signal.aborted) throw retryErr;
|
|
2030
|
-
if (isStuckAppStateError(retryErr)) {
|
|
2031
|
-
debugLog("[LedgerAdapter] stuck-app retry exhausted (2nd 6901): method=", method);
|
|
2032
|
-
throw err;
|
|
2033
|
-
}
|
|
2034
|
-
debugLog(
|
|
2035
|
-
"[LedgerAdapter] stuck-app retry threw non-stuck error: method=",
|
|
2036
|
-
method,
|
|
2037
|
-
"retryErrTag=",
|
|
2038
|
-
retryErr?._tag
|
|
2039
|
-
);
|
|
2040
|
-
throw retryErr;
|
|
2041
|
-
}
|
|
2042
|
-
}
|
|
2043
|
-
if (isDeviceLockedError(err) || isDeviceNotAdvertisingError(err) || isDeviceDisconnectedError(err)) {
|
|
2044
|
-
let lastErr = err;
|
|
2045
|
-
for (let attempt = 0; attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET; attempt += 1) {
|
|
2046
|
-
if (signal.aborted) throw lastErr;
|
|
2047
|
-
try {
|
|
2048
|
-
this._sessions.delete(resolvedConnectId);
|
|
2049
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2050
|
-
if (isDeviceDisconnectedError(lastErr)) {
|
|
2051
|
-
try {
|
|
2052
|
-
this.connector.reset?.();
|
|
2053
|
-
} catch {
|
|
2054
|
-
}
|
|
2055
|
-
}
|
|
2056
|
-
const reConnectId = await this.ensureConnected(
|
|
2057
|
-
resolvedConnectId,
|
|
2058
|
-
signal,
|
|
2059
|
-
allowUsbEphemeralFallback
|
|
2060
|
-
);
|
|
2061
|
-
const reSessionId = this._sessions.get(reConnectId);
|
|
2062
|
-
if (!reSessionId) throw lastErr;
|
|
2063
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2064
|
-
const fp = await this._abortable(
|
|
2065
|
-
signal,
|
|
2066
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2067
|
-
reSessionId,
|
|
2068
|
-
fingerprint.deviceId,
|
|
2069
|
-
fingerprint.chain
|
|
2070
|
-
)
|
|
2071
|
-
);
|
|
2072
|
-
if (!fp.success) {
|
|
2073
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2074
|
-
code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
|
|
2075
|
-
});
|
|
2076
|
-
}
|
|
2077
|
-
}
|
|
2078
|
-
return await this._callConnector(reSessionId, method, effectiveParams, signal);
|
|
2079
|
-
} catch (retryErr) {
|
|
2080
|
-
if (signal.aborted) throw retryErr;
|
|
2081
|
-
lastErr = retryErr;
|
|
2082
|
-
const canRetry = attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET - 1 && (isDeviceLockedError(retryErr) || isDeviceNotAdvertisingError(retryErr) || isDeviceDisconnectedError(retryErr));
|
|
2083
|
-
if (!canRetry) {
|
|
2084
|
-
throw retryErr;
|
|
2085
|
-
}
|
|
2086
|
-
}
|
|
2087
|
-
}
|
|
2088
|
-
throw lastErr;
|
|
2089
|
-
}
|
|
2090
|
-
if (isTimeoutError(err)) {
|
|
2091
|
-
debugLog("[LedgerAdapter] timeout, retrying with fresh connection...");
|
|
2092
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2093
|
-
return this._retryWithFreshConnection(
|
|
2094
|
-
resolvedConnectId,
|
|
2095
|
-
method,
|
|
2096
|
-
effectiveParams,
|
|
2097
|
-
signal,
|
|
2098
|
-
err,
|
|
2099
|
-
fingerprint
|
|
2100
|
-
);
|
|
2101
|
-
}
|
|
2102
|
-
if (isConnectionLevelError(err)) {
|
|
2103
|
-
debugLog("[LedgerAdapter] connection-level fail-closed reset");
|
|
2104
|
-
this._sessions.delete(resolvedConnectId);
|
|
2105
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2106
|
-
this.connector.reset();
|
|
2107
|
-
const codeNum = err?.code;
|
|
2108
|
-
throw Object.assign(err, {
|
|
2109
|
-
code: codeNum ?? import_hwk_adapter_core3.HardwareErrorCode.DeviceDisconnected
|
|
2110
|
-
});
|
|
2111
|
-
}
|
|
2112
3129
|
throw err;
|
|
2113
3130
|
}
|
|
2114
3131
|
}
|
|
2115
|
-
/**
|
|
2116
|
-
* Stuck-app recovery: pause for the device's UI transition, then retry once.
|
|
2117
|
-
*
|
|
2118
|
-
* Caller has already cleared the session + reset connector. We wait so Stax
|
|
2119
|
-
* finishes its post-CloseApp animation, then go through ensureConnected +
|
|
2120
|
-
* fingerprint check + call exactly once. Caller decides what to do on a
|
|
2121
|
-
* second stuck-app hit.
|
|
2122
|
-
*/
|
|
2123
|
-
async _retryAfterStuckApp(resolvedConnectId, method, params, signal, originalErr, fingerprint) {
|
|
2124
|
-
await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
|
|
2125
|
-
const retryConnectId = await this.ensureConnected(
|
|
2126
|
-
resolvedConnectId,
|
|
2127
|
-
signal,
|
|
2128
|
-
!!fingerprint?.deviceId && !fingerprint.skipFingerprint
|
|
2129
|
-
);
|
|
2130
|
-
const retrySessionId = this._sessions.get(retryConnectId);
|
|
2131
|
-
if (!retrySessionId) throw originalErr;
|
|
2132
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2133
|
-
const fp = await this._abortable(
|
|
2134
|
-
signal,
|
|
2135
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2136
|
-
retrySessionId,
|
|
2137
|
-
fingerprint.deviceId,
|
|
2138
|
-
fingerprint.chain
|
|
2139
|
-
)
|
|
2140
|
-
);
|
|
2141
|
-
if (!fp.success) {
|
|
2142
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2143
|
-
code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
|
|
2144
|
-
});
|
|
2145
|
-
}
|
|
2146
|
-
}
|
|
2147
|
-
return this._callConnector(retrySessionId, method, params, signal);
|
|
2148
|
-
}
|
|
2149
3132
|
_sleepAbortable(ms, signal) {
|
|
2150
3133
|
return new Promise((resolve, reject) => {
|
|
2151
3134
|
if (signal.aborted) {
|
|
@@ -2164,115 +3147,26 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2164
3147
|
});
|
|
2165
3148
|
}
|
|
2166
3149
|
/**
|
|
2167
|
-
*
|
|
2168
|
-
*
|
|
2169
|
-
* Timeout recovery starts with a full connector reset. After an APDU
|
|
2170
|
-
* timeout, DMK/transport state may still emit malformed responses; retrying
|
|
2171
|
-
* on the same DMK can poison the next chain switch.
|
|
2172
|
-
*/
|
|
2173
|
-
async _retryWithFreshConnection(targetConnectId, method, params, signal, originalErr, fingerprint) {
|
|
2174
|
-
this.connector.reset();
|
|
2175
|
-
this._sessions.clear();
|
|
2176
|
-
this._discoveredDevices.clear();
|
|
2177
|
-
this._connectingPromise = null;
|
|
2178
|
-
const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
|
|
2179
|
-
const retryConnectId = await this.ensureConnected(
|
|
2180
|
-
targetConnectId,
|
|
2181
|
-
signal,
|
|
2182
|
-
allowUsbEphemeralFallback
|
|
2183
|
-
);
|
|
2184
|
-
const retrySessionId = this._sessions.get(retryConnectId);
|
|
2185
|
-
if (!retrySessionId) {
|
|
2186
|
-
throw originalErr;
|
|
2187
|
-
}
|
|
2188
|
-
try {
|
|
2189
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2190
|
-
const fp = await this._abortable(
|
|
2191
|
-
signal,
|
|
2192
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2193
|
-
retrySessionId,
|
|
2194
|
-
fingerprint.deviceId,
|
|
2195
|
-
fingerprint.chain
|
|
2196
|
-
)
|
|
2197
|
-
);
|
|
2198
|
-
if (!fp.success) {
|
|
2199
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2200
|
-
code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
|
|
2201
|
-
});
|
|
2202
|
-
}
|
|
2203
|
-
}
|
|
2204
|
-
return await this._callConnector(retrySessionId, method, params, signal);
|
|
2205
|
-
} catch (retryErr) {
|
|
2206
|
-
if (signal.aborted) throw retryErr;
|
|
2207
|
-
this.connector.reset();
|
|
2208
|
-
this._sessions.clear();
|
|
2209
|
-
this._discoveredDevices.clear();
|
|
2210
|
-
this._connectingPromise = null;
|
|
2211
|
-
if (!isDeviceDisconnectedError(retryErr) && !isTimeoutError(retryErr)) {
|
|
2212
|
-
throw retryErr;
|
|
2213
|
-
}
|
|
2214
|
-
debugLog(
|
|
2215
|
-
"[LedgerAdapter] fresh-session retry still failed; resetting connector and rebuilding DMK"
|
|
2216
|
-
);
|
|
2217
|
-
this.connector.reset();
|
|
2218
|
-
this._sessions.clear();
|
|
2219
|
-
this._discoveredDevices.clear();
|
|
2220
|
-
this._connectingPromise = null;
|
|
2221
|
-
const finalConnectId = await this.ensureConnected(
|
|
2222
|
-
targetConnectId,
|
|
2223
|
-
signal,
|
|
2224
|
-
allowUsbEphemeralFallback
|
|
2225
|
-
);
|
|
2226
|
-
const finalSessionId = this._sessions.get(finalConnectId);
|
|
2227
|
-
if (!finalSessionId) {
|
|
2228
|
-
throw originalErr;
|
|
2229
|
-
}
|
|
2230
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2231
|
-
const fp = await this._abortable(
|
|
2232
|
-
signal,
|
|
2233
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2234
|
-
finalSessionId,
|
|
2235
|
-
fingerprint.deviceId,
|
|
2236
|
-
fingerprint.chain
|
|
2237
|
-
)
|
|
2238
|
-
);
|
|
2239
|
-
if (!fp.success) {
|
|
2240
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2241
|
-
code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
|
|
2242
|
-
});
|
|
2243
|
-
}
|
|
2244
|
-
}
|
|
2245
|
-
return this._callConnector(finalSessionId, method, params, signal);
|
|
2246
|
-
}
|
|
2247
|
-
}
|
|
2248
|
-
/**
|
|
2249
|
-
* Ensure OS-level device permission (Bluetooth / USB) before proceeding.
|
|
2250
|
-
*
|
|
2251
|
-
* Emits `REQUEST_DEVICE_PERMISSION` and awaits the consumer's
|
|
2252
|
-
* `RECEIVE_DEVICE_PERMISSION` reply (60s budget covers "probe → system
|
|
2253
|
-
* prompt → user tap" plus a generous margin). If the consumer never wires
|
|
2254
|
-
* a handler or never replies, the wait times out and the operation fails
|
|
2255
|
-
* fast so scanners/callers don't hang silently.
|
|
2256
|
-
*
|
|
2257
|
-
* - No connectId (searchDevices): environment-level permission
|
|
2258
|
-
* - With connectId (business methods): device-level permission
|
|
3150
|
+
* Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
|
|
3151
|
+
* replies. Without connectId the request is environment-level, else device-level.
|
|
2259
3152
|
*/
|
|
2260
3153
|
async _ensureDevicePermission(connectId, deviceId, signal) {
|
|
2261
3154
|
if (signal?.aborted) {
|
|
2262
3155
|
_LedgerAdapter._throwIfAborted(signal);
|
|
2263
3156
|
}
|
|
2264
3157
|
const transportType = this.activeTransport ?? "hid";
|
|
3158
|
+
const operationId = this._activeOperationId();
|
|
2265
3159
|
const waitPromise = this._uiRegistry.wait(
|
|
2266
|
-
|
|
2267
|
-
{ timeoutMs: 6e4 }
|
|
3160
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
3161
|
+
{ timeoutMs: 6e4, operationId }
|
|
2268
3162
|
);
|
|
2269
|
-
this.emitter.emit(
|
|
2270
|
-
type:
|
|
2271
|
-
payload: { transportType, connectId, deviceId }
|
|
3163
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
|
|
3164
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
3165
|
+
payload: { transportType, connectId, deviceId, operationId }
|
|
2272
3166
|
});
|
|
2273
3167
|
let response;
|
|
2274
3168
|
const onAbort = () => {
|
|
2275
|
-
this._uiRegistry.cancel(
|
|
3169
|
+
this._uiRegistry.cancel(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION);
|
|
2276
3170
|
};
|
|
2277
3171
|
try {
|
|
2278
3172
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
@@ -2281,14 +3175,14 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2281
3175
|
if (signal?.aborted) {
|
|
2282
3176
|
_LedgerAdapter._throwIfAborted(signal);
|
|
2283
3177
|
}
|
|
2284
|
-
if (err?._tag ===
|
|
2285
|
-
this.emitter.emit(
|
|
2286
|
-
type:
|
|
3178
|
+
if (err?._tag === import_hwk_adapter_core4.UI_REQUEST_PREEMPTED_TAG) {
|
|
3179
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
3180
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
2287
3181
|
payload: {}
|
|
2288
3182
|
});
|
|
2289
3183
|
throw Object.assign(new Error("Device permission request superseded"), {
|
|
2290
3184
|
_tag: ERROR_TAG.UserAborted,
|
|
2291
|
-
code:
|
|
3185
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
2292
3186
|
cause: err
|
|
2293
3187
|
});
|
|
2294
3188
|
}
|
|
@@ -2299,7 +3193,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2299
3193
|
const { granted, reason, message } = response;
|
|
2300
3194
|
if (!granted) {
|
|
2301
3195
|
throw Object.assign(new Error(message ?? "Device permission denied"), {
|
|
2302
|
-
code:
|
|
3196
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DevicePermissionDenied,
|
|
2303
3197
|
reason
|
|
2304
3198
|
});
|
|
2305
3199
|
}
|
|
@@ -2313,8 +3207,16 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2313
3207
|
const tag = err && typeof err === "object" ? err._tag : void 0;
|
|
2314
3208
|
if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
|
|
2315
3209
|
const e = err;
|
|
2316
|
-
const params = e.code ===
|
|
2317
|
-
return ledgerFailure(
|
|
3210
|
+
const params = e.code === import_hwk_adapter_core4.HardwareErrorCode.DevicePermissionDenied && e.reason ? { permissionDeniedReason: e.reason } : e.params;
|
|
3211
|
+
return ledgerFailure(
|
|
3212
|
+
e.code,
|
|
3213
|
+
e.message ?? "Unknown error",
|
|
3214
|
+
e.appName,
|
|
3215
|
+
tag,
|
|
3216
|
+
params,
|
|
3217
|
+
void 0,
|
|
3218
|
+
(0, import_hwk_adapter_core4.isHwkRecoveryHint)(e.recovery) ? e.recovery : void 0
|
|
3219
|
+
);
|
|
2318
3220
|
}
|
|
2319
3221
|
const mapped = mapLedgerError(err);
|
|
2320
3222
|
return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
|
|
@@ -2341,7 +3243,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2341
3243
|
deviceId: device.deviceId,
|
|
2342
3244
|
connectId: device.connectId,
|
|
2343
3245
|
label: device.name,
|
|
2344
|
-
connectionType: this.connector.connectionType,
|
|
3246
|
+
connectionType: device.connectionType ?? this.connector.connectionType,
|
|
2345
3247
|
rssi: device.rssi,
|
|
2346
3248
|
isConnectable: device.isConnectable,
|
|
2347
3249
|
serialNumber: device.serialNumber,
|
|
@@ -2639,11 +3541,12 @@ var import_device_signer_kit_ethereum = require("@ledgerhq/device-signer-kit-eth
|
|
|
2639
3541
|
var import_context_module = require("@ledgerhq/context-module");
|
|
2640
3542
|
|
|
2641
3543
|
// src/signer/SignerEth.ts
|
|
2642
|
-
var
|
|
3544
|
+
var import_hwk_adapter_core5 = require("@onekeyfe/hwk-adapter-core");
|
|
2643
3545
|
|
|
2644
3546
|
// src/signer/deviceActionToPromise.ts
|
|
2645
3547
|
var import_device_management_kit = require("@ledgerhq/device-management-kit");
|
|
2646
3548
|
var IDLE_WATCHDOG_MS = 65e3;
|
|
3549
|
+
var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
|
|
2647
3550
|
function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
|
|
2648
3551
|
return new Promise((resolve, reject) => {
|
|
2649
3552
|
let settled = false;
|
|
@@ -2831,7 +3734,6 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
|
|
|
2831
3734
|
}
|
|
2832
3735
|
|
|
2833
3736
|
// src/signer/SignerEth.ts
|
|
2834
|
-
var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
|
|
2835
3737
|
var SignerEth = class {
|
|
2836
3738
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
2837
3739
|
constructor(_sdk) {
|
|
@@ -2852,7 +3754,7 @@ var SignerEth = class {
|
|
|
2852
3754
|
);
|
|
2853
3755
|
}
|
|
2854
3756
|
async signTransaction(derivationPath, serializedTxHex) {
|
|
2855
|
-
const action = this._sdk.signTransaction(derivationPath, (0,
|
|
3757
|
+
const action = this._sdk.signTransaction(derivationPath, (0, import_hwk_adapter_core5.hexToBytes)(serializedTxHex));
|
|
2856
3758
|
return deviceActionToPromise(
|
|
2857
3759
|
action,
|
|
2858
3760
|
this.onInteraction,
|
|
@@ -2861,7 +3763,7 @@ var SignerEth = class {
|
|
|
2861
3763
|
);
|
|
2862
3764
|
}
|
|
2863
3765
|
async signMessage(derivationPath, message) {
|
|
2864
|
-
const action = this._sdk.signMessage(derivationPath, (0,
|
|
3766
|
+
const action = this._sdk.signMessage(derivationPath, (0, import_hwk_adapter_core5.hexToBytes)(message));
|
|
2865
3767
|
return deviceActionToPromise(
|
|
2866
3768
|
action,
|
|
2867
3769
|
this.onInteraction,
|
|
@@ -2902,7 +3804,7 @@ var SignerManager = class _SignerManager {
|
|
|
2902
3804
|
return (args) => new import_device_signer_kit_ethereum.SignerEthBuilder(args);
|
|
2903
3805
|
}
|
|
2904
3806
|
static _createContextModule() {
|
|
2905
|
-
const contextModule = new import_context_module.ContextModuleBuilder({}).removeDefaultLoaders().build();
|
|
3807
|
+
const contextModule = new import_context_module.ContextModuleBuilder({}).setChain(import_context_module.ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
|
|
2906
3808
|
return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
|
|
2907
3809
|
}
|
|
2908
3810
|
static wrapBlindSigningReportNonBlocking(contextModule) {
|
|
@@ -2921,23 +3823,44 @@ var SignerManager = class _SignerManager {
|
|
|
2921
3823
|
};
|
|
2922
3824
|
|
|
2923
3825
|
// src/connector/chains/evm.ts
|
|
2924
|
-
var
|
|
3826
|
+
var import_hwk_adapter_core7 = require("@onekeyfe/hwk-adapter-core");
|
|
2925
3827
|
|
|
2926
3828
|
// src/connector/chains/utils.ts
|
|
2927
|
-
var
|
|
3829
|
+
var import_hwk_adapter_core6 = require("@onekeyfe/hwk-adapter-core");
|
|
2928
3830
|
function normalizePath(path) {
|
|
2929
3831
|
return path.startsWith("m/") ? path.slice(2) : path;
|
|
2930
3832
|
}
|
|
2931
3833
|
function collapseSignerInteraction(interaction) {
|
|
2932
3834
|
switch (interaction) {
|
|
2933
3835
|
case "confirm-open-app":
|
|
2934
|
-
return
|
|
3836
|
+
return import_hwk_adapter_core6.EConnectorInteraction.ConfirmOpenApp;
|
|
2935
3837
|
case "unlock-device":
|
|
2936
|
-
return
|
|
3838
|
+
return import_hwk_adapter_core6.EConnectorInteraction.UnlockDevice;
|
|
2937
3839
|
case "interaction-complete":
|
|
2938
|
-
return
|
|
3840
|
+
return import_hwk_adapter_core6.EConnectorInteraction.InteractionComplete;
|
|
2939
3841
|
default:
|
|
2940
|
-
return
|
|
3842
|
+
return import_hwk_adapter_core6.EConnectorInteraction.ConfirmOnDevice;
|
|
3843
|
+
}
|
|
3844
|
+
}
|
|
3845
|
+
function wireSignerToSession(ctx, sessionId, chain, signer) {
|
|
3846
|
+
signer.onInteraction = (interaction) => {
|
|
3847
|
+
debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
|
|
3848
|
+
ctx.emit("ui-event", {
|
|
3849
|
+
type: collapseSignerInteraction(interaction),
|
|
3850
|
+
payload: { sessionId }
|
|
3851
|
+
});
|
|
3852
|
+
};
|
|
3853
|
+
signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
|
|
3854
|
+
return signer;
|
|
3855
|
+
}
|
|
3856
|
+
async function runSignerCall(ctx, sessionId, call) {
|
|
3857
|
+
try {
|
|
3858
|
+
return await call();
|
|
3859
|
+
} catch (err) {
|
|
3860
|
+
ctx.invalidateSession(sessionId);
|
|
3861
|
+
throw ctx.wrapError(err);
|
|
3862
|
+
} finally {
|
|
3863
|
+
ctx.clearCanceller(sessionId);
|
|
2941
3864
|
}
|
|
2942
3865
|
}
|
|
2943
3866
|
|
|
@@ -2963,7 +3886,7 @@ async function evmSignTransaction(ctx, sessionId, params) {
|
|
|
2963
3886
|
new Error(
|
|
2964
3887
|
"Ledger requires a pre-serialized transaction (serializedTx). Provide an RLP-encoded hex string."
|
|
2965
3888
|
),
|
|
2966
|
-
{ code:
|
|
3889
|
+
{ code: import_hwk_adapter_core7.HardwareErrorCode.InvalidParams }
|
|
2967
3890
|
);
|
|
2968
3891
|
}
|
|
2969
3892
|
const signer = await _getEthSigner(ctx, sessionId);
|
|
@@ -2972,8 +3895,8 @@ async function evmSignTransaction(ctx, sessionId, params) {
|
|
|
2972
3895
|
const result = await signer.signTransaction(path, params.serializedTx);
|
|
2973
3896
|
return {
|
|
2974
3897
|
v: `0x${result.v.toString(16)}`,
|
|
2975
|
-
r: (0,
|
|
2976
|
-
s: (0,
|
|
3898
|
+
r: (0, import_hwk_adapter_core7.padHex64)(result.r),
|
|
3899
|
+
s: (0, import_hwk_adapter_core7.padHex64)(result.s)
|
|
2977
3900
|
};
|
|
2978
3901
|
} catch (err) {
|
|
2979
3902
|
ctx.invalidateSession(sessionId);
|
|
@@ -2987,8 +3910,8 @@ async function evmSignMessage(ctx, sessionId, params) {
|
|
|
2987
3910
|
const path = normalizePath(params.path);
|
|
2988
3911
|
try {
|
|
2989
3912
|
const result = await signer.signMessage(path, params.message);
|
|
2990
|
-
const rHex = (0,
|
|
2991
|
-
const sHex = (0,
|
|
3913
|
+
const rHex = (0, import_hwk_adapter_core7.stripHex)(result.r).padStart(64, "0");
|
|
3914
|
+
const sHex = (0, import_hwk_adapter_core7.stripHex)(result.s).padStart(64, "0");
|
|
2992
3915
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
2993
3916
|
return { signature: `0x${rHex}${sHex}${vHex}` };
|
|
2994
3917
|
} catch (err) {
|
|
@@ -3004,15 +3927,15 @@ async function evmSignTypedData(ctx, sessionId, params) {
|
|
|
3004
3927
|
new Error(
|
|
3005
3928
|
'Ledger does not support hash-only EIP-712 signing. Use mode "full" with the complete typed data structure.'
|
|
3006
3929
|
),
|
|
3007
|
-
{ code:
|
|
3930
|
+
{ code: import_hwk_adapter_core7.HardwareErrorCode.MethodNotSupported }
|
|
3008
3931
|
);
|
|
3009
3932
|
}
|
|
3010
3933
|
const signer = await _getEthSigner(ctx, sessionId);
|
|
3011
3934
|
const path = normalizePath(params.path);
|
|
3012
3935
|
try {
|
|
3013
3936
|
const result = await signer.signTypedData(path, params.data);
|
|
3014
|
-
const rHex = (0,
|
|
3015
|
-
const sHex = (0,
|
|
3937
|
+
const rHex = (0, import_hwk_adapter_core7.stripHex)(result.r).padStart(64, "0");
|
|
3938
|
+
const sHex = (0, import_hwk_adapter_core7.stripHex)(result.s).padStart(64, "0");
|
|
3016
3939
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
3017
3940
|
return { signature: `0x${rHex}${sHex}${vHex}` };
|
|
3018
3941
|
} catch (err) {
|
|
@@ -3039,15 +3962,14 @@ async function _getEthSigner(ctx, sessionId) {
|
|
|
3039
3962
|
}
|
|
3040
3963
|
|
|
3041
3964
|
// src/connector/chains/btc.ts
|
|
3042
|
-
var
|
|
3043
|
-
var
|
|
3965
|
+
var import_hwk_adapter_core9 = require("@onekeyfe/hwk-adapter-core");
|
|
3966
|
+
var import_bitcoinjs_lib2 = require("bitcoinjs-lib");
|
|
3044
3967
|
|
|
3045
3968
|
// src/signer/SignerBtc.ts
|
|
3046
|
-
var
|
|
3969
|
+
var import_hwk_adapter_core8 = require("@onekeyfe/hwk-adapter-core");
|
|
3047
3970
|
function hexToUtf8(hex) {
|
|
3048
|
-
return new TextDecoder().decode((0,
|
|
3971
|
+
return new TextDecoder().decode((0, import_hwk_adapter_core8.hexToBytes)(hex));
|
|
3049
3972
|
}
|
|
3050
|
-
var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
|
|
3051
3973
|
var SignerBtc = class {
|
|
3052
3974
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
3053
3975
|
constructor(_sdk) {
|
|
@@ -3061,7 +3983,7 @@ var SignerBtc = class {
|
|
|
3061
3983
|
return deviceActionToPromise(
|
|
3062
3984
|
action,
|
|
3063
3985
|
this.onInteraction,
|
|
3064
|
-
void 0,
|
|
3986
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3065
3987
|
this.onRegisterCanceller
|
|
3066
3988
|
);
|
|
3067
3989
|
}
|
|
@@ -3079,14 +4001,14 @@ var SignerBtc = class {
|
|
|
3079
4001
|
const result = await deviceActionToPromise(
|
|
3080
4002
|
action,
|
|
3081
4003
|
this.onInteraction,
|
|
3082
|
-
void 0,
|
|
4004
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3083
4005
|
this.onRegisterCanceller
|
|
3084
4006
|
);
|
|
3085
4007
|
debugLog(
|
|
3086
4008
|
"[SignerBtc] getExtendedPublicKey result type:",
|
|
3087
4009
|
typeof result,
|
|
3088
4010
|
"value:",
|
|
3089
|
-
|
|
4011
|
+
summarizeForLog(result)
|
|
3090
4012
|
);
|
|
3091
4013
|
if (typeof result === "string") return result;
|
|
3092
4014
|
return result.extendedPublicKey;
|
|
@@ -3115,7 +4037,7 @@ var SignerBtc = class {
|
|
|
3115
4037
|
return deviceActionToPromise(
|
|
3116
4038
|
action,
|
|
3117
4039
|
this.onInteraction,
|
|
3118
|
-
|
|
4040
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3119
4041
|
this.onRegisterCanceller
|
|
3120
4042
|
);
|
|
3121
4043
|
}
|
|
@@ -3128,7 +4050,7 @@ var SignerBtc = class {
|
|
|
3128
4050
|
return deviceActionToPromise(
|
|
3129
4051
|
action,
|
|
3130
4052
|
this.onInteraction,
|
|
3131
|
-
|
|
4053
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3132
4054
|
this.onRegisterCanceller
|
|
3133
4055
|
);
|
|
3134
4056
|
}
|
|
@@ -3141,7 +4063,7 @@ var SignerBtc = class {
|
|
|
3141
4063
|
return deviceActionToPromise(
|
|
3142
4064
|
action,
|
|
3143
4065
|
this.onInteraction,
|
|
3144
|
-
|
|
4066
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3145
4067
|
this.onRegisterCanceller
|
|
3146
4068
|
);
|
|
3147
4069
|
}
|
|
@@ -3160,11 +4082,25 @@ function _purposeToTemplate(purpose, DDT) {
|
|
|
3160
4082
|
return DDT.TAPROOT;
|
|
3161
4083
|
default:
|
|
3162
4084
|
throw Object.assign(new Error(`Unsupported BTC purpose: m/${purpose ?? "<undefined>"}'`), {
|
|
3163
|
-
code:
|
|
4085
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams
|
|
3164
4086
|
});
|
|
3165
4087
|
}
|
|
3166
4088
|
}
|
|
4089
|
+
function assertBitcoinMainnet(coin) {
|
|
4090
|
+
if (coin !== void 0 && !["btc", "bitcoin"].includes(coin.toLowerCase())) {
|
|
4091
|
+
throw Object.assign(new Error(`Ledger BTC supports Bitcoin mainnet only, not ${coin}`), {
|
|
4092
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.ChainNotSupported
|
|
4093
|
+
});
|
|
4094
|
+
}
|
|
4095
|
+
}
|
|
3167
4096
|
async function btcGetAddress(ctx, sessionId, params) {
|
|
4097
|
+
assertBitcoinMainnet(params.coin);
|
|
4098
|
+
if (normalizePath(params.path).split("/").length !== 3) {
|
|
4099
|
+
throw Object.assign(
|
|
4100
|
+
new Error("Ledger btcGetAddress takes an account path (e.g. m/84'/0'/0') plus addressIndex"),
|
|
4101
|
+
{ code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams }
|
|
4102
|
+
);
|
|
4103
|
+
}
|
|
3168
4104
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
3169
4105
|
const path = normalizePath(params.path);
|
|
3170
4106
|
try {
|
|
@@ -3195,6 +4131,7 @@ async function btcGetAddress(ctx, sessionId, params) {
|
|
|
3195
4131
|
}
|
|
3196
4132
|
}
|
|
3197
4133
|
async function btcGetPublicKey(ctx, sessionId, params) {
|
|
4134
|
+
assertBitcoinMainnet(params.coin);
|
|
3198
4135
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
3199
4136
|
const path = normalizePath(params.path);
|
|
3200
4137
|
debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
|
|
@@ -3202,7 +4139,7 @@ async function btcGetPublicKey(ctx, sessionId, params) {
|
|
|
3202
4139
|
const xpub = await btcSigner.getExtendedPublicKey(path, {
|
|
3203
4140
|
checkOnDevice: params.showOnDevice ?? false
|
|
3204
4141
|
});
|
|
3205
|
-
debugLog("[LedgerConnector] btcGetPublicKey success, xpub:",
|
|
4142
|
+
debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", summarizeForLog(xpub));
|
|
3206
4143
|
return { xpub, path: params.path };
|
|
3207
4144
|
} catch (err) {
|
|
3208
4145
|
debugError("[LedgerConnector] btcGetPublicKey error, path:", path, "err:", err);
|
|
@@ -3216,7 +4153,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3216
4153
|
if (!params.psbt) {
|
|
3217
4154
|
throw Object.assign(
|
|
3218
4155
|
new Error("Ledger requires PSBT format for BTC transaction signing. Provide params.psbt."),
|
|
3219
|
-
{ code:
|
|
4156
|
+
{ code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams }
|
|
3220
4157
|
);
|
|
3221
4158
|
}
|
|
3222
4159
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
@@ -3230,7 +4167,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3230
4167
|
debugLog("[LedgerConnector] btcSignTransaction wallet:", { path, purpose, template });
|
|
3231
4168
|
const wallet = new DefaultWallet(path, template);
|
|
3232
4169
|
const signedTxHex = await btcSigner.signTransaction(wallet, params.psbt);
|
|
3233
|
-
return { serializedTx: (0,
|
|
4170
|
+
return { serializedTx: (0, import_hwk_adapter_core9.stripHex)(signedTxHex) };
|
|
3234
4171
|
} catch (err) {
|
|
3235
4172
|
ctx.invalidateSession(sessionId);
|
|
3236
4173
|
throw ctx.wrapError(err);
|
|
@@ -3241,7 +4178,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3241
4178
|
async function btcSignPsbt(ctx, sessionId, params) {
|
|
3242
4179
|
if (!params.psbt) {
|
|
3243
4180
|
throw Object.assign(new Error("btcSignPsbt requires params.psbt"), {
|
|
3244
|
-
code:
|
|
4181
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams
|
|
3245
4182
|
});
|
|
3246
4183
|
}
|
|
3247
4184
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
@@ -3271,8 +4208,8 @@ async function btcSignMessage(ctx, sessionId, params) {
|
|
|
3271
4208
|
try {
|
|
3272
4209
|
const result = await btcSigner.signMessage(path, params.message);
|
|
3273
4210
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
3274
|
-
const rHex = (0,
|
|
3275
|
-
const sHex = (0,
|
|
4211
|
+
const rHex = (0, import_hwk_adapter_core9.stripHex)(result.r).padStart(64, "0");
|
|
4212
|
+
const sHex = (0, import_hwk_adapter_core9.stripHex)(result.s).padStart(64, "0");
|
|
3276
4213
|
return { signature: `${vHex}${rHex}${sHex}` };
|
|
3277
4214
|
} catch (err) {
|
|
3278
4215
|
ctx.invalidateSession(sessionId);
|
|
@@ -3323,7 +4260,7 @@ function _isScriptPathInput(input) {
|
|
|
3323
4260
|
return !!(input.tapLeafScript && input.tapLeafScript.length > 0);
|
|
3324
4261
|
}
|
|
3325
4262
|
function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
3326
|
-
const psbt =
|
|
4263
|
+
const psbt = import_bitcoinjs_lib2.Psbt.fromHex(psbtHex);
|
|
3327
4264
|
for (const sig of signatures) {
|
|
3328
4265
|
const input = psbt.data.inputs[sig.inputIndex];
|
|
3329
4266
|
if (!input) {
|
|
@@ -3372,7 +4309,8 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
|
3372
4309
|
}
|
|
3373
4310
|
|
|
3374
4311
|
// src/connector/chains/sol.ts
|
|
3375
|
-
var
|
|
4312
|
+
var import_hwk_adapter_core10 = require("@onekeyfe/hwk-adapter-core");
|
|
4313
|
+
var import_bs58 = __toESM(require("bs58"));
|
|
3376
4314
|
|
|
3377
4315
|
// src/signer/SignerSol.ts
|
|
3378
4316
|
var SignerSol = class {
|
|
@@ -3390,7 +4328,7 @@ var SignerSol = class {
|
|
|
3390
4328
|
return deviceActionToPromise(
|
|
3391
4329
|
action,
|
|
3392
4330
|
this.onInteraction,
|
|
3393
|
-
void 0,
|
|
4331
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3394
4332
|
this.onRegisterCanceller
|
|
3395
4333
|
);
|
|
3396
4334
|
}
|
|
@@ -3402,7 +4340,7 @@ var SignerSol = class {
|
|
|
3402
4340
|
return deviceActionToPromise(
|
|
3403
4341
|
action,
|
|
3404
4342
|
this.onInteraction,
|
|
3405
|
-
|
|
4343
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3406
4344
|
this.onRegisterCanceller
|
|
3407
4345
|
);
|
|
3408
4346
|
}
|
|
@@ -3415,7 +4353,7 @@ var SignerSol = class {
|
|
|
3415
4353
|
return deviceActionToPromise(
|
|
3416
4354
|
action,
|
|
3417
4355
|
this.onInteraction,
|
|
3418
|
-
|
|
4356
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3419
4357
|
this.onRegisterCanceller
|
|
3420
4358
|
);
|
|
3421
4359
|
}
|
|
@@ -3440,10 +4378,10 @@ async function solGetAddress(ctx, sessionId, params) {
|
|
|
3440
4378
|
async function solSignTransaction(ctx, sessionId, params) {
|
|
3441
4379
|
const solSigner = await _createSolSigner(ctx, sessionId);
|
|
3442
4380
|
const path = normalizePath(params.path);
|
|
3443
|
-
const txBytes = (0,
|
|
4381
|
+
const txBytes = (0, import_hwk_adapter_core10.hexToBytes)(params.serializedTx);
|
|
3444
4382
|
try {
|
|
3445
4383
|
const result = await solSigner.signTransaction(path, txBytes);
|
|
3446
|
-
return { signature: (0,
|
|
4384
|
+
return { signature: (0, import_hwk_adapter_core10.bytesToHex)(result) };
|
|
3447
4385
|
} catch (err) {
|
|
3448
4386
|
ctx.invalidateSession(sessionId);
|
|
3449
4387
|
throw ctx.wrapError(err);
|
|
@@ -3454,10 +4392,23 @@ async function solSignTransaction(ctx, sessionId, params) {
|
|
|
3454
4392
|
async function solSignMessage(ctx, sessionId, params) {
|
|
3455
4393
|
const solSigner = await _createSolSigner(ctx, sessionId);
|
|
3456
4394
|
const path = normalizePath(params.path);
|
|
3457
|
-
const messageBytes = (0,
|
|
4395
|
+
const messageBytes = (0, import_hwk_adapter_core10.hexToBytes)(params.message);
|
|
3458
4396
|
try {
|
|
4397
|
+
if (params.messageVersion === 1) {
|
|
4398
|
+
const preparedMessage = (0, import_hwk_adapter_core10.prepareSolanaOffchainMessageV1)({
|
|
4399
|
+
message: messageBytes,
|
|
4400
|
+
requiredSigners: params.requiredSigners
|
|
4401
|
+
});
|
|
4402
|
+
const { SignMessageVersion } = await ctx.importLedgerKit(
|
|
4403
|
+
"@ledgerhq/device-signer-kit-solana"
|
|
4404
|
+
);
|
|
4405
|
+
const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
|
|
4406
|
+
version: SignMessageVersion.Raw
|
|
4407
|
+
});
|
|
4408
|
+
return { signature: decodeBase58Signature(result2.signature) };
|
|
4409
|
+
}
|
|
3459
4410
|
const result = await solSigner.signMessage(path, messageBytes);
|
|
3460
|
-
return { signature: result.signature };
|
|
4411
|
+
return { signature: decodeBase58EnvelopeSignature(result.signature) };
|
|
3461
4412
|
} catch (err) {
|
|
3462
4413
|
ctx.invalidateSession(sessionId);
|
|
3463
4414
|
throw ctx.wrapError(err);
|
|
@@ -3465,11 +4416,27 @@ async function solSignMessage(ctx, sessionId, params) {
|
|
|
3465
4416
|
ctx.clearCanceller(sessionId);
|
|
3466
4417
|
}
|
|
3467
4418
|
}
|
|
4419
|
+
function decodeBase58Signature(signature) {
|
|
4420
|
+
const bytes = import_bs58.default.decode(signature);
|
|
4421
|
+
if (bytes.length !== 64) {
|
|
4422
|
+
throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
|
|
4423
|
+
}
|
|
4424
|
+
return (0, import_hwk_adapter_core10.bytesToHex)(bytes);
|
|
4425
|
+
}
|
|
4426
|
+
function decodeBase58EnvelopeSignature(envelope) {
|
|
4427
|
+
const bytes = import_bs58.default.decode(envelope);
|
|
4428
|
+
if (bytes.length < 65 || bytes[0] !== 1) {
|
|
4429
|
+
throw new Error("Ledger Solana signature envelope is invalid");
|
|
4430
|
+
}
|
|
4431
|
+
return (0, import_hwk_adapter_core10.bytesToHex)(bytes.subarray(1, 65));
|
|
4432
|
+
}
|
|
3468
4433
|
async function _createSolSigner(ctx, sessionId) {
|
|
3469
4434
|
const dmk = await ctx.getOrCreateDmk();
|
|
3470
|
-
const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit(
|
|
4435
|
+
const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
|
|
4436
|
+
"@ledgerhq/context-module"
|
|
4437
|
+
);
|
|
3471
4438
|
const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
|
|
3472
|
-
const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
|
|
4439
|
+
const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
|
|
3473
4440
|
const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
|
|
3474
4441
|
const signer = new SignerSol(sdkSigner);
|
|
3475
4442
|
signer.onInteraction = (interaction) => {
|
|
@@ -3485,316 +4452,119 @@ async function _createSolSigner(ctx, sessionId) {
|
|
|
3485
4452
|
return signer;
|
|
3486
4453
|
}
|
|
3487
4454
|
|
|
3488
|
-
// src/connector/chains/
|
|
3489
|
-
var import_hwk_adapter_core12 = require("@onekeyfe/hwk-adapter-core");
|
|
3490
|
-
var import_hw_app_trx = __toESM(require("@ledgerhq/hw-app-trx"));
|
|
3491
|
-
|
|
3492
|
-
// src/connector/chains/legacyChainCall.ts
|
|
4455
|
+
// src/connector/chains/zcash.ts
|
|
3493
4456
|
var import_hwk_adapter_core11 = require("@onekeyfe/hwk-adapter-core");
|
|
3494
4457
|
|
|
3495
|
-
// src/
|
|
3496
|
-
var
|
|
3497
|
-
|
|
3498
|
-
|
|
3499
|
-
|
|
3500
|
-
BTC: "Bitcoin",
|
|
3501
|
-
SOL: "Solana",
|
|
3502
|
-
TRX: "Tron",
|
|
3503
|
-
XRP: "XRP",
|
|
3504
|
-
ADA: "Cardano",
|
|
3505
|
-
DOT: "Polkadot",
|
|
3506
|
-
ATOM: "Cosmos"
|
|
3507
|
-
};
|
|
3508
|
-
var DASHBOARD_APP_NAME = "BOLOS";
|
|
3509
|
-
var AppManager = class {
|
|
3510
|
-
constructor(dmk, options) {
|
|
3511
|
-
this._dmk = dmk;
|
|
3512
|
-
this._waitMs = options?.waitMs ?? 1e3;
|
|
3513
|
-
this._maxRetries = options?.maxRetries ?? 10;
|
|
3514
|
-
}
|
|
3515
|
-
/**
|
|
3516
|
-
* Return the Ledger app name for a given chain ticker,
|
|
3517
|
-
* or undefined if the chain is not supported.
|
|
3518
|
-
*/
|
|
3519
|
-
static getAppName(chain) {
|
|
3520
|
-
return APP_NAME_MAP[chain];
|
|
3521
|
-
}
|
|
3522
|
-
/**
|
|
3523
|
-
* Ensure the target app is open on the device identified by `sessionId`.
|
|
3524
|
-
*
|
|
3525
|
-
* Flow:
|
|
3526
|
-
* 1. Check the currently running app.
|
|
3527
|
-
* 2. If it is already the target, return immediately.
|
|
3528
|
-
* 3. If a different app is running (not dashboard), close it first.
|
|
3529
|
-
* 4. Open the target app.
|
|
3530
|
-
* 5. Poll until the device confirms the target app is running.
|
|
3531
|
-
*/
|
|
3532
|
-
/**
|
|
3533
|
-
* @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
|
|
3534
|
-
* device is about to display "Open <app>" on screen and wait for the
|
|
3535
|
-
* user's button press. UI consumers should show their "open app" prompt
|
|
3536
|
-
* in response. NOT called when the target app is already open (no user
|
|
3537
|
-
* interaction needed in that case).
|
|
3538
|
-
*
|
|
3539
|
-
* Important: OpenAppCommand is blocking. It does not resolve until the user
|
|
3540
|
-
* has physically confirmed on the device, so anything that runs AFTER
|
|
3541
|
-
* `await this._openApp(...)` lands AFTER the prompt is already gone.
|
|
3542
|
-
* Hence the callback must fire BEFORE that await.
|
|
3543
|
-
*/
|
|
3544
|
-
async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
|
|
3545
|
-
const currentApp = await this._getCurrentApp(sessionId);
|
|
3546
|
-
if (currentApp === targetAppName) {
|
|
3547
|
-
return;
|
|
3548
|
-
}
|
|
3549
|
-
if (!this._isDashboard(currentApp)) {
|
|
3550
|
-
await this._closeCurrentApp(sessionId);
|
|
3551
|
-
await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
|
|
3552
|
-
}
|
|
3553
|
-
onConfirmOnDevice?.();
|
|
3554
|
-
await this._openApp(sessionId, targetAppName);
|
|
3555
|
-
await this._waitForApp(sessionId, targetAppName);
|
|
4458
|
+
// src/signer/SignerZcash.ts
|
|
4459
|
+
var SignerZcash = class {
|
|
4460
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4461
|
+
constructor(_sdk) {
|
|
4462
|
+
this._sdk = _sdk;
|
|
3556
4463
|
}
|
|
3557
|
-
|
|
3558
|
-
|
|
3559
|
-
|
|
3560
|
-
|
|
3561
|
-
|
|
3562
|
-
|
|
3563
|
-
|
|
3564
|
-
|
|
3565
|
-
if ((0, import_device_management_kit2.isSuccessCommandResult)(result)) {
|
|
3566
|
-
debugLog("[AppManager] currentApp:", result.data.name);
|
|
3567
|
-
return result.data.name;
|
|
3568
|
-
}
|
|
3569
|
-
const errResult = result;
|
|
3570
|
-
const dmkErr = errResult.error ?? {};
|
|
3571
|
-
const original = dmkErr.originalError;
|
|
3572
|
-
debugLog(
|
|
3573
|
-
"[AppManager] _getCurrentApp failed sessionId=",
|
|
3574
|
-
sessionId,
|
|
3575
|
-
"tag=",
|
|
3576
|
-
dmkErr._tag,
|
|
3577
|
-
"errorCode=",
|
|
3578
|
-
dmkErr.errorCode,
|
|
3579
|
-
"message=",
|
|
3580
|
-
dmkErr.message,
|
|
3581
|
-
"originalErrorMessage=",
|
|
3582
|
-
original?.message ?? String(original ?? "")
|
|
3583
|
-
);
|
|
3584
|
-
throw Object.assign(
|
|
3585
|
-
new Error(
|
|
3586
|
-
dmkErr.message ?? "Failed to get current app from device"
|
|
3587
|
-
),
|
|
3588
|
-
{
|
|
3589
|
-
_tag: dmkErr._tag,
|
|
3590
|
-
errorCode: dmkErr.errorCode,
|
|
3591
|
-
originalError: original
|
|
3592
|
-
}
|
|
4464
|
+
/** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
|
|
4465
|
+
async getFullViewingKey(derivationPath, options) {
|
|
4466
|
+
const action = this._sdk.getFullViewingKey(derivationPath, options);
|
|
4467
|
+
return deviceActionToPromise(
|
|
4468
|
+
action,
|
|
4469
|
+
this.onInteraction,
|
|
4470
|
+
void 0,
|
|
4471
|
+
this.onRegisterCanceller
|
|
3593
4472
|
);
|
|
3594
4473
|
}
|
|
3595
|
-
|
|
3596
|
-
|
|
3597
|
-
|
|
3598
|
-
|
|
3599
|
-
|
|
3600
|
-
|
|
3601
|
-
|
|
3602
|
-
|
|
3603
|
-
const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
|
|
3604
|
-
debugLog(
|
|
3605
|
-
"[AppManager] openApp failed:",
|
|
3606
|
-
appName,
|
|
3607
|
-
"errorCode:",
|
|
3608
|
-
errorCode,
|
|
3609
|
-
"tag:",
|
|
3610
|
-
dmkErr._tag
|
|
3611
|
-
);
|
|
3612
|
-
let code;
|
|
3613
|
-
if (errorCode === "6807" || /unknown application/i.test(message)) {
|
|
3614
|
-
code = import_hwk_adapter_core10.HardwareErrorCode.AppNotInstalled;
|
|
3615
|
-
} else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
|
|
3616
|
-
code = import_hwk_adapter_core10.HardwareErrorCode.UserRejected;
|
|
3617
|
-
}
|
|
3618
|
-
throw Object.assign(new Error(`Failed to open "${appName}"`), {
|
|
3619
|
-
_tag: ERROR_TAG.OpenAppCommand,
|
|
3620
|
-
code,
|
|
3621
|
-
errorCode,
|
|
3622
|
-
statusCode: errorCode,
|
|
3623
|
-
appName,
|
|
3624
|
-
originalError: dmkErr
|
|
3625
|
-
});
|
|
3626
|
-
}
|
|
3627
|
-
}
|
|
3628
|
-
async _closeCurrentApp(sessionId) {
|
|
3629
|
-
debugLog("[AppManager] closeCurrentApp");
|
|
3630
|
-
await this._dmk.sendCommand({
|
|
3631
|
-
sessionId,
|
|
3632
|
-
command: new import_device_management_kit2.CloseAppCommand()
|
|
3633
|
-
});
|
|
3634
|
-
}
|
|
3635
|
-
/**
|
|
3636
|
-
* Poll the device until the expected app is reported as running,
|
|
3637
|
-
* or throw after `_maxRetries` attempts.
|
|
3638
|
-
*/
|
|
3639
|
-
async _waitForApp(sessionId, expectedAppName) {
|
|
3640
|
-
let lastSeen = "";
|
|
3641
|
-
for (let i = 0; i < this._maxRetries; i++) {
|
|
3642
|
-
await this._wait();
|
|
3643
|
-
const current = await this._getCurrentApp(sessionId);
|
|
3644
|
-
lastSeen = current;
|
|
3645
|
-
if (current === expectedAppName) {
|
|
3646
|
-
return;
|
|
3647
|
-
}
|
|
3648
|
-
}
|
|
3649
|
-
debugLog(
|
|
3650
|
-
"[AppManager] waitForApp exhausted: expected=",
|
|
3651
|
-
expectedAppName,
|
|
3652
|
-
"lastSeen=",
|
|
3653
|
-
lastSeen
|
|
3654
|
-
);
|
|
3655
|
-
throw new Error(
|
|
3656
|
-
`Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
|
|
4474
|
+
/** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
|
|
4475
|
+
async getShieldedAddress(derivationPath, options) {
|
|
4476
|
+
const action = this._sdk.getShieldedAddress(derivationPath, options);
|
|
4477
|
+
return deviceActionToPromise(
|
|
4478
|
+
action,
|
|
4479
|
+
this.onInteraction,
|
|
4480
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
4481
|
+
this.onRegisterCanceller
|
|
3657
4482
|
);
|
|
3658
4483
|
}
|
|
3659
|
-
_isDashboard(appName) {
|
|
3660
|
-
return appName === DASHBOARD_APP_NAME;
|
|
3661
|
-
}
|
|
3662
|
-
_wait() {
|
|
3663
|
-
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
3664
|
-
}
|
|
3665
4484
|
};
|
|
3666
4485
|
|
|
3667
|
-
// src/connector/chains/
|
|
3668
|
-
function
|
|
3669
|
-
|
|
4486
|
+
// src/connector/chains/zcash.ts
|
|
4487
|
+
async function zcashGetFullViewingKey(ctx, sessionId, params) {
|
|
4488
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4489
|
+
const path = normalizePath(params.path);
|
|
4490
|
+
const mode = params.mode ?? "ufvk";
|
|
4491
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4492
|
+
const result = await signer.getFullViewingKey(path, { mode });
|
|
4493
|
+
if (result.mode === "ufvk") {
|
|
4494
|
+
return { path: params.path, mode, ufvk: result.fullViewingKey };
|
|
4495
|
+
}
|
|
4496
|
+
return { path: params.path, mode, orchardFvk: (0, import_hwk_adapter_core11.bytesToHex)(result.fullViewingKey) };
|
|
4497
|
+
});
|
|
3670
4498
|
}
|
|
3671
|
-
async function
|
|
3672
|
-
const
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
type: import_hwk_adapter_core11.EConnectorInteraction.ConfirmOpenApp,
|
|
3678
|
-
payload: { sessionId }
|
|
4499
|
+
async function zcashGetShieldedAddress(ctx, sessionId, params) {
|
|
4500
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4501
|
+
const path = normalizePath(params.path);
|
|
4502
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4503
|
+
const result = await signer.getShieldedAddress(path, {
|
|
4504
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
3679
4505
|
});
|
|
3680
|
-
|
|
3681
|
-
|
|
3682
|
-
if (openAppPromptShown) {
|
|
3683
|
-
ctx.emit("ui-event", {
|
|
3684
|
-
type: import_hwk_adapter_core11.EConnectorInteraction.InteractionComplete,
|
|
3685
|
-
payload: { sessionId }
|
|
3686
|
-
});
|
|
3687
|
-
openAppPromptShown = false;
|
|
3688
|
-
}
|
|
3689
|
-
};
|
|
3690
|
-
try {
|
|
3691
|
-
await _ensureAppOpen(ctx, sessionId, appName, onAppOpenPrompt);
|
|
3692
|
-
} catch (err) {
|
|
3693
|
-
debugLog(
|
|
3694
|
-
"[LegacyChainCall] pre-flight ensureAppOpen failed:",
|
|
3695
|
-
appName,
|
|
3696
|
-
err?.message
|
|
3697
|
-
);
|
|
3698
|
-
closeOpenAppUiIfShown();
|
|
3699
|
-
throw ctx.wrapError(err, { defaultAppName: appName });
|
|
3700
|
-
}
|
|
3701
|
-
const runOnce = async () => {
|
|
3702
|
-
let confirmEmitted = false;
|
|
3703
|
-
if (needsConfirmation) {
|
|
3704
|
-
ctx.emit("ui-event", {
|
|
3705
|
-
type: import_hwk_adapter_core11.EConnectorInteraction.ConfirmOnDevice,
|
|
3706
|
-
payload: { sessionId }
|
|
3707
|
-
});
|
|
3708
|
-
confirmEmitted = true;
|
|
3709
|
-
}
|
|
3710
|
-
try {
|
|
3711
|
-
return await action(sessionId);
|
|
3712
|
-
} finally {
|
|
3713
|
-
if (confirmEmitted || openAppPromptShown) {
|
|
3714
|
-
ctx.emit("ui-event", {
|
|
3715
|
-
type: import_hwk_adapter_core11.EConnectorInteraction.InteractionComplete,
|
|
3716
|
-
payload: { sessionId }
|
|
3717
|
-
});
|
|
3718
|
-
openAppPromptShown = false;
|
|
3719
|
-
}
|
|
3720
|
-
}
|
|
3721
|
-
};
|
|
3722
|
-
try {
|
|
3723
|
-
return await runOnce();
|
|
3724
|
-
} catch (err) {
|
|
3725
|
-
if (!isLegacyWrongAppError(err, appName)) {
|
|
3726
|
-
debugLog("[LegacyChainCall] non-wrong-app failure:", appName, err?.message);
|
|
3727
|
-
ctx.invalidateSession(sessionId);
|
|
3728
|
-
throw ctx.wrapError(err, { defaultAppName: appName });
|
|
3729
|
-
}
|
|
3730
|
-
debugLog("[LegacyChainCall] wrong-app detected, retrying:", appName);
|
|
3731
|
-
try {
|
|
3732
|
-
await _ensureAppOpen(ctx, sessionId, appName, onAppOpenPrompt);
|
|
3733
|
-
} catch (switchErr) {
|
|
3734
|
-
debugLog(
|
|
3735
|
-
"[LegacyChainCall] retry ensureAppOpen failed:",
|
|
3736
|
-
appName,
|
|
3737
|
-
switchErr?.message
|
|
3738
|
-
);
|
|
3739
|
-
closeOpenAppUiIfShown();
|
|
3740
|
-
throw ctx.wrapError(switchErr, { defaultAppName: appName });
|
|
3741
|
-
}
|
|
3742
|
-
ctx.clearAllSigners();
|
|
3743
|
-
const result = await runOnce();
|
|
3744
|
-
debugLog("[LegacyChainCall] retry succeeded:", appName);
|
|
3745
|
-
return result;
|
|
3746
|
-
}
|
|
4506
|
+
return { address: result.address, path: params.path };
|
|
4507
|
+
});
|
|
3747
4508
|
}
|
|
3748
|
-
async function
|
|
4509
|
+
async function _createZcashSigner(ctx, sessionId) {
|
|
3749
4510
|
const dmk = await ctx.getOrCreateDmk();
|
|
3750
|
-
const
|
|
3751
|
-
|
|
4511
|
+
const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
|
|
4512
|
+
const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
|
|
4513
|
+
return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
|
|
3752
4514
|
}
|
|
3753
4515
|
|
|
3754
|
-
// src/
|
|
3755
|
-
var
|
|
3756
|
-
|
|
3757
|
-
|
|
3758
|
-
|
|
3759
|
-
|
|
3760
|
-
|
|
4516
|
+
// src/connector/chains/tron.ts
|
|
4517
|
+
var import_hwk_adapter_core12 = require("@onekeyfe/hwk-adapter-core");
|
|
4518
|
+
|
|
4519
|
+
// src/signer/SignerTron.ts
|
|
4520
|
+
var SignerTron = class {
|
|
4521
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4522
|
+
constructor(_sdk) {
|
|
4523
|
+
this._sdk = _sdk;
|
|
3761
4524
|
}
|
|
3762
|
-
|
|
3763
|
-
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
|
|
3767
|
-
|
|
3768
|
-
|
|
3769
|
-
|
|
3770
|
-
|
|
3771
|
-
}
|
|
3772
|
-
result.set(statusCode, data.length);
|
|
3773
|
-
return result;
|
|
4525
|
+
/** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
|
|
4526
|
+
async getAddress(derivationPath, options) {
|
|
4527
|
+
const action = this._sdk.getAddress(derivationPath, options);
|
|
4528
|
+
const result = await deviceActionToPromise(
|
|
4529
|
+
action,
|
|
4530
|
+
this.onInteraction,
|
|
4531
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
4532
|
+
this.onRegisterCanceller
|
|
4533
|
+
);
|
|
4534
|
+
return { address: result.address, publicKey: result.publicKey };
|
|
3774
4535
|
}
|
|
3775
|
-
|
|
4536
|
+
/** Sign a protobuf-encoded raw transaction. */
|
|
4537
|
+
async signTransaction(derivationPath, transaction, options) {
|
|
4538
|
+
const action = this._sdk.signTransaction(derivationPath, transaction, options);
|
|
4539
|
+
return deviceActionToPromise(
|
|
4540
|
+
action,
|
|
4541
|
+
this.onInteraction,
|
|
4542
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
4543
|
+
this.onRegisterCanceller
|
|
4544
|
+
);
|
|
4545
|
+
}
|
|
4546
|
+
/** Sign a personal message (TIP-191). */
|
|
4547
|
+
async signPersonalMessage(derivationPath, message, options) {
|
|
4548
|
+
const action = this._sdk.signPersonalMessage(derivationPath, message, options);
|
|
4549
|
+
return deviceActionToPromise(
|
|
4550
|
+
action,
|
|
4551
|
+
this.onInteraction,
|
|
4552
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
4553
|
+
this.onRegisterCanceller
|
|
4554
|
+
);
|
|
3776
4555
|
}
|
|
3777
4556
|
};
|
|
3778
4557
|
|
|
3779
4558
|
// src/connector/chains/tron.ts
|
|
3780
4559
|
async function tronGetAddress(ctx, sessionId, params) {
|
|
4560
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3781
4561
|
const path = normalizePath(params.path);
|
|
3782
|
-
|
|
3783
|
-
|
|
3784
|
-
|
|
3785
|
-
|
|
3786
|
-
{
|
|
3787
|
-
|
|
3788
|
-
// Only show "confirm on device" UI when the device is actually going
|
|
3789
|
-
// to display the address for the user to verify.
|
|
3790
|
-
needsConfirmation: showOnDevice
|
|
3791
|
-
},
|
|
3792
|
-
async (sid) => {
|
|
3793
|
-
const trx = await _createTrx(ctx, sid);
|
|
3794
|
-
const result = await trx.getAddress(path, showOnDevice);
|
|
3795
|
-
return { address: result.address, publicKey: result.publicKey, path: params.path };
|
|
3796
|
-
}
|
|
3797
|
-
);
|
|
4562
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4563
|
+
const result = await tronSigner.getAddress(path, {
|
|
4564
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
4565
|
+
});
|
|
4566
|
+
return { address: result.address, publicKey: result.publicKey, path: params.path };
|
|
4567
|
+
});
|
|
3798
4568
|
}
|
|
3799
4569
|
async function tronSignTransaction(ctx, sessionId, params) {
|
|
3800
4570
|
if (!params.rawTxHex) {
|
|
@@ -3803,42 +4573,30 @@ async function tronSignTransaction(ctx, sessionId, params) {
|
|
|
3803
4573
|
{ code: import_hwk_adapter_core12.HardwareErrorCode.InvalidParams }
|
|
3804
4574
|
);
|
|
3805
4575
|
}
|
|
4576
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3806
4577
|
const path = normalizePath(params.path);
|
|
3807
|
-
return
|
|
3808
|
-
|
|
3809
|
-
|
|
3810
|
-
|
|
3811
|
-
async (sid) => {
|
|
3812
|
-
const trx = await _createTrx(ctx, sid);
|
|
3813
|
-
const signature = await trx.signTransaction(
|
|
3814
|
-
path,
|
|
3815
|
-
params.rawTxHex,
|
|
3816
|
-
params.tokenSignatures ?? []
|
|
3817
|
-
);
|
|
3818
|
-
return { signature };
|
|
3819
|
-
}
|
|
3820
|
-
);
|
|
4578
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4579
|
+
const signature = await tronSigner.signTransaction(path, (0, import_hwk_adapter_core12.hexToBytes)(params.rawTxHex));
|
|
4580
|
+
return { signature: (0, import_hwk_adapter_core12.bytesToHex)(signature) };
|
|
4581
|
+
});
|
|
3821
4582
|
}
|
|
3822
4583
|
async function tronSignMessage(ctx, sessionId, params) {
|
|
4584
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3823
4585
|
const path = normalizePath(params.path);
|
|
3824
|
-
return
|
|
3825
|
-
|
|
3826
|
-
|
|
3827
|
-
|
|
3828
|
-
async (sid) => {
|
|
3829
|
-
const trx = await _createTrx(ctx, sid);
|
|
3830
|
-
const signature = await trx.signPersonalMessage(path, params.messageHex);
|
|
3831
|
-
return { signature };
|
|
3832
|
-
}
|
|
3833
|
-
);
|
|
4586
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4587
|
+
const signature = await tronSigner.signPersonalMessage(path, (0, import_hwk_adapter_core12.hexToBytes)(params.messageHex));
|
|
4588
|
+
return { signature: (0, import_hwk_adapter_core12.bytesToHex)(signature) };
|
|
4589
|
+
});
|
|
3834
4590
|
}
|
|
3835
|
-
async function
|
|
4591
|
+
async function _createTronSigner(ctx, sessionId) {
|
|
3836
4592
|
const dmk = await ctx.getOrCreateDmk();
|
|
3837
|
-
|
|
4593
|
+
const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
|
|
4594
|
+
const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
|
|
4595
|
+
return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
|
|
3838
4596
|
}
|
|
3839
4597
|
|
|
3840
4598
|
// src/device-apps/customActions.ts
|
|
3841
|
-
var
|
|
4599
|
+
var import_device_management_kit2 = require("@ledgerhq/device-management-kit");
|
|
3842
4600
|
var import_rxjs = require("rxjs");
|
|
3843
4601
|
var GetOsVersionDeviceAction = class {
|
|
3844
4602
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
@@ -3852,7 +4610,7 @@ var GetOsVersionDeviceAction = class {
|
|
|
3852
4610
|
(async () => {
|
|
3853
4611
|
try {
|
|
3854
4612
|
subject.next({
|
|
3855
|
-
status:
|
|
4613
|
+
status: import_device_management_kit2.DeviceActionStatus.Pending,
|
|
3856
4614
|
intermediateValue: { requiredUserInteraction: "none" }
|
|
3857
4615
|
});
|
|
3858
4616
|
const result = await internalApi.sendCommand(new this._deps.GetOsVersionCommand());
|
|
@@ -3861,11 +4619,11 @@ var GetOsVersionDeviceAction = class {
|
|
|
3861
4619
|
const errObj = result?.error;
|
|
3862
4620
|
throw new Error(errObj?.message ?? "GetOsVersionCommand failed");
|
|
3863
4621
|
}
|
|
3864
|
-
subject.next({ status:
|
|
4622
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: result.data });
|
|
3865
4623
|
subject.complete();
|
|
3866
4624
|
} catch (err) {
|
|
3867
4625
|
if (cancelled) return;
|
|
3868
|
-
subject.next({ status:
|
|
4626
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
|
|
3869
4627
|
subject.complete();
|
|
3870
4628
|
}
|
|
3871
4629
|
})();
|
|
@@ -3873,7 +4631,7 @@ var GetOsVersionDeviceAction = class {
|
|
|
3873
4631
|
observable: subject.asObservable(),
|
|
3874
4632
|
cancel: () => {
|
|
3875
4633
|
cancelled = true;
|
|
3876
|
-
subject.next({ status:
|
|
4634
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
|
|
3877
4635
|
subject.complete();
|
|
3878
4636
|
}
|
|
3879
4637
|
};
|
|
@@ -3891,7 +4649,7 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3891
4649
|
(async () => {
|
|
3892
4650
|
try {
|
|
3893
4651
|
subject.next({
|
|
3894
|
-
status:
|
|
4652
|
+
status: import_device_management_kit2.DeviceActionStatus.Pending,
|
|
3895
4653
|
intermediateValue: { requiredUserInteraction: "none" }
|
|
3896
4654
|
});
|
|
3897
4655
|
const osVersionResult = await internalApi.sendCommand(new this._GetOsVersionCommand());
|
|
@@ -3908,11 +4666,11 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3908
4666
|
throw new Error(httpErr?.message ?? "Manager API getAppList failed");
|
|
3909
4667
|
}
|
|
3910
4668
|
const apps = either.extract();
|
|
3911
|
-
subject.next({ status:
|
|
4669
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: apps });
|
|
3912
4670
|
subject.complete();
|
|
3913
4671
|
} catch (err) {
|
|
3914
4672
|
if (cancelled) return;
|
|
3915
|
-
subject.next({ status:
|
|
4673
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
|
|
3916
4674
|
subject.complete();
|
|
3917
4675
|
}
|
|
3918
4676
|
})();
|
|
@@ -3920,7 +4678,7 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3920
4678
|
observable: subject.asObservable(),
|
|
3921
4679
|
cancel: () => {
|
|
3922
4680
|
cancelled = true;
|
|
3923
|
-
subject.next({ status:
|
|
4681
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
|
|
3924
4682
|
subject.complete();
|
|
3925
4683
|
}
|
|
3926
4684
|
};
|
|
@@ -4013,7 +4771,7 @@ var DeviceApps = class {
|
|
|
4013
4771
|
seTargetId: v.seTargetId,
|
|
4014
4772
|
mcuTargetId: v.mcuTargetId,
|
|
4015
4773
|
seVersion: v.seVersion,
|
|
4016
|
-
seFlagsHex:
|
|
4774
|
+
seFlagsHex: bytesToHex4(v.seFlags),
|
|
4017
4775
|
mcuSephVersion: v.mcuSephVersion,
|
|
4018
4776
|
mcuBootloaderVersion: v.mcuBootloaderVersion,
|
|
4019
4777
|
hwVersion: v.hwVersion
|
|
@@ -4087,7 +4845,7 @@ var DeviceApps = class {
|
|
|
4087
4845
|
}
|
|
4088
4846
|
}
|
|
4089
4847
|
};
|
|
4090
|
-
function
|
|
4848
|
+
function bytesToHex4(bytes) {
|
|
4091
4849
|
if (!bytes) return "";
|
|
4092
4850
|
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
4093
4851
|
}
|
|
@@ -4130,7 +4888,8 @@ var METHOD_PREFIX_TO_APP_NAME = {
|
|
|
4130
4888
|
evm: "Ethereum",
|
|
4131
4889
|
btc: "Bitcoin",
|
|
4132
4890
|
sol: "Solana",
|
|
4133
|
-
tron: "Tron"
|
|
4891
|
+
tron: "Tron",
|
|
4892
|
+
zcash: "Zcash"
|
|
4134
4893
|
};
|
|
4135
4894
|
var HARDWARE_ERROR_CODE_VALUES = new Set(
|
|
4136
4895
|
Object.values(import_hwk_adapter_core13.HardwareErrorCode).filter((value) => typeof value === "number")
|
|
@@ -4170,6 +4929,10 @@ async function defaultLedgerKitImporter(pkg) {
|
|
|
4170
4929
|
return import("@ledgerhq/device-signer-kit-bitcoin");
|
|
4171
4930
|
case "@ledgerhq/device-signer-kit-solana":
|
|
4172
4931
|
return import("@ledgerhq/device-signer-kit-solana");
|
|
4932
|
+
case "@ledgerhq/device-signer-kit-tron":
|
|
4933
|
+
return import("@ledgerhq/device-signer-kit-tron");
|
|
4934
|
+
case "@ledgerhq/device-signer-kit-zcash":
|
|
4935
|
+
return import("@ledgerhq/device-signer-kit-zcash");
|
|
4173
4936
|
case "@ledgerhq/context-module":
|
|
4174
4937
|
return import("@ledgerhq/context-module");
|
|
4175
4938
|
default:
|
|
@@ -4229,6 +4992,7 @@ var LedgerConnectorBase = class {
|
|
|
4229
4992
|
this._ctx = {
|
|
4230
4993
|
emit: (event, data) => this._emit(event, data),
|
|
4231
4994
|
invalidateSession: (sid) => this._invalidateSession(sid),
|
|
4995
|
+
teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
|
|
4232
4996
|
wrapError: (err, opts) => this._wrapError(err, opts),
|
|
4233
4997
|
getOrCreateDmk: () => this._getOrCreateDmk(),
|
|
4234
4998
|
getDeviceManager: () => this._getDeviceManager(),
|
|
@@ -4418,7 +5182,7 @@ var LedgerConnectorBase = class {
|
|
|
4418
5182
|
this._resetSignersAndSessions();
|
|
4419
5183
|
if (isLedgerBleConnectionType(this.connectionType)) {
|
|
4420
5184
|
const tag = err?._tag;
|
|
4421
|
-
if (isKnownConnectionTag(tag)) {
|
|
5185
|
+
if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
|
|
4422
5186
|
throw err;
|
|
4423
5187
|
}
|
|
4424
5188
|
const wrapped = new Error(
|
|
@@ -4519,7 +5283,7 @@ var LedgerConnectorBase = class {
|
|
|
4519
5283
|
// whitelist (`toPlainError`). The SW-side adapter rehydrates and re-throws
|
|
4520
5284
|
// locally (see LedgerAdapter._unwrapConnectorResult).
|
|
4521
5285
|
async call(sessionId, method, params) {
|
|
4522
|
-
debugLog("[DMK] call:", method, JSON.stringify(params));
|
|
5286
|
+
debugLog("[DMK] call:", method, JSON.stringify(summarizeForLog(params, { method })));
|
|
4523
5287
|
try {
|
|
4524
5288
|
const payload = await this._dispatch(sessionId, method, params);
|
|
4525
5289
|
return { success: true, payload };
|
|
@@ -4587,6 +5351,11 @@ var LedgerConnectorBase = class {
|
|
|
4587
5351
|
return solSignTransaction(ctx, sessionId, params);
|
|
4588
5352
|
case "solSignMessage":
|
|
4589
5353
|
return solSignMessage(ctx, sessionId, params);
|
|
5354
|
+
// ZCASH
|
|
5355
|
+
case "zcashGetFullViewingKey":
|
|
5356
|
+
return zcashGetFullViewingKey(ctx, sessionId, params);
|
|
5357
|
+
case "zcashGetShieldedAddress":
|
|
5358
|
+
return zcashGetShieldedAddress(ctx, sessionId, params);
|
|
4590
5359
|
// TRON
|
|
4591
5360
|
case "tronGetAddress":
|
|
4592
5361
|
return tronGetAddress(ctx, sessionId, params);
|
|
@@ -4620,7 +5389,7 @@ var LedgerConnectorBase = class {
|
|
|
4620
5389
|
});
|
|
4621
5390
|
});
|
|
4622
5391
|
} catch (err) {
|
|
4623
|
-
ctx.
|
|
5392
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4624
5393
|
throw ctx.wrapError(err);
|
|
4625
5394
|
} finally {
|
|
4626
5395
|
ctx.clearCanceller(sessionId);
|
|
@@ -4710,7 +5479,7 @@ var LedgerConnectorBase = class {
|
|
|
4710
5479
|
);
|
|
4711
5480
|
return { isGenuine: output.isGenuine, deviceId };
|
|
4712
5481
|
} catch (err) {
|
|
4713
|
-
ctx.
|
|
5482
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4714
5483
|
throw ctx.wrapError(err);
|
|
4715
5484
|
} finally {
|
|
4716
5485
|
ctx.clearCanceller(sessionId);
|
|
@@ -4832,6 +5601,17 @@ var LedgerConnectorBase = class {
|
|
|
4832
5601
|
_invalidateSession(sessionId) {
|
|
4833
5602
|
this._signerManager?.invalidate(sessionId);
|
|
4834
5603
|
}
|
|
5604
|
+
_teardownSecureChannelSession(sessionId) {
|
|
5605
|
+
const cancel = this._cancellers.get(sessionId);
|
|
5606
|
+
this._cancellers.delete(sessionId);
|
|
5607
|
+
if (cancel) {
|
|
5608
|
+
try {
|
|
5609
|
+
cancel();
|
|
5610
|
+
} catch {
|
|
5611
|
+
}
|
|
5612
|
+
}
|
|
5613
|
+
this._invalidateSession(sessionId);
|
|
5614
|
+
}
|
|
4835
5615
|
/**
|
|
4836
5616
|
* Replace an old session with a new one after app switch.
|
|
4837
5617
|
* Emits device-connect so the adapter updates its _sessions Map.
|
|
@@ -4916,7 +5696,7 @@ var LedgerConnectorBase = class {
|
|
|
4916
5696
|
* at every catch site. Falls through unchanged for unknown methods.
|
|
4917
5697
|
*/
|
|
4918
5698
|
_ctxForMethod(method) {
|
|
4919
|
-
const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
|
|
5699
|
+
const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
|
|
4920
5700
|
const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
|
|
4921
5701
|
if (!defaultAppName) return this._ctx;
|
|
4922
5702
|
return {
|
|
@@ -4950,6 +5730,204 @@ var LedgerConnectorBase = class {
|
|
|
4950
5730
|
return error;
|
|
4951
5731
|
}
|
|
4952
5732
|
};
|
|
5733
|
+
|
|
5734
|
+
// src/transport/DmkTransport.ts
|
|
5735
|
+
var import_hw_transport = __toESM(require("@ledgerhq/hw-transport"));
|
|
5736
|
+
var DmkTransport = class extends import_hw_transport.default {
|
|
5737
|
+
constructor(dmk, sessionId) {
|
|
5738
|
+
super();
|
|
5739
|
+
this._dmk = dmk;
|
|
5740
|
+
this._sessionId = sessionId;
|
|
5741
|
+
}
|
|
5742
|
+
async exchange(apdu) {
|
|
5743
|
+
const response = await this._dmk.sendApdu({
|
|
5744
|
+
sessionId: this._sessionId,
|
|
5745
|
+
apdu: new Uint8Array(apdu)
|
|
5746
|
+
});
|
|
5747
|
+
const { data, statusCode } = response;
|
|
5748
|
+
const result = Buffer.alloc(data.length + 2);
|
|
5749
|
+
if (data.length > 0) {
|
|
5750
|
+
result.set(data, 0);
|
|
5751
|
+
}
|
|
5752
|
+
result.set(statusCode, data.length);
|
|
5753
|
+
return result;
|
|
5754
|
+
}
|
|
5755
|
+
async close() {
|
|
5756
|
+
}
|
|
5757
|
+
};
|
|
5758
|
+
|
|
5759
|
+
// src/app/AppManager.ts
|
|
5760
|
+
var import_device_management_kit3 = require("@ledgerhq/device-management-kit");
|
|
5761
|
+
var import_hwk_adapter_core14 = require("@onekeyfe/hwk-adapter-core");
|
|
5762
|
+
var APP_NAME_MAP = {
|
|
5763
|
+
ETH: "Ethereum",
|
|
5764
|
+
BTC: "Bitcoin",
|
|
5765
|
+
SOL: "Solana",
|
|
5766
|
+
TRX: "Tron",
|
|
5767
|
+
ZEC: "Zcash",
|
|
5768
|
+
XRP: "XRP",
|
|
5769
|
+
ADA: "Cardano",
|
|
5770
|
+
DOT: "Polkadot",
|
|
5771
|
+
ATOM: "Cosmos"
|
|
5772
|
+
};
|
|
5773
|
+
var DASHBOARD_APP_NAME = "BOLOS";
|
|
5774
|
+
var AppManager = class {
|
|
5775
|
+
constructor(dmk, options) {
|
|
5776
|
+
this._dmk = dmk;
|
|
5777
|
+
this._waitMs = options?.waitMs ?? 1e3;
|
|
5778
|
+
this._maxRetries = options?.maxRetries ?? 10;
|
|
5779
|
+
}
|
|
5780
|
+
/**
|
|
5781
|
+
* Return the Ledger app name for a given chain ticker,
|
|
5782
|
+
* or undefined if the chain is not supported.
|
|
5783
|
+
*/
|
|
5784
|
+
static getAppName(chain) {
|
|
5785
|
+
return APP_NAME_MAP[chain];
|
|
5786
|
+
}
|
|
5787
|
+
/**
|
|
5788
|
+
* Ensure the target app is open on the device identified by `sessionId`.
|
|
5789
|
+
*
|
|
5790
|
+
* Flow:
|
|
5791
|
+
* 1. Check the currently running app.
|
|
5792
|
+
* 2. If it is already the target, return immediately.
|
|
5793
|
+
* 3. If a different app is running (not dashboard), close it first.
|
|
5794
|
+
* 4. Open the target app.
|
|
5795
|
+
* 5. Poll until the device confirms the target app is running.
|
|
5796
|
+
*/
|
|
5797
|
+
/**
|
|
5798
|
+
* @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
|
|
5799
|
+
* device is about to display "Open <app>" on screen and wait for the
|
|
5800
|
+
* user's button press. UI consumers should show their "open app" prompt
|
|
5801
|
+
* in response. NOT called when the target app is already open (no user
|
|
5802
|
+
* interaction needed in that case).
|
|
5803
|
+
*
|
|
5804
|
+
* Important: OpenAppCommand is blocking. It does not resolve until the user
|
|
5805
|
+
* has physically confirmed on the device, so anything that runs AFTER
|
|
5806
|
+
* `await this._openApp(...)` lands AFTER the prompt is already gone.
|
|
5807
|
+
* Hence the callback must fire BEFORE that await.
|
|
5808
|
+
*/
|
|
5809
|
+
async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
|
|
5810
|
+
const currentApp = await this._getCurrentApp(sessionId);
|
|
5811
|
+
if (currentApp === targetAppName) {
|
|
5812
|
+
return;
|
|
5813
|
+
}
|
|
5814
|
+
if (!this._isDashboard(currentApp)) {
|
|
5815
|
+
await this._closeCurrentApp(sessionId);
|
|
5816
|
+
await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
|
|
5817
|
+
}
|
|
5818
|
+
onConfirmOnDevice?.();
|
|
5819
|
+
await this._openApp(sessionId, targetAppName);
|
|
5820
|
+
await this._waitForApp(sessionId, targetAppName);
|
|
5821
|
+
}
|
|
5822
|
+
// ---------------------------------------------------------------------------
|
|
5823
|
+
// Private helpers
|
|
5824
|
+
// ---------------------------------------------------------------------------
|
|
5825
|
+
async _getCurrentApp(sessionId) {
|
|
5826
|
+
const result = await this._dmk.sendCommand({
|
|
5827
|
+
sessionId,
|
|
5828
|
+
command: new import_device_management_kit3.GetAppAndVersionCommand()
|
|
5829
|
+
});
|
|
5830
|
+
if ((0, import_device_management_kit3.isSuccessCommandResult)(result)) {
|
|
5831
|
+
debugLog("[AppManager] currentApp:", result.data.name);
|
|
5832
|
+
return result.data.name;
|
|
5833
|
+
}
|
|
5834
|
+
const errResult = result;
|
|
5835
|
+
const dmkErr = errResult.error ?? {};
|
|
5836
|
+
const original = dmkErr.originalError;
|
|
5837
|
+
debugLog(
|
|
5838
|
+
"[AppManager] _getCurrentApp failed sessionId=",
|
|
5839
|
+
sessionId,
|
|
5840
|
+
"tag=",
|
|
5841
|
+
dmkErr._tag,
|
|
5842
|
+
"errorCode=",
|
|
5843
|
+
dmkErr.errorCode,
|
|
5844
|
+
"message=",
|
|
5845
|
+
dmkErr.message,
|
|
5846
|
+
"originalErrorMessage=",
|
|
5847
|
+
original?.message ?? String(original ?? "")
|
|
5848
|
+
);
|
|
5849
|
+
throw Object.assign(
|
|
5850
|
+
new Error(
|
|
5851
|
+
dmkErr.message ?? "Failed to get current app from device"
|
|
5852
|
+
),
|
|
5853
|
+
{
|
|
5854
|
+
_tag: dmkErr._tag,
|
|
5855
|
+
errorCode: dmkErr.errorCode,
|
|
5856
|
+
originalError: original
|
|
5857
|
+
}
|
|
5858
|
+
);
|
|
5859
|
+
}
|
|
5860
|
+
async _openApp(sessionId, appName) {
|
|
5861
|
+
const result = await this._dmk.sendCommand({
|
|
5862
|
+
sessionId,
|
|
5863
|
+
command: new import_device_management_kit3.OpenAppCommand({ appName })
|
|
5864
|
+
});
|
|
5865
|
+
if (!(0, import_device_management_kit3.isSuccessCommandResult)(result)) {
|
|
5866
|
+
const dmkErr = result.error;
|
|
5867
|
+
const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
|
|
5868
|
+
const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
|
|
5869
|
+
debugLog(
|
|
5870
|
+
"[AppManager] openApp failed:",
|
|
5871
|
+
appName,
|
|
5872
|
+
"errorCode:",
|
|
5873
|
+
errorCode,
|
|
5874
|
+
"tag:",
|
|
5875
|
+
dmkErr._tag
|
|
5876
|
+
);
|
|
5877
|
+
let code;
|
|
5878
|
+
if (errorCode === "6807" || /unknown application/i.test(message)) {
|
|
5879
|
+
code = import_hwk_adapter_core14.HardwareErrorCode.AppNotInstalled;
|
|
5880
|
+
} else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
|
|
5881
|
+
code = import_hwk_adapter_core14.HardwareErrorCode.UserRejected;
|
|
5882
|
+
}
|
|
5883
|
+
throw Object.assign(new Error(`Failed to open "${appName}"`), {
|
|
5884
|
+
_tag: ERROR_TAG.OpenAppCommand,
|
|
5885
|
+
code,
|
|
5886
|
+
errorCode,
|
|
5887
|
+
statusCode: errorCode,
|
|
5888
|
+
appName,
|
|
5889
|
+
originalError: dmkErr
|
|
5890
|
+
});
|
|
5891
|
+
}
|
|
5892
|
+
}
|
|
5893
|
+
async _closeCurrentApp(sessionId) {
|
|
5894
|
+
debugLog("[AppManager] closeCurrentApp");
|
|
5895
|
+
await this._dmk.sendCommand({
|
|
5896
|
+
sessionId,
|
|
5897
|
+
command: new import_device_management_kit3.CloseAppCommand()
|
|
5898
|
+
});
|
|
5899
|
+
}
|
|
5900
|
+
/**
|
|
5901
|
+
* Poll the device until the expected app is reported as running,
|
|
5902
|
+
* or throw after `_maxRetries` attempts.
|
|
5903
|
+
*/
|
|
5904
|
+
async _waitForApp(sessionId, expectedAppName) {
|
|
5905
|
+
let lastSeen = "";
|
|
5906
|
+
for (let i = 0; i < this._maxRetries; i++) {
|
|
5907
|
+
await this._wait();
|
|
5908
|
+
const current = await this._getCurrentApp(sessionId);
|
|
5909
|
+
lastSeen = current;
|
|
5910
|
+
if (current === expectedAppName) {
|
|
5911
|
+
return;
|
|
5912
|
+
}
|
|
5913
|
+
}
|
|
5914
|
+
debugLog(
|
|
5915
|
+
"[AppManager] waitForApp exhausted: expected=",
|
|
5916
|
+
expectedAppName,
|
|
5917
|
+
"lastSeen=",
|
|
5918
|
+
lastSeen
|
|
5919
|
+
);
|
|
5920
|
+
throw new Error(
|
|
5921
|
+
`Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
|
|
5922
|
+
);
|
|
5923
|
+
}
|
|
5924
|
+
_isDashboard(appName) {
|
|
5925
|
+
return appName === DASHBOARD_APP_NAME;
|
|
5926
|
+
}
|
|
5927
|
+
_wait() {
|
|
5928
|
+
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
5929
|
+
}
|
|
5930
|
+
};
|
|
4953
5931
|
// Annotate the CommonJS export names for ESM import in node:
|
|
4954
5932
|
0 && (module.exports = {
|
|
4955
5933
|
AppManager,
|
|
@@ -4961,6 +5939,7 @@ var LedgerConnectorBase = class {
|
|
|
4961
5939
|
SignerEth,
|
|
4962
5940
|
SignerManager,
|
|
4963
5941
|
SignerSol,
|
|
5942
|
+
SignerZcash,
|
|
4964
5943
|
debugLog,
|
|
4965
5944
|
deviceActionToPromise,
|
|
4966
5945
|
isDeviceLockedError,
|