@onekeyfe/hwk-ledger-adapter 1.2.8 → 1.2.9
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 +97 -52
- package/dist/index.d.ts +97 -52
- package/dist/index.js +2086 -992
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2034 -914
- package/dist/index.mjs.map +1 -1
- package/package.json +14 -11
package/dist/index.mjs
CHANGED
|
@@ -6,30 +6,43 @@ import {
|
|
|
6
6
|
DeviceJobQueue,
|
|
7
7
|
EConnectorInteraction,
|
|
8
8
|
HardwareErrorCode as HardwareErrorCode3,
|
|
9
|
+
OperationRegistry,
|
|
10
|
+
SDK,
|
|
9
11
|
TypedEventEmitter,
|
|
10
12
|
UI_REQUEST,
|
|
11
13
|
UI_REQUEST_PREEMPTED_TAG,
|
|
12
14
|
UiRequestRegistry,
|
|
15
|
+
canReplayHardwareMethodAfterTransportFailure,
|
|
13
16
|
createHwkError,
|
|
14
17
|
deriveDeviceFingerprint,
|
|
18
|
+
emitDeviceBindingStatus,
|
|
15
19
|
failure as failure2,
|
|
20
|
+
isHardwareOperationId,
|
|
21
|
+
isHwkRecoveryHint,
|
|
22
|
+
operationMayHaveCompletedParams,
|
|
23
|
+
pickConnectionContext,
|
|
16
24
|
rehydrateConnectorError,
|
|
17
|
-
|
|
25
|
+
requestBleDeviceSelection,
|
|
26
|
+
requestSaveDeviceBinding,
|
|
27
|
+
success as success2,
|
|
28
|
+
toPhysicalDeviceSearchTarget
|
|
18
29
|
} from "@onekeyfe/hwk-adapter-core";
|
|
19
30
|
|
|
20
31
|
// src/errors.ts
|
|
21
|
-
import {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
function ledgerFailure(code, error, appName, tag, params) {
|
|
32
|
+
import {
|
|
33
|
+
HardwareErrorCode,
|
|
34
|
+
defaultOriginForCode,
|
|
35
|
+
defaultRecoveryForCode,
|
|
36
|
+
enrichErrorMessage
|
|
37
|
+
} from "@onekeyfe/hwk-adapter-core";
|
|
38
|
+
function ledgerFailure(code, error, appName, tag, params, origin, recovery) {
|
|
29
39
|
const payload = { error, code };
|
|
30
40
|
if (appName !== void 0) payload.appName = appName;
|
|
31
41
|
if (tag !== void 0) payload._tag = tag;
|
|
32
42
|
if (params !== void 0) payload.params = params;
|
|
43
|
+
const resolvedOrigin = origin ?? defaultOriginForCode(code);
|
|
44
|
+
if (resolvedOrigin !== void 0) payload.origin = resolvedOrigin;
|
|
45
|
+
payload.recovery = recovery ?? defaultRecoveryForCode(code);
|
|
33
46
|
return { success: false, payload };
|
|
34
47
|
}
|
|
35
48
|
var LOCKED_ERROR_CODES = /* @__PURE__ */ new Set(["5515", "21781", "6982", "27010", "5303", "21251"]);
|
|
@@ -170,7 +183,10 @@ var ERROR_TAG = {
|
|
|
170
183
|
UnknownDevice: "UnknownDeviceError",
|
|
171
184
|
DeviceSessionRefresher: "DeviceSessionRefresherError",
|
|
172
185
|
DeviceNotInitialized: "DeviceNotInitializedError",
|
|
173
|
-
|
|
186
|
+
// DMK class OpeningConnectionError carries `_tag` "ConnectionOpeningError"; both
|
|
187
|
+
// spellings are kept so a DMK release that aligns them still classifies.
|
|
188
|
+
OpeningConnection: "ConnectionOpeningError",
|
|
189
|
+
OpeningConnectionLegacy: "OpeningConnectionError",
|
|
174
190
|
DeviceDisconnectedBeforeSendingApdu: "DeviceDisconnectedBeforeSendingApdu",
|
|
175
191
|
DeviceDisconnectedWhileSending: "DeviceDisconnectedWhileSendingError",
|
|
176
192
|
Disconnect: "DisconnectError",
|
|
@@ -180,10 +196,20 @@ var ERROR_TAG = {
|
|
|
180
196
|
// outcome when the user doesn't confirm pairing on the device, or the
|
|
181
197
|
// existing bond is invalid. Observed in production after ~30s.
|
|
182
198
|
PairingRefused: "PairingRefusedError",
|
|
199
|
+
PeerRemovedPairing: "PeerRemovedPairingError",
|
|
183
200
|
// DMK remote-network failures (manager-api HTTP / secure-channel WS).
|
|
184
201
|
WebSocketConnection: "WebSocketConnectionError",
|
|
185
202
|
HttpFetch: "FetchError",
|
|
186
|
-
|
|
203
|
+
NetworkDA: "NetworkDAError",
|
|
204
|
+
InvalidFirmwareMetadataResponse: "InvalidGetFirmwareMetadataResponseError",
|
|
205
|
+
ApplicationsMetadataTask: "GetApplicationsMetadataTaskError",
|
|
206
|
+
// DMK OS device actions. SecureChannelError is what mapInstallDAErrors() leaves
|
|
207
|
+
// after splitting out device answers, i.e. the relay itself broke.
|
|
208
|
+
SecureChannel: "SecureChannelError",
|
|
209
|
+
RefusedByUserDA: "RefusedByUserDAError",
|
|
210
|
+
AppAlreadyInstalledDA: "AppAlreadyInstalledDAError",
|
|
211
|
+
OutOfMemoryDA: "OutOfMemoryDAError",
|
|
212
|
+
DeviceNotOnboarded: "DeviceNotOnboardedError"
|
|
187
213
|
};
|
|
188
214
|
function isDeviceLockedError(err) {
|
|
189
215
|
if (!err || typeof err !== "object") return false;
|
|
@@ -199,6 +225,27 @@ function isDeviceNotAdvertisingError(err) {
|
|
|
199
225
|
if (!err || typeof err !== "object") return false;
|
|
200
226
|
return err._tag === ERROR_TAG.DeviceNotAdvertising;
|
|
201
227
|
}
|
|
228
|
+
function isBleBondInvalidError(err) {
|
|
229
|
+
const pending = [err];
|
|
230
|
+
const seen = /* @__PURE__ */ new Set();
|
|
231
|
+
while (pending.length > 0) {
|
|
232
|
+
const candidate = pending.pop();
|
|
233
|
+
if (candidate && typeof candidate === "object" && !seen.has(candidate)) {
|
|
234
|
+
seen.add(candidate);
|
|
235
|
+
const e = candidate;
|
|
236
|
+
if (e._tag === ERROR_TAG.PeerRemovedPairing || e.iosErrorCode === 14 || e.attErrorCode === 5 || e.nativeErrorDomain === "CBErrorDomain" && e.nativeErrorCode === 14) {
|
|
237
|
+
return true;
|
|
238
|
+
}
|
|
239
|
+
const reason = typeof e.reason === "string" ? e.reason : "";
|
|
240
|
+
const message = typeof e.message === "string" ? e.message : "";
|
|
241
|
+
if (/\bCBErrorDomain:14(?:\s|$)/.test(message) || reason.includes("Peer removed pairing information") || reason.includes("GATT_INSUF_AUTHENTICATION")) {
|
|
242
|
+
return true;
|
|
243
|
+
}
|
|
244
|
+
pending.push(e.originalError, e.err);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
202
249
|
var PAIRING_FAILURE_TAGS = /* @__PURE__ */ new Set([
|
|
203
250
|
ERROR_TAG.BlePairingTimeout,
|
|
204
251
|
ERROR_TAG.BleGattBondingFailed,
|
|
@@ -213,11 +260,11 @@ function isBlePairingFailureError(err) {
|
|
|
213
260
|
return false;
|
|
214
261
|
}
|
|
215
262
|
var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
|
|
216
|
-
ERROR_TAG.DeviceLocked,
|
|
217
263
|
ERROR_TAG.DeviceNotAdvertising,
|
|
218
264
|
ERROR_TAG.BlePairingTimeout,
|
|
219
265
|
ERROR_TAG.BleGattBondingFailed,
|
|
220
266
|
ERROR_TAG.PairingRefused,
|
|
267
|
+
ERROR_TAG.PeerRemovedPairing,
|
|
221
268
|
ERROR_TAG.DeviceNotRecognized,
|
|
222
269
|
ERROR_TAG.NoAccessibleDevice,
|
|
223
270
|
ERROR_TAG.UnknownDevice,
|
|
@@ -225,6 +272,7 @@ var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
|
|
|
225
272
|
ERROR_TAG.DeviceSessionRefresher,
|
|
226
273
|
ERROR_TAG.DeviceNotInitialized,
|
|
227
274
|
ERROR_TAG.OpeningConnection,
|
|
275
|
+
ERROR_TAG.OpeningConnectionLegacy,
|
|
228
276
|
ERROR_TAG.DeviceDisconnectedBeforeSendingApdu,
|
|
229
277
|
ERROR_TAG.DeviceDisconnectedWhileSending,
|
|
230
278
|
ERROR_TAG.Disconnect,
|
|
@@ -239,7 +287,10 @@ var DEVICE_NOT_FOUND_TAGS = /* @__PURE__ */ new Set([
|
|
|
239
287
|
// Map to DeviceNotFound so non-BLE-direct paths get a sensible error code.
|
|
240
288
|
ERROR_TAG.DeviceNotInDiscoveryCache
|
|
241
289
|
]);
|
|
242
|
-
var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
|
|
290
|
+
var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
|
|
291
|
+
ERROR_TAG.OpeningConnection,
|
|
292
|
+
ERROR_TAG.OpeningConnectionLegacy
|
|
293
|
+
]);
|
|
243
294
|
var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
|
|
244
295
|
ERROR_TAG.DeviceNotRecognized,
|
|
245
296
|
ERROR_TAG.DeviceSessionNotFound,
|
|
@@ -251,17 +302,18 @@ var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
|
|
|
251
302
|
ERROR_TAG.WebHIDDisconnect
|
|
252
303
|
]);
|
|
253
304
|
function isConnectionLevelError(err) {
|
|
254
|
-
|
|
255
|
-
const tag = err._tag;
|
|
256
|
-
if (tag && CONNECTION_LEVEL_TAGS.has(tag)) return true;
|
|
257
|
-
const e = err;
|
|
258
|
-
if (e.originalError != null && isConnectionLevelError(e.originalError)) return true;
|
|
259
|
-
if (e.error != null && e._tag && isConnectionLevelError(e.error)) return true;
|
|
260
|
-
return false;
|
|
305
|
+
return hasErrorTag(err, CONNECTION_LEVEL_TAGS);
|
|
261
306
|
}
|
|
262
307
|
function isKnownConnectionTag(tag) {
|
|
263
308
|
return typeof tag === "string" && CONNECTION_LEVEL_TAGS.has(tag);
|
|
264
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
|
+
}
|
|
265
317
|
function hasStatusCode(err, codeSet) {
|
|
266
318
|
if (!err || typeof err !== "object") return false;
|
|
267
319
|
const e = err;
|
|
@@ -297,28 +349,28 @@ function hasInvalidArgumentCode(err) {
|
|
|
297
349
|
if (e.error != null && e._tag && hasInvalidArgumentCode(e.error)) return true;
|
|
298
350
|
return false;
|
|
299
351
|
}
|
|
300
|
-
function
|
|
352
|
+
function hasErrorTag(err, tags) {
|
|
301
353
|
if (!err || typeof err !== "object") return false;
|
|
302
|
-
const tag = err._tag;
|
|
303
|
-
if (tag && DEVICE_NOT_FOUND_TAGS.has(tag)) return true;
|
|
304
354
|
const e = err;
|
|
305
|
-
if (e.
|
|
306
|
-
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;
|
|
307
358
|
return false;
|
|
308
359
|
}
|
|
360
|
+
function isDeviceNotFoundError(err) {
|
|
361
|
+
return hasErrorTag(err, DEVICE_NOT_FOUND_TAGS);
|
|
362
|
+
}
|
|
309
363
|
function isDeviceBusyError(err) {
|
|
310
|
-
|
|
311
|
-
const tag = err._tag;
|
|
312
|
-
if (tag && DEVICE_BUSY_TAGS.has(tag)) return true;
|
|
313
|
-
const e = err;
|
|
314
|
-
if (e.originalError != null && isDeviceBusyError(e.originalError)) return true;
|
|
315
|
-
if (e.error != null && e._tag && isDeviceBusyError(e.error)) return true;
|
|
316
|
-
return false;
|
|
364
|
+
return hasErrorTag(err, DEVICE_BUSY_TAGS);
|
|
317
365
|
}
|
|
366
|
+
var USER_REJECTED_TAGS = /* @__PURE__ */ new Set([
|
|
367
|
+
ERROR_TAG.UserRefusedOnDevice,
|
|
368
|
+
ERROR_TAG.RefusedByUserDA
|
|
369
|
+
]);
|
|
318
370
|
function isUserRejectedError(err) {
|
|
319
371
|
if (!err || typeof err !== "object") return false;
|
|
320
372
|
const e = err;
|
|
321
|
-
if (
|
|
373
|
+
if (hasErrorTag(err, USER_REJECTED_TAGS)) return true;
|
|
322
374
|
if (typeof e.message === "string" && /denied|rejected|refused/i.test(e.message)) return true;
|
|
323
375
|
if (hasStatusCode(err, USER_REJECTED_CODES)) return true;
|
|
324
376
|
return false;
|
|
@@ -349,15 +401,33 @@ function isAppNotInstalledError(err) {
|
|
|
349
401
|
if (hasStatusCode(err, APP_NOT_INSTALLED_CODES)) return true;
|
|
350
402
|
return false;
|
|
351
403
|
}
|
|
404
|
+
var OUT_OF_MEMORY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OutOfMemoryDA]);
|
|
352
405
|
function isOutOfMemoryError(err) {
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
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);
|
|
356
426
|
}
|
|
357
427
|
var NETWORK_ERROR_TAGS = /* @__PURE__ */ new Set([
|
|
358
428
|
ERROR_TAG.WebSocketConnection,
|
|
359
429
|
ERROR_TAG.HttpFetch,
|
|
360
|
-
ERROR_TAG.
|
|
430
|
+
ERROR_TAG.NetworkDA
|
|
361
431
|
]);
|
|
362
432
|
function isNetworkError(err) {
|
|
363
433
|
if (!err || typeof err !== "object") return false;
|
|
@@ -407,23 +477,36 @@ function isTransportStuck(err) {
|
|
|
407
477
|
function isStuckAppStateError(err) {
|
|
408
478
|
return isAppStuckByApdu(err) || isTransportStuck(err);
|
|
409
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
|
+
}
|
|
410
489
|
function mapLedgerError(err, opts) {
|
|
411
490
|
let originalMessage = "Unknown Ledger error";
|
|
412
491
|
if (err instanceof Error) {
|
|
413
492
|
originalMessage = err.message;
|
|
414
493
|
} else if (err && typeof err === "object") {
|
|
415
494
|
const e = err;
|
|
416
|
-
originalMessage = String(
|
|
495
|
+
originalMessage = String(
|
|
496
|
+
e.message ?? nestedErrorMessage(e.originalError) ?? e._tag ?? e.type ?? JSON.stringify(err)
|
|
497
|
+
);
|
|
417
498
|
}
|
|
418
499
|
let code;
|
|
419
500
|
if (isDeviceLockedError(err)) {
|
|
420
501
|
code = HardwareErrorCode.DeviceLocked;
|
|
421
502
|
} else if (isDeviceNotAdvertisingError(err) || isDeviceNotFoundError(err)) {
|
|
422
503
|
code = HardwareErrorCode.DeviceNotFound;
|
|
423
|
-
} else if (
|
|
424
|
-
code = HardwareErrorCode.
|
|
504
|
+
} else if (isBleBondInvalidError(err)) {
|
|
505
|
+
code = HardwareErrorCode.BleBondInvalid;
|
|
425
506
|
} else if (isBlePairingFailureError(err)) {
|
|
426
507
|
code = HardwareErrorCode.BlePairingTimeout;
|
|
508
|
+
} else if (isDeviceBusyError(err)) {
|
|
509
|
+
code = HardwareErrorCode.DeviceBusy;
|
|
427
510
|
} else if (isUserAbortedError(err)) {
|
|
428
511
|
code = HardwareErrorCode.UserAborted;
|
|
429
512
|
} else if (isUserRejectedError(err)) {
|
|
@@ -432,10 +515,18 @@ function mapLedgerError(err, opts) {
|
|
|
432
515
|
code = HardwareErrorCode.WrongApp;
|
|
433
516
|
} else if (isAppNotInstalledError(err)) {
|
|
434
517
|
code = HardwareErrorCode.AppNotInstalled;
|
|
518
|
+
} else if (isAppAlreadyInstalledError(err)) {
|
|
519
|
+
code = HardwareErrorCode.AppAlreadyInstalled;
|
|
435
520
|
} else if (isOutOfMemoryError(err)) {
|
|
436
521
|
code = HardwareErrorCode.DeviceOutOfMemory;
|
|
522
|
+
} else if (isDeviceNotOnboardedError(err)) {
|
|
523
|
+
code = HardwareErrorCode.DeviceNotInitialized;
|
|
524
|
+
} else if (isFirmwareMetadataError(err)) {
|
|
525
|
+
code = HardwareErrorCode.LedgerFirmwareMetadataError;
|
|
437
526
|
} else if (isNetworkError(err)) {
|
|
438
527
|
code = HardwareErrorCode.NetworkError;
|
|
528
|
+
} else if (isSecureChannelError(err)) {
|
|
529
|
+
code = HardwareErrorCode.LedgerSecureChannelError;
|
|
439
530
|
} else if (isDeviceDisconnectedError(err)) {
|
|
440
531
|
code = HardwareErrorCode.DeviceDisconnected;
|
|
441
532
|
} else if (isTimeoutError(err)) {
|
|
@@ -448,11 +539,35 @@ function mapLedgerError(err, opts) {
|
|
|
448
539
|
}
|
|
449
540
|
const errAppName = err && typeof err === "object" ? err.appName : void 0;
|
|
450
541
|
const appName = errAppName ?? opts?.defaultAppName;
|
|
451
|
-
return {
|
|
542
|
+
return {
|
|
543
|
+
code,
|
|
544
|
+
message: enrichErrorMessage(code, originalMessage),
|
|
545
|
+
origin: defaultOriginForCode(code),
|
|
546
|
+
appName
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// src/utils/queueKey.ts
|
|
551
|
+
var LEDGER_DEFAULT_QUEUE_KEY = "__ledger_default__";
|
|
552
|
+
function ledgerQueueKey({
|
|
553
|
+
operationId,
|
|
554
|
+
connectId
|
|
555
|
+
}) {
|
|
556
|
+
return (operationId ?? connectId) || LEDGER_DEFAULT_QUEUE_KEY;
|
|
452
557
|
}
|
|
453
558
|
|
|
454
559
|
// src/adapter/methods/allNetworkGetAddress.ts
|
|
455
|
-
import {
|
|
560
|
+
import {
|
|
561
|
+
HardwareErrorCode as HardwareErrorCode2,
|
|
562
|
+
buildAllNetworkCancelledFailure,
|
|
563
|
+
failure,
|
|
564
|
+
isConnectionLost,
|
|
565
|
+
isUserRefusal,
|
|
566
|
+
isWalletSafetyFailure,
|
|
567
|
+
resolveHardwareOperationTarget,
|
|
568
|
+
runAllNetworkGetAddress,
|
|
569
|
+
success
|
|
570
|
+
} from "@onekeyfe/hwk-adapter-core";
|
|
456
571
|
|
|
457
572
|
// src/utils/sdkEventBus.ts
|
|
458
573
|
var listeners = /* @__PURE__ */ new Set();
|
|
@@ -499,6 +614,32 @@ function debugError(...args) {
|
|
|
499
614
|
emitLog("error", ...args);
|
|
500
615
|
}
|
|
501
616
|
|
|
617
|
+
// src/utils/logSummary.ts
|
|
618
|
+
import { summarizeForLog as summarizeForLogCore } from "@onekeyfe/hwk-adapter-core";
|
|
619
|
+
import { Psbt, Transaction } from "bitcoinjs-lib";
|
|
620
|
+
var HEX_RE = /^(0x)?[0-9a-fA-F]+$/;
|
|
621
|
+
var BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
622
|
+
function parsePsbt(input) {
|
|
623
|
+
if (typeof input !== "string") return Psbt.fromBuffer(input);
|
|
624
|
+
if (HEX_RE.test(input)) return Psbt.fromHex(input.replace(/^0x/i, ""));
|
|
625
|
+
if (BASE64_RE.test(input)) return Psbt.fromBase64(input);
|
|
626
|
+
return void 0;
|
|
627
|
+
}
|
|
628
|
+
var describePsbtForLog = (key, value) => {
|
|
629
|
+
if (key !== "psbt") return void 0;
|
|
630
|
+
try {
|
|
631
|
+
const psbt = parsePsbt(value);
|
|
632
|
+
if (!psbt) return void 0;
|
|
633
|
+
const unsignedTx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());
|
|
634
|
+
return `inputs=${psbt.inputCount} outputs=${psbt.txOutputs.length} txid=${unsignedTx.getId()}`;
|
|
635
|
+
} catch {
|
|
636
|
+
return void 0;
|
|
637
|
+
}
|
|
638
|
+
};
|
|
639
|
+
function summarizeForLog(value, options = {}) {
|
|
640
|
+
return summarizeForLogCore(value, { ...options, describePayload: describePsbtForLog });
|
|
641
|
+
}
|
|
642
|
+
|
|
502
643
|
// src/adapter/methods/allNetworkGetAddress.ts
|
|
503
644
|
var LEDGER_BTC_NETWORK_COIN_MAP = {
|
|
504
645
|
tbtc: "Testnet",
|
|
@@ -509,57 +650,105 @@ var LEDGER_BTC_NETWORK_COIN_MAP = {
|
|
|
509
650
|
var LEDGER_UNSUPPORTED_ALLNETWORK_NETWORKS = /* @__PURE__ */ new Set(["doge", "dogecoin"]);
|
|
510
651
|
function createAllNetworkGetAddress({
|
|
511
652
|
callChain,
|
|
512
|
-
getChainFingerprint
|
|
653
|
+
getChainFingerprint,
|
|
654
|
+
retainOperation,
|
|
655
|
+
errorToFailure,
|
|
656
|
+
createCancelScope,
|
|
657
|
+
releaseBundle
|
|
513
658
|
}) {
|
|
514
659
|
return async function allNetworkGetAddress(connectId, _deviceId, params) {
|
|
515
|
-
debugLog("[LedgerAdapter][REQ]", {
|
|
516
|
-
|
|
660
|
+
debugLog("[LedgerAdapter][REQ]", {
|
|
661
|
+
method: "allNetworkGetAddress",
|
|
662
|
+
connectId,
|
|
663
|
+
itemCount: params.bundle.length
|
|
664
|
+
});
|
|
665
|
+
const target = resolveHardwareOperationTarget(connectId, params.operationId, "ledger");
|
|
666
|
+
if (!target.success) return target;
|
|
667
|
+
const effectiveTargetId = target.payload.targetId ?? "";
|
|
668
|
+
let releaseOperationRetention;
|
|
669
|
+
try {
|
|
670
|
+
releaseOperationRetention = target.payload.operationId ? retainOperation(target.payload.operationId) : void 0;
|
|
671
|
+
} catch (error) {
|
|
672
|
+
return errorToFailure(error);
|
|
673
|
+
}
|
|
674
|
+
const cancelScope = createCancelScope(
|
|
675
|
+
ledgerQueueKey({ operationId: target.payload.operationId, connectId: effectiveTargetId })
|
|
676
|
+
);
|
|
677
|
+
const installContext = {
|
|
678
|
+
walletCheck: { expected: params.bundle.some((item) => Boolean(getItemDeviceId(item))) }
|
|
679
|
+
};
|
|
517
680
|
const commonParams = {
|
|
518
|
-
autoInstallApp: params.autoInstallApp
|
|
681
|
+
autoInstallApp: params.autoInstallApp,
|
|
682
|
+
operationId: target.payload.operationId,
|
|
683
|
+
knownConnections: params.knownConnections,
|
|
684
|
+
extra: params.extra,
|
|
685
|
+
allowDeviceSelection: params.allowDeviceSelection,
|
|
686
|
+
supportedTransports: params.supportedTransports
|
|
519
687
|
};
|
|
520
688
|
const chainFingerprints = /* @__PURE__ */ new Map();
|
|
521
|
-
const
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
689
|
+
const order = params.bundle.map((_item, index) => index).sort(
|
|
690
|
+
(a, b) => Number(Boolean(getItemDeviceId(params.bundle[b]))) - Number(Boolean(getItemDeviceId(params.bundle[a])))
|
|
691
|
+
);
|
|
692
|
+
try {
|
|
693
|
+
const ordered = await runAllNetworkGetAddress({
|
|
694
|
+
connectId: effectiveTargetId,
|
|
695
|
+
deviceId: _deviceId,
|
|
696
|
+
params: { ...params, bundle: order.map((index) => params.bundle[index]) },
|
|
697
|
+
normalizeItem: normalizeLedgerAllNetworkItem,
|
|
698
|
+
buildUnsupportedNetworkResponse: (item) => isUnsupportedLedgerAllNetworkNetwork(item) ? buildUnsupportedNetworkResponse(item) : void 0,
|
|
699
|
+
callItem: async ({ method, chain, item }) => {
|
|
700
|
+
if (cancelScope.signal.aborted)
|
|
701
|
+
return buildAllNetworkCancelledFailure(cancelScope.signal);
|
|
702
|
+
const itemDeviceId = getItemDeviceId(item) ?? chainFingerprints.get(chain) ?? "";
|
|
703
|
+
return callAllNetworkMethod(
|
|
704
|
+
callChain,
|
|
705
|
+
effectiveTargetId,
|
|
706
|
+
itemDeviceId,
|
|
707
|
+
method,
|
|
708
|
+
item,
|
|
709
|
+
commonParams,
|
|
710
|
+
installContext
|
|
711
|
+
);
|
|
712
|
+
},
|
|
713
|
+
attachIdentity: async ({ item, chain, payload }) => attachLedgerIdentity(
|
|
714
|
+
getChainFingerprint,
|
|
715
|
+
effectiveTargetId,
|
|
534
716
|
item,
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
)
|
|
717
|
+
chain,
|
|
718
|
+
payload,
|
|
719
|
+
chainFingerprints,
|
|
720
|
+
installContext,
|
|
721
|
+
cancelScope.signal
|
|
722
|
+
),
|
|
723
|
+
shouldAbortBundle: isTopLevelAllNetworkFailure,
|
|
724
|
+
buildTopLevelFailure: (response) => {
|
|
725
|
+
const code = response.payload?.code ?? HardwareErrorCode2.DeviceMismatch;
|
|
726
|
+
return failure(
|
|
727
|
+
code,
|
|
728
|
+
response.payload?.error ?? "All-network get-address aborted",
|
|
729
|
+
response.payload?.params
|
|
730
|
+
);
|
|
731
|
+
}
|
|
732
|
+
});
|
|
733
|
+
let result = ordered;
|
|
734
|
+
if (ordered.success) {
|
|
735
|
+
const responses = [];
|
|
736
|
+
ordered.payload.forEach((response, position) => {
|
|
737
|
+
responses[order[position]] = response;
|
|
738
|
+
});
|
|
739
|
+
result = success(responses);
|
|
555
740
|
}
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
741
|
+
debugLog("[LedgerAdapter][RES]", {
|
|
742
|
+
method: "allNetworkGetAddress",
|
|
743
|
+
success: result.success,
|
|
744
|
+
payload: summarizeForLog(result, { method: "allNetworkGetAddress", role: "result" })
|
|
745
|
+
});
|
|
746
|
+
return result;
|
|
747
|
+
} finally {
|
|
748
|
+
await releaseBundle(installContext, cancelScope.signal).catch(() => void 0);
|
|
749
|
+
cancelScope.release();
|
|
750
|
+
releaseOperationRetention?.();
|
|
751
|
+
}
|
|
563
752
|
};
|
|
564
753
|
}
|
|
565
754
|
function isTopLevelAllNetworkFailure(response) {
|
|
@@ -567,7 +756,7 @@ function isTopLevelAllNetworkFailure(response) {
|
|
|
567
756
|
return false;
|
|
568
757
|
}
|
|
569
758
|
const code = response.payload?.code;
|
|
570
|
-
return code
|
|
759
|
+
return isWalletSafetyFailure(code) || isUserRefusal(code) || isConnectionLost(code);
|
|
571
760
|
}
|
|
572
761
|
function getItemDeviceId(item) {
|
|
573
762
|
const { deviceId } = item;
|
|
@@ -597,8 +786,18 @@ function normalizeLedgerAllNetworkItem(method, item) {
|
|
|
597
786
|
const coin = LEDGER_BTC_NETWORK_COIN_MAP[item.network];
|
|
598
787
|
return coin ? { ...item, coin } : item;
|
|
599
788
|
}
|
|
600
|
-
async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints) {
|
|
601
|
-
const
|
|
789
|
+
async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints, context, cancelSignal) {
|
|
790
|
+
const knownFingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || "";
|
|
791
|
+
if (!knownFingerprint && cancelSignal.aborted) {
|
|
792
|
+
const cancelled = buildAllNetworkCancelledFailure(cancelSignal);
|
|
793
|
+
return { ...item, success: false, payload: cancelled.payload };
|
|
794
|
+
}
|
|
795
|
+
const fingerprint = knownFingerprint || await bootstrapChainFingerprint(
|
|
796
|
+
getChainFingerprint,
|
|
797
|
+
context.connection?.connectId ?? connectId,
|
|
798
|
+
chain,
|
|
799
|
+
context
|
|
800
|
+
);
|
|
602
801
|
if (!fingerprint) {
|
|
603
802
|
return buildFingerprintBootstrapFailure(item, chain);
|
|
604
803
|
}
|
|
@@ -619,8 +818,8 @@ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain,
|
|
|
619
818
|
}
|
|
620
819
|
};
|
|
621
820
|
}
|
|
622
|
-
async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain) {
|
|
623
|
-
const response = await getChainFingerprint(connectId, chain);
|
|
821
|
+
async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain, context) {
|
|
822
|
+
const response = await getChainFingerprint(connectId, chain, context);
|
|
624
823
|
return response.success ? response.payload : "";
|
|
625
824
|
}
|
|
626
825
|
function buildFingerprintBootstrapFailure(item, chain) {
|
|
@@ -713,7 +912,16 @@ function isLedgerBleDescriptor(connectionType, descriptor) {
|
|
|
713
912
|
function formatDeviceMismatchError(expected, actual) {
|
|
714
913
|
return `Wrong device: expected ${expected}, got ${actual}`;
|
|
715
914
|
}
|
|
915
|
+
function isLostConnectionError(err) {
|
|
916
|
+
return isDeviceDisconnectedError(err) || isDeviceNotAdvertisingError(err) || isTimeoutError(err) || isConnectionLevelError(err);
|
|
917
|
+
}
|
|
716
918
|
var BTC_HIGH_INDEX_THRESHOLD = 100;
|
|
919
|
+
var APP_MANAGEMENT_METHODS = /* @__PURE__ */ new Set([
|
|
920
|
+
"installApp",
|
|
921
|
+
"listInstalledApps",
|
|
922
|
+
"listInstalledNames",
|
|
923
|
+
"listAvailableApps"
|
|
924
|
+
]);
|
|
717
925
|
function btcAccountIndexFromPath(path) {
|
|
718
926
|
const segments = path.replace(/^m\//, "").split("/");
|
|
719
927
|
if (segments.length < 3) return null;
|
|
@@ -724,9 +932,35 @@ function btcAccountIndexFromPath(path) {
|
|
|
724
932
|
var _LedgerAdapter = class _LedgerAdapter {
|
|
725
933
|
constructor(connector, options) {
|
|
726
934
|
this.vendor = "ledger";
|
|
935
|
+
// Cancel frees the DMK action and its intent-queue slot, but cannot retract a
|
|
936
|
+
// confirmation screen the device is already showing.
|
|
937
|
+
this.cancelCapability = "stops-waiting";
|
|
727
938
|
this.emitter = new TypedEventEmitter();
|
|
939
|
+
this._operations = new OperationRegistry({
|
|
940
|
+
vendor: "ledger",
|
|
941
|
+
onEnded: (operation, reason) => {
|
|
942
|
+
this._discardPendingBinding(this._pendingOperationBindings.get(operation.operationId));
|
|
943
|
+
this._pendingOperationBindings.delete(operation.operationId);
|
|
944
|
+
this.emitter.emit(SDK.OPERATION_ENDED, {
|
|
945
|
+
type: SDK.OPERATION_ENDED,
|
|
946
|
+
payload: { operationId: operation.operationId, reason }
|
|
947
|
+
});
|
|
948
|
+
if (reason === "timeout" && !this._bareCallMayUseConnection(operation)) {
|
|
949
|
+
void this._releaseOperationConnection(operation);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
});
|
|
728
953
|
this._discoveredDevices = /* @__PURE__ */ new Map();
|
|
729
954
|
this._sessions = /* @__PURE__ */ new Map();
|
|
955
|
+
// An operation's BLE pick is saved by its first call that gets past the wallet check.
|
|
956
|
+
this._pendingOperationBindings = /* @__PURE__ */ new Map();
|
|
957
|
+
// A one-shot call's unchecked BLE pick, by connectId. It outlives the call only
|
|
958
|
+
// through an unlock retry; any other failure drops it with its session.
|
|
959
|
+
this._pendingPickBindings = /* @__PURE__ */ new Map();
|
|
960
|
+
// Transport each session was opened on, by sessionId. The adapter-wide
|
|
961
|
+
// `_activeConnectionType` moves with every discovery and can go stale.
|
|
962
|
+
this._sessionTransports = /* @__PURE__ */ new Map();
|
|
963
|
+
this._selectedBleReconnectTargets = /* @__PURE__ */ new Map();
|
|
730
964
|
this._uiRegistry = new UiRequestRegistry();
|
|
731
965
|
// BTC App rejects account index >= 100 unless display=true. Cached per
|
|
732
966
|
// adapter instance: first 100+ path asks the user once via UI request,
|
|
@@ -740,21 +974,36 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
740
974
|
this._deviceAuthenticityQueueTail = Promise.resolve();
|
|
741
975
|
// Shared across concurrent callers — only `cancel()` aborts.
|
|
742
976
|
this._doConnectAbortController = null;
|
|
977
|
+
this._unsettledConnectorOperations = /* @__PURE__ */ new Map();
|
|
978
|
+
this._connectorIdleWaiters = /* @__PURE__ */ new Set();
|
|
979
|
+
this._resetPromise = null;
|
|
980
|
+
this._stateGeneration = 0;
|
|
981
|
+
this._connectorTeardownTail = Promise.resolve();
|
|
982
|
+
this._pendingConnectorTeardowns = 0;
|
|
983
|
+
this._activeOperationJobs = /* @__PURE__ */ new Set();
|
|
984
|
+
this._pendingOperationDisconnects = /* @__PURE__ */ new Set();
|
|
743
985
|
this._installProgressLastEmittedValue = -Infinity;
|
|
744
986
|
this.allNetworkGetAddress = createAllNetworkGetAddress({
|
|
745
987
|
callChain: this.callChain.bind(this),
|
|
746
|
-
getChainFingerprint: (connectId, chain) =>
|
|
988
|
+
getChainFingerprint: async (connectId, chain, context) => {
|
|
989
|
+
try {
|
|
990
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
991
|
+
chain,
|
|
992
|
+
(method, params) => this.connectorCall(connectId, method, params, void 0, void 0, void 0, context)
|
|
993
|
+
);
|
|
994
|
+
return success2(fingerprint);
|
|
995
|
+
} catch (error) {
|
|
996
|
+
return this.errorToFailure(error);
|
|
997
|
+
}
|
|
998
|
+
},
|
|
999
|
+
retainOperation: (operationId) => this._operations.retain(operationId),
|
|
1000
|
+
errorToFailure: (error) => this.errorToFailure(error),
|
|
1001
|
+
createCancelScope: (queueKey) => this._jobQueue.createCancelScope(queueKey),
|
|
1002
|
+
releaseBundle: (context, signal) => this._dropUncheckedBundlePick(context, signal)
|
|
747
1003
|
});
|
|
748
1004
|
// ---------------------------------------------------------------------------
|
|
749
1005
|
// Private helpers
|
|
750
1006
|
// ---------------------------------------------------------------------------
|
|
751
|
-
/**
|
|
752
|
-
* Ensure at least one device is connected and return a valid connectId.
|
|
753
|
-
*
|
|
754
|
-
* - If a session already exists for the given connectId, reuse it.
|
|
755
|
-
* - If ANY session exists (Ledger IDs are ephemeral), reuse it.
|
|
756
|
-
* - Otherwise: search → exactly 1 USB device auto-connects; multiple or none throws.
|
|
757
|
-
*/
|
|
758
1007
|
// Mutex for ensureConnected — prevents concurrent calls from establishing duplicate connections
|
|
759
1008
|
this._connectingPromise = null;
|
|
760
1009
|
// ---------------------------------------------------------------------------
|
|
@@ -770,6 +1019,12 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
770
1019
|
});
|
|
771
1020
|
};
|
|
772
1021
|
this.deviceDisconnectHandler = (data) => {
|
|
1022
|
+
const activeOperation = this._operations.findActiveByConnectionKey(data.connectId);
|
|
1023
|
+
if (activeOperation && this._activeOperationJobs.has(activeOperation.operationId)) {
|
|
1024
|
+
this._pendingOperationDisconnects.add(activeOperation.operationId);
|
|
1025
|
+
} else {
|
|
1026
|
+
this._operations.endByConnectionKey(data.connectId, "disconnect");
|
|
1027
|
+
}
|
|
773
1028
|
this._discoveredDevices.delete(data.connectId);
|
|
774
1029
|
this._sessions.delete(data.connectId);
|
|
775
1030
|
this.emitter.emit(DEVICE.DISCONNECT, {
|
|
@@ -778,11 +1033,10 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
778
1033
|
});
|
|
779
1034
|
};
|
|
780
1035
|
// Forward connector `ui-event` to the public hw.emitter so consumers only
|
|
781
|
-
// need to subscribe in one place.
|
|
782
|
-
//
|
|
783
|
-
// exists (race during teardown) we drop. All other variants pass through
|
|
784
|
-
// unchanged.
|
|
1036
|
+
// need to subscribe in one place. The AppInstallProgress variant re-keys
|
|
1037
|
+
// sessionId to connectId via `_sessions`, and drops if no mapping exists.
|
|
785
1038
|
this.uiEventForwarder = (event) => {
|
|
1039
|
+
const operationId = this._activeOperationId();
|
|
786
1040
|
if (event.type === EConnectorInteraction.AppInstallProgress) {
|
|
787
1041
|
let connectId;
|
|
788
1042
|
for (const [cid, sid] of this._sessions) {
|
|
@@ -811,6 +1065,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
811
1065
|
this._installProgressLastEmittedValue = progress;
|
|
812
1066
|
this.emitter.emit("ui-event", {
|
|
813
1067
|
type: EConnectorInteraction.AppInstallProgress,
|
|
1068
|
+
...operationId ? { operationId } : {},
|
|
814
1069
|
payload: {
|
|
815
1070
|
connectId,
|
|
816
1071
|
appName,
|
|
@@ -819,18 +1074,37 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
819
1074
|
});
|
|
820
1075
|
return;
|
|
821
1076
|
}
|
|
822
|
-
this.emitter.emit("ui-event", event);
|
|
1077
|
+
this.emitter.emit("ui-event", operationId ? { ...event, operationId } : event);
|
|
823
1078
|
};
|
|
824
1079
|
this.connector = connector;
|
|
825
1080
|
this._defaultAutoInstallApp = options?.autoInstallApp ?? false;
|
|
826
1081
|
this._jobQueue = new DeviceJobQueue();
|
|
827
1082
|
this.registerEventListeners();
|
|
828
1083
|
}
|
|
1084
|
+
_discardPendingBinding(owner, status = "cancelled") {
|
|
1085
|
+
const pending = owner?.pendingBinding;
|
|
1086
|
+
if (!owner || !pending) return;
|
|
1087
|
+
owner.pendingBinding = void 0;
|
|
1088
|
+
if (pending.requestId === this._bindingSelectionRequestId) this._finishBleBinding(status);
|
|
1089
|
+
}
|
|
1090
|
+
_finishBleBinding(status) {
|
|
1091
|
+
const selectionRequestId = this._bindingSelectionRequestId;
|
|
1092
|
+
this._bindingSelectionRequestId = void 0;
|
|
1093
|
+
if (selectionRequestId) emitDeviceBindingStatus(this.emitter, selectionRequestId, status);
|
|
1094
|
+
}
|
|
1095
|
+
_isBleConnection() {
|
|
1096
|
+
return isLedgerBleConnectionType(this._activeConnectionType ?? this.connector.connectionType);
|
|
1097
|
+
}
|
|
829
1098
|
// Transport
|
|
830
1099
|
get activeTransport() {
|
|
831
|
-
return
|
|
1100
|
+
return this._isBleConnection() ? "ble" : "hid";
|
|
832
1101
|
}
|
|
833
1102
|
getAvailableTransports() {
|
|
1103
|
+
if (this.connector.availableTransports) {
|
|
1104
|
+
return this.connector.availableTransports.map(
|
|
1105
|
+
(transport) => transport === "ble" ? "ble" : "hid"
|
|
1106
|
+
);
|
|
1107
|
+
}
|
|
834
1108
|
return this.activeTransport ? [this.activeTransport] : [];
|
|
835
1109
|
}
|
|
836
1110
|
// Connector is bound at construction; switching requires a new adapter.
|
|
@@ -847,21 +1121,43 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
847
1121
|
* The next operation will re-discover and re-connect automatically.
|
|
848
1122
|
*/
|
|
849
1123
|
resetState() {
|
|
1124
|
+
void this._resetStateAndDisconnectSessions();
|
|
1125
|
+
}
|
|
1126
|
+
_resetStateAndDisconnectSessions() {
|
|
1127
|
+
if (this._resetPromise) return this._resetPromise;
|
|
1128
|
+
const sessionIds = new Set(this._sessions.values());
|
|
1129
|
+
this._stateGeneration += 1;
|
|
1130
|
+
this._finishBleBinding("cancelled");
|
|
1131
|
+
this._operations.endAll("runtime-reset");
|
|
1132
|
+
this._doConnectAbortController?.abort();
|
|
850
1133
|
this._discoveredDevices.clear();
|
|
851
1134
|
this._sessions.clear();
|
|
1135
|
+
this._sessionTransports.clear();
|
|
1136
|
+
this._activeConnectionType = void 0;
|
|
1137
|
+
this._pendingOperationBindings.clear();
|
|
1138
|
+
this._pendingPickBindings.clear();
|
|
1139
|
+
this._selectedBleReconnectTargets.clear();
|
|
852
1140
|
this._connectingPromise = null;
|
|
1141
|
+
this._doConnectAbortController = null;
|
|
853
1142
|
this._uiRegistry.reset();
|
|
854
1143
|
this._jobQueue.clear();
|
|
855
1144
|
this._btcHighIndexConfirmedThisSession = false;
|
|
1145
|
+
const resetPromise = this._runConnectorTeardown(async () => {
|
|
1146
|
+
for (const sessionId of sessionIds) {
|
|
1147
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
1148
|
+
}
|
|
1149
|
+
});
|
|
1150
|
+
this._resetPromise = resetPromise;
|
|
1151
|
+
return resetPromise.finally(() => {
|
|
1152
|
+
if (this._resetPromise === resetPromise) {
|
|
1153
|
+
this._resetPromise = null;
|
|
1154
|
+
}
|
|
1155
|
+
});
|
|
856
1156
|
}
|
|
857
1157
|
async dispose() {
|
|
858
|
-
this.
|
|
859
|
-
this._jobQueue.clear();
|
|
1158
|
+
await this._resetStateAndDisconnectSessions();
|
|
860
1159
|
this.unregisterEventListeners();
|
|
861
1160
|
this.connector.reset();
|
|
862
|
-
this._discoveredDevices.clear();
|
|
863
|
-
this._sessions.clear();
|
|
864
|
-
this._btcHighIndexConfirmedThisSession = false;
|
|
865
1161
|
this.emitter.removeAllListeners();
|
|
866
1162
|
}
|
|
867
1163
|
uiResponse(response) {
|
|
@@ -871,17 +1167,32 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
871
1167
|
// Device management
|
|
872
1168
|
// ---------------------------------------------------------------------------
|
|
873
1169
|
async searchDevices(options) {
|
|
1170
|
+
return this._searchDevices(options);
|
|
1171
|
+
}
|
|
1172
|
+
async _searchDevices(options, signal) {
|
|
874
1173
|
debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
|
|
875
1174
|
try {
|
|
876
1175
|
if (options?.resetSession) {
|
|
877
|
-
this.
|
|
878
|
-
|
|
879
|
-
this.
|
|
880
|
-
|
|
881
|
-
|
|
1176
|
+
await this._resetStateAndDisconnectSessions();
|
|
1177
|
+
} else {
|
|
1178
|
+
await this._connectorTeardownTail;
|
|
1179
|
+
}
|
|
1180
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
1181
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1182
|
+
const stateGeneration = this._stateGeneration;
|
|
1183
|
+
const devices = await this.connector.searchDevices(
|
|
1184
|
+
options?.transportType ? {
|
|
1185
|
+
transportType: options.transportType,
|
|
1186
|
+
waitForAll: options.waitForAllTransports
|
|
1187
|
+
} : void 0
|
|
1188
|
+
);
|
|
1189
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1190
|
+
if (stateGeneration !== this._stateGeneration) {
|
|
1191
|
+
throw createHwkError({
|
|
1192
|
+
code: HardwareErrorCode3.UserAborted,
|
|
1193
|
+
message: "Ledger discovery was reset"
|
|
1194
|
+
});
|
|
882
1195
|
}
|
|
883
|
-
await this._ensureDevicePermission();
|
|
884
|
-
const devices = await this.connector.searchDevices();
|
|
885
1196
|
this._discoveredDevices.clear();
|
|
886
1197
|
for (const d of devices) {
|
|
887
1198
|
if (d.connectId) {
|
|
@@ -889,7 +1200,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
889
1200
|
}
|
|
890
1201
|
}
|
|
891
1202
|
if (this._discoveredDevices.size === 0) {
|
|
892
|
-
await this._ensureDevicePermission();
|
|
1203
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
893
1204
|
}
|
|
894
1205
|
const result = Array.from(this._discoveredDevices.values());
|
|
895
1206
|
debugLog("[LedgerAdapter][RES]", {
|
|
@@ -908,41 +1219,267 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
908
1219
|
throw err;
|
|
909
1220
|
}
|
|
910
1221
|
}
|
|
1222
|
+
async searchDeviceTargets(options) {
|
|
1223
|
+
const devices = await this.searchDevices(options);
|
|
1224
|
+
return devices.map((device) => toPhysicalDeviceSearchTarget("ledger", device));
|
|
1225
|
+
}
|
|
911
1226
|
// USB single-session invariant: evict all sessions, best-effort (see connectDevice).
|
|
912
|
-
async _evictAllSessions() {
|
|
1227
|
+
async _evictAllSessions(preserveOperationId) {
|
|
1228
|
+
this._operations.endAll("explicit", preserveOperationId);
|
|
913
1229
|
if (this._sessions.size === 0) return;
|
|
914
1230
|
const stale = [...this._sessions.values()];
|
|
915
1231
|
this._sessions.clear();
|
|
916
|
-
for (const sid of stale)
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
1232
|
+
for (const sid of stale) this._sessionTransports.delete(sid);
|
|
1233
|
+
await this._runConnectorTeardown(async () => {
|
|
1234
|
+
for (const sid of stale) {
|
|
1235
|
+
try {
|
|
1236
|
+
await this.connector.disconnect(sid);
|
|
1237
|
+
} catch {
|
|
1238
|
+
}
|
|
920
1239
|
}
|
|
921
|
-
}
|
|
1240
|
+
});
|
|
922
1241
|
}
|
|
923
1242
|
static _createDeviceBusyError(method) {
|
|
924
1243
|
return Object.assign(new Error(`Ledger device is busy while calling ${method}`), {
|
|
925
1244
|
code: HardwareErrorCode3.DeviceBusy
|
|
926
1245
|
});
|
|
927
1246
|
}
|
|
928
|
-
async connectDevice(
|
|
1247
|
+
async connectDevice(searchTargetId) {
|
|
1248
|
+
try {
|
|
1249
|
+
return await this._jobQueue.enqueue(
|
|
1250
|
+
searchTargetId || "__ledger_connect__",
|
|
1251
|
+
async (signal) => {
|
|
1252
|
+
const connected = await this._connectTarget(searchTargetId, void 0, signal);
|
|
1253
|
+
if (!connected.success) return connected;
|
|
1254
|
+
return this._createOperation(searchTargetId, connected.payload);
|
|
1255
|
+
},
|
|
1256
|
+
{
|
|
1257
|
+
label: "connectDevice",
|
|
1258
|
+
rejectIfBusy: true,
|
|
1259
|
+
busyError: _LedgerAdapter._createDeviceBusyError("connectDevice")
|
|
1260
|
+
}
|
|
1261
|
+
);
|
|
1262
|
+
} catch (error) {
|
|
1263
|
+
return this.errorToFailure(error);
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
/** Binds the picked BLE device; with a recorded wallet identity it must match first. */
|
|
1267
|
+
async bindBleDevice(params) {
|
|
1268
|
+
const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
|
|
1269
|
+
const identities = identity ? [identity, ...params.fallbackIdentities ?? []] : [];
|
|
1270
|
+
try {
|
|
1271
|
+
return await this._jobQueue.enqueue(
|
|
1272
|
+
"__ledger_bind_ble__",
|
|
1273
|
+
async (signal) => {
|
|
1274
|
+
if (!this.getAvailableTransports().includes("ble")) {
|
|
1275
|
+
throw createHwkError({
|
|
1276
|
+
code: HardwareErrorCode3.TransportNotAvailable,
|
|
1277
|
+
message: "Ledger Bluetooth transport is not available"
|
|
1278
|
+
});
|
|
1279
|
+
}
|
|
1280
|
+
this._activeConnectionType = "ble";
|
|
1281
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
1282
|
+
const attempt = {
|
|
1283
|
+
extra: params.extra,
|
|
1284
|
+
bindingReason: "manual-rebind",
|
|
1285
|
+
deferBindingSave: Boolean(identity)
|
|
1286
|
+
};
|
|
1287
|
+
try {
|
|
1288
|
+
const connectId = await this._connectFirstOrSelect(
|
|
1289
|
+
[],
|
|
1290
|
+
void 0,
|
|
1291
|
+
true,
|
|
1292
|
+
void 0,
|
|
1293
|
+
attempt,
|
|
1294
|
+
signal
|
|
1295
|
+
);
|
|
1296
|
+
const pending = attempt.pendingBinding;
|
|
1297
|
+
if (identity && pending) {
|
|
1298
|
+
attempt.pendingBinding = void 0;
|
|
1299
|
+
const sessionId = this._sessions.get(connectId);
|
|
1300
|
+
if (!sessionId) {
|
|
1301
|
+
throw createHwkError({
|
|
1302
|
+
code: HardwareErrorCode3.DeviceDisconnected,
|
|
1303
|
+
message: "Selected Ledger connection ended"
|
|
1304
|
+
});
|
|
1305
|
+
}
|
|
1306
|
+
const checked = await this._fingerprintFirstOpenableChain(
|
|
1307
|
+
identities,
|
|
1308
|
+
(chain, autoInstallApp) => this._computeChainFingerprint(
|
|
1309
|
+
chain,
|
|
1310
|
+
(method, callParams) => this._runConnectorCall(
|
|
1311
|
+
connectId,
|
|
1312
|
+
method,
|
|
1313
|
+
callParams,
|
|
1314
|
+
signal,
|
|
1315
|
+
void 0,
|
|
1316
|
+
void 0,
|
|
1317
|
+
{ autoInstallApp },
|
|
1318
|
+
{ connection: { connectId, sessionId } }
|
|
1319
|
+
)
|
|
1320
|
+
)
|
|
1321
|
+
);
|
|
1322
|
+
if (checked.fingerprint !== checked.identity.value) {
|
|
1323
|
+
await this._dropSession(connectId, signal);
|
|
1324
|
+
throw createHwkError({
|
|
1325
|
+
code: HardwareErrorCode3.DeviceMismatch,
|
|
1326
|
+
message: formatDeviceMismatchError(checked.identity.value, checked.fingerprint)
|
|
1327
|
+
});
|
|
1328
|
+
}
|
|
1329
|
+
await this._saveSelectedBleBinding(
|
|
1330
|
+
connectId,
|
|
1331
|
+
pending.requestId,
|
|
1332
|
+
attempt,
|
|
1333
|
+
void 0,
|
|
1334
|
+
signal,
|
|
1335
|
+
checked.identity
|
|
1336
|
+
);
|
|
1337
|
+
}
|
|
1338
|
+
if (!attempt.bindingSaved) {
|
|
1339
|
+
await this._dropSession(connectId, signal);
|
|
1340
|
+
throw createHwkError({
|
|
1341
|
+
code: HardwareErrorCode3.UnknownError,
|
|
1342
|
+
message: "Bluetooth binding could not be saved",
|
|
1343
|
+
origin: "host"
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
return success2(connectId);
|
|
1347
|
+
} catch (error) {
|
|
1348
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
1349
|
+
throw error;
|
|
1350
|
+
}
|
|
1351
|
+
},
|
|
1352
|
+
{
|
|
1353
|
+
label: "bindBleDevice",
|
|
1354
|
+
rejectIfBusy: true,
|
|
1355
|
+
busyError: _LedgerAdapter._createDeviceBusyError("bindBleDevice")
|
|
1356
|
+
}
|
|
1357
|
+
);
|
|
1358
|
+
} catch (error) {
|
|
1359
|
+
return this.errorToFailure(error);
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
async acquireOperation(connectId, context) {
|
|
1363
|
+
try {
|
|
1364
|
+
return await this._jobQueue.enqueue(
|
|
1365
|
+
connectId || "__ledger_acquire__",
|
|
1366
|
+
async (signal) => {
|
|
1367
|
+
const transport = this._isBleConnection() ? "ble" : "usb";
|
|
1368
|
+
const hint = context.knownConnections?.find(
|
|
1369
|
+
(connection) => connection.transport === transport
|
|
1370
|
+
);
|
|
1371
|
+
const target = hint && hint.transport !== "qr" ? hint.connectId : connectId;
|
|
1372
|
+
await this._ensureDevicePermission(target, void 0, signal);
|
|
1373
|
+
const attempt = {
|
|
1374
|
+
...context,
|
|
1375
|
+
extra: context.extra ? { ...context.extra } : void 0,
|
|
1376
|
+
// The operation's calls decide whether the pick is the right wallet.
|
|
1377
|
+
deferBindingSave: true
|
|
1378
|
+
};
|
|
1379
|
+
try {
|
|
1380
|
+
const resolvedConnectId = await this.ensureConnected(
|
|
1381
|
+
target,
|
|
1382
|
+
signal,
|
|
1383
|
+
true,
|
|
1384
|
+
void 0,
|
|
1385
|
+
attempt
|
|
1386
|
+
);
|
|
1387
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1388
|
+
const result = this._createOperation(connectId, resolvedConnectId);
|
|
1389
|
+
if (result.success && attempt.pendingBinding) {
|
|
1390
|
+
this._pendingOperationBindings.set(result.payload, attempt);
|
|
1391
|
+
}
|
|
1392
|
+
return result;
|
|
1393
|
+
} catch (error) {
|
|
1394
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
1395
|
+
throw error;
|
|
1396
|
+
}
|
|
1397
|
+
},
|
|
1398
|
+
{
|
|
1399
|
+
label: "acquireOperation",
|
|
1400
|
+
rejectIfBusy: true,
|
|
1401
|
+
busyError: _LedgerAdapter._createDeviceBusyError("acquireOperation")
|
|
1402
|
+
}
|
|
1403
|
+
);
|
|
1404
|
+
} catch (error) {
|
|
1405
|
+
return this.errorToFailure(error);
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
_createOperation(searchTargetId, resolvedConnectId) {
|
|
1409
|
+
this._operations.endByConnectionKey(resolvedConnectId, "explicit");
|
|
1410
|
+
const sessionId = this._sessions.get(resolvedConnectId);
|
|
1411
|
+
if (sessionId) this._operations.endByConnectionKey(sessionId, "explicit");
|
|
1412
|
+
const connectionType = sessionId && this._sessionTransports.get(sessionId) || (this._isBleConnection() ? "ble" : "usb");
|
|
1413
|
+
const device = this._discoveredDevices.get(resolvedConnectId) ?? {
|
|
1414
|
+
vendor: "ledger",
|
|
1415
|
+
model: "unknown",
|
|
1416
|
+
firmwareVersion: "",
|
|
1417
|
+
deviceId: "",
|
|
1418
|
+
connectId: resolvedConnectId,
|
|
1419
|
+
connectionType
|
|
1420
|
+
};
|
|
1421
|
+
const operation = this._operations.create({
|
|
1422
|
+
searchTargetId,
|
|
1423
|
+
connectId: resolvedConnectId,
|
|
1424
|
+
device,
|
|
1425
|
+
connectionType,
|
|
1426
|
+
connectionKeys: [this._sessions.get(resolvedConnectId) ?? ""]
|
|
1427
|
+
});
|
|
1428
|
+
return success2(operation.operationId);
|
|
1429
|
+
}
|
|
1430
|
+
async _connectTarget(connectId, preserveOperationId, signal) {
|
|
929
1431
|
debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
|
|
930
1432
|
try {
|
|
931
|
-
|
|
1433
|
+
this._assertConnectorReady("connectDevice");
|
|
1434
|
+
const discoveredType = this._discoveredDevices.get(connectId)?.connectionType;
|
|
1435
|
+
if (discoveredType === "usb" || discoveredType === "ble") {
|
|
1436
|
+
this._activeConnectionType = discoveredType;
|
|
1437
|
+
}
|
|
1438
|
+
if (this._isBleConnection() && !connectId) {
|
|
932
1439
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
933
1440
|
code: HardwareErrorCode3.DeviceNotFound
|
|
934
1441
|
});
|
|
935
1442
|
}
|
|
936
|
-
|
|
937
|
-
|
|
1443
|
+
await this._ensureDevicePermission(connectId, void 0, signal);
|
|
1444
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1445
|
+
const isMultiTransport = (this.connector.availableTransports?.length ?? 0) > 1;
|
|
1446
|
+
if (!isMultiTransport && this._isBleConnection()) {
|
|
1447
|
+
const previousSessionId = this._sessions.get(connectId);
|
|
1448
|
+
this._operations.endByConnectionKey(connectId, "explicit", preserveOperationId);
|
|
1449
|
+
if (previousSessionId) {
|
|
1450
|
+
this._operations.endByConnectionKey(previousSessionId, "explicit", preserveOperationId);
|
|
1451
|
+
this._sessions.delete(connectId);
|
|
1452
|
+
await this.connector.disconnect(previousSessionId).catch(() => void 0);
|
|
1453
|
+
}
|
|
1454
|
+
} else {
|
|
1455
|
+
await this._evictAllSessions(preserveOperationId);
|
|
1456
|
+
}
|
|
1457
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1458
|
+
const stateGeneration = this._stateGeneration;
|
|
1459
|
+
const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
|
|
1460
|
+
let session;
|
|
1461
|
+
this._connectingConnectId = connectId;
|
|
1462
|
+
try {
|
|
1463
|
+
session = this.connector.availableTransports?.length ? await this.connector.connect(connectId, {
|
|
1464
|
+
transportType: this._activeConnectionType ?? "usb"
|
|
1465
|
+
}) : await this.connector.connect(connectId);
|
|
1466
|
+
if (signal?.aborted || stateGeneration !== this._stateGeneration) {
|
|
1467
|
+
await this.connector.disconnect(session.sessionId).catch(() => void 0);
|
|
1468
|
+
throw Object.assign(new Error("Ledger connection aborted"), {
|
|
1469
|
+
code: HardwareErrorCode3.UserAborted
|
|
1470
|
+
});
|
|
1471
|
+
}
|
|
1472
|
+
} finally {
|
|
1473
|
+
if (this._connectingConnectId === connectId) this._connectingConnectId = void 0;
|
|
1474
|
+
releaseOperation();
|
|
938
1475
|
}
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
this.
|
|
1476
|
+
const resolvedConnectId = session.deviceInfo?.connectId || connectId;
|
|
1477
|
+
this._sessions.set(resolvedConnectId, session.sessionId);
|
|
1478
|
+
this._sessionTransports.set(session.sessionId, this._isBleConnection() ? "ble" : "usb");
|
|
942
1479
|
if (session.deviceInfo) {
|
|
943
|
-
this._discoveredDevices.set(
|
|
1480
|
+
this._discoveredDevices.set(resolvedConnectId, session.deviceInfo);
|
|
944
1481
|
}
|
|
945
|
-
const result =
|
|
1482
|
+
const result = success2(resolvedConnectId);
|
|
946
1483
|
debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
|
|
947
1484
|
return result;
|
|
948
1485
|
} catch (err) {
|
|
@@ -955,30 +1492,84 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
955
1492
|
return failureResult;
|
|
956
1493
|
}
|
|
957
1494
|
}
|
|
958
|
-
async
|
|
1495
|
+
async releaseOperation(operationId) {
|
|
1496
|
+
const operation = this._operations.findActive(operationId);
|
|
1497
|
+
if (operation) this._cancelOperationWork(operation);
|
|
1498
|
+
const endedOperation = this._operations.release(operationId);
|
|
1499
|
+
if (!endedOperation || this._bareCallMayUseConnection(endedOperation)) return;
|
|
1500
|
+
const { connectId } = endedOperation;
|
|
959
1501
|
debugLog("[LedgerAdapter][REQ]", {
|
|
960
|
-
method: "
|
|
1502
|
+
method: "releaseOperation",
|
|
961
1503
|
connectId,
|
|
962
1504
|
params: { connectId }
|
|
963
1505
|
});
|
|
964
1506
|
try {
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
await this.connector.disconnect(sessionId);
|
|
968
|
-
this._sessions.delete(connectId);
|
|
969
|
-
}
|
|
970
|
-
debugLog("[LedgerAdapter][RES]", { method: "disconnectDevice", success: true });
|
|
1507
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1508
|
+
debugLog("[LedgerAdapter][RES]", { method: "releaseOperation", success: true });
|
|
971
1509
|
} catch (err) {
|
|
972
1510
|
const e = err;
|
|
973
1511
|
debugLog("[LedgerAdapter][RES]", {
|
|
974
|
-
method: "
|
|
1512
|
+
method: "releaseOperation",
|
|
975
1513
|
success: false,
|
|
976
1514
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
977
1515
|
});
|
|
978
1516
|
throw err;
|
|
979
1517
|
}
|
|
980
1518
|
}
|
|
981
|
-
|
|
1519
|
+
/**
|
|
1520
|
+
* Ends a released operation's calls and prompts before teardown, which otherwise waits on a call
|
|
1521
|
+
* that waits on a prompt nobody will answer. Device I/O already on the wire still drains.
|
|
1522
|
+
*/
|
|
1523
|
+
_cancelOperationWork(operation) {
|
|
1524
|
+
const { operationId } = operation;
|
|
1525
|
+
const reason = createHwkError({
|
|
1526
|
+
code: HardwareErrorCode3.OperationEnded,
|
|
1527
|
+
message: "Ledger operation was released",
|
|
1528
|
+
params: { operationId, reason: "explicit" }
|
|
1529
|
+
});
|
|
1530
|
+
const queueKey = ledgerQueueKey({ operationId });
|
|
1531
|
+
const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
|
|
1532
|
+
this._jobQueue.cancelActiveAndPending(queueKey, reason);
|
|
1533
|
+
if (!ownsRunningCall) return;
|
|
1534
|
+
this._uiRegistry.cancel(void 0, void 0, operationId);
|
|
1535
|
+
void this.connector.cancel(this._sessions.get(operation.connectId) ?? operation.connectId);
|
|
1536
|
+
}
|
|
1537
|
+
/**
|
|
1538
|
+
* A running call by bare connectId (or still resolving its device by identity) may be on this
|
|
1539
|
+
* connection, e.g. waiting for an unlock; its later stages need it, so it stays cached for that
|
|
1540
|
+
* caller like any bare call's session. A lost connection is torn down regardless.
|
|
1541
|
+
*/
|
|
1542
|
+
_bareCallMayUseConnection(operation) {
|
|
1543
|
+
const activeKey = this._jobQueue.getActiveJob()?.deviceId;
|
|
1544
|
+
return activeKey !== void 0 && !isHardwareOperationId(activeKey) && (activeKey === operation.connectId || activeKey === LEDGER_DEFAULT_QUEUE_KEY || operation.connectionKeys.includes(activeKey));
|
|
1545
|
+
}
|
|
1546
|
+
async _releaseOperationConnection(operation) {
|
|
1547
|
+
const sessionIds = /* @__PURE__ */ new Set();
|
|
1548
|
+
for (const [connectId, sessionId] of this._sessions) {
|
|
1549
|
+
if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
|
|
1550
|
+
this._sessions.delete(connectId);
|
|
1551
|
+
sessionIds.add(sessionId);
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
for (const sessionId of sessionIds) {
|
|
1555
|
+
await this._runConnectorTeardown(
|
|
1556
|
+
() => this.connector.disconnect(sessionId).catch(() => void 0)
|
|
1557
|
+
);
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
async _releaseLostOperationConnection(operationId) {
|
|
1561
|
+
const endedOperation = this._operations.end(operationId, "disconnect");
|
|
1562
|
+
if (!endedOperation) return;
|
|
1563
|
+
this._discoveredDevices.delete(endedOperation.connectId);
|
|
1564
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1565
|
+
}
|
|
1566
|
+
async getDeviceInfo(connectIdOrOperationId, deviceId) {
|
|
1567
|
+
let connectId;
|
|
1568
|
+
try {
|
|
1569
|
+
connectId = isHardwareOperationId(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
|
|
1570
|
+
} catch (error) {
|
|
1571
|
+
return this.errorToFailure(error);
|
|
1572
|
+
}
|
|
982
1573
|
debugLog("[LedgerAdapter][REQ]", {
|
|
983
1574
|
method: "getDeviceInfo",
|
|
984
1575
|
connectId,
|
|
@@ -988,7 +1579,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
988
1579
|
await this._ensureDevicePermission(connectId, deviceId);
|
|
989
1580
|
const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
|
|
990
1581
|
if (cached) {
|
|
991
|
-
const result =
|
|
1582
|
+
const result = success2(cached);
|
|
992
1583
|
debugLog("[LedgerAdapter][RES]", {
|
|
993
1584
|
method: "getDeviceInfo",
|
|
994
1585
|
success: true,
|
|
@@ -1013,11 +1604,19 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1013
1604
|
success: false,
|
|
1014
1605
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
1015
1606
|
});
|
|
1016
|
-
|
|
1607
|
+
return this.errorToFailure(err);
|
|
1017
1608
|
}
|
|
1018
1609
|
}
|
|
1019
|
-
|
|
1020
|
-
|
|
1610
|
+
/** A bundle's BLE pick that no item got past the wallet check is not kept. */
|
|
1611
|
+
async _dropUncheckedBundlePick(context, signal) {
|
|
1612
|
+
const { connection } = context;
|
|
1613
|
+
const owner = connection ? this._pendingPickBindings.get(connection.connectId) : void 0;
|
|
1614
|
+
if (!connection || !owner) return;
|
|
1615
|
+
this._pendingPickBindings.delete(connection.connectId);
|
|
1616
|
+
this._discardPendingBinding(owner, signal.aborted ? "cancelled" : "failed");
|
|
1617
|
+
if (this._sessions.get(connection.connectId) === connection.sessionId) {
|
|
1618
|
+
await this._dropSession(connection.connectId, signal);
|
|
1619
|
+
}
|
|
1021
1620
|
}
|
|
1022
1621
|
// ---------------------------------------------------------------------------
|
|
1023
1622
|
// Chain call helper
|
|
@@ -1037,7 +1636,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1037
1636
|
commonParams,
|
|
1038
1637
|
installContext
|
|
1039
1638
|
);
|
|
1040
|
-
return
|
|
1639
|
+
return success2(result);
|
|
1041
1640
|
} catch (err) {
|
|
1042
1641
|
return this.errorToFailure(err);
|
|
1043
1642
|
}
|
|
@@ -1053,13 +1652,25 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1053
1652
|
if (params && typeof params === "object") {
|
|
1054
1653
|
const {
|
|
1055
1654
|
autoInstallApp,
|
|
1655
|
+
operationId,
|
|
1056
1656
|
passphraseState: _passphraseState,
|
|
1057
1657
|
useEmptyPassphrase: _useEmptyPassphrase,
|
|
1658
|
+
knownConnections,
|
|
1659
|
+
extra,
|
|
1660
|
+
allowDeviceSelection,
|
|
1661
|
+
supportedTransports,
|
|
1058
1662
|
...rest
|
|
1059
1663
|
} = params;
|
|
1060
1664
|
return {
|
|
1061
1665
|
commonParams: {
|
|
1062
|
-
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
|
|
1666
|
+
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
|
|
1667
|
+
operationId: typeof operationId === "string" ? operationId : void 0,
|
|
1668
|
+
...pickConnectionContext({
|
|
1669
|
+
knownConnections,
|
|
1670
|
+
extra,
|
|
1671
|
+
allowDeviceSelection,
|
|
1672
|
+
supportedTransports
|
|
1673
|
+
})
|
|
1063
1674
|
},
|
|
1064
1675
|
rest
|
|
1065
1676
|
};
|
|
@@ -1225,7 +1836,13 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1225
1836
|
params
|
|
1226
1837
|
);
|
|
1227
1838
|
}
|
|
1228
|
-
tronSignMessage(connectId, deviceId, params) {
|
|
1839
|
+
async tronSignMessage(connectId, deviceId, params) {
|
|
1840
|
+
if (params?.messageType !== "V2") {
|
|
1841
|
+
return failure2(
|
|
1842
|
+
HardwareErrorCode3.MethodNotSupported,
|
|
1843
|
+
'Ledger signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
|
|
1844
|
+
);
|
|
1845
|
+
}
|
|
1229
1846
|
return this.callChainWithMergedParams(
|
|
1230
1847
|
connectId,
|
|
1231
1848
|
deviceId,
|
|
@@ -1235,14 +1852,33 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1235
1852
|
);
|
|
1236
1853
|
}
|
|
1237
1854
|
// ---------------------------------------------------------------------------
|
|
1238
|
-
//
|
|
1239
|
-
//
|
|
1240
|
-
|
|
1855
|
+
// Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
|
|
1856
|
+
// ---------------------------------------------------------------------------
|
|
1857
|
+
zcashGetFullViewingKey(connectId, deviceId, params) {
|
|
1858
|
+
return this.callChainWithMergedParams(
|
|
1859
|
+
connectId,
|
|
1860
|
+
deviceId,
|
|
1861
|
+
"zcash",
|
|
1862
|
+
"zcashGetFullViewingKey",
|
|
1863
|
+
params
|
|
1864
|
+
);
|
|
1865
|
+
}
|
|
1866
|
+
zcashGetShieldedAddress(connectId, deviceId, params) {
|
|
1867
|
+
return this.callChainWithMergedParams(
|
|
1868
|
+
connectId,
|
|
1869
|
+
deviceId,
|
|
1870
|
+
"zcash",
|
|
1871
|
+
"zcashGetShieldedAddress",
|
|
1872
|
+
params
|
|
1873
|
+
);
|
|
1874
|
+
}
|
|
1875
|
+
// ---------------------------------------------------------------------------
|
|
1876
|
+
// App management: OS-level app install/list, no fingerprint or chain dispatch.
|
|
1241
1877
|
// ---------------------------------------------------------------------------
|
|
1242
1878
|
async installApp(connectId, appName) {
|
|
1243
1879
|
try {
|
|
1244
1880
|
await this.connectorCall(connectId, "installApp", { appName });
|
|
1245
|
-
return
|
|
1881
|
+
return success2(void 0);
|
|
1246
1882
|
} catch (err) {
|
|
1247
1883
|
return this.errorToFailure(err);
|
|
1248
1884
|
}
|
|
@@ -1250,7 +1886,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1250
1886
|
async listInstalledApps(connectId) {
|
|
1251
1887
|
try {
|
|
1252
1888
|
const result = await this.connectorCall(connectId, "listInstalledApps", {});
|
|
1253
|
-
return
|
|
1889
|
+
return success2(result);
|
|
1254
1890
|
} catch (err) {
|
|
1255
1891
|
return this.errorToFailure(err);
|
|
1256
1892
|
}
|
|
@@ -1259,7 +1895,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1259
1895
|
async listInstalledNames(connectId) {
|
|
1260
1896
|
try {
|
|
1261
1897
|
const result = await this.connectorCall(connectId, "listInstalledNames", {});
|
|
1262
|
-
return
|
|
1898
|
+
return success2(result);
|
|
1263
1899
|
} catch (err) {
|
|
1264
1900
|
return this.errorToFailure(err);
|
|
1265
1901
|
}
|
|
@@ -1267,7 +1903,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1267
1903
|
async listAvailableApps(connectId) {
|
|
1268
1904
|
try {
|
|
1269
1905
|
const result = await this.connectorCall(connectId, "listAvailableApps", {});
|
|
1270
|
-
return
|
|
1906
|
+
return success2(result);
|
|
1271
1907
|
} catch (err) {
|
|
1272
1908
|
return this.errorToFailure(err);
|
|
1273
1909
|
}
|
|
@@ -1275,7 +1911,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1275
1911
|
async getLedgerFirmwareVersion(connectId) {
|
|
1276
1912
|
try {
|
|
1277
1913
|
const result = await this.connectorCall(connectId, "getFirmwareVersion", {});
|
|
1278
|
-
return
|
|
1914
|
+
return success2(result);
|
|
1279
1915
|
} catch (err) {
|
|
1280
1916
|
return this.errorToFailure(err);
|
|
1281
1917
|
}
|
|
@@ -1283,7 +1919,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1283
1919
|
async getLedgerDeviceInfo(connectId) {
|
|
1284
1920
|
try {
|
|
1285
1921
|
const result = await this.connectorCall(connectId, "getDeviceInfo", {});
|
|
1286
|
-
return
|
|
1922
|
+
return success2(result);
|
|
1287
1923
|
} catch (err) {
|
|
1288
1924
|
return this.errorToFailure(err);
|
|
1289
1925
|
}
|
|
@@ -1323,11 +1959,11 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1323
1959
|
);
|
|
1324
1960
|
}
|
|
1325
1961
|
await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
|
|
1326
|
-
this.
|
|
1962
|
+
await this._resetStateAndDisconnectSessions();
|
|
1327
1963
|
}
|
|
1328
1964
|
const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
|
|
1329
1965
|
if (!result.isGenuine) {
|
|
1330
|
-
return
|
|
1966
|
+
return success2({
|
|
1331
1967
|
vendor: "ledger",
|
|
1332
1968
|
verified: false
|
|
1333
1969
|
});
|
|
@@ -1338,7 +1974,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1338
1974
|
`Genuine check completed (isGenuine=${result.isGenuine}) but no deviceId was captured`
|
|
1339
1975
|
);
|
|
1340
1976
|
}
|
|
1341
|
-
return
|
|
1977
|
+
return success2({
|
|
1342
1978
|
vendor: "ledger",
|
|
1343
1979
|
verified: result.isGenuine,
|
|
1344
1980
|
deviceId: result.deviceId
|
|
@@ -1349,10 +1985,10 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1349
1985
|
if (relayUrl) {
|
|
1350
1986
|
try {
|
|
1351
1987
|
await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
|
|
1352
|
-
this.
|
|
1988
|
+
await this._resetStateAndDisconnectSessions();
|
|
1353
1989
|
} catch {
|
|
1354
1990
|
this.connector.reset();
|
|
1355
|
-
this.
|
|
1991
|
+
await this._resetStateAndDisconnectSessions();
|
|
1356
1992
|
}
|
|
1357
1993
|
}
|
|
1358
1994
|
}
|
|
@@ -1364,6 +2000,20 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1364
2000
|
this.emitter.off(event, listener);
|
|
1365
2001
|
}
|
|
1366
2002
|
cancel(connectId) {
|
|
2003
|
+
const namedOperationIsLive = (id) => {
|
|
2004
|
+
try {
|
|
2005
|
+
this._operations.resolve(id);
|
|
2006
|
+
return true;
|
|
2007
|
+
} catch {
|
|
2008
|
+
return false;
|
|
2009
|
+
}
|
|
2010
|
+
};
|
|
2011
|
+
if (isHardwareOperationId(connectId) && !namedOperationIsLive(connectId)) {
|
|
2012
|
+
debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
|
|
2013
|
+
connectId
|
|
2014
|
+
});
|
|
2015
|
+
return;
|
|
2016
|
+
}
|
|
1367
2017
|
const userAbortReason = Object.assign(new Error("User aborted operation"), {
|
|
1368
2018
|
code: HardwareErrorCode3.UserAborted,
|
|
1369
2019
|
_tag: ERROR_TAG.UserAborted
|
|
@@ -1374,60 +2024,163 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1374
2024
|
this._lastCancelReason = void 0;
|
|
1375
2025
|
}
|
|
1376
2026
|
}, 2e3);
|
|
1377
|
-
this.
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
2027
|
+
const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
|
|
2028
|
+
let operationId;
|
|
2029
|
+
if (isHardwareOperationId(connectId)) {
|
|
2030
|
+
operationId = connectId;
|
|
2031
|
+
} else if (!connectId && isHardwareOperationId(activeJobId)) {
|
|
2032
|
+
operationId = activeJobId;
|
|
1382
2033
|
}
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
2034
|
+
let resolvedConnectId = connectId;
|
|
2035
|
+
if (operationId) {
|
|
2036
|
+
try {
|
|
2037
|
+
resolvedConnectId = this._operations.resolve(operationId).connectId;
|
|
2038
|
+
} catch {
|
|
2039
|
+
resolvedConnectId = void 0;
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
|
|
2043
|
+
const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
|
|
2044
|
+
if (!connectId) {
|
|
2045
|
+
this._uiRegistry.cancel();
|
|
2046
|
+
} else if (pendingOperationId) {
|
|
2047
|
+
this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
|
|
2048
|
+
}
|
|
2049
|
+
this._finishBleBinding("cancelled");
|
|
2050
|
+
if (!connectId) this._pendingOperationBindings.clear();
|
|
2051
|
+
else if (pendingOperationId) this._pendingOperationBindings.delete(pendingOperationId);
|
|
2052
|
+
const queueKeys = /* @__PURE__ */ new Set();
|
|
2053
|
+
if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
|
|
2054
|
+
if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
|
|
2055
|
+
if (queueKeys.size) {
|
|
2056
|
+
let cancelledAnyJob = false;
|
|
2057
|
+
for (const key of queueKeys) {
|
|
2058
|
+
cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
|
|
2059
|
+
}
|
|
2060
|
+
debugLog("[LedgerAdapter] cancel routed to queue keys", {
|
|
2061
|
+
queueKeys: [...queueKeys],
|
|
2062
|
+
cancelledAnyJob
|
|
2063
|
+
});
|
|
2064
|
+
} else {
|
|
2065
|
+
this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
|
|
2066
|
+
}
|
|
2067
|
+
const connectingConnectId = this._connectingConnectId;
|
|
2068
|
+
const targetKeys = new Set(
|
|
2069
|
+
[
|
|
2070
|
+
connectId,
|
|
2071
|
+
resolvedConnectId,
|
|
2072
|
+
...pendingOperationId ? this._operations.find(pendingOperationId)?.connectionKeys ?? [] : []
|
|
2073
|
+
].filter(Boolean)
|
|
2074
|
+
);
|
|
2075
|
+
const ownsPendingConnect = !connectId || activeJobId !== void 0 && queueKeys.has(activeJobId) || connectingConnectId !== void 0 && targetKeys.has(connectingConnectId);
|
|
2076
|
+
if (activeJobId === void 0 || ownsPendingConnect) {
|
|
2077
|
+
if (resolvedConnectId) {
|
|
2078
|
+
const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
|
|
2079
|
+
void this.connector.cancel(sessionId);
|
|
2080
|
+
} else {
|
|
2081
|
+
for (const sid of this._sessions.values()) void this.connector.cancel(sid);
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
if (this._connectingPromise && ownsPendingConnect) {
|
|
2085
|
+
this._doConnectAbortController?.abort(userAbortReason);
|
|
1391
2086
|
}
|
|
2087
|
+
if (connectingConnectId && ownsPendingConnect) void this.connector.cancel(connectingConnectId);
|
|
1392
2088
|
}
|
|
1393
2089
|
// ---------------------------------------------------------------------------
|
|
1394
2090
|
// Chain fingerprint
|
|
1395
2091
|
// ---------------------------------------------------------------------------
|
|
2092
|
+
/** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
|
|
1396
2093
|
async getChainFingerprint(connectId, deviceId, chain) {
|
|
1397
2094
|
try {
|
|
1398
2095
|
const fingerprint = await this._computeChainFingerprint(
|
|
1399
2096
|
chain,
|
|
1400
2097
|
(method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
|
|
1401
2098
|
);
|
|
1402
|
-
|
|
2099
|
+
if (deviceId) {
|
|
2100
|
+
if (fingerprint !== deviceId) {
|
|
2101
|
+
return failure2(
|
|
2102
|
+
HardwareErrorCode3.DeviceMismatch,
|
|
2103
|
+
formatDeviceMismatchError(deviceId, fingerprint)
|
|
2104
|
+
);
|
|
2105
|
+
}
|
|
2106
|
+
}
|
|
2107
|
+
return success2(fingerprint);
|
|
1403
2108
|
} catch (err) {
|
|
1404
2109
|
debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
|
|
1405
2110
|
return this.errorToFailure(err);
|
|
1406
2111
|
}
|
|
1407
2112
|
}
|
|
1408
2113
|
/**
|
|
1409
|
-
*
|
|
1410
|
-
*
|
|
2114
|
+
* Fingerprints the first recorded chain whose app the device can open. Only a missing app
|
|
2115
|
+
* moves on to the next chain; when every app is missing, the first chain offers its install.
|
|
1411
2116
|
*/
|
|
1412
|
-
async
|
|
1413
|
-
|
|
2117
|
+
async _fingerprintFirstOpenableChain(identities, fingerprintOf) {
|
|
2118
|
+
const [first] = identities;
|
|
2119
|
+
if (identities.length > 1) {
|
|
2120
|
+
for (const identity of identities) {
|
|
2121
|
+
try {
|
|
2122
|
+
return { identity, fingerprint: await fingerprintOf(identity.chain, false) };
|
|
2123
|
+
} catch (error) {
|
|
2124
|
+
const isAppMissing = isAppNotInstalledError(error) || error?.code === HardwareErrorCode3.AppNotInstalled;
|
|
2125
|
+
if (!isAppMissing) throw error;
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
2129
|
+
return { identity: first, fingerprint: await fingerprintOf(first.chain, true) };
|
|
2130
|
+
}
|
|
2131
|
+
/** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
|
|
2132
|
+
async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
|
|
1414
2133
|
try {
|
|
1415
|
-
const
|
|
1416
|
-
|
|
1417
|
-
|
|
2134
|
+
const outcome = await requestSaveDeviceBinding(
|
|
2135
|
+
this.emitter,
|
|
2136
|
+
this._uiRegistry,
|
|
2137
|
+
{
|
|
2138
|
+
selectionRequestId,
|
|
2139
|
+
connection: { transport: "ble", connectId },
|
|
2140
|
+
...identity ? { identity } : {},
|
|
2141
|
+
extra: context?.extra,
|
|
2142
|
+
operationId
|
|
2143
|
+
},
|
|
2144
|
+
signal
|
|
1418
2145
|
);
|
|
1419
|
-
if (
|
|
1420
|
-
|
|
2146
|
+
if (context) context.bindingSaved = outcome.saved;
|
|
2147
|
+
if (!outcome.saved) {
|
|
2148
|
+
debugLog("[LedgerAdapter] BLE binding not persisted by host", {
|
|
2149
|
+
connectId,
|
|
2150
|
+
reason: outcome.reason
|
|
2151
|
+
});
|
|
1421
2152
|
}
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
2153
|
+
} catch (error) {
|
|
2154
|
+
await this._dropSession(connectId, signal);
|
|
2155
|
+
throw error;
|
|
2156
|
+
} finally {
|
|
2157
|
+
if (this._bindingSelectionRequestId === selectionRequestId) {
|
|
2158
|
+
this._bindingSelectionRequestId = void 0;
|
|
1427
2159
|
}
|
|
1428
|
-
throw err;
|
|
1429
2160
|
}
|
|
1430
2161
|
}
|
|
2162
|
+
async _dropSession(connectId, signal) {
|
|
2163
|
+
const sessionId = this._sessions.get(connectId);
|
|
2164
|
+
this._sessions.delete(connectId);
|
|
2165
|
+
if (!sessionId) return;
|
|
2166
|
+
this._sessionTransports.delete(sessionId);
|
|
2167
|
+
const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
|
|
2168
|
+
() => void 0
|
|
2169
|
+
);
|
|
2170
|
+
if (!signal.aborted) await teardown;
|
|
2171
|
+
}
|
|
2172
|
+
/** Verify on the acquired session without re-entering the job queue. */
|
|
2173
|
+
async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
|
|
2174
|
+
if (!deviceId) return { success: true };
|
|
2175
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
2176
|
+
chain,
|
|
2177
|
+
(method, params) => this._callConnector(sessionId, method, params)
|
|
2178
|
+
);
|
|
2179
|
+
if (fingerprint === deviceId) {
|
|
2180
|
+
return { success: true };
|
|
2181
|
+
}
|
|
2182
|
+
return { success: false, expected: deviceId, actual: fingerprint };
|
|
2183
|
+
}
|
|
1431
2184
|
/**
|
|
1432
2185
|
* Compute the chain fingerprint via a caller-supplied call strategy.
|
|
1433
2186
|
*
|
|
@@ -1455,11 +2208,20 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1455
2208
|
address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
|
|
1456
2209
|
} else if (chain === "tron") {
|
|
1457
2210
|
address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
|
|
2211
|
+
} else if (chain === "zcash") {
|
|
2212
|
+
address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
|
|
1458
2213
|
} else {
|
|
1459
2214
|
throw new Error(`Unsupported chain for fingerprint: ${chain}`);
|
|
1460
2215
|
}
|
|
1461
2216
|
return deriveDeviceFingerprint(address);
|
|
1462
2217
|
}
|
|
2218
|
+
/**
|
|
2219
|
+
* Operation owning the running job, so a mid-call UI request can name it.
|
|
2220
|
+
* Undefined at cold start when no operation owns the job.
|
|
2221
|
+
*/
|
|
2222
|
+
_activeOperationId() {
|
|
2223
|
+
return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
|
|
2224
|
+
}
|
|
1463
2225
|
// Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
|
|
1464
2226
|
// The user must press Confirm after unlocking, which triggers a search retry.
|
|
1465
2227
|
// If `signal` is provided, an abort cancels the pending UI request so the
|
|
@@ -1469,15 +2231,18 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1469
2231
|
if (signal?.aborted) {
|
|
1470
2232
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1471
2233
|
}
|
|
2234
|
+
const operationId = this._activeOperationId();
|
|
1472
2235
|
const waitPromise = this._uiRegistry.wait(
|
|
1473
|
-
UI_REQUEST.REQUEST_DEVICE_CONNECT
|
|
2236
|
+
UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
2237
|
+
{ operationId }
|
|
1474
2238
|
);
|
|
1475
2239
|
this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_CONNECT, {
|
|
1476
2240
|
type: UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
1477
2241
|
payload: {
|
|
1478
2242
|
vendor: "ledger",
|
|
1479
2243
|
reason: "device-not-found",
|
|
1480
|
-
message: "Please connect and unlock your Ledger device"
|
|
2244
|
+
message: "Please connect and unlock your Ledger device",
|
|
2245
|
+
operationId
|
|
1481
2246
|
}
|
|
1482
2247
|
});
|
|
1483
2248
|
let payload;
|
|
@@ -1498,7 +2263,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1498
2263
|
} catch (err) {
|
|
1499
2264
|
this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
1500
2265
|
type: UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1501
|
-
payload: {}
|
|
2266
|
+
payload: { operationId }
|
|
1502
2267
|
});
|
|
1503
2268
|
throw Object.assign(new Error("User cancelled Ledger connection"), {
|
|
1504
2269
|
_tag: ERROR_TAG.UserAborted,
|
|
@@ -1523,7 +2288,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1523
2288
|
* Returns the params to pass through (with `showOnDevice` possibly
|
|
1524
2289
|
* promoted), or `null` if the user declined.
|
|
1525
2290
|
*/
|
|
1526
|
-
async _gateBtcHighIndex(params) {
|
|
2291
|
+
async _gateBtcHighIndex(params, signal) {
|
|
1527
2292
|
const accountIndex = btcAccountIndexFromPath(params.path);
|
|
1528
2293
|
if (params.showOnDevice) return params;
|
|
1529
2294
|
if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
|
|
@@ -1532,51 +2297,75 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1532
2297
|
if (this._btcHighIndexConfirmedThisSession) {
|
|
1533
2298
|
return { ...params, showOnDevice: true };
|
|
1534
2299
|
}
|
|
1535
|
-
const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
|
|
2300
|
+
const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
|
|
1536
2301
|
if (!confirmed) return null;
|
|
1537
2302
|
this._btcHighIndexConfirmedThisSession = true;
|
|
1538
2303
|
return { ...params, showOnDevice: true };
|
|
1539
2304
|
}
|
|
1540
|
-
async _waitForBtcHighIndexConfirm(path, accountIndex) {
|
|
2305
|
+
async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
|
|
2306
|
+
const operationId = this._activeOperationId();
|
|
1541
2307
|
const waitPromise = this._uiRegistry.wait(
|
|
1542
|
-
UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM
|
|
2308
|
+
UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2309
|
+
{ operationId }
|
|
1543
2310
|
);
|
|
1544
2311
|
this.emitter.emit(UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
|
|
1545
2312
|
type: UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
1546
2313
|
payload: {
|
|
1547
2314
|
vendor: "ledger",
|
|
1548
2315
|
path,
|
|
1549
|
-
accountIndex
|
|
2316
|
+
accountIndex,
|
|
2317
|
+
operationId
|
|
1550
2318
|
}
|
|
1551
2319
|
});
|
|
1552
2320
|
try {
|
|
1553
|
-
const payload = await
|
|
2321
|
+
const payload = await this._awaitUiAnswer(
|
|
2322
|
+
UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2323
|
+
waitPromise,
|
|
2324
|
+
signal
|
|
2325
|
+
);
|
|
1554
2326
|
return !!payload?.confirmed;
|
|
1555
2327
|
} catch (err) {
|
|
1556
2328
|
this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
1557
2329
|
type: UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1558
|
-
payload: {}
|
|
2330
|
+
payload: { operationId }
|
|
1559
2331
|
});
|
|
1560
2332
|
return false;
|
|
1561
2333
|
}
|
|
1562
2334
|
}
|
|
2335
|
+
/** A cancel of the job ends its open prompt, even when no operation names that prompt. */
|
|
2336
|
+
async _awaitUiAnswer(requestType, waitPromise, signal) {
|
|
2337
|
+
const onAbort = () => this._uiRegistry.cancel(requestType);
|
|
2338
|
+
if (signal.aborted) onAbort();
|
|
2339
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2340
|
+
try {
|
|
2341
|
+
return await waitPromise;
|
|
2342
|
+
} finally {
|
|
2343
|
+
signal.removeEventListener("abort", onAbort);
|
|
2344
|
+
}
|
|
2345
|
+
}
|
|
1563
2346
|
// Ask the user whether to install a missing app (autoInstallApp flow).
|
|
1564
2347
|
// Same register-then-emit ordering as the BTC high-index gate.
|
|
1565
|
-
async _waitForInstallAppConfirm(appName) {
|
|
2348
|
+
async _waitForInstallAppConfirm(appName, signal) {
|
|
2349
|
+
const operationId = this._activeOperationId();
|
|
1566
2350
|
const waitPromise = this._uiRegistry.wait(
|
|
1567
|
-
UI_REQUEST.REQUEST_INSTALL_APP
|
|
2351
|
+
UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2352
|
+
{ operationId }
|
|
1568
2353
|
);
|
|
1569
2354
|
this.emitter.emit(UI_REQUEST.REQUEST_INSTALL_APP, {
|
|
1570
2355
|
type: UI_REQUEST.REQUEST_INSTALL_APP,
|
|
1571
|
-
payload: { vendor: "ledger", appName }
|
|
2356
|
+
payload: { vendor: "ledger", appName, operationId }
|
|
1572
2357
|
});
|
|
1573
2358
|
try {
|
|
1574
|
-
const payload = await
|
|
2359
|
+
const payload = await this._awaitUiAnswer(
|
|
2360
|
+
UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2361
|
+
waitPromise,
|
|
2362
|
+
signal
|
|
2363
|
+
);
|
|
1575
2364
|
return !!payload?.confirmed;
|
|
1576
2365
|
} catch (err) {
|
|
1577
2366
|
this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
1578
2367
|
type: UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1579
|
-
payload: {}
|
|
2368
|
+
payload: { operationId }
|
|
1580
2369
|
});
|
|
1581
2370
|
return false;
|
|
1582
2371
|
}
|
|
@@ -1584,16 +2373,17 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1584
2373
|
// Layer 1 entry. Caller signal only races the outer awaiter; the shared
|
|
1585
2374
|
// `_doConnect` runs under its own internal controller so caller A's cancel
|
|
1586
2375
|
// doesn't kill caller B's await.
|
|
1587
|
-
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
|
|
2376
|
+
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
1588
2377
|
if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
|
|
1589
|
-
|
|
2378
|
+
this._assertConnectorReady("connectDevice");
|
|
2379
|
+
if (!this.connector.availableTransports?.includes("usb") && this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
|
|
1590
2380
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1591
2381
|
code: HardwareErrorCode3.DeviceNotFound
|
|
1592
2382
|
});
|
|
1593
2383
|
}
|
|
1594
2384
|
if (connectId && this._sessions.has(connectId)) return connectId;
|
|
1595
2385
|
if (!connectId && this._sessions.size > 0) {
|
|
1596
|
-
if (!
|
|
2386
|
+
if (!this._isBleConnection() && this._sessions.size > 1) {
|
|
1597
2387
|
throw Object.assign(
|
|
1598
2388
|
new Error(
|
|
1599
2389
|
"Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
|
|
@@ -1603,15 +2393,25 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1603
2393
|
}
|
|
1604
2394
|
return this._sessions.keys().next().value;
|
|
1605
2395
|
}
|
|
1606
|
-
if (!this._connectingPromise) {
|
|
1607
|
-
|
|
1608
|
-
|
|
2396
|
+
if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
|
|
2397
|
+
const controller = new AbortController();
|
|
2398
|
+
this._doConnectAbortController = controller;
|
|
2399
|
+
const innerSignal = controller.signal;
|
|
1609
2400
|
this._connectingPromise = (async () => {
|
|
1610
2401
|
try {
|
|
1611
|
-
return await this._doConnect(
|
|
2402
|
+
return await this._doConnect(
|
|
2403
|
+
innerSignal,
|
|
2404
|
+
connectId,
|
|
2405
|
+
allowUsbEphemeralFallback,
|
|
2406
|
+
preserveOperationId,
|
|
2407
|
+
context
|
|
2408
|
+
);
|
|
1612
2409
|
} finally {
|
|
1613
|
-
this.
|
|
1614
|
-
|
|
2410
|
+
if (this._doConnectAbortController === controller) {
|
|
2411
|
+
this._connectingPromise = null;
|
|
2412
|
+
this._doConnectAbortController = null;
|
|
2413
|
+
if (this._sessions.size === 0) this._activeConnectionType = void 0;
|
|
2414
|
+
}
|
|
1615
2415
|
}
|
|
1616
2416
|
})();
|
|
1617
2417
|
}
|
|
@@ -1620,22 +2420,54 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1620
2420
|
// Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
|
|
1621
2421
|
// Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
|
|
1622
2422
|
// throw DeviceNotFound so the user is kicked out of the loop.
|
|
1623
|
-
async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false) {
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
2423
|
+
async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
2424
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2425
|
+
if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
|
|
2426
|
+
this._activeConnectionType = "usb";
|
|
2427
|
+
const usbDevices = context?.supportedTransports && !context.supportedTransports.includes("usb") ? [] : await this._searchDevices({ transportType: "usb" }, internalSignal);
|
|
2428
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2429
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2430
|
+
(connection) => connection.transport === "usb"
|
|
2431
|
+
);
|
|
2432
|
+
const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
|
|
2433
|
+
if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback || context?.takesPluggedUsb)) {
|
|
2434
|
+
return this._connectFirstOrSelect(
|
|
2435
|
+
usbDevices,
|
|
2436
|
+
usbTarget,
|
|
2437
|
+
allowUsbEphemeralFallback,
|
|
2438
|
+
preserveOperationId,
|
|
2439
|
+
context,
|
|
2440
|
+
internalSignal
|
|
2441
|
+
);
|
|
2442
|
+
}
|
|
2443
|
+
if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
|
|
2444
|
+
throw createHwkError({
|
|
2445
|
+
code: HardwareErrorCode3.DeviceNotFound,
|
|
2446
|
+
message: "This Ledger model has no Bluetooth transport; connect it over USB"
|
|
2447
|
+
});
|
|
1638
2448
|
}
|
|
2449
|
+
this._activeConnectionType = "ble";
|
|
2450
|
+
const knownBle = context?.knownConnections?.find(
|
|
2451
|
+
(connection) => connection.transport === "ble"
|
|
2452
|
+
);
|
|
2453
|
+
if (knownBle?.transport === "ble") {
|
|
2454
|
+
return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
|
|
2455
|
+
}
|
|
2456
|
+
const bleContext = context ?? {};
|
|
2457
|
+
bleContext.allowBleSelection = true;
|
|
2458
|
+
bleContext.usbFallbackConnectId = usbTarget ?? targetConnectId;
|
|
2459
|
+
const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
|
|
2460
|
+
return this._connectFirstOrSelect(
|
|
2461
|
+
bleDevices,
|
|
2462
|
+
void 0,
|
|
2463
|
+
allowUsbEphemeralFallback,
|
|
2464
|
+
preserveOperationId,
|
|
2465
|
+
bleContext,
|
|
2466
|
+
internalSignal
|
|
2467
|
+
);
|
|
2468
|
+
}
|
|
2469
|
+
if (this._isBleConnection() && targetConnectId) {
|
|
2470
|
+
return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
|
|
1639
2471
|
}
|
|
1640
2472
|
let confirms = 0;
|
|
1641
2473
|
while (!internalSignal.aborted) {
|
|
@@ -1643,22 +2475,28 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1643
2475
|
type: EConnectorInteraction.Searching,
|
|
1644
2476
|
payload: { sessionId: "" }
|
|
1645
2477
|
});
|
|
1646
|
-
let devices = await this.
|
|
2478
|
+
let devices = await this._searchDevices(void 0, internalSignal);
|
|
2479
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1647
2480
|
if (devices.length === 0) {
|
|
1648
2481
|
for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
|
|
1649
2482
|
await new Promise((resolve) => {
|
|
1650
2483
|
setTimeout(resolve, DEVICE_CONNECT_RETRY_DELAY_MS);
|
|
1651
2484
|
});
|
|
1652
|
-
|
|
2485
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2486
|
+
devices = await this._searchDevices(void 0, internalSignal);
|
|
2487
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1653
2488
|
if (devices.length > 0) break;
|
|
1654
2489
|
}
|
|
1655
2490
|
}
|
|
1656
|
-
if (devices.length > 0) {
|
|
2491
|
+
if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
|
|
1657
2492
|
try {
|
|
1658
2493
|
return await this._connectFirstOrSelect(
|
|
1659
2494
|
devices,
|
|
1660
2495
|
targetConnectId,
|
|
1661
|
-
allowUsbEphemeralFallback
|
|
2496
|
+
allowUsbEphemeralFallback,
|
|
2497
|
+
preserveOperationId,
|
|
2498
|
+
context,
|
|
2499
|
+
internalSignal
|
|
1662
2500
|
);
|
|
1663
2501
|
} catch (err) {
|
|
1664
2502
|
if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
|
|
@@ -1687,45 +2525,148 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1687
2525
|
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1688
2526
|
throw new Error("_doConnect aborted");
|
|
1689
2527
|
}
|
|
1690
|
-
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback
|
|
2528
|
+
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
|
|
2529
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1691
2530
|
if (targetConnectId) {
|
|
1692
2531
|
const target = devices.find(
|
|
1693
2532
|
(d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
|
|
1694
2533
|
);
|
|
1695
2534
|
if (target) {
|
|
1696
|
-
return this._connectDeviceOrThrow(target.connectId);
|
|
2535
|
+
return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
|
|
1697
2536
|
}
|
|
1698
|
-
if (!
|
|
2537
|
+
if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
|
|
1699
2538
|
debugLog(
|
|
1700
2539
|
`[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
|
|
1701
2540
|
);
|
|
1702
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2541
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1703
2542
|
}
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
2543
|
+
if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
|
|
2544
|
+
const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
|
|
2545
|
+
code: HardwareErrorCode3.DeviceNotFound
|
|
2546
|
+
});
|
|
2547
|
+
if (this._isBleConnection()) {
|
|
2548
|
+
err._tag = ERROR_TAG.DeviceNotAdvertising;
|
|
2549
|
+
}
|
|
2550
|
+
throw err;
|
|
1709
2551
|
}
|
|
1710
|
-
throw err;
|
|
1711
2552
|
}
|
|
1712
|
-
|
|
2553
|
+
const requiresBleSelection = this._isBleConnection();
|
|
2554
|
+
if (requiresBleSelection && !allowUsbEphemeralFallback && !context?.allowBleSelection) {
|
|
1713
2555
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1714
2556
|
code: HardwareErrorCode3.DeviceNotFound
|
|
1715
2557
|
});
|
|
1716
2558
|
}
|
|
1717
|
-
if (
|
|
1718
|
-
|
|
2559
|
+
if (requiresBleSelection && context?.allowDeviceSelection !== false) {
|
|
2560
|
+
const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
|
|
2561
|
+
if (context) context.bindingSessionId = bindingSessionId;
|
|
2562
|
+
const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb")) && (!context?.supportedTransports || context.supportedTransports.includes("usb"));
|
|
2563
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2564
|
+
(connection) => connection.transport === "usb"
|
|
2565
|
+
);
|
|
2566
|
+
const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : context?.usbFallbackConnectId ?? targetConnectId;
|
|
2567
|
+
const maySelectAnyUsb = allowUsbEphemeralFallback || !usbConnectId && !context?.knownConnections?.some((connection) => connection.transport !== "qr");
|
|
2568
|
+
const { device, requestId } = await requestBleDeviceSelection({
|
|
2569
|
+
emitter: this.emitter,
|
|
2570
|
+
registry: this._uiRegistry,
|
|
2571
|
+
signal,
|
|
2572
|
+
allowUsbFallback,
|
|
2573
|
+
scan: async () => {
|
|
2574
|
+
if (allowUsbFallback) {
|
|
2575
|
+
const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
|
|
2576
|
+
const candidate = usbDevices.find(
|
|
2577
|
+
(device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
|
|
2578
|
+
) ?? (maySelectAnyUsb && usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
|
|
2579
|
+
if (candidate) return [candidate];
|
|
2580
|
+
}
|
|
2581
|
+
return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
|
|
2582
|
+
},
|
|
2583
|
+
request: {
|
|
2584
|
+
devices,
|
|
2585
|
+
bindingSessionId,
|
|
2586
|
+
context: {
|
|
2587
|
+
kind: "bind-connection",
|
|
2588
|
+
transport: "ble",
|
|
2589
|
+
reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
|
|
2590
|
+
},
|
|
2591
|
+
extra: context?.extra,
|
|
2592
|
+
operationId: preserveOperationId
|
|
2593
|
+
}
|
|
2594
|
+
});
|
|
2595
|
+
if (device.connectionType === "usb") {
|
|
2596
|
+
this._activeConnectionType = "usb";
|
|
2597
|
+
if (context) context.selectedConnection = void 0;
|
|
2598
|
+
this._bindingSelectionRequestId = requestId;
|
|
2599
|
+
this._finishBleBinding("cancelled");
|
|
2600
|
+
return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
|
|
2601
|
+
}
|
|
2602
|
+
this._bindingSelectionRequestId = requestId;
|
|
2603
|
+
const connected = await this._connectDeviceOrThrow(
|
|
2604
|
+
device.connectId,
|
|
2605
|
+
preserveOperationId,
|
|
2606
|
+
signal
|
|
2607
|
+
);
|
|
2608
|
+
if (context) context.selectedConnection = { connectId: connected, requestId };
|
|
2609
|
+
if (context?.deferBindingSave) {
|
|
2610
|
+
context.pendingBinding = { connectId: connected, requestId };
|
|
2611
|
+
} else {
|
|
2612
|
+
await this._saveSelectedBleBinding(
|
|
2613
|
+
connected,
|
|
2614
|
+
requestId,
|
|
2615
|
+
context,
|
|
2616
|
+
preserveOperationId,
|
|
2617
|
+
signal
|
|
2618
|
+
);
|
|
2619
|
+
}
|
|
2620
|
+
return connected;
|
|
2621
|
+
}
|
|
2622
|
+
if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
|
|
2623
|
+
if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(UI_REQUEST.REQUEST_SELECT_DEVICE)) {
|
|
2624
|
+
throw createHwkError({
|
|
2625
|
+
code: HardwareErrorCode3.DeviceNotFound,
|
|
2626
|
+
message: "Select a Ledger device before continuing"
|
|
2627
|
+
});
|
|
2628
|
+
}
|
|
2629
|
+
const requestId = this._uiRegistry.createRequestId();
|
|
2630
|
+
const operationId = this._activeOperationId();
|
|
2631
|
+
const waitPromise = this._uiRegistry.wait(
|
|
2632
|
+
UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2633
|
+
{ requestId, operationId }
|
|
2634
|
+
);
|
|
2635
|
+
this.emitter.emit(UI_REQUEST.REQUEST_SELECT_DEVICE, {
|
|
2636
|
+
type: UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2637
|
+
payload: {
|
|
2638
|
+
devices,
|
|
2639
|
+
requestId,
|
|
2640
|
+
operationId,
|
|
2641
|
+
context: requiresBleSelection ? {
|
|
2642
|
+
kind: "bind-connection",
|
|
2643
|
+
transport: "ble",
|
|
2644
|
+
reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
|
|
2645
|
+
} : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
|
|
2646
|
+
extra: context?.extra
|
|
2647
|
+
}
|
|
2648
|
+
});
|
|
2649
|
+
const { sdkConnectId } = await this._abortable(signal, waitPromise);
|
|
2650
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
2651
|
+
const selected = devices.find((device) => device.connectId === sdkConnectId);
|
|
2652
|
+
if (!selected) {
|
|
2653
|
+
throw Object.assign(new Error("Selected Ledger is no longer available"), {
|
|
2654
|
+
code: HardwareErrorCode3.DeviceNotFound
|
|
2655
|
+
});
|
|
2656
|
+
}
|
|
2657
|
+
if (context && requiresBleSelection)
|
|
2658
|
+
context.selectedConnection = { connectId: selected.connectId, requestId };
|
|
2659
|
+
return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
|
|
1719
2660
|
}
|
|
1720
2661
|
if (devices.length !== 1) {
|
|
1721
2662
|
throw Object.assign(new Error("Ledger device not found."), {
|
|
1722
2663
|
code: HardwareErrorCode3.DeviceNotFound
|
|
1723
2664
|
});
|
|
1724
2665
|
}
|
|
1725
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2666
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1726
2667
|
}
|
|
1727
|
-
async _connectDeviceOrThrow(chosenConnectId) {
|
|
1728
|
-
const result = await this.
|
|
2668
|
+
async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
|
|
2669
|
+
const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
|
|
1729
2670
|
if (!result.success) {
|
|
1730
2671
|
const payload = result.payload;
|
|
1731
2672
|
const rethrow = Object.assign(new Error(payload.error), {
|
|
@@ -1736,16 +2677,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1736
2677
|
}
|
|
1737
2678
|
throw rethrow;
|
|
1738
2679
|
}
|
|
1739
|
-
return
|
|
2680
|
+
return result.payload;
|
|
1740
2681
|
}
|
|
1741
|
-
/**
|
|
1742
|
-
* Call the connector with automatic session resolution and disconnect retry.
|
|
1743
|
-
*
|
|
1744
|
-
* 1. Resolves a valid connectId via ensureConnected()
|
|
1745
|
-
* 2. Looks up sessionId from _sessions
|
|
1746
|
-
* 3. Calls connector.call()
|
|
1747
|
-
* 4. On disconnect error: clears stale session, re-connects, retries once
|
|
1748
|
-
*/
|
|
1749
2682
|
/**
|
|
1750
2683
|
* Unwrap a `ConnectorCallResult` back into the throw-based control flow this
|
|
1751
2684
|
* class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
|
|
@@ -1766,33 +2699,145 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1766
2699
|
* lives in one place.
|
|
1767
2700
|
*/
|
|
1768
2701
|
async _callConnector(sessionId, method, params, signal) {
|
|
1769
|
-
|
|
2702
|
+
this._assertConnectorReady(method);
|
|
2703
|
+
if (signal?.aborted) throw this._abortReason(signal);
|
|
2704
|
+
const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
|
|
2705
|
+
let promise;
|
|
2706
|
+
try {
|
|
2707
|
+
promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
|
|
2708
|
+
} catch (error) {
|
|
2709
|
+
releaseOperation();
|
|
2710
|
+
throw error;
|
|
2711
|
+
}
|
|
1770
2712
|
const result = signal ? await this._abortable(signal, promise) : await promise;
|
|
1771
2713
|
return this._unwrapConnectorResult(result);
|
|
1772
2714
|
}
|
|
2715
|
+
_assertConnectorReady(method) {
|
|
2716
|
+
if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
|
|
2717
|
+
throw _LedgerAdapter._createDeviceBusyError(method);
|
|
2718
|
+
}
|
|
2719
|
+
}
|
|
2720
|
+
_runConnectorTeardown(task) {
|
|
2721
|
+
const previous = this._connectorTeardownTail;
|
|
2722
|
+
let releaseTail = () => void 0;
|
|
2723
|
+
this._connectorTeardownTail = new Promise((resolve) => {
|
|
2724
|
+
releaseTail = resolve;
|
|
2725
|
+
});
|
|
2726
|
+
this._pendingConnectorTeardowns += 1;
|
|
2727
|
+
return (async () => {
|
|
2728
|
+
try {
|
|
2729
|
+
await previous;
|
|
2730
|
+
await this._waitForConnectorOperationsToDrain();
|
|
2731
|
+
await task();
|
|
2732
|
+
} finally {
|
|
2733
|
+
this._pendingConnectorTeardowns -= 1;
|
|
2734
|
+
releaseTail();
|
|
2735
|
+
}
|
|
2736
|
+
})();
|
|
2737
|
+
}
|
|
2738
|
+
_waitForConnectorOperationsToDrain() {
|
|
2739
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2740
|
+
return Promise.resolve();
|
|
2741
|
+
}
|
|
2742
|
+
return new Promise((resolve) => {
|
|
2743
|
+
this._connectorIdleWaiters.add(resolve);
|
|
2744
|
+
});
|
|
2745
|
+
}
|
|
2746
|
+
_retainConnectorOperation(key) {
|
|
2747
|
+
this._unsettledConnectorOperations.set(
|
|
2748
|
+
key,
|
|
2749
|
+
(this._unsettledConnectorOperations.get(key) ?? 0) + 1
|
|
2750
|
+
);
|
|
2751
|
+
let released = false;
|
|
2752
|
+
return () => {
|
|
2753
|
+
if (released) return;
|
|
2754
|
+
released = true;
|
|
2755
|
+
const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
|
|
2756
|
+
if (remaining > 0) {
|
|
2757
|
+
this._unsettledConnectorOperations.set(key, remaining);
|
|
2758
|
+
} else {
|
|
2759
|
+
this._unsettledConnectorOperations.delete(key);
|
|
2760
|
+
}
|
|
2761
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2762
|
+
for (const resolve of this._connectorIdleWaiters) resolve();
|
|
2763
|
+
this._connectorIdleWaiters.clear();
|
|
2764
|
+
}
|
|
2765
|
+
};
|
|
2766
|
+
}
|
|
1773
2767
|
async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
1774
|
-
|
|
1775
|
-
|
|
2768
|
+
const positionalOperationId = isHardwareOperationId(connectId) ? connectId : void 0;
|
|
2769
|
+
if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
|
|
2770
|
+
throw createHwkError({
|
|
2771
|
+
code: HardwareErrorCode3.InvalidParams,
|
|
2772
|
+
message: "Conflicting Ledger operation ids",
|
|
2773
|
+
params: {
|
|
2774
|
+
positionalOperationId,
|
|
2775
|
+
commonOperationId: commonParams.operationId
|
|
2776
|
+
}
|
|
2777
|
+
});
|
|
2778
|
+
}
|
|
2779
|
+
const operationId = commonParams?.operationId ?? positionalOperationId;
|
|
2780
|
+
const operation = operationId ? this._operations.resolve(operationId) : void 0;
|
|
2781
|
+
const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
|
|
2782
|
+
const effectiveConnectId = operation?.connectId ?? connectId;
|
|
2783
|
+
debugLog("[LedgerAdapter][REQ]", {
|
|
2784
|
+
method,
|
|
2785
|
+
connectId: effectiveConnectId || "(empty)",
|
|
2786
|
+
params: summarizeForLog(params, { method })
|
|
2787
|
+
});
|
|
2788
|
+
const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
|
|
1776
2789
|
try {
|
|
1777
2790
|
const result = await this._jobQueue.enqueue(
|
|
1778
2791
|
queueKey,
|
|
1779
|
-
async (signal) =>
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
2792
|
+
async (signal) => {
|
|
2793
|
+
if (operationId) this._activeOperationJobs.add(operationId);
|
|
2794
|
+
try {
|
|
2795
|
+
return await this._runConnectorCall(
|
|
2796
|
+
effectiveConnectId,
|
|
2797
|
+
method,
|
|
2798
|
+
params,
|
|
2799
|
+
signal,
|
|
2800
|
+
fingerprint,
|
|
2801
|
+
permissionDeviceId,
|
|
2802
|
+
commonParams,
|
|
2803
|
+
installContext ?? {},
|
|
2804
|
+
operationId
|
|
2805
|
+
);
|
|
2806
|
+
} catch (error) {
|
|
2807
|
+
const status = signal.aborted ? "cancelled" : "failed";
|
|
2808
|
+
const bundleConnectId = installContext?.connection?.connectId;
|
|
2809
|
+
let keptBundlePick = false;
|
|
2810
|
+
for (const [pickedConnectId, owner] of this._pendingPickBindings) {
|
|
2811
|
+
if (pickedConnectId === bundleConnectId) {
|
|
2812
|
+
keptBundlePick = true;
|
|
2813
|
+
} else {
|
|
2814
|
+
this._pendingPickBindings.delete(pickedConnectId);
|
|
2815
|
+
this._discardPendingBinding(owner, status);
|
|
2816
|
+
await this._dropSession(pickedConnectId, signal);
|
|
2817
|
+
}
|
|
2818
|
+
}
|
|
2819
|
+
if (!keptBundlePick) this._finishBleBinding(status);
|
|
2820
|
+
throw error;
|
|
2821
|
+
} finally {
|
|
2822
|
+
if (operationId) {
|
|
2823
|
+
this._activeOperationJobs.delete(operationId);
|
|
2824
|
+
if (this._pendingOperationDisconnects.delete(operationId)) {
|
|
2825
|
+
await this._releaseLostOperationConnection(operationId);
|
|
2826
|
+
}
|
|
2827
|
+
}
|
|
2828
|
+
}
|
|
2829
|
+
},
|
|
1789
2830
|
{
|
|
1790
2831
|
label: method,
|
|
1791
2832
|
rejectIfBusy: true,
|
|
1792
2833
|
busyError: _LedgerAdapter._createDeviceBusyError(method)
|
|
1793
2834
|
}
|
|
1794
2835
|
);
|
|
1795
|
-
debugLog("[LedgerAdapter][RES]", {
|
|
2836
|
+
debugLog("[LedgerAdapter][RES]", {
|
|
2837
|
+
method,
|
|
2838
|
+
success: true,
|
|
2839
|
+
payload: summarizeForLog(result, { method, role: "result" })
|
|
2840
|
+
});
|
|
1796
2841
|
return result;
|
|
1797
2842
|
} catch (err) {
|
|
1798
2843
|
const e = err;
|
|
@@ -1806,15 +2851,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1806
2851
|
}
|
|
1807
2852
|
});
|
|
1808
2853
|
throw err;
|
|
2854
|
+
} finally {
|
|
2855
|
+
releaseOperationRetention?.();
|
|
1809
2856
|
}
|
|
1810
2857
|
}
|
|
2858
|
+
/** Hermes/RN polyfills don't always populate signal.reason; fall back. */
|
|
2859
|
+
_abortReason(signal) {
|
|
2860
|
+
return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
|
|
2861
|
+
}
|
|
1811
2862
|
/**
|
|
1812
2863
|
* Race a promise against an abort signal. On abort, rejects with
|
|
1813
2864
|
* signal.reason → instance _lastCancelReason → generic Error('Aborted').
|
|
1814
2865
|
*/
|
|
1815
2866
|
_abortable(signal, promise) {
|
|
1816
|
-
const getAbortReason = () =>
|
|
2867
|
+
const getAbortReason = () => this._abortReason(signal);
|
|
1817
2868
|
if (signal.aborted) {
|
|
2869
|
+
void promise.catch(() => void 0);
|
|
1818
2870
|
return Promise.reject(getAbortReason());
|
|
1819
2871
|
}
|
|
1820
2872
|
return new Promise((resolve, reject) => {
|
|
@@ -1841,17 +2893,20 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1841
2893
|
}
|
|
1842
2894
|
}
|
|
1843
2895
|
/** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
|
|
1844
|
-
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
2896
|
+
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
|
|
1845
2897
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
2898
|
+
const resolvesAppManagementTransport = APP_MANAGEMENT_METHODS.has(method) && this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble");
|
|
2899
|
+
if (!operationId && !resolvesAppManagementTransport) {
|
|
2900
|
+
await this._ensureDevicePermission(
|
|
2901
|
+
connectId,
|
|
2902
|
+
permissionDeviceId ?? fingerprint?.deviceId,
|
|
2903
|
+
signal
|
|
2904
|
+
);
|
|
2905
|
+
}
|
|
1851
2906
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1852
2907
|
let effectiveParams = params;
|
|
1853
2908
|
if (method === "btcGetPublicKey") {
|
|
1854
|
-
const gatedParams = await this._gateBtcHighIndex(params);
|
|
2909
|
+
const gatedParams = await this._gateBtcHighIndex(params, signal);
|
|
1855
2910
|
if (gatedParams === null) {
|
|
1856
2911
|
throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
|
|
1857
2912
|
_tag: ERROR_TAG.UserAborted,
|
|
@@ -1861,19 +2916,78 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1861
2916
|
effectiveParams = gatedParams;
|
|
1862
2917
|
}
|
|
1863
2918
|
const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
|
|
1864
|
-
|
|
1865
|
-
|
|
2919
|
+
let businessCallStarted = false;
|
|
2920
|
+
const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
|
|
2921
|
+
const knownTransport = this._isBleConnection() ? "ble" : "usb";
|
|
2922
|
+
const hintedConnectId = commonParams?.knownConnections?.find(
|
|
2923
|
+
(connection) => connection.transport === knownTransport
|
|
2924
|
+
);
|
|
2925
|
+
const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
|
|
2926
|
+
const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
|
|
2927
|
+
const checksWallet = Boolean(
|
|
2928
|
+
fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId
|
|
2929
|
+
);
|
|
2930
|
+
const connectionAttempt = {
|
|
2931
|
+
...commonParams,
|
|
2932
|
+
deferBindingSave: checksWallet,
|
|
2933
|
+
...APP_MANAGEMENT_METHODS.has(method) ? { takesPluggedUsb: true } : {}
|
|
2934
|
+
};
|
|
2935
|
+
const bundleConnection = installContext?.connection;
|
|
2936
|
+
if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
|
|
2937
|
+
throw createHwkError({
|
|
2938
|
+
code: HardwareErrorCode3.DeviceDisconnected,
|
|
2939
|
+
message: "Ledger all-network connection ended"
|
|
2940
|
+
});
|
|
2941
|
+
}
|
|
2942
|
+
const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
|
|
2943
|
+
preferredConnectId,
|
|
1866
2944
|
signal,
|
|
1867
|
-
allowUsbEphemeralFallback
|
|
2945
|
+
allowUsbEphemeralFallback,
|
|
2946
|
+
void 0,
|
|
2947
|
+
connectionAttempt
|
|
1868
2948
|
);
|
|
2949
|
+
const walletCheck = installContext?.walletCheck;
|
|
2950
|
+
if (walletCheck && !checksWallet && (walletCheck.verified === false || walletCheck.expected && !walletCheck.verified)) {
|
|
2951
|
+
throw createHwkError({
|
|
2952
|
+
code: HardwareErrorCode3.DeviceMismatch,
|
|
2953
|
+
message: "Ledger wallet is not verified on this connection; refusing to derive an unverifiable address"
|
|
2954
|
+
});
|
|
2955
|
+
}
|
|
1869
2956
|
const sessionId = this._sessions.get(resolvedConnectId);
|
|
2957
|
+
if (sessionId && installContext && !installContext.connection) {
|
|
2958
|
+
installContext.connection = { connectId: resolvedConnectId, sessionId };
|
|
2959
|
+
}
|
|
1870
2960
|
if (!sessionId) {
|
|
2961
|
+
if (operationId) {
|
|
2962
|
+
this._operations.end(operationId, "disconnect");
|
|
2963
|
+
throw createHwkError({
|
|
2964
|
+
code: HardwareErrorCode3.OperationEnded,
|
|
2965
|
+
message: "Ledger operation connection is no longer active",
|
|
2966
|
+
params: { operationId, reason: "disconnect" }
|
|
2967
|
+
});
|
|
2968
|
+
}
|
|
1871
2969
|
throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
|
|
1872
2970
|
_tag: ERROR_TAG.DeviceSessionNotFound
|
|
1873
2971
|
});
|
|
1874
2972
|
}
|
|
2973
|
+
if (!operationId && resolvesAppManagementTransport) {
|
|
2974
|
+
const transport = this._sessionTransports.get(sessionId);
|
|
2975
|
+
await this._ensureDevicePermission(
|
|
2976
|
+
resolvedConnectId,
|
|
2977
|
+
permissionDeviceId ?? fingerprint?.deviceId,
|
|
2978
|
+
signal,
|
|
2979
|
+
transport && (isLedgerBleConnectionType(transport) ? "ble" : "hid")
|
|
2980
|
+
);
|
|
2981
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
2982
|
+
}
|
|
1875
2983
|
try {
|
|
1876
|
-
|
|
2984
|
+
const isBleSession = this._sessionTransports.get(sessionId) === "ble";
|
|
2985
|
+
if (!operationId && connectionAttempt.pendingBinding) {
|
|
2986
|
+
this._pendingPickBindings.set(resolvedConnectId, connectionAttempt);
|
|
2987
|
+
}
|
|
2988
|
+
const bindingOwner = operationId ? this._pendingOperationBindings.get(operationId) : this._pendingPickBindings.get(resolvedConnectId);
|
|
2989
|
+
const pendingBinding = bindingOwner?.pendingBinding?.connectId === resolvedConnectId ? bindingOwner.pendingBinding : void 0;
|
|
2990
|
+
if (fingerprint && checksWallet) {
|
|
1877
2991
|
const fp = await this._abortable(
|
|
1878
2992
|
signal,
|
|
1879
2993
|
this._verifyDeviceFingerprintWithSession(
|
|
@@ -1883,14 +2997,68 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1883
2997
|
)
|
|
1884
2998
|
);
|
|
1885
2999
|
if (!fp.success) {
|
|
3000
|
+
if (pendingBinding) {
|
|
3001
|
+
this._discardPendingBinding(bindingOwner, "failed");
|
|
3002
|
+
this._pendingPickBindings.delete(resolvedConnectId);
|
|
3003
|
+
}
|
|
3004
|
+
if (operationId) {
|
|
3005
|
+
this._pendingOperationBindings.delete(operationId);
|
|
3006
|
+
this._operations.end(operationId, "explicit");
|
|
3007
|
+
await this._dropSession(resolvedConnectId, signal);
|
|
3008
|
+
}
|
|
1886
3009
|
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
1887
3010
|
code: HardwareErrorCode3.DeviceMismatch
|
|
1888
3011
|
});
|
|
1889
3012
|
}
|
|
3013
|
+
if (walletCheck) walletCheck.verified = true;
|
|
3014
|
+
}
|
|
3015
|
+
if (pendingBinding && bindingOwner) {
|
|
3016
|
+
bindingOwner.pendingBinding = void 0;
|
|
3017
|
+
if (operationId) this._pendingOperationBindings.delete(operationId);
|
|
3018
|
+
else this._pendingPickBindings.delete(resolvedConnectId);
|
|
3019
|
+
await this._saveSelectedBleBinding(
|
|
3020
|
+
pendingBinding.connectId,
|
|
3021
|
+
pendingBinding.requestId,
|
|
3022
|
+
bindingOwner,
|
|
3023
|
+
operationId,
|
|
3024
|
+
signal,
|
|
3025
|
+
fingerprint && checksWallet ? {
|
|
3026
|
+
vendor: "ledger",
|
|
3027
|
+
type: "chainFingerprint",
|
|
3028
|
+
chain: fingerprint.chain,
|
|
3029
|
+
value: fingerprint.deviceId
|
|
3030
|
+
} : void 0
|
|
3031
|
+
);
|
|
3032
|
+
}
|
|
3033
|
+
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
|
|
3034
|
+
this._selectedBleReconnectTargets.set(connectId, {
|
|
3035
|
+
connectId: resolvedConnectId,
|
|
3036
|
+
chain: fingerprint.chain,
|
|
3037
|
+
fingerprint: fingerprint.deviceId
|
|
3038
|
+
});
|
|
1890
3039
|
}
|
|
1891
|
-
|
|
3040
|
+
businessCallStarted = true;
|
|
3041
|
+
const result = await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
3042
|
+
if (walletCheck) walletCheck.derived = true;
|
|
3043
|
+
return result;
|
|
1892
3044
|
} catch (err) {
|
|
1893
3045
|
if (signal.aborted) throw err;
|
|
3046
|
+
if (isLostConnectionError(err)) {
|
|
3047
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3048
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
3049
|
+
else {
|
|
3050
|
+
this._sessions.delete(resolvedConnectId);
|
|
3051
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3052
|
+
}
|
|
3053
|
+
const ambiguous = businessCallStarted && !canReplayHardwareMethodAfterTransportFailure(method);
|
|
3054
|
+
const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
|
|
3055
|
+
throw createHwkError({
|
|
3056
|
+
code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(err).code,
|
|
3057
|
+
message: "Ledger operation connection was lost; start a new operation",
|
|
3058
|
+
params: ambiguous ? operationMayHaveCompletedParams(method, { operationId }) : interactionParams,
|
|
3059
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
3060
|
+
});
|
|
3061
|
+
}
|
|
1894
3062
|
const errObj = err;
|
|
1895
3063
|
debugLog("[LedgerAdapter] connectorCall error:", method, {
|
|
1896
3064
|
message: errObj?.message,
|
|
@@ -1902,6 +3070,64 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1902
3070
|
isNotAdvertising: isDeviceNotAdvertisingError(err),
|
|
1903
3071
|
isStuckApp: isStuckAppStateError(err)
|
|
1904
3072
|
});
|
|
3073
|
+
const assertSessionCurrent = (message) => {
|
|
3074
|
+
if (this._sessions.get(resolvedConnectId) === sessionId) return;
|
|
3075
|
+
throw createHwkError({
|
|
3076
|
+
code: operationId ? HardwareErrorCode3.OperationEnded : HardwareErrorCode3.DeviceDisconnected,
|
|
3077
|
+
message
|
|
3078
|
+
});
|
|
3079
|
+
};
|
|
3080
|
+
if ((isDeviceLockedError(err) || errObj?.code === HardwareErrorCode3.DeviceLocked) && lockedRetryBudget > 0) {
|
|
3081
|
+
await this._waitForDeviceConnect(signal);
|
|
3082
|
+
assertSessionCurrent("Ledger connection ended while waiting for unlock");
|
|
3083
|
+
if (walletCheck?.derived) walletCheck.verified = false;
|
|
3084
|
+
return this._runConnectorCall(
|
|
3085
|
+
resolvedConnectId,
|
|
3086
|
+
method,
|
|
3087
|
+
effectiveParams,
|
|
3088
|
+
signal,
|
|
3089
|
+
fingerprint,
|
|
3090
|
+
permissionDeviceId,
|
|
3091
|
+
commonParams,
|
|
3092
|
+
installContext,
|
|
3093
|
+
operationId,
|
|
3094
|
+
lockedRetryBudget - 1
|
|
3095
|
+
);
|
|
3096
|
+
}
|
|
3097
|
+
if (businessCallStarted && isStuckAppStateError(err)) {
|
|
3098
|
+
await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
|
|
3099
|
+
assertSessionCurrent("Ledger connection ended during the app transition");
|
|
3100
|
+
try {
|
|
3101
|
+
const retried = await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
3102
|
+
if (walletCheck) walletCheck.derived = true;
|
|
3103
|
+
return retried;
|
|
3104
|
+
} catch (retryErr) {
|
|
3105
|
+
if (isStuckAppStateError(retryErr)) throw err;
|
|
3106
|
+
if (isLostConnectionError(retryErr)) {
|
|
3107
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
3108
|
+
else {
|
|
3109
|
+
this._sessions.delete(resolvedConnectId);
|
|
3110
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3111
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3112
|
+
}
|
|
3113
|
+
const ambiguous = !canReplayHardwareMethodAfterTransportFailure(method);
|
|
3114
|
+
throw createHwkError({
|
|
3115
|
+
code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(retryErr).code,
|
|
3116
|
+
message: `Ledger ${method} may have completed before the connection was lost`,
|
|
3117
|
+
params: ambiguous ? operationMayHaveCompletedParams(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
|
|
3118
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
3119
|
+
});
|
|
3120
|
+
}
|
|
3121
|
+
throw retryErr;
|
|
3122
|
+
}
|
|
3123
|
+
}
|
|
3124
|
+
if (!operationId && errObj?.code === HardwareErrorCode3.DeviceMismatch) {
|
|
3125
|
+
this._sessions.delete(resolvedConnectId);
|
|
3126
|
+
this._sessionTransports.delete(sessionId);
|
|
3127
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3128
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3129
|
+
throw err;
|
|
3130
|
+
}
|
|
1905
3131
|
const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
|
|
1906
3132
|
const isAppMissing = isAppNotInstalledError(err) || err?.code === HardwareErrorCode3.AppNotInstalled;
|
|
1907
3133
|
if (autoInstallApp && isAppMissing) {
|
|
@@ -1918,7 +3144,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1918
3144
|
appName
|
|
1919
3145
|
});
|
|
1920
3146
|
}
|
|
1921
|
-
const confirmed = await this._waitForInstallAppConfirm(appName);
|
|
3147
|
+
const confirmed = await this._waitForInstallAppConfirm(appName, signal);
|
|
1922
3148
|
if (!confirmed) {
|
|
1923
3149
|
throw createHwkError({
|
|
1924
3150
|
code: HardwareErrorCode3.UserAborted,
|
|
@@ -1947,7 +3173,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1947
3173
|
}
|
|
1948
3174
|
this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
1949
3175
|
type: UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1950
|
-
payload: {}
|
|
3176
|
+
payload: { operationId }
|
|
1951
3177
|
});
|
|
1952
3178
|
return await this._runConnectorCall(
|
|
1953
3179
|
resolvedConnectId,
|
|
@@ -1957,162 +3183,19 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1957
3183
|
fingerprint,
|
|
1958
3184
|
permissionDeviceId,
|
|
1959
3185
|
commonParams,
|
|
1960
|
-
installContext
|
|
3186
|
+
installContext,
|
|
3187
|
+
operationId
|
|
1961
3188
|
);
|
|
1962
3189
|
}
|
|
1963
3190
|
}
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
"[LedgerAdapter] stuck-app retry: method=",
|
|
1973
|
-
method,
|
|
1974
|
-
"delayMs=",
|
|
1975
|
-
_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS,
|
|
1976
|
-
"_tag=",
|
|
1977
|
-
err?._tag
|
|
1978
|
-
);
|
|
1979
|
-
try {
|
|
1980
|
-
const retryResult = await this._retryAfterStuckApp(
|
|
1981
|
-
resolvedConnectId,
|
|
1982
|
-
method,
|
|
1983
|
-
effectiveParams,
|
|
1984
|
-
signal,
|
|
1985
|
-
err,
|
|
1986
|
-
fingerprint
|
|
1987
|
-
);
|
|
1988
|
-
debugLog("[LedgerAdapter] stuck-app retry succeeded: method=", method);
|
|
1989
|
-
return retryResult;
|
|
1990
|
-
} catch (retryErr) {
|
|
1991
|
-
if (signal.aborted) throw retryErr;
|
|
1992
|
-
if (isStuckAppStateError(retryErr)) {
|
|
1993
|
-
debugLog("[LedgerAdapter] stuck-app retry exhausted (2nd 6901): method=", method);
|
|
1994
|
-
throw err;
|
|
1995
|
-
}
|
|
1996
|
-
debugLog(
|
|
1997
|
-
"[LedgerAdapter] stuck-app retry threw non-stuck error: method=",
|
|
1998
|
-
method,
|
|
1999
|
-
"retryErrTag=",
|
|
2000
|
-
retryErr?._tag
|
|
2001
|
-
);
|
|
2002
|
-
throw retryErr;
|
|
2003
|
-
}
|
|
2004
|
-
}
|
|
2005
|
-
if (isDeviceLockedError(err) || isDeviceNotAdvertisingError(err) || isDeviceDisconnectedError(err)) {
|
|
2006
|
-
let lastErr = err;
|
|
2007
|
-
for (let attempt = 0; attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET; attempt += 1) {
|
|
2008
|
-
if (signal.aborted) throw lastErr;
|
|
2009
|
-
try {
|
|
2010
|
-
this._sessions.delete(resolvedConnectId);
|
|
2011
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2012
|
-
if (isDeviceDisconnectedError(lastErr)) {
|
|
2013
|
-
try {
|
|
2014
|
-
this.connector.reset?.();
|
|
2015
|
-
} catch {
|
|
2016
|
-
}
|
|
2017
|
-
}
|
|
2018
|
-
const reConnectId = await this.ensureConnected(
|
|
2019
|
-
resolvedConnectId,
|
|
2020
|
-
signal,
|
|
2021
|
-
allowUsbEphemeralFallback
|
|
2022
|
-
);
|
|
2023
|
-
const reSessionId = this._sessions.get(reConnectId);
|
|
2024
|
-
if (!reSessionId) throw lastErr;
|
|
2025
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2026
|
-
const fp = await this._abortable(
|
|
2027
|
-
signal,
|
|
2028
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2029
|
-
reSessionId,
|
|
2030
|
-
fingerprint.deviceId,
|
|
2031
|
-
fingerprint.chain
|
|
2032
|
-
)
|
|
2033
|
-
);
|
|
2034
|
-
if (!fp.success) {
|
|
2035
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2036
|
-
code: HardwareErrorCode3.DeviceMismatch
|
|
2037
|
-
});
|
|
2038
|
-
}
|
|
2039
|
-
}
|
|
2040
|
-
return await this._callConnector(reSessionId, method, effectiveParams, signal);
|
|
2041
|
-
} catch (retryErr) {
|
|
2042
|
-
if (signal.aborted) throw retryErr;
|
|
2043
|
-
lastErr = retryErr;
|
|
2044
|
-
const canRetry = attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET - 1 && (isDeviceLockedError(retryErr) || isDeviceNotAdvertisingError(retryErr) || isDeviceDisconnectedError(retryErr));
|
|
2045
|
-
if (!canRetry) {
|
|
2046
|
-
throw retryErr;
|
|
2047
|
-
}
|
|
2048
|
-
}
|
|
2049
|
-
}
|
|
2050
|
-
throw lastErr;
|
|
2051
|
-
}
|
|
2052
|
-
if (isTimeoutError(err)) {
|
|
2053
|
-
debugLog("[LedgerAdapter] timeout, retrying with fresh connection...");
|
|
2054
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2055
|
-
return this._retryWithFreshConnection(
|
|
2056
|
-
resolvedConnectId,
|
|
2057
|
-
method,
|
|
2058
|
-
effectiveParams,
|
|
2059
|
-
signal,
|
|
2060
|
-
err,
|
|
2061
|
-
fingerprint
|
|
2062
|
-
);
|
|
2063
|
-
}
|
|
2064
|
-
if (isConnectionLevelError(err)) {
|
|
2065
|
-
debugLog("[LedgerAdapter] connection-level fail-closed reset");
|
|
2066
|
-
this._sessions.delete(resolvedConnectId);
|
|
2067
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2068
|
-
this.connector.reset();
|
|
2069
|
-
const codeNum = err?.code;
|
|
2070
|
-
throw Object.assign(err, {
|
|
2071
|
-
code: codeNum ?? HardwareErrorCode3.DeviceDisconnected
|
|
2072
|
-
});
|
|
2073
|
-
}
|
|
2074
|
-
throw err;
|
|
2075
|
-
}
|
|
2076
|
-
}
|
|
2077
|
-
/**
|
|
2078
|
-
* Stuck-app recovery: pause for the device's UI transition, then retry once.
|
|
2079
|
-
*
|
|
2080
|
-
* Caller has already cleared the session + reset connector. We wait so Stax
|
|
2081
|
-
* finishes its post-CloseApp animation, then go through ensureConnected +
|
|
2082
|
-
* fingerprint check + call exactly once. Caller decides what to do on a
|
|
2083
|
-
* second stuck-app hit.
|
|
2084
|
-
*/
|
|
2085
|
-
async _retryAfterStuckApp(resolvedConnectId, method, params, signal, originalErr, fingerprint) {
|
|
2086
|
-
await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
|
|
2087
|
-
const retryConnectId = await this.ensureConnected(
|
|
2088
|
-
resolvedConnectId,
|
|
2089
|
-
signal,
|
|
2090
|
-
!!fingerprint?.deviceId && !fingerprint.skipFingerprint
|
|
2091
|
-
);
|
|
2092
|
-
const retrySessionId = this._sessions.get(retryConnectId);
|
|
2093
|
-
if (!retrySessionId) throw originalErr;
|
|
2094
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2095
|
-
const fp = await this._abortable(
|
|
2096
|
-
signal,
|
|
2097
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2098
|
-
retrySessionId,
|
|
2099
|
-
fingerprint.deviceId,
|
|
2100
|
-
fingerprint.chain
|
|
2101
|
-
)
|
|
2102
|
-
);
|
|
2103
|
-
if (!fp.success) {
|
|
2104
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2105
|
-
code: HardwareErrorCode3.DeviceMismatch
|
|
2106
|
-
});
|
|
2107
|
-
}
|
|
2108
|
-
}
|
|
2109
|
-
return this._callConnector(retrySessionId, method, params, signal);
|
|
2110
|
-
}
|
|
2111
|
-
_sleepAbortable(ms, signal) {
|
|
2112
|
-
return new Promise((resolve, reject) => {
|
|
2113
|
-
if (signal.aborted) {
|
|
2114
|
-
reject(signal.reason ?? new Error("Aborted"));
|
|
2115
|
-
return;
|
|
3191
|
+
throw err;
|
|
3192
|
+
}
|
|
3193
|
+
}
|
|
3194
|
+
_sleepAbortable(ms, signal) {
|
|
3195
|
+
return new Promise((resolve, reject) => {
|
|
3196
|
+
if (signal.aborted) {
|
|
3197
|
+
reject(signal.reason ?? new Error("Aborted"));
|
|
3198
|
+
return;
|
|
2116
3199
|
}
|
|
2117
3200
|
const timer = setTimeout(() => {
|
|
2118
3201
|
signal.removeEventListener("abort", onAbort);
|
|
@@ -2126,111 +3209,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2126
3209
|
});
|
|
2127
3210
|
}
|
|
2128
3211
|
/**
|
|
2129
|
-
*
|
|
2130
|
-
*
|
|
2131
|
-
* Timeout recovery starts with a full connector reset. After an APDU
|
|
2132
|
-
* timeout, DMK/transport state may still emit malformed responses; retrying
|
|
2133
|
-
* on the same DMK can poison the next chain switch.
|
|
2134
|
-
*/
|
|
2135
|
-
async _retryWithFreshConnection(targetConnectId, method, params, signal, originalErr, fingerprint) {
|
|
2136
|
-
this.connector.reset();
|
|
2137
|
-
this._sessions.clear();
|
|
2138
|
-
this._discoveredDevices.clear();
|
|
2139
|
-
this._connectingPromise = null;
|
|
2140
|
-
const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
|
|
2141
|
-
const retryConnectId = await this.ensureConnected(
|
|
2142
|
-
targetConnectId,
|
|
2143
|
-
signal,
|
|
2144
|
-
allowUsbEphemeralFallback
|
|
2145
|
-
);
|
|
2146
|
-
const retrySessionId = this._sessions.get(retryConnectId);
|
|
2147
|
-
if (!retrySessionId) {
|
|
2148
|
-
throw originalErr;
|
|
2149
|
-
}
|
|
2150
|
-
try {
|
|
2151
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2152
|
-
const fp = await this._abortable(
|
|
2153
|
-
signal,
|
|
2154
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2155
|
-
retrySessionId,
|
|
2156
|
-
fingerprint.deviceId,
|
|
2157
|
-
fingerprint.chain
|
|
2158
|
-
)
|
|
2159
|
-
);
|
|
2160
|
-
if (!fp.success) {
|
|
2161
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2162
|
-
code: HardwareErrorCode3.DeviceMismatch
|
|
2163
|
-
});
|
|
2164
|
-
}
|
|
2165
|
-
}
|
|
2166
|
-
return await this._callConnector(retrySessionId, method, params, signal);
|
|
2167
|
-
} catch (retryErr) {
|
|
2168
|
-
if (signal.aborted) throw retryErr;
|
|
2169
|
-
this.connector.reset();
|
|
2170
|
-
this._sessions.clear();
|
|
2171
|
-
this._discoveredDevices.clear();
|
|
2172
|
-
this._connectingPromise = null;
|
|
2173
|
-
if (!isDeviceDisconnectedError(retryErr) && !isTimeoutError(retryErr)) {
|
|
2174
|
-
throw retryErr;
|
|
2175
|
-
}
|
|
2176
|
-
debugLog(
|
|
2177
|
-
"[LedgerAdapter] fresh-session retry still failed; resetting connector and rebuilding DMK"
|
|
2178
|
-
);
|
|
2179
|
-
this.connector.reset();
|
|
2180
|
-
this._sessions.clear();
|
|
2181
|
-
this._discoveredDevices.clear();
|
|
2182
|
-
this._connectingPromise = null;
|
|
2183
|
-
const finalConnectId = await this.ensureConnected(
|
|
2184
|
-
targetConnectId,
|
|
2185
|
-
signal,
|
|
2186
|
-
allowUsbEphemeralFallback
|
|
2187
|
-
);
|
|
2188
|
-
const finalSessionId = this._sessions.get(finalConnectId);
|
|
2189
|
-
if (!finalSessionId) {
|
|
2190
|
-
throw originalErr;
|
|
2191
|
-
}
|
|
2192
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2193
|
-
const fp = await this._abortable(
|
|
2194
|
-
signal,
|
|
2195
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2196
|
-
finalSessionId,
|
|
2197
|
-
fingerprint.deviceId,
|
|
2198
|
-
fingerprint.chain
|
|
2199
|
-
)
|
|
2200
|
-
);
|
|
2201
|
-
if (!fp.success) {
|
|
2202
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2203
|
-
code: HardwareErrorCode3.DeviceMismatch
|
|
2204
|
-
});
|
|
2205
|
-
}
|
|
2206
|
-
}
|
|
2207
|
-
return this._callConnector(finalSessionId, method, params, signal);
|
|
2208
|
-
}
|
|
2209
|
-
}
|
|
2210
|
-
/**
|
|
2211
|
-
* Ensure OS-level device permission (Bluetooth / USB) before proceeding.
|
|
2212
|
-
*
|
|
2213
|
-
* Emits `REQUEST_DEVICE_PERMISSION` and awaits the consumer's
|
|
2214
|
-
* `RECEIVE_DEVICE_PERMISSION` reply (60s budget covers "probe → system
|
|
2215
|
-
* prompt → user tap" plus a generous margin). If the consumer never wires
|
|
2216
|
-
* a handler or never replies, the wait times out and the operation fails
|
|
2217
|
-
* fast so scanners/callers don't hang silently.
|
|
2218
|
-
*
|
|
2219
|
-
* - No connectId (searchDevices): environment-level permission
|
|
2220
|
-
* - With connectId (business methods): device-level permission
|
|
3212
|
+
* Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
|
|
3213
|
+
* replies. Without connectId the request is environment-level, else device-level.
|
|
2221
3214
|
*/
|
|
2222
|
-
async _ensureDevicePermission(connectId, deviceId, signal) {
|
|
3215
|
+
async _ensureDevicePermission(connectId, deviceId, signal, transportOverride) {
|
|
2223
3216
|
if (signal?.aborted) {
|
|
2224
3217
|
_LedgerAdapter._throwIfAborted(signal);
|
|
2225
3218
|
}
|
|
2226
|
-
const transportType = this.activeTransport ?? "hid";
|
|
3219
|
+
const transportType = transportOverride ?? this.activeTransport ?? "hid";
|
|
3220
|
+
const operationId = this._activeOperationId();
|
|
2227
3221
|
const waitPromise = this._uiRegistry.wait(
|
|
2228
3222
|
UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
2229
|
-
{ timeoutMs: 6e4 }
|
|
3223
|
+
{ timeoutMs: 6e4, operationId }
|
|
2230
3224
|
);
|
|
2231
3225
|
this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
|
|
2232
3226
|
type: UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
2233
|
-
payload: { transportType, connectId, deviceId }
|
|
3227
|
+
payload: { transportType, connectId, deviceId, operationId }
|
|
2234
3228
|
});
|
|
2235
3229
|
let response;
|
|
2236
3230
|
const onAbort = () => {
|
|
@@ -2246,7 +3240,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2246
3240
|
if (err?._tag === UI_REQUEST_PREEMPTED_TAG) {
|
|
2247
3241
|
this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2248
3242
|
type: UI_REQUEST.CLOSE_UI_WINDOW,
|
|
2249
|
-
payload: {}
|
|
3243
|
+
payload: { operationId }
|
|
2250
3244
|
});
|
|
2251
3245
|
throw Object.assign(new Error("Device permission request superseded"), {
|
|
2252
3246
|
_tag: ERROR_TAG.UserAborted,
|
|
@@ -2276,7 +3270,15 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2276
3270
|
if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
|
|
2277
3271
|
const e = err;
|
|
2278
3272
|
const params = e.code === HardwareErrorCode3.DevicePermissionDenied && e.reason ? { permissionDeniedReason: e.reason } : e.params;
|
|
2279
|
-
return ledgerFailure(
|
|
3273
|
+
return ledgerFailure(
|
|
3274
|
+
e.code,
|
|
3275
|
+
e.message ?? "Unknown error",
|
|
3276
|
+
e.appName,
|
|
3277
|
+
tag,
|
|
3278
|
+
params,
|
|
3279
|
+
void 0,
|
|
3280
|
+
isHwkRecoveryHint(e.recovery) ? e.recovery : void 0
|
|
3281
|
+
);
|
|
2280
3282
|
}
|
|
2281
3283
|
const mapped = mapLedgerError(err);
|
|
2282
3284
|
return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
|
|
@@ -2303,7 +3305,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2303
3305
|
deviceId: device.deviceId,
|
|
2304
3306
|
connectId: device.connectId,
|
|
2305
3307
|
label: device.name,
|
|
2306
|
-
connectionType: this.connector.connectionType,
|
|
3308
|
+
connectionType: device.connectionType ?? this.connector.connectionType,
|
|
2307
3309
|
rssi: device.rssi,
|
|
2308
3310
|
isConnectable: device.isConnectable,
|
|
2309
3311
|
serialNumber: device.serialNumber,
|
|
@@ -2329,8 +3331,9 @@ var LedgerAdapter = _LedgerAdapter;
|
|
|
2329
3331
|
|
|
2330
3332
|
// src/connector/LedgerConnectorBase.ts
|
|
2331
3333
|
import {
|
|
2332
|
-
EConnectorInteraction as
|
|
2333
|
-
HardwareErrorCode as
|
|
3334
|
+
EConnectorInteraction as EConnectorInteraction3,
|
|
3335
|
+
HardwareErrorCode as HardwareErrorCode7,
|
|
3336
|
+
createHwkError as createHwkError2,
|
|
2334
3337
|
isKnownNonTargetHardwareVendor,
|
|
2335
3338
|
serializeConnectorError
|
|
2336
3339
|
} from "@onekeyfe/hwk-adapter-core";
|
|
@@ -2603,7 +3606,7 @@ var LedgerDeviceManager = class {
|
|
|
2603
3606
|
|
|
2604
3607
|
// src/signer/SignerManager.ts
|
|
2605
3608
|
import { SignerEthBuilder } from "@ledgerhq/device-signer-kit-ethereum";
|
|
2606
|
-
import { ContextModuleBuilder } from "@ledgerhq/context-module";
|
|
3609
|
+
import { ContextModuleBuilder, ContextModuleChainID } from "@ledgerhq/context-module";
|
|
2607
3610
|
|
|
2608
3611
|
// src/signer/SignerEth.ts
|
|
2609
3612
|
import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
|
|
@@ -2611,11 +3614,15 @@ import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
|
|
|
2611
3614
|
// src/signer/deviceActionToPromise.ts
|
|
2612
3615
|
import { DeviceActionStatus } from "@ledgerhq/device-management-kit";
|
|
2613
3616
|
var IDLE_WATCHDOG_MS = 65e3;
|
|
3617
|
+
var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
|
|
3618
|
+
var INTERACTION_PROMPT_DELAY_MS = 500;
|
|
2614
3619
|
function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
|
|
2615
3620
|
return new Promise((resolve, reject) => {
|
|
2616
3621
|
let settled = false;
|
|
2617
3622
|
let lastStep;
|
|
2618
3623
|
let activeInteraction;
|
|
3624
|
+
let pendingInteraction;
|
|
3625
|
+
let pendingInteractionTimer = null;
|
|
2619
3626
|
const observedSteps = [];
|
|
2620
3627
|
let sub;
|
|
2621
3628
|
let timer = null;
|
|
@@ -2643,31 +3650,52 @@ function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_
|
|
|
2643
3650
|
}
|
|
2644
3651
|
return false;
|
|
2645
3652
|
};
|
|
3653
|
+
const cancelPendingInteraction = () => {
|
|
3654
|
+
if (pendingInteractionTimer) clearTimeout(pendingInteractionTimer);
|
|
3655
|
+
pendingInteractionTimer = null;
|
|
3656
|
+
pendingInteraction = void 0;
|
|
3657
|
+
};
|
|
3658
|
+
const showInteraction = (interactionName) => {
|
|
3659
|
+
activeInteraction = interactionName;
|
|
3660
|
+
debugLog(
|
|
3661
|
+
"[DeviceAction] requiredUserInteraction",
|
|
3662
|
+
`interaction=${interactionName}`,
|
|
3663
|
+
`step=${lastStep ?? "unknown"}`
|
|
3664
|
+
);
|
|
3665
|
+
if (interactionName === "unlock-device" && timer) {
|
|
3666
|
+
clearTimeout(timer);
|
|
3667
|
+
timer = null;
|
|
3668
|
+
}
|
|
3669
|
+
onInteraction?.(interactionName);
|
|
3670
|
+
};
|
|
2646
3671
|
const emitInteraction = (interaction) => {
|
|
2647
3672
|
if (!onInteraction) {
|
|
2648
3673
|
return;
|
|
2649
3674
|
}
|
|
2650
3675
|
if (!interaction || interaction === "none") {
|
|
3676
|
+
cancelPendingInteraction();
|
|
2651
3677
|
clearActiveInteraction();
|
|
2652
3678
|
return;
|
|
2653
3679
|
}
|
|
2654
3680
|
const interactionName = String(interaction);
|
|
2655
|
-
if (interactionName === activeInteraction) {
|
|
3681
|
+
if (interactionName === activeInteraction || interactionName === pendingInteraction) {
|
|
2656
3682
|
return;
|
|
2657
3683
|
}
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
);
|
|
2664
|
-
if (interaction === "unlock-device" && timer) {
|
|
2665
|
-
clearTimeout(timer);
|
|
2666
|
-
timer = null;
|
|
3684
|
+
cancelPendingInteraction();
|
|
3685
|
+
clearActiveInteraction();
|
|
3686
|
+
if (interactionName === "unlock-device") {
|
|
3687
|
+
showInteraction(interactionName);
|
|
3688
|
+
return;
|
|
2667
3689
|
}
|
|
2668
|
-
|
|
3690
|
+
pendingInteraction = interactionName;
|
|
3691
|
+
pendingInteractionTimer = setTimeout(() => {
|
|
3692
|
+
pendingInteractionTimer = null;
|
|
3693
|
+
pendingInteraction = void 0;
|
|
3694
|
+
if (!settled) showInteraction(interactionName);
|
|
3695
|
+
}, INTERACTION_PROMPT_DELAY_MS);
|
|
2669
3696
|
};
|
|
2670
3697
|
const completeInteraction = () => {
|
|
3698
|
+
cancelPendingInteraction();
|
|
2671
3699
|
if (!clearActiveInteraction()) {
|
|
2672
3700
|
onInteraction?.("interaction-complete");
|
|
2673
3701
|
}
|
|
@@ -2798,7 +3826,6 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
|
|
|
2798
3826
|
}
|
|
2799
3827
|
|
|
2800
3828
|
// src/signer/SignerEth.ts
|
|
2801
|
-
var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
|
|
2802
3829
|
var SignerEth = class {
|
|
2803
3830
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
2804
3831
|
constructor(_sdk) {
|
|
@@ -2869,7 +3896,7 @@ var SignerManager = class _SignerManager {
|
|
|
2869
3896
|
return (args) => new SignerEthBuilder(args);
|
|
2870
3897
|
}
|
|
2871
3898
|
static _createContextModule() {
|
|
2872
|
-
const contextModule = new ContextModuleBuilder({}).removeDefaultLoaders().build();
|
|
3899
|
+
const contextModule = new ContextModuleBuilder({}).setChain(ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
|
|
2873
3900
|
return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
|
|
2874
3901
|
}
|
|
2875
3902
|
static wrapBlindSigningReportNonBlocking(contextModule) {
|
|
@@ -2907,6 +3934,27 @@ function collapseSignerInteraction(interaction) {
|
|
|
2907
3934
|
return EConnectorInteraction2.ConfirmOnDevice;
|
|
2908
3935
|
}
|
|
2909
3936
|
}
|
|
3937
|
+
function wireSignerToSession(ctx, sessionId, chain, signer) {
|
|
3938
|
+
signer.onInteraction = (interaction) => {
|
|
3939
|
+
debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
|
|
3940
|
+
ctx.emit("ui-event", {
|
|
3941
|
+
type: collapseSignerInteraction(interaction),
|
|
3942
|
+
payload: { sessionId }
|
|
3943
|
+
});
|
|
3944
|
+
};
|
|
3945
|
+
signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
|
|
3946
|
+
return signer;
|
|
3947
|
+
}
|
|
3948
|
+
async function runSignerCall(ctx, sessionId, call) {
|
|
3949
|
+
try {
|
|
3950
|
+
return await call();
|
|
3951
|
+
} catch (err) {
|
|
3952
|
+
ctx.invalidateSession(sessionId);
|
|
3953
|
+
throw ctx.wrapError(err);
|
|
3954
|
+
} finally {
|
|
3955
|
+
ctx.clearCanceller(sessionId);
|
|
3956
|
+
}
|
|
3957
|
+
}
|
|
2910
3958
|
|
|
2911
3959
|
// src/connector/chains/evm.ts
|
|
2912
3960
|
async function evmGetAddress(ctx, sessionId, params) {
|
|
@@ -3007,14 +4055,13 @@ async function _getEthSigner(ctx, sessionId) {
|
|
|
3007
4055
|
|
|
3008
4056
|
// src/connector/chains/btc.ts
|
|
3009
4057
|
import { HardwareErrorCode as HardwareErrorCode5, stripHex as stripHex2 } from "@onekeyfe/hwk-adapter-core";
|
|
3010
|
-
import { Psbt } from "bitcoinjs-lib";
|
|
4058
|
+
import { Psbt as Psbt2 } from "bitcoinjs-lib";
|
|
3011
4059
|
|
|
3012
4060
|
// src/signer/SignerBtc.ts
|
|
3013
4061
|
import { hexToBytes as hexToBytes2 } from "@onekeyfe/hwk-adapter-core";
|
|
3014
4062
|
function hexToUtf8(hex) {
|
|
3015
4063
|
return new TextDecoder().decode(hexToBytes2(hex));
|
|
3016
4064
|
}
|
|
3017
|
-
var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
|
|
3018
4065
|
var SignerBtc = class {
|
|
3019
4066
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
3020
4067
|
constructor(_sdk) {
|
|
@@ -3028,7 +4075,7 @@ var SignerBtc = class {
|
|
|
3028
4075
|
return deviceActionToPromise(
|
|
3029
4076
|
action,
|
|
3030
4077
|
this.onInteraction,
|
|
3031
|
-
void 0,
|
|
4078
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3032
4079
|
this.onRegisterCanceller
|
|
3033
4080
|
);
|
|
3034
4081
|
}
|
|
@@ -3046,14 +4093,14 @@ var SignerBtc = class {
|
|
|
3046
4093
|
const result = await deviceActionToPromise(
|
|
3047
4094
|
action,
|
|
3048
4095
|
this.onInteraction,
|
|
3049
|
-
void 0,
|
|
4096
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3050
4097
|
this.onRegisterCanceller
|
|
3051
4098
|
);
|
|
3052
4099
|
debugLog(
|
|
3053
4100
|
"[SignerBtc] getExtendedPublicKey result type:",
|
|
3054
4101
|
typeof result,
|
|
3055
4102
|
"value:",
|
|
3056
|
-
|
|
4103
|
+
summarizeForLog(result)
|
|
3057
4104
|
);
|
|
3058
4105
|
if (typeof result === "string") return result;
|
|
3059
4106
|
return result.extendedPublicKey;
|
|
@@ -3082,7 +4129,7 @@ var SignerBtc = class {
|
|
|
3082
4129
|
return deviceActionToPromise(
|
|
3083
4130
|
action,
|
|
3084
4131
|
this.onInteraction,
|
|
3085
|
-
|
|
4132
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3086
4133
|
this.onRegisterCanceller
|
|
3087
4134
|
);
|
|
3088
4135
|
}
|
|
@@ -3095,7 +4142,7 @@ var SignerBtc = class {
|
|
|
3095
4142
|
return deviceActionToPromise(
|
|
3096
4143
|
action,
|
|
3097
4144
|
this.onInteraction,
|
|
3098
|
-
|
|
4145
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3099
4146
|
this.onRegisterCanceller
|
|
3100
4147
|
);
|
|
3101
4148
|
}
|
|
@@ -3108,7 +4155,7 @@ var SignerBtc = class {
|
|
|
3108
4155
|
return deviceActionToPromise(
|
|
3109
4156
|
action,
|
|
3110
4157
|
this.onInteraction,
|
|
3111
|
-
|
|
4158
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3112
4159
|
this.onRegisterCanceller
|
|
3113
4160
|
);
|
|
3114
4161
|
}
|
|
@@ -3131,7 +4178,21 @@ function _purposeToTemplate(purpose, DDT) {
|
|
|
3131
4178
|
});
|
|
3132
4179
|
}
|
|
3133
4180
|
}
|
|
4181
|
+
function assertBitcoinMainnet(coin) {
|
|
4182
|
+
if (coin !== void 0 && !["btc", "bitcoin"].includes(coin.toLowerCase())) {
|
|
4183
|
+
throw Object.assign(new Error(`Ledger BTC supports Bitcoin mainnet only, not ${coin}`), {
|
|
4184
|
+
code: HardwareErrorCode5.ChainNotSupported
|
|
4185
|
+
});
|
|
4186
|
+
}
|
|
4187
|
+
}
|
|
3134
4188
|
async function btcGetAddress(ctx, sessionId, params) {
|
|
4189
|
+
assertBitcoinMainnet(params.coin);
|
|
4190
|
+
if (normalizePath(params.path).split("/").length !== 3) {
|
|
4191
|
+
throw Object.assign(
|
|
4192
|
+
new Error("Ledger btcGetAddress takes an account path (e.g. m/84'/0'/0') plus addressIndex"),
|
|
4193
|
+
{ code: HardwareErrorCode5.InvalidParams }
|
|
4194
|
+
);
|
|
4195
|
+
}
|
|
3135
4196
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
3136
4197
|
const path = normalizePath(params.path);
|
|
3137
4198
|
try {
|
|
@@ -3162,6 +4223,7 @@ async function btcGetAddress(ctx, sessionId, params) {
|
|
|
3162
4223
|
}
|
|
3163
4224
|
}
|
|
3164
4225
|
async function btcGetPublicKey(ctx, sessionId, params) {
|
|
4226
|
+
assertBitcoinMainnet(params.coin);
|
|
3165
4227
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
3166
4228
|
const path = normalizePath(params.path);
|
|
3167
4229
|
debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
|
|
@@ -3169,7 +4231,7 @@ async function btcGetPublicKey(ctx, sessionId, params) {
|
|
|
3169
4231
|
const xpub = await btcSigner.getExtendedPublicKey(path, {
|
|
3170
4232
|
checkOnDevice: params.showOnDevice ?? false
|
|
3171
4233
|
});
|
|
3172
|
-
debugLog("[LedgerConnector] btcGetPublicKey success, xpub:",
|
|
4234
|
+
debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", summarizeForLog(xpub));
|
|
3173
4235
|
return { xpub, path: params.path };
|
|
3174
4236
|
} catch (err) {
|
|
3175
4237
|
debugError("[LedgerConnector] btcGetPublicKey error, path:", path, "err:", err);
|
|
@@ -3290,7 +4352,7 @@ function _isScriptPathInput(input) {
|
|
|
3290
4352
|
return !!(input.tapLeafScript && input.tapLeafScript.length > 0);
|
|
3291
4353
|
}
|
|
3292
4354
|
function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
3293
|
-
const psbt =
|
|
4355
|
+
const psbt = Psbt2.fromHex(psbtHex);
|
|
3294
4356
|
for (const sig of signatures) {
|
|
3295
4357
|
const input = psbt.data.inputs[sig.inputIndex];
|
|
3296
4358
|
if (!input) {
|
|
@@ -3339,7 +4401,8 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
|
3339
4401
|
}
|
|
3340
4402
|
|
|
3341
4403
|
// src/connector/chains/sol.ts
|
|
3342
|
-
import { bytesToHex, hexToBytes as hexToBytes3 } from "@onekeyfe/hwk-adapter-core";
|
|
4404
|
+
import { bytesToHex, hexToBytes as hexToBytes3, prepareSolanaOffchainMessageV1 } from "@onekeyfe/hwk-adapter-core";
|
|
4405
|
+
import bs58 from "bs58";
|
|
3343
4406
|
|
|
3344
4407
|
// src/signer/SignerSol.ts
|
|
3345
4408
|
var SignerSol = class {
|
|
@@ -3357,7 +4420,7 @@ var SignerSol = class {
|
|
|
3357
4420
|
return deviceActionToPromise(
|
|
3358
4421
|
action,
|
|
3359
4422
|
this.onInteraction,
|
|
3360
|
-
void 0,
|
|
4423
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3361
4424
|
this.onRegisterCanceller
|
|
3362
4425
|
);
|
|
3363
4426
|
}
|
|
@@ -3369,7 +4432,7 @@ var SignerSol = class {
|
|
|
3369
4432
|
return deviceActionToPromise(
|
|
3370
4433
|
action,
|
|
3371
4434
|
this.onInteraction,
|
|
3372
|
-
|
|
4435
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3373
4436
|
this.onRegisterCanceller
|
|
3374
4437
|
);
|
|
3375
4438
|
}
|
|
@@ -3382,7 +4445,7 @@ var SignerSol = class {
|
|
|
3382
4445
|
return deviceActionToPromise(
|
|
3383
4446
|
action,
|
|
3384
4447
|
this.onInteraction,
|
|
3385
|
-
|
|
4448
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3386
4449
|
this.onRegisterCanceller
|
|
3387
4450
|
);
|
|
3388
4451
|
}
|
|
@@ -3423,8 +4486,21 @@ async function solSignMessage(ctx, sessionId, params) {
|
|
|
3423
4486
|
const path = normalizePath(params.path);
|
|
3424
4487
|
const messageBytes = hexToBytes3(params.message);
|
|
3425
4488
|
try {
|
|
4489
|
+
if (params.messageVersion === 1) {
|
|
4490
|
+
const preparedMessage = prepareSolanaOffchainMessageV1({
|
|
4491
|
+
message: messageBytes,
|
|
4492
|
+
requiredSigners: params.requiredSigners
|
|
4493
|
+
});
|
|
4494
|
+
const { SignMessageVersion } = await ctx.importLedgerKit(
|
|
4495
|
+
"@ledgerhq/device-signer-kit-solana"
|
|
4496
|
+
);
|
|
4497
|
+
const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
|
|
4498
|
+
version: SignMessageVersion.Raw
|
|
4499
|
+
});
|
|
4500
|
+
return { signature: decodeBase58Signature(result2.signature) };
|
|
4501
|
+
}
|
|
3426
4502
|
const result = await solSigner.signMessage(path, messageBytes);
|
|
3427
|
-
return { signature: result.signature };
|
|
4503
|
+
return { signature: decodeBase58EnvelopeSignature(result.signature) };
|
|
3428
4504
|
} catch (err) {
|
|
3429
4505
|
ctx.invalidateSession(sessionId);
|
|
3430
4506
|
throw ctx.wrapError(err);
|
|
@@ -3432,11 +4508,27 @@ async function solSignMessage(ctx, sessionId, params) {
|
|
|
3432
4508
|
ctx.clearCanceller(sessionId);
|
|
3433
4509
|
}
|
|
3434
4510
|
}
|
|
4511
|
+
function decodeBase58Signature(signature) {
|
|
4512
|
+
const bytes = bs58.decode(signature);
|
|
4513
|
+
if (bytes.length !== 64) {
|
|
4514
|
+
throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
|
|
4515
|
+
}
|
|
4516
|
+
return bytesToHex(bytes);
|
|
4517
|
+
}
|
|
4518
|
+
function decodeBase58EnvelopeSignature(envelope) {
|
|
4519
|
+
const bytes = bs58.decode(envelope);
|
|
4520
|
+
if (bytes.length < 65 || bytes[0] !== 1) {
|
|
4521
|
+
throw new Error("Ledger Solana signature envelope is invalid");
|
|
4522
|
+
}
|
|
4523
|
+
return bytesToHex(bytes.subarray(1, 65));
|
|
4524
|
+
}
|
|
3435
4525
|
async function _createSolSigner(ctx, sessionId) {
|
|
3436
4526
|
const dmk = await ctx.getOrCreateDmk();
|
|
3437
|
-
const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit(
|
|
4527
|
+
const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
|
|
4528
|
+
"@ledgerhq/context-module"
|
|
4529
|
+
);
|
|
3438
4530
|
const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
|
|
3439
|
-
const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
|
|
4531
|
+
const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
|
|
3440
4532
|
const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
|
|
3441
4533
|
const signer = new SignerSol(sdkSigner);
|
|
3442
4534
|
signer.onInteraction = (interaction) => {
|
|
@@ -3452,361 +4544,147 @@ async function _createSolSigner(ctx, sessionId) {
|
|
|
3452
4544
|
return signer;
|
|
3453
4545
|
}
|
|
3454
4546
|
|
|
3455
|
-
// src/connector/chains/
|
|
3456
|
-
import {
|
|
3457
|
-
import Trx from "@ledgerhq/hw-app-trx";
|
|
3458
|
-
|
|
3459
|
-
// src/connector/chains/legacyChainCall.ts
|
|
3460
|
-
import { EConnectorInteraction as EConnectorInteraction3 } from "@onekeyfe/hwk-adapter-core";
|
|
4547
|
+
// src/connector/chains/zcash.ts
|
|
4548
|
+
import { bytesToHex as bytesToHex2 } from "@onekeyfe/hwk-adapter-core";
|
|
3461
4549
|
|
|
3462
|
-
// src/
|
|
3463
|
-
|
|
3464
|
-
|
|
3465
|
-
|
|
3466
|
-
|
|
3467
|
-
isSuccessCommandResult
|
|
3468
|
-
} from "@ledgerhq/device-management-kit";
|
|
3469
|
-
import { HardwareErrorCode as HardwareErrorCode6 } from "@onekeyfe/hwk-adapter-core";
|
|
3470
|
-
var APP_NAME_MAP = {
|
|
3471
|
-
ETH: "Ethereum",
|
|
3472
|
-
BTC: "Bitcoin",
|
|
3473
|
-
SOL: "Solana",
|
|
3474
|
-
TRX: "Tron",
|
|
3475
|
-
XRP: "XRP",
|
|
3476
|
-
ADA: "Cardano",
|
|
3477
|
-
DOT: "Polkadot",
|
|
3478
|
-
ATOM: "Cosmos"
|
|
3479
|
-
};
|
|
3480
|
-
var DASHBOARD_APP_NAME = "BOLOS";
|
|
3481
|
-
var AppManager = class {
|
|
3482
|
-
constructor(dmk, options) {
|
|
3483
|
-
this._dmk = dmk;
|
|
3484
|
-
this._waitMs = options?.waitMs ?? 1e3;
|
|
3485
|
-
this._maxRetries = options?.maxRetries ?? 10;
|
|
3486
|
-
}
|
|
3487
|
-
/**
|
|
3488
|
-
* Return the Ledger app name for a given chain ticker,
|
|
3489
|
-
* or undefined if the chain is not supported.
|
|
3490
|
-
*/
|
|
3491
|
-
static getAppName(chain) {
|
|
3492
|
-
return APP_NAME_MAP[chain];
|
|
3493
|
-
}
|
|
3494
|
-
/**
|
|
3495
|
-
* Ensure the target app is open on the device identified by `sessionId`.
|
|
3496
|
-
*
|
|
3497
|
-
* Flow:
|
|
3498
|
-
* 1. Check the currently running app.
|
|
3499
|
-
* 2. If it is already the target, return immediately.
|
|
3500
|
-
* 3. If a different app is running (not dashboard), close it first.
|
|
3501
|
-
* 4. Open the target app.
|
|
3502
|
-
* 5. Poll until the device confirms the target app is running.
|
|
3503
|
-
*/
|
|
3504
|
-
/**
|
|
3505
|
-
* @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
|
|
3506
|
-
* device is about to display "Open <app>" on screen and wait for the
|
|
3507
|
-
* user's button press. UI consumers should show their "open app" prompt
|
|
3508
|
-
* in response. NOT called when the target app is already open (no user
|
|
3509
|
-
* interaction needed in that case).
|
|
3510
|
-
*
|
|
3511
|
-
* Important: OpenAppCommand is blocking. It does not resolve until the user
|
|
3512
|
-
* has physically confirmed on the device, so anything that runs AFTER
|
|
3513
|
-
* `await this._openApp(...)` lands AFTER the prompt is already gone.
|
|
3514
|
-
* Hence the callback must fire BEFORE that await.
|
|
3515
|
-
*/
|
|
3516
|
-
async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
|
|
3517
|
-
const currentApp = await this._getCurrentApp(sessionId);
|
|
3518
|
-
if (currentApp === targetAppName) {
|
|
3519
|
-
return;
|
|
3520
|
-
}
|
|
3521
|
-
if (!this._isDashboard(currentApp)) {
|
|
3522
|
-
await this._closeCurrentApp(sessionId);
|
|
3523
|
-
await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
|
|
3524
|
-
}
|
|
3525
|
-
onConfirmOnDevice?.();
|
|
3526
|
-
await this._openApp(sessionId, targetAppName);
|
|
3527
|
-
await this._waitForApp(sessionId, targetAppName);
|
|
4550
|
+
// src/signer/SignerZcash.ts
|
|
4551
|
+
var SignerZcash = class {
|
|
4552
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4553
|
+
constructor(_sdk) {
|
|
4554
|
+
this._sdk = _sdk;
|
|
3528
4555
|
}
|
|
3529
|
-
|
|
3530
|
-
|
|
3531
|
-
|
|
3532
|
-
|
|
3533
|
-
|
|
3534
|
-
|
|
3535
|
-
|
|
3536
|
-
|
|
3537
|
-
if (isSuccessCommandResult(result)) {
|
|
3538
|
-
debugLog("[AppManager] currentApp:", result.data.name);
|
|
3539
|
-
return result.data.name;
|
|
3540
|
-
}
|
|
3541
|
-
const errResult = result;
|
|
3542
|
-
const dmkErr = errResult.error ?? {};
|
|
3543
|
-
const original = dmkErr.originalError;
|
|
3544
|
-
debugLog(
|
|
3545
|
-
"[AppManager] _getCurrentApp failed sessionId=",
|
|
3546
|
-
sessionId,
|
|
3547
|
-
"tag=",
|
|
3548
|
-
dmkErr._tag,
|
|
3549
|
-
"errorCode=",
|
|
3550
|
-
dmkErr.errorCode,
|
|
3551
|
-
"message=",
|
|
3552
|
-
dmkErr.message,
|
|
3553
|
-
"originalErrorMessage=",
|
|
3554
|
-
original?.message ?? String(original ?? "")
|
|
3555
|
-
);
|
|
3556
|
-
throw Object.assign(
|
|
3557
|
-
new Error(
|
|
3558
|
-
dmkErr.message ?? "Failed to get current app from device"
|
|
3559
|
-
),
|
|
3560
|
-
{
|
|
3561
|
-
_tag: dmkErr._tag,
|
|
3562
|
-
errorCode: dmkErr.errorCode,
|
|
3563
|
-
originalError: original
|
|
3564
|
-
}
|
|
4556
|
+
/** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
|
|
4557
|
+
async getFullViewingKey(derivationPath, options) {
|
|
4558
|
+
const action = this._sdk.getFullViewingKey(derivationPath, options);
|
|
4559
|
+
return deviceActionToPromise(
|
|
4560
|
+
action,
|
|
4561
|
+
this.onInteraction,
|
|
4562
|
+
void 0,
|
|
4563
|
+
this.onRegisterCanceller
|
|
3565
4564
|
);
|
|
3566
4565
|
}
|
|
3567
|
-
|
|
3568
|
-
|
|
3569
|
-
|
|
3570
|
-
|
|
3571
|
-
|
|
3572
|
-
|
|
3573
|
-
|
|
3574
|
-
|
|
3575
|
-
const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
|
|
3576
|
-
debugLog(
|
|
3577
|
-
"[AppManager] openApp failed:",
|
|
3578
|
-
appName,
|
|
3579
|
-
"errorCode:",
|
|
3580
|
-
errorCode,
|
|
3581
|
-
"tag:",
|
|
3582
|
-
dmkErr._tag
|
|
3583
|
-
);
|
|
3584
|
-
let code;
|
|
3585
|
-
if (errorCode === "6807" || /unknown application/i.test(message)) {
|
|
3586
|
-
code = HardwareErrorCode6.AppNotInstalled;
|
|
3587
|
-
} else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
|
|
3588
|
-
code = HardwareErrorCode6.UserRejected;
|
|
3589
|
-
}
|
|
3590
|
-
throw Object.assign(new Error(`Failed to open "${appName}"`), {
|
|
3591
|
-
_tag: ERROR_TAG.OpenAppCommand,
|
|
3592
|
-
code,
|
|
3593
|
-
errorCode,
|
|
3594
|
-
statusCode: errorCode,
|
|
3595
|
-
appName,
|
|
3596
|
-
originalError: dmkErr
|
|
3597
|
-
});
|
|
3598
|
-
}
|
|
3599
|
-
}
|
|
3600
|
-
async _closeCurrentApp(sessionId) {
|
|
3601
|
-
debugLog("[AppManager] closeCurrentApp");
|
|
3602
|
-
await this._dmk.sendCommand({
|
|
3603
|
-
sessionId,
|
|
3604
|
-
command: new CloseAppCommand()
|
|
3605
|
-
});
|
|
3606
|
-
}
|
|
3607
|
-
/**
|
|
3608
|
-
* Poll the device until the expected app is reported as running,
|
|
3609
|
-
* or throw after `_maxRetries` attempts.
|
|
3610
|
-
*/
|
|
3611
|
-
async _waitForApp(sessionId, expectedAppName) {
|
|
3612
|
-
let lastSeen = "";
|
|
3613
|
-
for (let i = 0; i < this._maxRetries; i++) {
|
|
3614
|
-
await this._wait();
|
|
3615
|
-
const current = await this._getCurrentApp(sessionId);
|
|
3616
|
-
lastSeen = current;
|
|
3617
|
-
if (current === expectedAppName) {
|
|
3618
|
-
return;
|
|
3619
|
-
}
|
|
3620
|
-
}
|
|
3621
|
-
debugLog(
|
|
3622
|
-
"[AppManager] waitForApp exhausted: expected=",
|
|
3623
|
-
expectedAppName,
|
|
3624
|
-
"lastSeen=",
|
|
3625
|
-
lastSeen
|
|
3626
|
-
);
|
|
3627
|
-
throw new Error(
|
|
3628
|
-
`Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
|
|
4566
|
+
/** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
|
|
4567
|
+
async getShieldedAddress(derivationPath, options) {
|
|
4568
|
+
const action = this._sdk.getShieldedAddress(derivationPath, options);
|
|
4569
|
+
return deviceActionToPromise(
|
|
4570
|
+
action,
|
|
4571
|
+
this.onInteraction,
|
|
4572
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
4573
|
+
this.onRegisterCanceller
|
|
3629
4574
|
);
|
|
3630
4575
|
}
|
|
3631
|
-
_isDashboard(appName) {
|
|
3632
|
-
return appName === DASHBOARD_APP_NAME;
|
|
3633
|
-
}
|
|
3634
|
-
_wait() {
|
|
3635
|
-
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
3636
|
-
}
|
|
3637
4576
|
};
|
|
3638
4577
|
|
|
3639
|
-
// src/connector/chains/
|
|
3640
|
-
function
|
|
3641
|
-
|
|
4578
|
+
// src/connector/chains/zcash.ts
|
|
4579
|
+
async function zcashGetFullViewingKey(ctx, sessionId, params) {
|
|
4580
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4581
|
+
const path = normalizePath(params.path);
|
|
4582
|
+
const mode = params.mode ?? "ufvk";
|
|
4583
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4584
|
+
const result = await signer.getFullViewingKey(path, { mode });
|
|
4585
|
+
if (result.mode === "ufvk") {
|
|
4586
|
+
return { path: params.path, mode, ufvk: result.fullViewingKey };
|
|
4587
|
+
}
|
|
4588
|
+
return { path: params.path, mode, orchardFvk: bytesToHex2(result.fullViewingKey) };
|
|
4589
|
+
});
|
|
3642
4590
|
}
|
|
3643
|
-
async function
|
|
3644
|
-
const
|
|
3645
|
-
|
|
3646
|
-
|
|
3647
|
-
|
|
3648
|
-
|
|
3649
|
-
type: EConnectorInteraction3.ConfirmOpenApp,
|
|
3650
|
-
payload: { sessionId }
|
|
4591
|
+
async function zcashGetShieldedAddress(ctx, sessionId, params) {
|
|
4592
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4593
|
+
const path = normalizePath(params.path);
|
|
4594
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4595
|
+
const result = await signer.getShieldedAddress(path, {
|
|
4596
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
3651
4597
|
});
|
|
3652
|
-
|
|
3653
|
-
|
|
3654
|
-
if (openAppPromptShown) {
|
|
3655
|
-
ctx.emit("ui-event", {
|
|
3656
|
-
type: EConnectorInteraction3.InteractionComplete,
|
|
3657
|
-
payload: { sessionId }
|
|
3658
|
-
});
|
|
3659
|
-
openAppPromptShown = false;
|
|
3660
|
-
}
|
|
3661
|
-
};
|
|
3662
|
-
try {
|
|
3663
|
-
await _ensureAppOpen(ctx, sessionId, appName, onAppOpenPrompt);
|
|
3664
|
-
} catch (err) {
|
|
3665
|
-
debugLog(
|
|
3666
|
-
"[LegacyChainCall] pre-flight ensureAppOpen failed:",
|
|
3667
|
-
appName,
|
|
3668
|
-
err?.message
|
|
3669
|
-
);
|
|
3670
|
-
closeOpenAppUiIfShown();
|
|
3671
|
-
throw ctx.wrapError(err, { defaultAppName: appName });
|
|
3672
|
-
}
|
|
3673
|
-
const runOnce = async () => {
|
|
3674
|
-
let confirmEmitted = false;
|
|
3675
|
-
if (needsConfirmation) {
|
|
3676
|
-
ctx.emit("ui-event", {
|
|
3677
|
-
type: EConnectorInteraction3.ConfirmOnDevice,
|
|
3678
|
-
payload: { sessionId }
|
|
3679
|
-
});
|
|
3680
|
-
confirmEmitted = true;
|
|
3681
|
-
}
|
|
3682
|
-
try {
|
|
3683
|
-
return await action(sessionId);
|
|
3684
|
-
} finally {
|
|
3685
|
-
if (confirmEmitted || openAppPromptShown) {
|
|
3686
|
-
ctx.emit("ui-event", {
|
|
3687
|
-
type: EConnectorInteraction3.InteractionComplete,
|
|
3688
|
-
payload: { sessionId }
|
|
3689
|
-
});
|
|
3690
|
-
openAppPromptShown = false;
|
|
3691
|
-
}
|
|
3692
|
-
}
|
|
3693
|
-
};
|
|
3694
|
-
try {
|
|
3695
|
-
return await runOnce();
|
|
3696
|
-
} catch (err) {
|
|
3697
|
-
if (!isLegacyWrongAppError(err, appName)) {
|
|
3698
|
-
debugLog("[LegacyChainCall] non-wrong-app failure:", appName, err?.message);
|
|
3699
|
-
ctx.invalidateSession(sessionId);
|
|
3700
|
-
throw ctx.wrapError(err, { defaultAppName: appName });
|
|
3701
|
-
}
|
|
3702
|
-
debugLog("[LegacyChainCall] wrong-app detected, retrying:", appName);
|
|
3703
|
-
try {
|
|
3704
|
-
await _ensureAppOpen(ctx, sessionId, appName, onAppOpenPrompt);
|
|
3705
|
-
} catch (switchErr) {
|
|
3706
|
-
debugLog(
|
|
3707
|
-
"[LegacyChainCall] retry ensureAppOpen failed:",
|
|
3708
|
-
appName,
|
|
3709
|
-
switchErr?.message
|
|
3710
|
-
);
|
|
3711
|
-
closeOpenAppUiIfShown();
|
|
3712
|
-
throw ctx.wrapError(switchErr, { defaultAppName: appName });
|
|
3713
|
-
}
|
|
3714
|
-
ctx.clearAllSigners();
|
|
3715
|
-
const result = await runOnce();
|
|
3716
|
-
debugLog("[LegacyChainCall] retry succeeded:", appName);
|
|
3717
|
-
return result;
|
|
3718
|
-
}
|
|
4598
|
+
return { address: result.address, path: params.path };
|
|
4599
|
+
});
|
|
3719
4600
|
}
|
|
3720
|
-
async function
|
|
4601
|
+
async function _createZcashSigner(ctx, sessionId) {
|
|
3721
4602
|
const dmk = await ctx.getOrCreateDmk();
|
|
3722
|
-
const
|
|
3723
|
-
|
|
4603
|
+
const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
|
|
4604
|
+
const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
|
|
4605
|
+
return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
|
|
3724
4606
|
}
|
|
3725
4607
|
|
|
3726
|
-
// src/
|
|
3727
|
-
import
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
|
|
3731
|
-
|
|
3732
|
-
|
|
4608
|
+
// src/connector/chains/tron.ts
|
|
4609
|
+
import { HardwareErrorCode as HardwareErrorCode6, bytesToHex as bytesToHex3, hexToBytes as hexToBytes4 } from "@onekeyfe/hwk-adapter-core";
|
|
4610
|
+
|
|
4611
|
+
// src/signer/SignerTron.ts
|
|
4612
|
+
var SignerTron = class {
|
|
4613
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4614
|
+
constructor(_sdk) {
|
|
4615
|
+
this._sdk = _sdk;
|
|
4616
|
+
}
|
|
4617
|
+
/** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
|
|
4618
|
+
async getAddress(derivationPath, options) {
|
|
4619
|
+
const action = this._sdk.getAddress(derivationPath, options);
|
|
4620
|
+
const result = await deviceActionToPromise(
|
|
4621
|
+
action,
|
|
4622
|
+
this.onInteraction,
|
|
4623
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
4624
|
+
this.onRegisterCanceller
|
|
4625
|
+
);
|
|
4626
|
+
return { address: result.address, publicKey: result.publicKey };
|
|
3733
4627
|
}
|
|
3734
|
-
|
|
3735
|
-
|
|
3736
|
-
|
|
3737
|
-
|
|
3738
|
-
|
|
3739
|
-
|
|
3740
|
-
|
|
3741
|
-
|
|
3742
|
-
|
|
3743
|
-
}
|
|
3744
|
-
result.set(statusCode, data.length);
|
|
3745
|
-
return result;
|
|
4628
|
+
/** Sign a protobuf-encoded raw transaction. */
|
|
4629
|
+
async signTransaction(derivationPath, transaction, options) {
|
|
4630
|
+
const action = this._sdk.signTransaction(derivationPath, transaction, options);
|
|
4631
|
+
return deviceActionToPromise(
|
|
4632
|
+
action,
|
|
4633
|
+
this.onInteraction,
|
|
4634
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
4635
|
+
this.onRegisterCanceller
|
|
4636
|
+
);
|
|
3746
4637
|
}
|
|
3747
|
-
|
|
4638
|
+
/** Sign a personal message (TIP-191). */
|
|
4639
|
+
async signPersonalMessage(derivationPath, message, options) {
|
|
4640
|
+
const action = this._sdk.signPersonalMessage(derivationPath, message, options);
|
|
4641
|
+
return deviceActionToPromise(
|
|
4642
|
+
action,
|
|
4643
|
+
this.onInteraction,
|
|
4644
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
4645
|
+
this.onRegisterCanceller
|
|
4646
|
+
);
|
|
3748
4647
|
}
|
|
3749
4648
|
};
|
|
3750
4649
|
|
|
3751
4650
|
// src/connector/chains/tron.ts
|
|
3752
4651
|
async function tronGetAddress(ctx, sessionId, params) {
|
|
4652
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3753
4653
|
const path = normalizePath(params.path);
|
|
3754
|
-
|
|
3755
|
-
|
|
3756
|
-
|
|
3757
|
-
|
|
3758
|
-
{
|
|
3759
|
-
|
|
3760
|
-
// Only show "confirm on device" UI when the device is actually going
|
|
3761
|
-
// to display the address for the user to verify.
|
|
3762
|
-
needsConfirmation: showOnDevice
|
|
3763
|
-
},
|
|
3764
|
-
async (sid) => {
|
|
3765
|
-
const trx = await _createTrx(ctx, sid);
|
|
3766
|
-
const result = await trx.getAddress(path, showOnDevice);
|
|
3767
|
-
return { address: result.address, publicKey: result.publicKey, path: params.path };
|
|
3768
|
-
}
|
|
3769
|
-
);
|
|
4654
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4655
|
+
const result = await tronSigner.getAddress(path, {
|
|
4656
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
4657
|
+
});
|
|
4658
|
+
return { address: result.address, publicKey: result.publicKey, path: params.path };
|
|
4659
|
+
});
|
|
3770
4660
|
}
|
|
3771
4661
|
async function tronSignTransaction(ctx, sessionId, params) {
|
|
3772
4662
|
if (!params.rawTxHex) {
|
|
3773
4663
|
throw Object.assign(
|
|
3774
4664
|
new Error("TRON signing requires a protobuf-encoded raw transaction hex (rawTxHex)."),
|
|
3775
|
-
{ code:
|
|
4665
|
+
{ code: HardwareErrorCode6.InvalidParams }
|
|
3776
4666
|
);
|
|
3777
4667
|
}
|
|
4668
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3778
4669
|
const path = normalizePath(params.path);
|
|
3779
|
-
return
|
|
3780
|
-
|
|
3781
|
-
|
|
3782
|
-
|
|
3783
|
-
async (sid) => {
|
|
3784
|
-
const trx = await _createTrx(ctx, sid);
|
|
3785
|
-
const signature = await trx.signTransaction(
|
|
3786
|
-
path,
|
|
3787
|
-
params.rawTxHex,
|
|
3788
|
-
params.tokenSignatures ?? []
|
|
3789
|
-
);
|
|
3790
|
-
return { signature };
|
|
3791
|
-
}
|
|
3792
|
-
);
|
|
4670
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4671
|
+
const signature = await tronSigner.signTransaction(path, hexToBytes4(params.rawTxHex));
|
|
4672
|
+
return { signature: bytesToHex3(signature) };
|
|
4673
|
+
});
|
|
3793
4674
|
}
|
|
3794
4675
|
async function tronSignMessage(ctx, sessionId, params) {
|
|
4676
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3795
4677
|
const path = normalizePath(params.path);
|
|
3796
|
-
return
|
|
3797
|
-
|
|
3798
|
-
|
|
3799
|
-
|
|
3800
|
-
async (sid) => {
|
|
3801
|
-
const trx = await _createTrx(ctx, sid);
|
|
3802
|
-
const signature = await trx.signPersonalMessage(path, params.messageHex);
|
|
3803
|
-
return { signature };
|
|
3804
|
-
}
|
|
3805
|
-
);
|
|
4678
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4679
|
+
const signature = await tronSigner.signPersonalMessage(path, hexToBytes4(params.messageHex));
|
|
4680
|
+
return { signature: bytesToHex3(signature) };
|
|
4681
|
+
});
|
|
3806
4682
|
}
|
|
3807
|
-
async function
|
|
4683
|
+
async function _createTronSigner(ctx, sessionId) {
|
|
3808
4684
|
const dmk = await ctx.getOrCreateDmk();
|
|
3809
|
-
|
|
4685
|
+
const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
|
|
4686
|
+
const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
|
|
4687
|
+
return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
|
|
3810
4688
|
}
|
|
3811
4689
|
|
|
3812
4690
|
// src/device-apps/customActions.ts
|
|
@@ -3985,7 +4863,7 @@ var DeviceApps = class {
|
|
|
3985
4863
|
seTargetId: v.seTargetId,
|
|
3986
4864
|
mcuTargetId: v.mcuTargetId,
|
|
3987
4865
|
seVersion: v.seVersion,
|
|
3988
|
-
seFlagsHex:
|
|
4866
|
+
seFlagsHex: bytesToHex4(v.seFlags),
|
|
3989
4867
|
mcuSephVersion: v.mcuSephVersion,
|
|
3990
4868
|
mcuBootloaderVersion: v.mcuBootloaderVersion,
|
|
3991
4869
|
hwVersion: v.hwVersion
|
|
@@ -4059,7 +4937,7 @@ var DeviceApps = class {
|
|
|
4059
4937
|
}
|
|
4060
4938
|
}
|
|
4061
4939
|
};
|
|
4062
|
-
function
|
|
4940
|
+
function bytesToHex4(bytes) {
|
|
4063
4941
|
if (!bytes) return "";
|
|
4064
4942
|
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
4065
4943
|
}
|
|
@@ -4102,10 +4980,19 @@ var METHOD_PREFIX_TO_APP_NAME = {
|
|
|
4102
4980
|
evm: "Ethereum",
|
|
4103
4981
|
btc: "Bitcoin",
|
|
4104
4982
|
sol: "Solana",
|
|
4105
|
-
tron: "Tron"
|
|
4983
|
+
tron: "Tron",
|
|
4984
|
+
zcash: "Zcash"
|
|
4106
4985
|
};
|
|
4986
|
+
function withOpenAppName(event, data, appName) {
|
|
4987
|
+
if (event !== "ui-event") return data;
|
|
4988
|
+
const uiEvent = data;
|
|
4989
|
+
if (uiEvent.type !== EConnectorInteraction3.ConfirmOpenApp || uiEvent.payload.appName) {
|
|
4990
|
+
return data;
|
|
4991
|
+
}
|
|
4992
|
+
return { ...uiEvent, payload: { ...uiEvent.payload, appName } };
|
|
4993
|
+
}
|
|
4107
4994
|
var HARDWARE_ERROR_CODE_VALUES = new Set(
|
|
4108
|
-
Object.values(
|
|
4995
|
+
Object.values(HardwareErrorCode7).filter((value) => typeof value === "number")
|
|
4109
4996
|
);
|
|
4110
4997
|
var BLE_CONNECT_SCAN_TIMEOUT_MS = 1500;
|
|
4111
4998
|
var LEDGER_RELAY_ALLOWED_ROOT_DOMAINS = ["onekeytest.com", "onekey.com"];
|
|
@@ -4142,6 +5029,10 @@ async function defaultLedgerKitImporter(pkg) {
|
|
|
4142
5029
|
return import("@ledgerhq/device-signer-kit-bitcoin");
|
|
4143
5030
|
case "@ledgerhq/device-signer-kit-solana":
|
|
4144
5031
|
return import("@ledgerhq/device-signer-kit-solana");
|
|
5032
|
+
case "@ledgerhq/device-signer-kit-tron":
|
|
5033
|
+
return import("@ledgerhq/device-signer-kit-tron");
|
|
5034
|
+
case "@ledgerhq/device-signer-kit-zcash":
|
|
5035
|
+
return import("@ledgerhq/device-signer-kit-zcash");
|
|
4145
5036
|
case "@ledgerhq/context-module":
|
|
4146
5037
|
return import("@ledgerhq/context-module");
|
|
4147
5038
|
default:
|
|
@@ -4201,6 +5092,7 @@ var LedgerConnectorBase = class {
|
|
|
4201
5092
|
this._ctx = {
|
|
4202
5093
|
emit: (event, data) => this._emit(event, data),
|
|
4203
5094
|
invalidateSession: (sid) => this._invalidateSession(sid),
|
|
5095
|
+
teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
|
|
4204
5096
|
wrapError: (err, opts) => this._wrapError(err, opts),
|
|
4205
5097
|
getOrCreateDmk: () => this._getOrCreateDmk(),
|
|
4206
5098
|
getDeviceManager: () => this._getDeviceManager(),
|
|
@@ -4300,7 +5192,7 @@ var LedgerConnectorBase = class {
|
|
|
4300
5192
|
`Ledger BLE connect did not return within ${HANG_CEILING_MS / 6e4}min \u2014 DMK hang fallback.`
|
|
4301
5193
|
);
|
|
4302
5194
|
err._tag = ERROR_TAG.BlePairingTimeout;
|
|
4303
|
-
err.code =
|
|
5195
|
+
err.code = HardwareErrorCode7.BlePairingTimeout;
|
|
4304
5196
|
reject(err);
|
|
4305
5197
|
}, HANG_CEILING_MS);
|
|
4306
5198
|
});
|
|
@@ -4333,7 +5225,7 @@ var LedgerConnectorBase = class {
|
|
|
4333
5225
|
"Ledger device is not currently advertising. Wake up and unlock the device, keep it nearby, then try again."
|
|
4334
5226
|
);
|
|
4335
5227
|
err._tag = ERROR_TAG.DeviceNotAdvertising;
|
|
4336
|
-
err.code =
|
|
5228
|
+
err.code = HardwareErrorCode7.DeviceNotFound;
|
|
4337
5229
|
throw err;
|
|
4338
5230
|
};
|
|
4339
5231
|
const doConnect = async (path) => {
|
|
@@ -4389,15 +5281,22 @@ var LedgerConnectorBase = class {
|
|
|
4389
5281
|
} catch (err) {
|
|
4390
5282
|
this._resetSignersAndSessions();
|
|
4391
5283
|
if (isLedgerBleConnectionType(this.connectionType)) {
|
|
5284
|
+
if (isBleBondInvalidError(err)) {
|
|
5285
|
+
throw createHwkError2({
|
|
5286
|
+
code: HardwareErrorCode7.BleBondInvalid,
|
|
5287
|
+
message: "Ledger Bluetooth pairing is no longer valid. Forget this device in system Bluetooth settings, then reconnect.",
|
|
5288
|
+
_tag: ERROR_TAG.PeerRemovedPairing
|
|
5289
|
+
});
|
|
5290
|
+
}
|
|
4392
5291
|
const tag = err?._tag;
|
|
4393
|
-
if (isKnownConnectionTag(tag)) {
|
|
5292
|
+
if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
|
|
4394
5293
|
throw err;
|
|
4395
5294
|
}
|
|
4396
5295
|
const wrapped = new Error(
|
|
4397
5296
|
"Ledger Bluetooth pairing failed. Make sure the device is unlocked and nearby, then try again."
|
|
4398
5297
|
);
|
|
4399
5298
|
wrapped._tag = ERROR_TAG.BleGattBondingFailed;
|
|
4400
|
-
wrapped.code =
|
|
5299
|
+
wrapped.code = HardwareErrorCode7.BlePairingTimeout;
|
|
4401
5300
|
wrapped.originalError = err;
|
|
4402
5301
|
throw wrapped;
|
|
4403
5302
|
}
|
|
@@ -4475,7 +5374,7 @@ var LedgerConnectorBase = class {
|
|
|
4475
5374
|
this._unwatchSessionState(sessionId);
|
|
4476
5375
|
this._signerManager?.invalidate(sessionId);
|
|
4477
5376
|
this._cancellers.get(sessionId)?.({
|
|
4478
|
-
code:
|
|
5377
|
+
code: HardwareErrorCode7.DeviceDisconnected,
|
|
4479
5378
|
tag: "DeviceDisconnected",
|
|
4480
5379
|
message: "Device disconnected"
|
|
4481
5380
|
});
|
|
@@ -4491,7 +5390,7 @@ var LedgerConnectorBase = class {
|
|
|
4491
5390
|
// whitelist (`toPlainError`). The SW-side adapter rehydrates and re-throws
|
|
4492
5391
|
// locally (see LedgerAdapter._unwrapConnectorResult).
|
|
4493
5392
|
async call(sessionId, method, params) {
|
|
4494
|
-
debugLog("[DMK] call:", method, JSON.stringify(params));
|
|
5393
|
+
debugLog("[DMK] call:", method, JSON.stringify(summarizeForLog(params, { method })));
|
|
4495
5394
|
try {
|
|
4496
5395
|
const payload = await this._dispatch(sessionId, method, params);
|
|
4497
5396
|
return { success: true, payload };
|
|
@@ -4501,7 +5400,7 @@ var LedgerConnectorBase = class {
|
|
|
4501
5400
|
success: false,
|
|
4502
5401
|
error: serializeConnectorError(
|
|
4503
5402
|
Object.assign(new Error("Ledger app is unresponsive"), {
|
|
4504
|
-
code:
|
|
5403
|
+
code: HardwareErrorCode7.DeviceAppStuck,
|
|
4505
5404
|
_tag: ERROR_TAG.DeviceAppStuck,
|
|
4506
5405
|
originalError: err
|
|
4507
5406
|
})
|
|
@@ -4513,7 +5412,7 @@ var LedgerConnectorBase = class {
|
|
|
4513
5412
|
success: false,
|
|
4514
5413
|
error: serializeConnectorError(
|
|
4515
5414
|
Object.assign(new Error("Device communication interrupted, please retry"), {
|
|
4516
|
-
code:
|
|
5415
|
+
code: HardwareErrorCode7.TransportError,
|
|
4517
5416
|
_tag: ERROR_TAG.DeviceTransportStuck,
|
|
4518
5417
|
originalError: err
|
|
4519
5418
|
})
|
|
@@ -4559,6 +5458,11 @@ var LedgerConnectorBase = class {
|
|
|
4559
5458
|
return solSignTransaction(ctx, sessionId, params);
|
|
4560
5459
|
case "solSignMessage":
|
|
4561
5460
|
return solSignMessage(ctx, sessionId, params);
|
|
5461
|
+
// ZCASH
|
|
5462
|
+
case "zcashGetFullViewingKey":
|
|
5463
|
+
return zcashGetFullViewingKey(ctx, sessionId, params);
|
|
5464
|
+
case "zcashGetShieldedAddress":
|
|
5465
|
+
return zcashGetShieldedAddress(ctx, sessionId, params);
|
|
4562
5466
|
// TRON
|
|
4563
5467
|
case "tronGetAddress":
|
|
4564
5468
|
return tronGetAddress(ctx, sessionId, params);
|
|
@@ -4583,7 +5487,7 @@ var LedgerConnectorBase = class {
|
|
|
4583
5487
|
try {
|
|
4584
5488
|
return await apps.install(p.appName, ({ progress }) => {
|
|
4585
5489
|
ctx.emit("ui-event", {
|
|
4586
|
-
type:
|
|
5490
|
+
type: EConnectorInteraction3.AppInstallProgress,
|
|
4587
5491
|
payload: {
|
|
4588
5492
|
sessionId,
|
|
4589
5493
|
appName: p.appName,
|
|
@@ -4592,7 +5496,7 @@ var LedgerConnectorBase = class {
|
|
|
4592
5496
|
});
|
|
4593
5497
|
});
|
|
4594
5498
|
} catch (err) {
|
|
4595
|
-
ctx.
|
|
5499
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4596
5500
|
throw ctx.wrapError(err);
|
|
4597
5501
|
} finally {
|
|
4598
5502
|
ctx.clearCanceller(sessionId);
|
|
@@ -4682,7 +5586,7 @@ var LedgerConnectorBase = class {
|
|
|
4682
5586
|
);
|
|
4683
5587
|
return { isGenuine: output.isGenuine, deviceId };
|
|
4684
5588
|
} catch (err) {
|
|
4685
|
-
ctx.
|
|
5589
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4686
5590
|
throw ctx.wrapError(err);
|
|
4687
5591
|
} finally {
|
|
4688
5592
|
ctx.clearCanceller(sessionId);
|
|
@@ -4804,6 +5708,17 @@ var LedgerConnectorBase = class {
|
|
|
4804
5708
|
_invalidateSession(sessionId) {
|
|
4805
5709
|
this._signerManager?.invalidate(sessionId);
|
|
4806
5710
|
}
|
|
5711
|
+
_teardownSecureChannelSession(sessionId) {
|
|
5712
|
+
const cancel = this._cancellers.get(sessionId);
|
|
5713
|
+
this._cancellers.delete(sessionId);
|
|
5714
|
+
if (cancel) {
|
|
5715
|
+
try {
|
|
5716
|
+
cancel();
|
|
5717
|
+
} catch {
|
|
5718
|
+
}
|
|
5719
|
+
}
|
|
5720
|
+
this._invalidateSession(sessionId);
|
|
5721
|
+
}
|
|
4807
5722
|
/**
|
|
4808
5723
|
* Replace an old session with a new one after app switch.
|
|
4809
5724
|
* Emits device-connect so the adapter updates its _sessions Map.
|
|
@@ -4884,16 +5799,17 @@ var LedgerConnectorBase = class {
|
|
|
4884
5799
|
// ---------------------------------------------------------------------------
|
|
4885
5800
|
/**
|
|
4886
5801
|
* Return a per-call ctx with the chain's Ledger app name pre-bound to
|
|
4887
|
-
* wrapError, so chain handlers don't need to repeat
|
|
4888
|
-
*
|
|
5802
|
+
* UI prompts and wrapError, so chain handlers don't need to repeat the name.
|
|
5803
|
+
* Falls through unchanged for unknown methods.
|
|
4889
5804
|
*/
|
|
4890
5805
|
_ctxForMethod(method) {
|
|
4891
|
-
const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
|
|
5806
|
+
const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
|
|
4892
5807
|
const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
|
|
4893
5808
|
if (!defaultAppName) return this._ctx;
|
|
4894
5809
|
return {
|
|
4895
5810
|
...this._ctx,
|
|
4896
|
-
wrapError: (err, opts) => this._wrapError(err, { defaultAppName, ...opts })
|
|
5811
|
+
wrapError: (err, opts) => this._wrapError(err, { defaultAppName, ...opts }),
|
|
5812
|
+
emit: (event, data) => this._ctx.emit(event, withOpenAppName(event, data, defaultAppName))
|
|
4897
5813
|
};
|
|
4898
5814
|
}
|
|
4899
5815
|
_wrapError(err, opts) {
|
|
@@ -4922,6 +5838,209 @@ var LedgerConnectorBase = class {
|
|
|
4922
5838
|
return error;
|
|
4923
5839
|
}
|
|
4924
5840
|
};
|
|
5841
|
+
|
|
5842
|
+
// src/transport/DmkTransport.ts
|
|
5843
|
+
import Transport from "@ledgerhq/hw-transport";
|
|
5844
|
+
var DmkTransport = class extends Transport {
|
|
5845
|
+
constructor(dmk, sessionId) {
|
|
5846
|
+
super();
|
|
5847
|
+
this._dmk = dmk;
|
|
5848
|
+
this._sessionId = sessionId;
|
|
5849
|
+
}
|
|
5850
|
+
async exchange(apdu) {
|
|
5851
|
+
const response = await this._dmk.sendApdu({
|
|
5852
|
+
sessionId: this._sessionId,
|
|
5853
|
+
apdu: new Uint8Array(apdu)
|
|
5854
|
+
});
|
|
5855
|
+
const { data, statusCode } = response;
|
|
5856
|
+
const result = Buffer.alloc(data.length + 2);
|
|
5857
|
+
if (data.length > 0) {
|
|
5858
|
+
result.set(data, 0);
|
|
5859
|
+
}
|
|
5860
|
+
result.set(statusCode, data.length);
|
|
5861
|
+
return result;
|
|
5862
|
+
}
|
|
5863
|
+
async close() {
|
|
5864
|
+
}
|
|
5865
|
+
};
|
|
5866
|
+
|
|
5867
|
+
// src/app/AppManager.ts
|
|
5868
|
+
import {
|
|
5869
|
+
CloseAppCommand,
|
|
5870
|
+
GetAppAndVersionCommand,
|
|
5871
|
+
OpenAppCommand,
|
|
5872
|
+
isSuccessCommandResult
|
|
5873
|
+
} from "@ledgerhq/device-management-kit";
|
|
5874
|
+
import { HardwareErrorCode as HardwareErrorCode8 } from "@onekeyfe/hwk-adapter-core";
|
|
5875
|
+
var APP_NAME_MAP = {
|
|
5876
|
+
ETH: "Ethereum",
|
|
5877
|
+
BTC: "Bitcoin",
|
|
5878
|
+
SOL: "Solana",
|
|
5879
|
+
TRX: "Tron",
|
|
5880
|
+
ZEC: "Zcash",
|
|
5881
|
+
XRP: "XRP",
|
|
5882
|
+
ADA: "Cardano",
|
|
5883
|
+
DOT: "Polkadot",
|
|
5884
|
+
ATOM: "Cosmos"
|
|
5885
|
+
};
|
|
5886
|
+
var DASHBOARD_APP_NAME = "BOLOS";
|
|
5887
|
+
var AppManager = class {
|
|
5888
|
+
constructor(dmk, options) {
|
|
5889
|
+
this._dmk = dmk;
|
|
5890
|
+
this._waitMs = options?.waitMs ?? 1e3;
|
|
5891
|
+
this._maxRetries = options?.maxRetries ?? 10;
|
|
5892
|
+
}
|
|
5893
|
+
/**
|
|
5894
|
+
* Return the Ledger app name for a given chain ticker,
|
|
5895
|
+
* or undefined if the chain is not supported.
|
|
5896
|
+
*/
|
|
5897
|
+
static getAppName(chain) {
|
|
5898
|
+
return APP_NAME_MAP[chain];
|
|
5899
|
+
}
|
|
5900
|
+
/**
|
|
5901
|
+
* Ensure the target app is open on the device identified by `sessionId`.
|
|
5902
|
+
*
|
|
5903
|
+
* Flow:
|
|
5904
|
+
* 1. Check the currently running app.
|
|
5905
|
+
* 2. If it is already the target, return immediately.
|
|
5906
|
+
* 3. If a different app is running (not dashboard), close it first.
|
|
5907
|
+
* 4. Open the target app.
|
|
5908
|
+
* 5. Poll until the device confirms the target app is running.
|
|
5909
|
+
*/
|
|
5910
|
+
/**
|
|
5911
|
+
* @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
|
|
5912
|
+
* device is about to display "Open <app>" on screen and wait for the
|
|
5913
|
+
* user's button press. UI consumers should show their "open app" prompt
|
|
5914
|
+
* in response. NOT called when the target app is already open (no user
|
|
5915
|
+
* interaction needed in that case).
|
|
5916
|
+
*
|
|
5917
|
+
* Important: OpenAppCommand is blocking. It does not resolve until the user
|
|
5918
|
+
* has physically confirmed on the device, so anything that runs AFTER
|
|
5919
|
+
* `await this._openApp(...)` lands AFTER the prompt is already gone.
|
|
5920
|
+
* Hence the callback must fire BEFORE that await.
|
|
5921
|
+
*/
|
|
5922
|
+
async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
|
|
5923
|
+
const currentApp = await this._getCurrentApp(sessionId);
|
|
5924
|
+
if (currentApp === targetAppName) {
|
|
5925
|
+
return;
|
|
5926
|
+
}
|
|
5927
|
+
if (!this._isDashboard(currentApp)) {
|
|
5928
|
+
await this._closeCurrentApp(sessionId);
|
|
5929
|
+
await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
|
|
5930
|
+
}
|
|
5931
|
+
onConfirmOnDevice?.();
|
|
5932
|
+
await this._openApp(sessionId, targetAppName);
|
|
5933
|
+
await this._waitForApp(sessionId, targetAppName);
|
|
5934
|
+
}
|
|
5935
|
+
// ---------------------------------------------------------------------------
|
|
5936
|
+
// Private helpers
|
|
5937
|
+
// ---------------------------------------------------------------------------
|
|
5938
|
+
async _getCurrentApp(sessionId) {
|
|
5939
|
+
const result = await this._dmk.sendCommand({
|
|
5940
|
+
sessionId,
|
|
5941
|
+
command: new GetAppAndVersionCommand()
|
|
5942
|
+
});
|
|
5943
|
+
if (isSuccessCommandResult(result)) {
|
|
5944
|
+
debugLog("[AppManager] currentApp:", result.data.name);
|
|
5945
|
+
return result.data.name;
|
|
5946
|
+
}
|
|
5947
|
+
const errResult = result;
|
|
5948
|
+
const dmkErr = errResult.error ?? {};
|
|
5949
|
+
const original = dmkErr.originalError;
|
|
5950
|
+
debugLog(
|
|
5951
|
+
"[AppManager] _getCurrentApp failed sessionId=",
|
|
5952
|
+
sessionId,
|
|
5953
|
+
"tag=",
|
|
5954
|
+
dmkErr._tag,
|
|
5955
|
+
"errorCode=",
|
|
5956
|
+
dmkErr.errorCode,
|
|
5957
|
+
"message=",
|
|
5958
|
+
dmkErr.message,
|
|
5959
|
+
"originalErrorMessage=",
|
|
5960
|
+
original?.message ?? String(original ?? "")
|
|
5961
|
+
);
|
|
5962
|
+
throw Object.assign(
|
|
5963
|
+
new Error(
|
|
5964
|
+
dmkErr.message ?? "Failed to get current app from device"
|
|
5965
|
+
),
|
|
5966
|
+
{
|
|
5967
|
+
_tag: dmkErr._tag,
|
|
5968
|
+
errorCode: dmkErr.errorCode,
|
|
5969
|
+
originalError: original
|
|
5970
|
+
}
|
|
5971
|
+
);
|
|
5972
|
+
}
|
|
5973
|
+
async _openApp(sessionId, appName) {
|
|
5974
|
+
const result = await this._dmk.sendCommand({
|
|
5975
|
+
sessionId,
|
|
5976
|
+
command: new OpenAppCommand({ appName })
|
|
5977
|
+
});
|
|
5978
|
+
if (!isSuccessCommandResult(result)) {
|
|
5979
|
+
const dmkErr = result.error;
|
|
5980
|
+
const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
|
|
5981
|
+
const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
|
|
5982
|
+
debugLog(
|
|
5983
|
+
"[AppManager] openApp failed:",
|
|
5984
|
+
appName,
|
|
5985
|
+
"errorCode:",
|
|
5986
|
+
errorCode,
|
|
5987
|
+
"tag:",
|
|
5988
|
+
dmkErr._tag
|
|
5989
|
+
);
|
|
5990
|
+
let code;
|
|
5991
|
+
if (errorCode === "6807" || /unknown application/i.test(message)) {
|
|
5992
|
+
code = HardwareErrorCode8.AppNotInstalled;
|
|
5993
|
+
} else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
|
|
5994
|
+
code = HardwareErrorCode8.UserRejected;
|
|
5995
|
+
}
|
|
5996
|
+
throw Object.assign(new Error(`Failed to open "${appName}"`), {
|
|
5997
|
+
_tag: ERROR_TAG.OpenAppCommand,
|
|
5998
|
+
code,
|
|
5999
|
+
errorCode,
|
|
6000
|
+
statusCode: errorCode,
|
|
6001
|
+
appName,
|
|
6002
|
+
originalError: dmkErr
|
|
6003
|
+
});
|
|
6004
|
+
}
|
|
6005
|
+
}
|
|
6006
|
+
async _closeCurrentApp(sessionId) {
|
|
6007
|
+
debugLog("[AppManager] closeCurrentApp");
|
|
6008
|
+
await this._dmk.sendCommand({
|
|
6009
|
+
sessionId,
|
|
6010
|
+
command: new CloseAppCommand()
|
|
6011
|
+
});
|
|
6012
|
+
}
|
|
6013
|
+
/**
|
|
6014
|
+
* Poll the device until the expected app is reported as running,
|
|
6015
|
+
* or throw after `_maxRetries` attempts.
|
|
6016
|
+
*/
|
|
6017
|
+
async _waitForApp(sessionId, expectedAppName) {
|
|
6018
|
+
let lastSeen = "";
|
|
6019
|
+
for (let i = 0; i < this._maxRetries; i++) {
|
|
6020
|
+
await this._wait();
|
|
6021
|
+
const current = await this._getCurrentApp(sessionId);
|
|
6022
|
+
lastSeen = current;
|
|
6023
|
+
if (current === expectedAppName) {
|
|
6024
|
+
return;
|
|
6025
|
+
}
|
|
6026
|
+
}
|
|
6027
|
+
debugLog(
|
|
6028
|
+
"[AppManager] waitForApp exhausted: expected=",
|
|
6029
|
+
expectedAppName,
|
|
6030
|
+
"lastSeen=",
|
|
6031
|
+
lastSeen
|
|
6032
|
+
);
|
|
6033
|
+
throw new Error(
|
|
6034
|
+
`Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
|
|
6035
|
+
);
|
|
6036
|
+
}
|
|
6037
|
+
_isDashboard(appName) {
|
|
6038
|
+
return appName === DASHBOARD_APP_NAME;
|
|
6039
|
+
}
|
|
6040
|
+
_wait() {
|
|
6041
|
+
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
6042
|
+
}
|
|
6043
|
+
};
|
|
4925
6044
|
export {
|
|
4926
6045
|
AppManager,
|
|
4927
6046
|
DmkTransport,
|
|
@@ -4932,6 +6051,7 @@ export {
|
|
|
4932
6051
|
SignerEth,
|
|
4933
6052
|
SignerManager,
|
|
4934
6053
|
SignerSol,
|
|
6054
|
+
SignerZcash,
|
|
4935
6055
|
debugLog,
|
|
4936
6056
|
deviceActionToPromise,
|
|
4937
6057
|
isDeviceLockedError,
|