@onekeyfe/hwk-ledger-adapter 1.2.8-alpha.4 → 1.2.8-alpha.50
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 +86 -52
- package/dist/index.d.ts +86 -52
- package/dist/index.js +1925 -963
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1865 -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") {
|
|
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,75 @@ 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) 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
|
+
async _releaseOperationConnection(operation) {
|
|
1513
|
+
const sessionIds = /* @__PURE__ */ new Set();
|
|
1514
|
+
for (const [connectId, sessionId] of this._sessions) {
|
|
1515
|
+
if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
|
|
1516
|
+
this._sessions.delete(connectId);
|
|
1517
|
+
sessionIds.add(sessionId);
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
for (const sessionId of sessionIds) {
|
|
1521
|
+
await this._runConnectorTeardown(
|
|
1522
|
+
() => this.connector.disconnect(sessionId).catch(() => void 0)
|
|
1523
|
+
);
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
async _releaseLostOperationConnection(operationId) {
|
|
1527
|
+
const endedOperation = this._operations.end(operationId, "disconnect");
|
|
1528
|
+
if (!endedOperation) return;
|
|
1529
|
+
this._discoveredDevices.delete(endedOperation.connectId);
|
|
1530
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1531
|
+
}
|
|
1532
|
+
async getDeviceInfo(connectIdOrOperationId, deviceId) {
|
|
1533
|
+
let connectId;
|
|
1534
|
+
try {
|
|
1535
|
+
connectId = (0, import_hwk_adapter_core4.isHardwareOperationId)(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
|
|
1536
|
+
} catch (error) {
|
|
1537
|
+
return this.errorToFailure(error);
|
|
1538
|
+
}
|
|
1020
1539
|
debugLog("[LedgerAdapter][REQ]", {
|
|
1021
1540
|
method: "getDeviceInfo",
|
|
1022
1541
|
connectId,
|
|
@@ -1026,7 +1545,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1026
1545
|
await this._ensureDevicePermission(connectId, deviceId);
|
|
1027
1546
|
const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
|
|
1028
1547
|
if (cached) {
|
|
1029
|
-
const result = (0,
|
|
1548
|
+
const result = (0, import_hwk_adapter_core4.success)(cached);
|
|
1030
1549
|
debugLog("[LedgerAdapter][RES]", {
|
|
1031
1550
|
method: "getDeviceInfo",
|
|
1032
1551
|
success: true,
|
|
@@ -1034,8 +1553,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1034
1553
|
});
|
|
1035
1554
|
return result;
|
|
1036
1555
|
}
|
|
1037
|
-
const notFound = (0,
|
|
1038
|
-
|
|
1556
|
+
const notFound = (0, import_hwk_adapter_core4.failure)(
|
|
1557
|
+
import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
1039
1558
|
"Device not found in cache. Call searchDevices() or wait for a device-connected event first."
|
|
1040
1559
|
);
|
|
1041
1560
|
debugLog("[LedgerAdapter][RES]", {
|
|
@@ -1051,11 +1570,19 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1051
1570
|
success: false,
|
|
1052
1571
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
1053
1572
|
});
|
|
1054
|
-
|
|
1573
|
+
return this.errorToFailure(err);
|
|
1055
1574
|
}
|
|
1056
1575
|
}
|
|
1057
|
-
|
|
1058
|
-
|
|
1576
|
+
/** A bundle's BLE pick that no item got past the wallet check is not kept. */
|
|
1577
|
+
async _dropUncheckedBundlePick(context, signal) {
|
|
1578
|
+
const { connection } = context;
|
|
1579
|
+
const owner = connection ? this._pendingPickBindings.get(connection.connectId) : void 0;
|
|
1580
|
+
if (!connection || !owner) return;
|
|
1581
|
+
this._pendingPickBindings.delete(connection.connectId);
|
|
1582
|
+
this._discardPendingBinding(owner, signal.aborted ? "cancelled" : "failed");
|
|
1583
|
+
if (this._sessions.get(connection.connectId) === connection.sessionId) {
|
|
1584
|
+
await this._dropSession(connection.connectId, signal);
|
|
1585
|
+
}
|
|
1059
1586
|
}
|
|
1060
1587
|
// ---------------------------------------------------------------------------
|
|
1061
1588
|
// Chain call helper
|
|
@@ -1075,7 +1602,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1075
1602
|
commonParams,
|
|
1076
1603
|
installContext
|
|
1077
1604
|
);
|
|
1078
|
-
return (0,
|
|
1605
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1079
1606
|
} catch (err) {
|
|
1080
1607
|
return this.errorToFailure(err);
|
|
1081
1608
|
}
|
|
@@ -1091,13 +1618,25 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1091
1618
|
if (params && typeof params === "object") {
|
|
1092
1619
|
const {
|
|
1093
1620
|
autoInstallApp,
|
|
1621
|
+
operationId,
|
|
1094
1622
|
passphraseState: _passphraseState,
|
|
1095
1623
|
useEmptyPassphrase: _useEmptyPassphrase,
|
|
1624
|
+
knownConnections,
|
|
1625
|
+
extra,
|
|
1626
|
+
allowDeviceSelection,
|
|
1627
|
+
supportedTransports,
|
|
1096
1628
|
...rest
|
|
1097
1629
|
} = params;
|
|
1098
1630
|
return {
|
|
1099
1631
|
commonParams: {
|
|
1100
|
-
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
|
|
1632
|
+
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
|
|
1633
|
+
operationId: typeof operationId === "string" ? operationId : void 0,
|
|
1634
|
+
...(0, import_hwk_adapter_core4.pickConnectionContext)({
|
|
1635
|
+
knownConnections,
|
|
1636
|
+
extra,
|
|
1637
|
+
allowDeviceSelection,
|
|
1638
|
+
supportedTransports
|
|
1639
|
+
})
|
|
1101
1640
|
},
|
|
1102
1641
|
rest
|
|
1103
1642
|
};
|
|
@@ -1273,14 +1812,33 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1273
1812
|
);
|
|
1274
1813
|
}
|
|
1275
1814
|
// ---------------------------------------------------------------------------
|
|
1276
|
-
//
|
|
1277
|
-
//
|
|
1278
|
-
|
|
1815
|
+
// Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
|
|
1816
|
+
// ---------------------------------------------------------------------------
|
|
1817
|
+
zcashGetFullViewingKey(connectId, deviceId, params) {
|
|
1818
|
+
return this.callChainWithMergedParams(
|
|
1819
|
+
connectId,
|
|
1820
|
+
deviceId,
|
|
1821
|
+
"zcash",
|
|
1822
|
+
"zcashGetFullViewingKey",
|
|
1823
|
+
params
|
|
1824
|
+
);
|
|
1825
|
+
}
|
|
1826
|
+
zcashGetShieldedAddress(connectId, deviceId, params) {
|
|
1827
|
+
return this.callChainWithMergedParams(
|
|
1828
|
+
connectId,
|
|
1829
|
+
deviceId,
|
|
1830
|
+
"zcash",
|
|
1831
|
+
"zcashGetShieldedAddress",
|
|
1832
|
+
params
|
|
1833
|
+
);
|
|
1834
|
+
}
|
|
1835
|
+
// ---------------------------------------------------------------------------
|
|
1836
|
+
// App management: OS-level app install/list, no fingerprint or chain dispatch.
|
|
1279
1837
|
// ---------------------------------------------------------------------------
|
|
1280
1838
|
async installApp(connectId, appName) {
|
|
1281
1839
|
try {
|
|
1282
1840
|
await this.connectorCall(connectId, "installApp", { appName });
|
|
1283
|
-
return (0,
|
|
1841
|
+
return (0, import_hwk_adapter_core4.success)(void 0);
|
|
1284
1842
|
} catch (err) {
|
|
1285
1843
|
return this.errorToFailure(err);
|
|
1286
1844
|
}
|
|
@@ -1288,7 +1846,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1288
1846
|
async listInstalledApps(connectId) {
|
|
1289
1847
|
try {
|
|
1290
1848
|
const result = await this.connectorCall(connectId, "listInstalledApps", {});
|
|
1291
|
-
return (0,
|
|
1849
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1292
1850
|
} catch (err) {
|
|
1293
1851
|
return this.errorToFailure(err);
|
|
1294
1852
|
}
|
|
@@ -1297,7 +1855,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1297
1855
|
async listInstalledNames(connectId) {
|
|
1298
1856
|
try {
|
|
1299
1857
|
const result = await this.connectorCall(connectId, "listInstalledNames", {});
|
|
1300
|
-
return (0,
|
|
1858
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1301
1859
|
} catch (err) {
|
|
1302
1860
|
return this.errorToFailure(err);
|
|
1303
1861
|
}
|
|
@@ -1305,7 +1863,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1305
1863
|
async listAvailableApps(connectId) {
|
|
1306
1864
|
try {
|
|
1307
1865
|
const result = await this.connectorCall(connectId, "listAvailableApps", {});
|
|
1308
|
-
return (0,
|
|
1866
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1309
1867
|
} catch (err) {
|
|
1310
1868
|
return this.errorToFailure(err);
|
|
1311
1869
|
}
|
|
@@ -1313,7 +1871,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1313
1871
|
async getLedgerFirmwareVersion(connectId) {
|
|
1314
1872
|
try {
|
|
1315
1873
|
const result = await this.connectorCall(connectId, "getFirmwareVersion", {});
|
|
1316
|
-
return (0,
|
|
1874
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1317
1875
|
} catch (err) {
|
|
1318
1876
|
return this.errorToFailure(err);
|
|
1319
1877
|
}
|
|
@@ -1321,7 +1879,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1321
1879
|
async getLedgerDeviceInfo(connectId) {
|
|
1322
1880
|
try {
|
|
1323
1881
|
const result = await this.connectorCall(connectId, "getDeviceInfo", {});
|
|
1324
|
-
return (0,
|
|
1882
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1325
1883
|
} catch (err) {
|
|
1326
1884
|
return this.errorToFailure(err);
|
|
1327
1885
|
}
|
|
@@ -1355,28 +1913,28 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1355
1913
|
try {
|
|
1356
1914
|
if (relayUrl) {
|
|
1357
1915
|
if (!this.connector.configure) {
|
|
1358
|
-
return (0,
|
|
1359
|
-
|
|
1916
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
1917
|
+
import_hwk_adapter_core4.HardwareErrorCode.MethodNotSupported,
|
|
1360
1918
|
"This Ledger connector does not support genuine-check relay configuration"
|
|
1361
1919
|
);
|
|
1362
1920
|
}
|
|
1363
1921
|
await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
|
|
1364
|
-
this.
|
|
1922
|
+
await this._resetStateAndDisconnectSessions();
|
|
1365
1923
|
}
|
|
1366
1924
|
const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
|
|
1367
1925
|
if (!result.isGenuine) {
|
|
1368
|
-
return (0,
|
|
1926
|
+
return (0, import_hwk_adapter_core4.success)({
|
|
1369
1927
|
vendor: "ledger",
|
|
1370
1928
|
verified: false
|
|
1371
1929
|
});
|
|
1372
1930
|
}
|
|
1373
1931
|
if (!result.deviceId) {
|
|
1374
|
-
return (0,
|
|
1375
|
-
|
|
1932
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
1933
|
+
import_hwk_adapter_core4.HardwareErrorCode.UnknownError,
|
|
1376
1934
|
`Genuine check completed (isGenuine=${result.isGenuine}) but no deviceId was captured`
|
|
1377
1935
|
);
|
|
1378
1936
|
}
|
|
1379
|
-
return (0,
|
|
1937
|
+
return (0, import_hwk_adapter_core4.success)({
|
|
1380
1938
|
vendor: "ledger",
|
|
1381
1939
|
verified: result.isGenuine,
|
|
1382
1940
|
deviceId: result.deviceId
|
|
@@ -1387,10 +1945,10 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1387
1945
|
if (relayUrl) {
|
|
1388
1946
|
try {
|
|
1389
1947
|
await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
|
|
1390
|
-
this.
|
|
1948
|
+
await this._resetStateAndDisconnectSessions();
|
|
1391
1949
|
} catch {
|
|
1392
1950
|
this.connector.reset();
|
|
1393
|
-
this.
|
|
1951
|
+
await this._resetStateAndDisconnectSessions();
|
|
1394
1952
|
}
|
|
1395
1953
|
}
|
|
1396
1954
|
}
|
|
@@ -1402,8 +1960,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1402
1960
|
this.emitter.off(event, listener);
|
|
1403
1961
|
}
|
|
1404
1962
|
cancel(connectId) {
|
|
1963
|
+
const namedOperationIsLive = (id) => {
|
|
1964
|
+
try {
|
|
1965
|
+
this._operations.resolve(id);
|
|
1966
|
+
return true;
|
|
1967
|
+
} catch {
|
|
1968
|
+
return false;
|
|
1969
|
+
}
|
|
1970
|
+
};
|
|
1971
|
+
if ((0, import_hwk_adapter_core4.isHardwareOperationId)(connectId) && !namedOperationIsLive(connectId)) {
|
|
1972
|
+
debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
|
|
1973
|
+
connectId
|
|
1974
|
+
});
|
|
1975
|
+
return;
|
|
1976
|
+
}
|
|
1405
1977
|
const userAbortReason = Object.assign(new Error("User aborted operation"), {
|
|
1406
|
-
code:
|
|
1978
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1407
1979
|
_tag: ERROR_TAG.UserAborted
|
|
1408
1980
|
});
|
|
1409
1981
|
this._lastCancelReason = userAbortReason;
|
|
@@ -1412,14 +1984,48 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1412
1984
|
this._lastCancelReason = void 0;
|
|
1413
1985
|
}
|
|
1414
1986
|
}, 2e3);
|
|
1415
|
-
this.
|
|
1416
|
-
|
|
1417
|
-
|
|
1987
|
+
const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
|
|
1988
|
+
let operationId;
|
|
1989
|
+
if ((0, import_hwk_adapter_core4.isHardwareOperationId)(connectId)) {
|
|
1990
|
+
operationId = connectId;
|
|
1991
|
+
} else if (!connectId && (0, import_hwk_adapter_core4.isHardwareOperationId)(activeJobId)) {
|
|
1992
|
+
operationId = activeJobId;
|
|
1993
|
+
}
|
|
1994
|
+
let resolvedConnectId = connectId;
|
|
1995
|
+
if (operationId) {
|
|
1996
|
+
try {
|
|
1997
|
+
resolvedConnectId = this._operations.resolve(operationId).connectId;
|
|
1998
|
+
} catch {
|
|
1999
|
+
resolvedConnectId = void 0;
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
|
|
2003
|
+
const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
|
|
2004
|
+
if (!connectId) {
|
|
2005
|
+
this._uiRegistry.cancel();
|
|
2006
|
+
} else if (pendingOperationId) {
|
|
2007
|
+
this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
|
|
2008
|
+
}
|
|
2009
|
+
this._finishBleBinding("cancelled");
|
|
2010
|
+
if (!connectId) this._pendingOperationBindings.clear();
|
|
2011
|
+
else if (pendingOperationId) this._pendingOperationBindings.delete(pendingOperationId);
|
|
2012
|
+
const queueKeys = /* @__PURE__ */ new Set();
|
|
2013
|
+
if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
|
|
2014
|
+
if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
|
|
2015
|
+
if (queueKeys.size) {
|
|
2016
|
+
let cancelledAnyJob = false;
|
|
2017
|
+
for (const key of queueKeys) {
|
|
2018
|
+
cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
|
|
2019
|
+
}
|
|
2020
|
+
debugLog("[LedgerAdapter] cancel routed to queue keys", {
|
|
2021
|
+
queueKeys: [...queueKeys],
|
|
2022
|
+
cancelledAnyJob
|
|
2023
|
+
});
|
|
1418
2024
|
} else {
|
|
1419
2025
|
this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
|
|
1420
2026
|
}
|
|
1421
|
-
if (
|
|
1422
|
-
const sessionId = this._sessions.get(
|
|
2027
|
+
if (resolvedConnectId) {
|
|
2028
|
+
const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
|
|
1423
2029
|
void this.connector.cancel(sessionId);
|
|
1424
2030
|
} else {
|
|
1425
2031
|
for (const sid of this._sessions.values()) void this.connector.cancel(sid);
|
|
@@ -1427,45 +2033,86 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1427
2033
|
if (this._connectingPromise) {
|
|
1428
2034
|
this._doConnectAbortController?.abort(userAbortReason);
|
|
1429
2035
|
}
|
|
2036
|
+
const connectingConnectId = this._connectingConnectId;
|
|
2037
|
+
if (connectingConnectId) void this.connector.cancel(connectingConnectId);
|
|
1430
2038
|
}
|
|
1431
2039
|
// ---------------------------------------------------------------------------
|
|
1432
2040
|
// Chain fingerprint
|
|
1433
2041
|
// ---------------------------------------------------------------------------
|
|
2042
|
+
/** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
|
|
1434
2043
|
async getChainFingerprint(connectId, deviceId, chain) {
|
|
1435
2044
|
try {
|
|
1436
2045
|
const fingerprint = await this._computeChainFingerprint(
|
|
1437
2046
|
chain,
|
|
1438
2047
|
(method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
|
|
1439
2048
|
);
|
|
1440
|
-
|
|
2049
|
+
if (deviceId) {
|
|
2050
|
+
if (fingerprint !== deviceId) {
|
|
2051
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
2052
|
+
import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
2053
|
+
formatDeviceMismatchError(deviceId, fingerprint)
|
|
2054
|
+
);
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
return (0, import_hwk_adapter_core4.success)(fingerprint);
|
|
1441
2058
|
} catch (err) {
|
|
1442
2059
|
debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
|
|
1443
2060
|
return this.errorToFailure(err);
|
|
1444
2061
|
}
|
|
1445
2062
|
}
|
|
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 };
|
|
2063
|
+
/** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
|
|
2064
|
+
async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
|
|
1452
2065
|
try {
|
|
1453
|
-
const
|
|
1454
|
-
|
|
1455
|
-
|
|
2066
|
+
const outcome = await (0, import_hwk_adapter_core4.requestSaveDeviceBinding)(
|
|
2067
|
+
this.emitter,
|
|
2068
|
+
this._uiRegistry,
|
|
2069
|
+
{
|
|
2070
|
+
selectionRequestId,
|
|
2071
|
+
connection: { transport: "ble", connectId },
|
|
2072
|
+
...identity ? { identity } : {},
|
|
2073
|
+
extra: context?.extra,
|
|
2074
|
+
operationId
|
|
2075
|
+
},
|
|
2076
|
+
signal
|
|
1456
2077
|
);
|
|
1457
|
-
if (
|
|
1458
|
-
|
|
2078
|
+
if (context) context.bindingSaved = outcome.saved;
|
|
2079
|
+
if (!outcome.saved) {
|
|
2080
|
+
debugLog("[LedgerAdapter] BLE binding not persisted by host", {
|
|
2081
|
+
connectId,
|
|
2082
|
+
reason: outcome.reason
|
|
2083
|
+
});
|
|
1459
2084
|
}
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
2085
|
+
} catch (error) {
|
|
2086
|
+
await this._dropSession(connectId, signal);
|
|
2087
|
+
throw error;
|
|
2088
|
+
} finally {
|
|
2089
|
+
if (this._bindingSelectionRequestId === selectionRequestId) {
|
|
2090
|
+
this._bindingSelectionRequestId = void 0;
|
|
1465
2091
|
}
|
|
1466
|
-
throw err;
|
|
1467
2092
|
}
|
|
1468
2093
|
}
|
|
2094
|
+
async _dropSession(connectId, signal) {
|
|
2095
|
+
const sessionId = this._sessions.get(connectId);
|
|
2096
|
+
this._sessions.delete(connectId);
|
|
2097
|
+
if (!sessionId) return;
|
|
2098
|
+
this._sessionTransports.delete(sessionId);
|
|
2099
|
+
const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
|
|
2100
|
+
() => void 0
|
|
2101
|
+
);
|
|
2102
|
+
if (!signal.aborted) await teardown;
|
|
2103
|
+
}
|
|
2104
|
+
/** Verify on the acquired session without re-entering the job queue. */
|
|
2105
|
+
async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
|
|
2106
|
+
if (!deviceId) return { success: true };
|
|
2107
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
2108
|
+
chain,
|
|
2109
|
+
(method, params) => this._callConnector(sessionId, method, params)
|
|
2110
|
+
);
|
|
2111
|
+
if (fingerprint === deviceId) {
|
|
2112
|
+
return { success: true };
|
|
2113
|
+
}
|
|
2114
|
+
return { success: false, expected: deviceId, actual: fingerprint };
|
|
2115
|
+
}
|
|
1469
2116
|
/**
|
|
1470
2117
|
* Compute the chain fingerprint via a caller-supplied call strategy.
|
|
1471
2118
|
*
|
|
@@ -1485,7 +2132,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1485
2132
|
const result = await callMethod("btcGetMasterFingerprint", {});
|
|
1486
2133
|
return result.masterFingerprint;
|
|
1487
2134
|
}
|
|
1488
|
-
const path =
|
|
2135
|
+
const path = import_hwk_adapter_core4.CHAIN_FINGERPRINT_PATHS[chain];
|
|
1489
2136
|
let address;
|
|
1490
2137
|
if (chain === "evm") {
|
|
1491
2138
|
address = (await callMethod("evmGetAddress", { path, showOnDevice: false })).address.toLowerCase();
|
|
@@ -1493,10 +2140,19 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1493
2140
|
address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
|
|
1494
2141
|
} else if (chain === "tron") {
|
|
1495
2142
|
address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
|
|
2143
|
+
} else if (chain === "zcash") {
|
|
2144
|
+
address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
|
|
1496
2145
|
} else {
|
|
1497
2146
|
throw new Error(`Unsupported chain for fingerprint: ${chain}`);
|
|
1498
2147
|
}
|
|
1499
|
-
return (0,
|
|
2148
|
+
return (0, import_hwk_adapter_core4.deriveDeviceFingerprint)(address);
|
|
2149
|
+
}
|
|
2150
|
+
/**
|
|
2151
|
+
* Operation owning the running job, so a mid-call UI request can name it.
|
|
2152
|
+
* Undefined at cold start when no operation owns the job.
|
|
2153
|
+
*/
|
|
2154
|
+
_activeOperationId() {
|
|
2155
|
+
return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
|
|
1500
2156
|
}
|
|
1501
2157
|
// Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
|
|
1502
2158
|
// The user must press Confirm after unlocking, which triggers a search retry.
|
|
@@ -1507,22 +2163,25 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1507
2163
|
if (signal?.aborted) {
|
|
1508
2164
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1509
2165
|
}
|
|
2166
|
+
const operationId = this._activeOperationId();
|
|
1510
2167
|
const waitPromise = this._uiRegistry.wait(
|
|
1511
|
-
|
|
2168
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
2169
|
+
{ operationId }
|
|
1512
2170
|
);
|
|
1513
|
-
this.emitter.emit(
|
|
1514
|
-
type:
|
|
2171
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT, {
|
|
2172
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
1515
2173
|
payload: {
|
|
1516
2174
|
vendor: "ledger",
|
|
1517
2175
|
reason: "device-not-found",
|
|
1518
|
-
message: "Please connect and unlock your Ledger device"
|
|
2176
|
+
message: "Please connect and unlock your Ledger device",
|
|
2177
|
+
operationId
|
|
1519
2178
|
}
|
|
1520
2179
|
});
|
|
1521
2180
|
let payload;
|
|
1522
2181
|
try {
|
|
1523
2182
|
if (signal) {
|
|
1524
2183
|
const onAbort = () => {
|
|
1525
|
-
this._uiRegistry.cancel(
|
|
2184
|
+
this._uiRegistry.cancel(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT);
|
|
1526
2185
|
};
|
|
1527
2186
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
1528
2187
|
try {
|
|
@@ -1534,20 +2193,20 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1534
2193
|
payload = await waitPromise;
|
|
1535
2194
|
}
|
|
1536
2195
|
} catch (err) {
|
|
1537
|
-
this.emitter.emit(
|
|
1538
|
-
type:
|
|
2196
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2197
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1539
2198
|
payload: {}
|
|
1540
2199
|
});
|
|
1541
2200
|
throw Object.assign(new Error("User cancelled Ledger connection"), {
|
|
1542
2201
|
_tag: ERROR_TAG.UserAborted,
|
|
1543
|
-
code:
|
|
2202
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1544
2203
|
cause: err
|
|
1545
2204
|
});
|
|
1546
2205
|
}
|
|
1547
2206
|
if (!payload?.confirmed) {
|
|
1548
2207
|
throw Object.assign(new Error("User cancelled Ledger connection"), {
|
|
1549
2208
|
_tag: ERROR_TAG.UserAborted,
|
|
1550
|
-
code:
|
|
2209
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1551
2210
|
});
|
|
1552
2211
|
}
|
|
1553
2212
|
await new Promise((resolve) => {
|
|
@@ -1561,7 +2220,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1561
2220
|
* Returns the params to pass through (with `showOnDevice` possibly
|
|
1562
2221
|
* promoted), or `null` if the user declined.
|
|
1563
2222
|
*/
|
|
1564
|
-
async _gateBtcHighIndex(params) {
|
|
2223
|
+
async _gateBtcHighIndex(params, signal) {
|
|
1565
2224
|
const accountIndex = btcAccountIndexFromPath(params.path);
|
|
1566
2225
|
if (params.showOnDevice) return params;
|
|
1567
2226
|
if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
|
|
@@ -1570,50 +2229,74 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1570
2229
|
if (this._btcHighIndexConfirmedThisSession) {
|
|
1571
2230
|
return { ...params, showOnDevice: true };
|
|
1572
2231
|
}
|
|
1573
|
-
const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
|
|
2232
|
+
const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
|
|
1574
2233
|
if (!confirmed) return null;
|
|
1575
2234
|
this._btcHighIndexConfirmedThisSession = true;
|
|
1576
2235
|
return { ...params, showOnDevice: true };
|
|
1577
2236
|
}
|
|
1578
|
-
async _waitForBtcHighIndexConfirm(path, accountIndex) {
|
|
2237
|
+
async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
|
|
2238
|
+
const operationId = this._activeOperationId();
|
|
1579
2239
|
const waitPromise = this._uiRegistry.wait(
|
|
1580
|
-
|
|
2240
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2241
|
+
{ operationId }
|
|
1581
2242
|
);
|
|
1582
|
-
this.emitter.emit(
|
|
1583
|
-
type:
|
|
2243
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
|
|
2244
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
1584
2245
|
payload: {
|
|
1585
2246
|
vendor: "ledger",
|
|
1586
2247
|
path,
|
|
1587
|
-
accountIndex
|
|
2248
|
+
accountIndex,
|
|
2249
|
+
operationId
|
|
1588
2250
|
}
|
|
1589
2251
|
});
|
|
1590
2252
|
try {
|
|
1591
|
-
const payload = await
|
|
2253
|
+
const payload = await this._awaitUiAnswer(
|
|
2254
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2255
|
+
waitPromise,
|
|
2256
|
+
signal
|
|
2257
|
+
);
|
|
1592
2258
|
return !!payload?.confirmed;
|
|
1593
2259
|
} catch (err) {
|
|
1594
|
-
this.emitter.emit(
|
|
1595
|
-
type:
|
|
2260
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2261
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1596
2262
|
payload: {}
|
|
1597
2263
|
});
|
|
1598
2264
|
return false;
|
|
1599
2265
|
}
|
|
1600
2266
|
}
|
|
2267
|
+
/** A cancel of the job ends its open prompt, even when no operation names that prompt. */
|
|
2268
|
+
async _awaitUiAnswer(requestType, waitPromise, signal) {
|
|
2269
|
+
const onAbort = () => this._uiRegistry.cancel(requestType);
|
|
2270
|
+
if (signal.aborted) onAbort();
|
|
2271
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2272
|
+
try {
|
|
2273
|
+
return await waitPromise;
|
|
2274
|
+
} finally {
|
|
2275
|
+
signal.removeEventListener("abort", onAbort);
|
|
2276
|
+
}
|
|
2277
|
+
}
|
|
1601
2278
|
// Ask the user whether to install a missing app (autoInstallApp flow).
|
|
1602
2279
|
// Same register-then-emit ordering as the BTC high-index gate.
|
|
1603
|
-
async _waitForInstallAppConfirm(appName) {
|
|
2280
|
+
async _waitForInstallAppConfirm(appName, signal) {
|
|
2281
|
+
const operationId = this._activeOperationId();
|
|
1604
2282
|
const waitPromise = this._uiRegistry.wait(
|
|
1605
|
-
|
|
2283
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2284
|
+
{ operationId }
|
|
1606
2285
|
);
|
|
1607
|
-
this.emitter.emit(
|
|
1608
|
-
type:
|
|
1609
|
-
payload: { vendor: "ledger", appName }
|
|
2286
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP, {
|
|
2287
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2288
|
+
payload: { vendor: "ledger", appName, operationId }
|
|
1610
2289
|
});
|
|
1611
2290
|
try {
|
|
1612
|
-
const payload = await
|
|
2291
|
+
const payload = await this._awaitUiAnswer(
|
|
2292
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2293
|
+
waitPromise,
|
|
2294
|
+
signal
|
|
2295
|
+
);
|
|
1613
2296
|
return !!payload?.confirmed;
|
|
1614
2297
|
} catch (err) {
|
|
1615
|
-
this.emitter.emit(
|
|
1616
|
-
type:
|
|
2298
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2299
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1617
2300
|
payload: {}
|
|
1618
2301
|
});
|
|
1619
2302
|
return false;
|
|
@@ -1622,34 +2305,44 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1622
2305
|
// Layer 1 entry. Caller signal only races the outer awaiter; the shared
|
|
1623
2306
|
// `_doConnect` runs under its own internal controller so caller A's cancel
|
|
1624
2307
|
// doesn't kill caller B's await.
|
|
1625
|
-
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
|
|
2308
|
+
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
1626
2309
|
if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
|
|
1627
|
-
|
|
2310
|
+
this._assertConnectorReady("connectDevice");
|
|
2311
|
+
if (this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
|
|
1628
2312
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1629
|
-
code:
|
|
2313
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
1630
2314
|
});
|
|
1631
2315
|
}
|
|
1632
2316
|
if (connectId && this._sessions.has(connectId)) return connectId;
|
|
1633
2317
|
if (!connectId && this._sessions.size > 0) {
|
|
1634
|
-
if (!
|
|
2318
|
+
if (!this._isBleConnection() && this._sessions.size > 1) {
|
|
1635
2319
|
throw Object.assign(
|
|
1636
2320
|
new Error(
|
|
1637
2321
|
"Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
|
|
1638
2322
|
),
|
|
1639
|
-
{ code:
|
|
2323
|
+
{ code: import_hwk_adapter_core4.HardwareErrorCode.DeviceOneDeviceOnly }
|
|
1640
2324
|
);
|
|
1641
2325
|
}
|
|
1642
2326
|
return this._sessions.keys().next().value;
|
|
1643
2327
|
}
|
|
1644
|
-
if (!this._connectingPromise) {
|
|
1645
|
-
|
|
1646
|
-
|
|
2328
|
+
if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
|
|
2329
|
+
const controller = new AbortController();
|
|
2330
|
+
this._doConnectAbortController = controller;
|
|
2331
|
+
const innerSignal = controller.signal;
|
|
1647
2332
|
this._connectingPromise = (async () => {
|
|
1648
2333
|
try {
|
|
1649
|
-
return await this._doConnect(
|
|
2334
|
+
return await this._doConnect(
|
|
2335
|
+
innerSignal,
|
|
2336
|
+
connectId,
|
|
2337
|
+
allowUsbEphemeralFallback,
|
|
2338
|
+
preserveOperationId,
|
|
2339
|
+
context
|
|
2340
|
+
);
|
|
1650
2341
|
} finally {
|
|
1651
|
-
this.
|
|
1652
|
-
|
|
2342
|
+
if (this._doConnectAbortController === controller) {
|
|
2343
|
+
this._connectingPromise = null;
|
|
2344
|
+
this._doConnectAbortController = null;
|
|
2345
|
+
}
|
|
1653
2346
|
}
|
|
1654
2347
|
})();
|
|
1655
2348
|
}
|
|
@@ -1658,45 +2351,86 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1658
2351
|
// Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
|
|
1659
2352
|
// Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
|
|
1660
2353
|
// 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
|
-
|
|
2354
|
+
async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
2355
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2356
|
+
if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
|
|
2357
|
+
this._activeConnectionType = "usb";
|
|
2358
|
+
const usbDevices = context?.supportedTransports && !context.supportedTransports.includes("usb") ? [] : await this._searchDevices({ transportType: "usb" }, internalSignal);
|
|
2359
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2360
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2361
|
+
(connection) => connection.transport === "usb"
|
|
2362
|
+
);
|
|
2363
|
+
const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
|
|
2364
|
+
if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback)) {
|
|
2365
|
+
return this._connectFirstOrSelect(
|
|
2366
|
+
usbDevices,
|
|
2367
|
+
usbTarget,
|
|
2368
|
+
allowUsbEphemeralFallback,
|
|
2369
|
+
preserveOperationId,
|
|
2370
|
+
context,
|
|
2371
|
+
internalSignal
|
|
2372
|
+
);
|
|
2373
|
+
}
|
|
2374
|
+
if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
|
|
2375
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2376
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
2377
|
+
message: "This Ledger model has no Bluetooth transport; connect it over USB"
|
|
2378
|
+
});
|
|
2379
|
+
}
|
|
2380
|
+
this._activeConnectionType = "ble";
|
|
2381
|
+
const knownBle = context?.knownConnections?.find(
|
|
2382
|
+
(connection) => connection.transport === "ble"
|
|
2383
|
+
);
|
|
2384
|
+
if (knownBle?.transport === "ble") {
|
|
2385
|
+
return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
|
|
2386
|
+
}
|
|
2387
|
+
if (targetConnectId && context?.knownConnections === void 0) {
|
|
2388
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2389
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
2390
|
+
message: "Ledger connection metadata is required before starting Bluetooth binding"
|
|
2391
|
+
});
|
|
1676
2392
|
}
|
|
2393
|
+
const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
|
|
2394
|
+
return this._connectFirstOrSelect(
|
|
2395
|
+
bleDevices,
|
|
2396
|
+
void 0,
|
|
2397
|
+
allowUsbEphemeralFallback,
|
|
2398
|
+
preserveOperationId,
|
|
2399
|
+
context,
|
|
2400
|
+
internalSignal
|
|
2401
|
+
);
|
|
2402
|
+
}
|
|
2403
|
+
if (this._isBleConnection() && targetConnectId) {
|
|
2404
|
+
return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
|
|
1677
2405
|
}
|
|
1678
2406
|
let confirms = 0;
|
|
1679
2407
|
while (!internalSignal.aborted) {
|
|
1680
2408
|
this.emitter.emit("ui-event", {
|
|
1681
|
-
type:
|
|
2409
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.Searching,
|
|
1682
2410
|
payload: { sessionId: "" }
|
|
1683
2411
|
});
|
|
1684
|
-
let devices = await this.
|
|
2412
|
+
let devices = await this._searchDevices(void 0, internalSignal);
|
|
2413
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1685
2414
|
if (devices.length === 0) {
|
|
1686
2415
|
for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
|
|
1687
2416
|
await new Promise((resolve) => {
|
|
1688
|
-
setTimeout(resolve,
|
|
2417
|
+
setTimeout(resolve, import_hwk_adapter_core4.DEVICE_CONNECT_RETRY_DELAY_MS);
|
|
1689
2418
|
});
|
|
1690
|
-
|
|
2419
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2420
|
+
devices = await this._searchDevices(void 0, internalSignal);
|
|
2421
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1691
2422
|
if (devices.length > 0) break;
|
|
1692
2423
|
}
|
|
1693
2424
|
}
|
|
1694
|
-
if (devices.length > 0) {
|
|
2425
|
+
if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
|
|
1695
2426
|
try {
|
|
1696
2427
|
return await this._connectFirstOrSelect(
|
|
1697
2428
|
devices,
|
|
1698
2429
|
targetConnectId,
|
|
1699
|
-
allowUsbEphemeralFallback
|
|
2430
|
+
allowUsbEphemeralFallback,
|
|
2431
|
+
preserveOperationId,
|
|
2432
|
+
context,
|
|
2433
|
+
internalSignal
|
|
1700
2434
|
);
|
|
1701
2435
|
} catch (err) {
|
|
1702
2436
|
if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
|
|
@@ -1716,7 +2450,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1716
2450
|
new Error(
|
|
1717
2451
|
"Device not connected after multiple attempts. Please ensure your Ledger is awake, unlocked, and in range, then try again."
|
|
1718
2452
|
),
|
|
1719
|
-
{ code:
|
|
2453
|
+
{ code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound }
|
|
1720
2454
|
);
|
|
1721
2455
|
}
|
|
1722
2456
|
await this._waitForDeviceConnect(internalSignal);
|
|
@@ -1725,45 +2459,147 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1725
2459
|
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1726
2460
|
throw new Error("_doConnect aborted");
|
|
1727
2461
|
}
|
|
1728
|
-
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback
|
|
2462
|
+
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
|
|
2463
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1729
2464
|
if (targetConnectId) {
|
|
1730
2465
|
const target = devices.find(
|
|
1731
2466
|
(d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
|
|
1732
2467
|
);
|
|
1733
2468
|
if (target) {
|
|
1734
|
-
return this._connectDeviceOrThrow(target.connectId);
|
|
2469
|
+
return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
|
|
1735
2470
|
}
|
|
1736
|
-
if (!
|
|
2471
|
+
if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
|
|
1737
2472
|
debugLog(
|
|
1738
2473
|
`[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
|
|
1739
2474
|
);
|
|
1740
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2475
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1741
2476
|
}
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
2477
|
+
if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
|
|
2478
|
+
const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
|
|
2479
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
2480
|
+
});
|
|
2481
|
+
if (this._isBleConnection()) {
|
|
2482
|
+
err._tag = ERROR_TAG.DeviceNotAdvertising;
|
|
2483
|
+
}
|
|
2484
|
+
throw err;
|
|
1747
2485
|
}
|
|
1748
|
-
throw err;
|
|
1749
2486
|
}
|
|
1750
|
-
|
|
2487
|
+
const requiresBleSelection = this._isBleConnection();
|
|
2488
|
+
if (requiresBleSelection && !allowUsbEphemeralFallback) {
|
|
1751
2489
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1752
|
-
code:
|
|
2490
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
2491
|
+
});
|
|
2492
|
+
}
|
|
2493
|
+
if (requiresBleSelection && context?.allowDeviceSelection !== false) {
|
|
2494
|
+
const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
|
|
2495
|
+
if (context) context.bindingSessionId = bindingSessionId;
|
|
2496
|
+
const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb")) && (!context?.supportedTransports || context.supportedTransports.includes("usb"));
|
|
2497
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2498
|
+
(connection) => connection.transport === "usb"
|
|
2499
|
+
);
|
|
2500
|
+
const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : targetConnectId;
|
|
2501
|
+
const { device, requestId } = await (0, import_hwk_adapter_core4.requestBleDeviceSelection)({
|
|
2502
|
+
emitter: this.emitter,
|
|
2503
|
+
registry: this._uiRegistry,
|
|
2504
|
+
signal,
|
|
2505
|
+
allowUsbFallback,
|
|
2506
|
+
scan: async () => {
|
|
2507
|
+
if (allowUsbFallback) {
|
|
2508
|
+
const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
|
|
2509
|
+
const candidate = usbDevices.find(
|
|
2510
|
+
(device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
|
|
2511
|
+
) ?? (usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
|
|
2512
|
+
if (candidate) return [candidate];
|
|
2513
|
+
}
|
|
2514
|
+
return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
|
|
2515
|
+
},
|
|
2516
|
+
request: {
|
|
2517
|
+
devices,
|
|
2518
|
+
bindingSessionId,
|
|
2519
|
+
context: {
|
|
2520
|
+
kind: "bind-connection",
|
|
2521
|
+
transport: "ble",
|
|
2522
|
+
reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
|
|
2523
|
+
},
|
|
2524
|
+
extra: context?.extra,
|
|
2525
|
+
operationId: preserveOperationId
|
|
2526
|
+
}
|
|
1753
2527
|
});
|
|
2528
|
+
if (device.connectionType === "usb") {
|
|
2529
|
+
this._activeConnectionType = "usb";
|
|
2530
|
+
if (context) context.selectedConnection = void 0;
|
|
2531
|
+
this._bindingSelectionRequestId = requestId;
|
|
2532
|
+
this._finishBleBinding("cancelled");
|
|
2533
|
+
return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
|
|
2534
|
+
}
|
|
2535
|
+
this._bindingSelectionRequestId = requestId;
|
|
2536
|
+
const connected = await this._connectDeviceOrThrow(
|
|
2537
|
+
device.connectId,
|
|
2538
|
+
preserveOperationId,
|
|
2539
|
+
signal
|
|
2540
|
+
);
|
|
2541
|
+
if (context) context.selectedConnection = { connectId: connected, requestId };
|
|
2542
|
+
if (context?.deferBindingSave) {
|
|
2543
|
+
context.pendingBinding = { connectId: connected, requestId };
|
|
2544
|
+
} else {
|
|
2545
|
+
await this._saveSelectedBleBinding(
|
|
2546
|
+
connected,
|
|
2547
|
+
requestId,
|
|
2548
|
+
context,
|
|
2549
|
+
preserveOperationId,
|
|
2550
|
+
signal
|
|
2551
|
+
);
|
|
2552
|
+
}
|
|
2553
|
+
return connected;
|
|
1754
2554
|
}
|
|
1755
|
-
if (devices.length > 1) {
|
|
1756
|
-
|
|
2555
|
+
if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
|
|
2556
|
+
if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE)) {
|
|
2557
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2558
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
2559
|
+
message: "Select a Ledger device before continuing"
|
|
2560
|
+
});
|
|
2561
|
+
}
|
|
2562
|
+
const requestId = this._uiRegistry.createRequestId();
|
|
2563
|
+
const operationId = this._activeOperationId();
|
|
2564
|
+
const waitPromise = this._uiRegistry.wait(
|
|
2565
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2566
|
+
{ requestId, operationId }
|
|
2567
|
+
);
|
|
2568
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE, {
|
|
2569
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2570
|
+
payload: {
|
|
2571
|
+
devices,
|
|
2572
|
+
requestId,
|
|
2573
|
+
operationId,
|
|
2574
|
+
context: requiresBleSelection ? {
|
|
2575
|
+
kind: "bind-connection",
|
|
2576
|
+
transport: "ble",
|
|
2577
|
+
reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
|
|
2578
|
+
} : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
|
|
2579
|
+
extra: context?.extra
|
|
2580
|
+
}
|
|
2581
|
+
});
|
|
2582
|
+
const { sdkConnectId } = await this._abortable(signal, waitPromise);
|
|
2583
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
2584
|
+
const selected = devices.find((device) => device.connectId === sdkConnectId);
|
|
2585
|
+
if (!selected) {
|
|
2586
|
+
throw Object.assign(new Error("Selected Ledger is no longer available"), {
|
|
2587
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
2588
|
+
});
|
|
2589
|
+
}
|
|
2590
|
+
if (context && requiresBleSelection)
|
|
2591
|
+
context.selectedConnection = { connectId: selected.connectId, requestId };
|
|
2592
|
+
return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
|
|
1757
2593
|
}
|
|
1758
2594
|
if (devices.length !== 1) {
|
|
1759
2595
|
throw Object.assign(new Error("Ledger device not found."), {
|
|
1760
|
-
code:
|
|
2596
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
1761
2597
|
});
|
|
1762
2598
|
}
|
|
1763
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2599
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1764
2600
|
}
|
|
1765
|
-
async _connectDeviceOrThrow(chosenConnectId) {
|
|
1766
|
-
const result = await this.
|
|
2601
|
+
async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
|
|
2602
|
+
const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
|
|
1767
2603
|
if (!result.success) {
|
|
1768
2604
|
const payload = result.payload;
|
|
1769
2605
|
const rethrow = Object.assign(new Error(payload.error), {
|
|
@@ -1774,16 +2610,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1774
2610
|
}
|
|
1775
2611
|
throw rethrow;
|
|
1776
2612
|
}
|
|
1777
|
-
return
|
|
2613
|
+
return result.payload;
|
|
1778
2614
|
}
|
|
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
2615
|
/**
|
|
1788
2616
|
* Unwrap a `ConnectorCallResult` back into the throw-based control flow this
|
|
1789
2617
|
* class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
|
|
@@ -1795,7 +2623,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1795
2623
|
*/
|
|
1796
2624
|
_unwrapConnectorResult(result) {
|
|
1797
2625
|
if (result.success) return result.payload;
|
|
1798
|
-
throw (0,
|
|
2626
|
+
throw (0, import_hwk_adapter_core4.rehydrateConnectorError)(result.error);
|
|
1799
2627
|
}
|
|
1800
2628
|
/**
|
|
1801
2629
|
* `connector.call` + result unwrap, optionally raced against an abort
|
|
@@ -1804,33 +2632,145 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1804
2632
|
* lives in one place.
|
|
1805
2633
|
*/
|
|
1806
2634
|
async _callConnector(sessionId, method, params, signal) {
|
|
1807
|
-
|
|
2635
|
+
this._assertConnectorReady(method);
|
|
2636
|
+
if (signal?.aborted) throw this._abortReason(signal);
|
|
2637
|
+
const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
|
|
2638
|
+
let promise;
|
|
2639
|
+
try {
|
|
2640
|
+
promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
|
|
2641
|
+
} catch (error) {
|
|
2642
|
+
releaseOperation();
|
|
2643
|
+
throw error;
|
|
2644
|
+
}
|
|
1808
2645
|
const result = signal ? await this._abortable(signal, promise) : await promise;
|
|
1809
2646
|
return this._unwrapConnectorResult(result);
|
|
1810
2647
|
}
|
|
2648
|
+
_assertConnectorReady(method) {
|
|
2649
|
+
if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
|
|
2650
|
+
throw _LedgerAdapter._createDeviceBusyError(method);
|
|
2651
|
+
}
|
|
2652
|
+
}
|
|
2653
|
+
_runConnectorTeardown(task) {
|
|
2654
|
+
const previous = this._connectorTeardownTail;
|
|
2655
|
+
let releaseTail = () => void 0;
|
|
2656
|
+
this._connectorTeardownTail = new Promise((resolve) => {
|
|
2657
|
+
releaseTail = resolve;
|
|
2658
|
+
});
|
|
2659
|
+
this._pendingConnectorTeardowns += 1;
|
|
2660
|
+
return (async () => {
|
|
2661
|
+
try {
|
|
2662
|
+
await previous;
|
|
2663
|
+
await this._waitForConnectorOperationsToDrain();
|
|
2664
|
+
await task();
|
|
2665
|
+
} finally {
|
|
2666
|
+
this._pendingConnectorTeardowns -= 1;
|
|
2667
|
+
releaseTail();
|
|
2668
|
+
}
|
|
2669
|
+
})();
|
|
2670
|
+
}
|
|
2671
|
+
_waitForConnectorOperationsToDrain() {
|
|
2672
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2673
|
+
return Promise.resolve();
|
|
2674
|
+
}
|
|
2675
|
+
return new Promise((resolve) => {
|
|
2676
|
+
this._connectorIdleWaiters.add(resolve);
|
|
2677
|
+
});
|
|
2678
|
+
}
|
|
2679
|
+
_retainConnectorOperation(key) {
|
|
2680
|
+
this._unsettledConnectorOperations.set(
|
|
2681
|
+
key,
|
|
2682
|
+
(this._unsettledConnectorOperations.get(key) ?? 0) + 1
|
|
2683
|
+
);
|
|
2684
|
+
let released = false;
|
|
2685
|
+
return () => {
|
|
2686
|
+
if (released) return;
|
|
2687
|
+
released = true;
|
|
2688
|
+
const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
|
|
2689
|
+
if (remaining > 0) {
|
|
2690
|
+
this._unsettledConnectorOperations.set(key, remaining);
|
|
2691
|
+
} else {
|
|
2692
|
+
this._unsettledConnectorOperations.delete(key);
|
|
2693
|
+
}
|
|
2694
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2695
|
+
for (const resolve of this._connectorIdleWaiters) resolve();
|
|
2696
|
+
this._connectorIdleWaiters.clear();
|
|
2697
|
+
}
|
|
2698
|
+
};
|
|
2699
|
+
}
|
|
1811
2700
|
async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
1812
|
-
|
|
1813
|
-
|
|
2701
|
+
const positionalOperationId = (0, import_hwk_adapter_core4.isHardwareOperationId)(connectId) ? connectId : void 0;
|
|
2702
|
+
if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
|
|
2703
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2704
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.InvalidParams,
|
|
2705
|
+
message: "Conflicting Ledger operation ids",
|
|
2706
|
+
params: {
|
|
2707
|
+
positionalOperationId,
|
|
2708
|
+
commonOperationId: commonParams.operationId
|
|
2709
|
+
}
|
|
2710
|
+
});
|
|
2711
|
+
}
|
|
2712
|
+
const operationId = commonParams?.operationId ?? positionalOperationId;
|
|
2713
|
+
const operation = operationId ? this._operations.resolve(operationId) : void 0;
|
|
2714
|
+
const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
|
|
2715
|
+
const effectiveConnectId = operation?.connectId ?? connectId;
|
|
2716
|
+
debugLog("[LedgerAdapter][REQ]", {
|
|
2717
|
+
method,
|
|
2718
|
+
connectId: effectiveConnectId || "(empty)",
|
|
2719
|
+
params: summarizeForLog(params, { method })
|
|
2720
|
+
});
|
|
2721
|
+
const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
|
|
1814
2722
|
try {
|
|
1815
2723
|
const result = await this._jobQueue.enqueue(
|
|
1816
2724
|
queueKey,
|
|
1817
|
-
async (signal) =>
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
2725
|
+
async (signal) => {
|
|
2726
|
+
if (operationId) this._activeOperationJobs.add(operationId);
|
|
2727
|
+
try {
|
|
2728
|
+
return await this._runConnectorCall(
|
|
2729
|
+
effectiveConnectId,
|
|
2730
|
+
method,
|
|
2731
|
+
params,
|
|
2732
|
+
signal,
|
|
2733
|
+
fingerprint,
|
|
2734
|
+
permissionDeviceId,
|
|
2735
|
+
commonParams,
|
|
2736
|
+
installContext ?? {},
|
|
2737
|
+
operationId
|
|
2738
|
+
);
|
|
2739
|
+
} catch (error) {
|
|
2740
|
+
const status = signal.aborted ? "cancelled" : "failed";
|
|
2741
|
+
const bundleConnectId = installContext?.connection?.connectId;
|
|
2742
|
+
let keptBundlePick = false;
|
|
2743
|
+
for (const [pickedConnectId, owner] of this._pendingPickBindings) {
|
|
2744
|
+
if (pickedConnectId === bundleConnectId) {
|
|
2745
|
+
keptBundlePick = true;
|
|
2746
|
+
} else {
|
|
2747
|
+
this._pendingPickBindings.delete(pickedConnectId);
|
|
2748
|
+
this._discardPendingBinding(owner, status);
|
|
2749
|
+
await this._dropSession(pickedConnectId, signal);
|
|
2750
|
+
}
|
|
2751
|
+
}
|
|
2752
|
+
if (!keptBundlePick) this._finishBleBinding(status);
|
|
2753
|
+
throw error;
|
|
2754
|
+
} finally {
|
|
2755
|
+
if (operationId) {
|
|
2756
|
+
this._activeOperationJobs.delete(operationId);
|
|
2757
|
+
if (this._pendingOperationDisconnects.delete(operationId)) {
|
|
2758
|
+
await this._releaseLostOperationConnection(operationId);
|
|
2759
|
+
}
|
|
2760
|
+
}
|
|
2761
|
+
}
|
|
2762
|
+
},
|
|
1827
2763
|
{
|
|
1828
2764
|
label: method,
|
|
1829
2765
|
rejectIfBusy: true,
|
|
1830
2766
|
busyError: _LedgerAdapter._createDeviceBusyError(method)
|
|
1831
2767
|
}
|
|
1832
2768
|
);
|
|
1833
|
-
debugLog("[LedgerAdapter][RES]", {
|
|
2769
|
+
debugLog("[LedgerAdapter][RES]", {
|
|
2770
|
+
method,
|
|
2771
|
+
success: true,
|
|
2772
|
+
payload: summarizeForLog(result, { method, role: "result" })
|
|
2773
|
+
});
|
|
1834
2774
|
return result;
|
|
1835
2775
|
} catch (err) {
|
|
1836
2776
|
const e = err;
|
|
@@ -1844,15 +2784,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1844
2784
|
}
|
|
1845
2785
|
});
|
|
1846
2786
|
throw err;
|
|
2787
|
+
} finally {
|
|
2788
|
+
releaseOperationRetention?.();
|
|
1847
2789
|
}
|
|
1848
2790
|
}
|
|
2791
|
+
/** Hermes/RN polyfills don't always populate signal.reason; fall back. */
|
|
2792
|
+
_abortReason(signal) {
|
|
2793
|
+
return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
|
|
2794
|
+
}
|
|
1849
2795
|
/**
|
|
1850
2796
|
* Race a promise against an abort signal. On abort, rejects with
|
|
1851
2797
|
* signal.reason → instance _lastCancelReason → generic Error('Aborted').
|
|
1852
2798
|
*/
|
|
1853
2799
|
_abortable(signal, promise) {
|
|
1854
|
-
const getAbortReason = () =>
|
|
2800
|
+
const getAbortReason = () => this._abortReason(signal);
|
|
1855
2801
|
if (signal.aborted) {
|
|
2802
|
+
void promise.catch(() => void 0);
|
|
1856
2803
|
return Promise.reject(getAbortReason());
|
|
1857
2804
|
}
|
|
1858
2805
|
return new Promise((resolve, reject) => {
|
|
@@ -1879,39 +2826,89 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1879
2826
|
}
|
|
1880
2827
|
}
|
|
1881
2828
|
/** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
|
|
1882
|
-
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
2829
|
+
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
|
|
1883
2830
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
2831
|
+
if (!operationId) {
|
|
2832
|
+
await this._ensureDevicePermission(
|
|
2833
|
+
connectId,
|
|
2834
|
+
permissionDeviceId ?? fingerprint?.deviceId,
|
|
2835
|
+
signal
|
|
2836
|
+
);
|
|
2837
|
+
}
|
|
1889
2838
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1890
2839
|
let effectiveParams = params;
|
|
1891
2840
|
if (method === "btcGetPublicKey") {
|
|
1892
|
-
const gatedParams = await this._gateBtcHighIndex(params);
|
|
2841
|
+
const gatedParams = await this._gateBtcHighIndex(params, signal);
|
|
1893
2842
|
if (gatedParams === null) {
|
|
1894
2843
|
throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
|
|
1895
2844
|
_tag: ERROR_TAG.UserAborted,
|
|
1896
|
-
code:
|
|
2845
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1897
2846
|
});
|
|
1898
2847
|
}
|
|
1899
2848
|
effectiveParams = gatedParams;
|
|
1900
2849
|
}
|
|
1901
2850
|
const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
|
|
1902
|
-
|
|
1903
|
-
|
|
2851
|
+
let businessCallStarted = false;
|
|
2852
|
+
const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
|
|
2853
|
+
const knownTransport = this._isBleConnection() ? "ble" : "usb";
|
|
2854
|
+
const hintedConnectId = commonParams?.knownConnections?.find(
|
|
2855
|
+
(connection) => connection.transport === knownTransport
|
|
2856
|
+
);
|
|
2857
|
+
const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
|
|
2858
|
+
const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
|
|
2859
|
+
const checksWallet = Boolean(
|
|
2860
|
+
fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId
|
|
2861
|
+
);
|
|
2862
|
+
const connectionAttempt = {
|
|
2863
|
+
...commonParams,
|
|
2864
|
+
deferBindingSave: checksWallet
|
|
2865
|
+
};
|
|
2866
|
+
const bundleConnection = installContext?.connection;
|
|
2867
|
+
if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
|
|
2868
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2869
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
2870
|
+
message: "Ledger all-network connection ended"
|
|
2871
|
+
});
|
|
2872
|
+
}
|
|
2873
|
+
const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
|
|
2874
|
+
preferredConnectId,
|
|
1904
2875
|
signal,
|
|
1905
|
-
allowUsbEphemeralFallback
|
|
2876
|
+
allowUsbEphemeralFallback,
|
|
2877
|
+
void 0,
|
|
2878
|
+
connectionAttempt
|
|
1906
2879
|
);
|
|
2880
|
+
const walletCheck = installContext?.walletCheck;
|
|
2881
|
+
if (walletCheck && !checksWallet && (walletCheck.verified === false || walletCheck.expected && !walletCheck.verified)) {
|
|
2882
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2883
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
2884
|
+
message: "Ledger wallet is not verified on this connection; refusing to derive an unverifiable address"
|
|
2885
|
+
});
|
|
2886
|
+
}
|
|
1907
2887
|
const sessionId = this._sessions.get(resolvedConnectId);
|
|
2888
|
+
if (sessionId && installContext && !installContext.connection) {
|
|
2889
|
+
installContext.connection = { connectId: resolvedConnectId, sessionId };
|
|
2890
|
+
}
|
|
1908
2891
|
if (!sessionId) {
|
|
2892
|
+
if (operationId) {
|
|
2893
|
+
this._operations.end(operationId, "disconnect");
|
|
2894
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2895
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.OperationEnded,
|
|
2896
|
+
message: "Ledger operation connection is no longer active",
|
|
2897
|
+
params: { operationId, reason: "disconnect" }
|
|
2898
|
+
});
|
|
2899
|
+
}
|
|
1909
2900
|
throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
|
|
1910
2901
|
_tag: ERROR_TAG.DeviceSessionNotFound
|
|
1911
2902
|
});
|
|
1912
2903
|
}
|
|
1913
2904
|
try {
|
|
1914
|
-
|
|
2905
|
+
const isBleSession = this._sessionTransports.get(sessionId) === "ble";
|
|
2906
|
+
if (!operationId && connectionAttempt.pendingBinding) {
|
|
2907
|
+
this._pendingPickBindings.set(resolvedConnectId, connectionAttempt);
|
|
2908
|
+
}
|
|
2909
|
+
const bindingOwner = operationId ? this._pendingOperationBindings.get(operationId) : this._pendingPickBindings.get(resolvedConnectId);
|
|
2910
|
+
const pendingBinding = bindingOwner?.pendingBinding?.connectId === resolvedConnectId ? bindingOwner.pendingBinding : void 0;
|
|
2911
|
+
if (fingerprint && checksWallet) {
|
|
1915
2912
|
const fp = await this._abortable(
|
|
1916
2913
|
signal,
|
|
1917
2914
|
this._verifyDeviceFingerprintWithSession(
|
|
@@ -1921,14 +2918,68 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1921
2918
|
)
|
|
1922
2919
|
);
|
|
1923
2920
|
if (!fp.success) {
|
|
2921
|
+
if (pendingBinding) {
|
|
2922
|
+
this._discardPendingBinding(bindingOwner, "failed");
|
|
2923
|
+
this._pendingPickBindings.delete(resolvedConnectId);
|
|
2924
|
+
}
|
|
2925
|
+
if (operationId) {
|
|
2926
|
+
this._pendingOperationBindings.delete(operationId);
|
|
2927
|
+
this._operations.end(operationId, "explicit");
|
|
2928
|
+
await this._dropSession(resolvedConnectId, signal);
|
|
2929
|
+
}
|
|
1924
2930
|
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
1925
|
-
code:
|
|
2931
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch
|
|
1926
2932
|
});
|
|
1927
2933
|
}
|
|
2934
|
+
if (walletCheck) walletCheck.verified = true;
|
|
1928
2935
|
}
|
|
1929
|
-
|
|
2936
|
+
if (pendingBinding && bindingOwner) {
|
|
2937
|
+
bindingOwner.pendingBinding = void 0;
|
|
2938
|
+
if (operationId) this._pendingOperationBindings.delete(operationId);
|
|
2939
|
+
else this._pendingPickBindings.delete(resolvedConnectId);
|
|
2940
|
+
await this._saveSelectedBleBinding(
|
|
2941
|
+
pendingBinding.connectId,
|
|
2942
|
+
pendingBinding.requestId,
|
|
2943
|
+
bindingOwner,
|
|
2944
|
+
operationId,
|
|
2945
|
+
signal,
|
|
2946
|
+
fingerprint && checksWallet ? {
|
|
2947
|
+
vendor: "ledger",
|
|
2948
|
+
type: "chainFingerprint",
|
|
2949
|
+
chain: fingerprint.chain,
|
|
2950
|
+
value: fingerprint.deviceId
|
|
2951
|
+
} : void 0
|
|
2952
|
+
);
|
|
2953
|
+
}
|
|
2954
|
+
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
|
|
2955
|
+
this._selectedBleReconnectTargets.set(connectId, {
|
|
2956
|
+
connectId: resolvedConnectId,
|
|
2957
|
+
chain: fingerprint.chain,
|
|
2958
|
+
fingerprint: fingerprint.deviceId
|
|
2959
|
+
});
|
|
2960
|
+
}
|
|
2961
|
+
businessCallStarted = true;
|
|
2962
|
+
const result = await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
2963
|
+
if (walletCheck) walletCheck.derived = true;
|
|
2964
|
+
return result;
|
|
1930
2965
|
} catch (err) {
|
|
1931
2966
|
if (signal.aborted) throw err;
|
|
2967
|
+
if (isLostConnectionError(err)) {
|
|
2968
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
2969
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
2970
|
+
else {
|
|
2971
|
+
this._sessions.delete(resolvedConnectId);
|
|
2972
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
2973
|
+
}
|
|
2974
|
+
const ambiguous = businessCallStarted && !(0, import_hwk_adapter_core4.canReplayHardwareMethodAfterTransportFailure)(method);
|
|
2975
|
+
const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
|
|
2976
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2977
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : mapLedgerError(err).code,
|
|
2978
|
+
message: "Ledger operation connection was lost; start a new operation",
|
|
2979
|
+
params: ambiguous ? (0, import_hwk_adapter_core4.operationMayHaveCompletedParams)(method, { operationId }) : interactionParams,
|
|
2980
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
2981
|
+
});
|
|
2982
|
+
}
|
|
1932
2983
|
const errObj = err;
|
|
1933
2984
|
debugLog("[LedgerAdapter] connectorCall error:", method, {
|
|
1934
2985
|
message: errObj?.message,
|
|
@@ -1940,8 +2991,66 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1940
2991
|
isNotAdvertising: isDeviceNotAdvertisingError(err),
|
|
1941
2992
|
isStuckApp: isStuckAppStateError(err)
|
|
1942
2993
|
});
|
|
2994
|
+
const assertSessionCurrent = (message) => {
|
|
2995
|
+
if (this._sessions.get(resolvedConnectId) === sessionId) return;
|
|
2996
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2997
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
2998
|
+
message
|
|
2999
|
+
});
|
|
3000
|
+
};
|
|
3001
|
+
if ((isDeviceLockedError(err) || errObj?.code === import_hwk_adapter_core4.HardwareErrorCode.DeviceLocked) && lockedRetryBudget > 0) {
|
|
3002
|
+
await this._waitForDeviceConnect(signal);
|
|
3003
|
+
assertSessionCurrent("Ledger connection ended while waiting for unlock");
|
|
3004
|
+
if (walletCheck?.derived) walletCheck.verified = false;
|
|
3005
|
+
return this._runConnectorCall(
|
|
3006
|
+
resolvedConnectId,
|
|
3007
|
+
method,
|
|
3008
|
+
effectiveParams,
|
|
3009
|
+
signal,
|
|
3010
|
+
fingerprint,
|
|
3011
|
+
permissionDeviceId,
|
|
3012
|
+
commonParams,
|
|
3013
|
+
installContext,
|
|
3014
|
+
operationId,
|
|
3015
|
+
lockedRetryBudget - 1
|
|
3016
|
+
);
|
|
3017
|
+
}
|
|
3018
|
+
if (businessCallStarted && isStuckAppStateError(err)) {
|
|
3019
|
+
await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
|
|
3020
|
+
assertSessionCurrent("Ledger connection ended during the app transition");
|
|
3021
|
+
try {
|
|
3022
|
+
const retried = await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
3023
|
+
if (walletCheck) walletCheck.derived = true;
|
|
3024
|
+
return retried;
|
|
3025
|
+
} catch (retryErr) {
|
|
3026
|
+
if (isStuckAppStateError(retryErr)) throw err;
|
|
3027
|
+
if (isLostConnectionError(retryErr)) {
|
|
3028
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
3029
|
+
else {
|
|
3030
|
+
this._sessions.delete(resolvedConnectId);
|
|
3031
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3032
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3033
|
+
}
|
|
3034
|
+
const ambiguous = !(0, import_hwk_adapter_core4.canReplayHardwareMethodAfterTransportFailure)(method);
|
|
3035
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3036
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : mapLedgerError(retryErr).code,
|
|
3037
|
+
message: `Ledger ${method} may have completed before the connection was lost`,
|
|
3038
|
+
params: ambiguous ? (0, import_hwk_adapter_core4.operationMayHaveCompletedParams)(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
|
|
3039
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
3040
|
+
});
|
|
3041
|
+
}
|
|
3042
|
+
throw retryErr;
|
|
3043
|
+
}
|
|
3044
|
+
}
|
|
3045
|
+
if (!operationId && errObj?.code === import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch) {
|
|
3046
|
+
this._sessions.delete(resolvedConnectId);
|
|
3047
|
+
this._sessionTransports.delete(sessionId);
|
|
3048
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3049
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3050
|
+
throw err;
|
|
3051
|
+
}
|
|
1943
3052
|
const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
|
|
1944
|
-
const isAppMissing = isAppNotInstalledError(err) || err?.code ===
|
|
3053
|
+
const isAppMissing = isAppNotInstalledError(err) || err?.code === import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled;
|
|
1945
3054
|
if (autoInstallApp && isAppMissing) {
|
|
1946
3055
|
if (installContext?.deviceOutOfMemoryError) {
|
|
1947
3056
|
throw installContext.deviceOutOfMemoryError;
|
|
@@ -1949,30 +3058,30 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1949
3058
|
const appName = err?.appName ?? mapLedgerError(err).appName;
|
|
1950
3059
|
if (appName) {
|
|
1951
3060
|
if (installContext?.installAttemptedAppNames?.has(appName)) {
|
|
1952
|
-
throw (0,
|
|
1953
|
-
code:
|
|
3061
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3062
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled,
|
|
1954
3063
|
message: `${appName} install reported success but the app is still missing on device`,
|
|
1955
3064
|
_tag: ERROR_TAG.AppInstallVerifyFailed,
|
|
1956
3065
|
appName
|
|
1957
3066
|
});
|
|
1958
3067
|
}
|
|
1959
|
-
const confirmed = await this._waitForInstallAppConfirm(appName);
|
|
3068
|
+
const confirmed = await this._waitForInstallAppConfirm(appName, signal);
|
|
1960
3069
|
if (!confirmed) {
|
|
1961
|
-
throw (0,
|
|
1962
|
-
code:
|
|
3070
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3071
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1963
3072
|
message: `User declined to install ${appName}`,
|
|
1964
3073
|
_tag: ERROR_TAG.UserAborted,
|
|
1965
3074
|
appName
|
|
1966
3075
|
});
|
|
1967
3076
|
}
|
|
1968
3077
|
this.emitter.emit("ui-event", {
|
|
1969
|
-
type:
|
|
3078
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress,
|
|
1970
3079
|
payload: { connectId: resolvedConnectId, appName, progress: 0 }
|
|
1971
3080
|
});
|
|
1972
3081
|
try {
|
|
1973
3082
|
await this._callConnector(sessionId, "installApp", { appName }, signal);
|
|
1974
3083
|
} catch (installErr) {
|
|
1975
|
-
if (mapLedgerError(installErr).code ===
|
|
3084
|
+
if (mapLedgerError(installErr).code === import_hwk_adapter_core4.HardwareErrorCode.DeviceOutOfMemory) {
|
|
1976
3085
|
if (installContext) {
|
|
1977
3086
|
installContext.deviceOutOfMemoryError = installErr;
|
|
1978
3087
|
}
|
|
@@ -1983,8 +3092,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1983
3092
|
installContext.installAttemptedAppNames = installContext.installAttemptedAppNames ?? /* @__PURE__ */ new Set();
|
|
1984
3093
|
installContext.installAttemptedAppNames.add(appName);
|
|
1985
3094
|
}
|
|
1986
|
-
this.emitter.emit(
|
|
1987
|
-
type:
|
|
3095
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
3096
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1988
3097
|
payload: {}
|
|
1989
3098
|
});
|
|
1990
3099
|
return await this._runConnectorCall(
|
|
@@ -1995,157 +3104,14 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1995
3104
|
fingerprint,
|
|
1996
3105
|
permissionDeviceId,
|
|
1997
3106
|
commonParams,
|
|
1998
|
-
installContext
|
|
1999
|
-
|
|
2000
|
-
}
|
|
2001
|
-
}
|
|
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
|
|
3107
|
+
installContext,
|
|
3108
|
+
operationId
|
|
2039
3109
|
);
|
|
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
3110
|
}
|
|
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
3111
|
}
|
|
2112
3112
|
throw err;
|
|
2113
3113
|
}
|
|
2114
3114
|
}
|
|
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
3115
|
_sleepAbortable(ms, signal) {
|
|
2150
3116
|
return new Promise((resolve, reject) => {
|
|
2151
3117
|
if (signal.aborted) {
|
|
@@ -2164,115 +3130,26 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2164
3130
|
});
|
|
2165
3131
|
}
|
|
2166
3132
|
/**
|
|
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
|
|
3133
|
+
* Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
|
|
3134
|
+
* replies. Without connectId the request is environment-level, else device-level.
|
|
2259
3135
|
*/
|
|
2260
3136
|
async _ensureDevicePermission(connectId, deviceId, signal) {
|
|
2261
3137
|
if (signal?.aborted) {
|
|
2262
3138
|
_LedgerAdapter._throwIfAborted(signal);
|
|
2263
3139
|
}
|
|
2264
3140
|
const transportType = this.activeTransport ?? "hid";
|
|
3141
|
+
const operationId = this._activeOperationId();
|
|
2265
3142
|
const waitPromise = this._uiRegistry.wait(
|
|
2266
|
-
|
|
2267
|
-
{ timeoutMs: 6e4 }
|
|
3143
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
3144
|
+
{ timeoutMs: 6e4, operationId }
|
|
2268
3145
|
);
|
|
2269
|
-
this.emitter.emit(
|
|
2270
|
-
type:
|
|
2271
|
-
payload: { transportType, connectId, deviceId }
|
|
3146
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
|
|
3147
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
3148
|
+
payload: { transportType, connectId, deviceId, operationId }
|
|
2272
3149
|
});
|
|
2273
3150
|
let response;
|
|
2274
3151
|
const onAbort = () => {
|
|
2275
|
-
this._uiRegistry.cancel(
|
|
3152
|
+
this._uiRegistry.cancel(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION);
|
|
2276
3153
|
};
|
|
2277
3154
|
try {
|
|
2278
3155
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
@@ -2281,14 +3158,14 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2281
3158
|
if (signal?.aborted) {
|
|
2282
3159
|
_LedgerAdapter._throwIfAborted(signal);
|
|
2283
3160
|
}
|
|
2284
|
-
if (err?._tag ===
|
|
2285
|
-
this.emitter.emit(
|
|
2286
|
-
type:
|
|
3161
|
+
if (err?._tag === import_hwk_adapter_core4.UI_REQUEST_PREEMPTED_TAG) {
|
|
3162
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
3163
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
2287
3164
|
payload: {}
|
|
2288
3165
|
});
|
|
2289
3166
|
throw Object.assign(new Error("Device permission request superseded"), {
|
|
2290
3167
|
_tag: ERROR_TAG.UserAborted,
|
|
2291
|
-
code:
|
|
3168
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
2292
3169
|
cause: err
|
|
2293
3170
|
});
|
|
2294
3171
|
}
|
|
@@ -2299,7 +3176,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2299
3176
|
const { granted, reason, message } = response;
|
|
2300
3177
|
if (!granted) {
|
|
2301
3178
|
throw Object.assign(new Error(message ?? "Device permission denied"), {
|
|
2302
|
-
code:
|
|
3179
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DevicePermissionDenied,
|
|
2303
3180
|
reason
|
|
2304
3181
|
});
|
|
2305
3182
|
}
|
|
@@ -2313,8 +3190,16 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2313
3190
|
const tag = err && typeof err === "object" ? err._tag : void 0;
|
|
2314
3191
|
if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
|
|
2315
3192
|
const e = err;
|
|
2316
|
-
const params = e.code ===
|
|
2317
|
-
return ledgerFailure(
|
|
3193
|
+
const params = e.code === import_hwk_adapter_core4.HardwareErrorCode.DevicePermissionDenied && e.reason ? { permissionDeniedReason: e.reason } : e.params;
|
|
3194
|
+
return ledgerFailure(
|
|
3195
|
+
e.code,
|
|
3196
|
+
e.message ?? "Unknown error",
|
|
3197
|
+
e.appName,
|
|
3198
|
+
tag,
|
|
3199
|
+
params,
|
|
3200
|
+
void 0,
|
|
3201
|
+
(0, import_hwk_adapter_core4.isHwkRecoveryHint)(e.recovery) ? e.recovery : void 0
|
|
3202
|
+
);
|
|
2318
3203
|
}
|
|
2319
3204
|
const mapped = mapLedgerError(err);
|
|
2320
3205
|
return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
|
|
@@ -2341,7 +3226,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2341
3226
|
deviceId: device.deviceId,
|
|
2342
3227
|
connectId: device.connectId,
|
|
2343
3228
|
label: device.name,
|
|
2344
|
-
connectionType: this.connector.connectionType,
|
|
3229
|
+
connectionType: device.connectionType ?? this.connector.connectionType,
|
|
2345
3230
|
rssi: device.rssi,
|
|
2346
3231
|
isConnectable: device.isConnectable,
|
|
2347
3232
|
serialNumber: device.serialNumber,
|
|
@@ -2639,11 +3524,12 @@ var import_device_signer_kit_ethereum = require("@ledgerhq/device-signer-kit-eth
|
|
|
2639
3524
|
var import_context_module = require("@ledgerhq/context-module");
|
|
2640
3525
|
|
|
2641
3526
|
// src/signer/SignerEth.ts
|
|
2642
|
-
var
|
|
3527
|
+
var import_hwk_adapter_core5 = require("@onekeyfe/hwk-adapter-core");
|
|
2643
3528
|
|
|
2644
3529
|
// src/signer/deviceActionToPromise.ts
|
|
2645
3530
|
var import_device_management_kit = require("@ledgerhq/device-management-kit");
|
|
2646
3531
|
var IDLE_WATCHDOG_MS = 65e3;
|
|
3532
|
+
var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
|
|
2647
3533
|
function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
|
|
2648
3534
|
return new Promise((resolve, reject) => {
|
|
2649
3535
|
let settled = false;
|
|
@@ -2831,7 +3717,6 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
|
|
|
2831
3717
|
}
|
|
2832
3718
|
|
|
2833
3719
|
// src/signer/SignerEth.ts
|
|
2834
|
-
var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
|
|
2835
3720
|
var SignerEth = class {
|
|
2836
3721
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
2837
3722
|
constructor(_sdk) {
|
|
@@ -2852,7 +3737,7 @@ var SignerEth = class {
|
|
|
2852
3737
|
);
|
|
2853
3738
|
}
|
|
2854
3739
|
async signTransaction(derivationPath, serializedTxHex) {
|
|
2855
|
-
const action = this._sdk.signTransaction(derivationPath, (0,
|
|
3740
|
+
const action = this._sdk.signTransaction(derivationPath, (0, import_hwk_adapter_core5.hexToBytes)(serializedTxHex));
|
|
2856
3741
|
return deviceActionToPromise(
|
|
2857
3742
|
action,
|
|
2858
3743
|
this.onInteraction,
|
|
@@ -2861,7 +3746,7 @@ var SignerEth = class {
|
|
|
2861
3746
|
);
|
|
2862
3747
|
}
|
|
2863
3748
|
async signMessage(derivationPath, message) {
|
|
2864
|
-
const action = this._sdk.signMessage(derivationPath, (0,
|
|
3749
|
+
const action = this._sdk.signMessage(derivationPath, (0, import_hwk_adapter_core5.hexToBytes)(message));
|
|
2865
3750
|
return deviceActionToPromise(
|
|
2866
3751
|
action,
|
|
2867
3752
|
this.onInteraction,
|
|
@@ -2902,7 +3787,7 @@ var SignerManager = class _SignerManager {
|
|
|
2902
3787
|
return (args) => new import_device_signer_kit_ethereum.SignerEthBuilder(args);
|
|
2903
3788
|
}
|
|
2904
3789
|
static _createContextModule() {
|
|
2905
|
-
const contextModule = new import_context_module.ContextModuleBuilder({}).removeDefaultLoaders().build();
|
|
3790
|
+
const contextModule = new import_context_module.ContextModuleBuilder({}).setChain(import_context_module.ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
|
|
2906
3791
|
return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
|
|
2907
3792
|
}
|
|
2908
3793
|
static wrapBlindSigningReportNonBlocking(contextModule) {
|
|
@@ -2921,23 +3806,44 @@ var SignerManager = class _SignerManager {
|
|
|
2921
3806
|
};
|
|
2922
3807
|
|
|
2923
3808
|
// src/connector/chains/evm.ts
|
|
2924
|
-
var
|
|
3809
|
+
var import_hwk_adapter_core7 = require("@onekeyfe/hwk-adapter-core");
|
|
2925
3810
|
|
|
2926
3811
|
// src/connector/chains/utils.ts
|
|
2927
|
-
var
|
|
3812
|
+
var import_hwk_adapter_core6 = require("@onekeyfe/hwk-adapter-core");
|
|
2928
3813
|
function normalizePath(path) {
|
|
2929
3814
|
return path.startsWith("m/") ? path.slice(2) : path;
|
|
2930
3815
|
}
|
|
2931
3816
|
function collapseSignerInteraction(interaction) {
|
|
2932
3817
|
switch (interaction) {
|
|
2933
3818
|
case "confirm-open-app":
|
|
2934
|
-
return
|
|
3819
|
+
return import_hwk_adapter_core6.EConnectorInteraction.ConfirmOpenApp;
|
|
2935
3820
|
case "unlock-device":
|
|
2936
|
-
return
|
|
3821
|
+
return import_hwk_adapter_core6.EConnectorInteraction.UnlockDevice;
|
|
2937
3822
|
case "interaction-complete":
|
|
2938
|
-
return
|
|
3823
|
+
return import_hwk_adapter_core6.EConnectorInteraction.InteractionComplete;
|
|
2939
3824
|
default:
|
|
2940
|
-
return
|
|
3825
|
+
return import_hwk_adapter_core6.EConnectorInteraction.ConfirmOnDevice;
|
|
3826
|
+
}
|
|
3827
|
+
}
|
|
3828
|
+
function wireSignerToSession(ctx, sessionId, chain, signer) {
|
|
3829
|
+
signer.onInteraction = (interaction) => {
|
|
3830
|
+
debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
|
|
3831
|
+
ctx.emit("ui-event", {
|
|
3832
|
+
type: collapseSignerInteraction(interaction),
|
|
3833
|
+
payload: { sessionId }
|
|
3834
|
+
});
|
|
3835
|
+
};
|
|
3836
|
+
signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
|
|
3837
|
+
return signer;
|
|
3838
|
+
}
|
|
3839
|
+
async function runSignerCall(ctx, sessionId, call) {
|
|
3840
|
+
try {
|
|
3841
|
+
return await call();
|
|
3842
|
+
} catch (err) {
|
|
3843
|
+
ctx.invalidateSession(sessionId);
|
|
3844
|
+
throw ctx.wrapError(err);
|
|
3845
|
+
} finally {
|
|
3846
|
+
ctx.clearCanceller(sessionId);
|
|
2941
3847
|
}
|
|
2942
3848
|
}
|
|
2943
3849
|
|
|
@@ -2963,7 +3869,7 @@ async function evmSignTransaction(ctx, sessionId, params) {
|
|
|
2963
3869
|
new Error(
|
|
2964
3870
|
"Ledger requires a pre-serialized transaction (serializedTx). Provide an RLP-encoded hex string."
|
|
2965
3871
|
),
|
|
2966
|
-
{ code:
|
|
3872
|
+
{ code: import_hwk_adapter_core7.HardwareErrorCode.InvalidParams }
|
|
2967
3873
|
);
|
|
2968
3874
|
}
|
|
2969
3875
|
const signer = await _getEthSigner(ctx, sessionId);
|
|
@@ -2972,8 +3878,8 @@ async function evmSignTransaction(ctx, sessionId, params) {
|
|
|
2972
3878
|
const result = await signer.signTransaction(path, params.serializedTx);
|
|
2973
3879
|
return {
|
|
2974
3880
|
v: `0x${result.v.toString(16)}`,
|
|
2975
|
-
r: (0,
|
|
2976
|
-
s: (0,
|
|
3881
|
+
r: (0, import_hwk_adapter_core7.padHex64)(result.r),
|
|
3882
|
+
s: (0, import_hwk_adapter_core7.padHex64)(result.s)
|
|
2977
3883
|
};
|
|
2978
3884
|
} catch (err) {
|
|
2979
3885
|
ctx.invalidateSession(sessionId);
|
|
@@ -2987,8 +3893,8 @@ async function evmSignMessage(ctx, sessionId, params) {
|
|
|
2987
3893
|
const path = normalizePath(params.path);
|
|
2988
3894
|
try {
|
|
2989
3895
|
const result = await signer.signMessage(path, params.message);
|
|
2990
|
-
const rHex = (0,
|
|
2991
|
-
const sHex = (0,
|
|
3896
|
+
const rHex = (0, import_hwk_adapter_core7.stripHex)(result.r).padStart(64, "0");
|
|
3897
|
+
const sHex = (0, import_hwk_adapter_core7.stripHex)(result.s).padStart(64, "0");
|
|
2992
3898
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
2993
3899
|
return { signature: `0x${rHex}${sHex}${vHex}` };
|
|
2994
3900
|
} catch (err) {
|
|
@@ -3004,15 +3910,15 @@ async function evmSignTypedData(ctx, sessionId, params) {
|
|
|
3004
3910
|
new Error(
|
|
3005
3911
|
'Ledger does not support hash-only EIP-712 signing. Use mode "full" with the complete typed data structure.'
|
|
3006
3912
|
),
|
|
3007
|
-
{ code:
|
|
3913
|
+
{ code: import_hwk_adapter_core7.HardwareErrorCode.MethodNotSupported }
|
|
3008
3914
|
);
|
|
3009
3915
|
}
|
|
3010
3916
|
const signer = await _getEthSigner(ctx, sessionId);
|
|
3011
3917
|
const path = normalizePath(params.path);
|
|
3012
3918
|
try {
|
|
3013
3919
|
const result = await signer.signTypedData(path, params.data);
|
|
3014
|
-
const rHex = (0,
|
|
3015
|
-
const sHex = (0,
|
|
3920
|
+
const rHex = (0, import_hwk_adapter_core7.stripHex)(result.r).padStart(64, "0");
|
|
3921
|
+
const sHex = (0, import_hwk_adapter_core7.stripHex)(result.s).padStart(64, "0");
|
|
3016
3922
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
3017
3923
|
return { signature: `0x${rHex}${sHex}${vHex}` };
|
|
3018
3924
|
} catch (err) {
|
|
@@ -3039,15 +3945,14 @@ async function _getEthSigner(ctx, sessionId) {
|
|
|
3039
3945
|
}
|
|
3040
3946
|
|
|
3041
3947
|
// src/connector/chains/btc.ts
|
|
3042
|
-
var
|
|
3043
|
-
var
|
|
3948
|
+
var import_hwk_adapter_core9 = require("@onekeyfe/hwk-adapter-core");
|
|
3949
|
+
var import_bitcoinjs_lib2 = require("bitcoinjs-lib");
|
|
3044
3950
|
|
|
3045
3951
|
// src/signer/SignerBtc.ts
|
|
3046
|
-
var
|
|
3952
|
+
var import_hwk_adapter_core8 = require("@onekeyfe/hwk-adapter-core");
|
|
3047
3953
|
function hexToUtf8(hex) {
|
|
3048
|
-
return new TextDecoder().decode((0,
|
|
3954
|
+
return new TextDecoder().decode((0, import_hwk_adapter_core8.hexToBytes)(hex));
|
|
3049
3955
|
}
|
|
3050
|
-
var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
|
|
3051
3956
|
var SignerBtc = class {
|
|
3052
3957
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
3053
3958
|
constructor(_sdk) {
|
|
@@ -3061,7 +3966,7 @@ var SignerBtc = class {
|
|
|
3061
3966
|
return deviceActionToPromise(
|
|
3062
3967
|
action,
|
|
3063
3968
|
this.onInteraction,
|
|
3064
|
-
void 0,
|
|
3969
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3065
3970
|
this.onRegisterCanceller
|
|
3066
3971
|
);
|
|
3067
3972
|
}
|
|
@@ -3079,14 +3984,14 @@ var SignerBtc = class {
|
|
|
3079
3984
|
const result = await deviceActionToPromise(
|
|
3080
3985
|
action,
|
|
3081
3986
|
this.onInteraction,
|
|
3082
|
-
void 0,
|
|
3987
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3083
3988
|
this.onRegisterCanceller
|
|
3084
3989
|
);
|
|
3085
3990
|
debugLog(
|
|
3086
3991
|
"[SignerBtc] getExtendedPublicKey result type:",
|
|
3087
3992
|
typeof result,
|
|
3088
3993
|
"value:",
|
|
3089
|
-
|
|
3994
|
+
summarizeForLog(result)
|
|
3090
3995
|
);
|
|
3091
3996
|
if (typeof result === "string") return result;
|
|
3092
3997
|
return result.extendedPublicKey;
|
|
@@ -3115,7 +4020,7 @@ var SignerBtc = class {
|
|
|
3115
4020
|
return deviceActionToPromise(
|
|
3116
4021
|
action,
|
|
3117
4022
|
this.onInteraction,
|
|
3118
|
-
|
|
4023
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3119
4024
|
this.onRegisterCanceller
|
|
3120
4025
|
);
|
|
3121
4026
|
}
|
|
@@ -3128,7 +4033,7 @@ var SignerBtc = class {
|
|
|
3128
4033
|
return deviceActionToPromise(
|
|
3129
4034
|
action,
|
|
3130
4035
|
this.onInteraction,
|
|
3131
|
-
|
|
4036
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3132
4037
|
this.onRegisterCanceller
|
|
3133
4038
|
);
|
|
3134
4039
|
}
|
|
@@ -3141,7 +4046,7 @@ var SignerBtc = class {
|
|
|
3141
4046
|
return deviceActionToPromise(
|
|
3142
4047
|
action,
|
|
3143
4048
|
this.onInteraction,
|
|
3144
|
-
|
|
4049
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3145
4050
|
this.onRegisterCanceller
|
|
3146
4051
|
);
|
|
3147
4052
|
}
|
|
@@ -3160,11 +4065,25 @@ function _purposeToTemplate(purpose, DDT) {
|
|
|
3160
4065
|
return DDT.TAPROOT;
|
|
3161
4066
|
default:
|
|
3162
4067
|
throw Object.assign(new Error(`Unsupported BTC purpose: m/${purpose ?? "<undefined>"}'`), {
|
|
3163
|
-
code:
|
|
4068
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams
|
|
3164
4069
|
});
|
|
3165
4070
|
}
|
|
3166
4071
|
}
|
|
4072
|
+
function assertBitcoinMainnet(coin) {
|
|
4073
|
+
if (coin !== void 0 && !["btc", "bitcoin"].includes(coin.toLowerCase())) {
|
|
4074
|
+
throw Object.assign(new Error(`Ledger BTC supports Bitcoin mainnet only, not ${coin}`), {
|
|
4075
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.ChainNotSupported
|
|
4076
|
+
});
|
|
4077
|
+
}
|
|
4078
|
+
}
|
|
3167
4079
|
async function btcGetAddress(ctx, sessionId, params) {
|
|
4080
|
+
assertBitcoinMainnet(params.coin);
|
|
4081
|
+
if (normalizePath(params.path).split("/").length !== 3) {
|
|
4082
|
+
throw Object.assign(
|
|
4083
|
+
new Error("Ledger btcGetAddress takes an account path (e.g. m/84'/0'/0') plus addressIndex"),
|
|
4084
|
+
{ code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams }
|
|
4085
|
+
);
|
|
4086
|
+
}
|
|
3168
4087
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
3169
4088
|
const path = normalizePath(params.path);
|
|
3170
4089
|
try {
|
|
@@ -3195,6 +4114,7 @@ async function btcGetAddress(ctx, sessionId, params) {
|
|
|
3195
4114
|
}
|
|
3196
4115
|
}
|
|
3197
4116
|
async function btcGetPublicKey(ctx, sessionId, params) {
|
|
4117
|
+
assertBitcoinMainnet(params.coin);
|
|
3198
4118
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
3199
4119
|
const path = normalizePath(params.path);
|
|
3200
4120
|
debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
|
|
@@ -3202,7 +4122,7 @@ async function btcGetPublicKey(ctx, sessionId, params) {
|
|
|
3202
4122
|
const xpub = await btcSigner.getExtendedPublicKey(path, {
|
|
3203
4123
|
checkOnDevice: params.showOnDevice ?? false
|
|
3204
4124
|
});
|
|
3205
|
-
debugLog("[LedgerConnector] btcGetPublicKey success, xpub:",
|
|
4125
|
+
debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", summarizeForLog(xpub));
|
|
3206
4126
|
return { xpub, path: params.path };
|
|
3207
4127
|
} catch (err) {
|
|
3208
4128
|
debugError("[LedgerConnector] btcGetPublicKey error, path:", path, "err:", err);
|
|
@@ -3216,7 +4136,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3216
4136
|
if (!params.psbt) {
|
|
3217
4137
|
throw Object.assign(
|
|
3218
4138
|
new Error("Ledger requires PSBT format for BTC transaction signing. Provide params.psbt."),
|
|
3219
|
-
{ code:
|
|
4139
|
+
{ code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams }
|
|
3220
4140
|
);
|
|
3221
4141
|
}
|
|
3222
4142
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
@@ -3230,7 +4150,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3230
4150
|
debugLog("[LedgerConnector] btcSignTransaction wallet:", { path, purpose, template });
|
|
3231
4151
|
const wallet = new DefaultWallet(path, template);
|
|
3232
4152
|
const signedTxHex = await btcSigner.signTransaction(wallet, params.psbt);
|
|
3233
|
-
return { serializedTx: (0,
|
|
4153
|
+
return { serializedTx: (0, import_hwk_adapter_core9.stripHex)(signedTxHex) };
|
|
3234
4154
|
} catch (err) {
|
|
3235
4155
|
ctx.invalidateSession(sessionId);
|
|
3236
4156
|
throw ctx.wrapError(err);
|
|
@@ -3241,7 +4161,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3241
4161
|
async function btcSignPsbt(ctx, sessionId, params) {
|
|
3242
4162
|
if (!params.psbt) {
|
|
3243
4163
|
throw Object.assign(new Error("btcSignPsbt requires params.psbt"), {
|
|
3244
|
-
code:
|
|
4164
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams
|
|
3245
4165
|
});
|
|
3246
4166
|
}
|
|
3247
4167
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
@@ -3271,8 +4191,8 @@ async function btcSignMessage(ctx, sessionId, params) {
|
|
|
3271
4191
|
try {
|
|
3272
4192
|
const result = await btcSigner.signMessage(path, params.message);
|
|
3273
4193
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
3274
|
-
const rHex = (0,
|
|
3275
|
-
const sHex = (0,
|
|
4194
|
+
const rHex = (0, import_hwk_adapter_core9.stripHex)(result.r).padStart(64, "0");
|
|
4195
|
+
const sHex = (0, import_hwk_adapter_core9.stripHex)(result.s).padStart(64, "0");
|
|
3276
4196
|
return { signature: `${vHex}${rHex}${sHex}` };
|
|
3277
4197
|
} catch (err) {
|
|
3278
4198
|
ctx.invalidateSession(sessionId);
|
|
@@ -3323,7 +4243,7 @@ function _isScriptPathInput(input) {
|
|
|
3323
4243
|
return !!(input.tapLeafScript && input.tapLeafScript.length > 0);
|
|
3324
4244
|
}
|
|
3325
4245
|
function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
3326
|
-
const psbt =
|
|
4246
|
+
const psbt = import_bitcoinjs_lib2.Psbt.fromHex(psbtHex);
|
|
3327
4247
|
for (const sig of signatures) {
|
|
3328
4248
|
const input = psbt.data.inputs[sig.inputIndex];
|
|
3329
4249
|
if (!input) {
|
|
@@ -3372,7 +4292,8 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
|
3372
4292
|
}
|
|
3373
4293
|
|
|
3374
4294
|
// src/connector/chains/sol.ts
|
|
3375
|
-
var
|
|
4295
|
+
var import_hwk_adapter_core10 = require("@onekeyfe/hwk-adapter-core");
|
|
4296
|
+
var import_bs58 = __toESM(require("bs58"));
|
|
3376
4297
|
|
|
3377
4298
|
// src/signer/SignerSol.ts
|
|
3378
4299
|
var SignerSol = class {
|
|
@@ -3390,7 +4311,7 @@ var SignerSol = class {
|
|
|
3390
4311
|
return deviceActionToPromise(
|
|
3391
4312
|
action,
|
|
3392
4313
|
this.onInteraction,
|
|
3393
|
-
void 0,
|
|
4314
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3394
4315
|
this.onRegisterCanceller
|
|
3395
4316
|
);
|
|
3396
4317
|
}
|
|
@@ -3402,7 +4323,7 @@ var SignerSol = class {
|
|
|
3402
4323
|
return deviceActionToPromise(
|
|
3403
4324
|
action,
|
|
3404
4325
|
this.onInteraction,
|
|
3405
|
-
|
|
4326
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3406
4327
|
this.onRegisterCanceller
|
|
3407
4328
|
);
|
|
3408
4329
|
}
|
|
@@ -3415,7 +4336,7 @@ var SignerSol = class {
|
|
|
3415
4336
|
return deviceActionToPromise(
|
|
3416
4337
|
action,
|
|
3417
4338
|
this.onInteraction,
|
|
3418
|
-
|
|
4339
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3419
4340
|
this.onRegisterCanceller
|
|
3420
4341
|
);
|
|
3421
4342
|
}
|
|
@@ -3440,10 +4361,10 @@ async function solGetAddress(ctx, sessionId, params) {
|
|
|
3440
4361
|
async function solSignTransaction(ctx, sessionId, params) {
|
|
3441
4362
|
const solSigner = await _createSolSigner(ctx, sessionId);
|
|
3442
4363
|
const path = normalizePath(params.path);
|
|
3443
|
-
const txBytes = (0,
|
|
4364
|
+
const txBytes = (0, import_hwk_adapter_core10.hexToBytes)(params.serializedTx);
|
|
3444
4365
|
try {
|
|
3445
4366
|
const result = await solSigner.signTransaction(path, txBytes);
|
|
3446
|
-
return { signature: (0,
|
|
4367
|
+
return { signature: (0, import_hwk_adapter_core10.bytesToHex)(result) };
|
|
3447
4368
|
} catch (err) {
|
|
3448
4369
|
ctx.invalidateSession(sessionId);
|
|
3449
4370
|
throw ctx.wrapError(err);
|
|
@@ -3454,10 +4375,23 @@ async function solSignTransaction(ctx, sessionId, params) {
|
|
|
3454
4375
|
async function solSignMessage(ctx, sessionId, params) {
|
|
3455
4376
|
const solSigner = await _createSolSigner(ctx, sessionId);
|
|
3456
4377
|
const path = normalizePath(params.path);
|
|
3457
|
-
const messageBytes = (0,
|
|
4378
|
+
const messageBytes = (0, import_hwk_adapter_core10.hexToBytes)(params.message);
|
|
3458
4379
|
try {
|
|
4380
|
+
if (params.messageVersion === 1) {
|
|
4381
|
+
const preparedMessage = (0, import_hwk_adapter_core10.prepareSolanaOffchainMessageV1)({
|
|
4382
|
+
message: messageBytes,
|
|
4383
|
+
requiredSigners: params.requiredSigners
|
|
4384
|
+
});
|
|
4385
|
+
const { SignMessageVersion } = await ctx.importLedgerKit(
|
|
4386
|
+
"@ledgerhq/device-signer-kit-solana"
|
|
4387
|
+
);
|
|
4388
|
+
const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
|
|
4389
|
+
version: SignMessageVersion.Raw
|
|
4390
|
+
});
|
|
4391
|
+
return { signature: decodeBase58Signature(result2.signature) };
|
|
4392
|
+
}
|
|
3459
4393
|
const result = await solSigner.signMessage(path, messageBytes);
|
|
3460
|
-
return { signature: result.signature };
|
|
4394
|
+
return { signature: decodeBase58EnvelopeSignature(result.signature) };
|
|
3461
4395
|
} catch (err) {
|
|
3462
4396
|
ctx.invalidateSession(sessionId);
|
|
3463
4397
|
throw ctx.wrapError(err);
|
|
@@ -3465,11 +4399,27 @@ async function solSignMessage(ctx, sessionId, params) {
|
|
|
3465
4399
|
ctx.clearCanceller(sessionId);
|
|
3466
4400
|
}
|
|
3467
4401
|
}
|
|
4402
|
+
function decodeBase58Signature(signature) {
|
|
4403
|
+
const bytes = import_bs58.default.decode(signature);
|
|
4404
|
+
if (bytes.length !== 64) {
|
|
4405
|
+
throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
|
|
4406
|
+
}
|
|
4407
|
+
return (0, import_hwk_adapter_core10.bytesToHex)(bytes);
|
|
4408
|
+
}
|
|
4409
|
+
function decodeBase58EnvelopeSignature(envelope) {
|
|
4410
|
+
const bytes = import_bs58.default.decode(envelope);
|
|
4411
|
+
if (bytes.length < 65 || bytes[0] !== 1) {
|
|
4412
|
+
throw new Error("Ledger Solana signature envelope is invalid");
|
|
4413
|
+
}
|
|
4414
|
+
return (0, import_hwk_adapter_core10.bytesToHex)(bytes.subarray(1, 65));
|
|
4415
|
+
}
|
|
3468
4416
|
async function _createSolSigner(ctx, sessionId) {
|
|
3469
4417
|
const dmk = await ctx.getOrCreateDmk();
|
|
3470
|
-
const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit(
|
|
4418
|
+
const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
|
|
4419
|
+
"@ledgerhq/context-module"
|
|
4420
|
+
);
|
|
3471
4421
|
const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
|
|
3472
|
-
const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
|
|
4422
|
+
const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
|
|
3473
4423
|
const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
|
|
3474
4424
|
const signer = new SignerSol(sdkSigner);
|
|
3475
4425
|
signer.onInteraction = (interaction) => {
|
|
@@ -3485,316 +4435,119 @@ async function _createSolSigner(ctx, sessionId) {
|
|
|
3485
4435
|
return signer;
|
|
3486
4436
|
}
|
|
3487
4437
|
|
|
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
|
|
4438
|
+
// src/connector/chains/zcash.ts
|
|
3493
4439
|
var import_hwk_adapter_core11 = require("@onekeyfe/hwk-adapter-core");
|
|
3494
4440
|
|
|
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);
|
|
4441
|
+
// src/signer/SignerZcash.ts
|
|
4442
|
+
var SignerZcash = class {
|
|
4443
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4444
|
+
constructor(_sdk) {
|
|
4445
|
+
this._sdk = _sdk;
|
|
3556
4446
|
}
|
|
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
|
-
}
|
|
4447
|
+
/** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
|
|
4448
|
+
async getFullViewingKey(derivationPath, options) {
|
|
4449
|
+
const action = this._sdk.getFullViewingKey(derivationPath, options);
|
|
4450
|
+
return deviceActionToPromise(
|
|
4451
|
+
action,
|
|
4452
|
+
this.onInteraction,
|
|
4453
|
+
void 0,
|
|
4454
|
+
this.onRegisterCanceller
|
|
3593
4455
|
);
|
|
3594
4456
|
}
|
|
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})`
|
|
4457
|
+
/** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
|
|
4458
|
+
async getShieldedAddress(derivationPath, options) {
|
|
4459
|
+
const action = this._sdk.getShieldedAddress(derivationPath, options);
|
|
4460
|
+
return deviceActionToPromise(
|
|
4461
|
+
action,
|
|
4462
|
+
this.onInteraction,
|
|
4463
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
4464
|
+
this.onRegisterCanceller
|
|
3657
4465
|
);
|
|
3658
4466
|
}
|
|
3659
|
-
_isDashboard(appName) {
|
|
3660
|
-
return appName === DASHBOARD_APP_NAME;
|
|
3661
|
-
}
|
|
3662
|
-
_wait() {
|
|
3663
|
-
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
3664
|
-
}
|
|
3665
4467
|
};
|
|
3666
4468
|
|
|
3667
|
-
// src/connector/chains/
|
|
3668
|
-
function
|
|
3669
|
-
|
|
4469
|
+
// src/connector/chains/zcash.ts
|
|
4470
|
+
async function zcashGetFullViewingKey(ctx, sessionId, params) {
|
|
4471
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4472
|
+
const path = normalizePath(params.path);
|
|
4473
|
+
const mode = params.mode ?? "ufvk";
|
|
4474
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4475
|
+
const result = await signer.getFullViewingKey(path, { mode });
|
|
4476
|
+
if (result.mode === "ufvk") {
|
|
4477
|
+
return { path: params.path, mode, ufvk: result.fullViewingKey };
|
|
4478
|
+
}
|
|
4479
|
+
return { path: params.path, mode, orchardFvk: (0, import_hwk_adapter_core11.bytesToHex)(result.fullViewingKey) };
|
|
4480
|
+
});
|
|
3670
4481
|
}
|
|
3671
|
-
async function
|
|
3672
|
-
const
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
type: import_hwk_adapter_core11.EConnectorInteraction.ConfirmOpenApp,
|
|
3678
|
-
payload: { sessionId }
|
|
4482
|
+
async function zcashGetShieldedAddress(ctx, sessionId, params) {
|
|
4483
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4484
|
+
const path = normalizePath(params.path);
|
|
4485
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4486
|
+
const result = await signer.getShieldedAddress(path, {
|
|
4487
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
3679
4488
|
});
|
|
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
|
-
}
|
|
4489
|
+
return { address: result.address, path: params.path };
|
|
4490
|
+
});
|
|
3747
4491
|
}
|
|
3748
|
-
async function
|
|
4492
|
+
async function _createZcashSigner(ctx, sessionId) {
|
|
3749
4493
|
const dmk = await ctx.getOrCreateDmk();
|
|
3750
|
-
const
|
|
3751
|
-
|
|
4494
|
+
const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
|
|
4495
|
+
const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
|
|
4496
|
+
return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
|
|
3752
4497
|
}
|
|
3753
4498
|
|
|
3754
|
-
// src/
|
|
3755
|
-
var
|
|
3756
|
-
|
|
3757
|
-
|
|
3758
|
-
|
|
3759
|
-
|
|
3760
|
-
|
|
4499
|
+
// src/connector/chains/tron.ts
|
|
4500
|
+
var import_hwk_adapter_core12 = require("@onekeyfe/hwk-adapter-core");
|
|
4501
|
+
|
|
4502
|
+
// src/signer/SignerTron.ts
|
|
4503
|
+
var SignerTron = class {
|
|
4504
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4505
|
+
constructor(_sdk) {
|
|
4506
|
+
this._sdk = _sdk;
|
|
3761
4507
|
}
|
|
3762
|
-
|
|
3763
|
-
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
|
|
3767
|
-
|
|
3768
|
-
|
|
3769
|
-
|
|
3770
|
-
|
|
3771
|
-
}
|
|
3772
|
-
result.set(statusCode, data.length);
|
|
3773
|
-
return result;
|
|
4508
|
+
/** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
|
|
4509
|
+
async getAddress(derivationPath, options) {
|
|
4510
|
+
const action = this._sdk.getAddress(derivationPath, options);
|
|
4511
|
+
const result = await deviceActionToPromise(
|
|
4512
|
+
action,
|
|
4513
|
+
this.onInteraction,
|
|
4514
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
4515
|
+
this.onRegisterCanceller
|
|
4516
|
+
);
|
|
4517
|
+
return { address: result.address, publicKey: result.publicKey };
|
|
3774
4518
|
}
|
|
3775
|
-
|
|
4519
|
+
/** Sign a protobuf-encoded raw transaction. */
|
|
4520
|
+
async signTransaction(derivationPath, transaction, options) {
|
|
4521
|
+
const action = this._sdk.signTransaction(derivationPath, transaction, options);
|
|
4522
|
+
return deviceActionToPromise(
|
|
4523
|
+
action,
|
|
4524
|
+
this.onInteraction,
|
|
4525
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
4526
|
+
this.onRegisterCanceller
|
|
4527
|
+
);
|
|
4528
|
+
}
|
|
4529
|
+
/** Sign a personal message (TIP-191). */
|
|
4530
|
+
async signPersonalMessage(derivationPath, message, options) {
|
|
4531
|
+
const action = this._sdk.signPersonalMessage(derivationPath, message, options);
|
|
4532
|
+
return deviceActionToPromise(
|
|
4533
|
+
action,
|
|
4534
|
+
this.onInteraction,
|
|
4535
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
4536
|
+
this.onRegisterCanceller
|
|
4537
|
+
);
|
|
3776
4538
|
}
|
|
3777
4539
|
};
|
|
3778
4540
|
|
|
3779
4541
|
// src/connector/chains/tron.ts
|
|
3780
4542
|
async function tronGetAddress(ctx, sessionId, params) {
|
|
4543
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3781
4544
|
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
|
-
);
|
|
4545
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4546
|
+
const result = await tronSigner.getAddress(path, {
|
|
4547
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
4548
|
+
});
|
|
4549
|
+
return { address: result.address, publicKey: result.publicKey, path: params.path };
|
|
4550
|
+
});
|
|
3798
4551
|
}
|
|
3799
4552
|
async function tronSignTransaction(ctx, sessionId, params) {
|
|
3800
4553
|
if (!params.rawTxHex) {
|
|
@@ -3803,42 +4556,30 @@ async function tronSignTransaction(ctx, sessionId, params) {
|
|
|
3803
4556
|
{ code: import_hwk_adapter_core12.HardwareErrorCode.InvalidParams }
|
|
3804
4557
|
);
|
|
3805
4558
|
}
|
|
4559
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3806
4560
|
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
|
-
);
|
|
4561
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4562
|
+
const signature = await tronSigner.signTransaction(path, (0, import_hwk_adapter_core12.hexToBytes)(params.rawTxHex));
|
|
4563
|
+
return { signature: (0, import_hwk_adapter_core12.bytesToHex)(signature) };
|
|
4564
|
+
});
|
|
3821
4565
|
}
|
|
3822
4566
|
async function tronSignMessage(ctx, sessionId, params) {
|
|
4567
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3823
4568
|
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
|
-
);
|
|
4569
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4570
|
+
const signature = await tronSigner.signPersonalMessage(path, (0, import_hwk_adapter_core12.hexToBytes)(params.messageHex));
|
|
4571
|
+
return { signature: (0, import_hwk_adapter_core12.bytesToHex)(signature) };
|
|
4572
|
+
});
|
|
3834
4573
|
}
|
|
3835
|
-
async function
|
|
4574
|
+
async function _createTronSigner(ctx, sessionId) {
|
|
3836
4575
|
const dmk = await ctx.getOrCreateDmk();
|
|
3837
|
-
|
|
4576
|
+
const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
|
|
4577
|
+
const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
|
|
4578
|
+
return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
|
|
3838
4579
|
}
|
|
3839
4580
|
|
|
3840
4581
|
// src/device-apps/customActions.ts
|
|
3841
|
-
var
|
|
4582
|
+
var import_device_management_kit2 = require("@ledgerhq/device-management-kit");
|
|
3842
4583
|
var import_rxjs = require("rxjs");
|
|
3843
4584
|
var GetOsVersionDeviceAction = class {
|
|
3844
4585
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
@@ -3852,7 +4593,7 @@ var GetOsVersionDeviceAction = class {
|
|
|
3852
4593
|
(async () => {
|
|
3853
4594
|
try {
|
|
3854
4595
|
subject.next({
|
|
3855
|
-
status:
|
|
4596
|
+
status: import_device_management_kit2.DeviceActionStatus.Pending,
|
|
3856
4597
|
intermediateValue: { requiredUserInteraction: "none" }
|
|
3857
4598
|
});
|
|
3858
4599
|
const result = await internalApi.sendCommand(new this._deps.GetOsVersionCommand());
|
|
@@ -3861,11 +4602,11 @@ var GetOsVersionDeviceAction = class {
|
|
|
3861
4602
|
const errObj = result?.error;
|
|
3862
4603
|
throw new Error(errObj?.message ?? "GetOsVersionCommand failed");
|
|
3863
4604
|
}
|
|
3864
|
-
subject.next({ status:
|
|
4605
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: result.data });
|
|
3865
4606
|
subject.complete();
|
|
3866
4607
|
} catch (err) {
|
|
3867
4608
|
if (cancelled) return;
|
|
3868
|
-
subject.next({ status:
|
|
4609
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
|
|
3869
4610
|
subject.complete();
|
|
3870
4611
|
}
|
|
3871
4612
|
})();
|
|
@@ -3873,7 +4614,7 @@ var GetOsVersionDeviceAction = class {
|
|
|
3873
4614
|
observable: subject.asObservable(),
|
|
3874
4615
|
cancel: () => {
|
|
3875
4616
|
cancelled = true;
|
|
3876
|
-
subject.next({ status:
|
|
4617
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
|
|
3877
4618
|
subject.complete();
|
|
3878
4619
|
}
|
|
3879
4620
|
};
|
|
@@ -3891,7 +4632,7 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3891
4632
|
(async () => {
|
|
3892
4633
|
try {
|
|
3893
4634
|
subject.next({
|
|
3894
|
-
status:
|
|
4635
|
+
status: import_device_management_kit2.DeviceActionStatus.Pending,
|
|
3895
4636
|
intermediateValue: { requiredUserInteraction: "none" }
|
|
3896
4637
|
});
|
|
3897
4638
|
const osVersionResult = await internalApi.sendCommand(new this._GetOsVersionCommand());
|
|
@@ -3908,11 +4649,11 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3908
4649
|
throw new Error(httpErr?.message ?? "Manager API getAppList failed");
|
|
3909
4650
|
}
|
|
3910
4651
|
const apps = either.extract();
|
|
3911
|
-
subject.next({ status:
|
|
4652
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: apps });
|
|
3912
4653
|
subject.complete();
|
|
3913
4654
|
} catch (err) {
|
|
3914
4655
|
if (cancelled) return;
|
|
3915
|
-
subject.next({ status:
|
|
4656
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
|
|
3916
4657
|
subject.complete();
|
|
3917
4658
|
}
|
|
3918
4659
|
})();
|
|
@@ -3920,7 +4661,7 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3920
4661
|
observable: subject.asObservable(),
|
|
3921
4662
|
cancel: () => {
|
|
3922
4663
|
cancelled = true;
|
|
3923
|
-
subject.next({ status:
|
|
4664
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
|
|
3924
4665
|
subject.complete();
|
|
3925
4666
|
}
|
|
3926
4667
|
};
|
|
@@ -4013,7 +4754,7 @@ var DeviceApps = class {
|
|
|
4013
4754
|
seTargetId: v.seTargetId,
|
|
4014
4755
|
mcuTargetId: v.mcuTargetId,
|
|
4015
4756
|
seVersion: v.seVersion,
|
|
4016
|
-
seFlagsHex:
|
|
4757
|
+
seFlagsHex: bytesToHex4(v.seFlags),
|
|
4017
4758
|
mcuSephVersion: v.mcuSephVersion,
|
|
4018
4759
|
mcuBootloaderVersion: v.mcuBootloaderVersion,
|
|
4019
4760
|
hwVersion: v.hwVersion
|
|
@@ -4087,7 +4828,7 @@ var DeviceApps = class {
|
|
|
4087
4828
|
}
|
|
4088
4829
|
}
|
|
4089
4830
|
};
|
|
4090
|
-
function
|
|
4831
|
+
function bytesToHex4(bytes) {
|
|
4091
4832
|
if (!bytes) return "";
|
|
4092
4833
|
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
4093
4834
|
}
|
|
@@ -4130,7 +4871,8 @@ var METHOD_PREFIX_TO_APP_NAME = {
|
|
|
4130
4871
|
evm: "Ethereum",
|
|
4131
4872
|
btc: "Bitcoin",
|
|
4132
4873
|
sol: "Solana",
|
|
4133
|
-
tron: "Tron"
|
|
4874
|
+
tron: "Tron",
|
|
4875
|
+
zcash: "Zcash"
|
|
4134
4876
|
};
|
|
4135
4877
|
var HARDWARE_ERROR_CODE_VALUES = new Set(
|
|
4136
4878
|
Object.values(import_hwk_adapter_core13.HardwareErrorCode).filter((value) => typeof value === "number")
|
|
@@ -4170,6 +4912,10 @@ async function defaultLedgerKitImporter(pkg) {
|
|
|
4170
4912
|
return import("@ledgerhq/device-signer-kit-bitcoin");
|
|
4171
4913
|
case "@ledgerhq/device-signer-kit-solana":
|
|
4172
4914
|
return import("@ledgerhq/device-signer-kit-solana");
|
|
4915
|
+
case "@ledgerhq/device-signer-kit-tron":
|
|
4916
|
+
return import("@ledgerhq/device-signer-kit-tron");
|
|
4917
|
+
case "@ledgerhq/device-signer-kit-zcash":
|
|
4918
|
+
return import("@ledgerhq/device-signer-kit-zcash");
|
|
4173
4919
|
case "@ledgerhq/context-module":
|
|
4174
4920
|
return import("@ledgerhq/context-module");
|
|
4175
4921
|
default:
|
|
@@ -4229,6 +4975,7 @@ var LedgerConnectorBase = class {
|
|
|
4229
4975
|
this._ctx = {
|
|
4230
4976
|
emit: (event, data) => this._emit(event, data),
|
|
4231
4977
|
invalidateSession: (sid) => this._invalidateSession(sid),
|
|
4978
|
+
teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
|
|
4232
4979
|
wrapError: (err, opts) => this._wrapError(err, opts),
|
|
4233
4980
|
getOrCreateDmk: () => this._getOrCreateDmk(),
|
|
4234
4981
|
getDeviceManager: () => this._getDeviceManager(),
|
|
@@ -4418,7 +5165,7 @@ var LedgerConnectorBase = class {
|
|
|
4418
5165
|
this._resetSignersAndSessions();
|
|
4419
5166
|
if (isLedgerBleConnectionType(this.connectionType)) {
|
|
4420
5167
|
const tag = err?._tag;
|
|
4421
|
-
if (isKnownConnectionTag(tag)) {
|
|
5168
|
+
if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
|
|
4422
5169
|
throw err;
|
|
4423
5170
|
}
|
|
4424
5171
|
const wrapped = new Error(
|
|
@@ -4519,7 +5266,7 @@ var LedgerConnectorBase = class {
|
|
|
4519
5266
|
// whitelist (`toPlainError`). The SW-side adapter rehydrates and re-throws
|
|
4520
5267
|
// locally (see LedgerAdapter._unwrapConnectorResult).
|
|
4521
5268
|
async call(sessionId, method, params) {
|
|
4522
|
-
debugLog("[DMK] call:", method, JSON.stringify(params));
|
|
5269
|
+
debugLog("[DMK] call:", method, JSON.stringify(summarizeForLog(params, { method })));
|
|
4523
5270
|
try {
|
|
4524
5271
|
const payload = await this._dispatch(sessionId, method, params);
|
|
4525
5272
|
return { success: true, payload };
|
|
@@ -4587,6 +5334,11 @@ var LedgerConnectorBase = class {
|
|
|
4587
5334
|
return solSignTransaction(ctx, sessionId, params);
|
|
4588
5335
|
case "solSignMessage":
|
|
4589
5336
|
return solSignMessage(ctx, sessionId, params);
|
|
5337
|
+
// ZCASH
|
|
5338
|
+
case "zcashGetFullViewingKey":
|
|
5339
|
+
return zcashGetFullViewingKey(ctx, sessionId, params);
|
|
5340
|
+
case "zcashGetShieldedAddress":
|
|
5341
|
+
return zcashGetShieldedAddress(ctx, sessionId, params);
|
|
4590
5342
|
// TRON
|
|
4591
5343
|
case "tronGetAddress":
|
|
4592
5344
|
return tronGetAddress(ctx, sessionId, params);
|
|
@@ -4620,7 +5372,7 @@ var LedgerConnectorBase = class {
|
|
|
4620
5372
|
});
|
|
4621
5373
|
});
|
|
4622
5374
|
} catch (err) {
|
|
4623
|
-
ctx.
|
|
5375
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4624
5376
|
throw ctx.wrapError(err);
|
|
4625
5377
|
} finally {
|
|
4626
5378
|
ctx.clearCanceller(sessionId);
|
|
@@ -4710,7 +5462,7 @@ var LedgerConnectorBase = class {
|
|
|
4710
5462
|
);
|
|
4711
5463
|
return { isGenuine: output.isGenuine, deviceId };
|
|
4712
5464
|
} catch (err) {
|
|
4713
|
-
ctx.
|
|
5465
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4714
5466
|
throw ctx.wrapError(err);
|
|
4715
5467
|
} finally {
|
|
4716
5468
|
ctx.clearCanceller(sessionId);
|
|
@@ -4832,6 +5584,17 @@ var LedgerConnectorBase = class {
|
|
|
4832
5584
|
_invalidateSession(sessionId) {
|
|
4833
5585
|
this._signerManager?.invalidate(sessionId);
|
|
4834
5586
|
}
|
|
5587
|
+
_teardownSecureChannelSession(sessionId) {
|
|
5588
|
+
const cancel = this._cancellers.get(sessionId);
|
|
5589
|
+
this._cancellers.delete(sessionId);
|
|
5590
|
+
if (cancel) {
|
|
5591
|
+
try {
|
|
5592
|
+
cancel();
|
|
5593
|
+
} catch {
|
|
5594
|
+
}
|
|
5595
|
+
}
|
|
5596
|
+
this._invalidateSession(sessionId);
|
|
5597
|
+
}
|
|
4835
5598
|
/**
|
|
4836
5599
|
* Replace an old session with a new one after app switch.
|
|
4837
5600
|
* Emits device-connect so the adapter updates its _sessions Map.
|
|
@@ -4916,7 +5679,7 @@ var LedgerConnectorBase = class {
|
|
|
4916
5679
|
* at every catch site. Falls through unchanged for unknown methods.
|
|
4917
5680
|
*/
|
|
4918
5681
|
_ctxForMethod(method) {
|
|
4919
|
-
const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
|
|
5682
|
+
const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
|
|
4920
5683
|
const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
|
|
4921
5684
|
if (!defaultAppName) return this._ctx;
|
|
4922
5685
|
return {
|
|
@@ -4950,6 +5713,204 @@ var LedgerConnectorBase = class {
|
|
|
4950
5713
|
return error;
|
|
4951
5714
|
}
|
|
4952
5715
|
};
|
|
5716
|
+
|
|
5717
|
+
// src/transport/DmkTransport.ts
|
|
5718
|
+
var import_hw_transport = __toESM(require("@ledgerhq/hw-transport"));
|
|
5719
|
+
var DmkTransport = class extends import_hw_transport.default {
|
|
5720
|
+
constructor(dmk, sessionId) {
|
|
5721
|
+
super();
|
|
5722
|
+
this._dmk = dmk;
|
|
5723
|
+
this._sessionId = sessionId;
|
|
5724
|
+
}
|
|
5725
|
+
async exchange(apdu) {
|
|
5726
|
+
const response = await this._dmk.sendApdu({
|
|
5727
|
+
sessionId: this._sessionId,
|
|
5728
|
+
apdu: new Uint8Array(apdu)
|
|
5729
|
+
});
|
|
5730
|
+
const { data, statusCode } = response;
|
|
5731
|
+
const result = Buffer.alloc(data.length + 2);
|
|
5732
|
+
if (data.length > 0) {
|
|
5733
|
+
result.set(data, 0);
|
|
5734
|
+
}
|
|
5735
|
+
result.set(statusCode, data.length);
|
|
5736
|
+
return result;
|
|
5737
|
+
}
|
|
5738
|
+
async close() {
|
|
5739
|
+
}
|
|
5740
|
+
};
|
|
5741
|
+
|
|
5742
|
+
// src/app/AppManager.ts
|
|
5743
|
+
var import_device_management_kit3 = require("@ledgerhq/device-management-kit");
|
|
5744
|
+
var import_hwk_adapter_core14 = require("@onekeyfe/hwk-adapter-core");
|
|
5745
|
+
var APP_NAME_MAP = {
|
|
5746
|
+
ETH: "Ethereum",
|
|
5747
|
+
BTC: "Bitcoin",
|
|
5748
|
+
SOL: "Solana",
|
|
5749
|
+
TRX: "Tron",
|
|
5750
|
+
ZEC: "Zcash",
|
|
5751
|
+
XRP: "XRP",
|
|
5752
|
+
ADA: "Cardano",
|
|
5753
|
+
DOT: "Polkadot",
|
|
5754
|
+
ATOM: "Cosmos"
|
|
5755
|
+
};
|
|
5756
|
+
var DASHBOARD_APP_NAME = "BOLOS";
|
|
5757
|
+
var AppManager = class {
|
|
5758
|
+
constructor(dmk, options) {
|
|
5759
|
+
this._dmk = dmk;
|
|
5760
|
+
this._waitMs = options?.waitMs ?? 1e3;
|
|
5761
|
+
this._maxRetries = options?.maxRetries ?? 10;
|
|
5762
|
+
}
|
|
5763
|
+
/**
|
|
5764
|
+
* Return the Ledger app name for a given chain ticker,
|
|
5765
|
+
* or undefined if the chain is not supported.
|
|
5766
|
+
*/
|
|
5767
|
+
static getAppName(chain) {
|
|
5768
|
+
return APP_NAME_MAP[chain];
|
|
5769
|
+
}
|
|
5770
|
+
/**
|
|
5771
|
+
* Ensure the target app is open on the device identified by `sessionId`.
|
|
5772
|
+
*
|
|
5773
|
+
* Flow:
|
|
5774
|
+
* 1. Check the currently running app.
|
|
5775
|
+
* 2. If it is already the target, return immediately.
|
|
5776
|
+
* 3. If a different app is running (not dashboard), close it first.
|
|
5777
|
+
* 4. Open the target app.
|
|
5778
|
+
* 5. Poll until the device confirms the target app is running.
|
|
5779
|
+
*/
|
|
5780
|
+
/**
|
|
5781
|
+
* @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
|
|
5782
|
+
* device is about to display "Open <app>" on screen and wait for the
|
|
5783
|
+
* user's button press. UI consumers should show their "open app" prompt
|
|
5784
|
+
* in response. NOT called when the target app is already open (no user
|
|
5785
|
+
* interaction needed in that case).
|
|
5786
|
+
*
|
|
5787
|
+
* Important: OpenAppCommand is blocking. It does not resolve until the user
|
|
5788
|
+
* has physically confirmed on the device, so anything that runs AFTER
|
|
5789
|
+
* `await this._openApp(...)` lands AFTER the prompt is already gone.
|
|
5790
|
+
* Hence the callback must fire BEFORE that await.
|
|
5791
|
+
*/
|
|
5792
|
+
async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
|
|
5793
|
+
const currentApp = await this._getCurrentApp(sessionId);
|
|
5794
|
+
if (currentApp === targetAppName) {
|
|
5795
|
+
return;
|
|
5796
|
+
}
|
|
5797
|
+
if (!this._isDashboard(currentApp)) {
|
|
5798
|
+
await this._closeCurrentApp(sessionId);
|
|
5799
|
+
await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
|
|
5800
|
+
}
|
|
5801
|
+
onConfirmOnDevice?.();
|
|
5802
|
+
await this._openApp(sessionId, targetAppName);
|
|
5803
|
+
await this._waitForApp(sessionId, targetAppName);
|
|
5804
|
+
}
|
|
5805
|
+
// ---------------------------------------------------------------------------
|
|
5806
|
+
// Private helpers
|
|
5807
|
+
// ---------------------------------------------------------------------------
|
|
5808
|
+
async _getCurrentApp(sessionId) {
|
|
5809
|
+
const result = await this._dmk.sendCommand({
|
|
5810
|
+
sessionId,
|
|
5811
|
+
command: new import_device_management_kit3.GetAppAndVersionCommand()
|
|
5812
|
+
});
|
|
5813
|
+
if ((0, import_device_management_kit3.isSuccessCommandResult)(result)) {
|
|
5814
|
+
debugLog("[AppManager] currentApp:", result.data.name);
|
|
5815
|
+
return result.data.name;
|
|
5816
|
+
}
|
|
5817
|
+
const errResult = result;
|
|
5818
|
+
const dmkErr = errResult.error ?? {};
|
|
5819
|
+
const original = dmkErr.originalError;
|
|
5820
|
+
debugLog(
|
|
5821
|
+
"[AppManager] _getCurrentApp failed sessionId=",
|
|
5822
|
+
sessionId,
|
|
5823
|
+
"tag=",
|
|
5824
|
+
dmkErr._tag,
|
|
5825
|
+
"errorCode=",
|
|
5826
|
+
dmkErr.errorCode,
|
|
5827
|
+
"message=",
|
|
5828
|
+
dmkErr.message,
|
|
5829
|
+
"originalErrorMessage=",
|
|
5830
|
+
original?.message ?? String(original ?? "")
|
|
5831
|
+
);
|
|
5832
|
+
throw Object.assign(
|
|
5833
|
+
new Error(
|
|
5834
|
+
dmkErr.message ?? "Failed to get current app from device"
|
|
5835
|
+
),
|
|
5836
|
+
{
|
|
5837
|
+
_tag: dmkErr._tag,
|
|
5838
|
+
errorCode: dmkErr.errorCode,
|
|
5839
|
+
originalError: original
|
|
5840
|
+
}
|
|
5841
|
+
);
|
|
5842
|
+
}
|
|
5843
|
+
async _openApp(sessionId, appName) {
|
|
5844
|
+
const result = await this._dmk.sendCommand({
|
|
5845
|
+
sessionId,
|
|
5846
|
+
command: new import_device_management_kit3.OpenAppCommand({ appName })
|
|
5847
|
+
});
|
|
5848
|
+
if (!(0, import_device_management_kit3.isSuccessCommandResult)(result)) {
|
|
5849
|
+
const dmkErr = result.error;
|
|
5850
|
+
const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
|
|
5851
|
+
const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
|
|
5852
|
+
debugLog(
|
|
5853
|
+
"[AppManager] openApp failed:",
|
|
5854
|
+
appName,
|
|
5855
|
+
"errorCode:",
|
|
5856
|
+
errorCode,
|
|
5857
|
+
"tag:",
|
|
5858
|
+
dmkErr._tag
|
|
5859
|
+
);
|
|
5860
|
+
let code;
|
|
5861
|
+
if (errorCode === "6807" || /unknown application/i.test(message)) {
|
|
5862
|
+
code = import_hwk_adapter_core14.HardwareErrorCode.AppNotInstalled;
|
|
5863
|
+
} else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
|
|
5864
|
+
code = import_hwk_adapter_core14.HardwareErrorCode.UserRejected;
|
|
5865
|
+
}
|
|
5866
|
+
throw Object.assign(new Error(`Failed to open "${appName}"`), {
|
|
5867
|
+
_tag: ERROR_TAG.OpenAppCommand,
|
|
5868
|
+
code,
|
|
5869
|
+
errorCode,
|
|
5870
|
+
statusCode: errorCode,
|
|
5871
|
+
appName,
|
|
5872
|
+
originalError: dmkErr
|
|
5873
|
+
});
|
|
5874
|
+
}
|
|
5875
|
+
}
|
|
5876
|
+
async _closeCurrentApp(sessionId) {
|
|
5877
|
+
debugLog("[AppManager] closeCurrentApp");
|
|
5878
|
+
await this._dmk.sendCommand({
|
|
5879
|
+
sessionId,
|
|
5880
|
+
command: new import_device_management_kit3.CloseAppCommand()
|
|
5881
|
+
});
|
|
5882
|
+
}
|
|
5883
|
+
/**
|
|
5884
|
+
* Poll the device until the expected app is reported as running,
|
|
5885
|
+
* or throw after `_maxRetries` attempts.
|
|
5886
|
+
*/
|
|
5887
|
+
async _waitForApp(sessionId, expectedAppName) {
|
|
5888
|
+
let lastSeen = "";
|
|
5889
|
+
for (let i = 0; i < this._maxRetries; i++) {
|
|
5890
|
+
await this._wait();
|
|
5891
|
+
const current = await this._getCurrentApp(sessionId);
|
|
5892
|
+
lastSeen = current;
|
|
5893
|
+
if (current === expectedAppName) {
|
|
5894
|
+
return;
|
|
5895
|
+
}
|
|
5896
|
+
}
|
|
5897
|
+
debugLog(
|
|
5898
|
+
"[AppManager] waitForApp exhausted: expected=",
|
|
5899
|
+
expectedAppName,
|
|
5900
|
+
"lastSeen=",
|
|
5901
|
+
lastSeen
|
|
5902
|
+
);
|
|
5903
|
+
throw new Error(
|
|
5904
|
+
`Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
|
|
5905
|
+
);
|
|
5906
|
+
}
|
|
5907
|
+
_isDashboard(appName) {
|
|
5908
|
+
return appName === DASHBOARD_APP_NAME;
|
|
5909
|
+
}
|
|
5910
|
+
_wait() {
|
|
5911
|
+
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
5912
|
+
}
|
|
5913
|
+
};
|
|
4953
5914
|
// Annotate the CommonJS export names for ESM import in node:
|
|
4954
5915
|
0 && (module.exports = {
|
|
4955
5916
|
AppManager,
|
|
@@ -4961,6 +5922,7 @@ var LedgerConnectorBase = class {
|
|
|
4961
5922
|
SignerEth,
|
|
4962
5923
|
SignerManager,
|
|
4963
5924
|
SignerSol,
|
|
5925
|
+
SignerZcash,
|
|
4964
5926
|
debugLog,
|
|
4965
5927
|
deviceActionToPromise,
|
|
4966
5928
|
isDeviceLockedError,
|