@onekeyfe/hwk-keystone-adapter 1.2.6-alpha.0 → 1.2.8-alpha.101

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.js CHANGED
@@ -105,11 +105,12 @@ var TronSignRequest = class _TronSignRequest extends import_bc_ur_registry.Regis
105
105
  static parsePath(path, xfp) {
106
106
  const segments = path.replace(/^[mM]\//, "").split("/");
107
107
  const components = segments.map((segment) => {
108
- const hardened = segment.endsWith("'");
109
- return new import_bc_ur_registry.PathComponent({
110
- index: parseInt(hardened ? segment.slice(0, -1) : segment, 10),
111
- hardened
112
- });
108
+ const match = /^(\d+)('?)$/.exec(segment);
109
+ const index = match ? Number(match[1]) : NaN;
110
+ if (!match || index >= 2147483648) {
111
+ throw new Error(`Invalid TRON derivation path segment (${segment})`);
112
+ }
113
+ return new import_bc_ur_registry.PathComponent({ index, hardened: match[2] === "'" });
113
114
  });
114
115
  return new import_bc_ur_registry.CryptoKeypath(components, Buffer.from(xfp, "hex"));
115
116
  }
@@ -167,7 +168,7 @@ var DERIVATION_CURVE = {
167
168
  ed25519: import_keystone_sdk.Curve.ed25519
168
169
  };
169
170
  function toSdkUr(ur) {
170
- return new import_keystone_sdk.UR(Buffer.from(ur.urData, "hex"), ur.urType);
171
+ return new import_keystone_sdk.UR((0, import_hwk_adapter_core.boundedCborFromHex)(ur.urData), ur.urType);
171
172
  }
172
173
  function fromSdkUr(ur) {
173
174
  return { urType: ur.type, urData: ur.cbor.toString("hex") };
@@ -205,8 +206,24 @@ function toParsedAccount(key) {
205
206
  name: key.name
206
207
  };
207
208
  }
209
+ var BIP32_HARDENED_OFFSET = 2147483648;
208
210
  function relativeHdPath(relativeDerivePath) {
209
- return `m/${relativeDerivePath.replace(/^m\//i, "")}`;
211
+ const segments = relativeDerivePath.replace(/^m\//i, "").split("/");
212
+ const valid = segments.every(
213
+ (segment) => /^\d+$/.test(segment) && Number(segment) < BIP32_HARDENED_OFFSET
214
+ );
215
+ if (!valid) {
216
+ throw (0, import_hwk_adapter_core.createHwkError)({
217
+ code: import_hwk_adapter_core.HardwareErrorCode.InvalidParams,
218
+ message: `Invalid change/index segments in derivation path (${relativeDerivePath})`
219
+ });
220
+ }
221
+ return `m/${segments.join("/")}`;
222
+ }
223
+ var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.]{1,20})?$/;
224
+ var DEVICE_TEXT = /^[^\p{Cc}\p{Cf}]{1,64}$/u;
225
+ function deviceText(value, pattern) {
226
+ return typeof value === "string" && pattern.test(value) ? value : void 0;
210
227
  }
211
228
  var KeystoneUrEngine = class {
212
229
  constructor(origin = "OneKey") {
@@ -217,9 +234,9 @@ var KeystoneUrEngine = class {
217
234
  const parsed = this.sdk.parseMultiAccounts(toSdkUr(ur));
218
235
  return {
219
236
  masterFingerprint: requireBip32MasterFingerprint(parsed.masterFingerprint),
220
- device: parsed.device,
221
- deviceId: parsed.deviceId,
222
- deviceVersion: parsed.deviceVersion,
237
+ device: deviceText(parsed.device, DEVICE_TEXT),
238
+ deviceId: deviceText(parsed.deviceId, DEVICE_TEXT),
239
+ deviceVersion: deviceText(parsed.deviceVersion, FIRMWARE_VERSION),
223
240
  accounts: parsed.keys.map(toParsedAccount)
224
241
  };
225
242
  }
@@ -281,10 +298,7 @@ var KeystoneUrEngine = class {
281
298
  return (0, import_bc_ur_registry_eth.generateAddressFromXpub)(xpub, relativeHdPath(relativeDerivePath));
282
299
  }
283
300
  // --- BTC (PSBT transaction signing + plain message signing) ---
284
- /**
285
- * `CryptoHDKey` always emits mainnet xpub version bytes (`0488B21E`), so `hdkey` parses it as is.
286
- * `p2tr` needs an ECC lib for BIP-341 tweaking, not wired here.
287
- */
301
+ /** `CryptoHDKey` always emits mainnet xpub version bytes (`0488B21E`), so `hdkey` parses it as is. */
288
302
  deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType) {
289
303
  const node = import_hdkey.default.fromExtendedKey(xpub).derive(relativeHdPath(relativeDerivePath));
290
304
  if (!node.publicKey) throw new Error("HDKey derivation did not produce a public key");
@@ -330,9 +344,27 @@ var KeystoneUrEngine = class {
330
344
  const ur = this.sdk.btc.generatePSBT(Buffer.from(unsignedPsbtHex, "hex"));
331
345
  return fromSdkUr(ur);
332
346
  }
333
- /** Returns the hex-encoded (possibly still-unsigned-in-part) PSBT the device replied with. */
334
- parseBtcPsbt(ur) {
335
- return this.sdk.btc.parsePSBT(toSdkUr(ur));
347
+ /**
348
+ * Returns the hex-encoded (possibly still-unsigned-in-part) PSBT the device replied with. A PSBT
349
+ * carries no request id, so the reply is bound to the request by its unsigned transaction, which
350
+ * signing never changes (BIP-174); a scan of another PSBT's signature is refused.
351
+ */
352
+ parseBtcPsbt(ur, requestPsbtHex) {
353
+ const signedPsbtHex = this.sdk.btc.parsePSBT(toSdkUr(ur));
354
+ let sameTransaction = false;
355
+ try {
356
+ const unsignedTx = (hex) => Buffer.from(bitcoin.Psbt.fromHex(hex).data.globalMap.unsignedTx.toBuffer());
357
+ sameTransaction = unsignedTx(signedPsbtHex).equals(unsignedTx(requestPsbtHex));
358
+ } catch {
359
+ sameTransaction = false;
360
+ }
361
+ if (!sameTransaction) {
362
+ throw (0, import_hwk_adapter_core.createHwkError)({
363
+ code: import_hwk_adapter_core.HardwareErrorCode.DeviceMismatch,
364
+ message: "Keystone returned a PSBT for another transaction than the one requested"
365
+ });
366
+ }
367
+ return signedPsbtHex;
336
368
  }
337
369
  buildBtcMessageSignRequest(params) {
338
370
  const ur = this.sdk.btc.generateSignRequest({
@@ -392,7 +424,7 @@ var KeystoneUrEngine = class {
392
424
  if (ur.urType !== "tron-signature") {
393
425
  throw new Error(`Expected a tron-signature UR, got ${ur.urType}`);
394
426
  }
395
- const signature = TronSignature.fromCBOR(Buffer.from(ur.urData, "hex"));
427
+ const signature = TronSignature.fromCBOR((0, import_hwk_adapter_core.boundedCborFromHex)(ur.urData));
396
428
  const requestId = signature.getRequestId();
397
429
  return {
398
430
  requestId: requestId ? (0, import_uuid.stringify)(requestId) : void 0,
@@ -436,14 +468,26 @@ function normalizePath(path) {
436
468
  const trimmed = path.trim();
437
469
  return /^m\//i.test(trimmed) ? `m/${trimmed.slice(2)}` : `m/${trimmed}`;
438
470
  }
471
+ var BIP32_HARDENED_OFFSET2 = 2147483648;
472
+ function isBip32Path(path) {
473
+ const segments = normalizePath(path).slice(2).split("/");
474
+ return segments.every((segment) => {
475
+ const match = /^(\d+)'?$/.exec(segment);
476
+ return match !== null && Number(match[1]) < BIP32_HARDENED_OFFSET2;
477
+ });
478
+ }
439
479
  function splitAccountPath(path) {
440
480
  const normalized = normalizePath(path);
441
481
  const segments = normalized.slice(2).split("/");
442
- if (segments.length <= 3) {
482
+ let accountLength = 0;
483
+ segments.forEach((segment, index) => {
484
+ if (segment.endsWith("'")) accountLength = index + 1;
485
+ });
486
+ if (segments.length <= 3 || accountLength === 0 || accountLength === segments.length) {
443
487
  return { accountPath: normalized, relativeDerivePath: "" };
444
488
  }
445
- const accountSegments = segments.slice(0, segments.length - 2);
446
- const relativeSegments = segments.slice(segments.length - 2);
489
+ const accountSegments = segments.slice(0, accountLength);
490
+ const relativeSegments = segments.slice(accountLength);
447
491
  return {
448
492
  accountPath: `m/${accountSegments.join("/")}`,
449
493
  relativeDerivePath: relativeSegments.join("/")
@@ -546,11 +590,24 @@ function keystoneCancelQueueKeys(identifiers) {
546
590
  }
547
591
 
548
592
  // src/adapter/KeystoneAdapter.ts
593
+ function keystoneBtcParamsFailure(params) {
594
+ const { coin, addressIndex, change } = params;
595
+ if (coin !== void 0 && !["btc", "bitcoin"].includes(String(coin).toLowerCase())) {
596
+ return (0, import_hwk_adapter_core3.failure)(
597
+ import_hwk_adapter_core3.HardwareErrorCode.ChainNotSupported,
598
+ `Keystone BTC supports Bitcoin mainnet only, not ${String(coin)}`
599
+ );
600
+ }
601
+ if (addressIndex !== void 0 || change !== void 0) {
602
+ return (0, import_hwk_adapter_core3.failure)(
603
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
604
+ "Keystone BTC takes the full address path; addressIndex and change are not supported"
605
+ );
606
+ }
607
+ return void 0;
608
+ }
549
609
  var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
550
610
  var KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS = 500;
551
- function resolveHardwareOperationTarget(positionalTargetId, operationId) {
552
- return (0, import_hwk_adapter_core3.resolveHardwareOperationTarget)(positionalTargetId, operationId, "keystone");
553
- }
554
611
  function keySchema(chain, path) {
555
612
  return { path, curve: chain === "sol" ? "ed25519" : "secp256k1" };
556
613
  }
@@ -559,21 +616,52 @@ function waitForKeystoneUsbReattachProbe() {
559
616
  setTimeout(resolve, KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS);
560
617
  });
561
618
  }
562
- function buildCancelledFailure(signal) {
563
- const reason = signal.reason;
564
- const code = typeof reason?.code === "number" ? reason.code : import_hwk_adapter_core3.HardwareErrorCode.UserAborted;
565
- const message = typeof reason?.message === "string" ? reason.message : "";
566
- return (0, import_hwk_adapter_core3.failure)(code, message || "All-network get-address cancelled");
567
- }
568
619
  var BIP44_COIN_TYPE_TO_CHAIN = {
569
620
  60: "evm",
570
621
  0: "btc",
571
622
  501: "sol",
572
623
  195: "tron"
573
624
  };
574
- function inferHwkChainFromPath(path) {
625
+ function hasChainCoinType(chain, path) {
575
626
  const match = normalizePath(path).match(/^m\/\d+'\/(\d+)'/);
576
- return match ? BIP44_COIN_TYPE_TO_CHAIN[Number(match[1])] : void 0;
627
+ return Boolean(match) && BIP44_COIN_TYPE_TO_CHAIN[Number(match?.[1])] === chain;
628
+ }
629
+ function exactHex(value) {
630
+ const hex = value.replace(/^0x/i, "");
631
+ return /^(?:[0-9a-f]{2})*$/i.test(hex) ? hex : void 0;
632
+ }
633
+ function invalidHexFailure(field) {
634
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${field} must be an even-length hex string`);
635
+ }
636
+ function requireExportedPath(parsed, path) {
637
+ const account = parsed.accounts.find((returned) => normalizePath(returned.path) === path);
638
+ if (!account) {
639
+ throw (0, import_hwk_adapter_core3.createHwkError)({
640
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
641
+ message: `Keystone did not return the requested derivation path (${path})`
642
+ });
643
+ }
644
+ return account;
645
+ }
646
+ function coinTypeFailure(chain, path) {
647
+ if (hasChainCoinType(chain, path)) return void 0;
648
+ return (0, import_hwk_adapter_core3.failure)(
649
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
650
+ `Keystone ${chain} needs a path with its own BIP44 coin type, not ${path}`
651
+ );
652
+ }
653
+ function btcAccountFailure(accountPath) {
654
+ if (isKeystoneSignableBtcAccountPath(accountPath)) return void 0;
655
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
656
+ }
657
+ function missingParamFailure(method, param) {
658
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${method} requires ${param}`);
659
+ }
660
+ function messageToHex(message, hex) {
661
+ return hex ? exactHex(message) : Buffer.from(message, "utf8").toString("hex");
662
+ }
663
+ function evmMessageSignature(sig) {
664
+ return { signature: (0, import_hwk_adapter_core3.ensure0x)(sig.r + sig.s + sig.v) };
577
665
  }
578
666
  var KeystoneAdapter = class _KeystoneAdapter {
579
667
  constructor(options) {
@@ -589,6 +677,19 @@ var KeystoneAdapter = class _KeystoneAdapter {
589
677
  const route = this._operationRoutes.get(operation.connectId);
590
678
  if (route?.operationId === operation.operationId) {
591
679
  this._operationRoutes.delete(operation.connectId);
680
+ if (route.connectionType === "qr") {
681
+ const ended = (0, import_hwk_adapter_core3.createHwkError)({
682
+ code: import_hwk_adapter_core3.HardwareErrorCode.OperationEnded,
683
+ message: "Keystone operation has ended",
684
+ params: { operationId: operation.operationId, reason }
685
+ });
686
+ const queueKey = keystoneQueueKey(operation.operationId);
687
+ const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
688
+ this._jobQueue.cancelActiveAndPending(queueKey, ended);
689
+ if (ownsRunningCall) {
690
+ this._uiRegistry.cancel(void 0, void 0, operation.operationId);
691
+ }
692
+ }
592
693
  }
593
694
  this.emitter.emit(import_hwk_adapter_core3.SDK.OPERATION_ENDED, {
594
695
  type: import_hwk_adapter_core3.SDK.OPERATION_ENDED,
@@ -629,18 +730,30 @@ var KeystoneAdapter = class _KeystoneAdapter {
629
730
  // All-network bundle, dispatched to the per-chain methods below.
630
731
  // ---------------------------------------------------------------------------
631
732
  this.allNetworkGetAddress = async (connectId, deviceId, params) => {
632
- const operationTarget = resolveHardwareOperationTarget(connectId, params.operationId);
733
+ const operationTarget = this._resolveOperationTarget(connectId, params.operationId);
633
734
  if (!operationTarget.success) return operationTarget;
634
735
  const effectiveConnectId = operationTarget.payload.targetId ?? "";
635
736
  const { operationId } = operationTarget.payload;
737
+ const namedWallets = new Set(
738
+ [deviceId, ...params.bundle.map((item) => item.deviceId)].filter(
739
+ (id) => typeof id === "string" && id.length > 0
740
+ )
741
+ );
742
+ if (namedWallets.size > 1) {
743
+ return (0, import_hwk_adapter_core3.failure)(
744
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
745
+ "Keystone all-network items name different wallets"
746
+ );
747
+ }
748
+ const [expectedDeviceId = ""] = namedWallets;
636
749
  let cancelScope;
637
750
  try {
638
- const prefetched = await this._prefetchAllNetworkAccounts(effectiveConnectId, deviceId, {
751
+ const prepared = await this._prepareAllNetworkBundle(effectiveConnectId, expectedDeviceId, {
639
752
  ...params,
640
753
  operationId
641
754
  });
642
- const { book } = prefetched;
643
- const itemDeviceId = deviceId || prefetched.masterFingerprint || "";
755
+ const { access } = prepared;
756
+ const itemDeviceId = expectedDeviceId || prepared.masterFingerprint || "";
644
757
  const scope = this._jobQueue.createCancelScope(
645
758
  keystoneQueueKey(effectiveConnectId, itemDeviceId)
646
759
  );
@@ -653,7 +766,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
653
766
  callItem: async ({ method, item, index }) => {
654
767
  if (scope.signal.aborted) {
655
768
  cancelledIndexes.add(index);
656
- return buildCancelledFailure(scope.signal);
769
+ return (0, import_hwk_adapter_core3.buildAllNetworkCancelledFailure)(scope.signal);
657
770
  }
658
771
  const commonArgs = {
659
772
  path: item.path,
@@ -662,20 +775,19 @@ var KeystoneAdapter = class _KeystoneAdapter {
662
775
  };
663
776
  switch (method) {
664
777
  case "evmGetAddress":
665
- return this.evmGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
778
+ return this.evmGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
666
779
  case "btcGetAddress":
667
- return this.btcGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
668
- case "btcGetPublicKey":
669
- return this.btcGetPublicKey(effectiveConnectId, itemDeviceId, commonArgs, book);
780
+ case "btcGetPublicKey": {
781
+ const btcArgs = {
782
+ ...commonArgs,
783
+ coin: item.coin ?? item.network
784
+ };
785
+ return method === "btcGetAddress" ? this.btcGetAddress(effectiveConnectId, itemDeviceId, btcArgs, access) : this.btcGetPublicKey(effectiveConnectId, itemDeviceId, btcArgs, access);
786
+ }
670
787
  case "solGetAddress":
671
- return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
788
+ return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
672
789
  case "tronGetAddress":
673
- return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
674
- default:
675
- return (0, import_hwk_adapter_core3.failure)(
676
- import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
677
- `Unsupported method: ${String(method)}`
678
- );
790
+ return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
679
791
  }
680
792
  },
681
793
  attachIdentity: (context) => {
@@ -694,11 +806,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
694
806
  }
695
807
  });
696
808
  },
697
- // Cancel, refusal or a lost session ends the batch; other per-item
698
- // failures carry on with the next chain.
809
+ // Cancel, refusal, a lost connection or a safety answer (another wallet, a locked
810
+ // device) ends the batch; other per-item failures carry on with the next chain.
699
811
  shouldAbortBundle: (response, { index }) => {
700
812
  const { code } = response.payload ?? {};
701
- return cancelledIndexes.has(index) || (0, import_hwk_adapter_core3.isUserRefusal)(code) || (0, import_hwk_adapter_core3.isConnectionLost)(code);
813
+ const usbSessionLost = access?.channel === "usb" && this._resolveTarget(effectiveConnectId, itemDeviceId).record?.usbSessionId !== access.usbSessionId;
814
+ return cancelledIndexes.has(index) || usbSessionLost || (0, import_hwk_adapter_core3.isWalletSafetyFailure)(code) || (0, import_hwk_adapter_core3.isUserRefusal)(code) || (0, import_hwk_adapter_core3.isConnectionLost)(code);
702
815
  }
703
816
  });
704
817
  } catch (err) {
@@ -715,9 +828,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
715
828
  this._usbConnector?.on("device-disconnect", this._handleUsbDisconnect);
716
829
  this._usbConnector?.on("ui-event", this._handleUsbUiEvent);
717
830
  }
718
- // ---------------------------------------------------------------------------
719
- // Lifecycle / transport
720
- // ---------------------------------------------------------------------------
721
831
  get activeTransport() {
722
832
  if (this._devices.size === 0) return null;
723
833
  const hasUsbSession = Array.from(this._devices.values()).some((r) => r.usbSessionId);
@@ -747,9 +857,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
747
857
  this._devices.clear();
748
858
  this.emitter.removeAllListeners();
749
859
  }
750
- // ---------------------------------------------------------------------------
751
- // Device table
752
- // ---------------------------------------------------------------------------
753
860
  /**
754
861
  * Returns known wallets plus USB scan results; USB entries have no mfp until `connectDevice()`
755
862
  * claims them. Explicit QR discovery returns one virtual target.
@@ -822,11 +929,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
822
929
  }
823
930
  /** Best-effort disconnect; the session is retired either way so it cannot be selected again. */
824
931
  async _retireUsbSession(sessionId) {
825
- if (this._usbConnector) {
826
- try {
827
- await this._usbConnector.disconnect(sessionId);
828
- } catch {
829
- }
932
+ try {
933
+ await this._usbConnector?.disconnect(sessionId);
934
+ } catch {
830
935
  }
831
936
  this._handleUsbDisconnect({ connectId: sessionId });
832
937
  }
@@ -845,13 +950,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
845
950
  serialNumber: device.serialNumber
846
951
  }));
847
952
  }
848
- async listConnectionTargets(options) {
849
- const targets = await this.searchDeviceTargets(options);
850
- return targets.map(({ searchTargetId, ...target }) => ({
851
- ...target,
852
- targetId: searchTargetId
853
- }));
854
- }
855
953
  async connectDevice(searchTargetId) {
856
954
  const scope = this._jobQueue.createCancelScope(searchTargetId);
857
955
  try {
@@ -860,16 +958,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
860
958
  const discoveredConnectionType = this._searchDeviceTargets.get(searchTargetId);
861
959
  if (discoveredConnectionType === "qr") {
862
960
  selectedConnectionType = "qr";
863
- const abortColdStart = () => this._jobQueue.cancelActiveAndPending(
864
- KEYSTONE_COLD_START_JOB_LABEL,
865
- scope.signal.reason
961
+ connected = await _KeystoneAdapter._untilAborted(
962
+ scope.signal,
963
+ this._importFromQr({}, searchTargetId)
866
964
  );
867
- scope.signal.addEventListener("abort", abortColdStart, { once: true });
868
- try {
869
- connected = await this.importFromQr();
870
- } finally {
871
- scope.signal.removeEventListener("abort", abortColdStart);
872
- }
873
965
  } else if (discoveredConnectionType === "usb") {
874
966
  selectedConnectionType = "usb";
875
967
  if (!this._usbConnector) {
@@ -878,7 +970,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
878
970
  "No USB connector configured for this Keystone adapter"
879
971
  );
880
972
  }
881
- connected = await this._connectUsb({}, searchTargetId, scope.signal);
973
+ connected = await this._connectUsb(this._usbConnector, {}, searchTargetId, scope.signal);
882
974
  } else if ((0, import_hwk_adapter_core3.hasHardwareRuntimeIdPrefix)(searchTargetId)) {
883
975
  return (0, import_hwk_adapter_core3.failure)(
884
976
  import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound,
@@ -899,7 +991,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
899
991
  );
900
992
  } else {
901
993
  selectedConnectionType = "usb";
902
- connected = await this._connectUsb(target, void 0, scope.signal);
994
+ connected = await this._connectUsb(this._usbConnector, target, void 0, scope.signal);
903
995
  }
904
996
  }
905
997
  _KeystoneAdapter._throwIfAborted(scope.signal);
@@ -958,10 +1050,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
958
1050
  const { record } = this._resolveTarget(connectId, deviceId);
959
1051
  if (!record) {
960
1052
  return Promise.resolve(
961
- (0, import_hwk_adapter_core3.failure)(
962
- import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound,
963
- `Unknown Keystone device: ${connectId || deviceId}`
964
- )
1053
+ (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound, "Unknown Keystone device")
965
1054
  );
966
1055
  }
967
1056
  return Promise.resolve((0, import_hwk_adapter_core3.success)(toDeviceInfo(record)));
@@ -1000,6 +1089,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1000
1089
  this._uiRegistry.cancel();
1001
1090
  }
1002
1091
  }
1092
+ /**
1093
+ * Derived from the wallet's master fingerprint, which the caller already holds as deviceId; the
1094
+ * device is never asked. It names the wallet but cannot check which device is attached.
1095
+ */
1003
1096
  getChainFingerprint(connectId, deviceId, chain) {
1004
1097
  try {
1005
1098
  const target = this._resolveTarget(connectId, deviceId);
@@ -1033,18 +1126,21 @@ var KeystoneAdapter = class _KeystoneAdapter {
1033
1126
  // Explicit account import: call before signing to avoid a cold sync per call.
1034
1127
  // ---------------------------------------------------------------------------
1035
1128
  async importFromQr(options = {}) {
1129
+ return this._importFromQr(options, KEYSTONE_COLD_START_JOB_LABEL);
1130
+ }
1131
+ async _importFromQr(options, jobKey) {
1036
1132
  try {
1037
- return await this._jobQueue.enqueue(KEYSTONE_COLD_START_JOB_LABEL, async (signal) => {
1133
+ return await this._jobQueue.enqueue(jobKey, async (signal) => {
1038
1134
  const displayDevice = placeholderDeviceInfo();
1039
1135
  let responseUr;
1040
1136
  if (options.mode === "scan") {
1041
- responseUr = await this._requestQrScanAndAwaitResponse(displayDevice, signal);
1137
+ responseUr = await this._requestQrAndAwaitResponse(displayDevice, void 0, signal);
1042
1138
  } else {
1043
1139
  const requestUr = this.urEngine.buildKeyDerivationRequest({
1044
1140
  schemas: [keySchema("evm", KEYSTONE_COLD_START_PATH)],
1045
1141
  origin: this._origin
1046
1142
  });
1047
- responseUr = await this._requestQrDisplayAndAwaitResponse(
1143
+ responseUr = await this._requestQrAndAwaitResponse(
1048
1144
  displayDevice,
1049
1145
  { ...requestUr, animated: false },
1050
1146
  signal
@@ -1052,6 +1148,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1052
1148
  }
1053
1149
  _KeystoneAdapter._throwIfAborted(signal);
1054
1150
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1151
+ if (options.mode !== "scan") requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1055
1152
  const record = this._upsertDeviceRecord(parsed);
1056
1153
  return (0, import_hwk_adapter_core3.success)(toDeviceInfo(record));
1057
1154
  });
@@ -1059,161 +1156,105 @@ var KeystoneAdapter = class _KeystoneAdapter {
1059
1156
  return this._errorToFailure(err);
1060
1157
  }
1061
1158
  }
1062
- // ---------------------------------------------------------------------------
1063
- // EVM
1064
- // ---------------------------------------------------------------------------
1065
- async evmGetAddress(connectIdArg, deviceIdArg, params, book) {
1066
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1067
- if (!operationTarget.success) return operationTarget;
1068
- const connectId = operationTarget.payload.targetId;
1069
- const deviceId = deviceIdArg ?? void 0;
1070
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmGetAddress requires params");
1071
- if (!params.path)
1072
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmGetAddress requires params.path");
1073
- const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1074
- if (!relativeDerivePath) {
1075
- return (0, import_hwk_adapter_core3.failure)(
1076
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1077
- "evmGetAddress requires a full leaf path, e.g. m/44'/60'/0'/0/0"
1078
- );
1079
- }
1080
- return this._runJob(connectId, deviceId, async (signal) => {
1081
- const xpub = await this._fetchAccountXpub(
1082
- connectId,
1083
- deviceId,
1084
- "evm",
1085
- accountPath,
1086
- signal,
1087
- book
1088
- );
1089
- const address = this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath);
1090
- return (0, import_hwk_adapter_core3.success)({ address, path: normalizePath(params.path) });
1091
- });
1159
+ async evmGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1160
+ const call = this._beginCall("evmGetAddress", connectIdArg, deviceIdArg, paramsArg);
1161
+ if (!call.success) return call;
1162
+ const { params } = call.payload;
1163
+ if (!params.path) return missingParamFailure("evmGetAddress", "params.path");
1164
+ const evmCoinTypeFailure = coinTypeFailure("evm", params.path);
1165
+ if (evmCoinTypeFailure) return evmCoinTypeFailure;
1166
+ return this._addressFromAccountXpub(
1167
+ "evmGetAddress",
1168
+ "evm",
1169
+ call.payload,
1170
+ params.path,
1171
+ "m/44'/60'/0'/0/0",
1172
+ bundle,
1173
+ (xpub, relativeDerivePath) => this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath)
1174
+ );
1092
1175
  }
1093
- async evmSignTransaction(connectIdArg, deviceIdArg, params) {
1094
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1095
- if (!operationTarget.success) return operationTarget;
1096
- const connectId = operationTarget.payload.targetId;
1097
- const deviceId = deviceIdArg ?? void 0;
1098
- if (!params)
1099
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignTransaction requires params");
1100
- if (!params.path) {
1101
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignTransaction requires params.path");
1102
- }
1176
+ async evmSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1177
+ const call = this._beginCall("evmSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1178
+ if (!call.success) return call;
1179
+ const { params } = call.payload;
1180
+ if (!params.path) return missingParamFailure("evmSignTransaction", "params.path");
1103
1181
  if (!("serializedTx" in params) || typeof params.serializedTx !== "string" || !params.serializedTx) {
1104
1182
  return (0, import_hwk_adapter_core3.failure)(
1105
1183
  import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1106
1184
  "Keystone only signs a fully RLP-serialized transaction (params.serializedTx) \u2014 structured-field signing is not supported"
1107
1185
  );
1108
1186
  }
1109
- const rawTxHex = (0, import_hwk_adapter_core3.stripHex)(params.serializedTx);
1110
- const path = normalizePath(params.path);
1187
+ const rawTxHex = exactHex(params.serializedTx);
1188
+ if (rawTxHex === void 0) return invalidHexFailure("serializedTx");
1111
1189
  const dataType = parseInt(rawTxHex.slice(0, 2), 16) < 192 ? "typedTransaction" : "transaction";
1112
- return this._signWithWallet({
1113
- connectId,
1114
- deviceId,
1115
- chain: "evm",
1116
- operationName: "evmSignTransaction",
1117
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1118
- requestId,
1119
- unsignedTxHex: rawTxHex,
1120
- dataType,
1121
- path,
1122
- xfp,
1123
- chainId: params.chainId,
1124
- origin: this._origin
1125
- }),
1126
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1127
- toPayload: (sig) => ({
1128
- v: (0, import_hwk_adapter_core3.ensure0x)(sig.v),
1129
- r: (0, import_hwk_adapter_core3.ensure0x)(sig.r),
1130
- s: (0, import_hwk_adapter_core3.ensure0x)(sig.s)
1131
- })
1132
- });
1190
+ return this._evmSign(
1191
+ "evmSignTransaction",
1192
+ call.payload,
1193
+ params.path,
1194
+ params.chainId,
1195
+ rawTxHex,
1196
+ dataType,
1197
+ (sig) => ({ v: (0, import_hwk_adapter_core3.ensure0x)(sig.v), r: (0, import_hwk_adapter_core3.ensure0x)(sig.r), s: (0, import_hwk_adapter_core3.ensure0x)(sig.s) })
1198
+ );
1133
1199
  }
1134
- async evmSignMessage(connectIdArg, deviceIdArg, params) {
1135
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1136
- if (!operationTarget.success) return operationTarget;
1137
- const connectId = operationTarget.payload.targetId;
1138
- const deviceId = deviceIdArg ?? void 0;
1139
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignMessage requires params");
1200
+ async evmSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1201
+ const call = this._beginCall("evmSignMessage", connectIdArg, deviceIdArg, paramsArg);
1202
+ if (!call.success) return call;
1203
+ const { params } = call.payload;
1140
1204
  if (!params.path || params.message === void 0) {
1141
- return (0, import_hwk_adapter_core3.failure)(
1142
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1143
- "evmSignMessage requires params.path and params.message"
1144
- );
1145
- }
1146
- const messageHex = params.hex ? (0, import_hwk_adapter_core3.stripHex)(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1147
- const path = normalizePath(params.path);
1148
- return this._signWithWallet({
1149
- connectId,
1150
- deviceId,
1151
- chain: "evm",
1152
- operationName: "evmSignMessage",
1153
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1154
- requestId,
1155
- unsignedTxHex: messageHex,
1156
- dataType: "personalMessage",
1157
- path,
1158
- xfp,
1159
- chainId: params.chainId,
1160
- origin: this._origin
1161
- }),
1162
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1163
- toPayload: (sig) => ({ signature: (0, import_hwk_adapter_core3.ensure0x)(sig.r + sig.s + sig.v) })
1164
- });
1205
+ return missingParamFailure("evmSignMessage", "params.path and params.message");
1206
+ }
1207
+ const messageHex = messageToHex(params.message, params.hex);
1208
+ if (messageHex === void 0) return invalidHexFailure("message");
1209
+ return this._evmSign(
1210
+ "evmSignMessage",
1211
+ call.payload,
1212
+ params.path,
1213
+ params.chainId,
1214
+ messageHex,
1215
+ "personalMessage",
1216
+ evmMessageSignature
1217
+ );
1165
1218
  }
1166
- async evmSignTypedData(connectIdArg, deviceIdArg, params) {
1167
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1168
- if (!operationTarget.success) return operationTarget;
1169
- const connectId = operationTarget.payload.targetId;
1170
- const deviceId = deviceIdArg ?? void 0;
1171
- if (!params)
1172
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignTypedData requires params");
1173
- if (!params.path) {
1174
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignTypedData requires params.path");
1175
- }
1219
+ async evmSignTypedData(connectIdArg, deviceIdArg, paramsArg) {
1220
+ const call = this._beginCall("evmSignTypedData", connectIdArg, deviceIdArg, paramsArg);
1221
+ if (!call.success) return call;
1222
+ const { params } = call.payload;
1223
+ if (!params.path) return missingParamFailure("evmSignTypedData", "params.path");
1176
1224
  if (params.mode === "hash") {
1177
1225
  return (0, import_hwk_adapter_core3.failure)(
1178
1226
  import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1179
1227
  "Keystone always displays the full EIP-712 payload for on-device review \u2014 pre-hashed signing is not supported"
1180
1228
  );
1181
1229
  }
1182
- const signDataHex = Buffer.from(
1183
- params.dataJson ?? JSON.stringify(params.data),
1184
- "utf8"
1185
- ).toString("hex");
1186
- const path = normalizePath(params.path);
1187
- return this._signWithWallet({
1188
- connectId,
1189
- deviceId,
1190
- chain: "evm",
1191
- operationName: "evmSignTypedData",
1192
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1193
- requestId,
1194
- unsignedTxHex: signDataHex,
1195
- dataType: "typedData",
1196
- path,
1197
- xfp,
1198
- chainId: params.chainId,
1199
- origin: this._origin
1200
- }),
1201
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1202
- toPayload: (sig) => ({ signature: (0, import_hwk_adapter_core3.ensure0x)(sig.r + sig.s + sig.v) })
1203
- });
1230
+ if (typeof params.dataJson !== "string" || !params.dataJson) {
1231
+ return (0, import_hwk_adapter_core3.failure)(
1232
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1233
+ "Keystone evmSignTypedData requires params.dataJson, the original typed-data JSON text"
1234
+ );
1235
+ }
1236
+ const signDataHex = Buffer.from(params.dataJson, "utf8").toString("hex");
1237
+ return this._evmSign(
1238
+ "evmSignTypedData",
1239
+ call.payload,
1240
+ params.path,
1241
+ params.chainId,
1242
+ signDataHex,
1243
+ "typedData",
1244
+ evmMessageSignature
1245
+ );
1204
1246
  }
1205
1247
  // ---------------------------------------------------------------------------
1206
1248
  // BTC: 44'/49'/84' addresses derive offline from the account xpub; P2TR addresses
1207
1249
  // and structured-field tx signing are unsupported (the host builds a PSBT instead).
1208
1250
  // ---------------------------------------------------------------------------
1209
- async btcGetAddress(connectIdArg, deviceIdArg, params, book) {
1210
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1211
- if (!operationTarget.success) return operationTarget;
1212
- const connectId = operationTarget.payload.targetId;
1213
- const deviceId = deviceIdArg ?? void 0;
1214
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetAddress requires params");
1215
- if (!params.path)
1216
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetAddress requires params.path");
1251
+ async btcGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1252
+ const call = this._beginCall("btcGetAddress", connectIdArg, deviceIdArg, paramsArg);
1253
+ if (!call.success) return call;
1254
+ const { params } = call.payload;
1255
+ if (!params.path) return missingParamFailure("btcGetAddress", "params.path");
1256
+ const btcParamsFailure = keystoneBtcParamsFailure(params);
1257
+ if (btcParamsFailure) return btcParamsFailure;
1217
1258
  const scriptType = btcScriptTypeFromPath(params.path);
1218
1259
  if (!scriptType) {
1219
1260
  return (0, import_hwk_adapter_core3.failure)(
@@ -1227,42 +1268,27 @@ var KeystoneAdapter = class _KeystoneAdapter {
1227
1268
  "P2TR (purpose 86') needs an elliptic-curve library for BIP-341 tweaking, not yet wired in \u2014 44'/49'/84' work"
1228
1269
  );
1229
1270
  }
1230
- const normalizedPath = normalizePath(params.path);
1231
- const { accountPath, relativeDerivePath } = splitAccountPath(normalizedPath);
1232
- if (!relativeDerivePath) {
1233
- return (0, import_hwk_adapter_core3.failure)(
1234
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1235
- "btcGetAddress requires a full leaf path, e.g. m/84'/0'/0'/0/0"
1236
- );
1237
- }
1238
- if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1239
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1240
- }
1241
- return this._runJob(connectId, deviceId, async (signal) => {
1242
- const xpub = await this._fetchAccountXpub(
1243
- connectId,
1244
- deviceId,
1245
- "btc",
1246
- accountPath,
1247
- signal,
1248
- book
1249
- );
1250
- const address = this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType);
1251
- return (0, import_hwk_adapter_core3.success)({ address, path: normalizedPath });
1252
- });
1271
+ return this._addressFromAccountXpub(
1272
+ "btcGetAddress",
1273
+ "btc",
1274
+ call.payload,
1275
+ params.path,
1276
+ "m/84'/0'/0'/0/0",
1277
+ bundle,
1278
+ (xpub, relativeDerivePath) => this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType)
1279
+ );
1253
1280
  }
1254
1281
  /**
1255
1282
  * `params.path` must be an account path (`m/84'/0'/0'`), the level Keystone syncs. An xpub is
1256
1283
  * script-type agnostic, so `86'` works here even though `btcGetAddress` rejects it.
1257
1284
  */
1258
- async btcGetPublicKey(connectIdArg, deviceIdArg, params, book) {
1259
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1260
- if (!operationTarget.success) return operationTarget;
1261
- const connectId = operationTarget.payload.targetId;
1262
- const deviceId = deviceIdArg ?? void 0;
1263
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params");
1264
- if (!params.path)
1265
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params.path");
1285
+ async btcGetPublicKey(connectIdArg, deviceIdArg, paramsArg, bundle) {
1286
+ const call = this._beginCall("btcGetPublicKey", connectIdArg, deviceIdArg, paramsArg);
1287
+ if (!call.success) return call;
1288
+ const { connectId, deviceId, params } = call.payload;
1289
+ if (!params.path) return missingParamFailure("btcGetPublicKey", "params.path");
1290
+ const btcParamsFailure = keystoneBtcParamsFailure(params);
1291
+ if (btcParamsFailure) return btcParamsFailure;
1266
1292
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1267
1293
  if (relativeDerivePath) {
1268
1294
  return (0, import_hwk_adapter_core3.failure)(
@@ -1270,9 +1296,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1270
1296
  "btcGetPublicKey requires an account path, e.g. m/84'/0'/0' (not a leaf path)"
1271
1297
  );
1272
1298
  }
1273
- if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1274
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1275
- }
1299
+ const accountFailure = btcAccountFailure(accountPath);
1300
+ if (accountFailure) return accountFailure;
1276
1301
  return this._runJob(connectId, deviceId, async (signal) => {
1277
1302
  const xpub = await this._fetchAccountXpub(
1278
1303
  connectId,
@@ -1280,7 +1305,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1280
1305
  "btc",
1281
1306
  accountPath,
1282
1307
  signal,
1283
- book
1308
+ bundle
1284
1309
  );
1285
1310
  const meta = this.urEngine.parseXpubMeta(xpub);
1286
1311
  return (0, import_hwk_adapter_core3.success)({
@@ -1289,7 +1314,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1289
1314
  chainCode: meta.chainCode,
1290
1315
  depth: meta.depth,
1291
1316
  fingerprint: meta.parentFingerprint,
1292
- path: normalizePath(accountPath)
1317
+ path: normalizePath(accountPath),
1318
+ accountKey: this._exportedAccountKey(accountPath, xpub)
1293
1319
  });
1294
1320
  });
1295
1321
  }
@@ -1299,23 +1325,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1299
1325
  "use btcSignPsbt \u2014 structured input/output signing needs host-side PSBT construction, not yet wired in"
1300
1326
  );
1301
1327
  }
1302
- async btcSignPsbt(connectIdArg, deviceIdArg, params) {
1303
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1304
- if (!operationTarget.success) return operationTarget;
1305
- const connectId = operationTarget.payload.targetId;
1306
- const deviceId = deviceIdArg ?? void 0;
1307
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcSignPsbt requires params");
1308
- if (!params.psbt)
1309
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcSignPsbt requires params.psbt");
1310
- if (!params.path)
1311
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcSignPsbt requires params.path");
1312
- if (!isKeystoneSignableBtcAccountPath(splitAccountPath(params.path).accountPath)) {
1313
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1314
- }
1328
+ async btcSignPsbt(connectIdArg, deviceIdArg, paramsArg) {
1329
+ const call = this._beginCall("btcSignPsbt", connectIdArg, deviceIdArg, paramsArg);
1330
+ if (!call.success) return call;
1331
+ const { connectId, deviceId, params } = call.payload;
1332
+ if (!params.psbt) return missingParamFailure("btcSignPsbt", "params.psbt");
1333
+ if (!params.path) return missingParamFailure("btcSignPsbt", "params.path");
1334
+ const accountFailure = btcAccountFailure(splitAccountPath(params.path).accountPath);
1335
+ if (accountFailure) return accountFailure;
1336
+ const requestPsbtHex = exactHex(params.psbt);
1337
+ if (requestPsbtHex === void 0) return invalidHexFailure("psbt");
1315
1338
  return this._runJob(connectId, deviceId, async (signal) => {
1316
1339
  const { record } = await this._ensureWalletKnown(connectId, deviceId, "btc", signal);
1317
1340
  _KeystoneAdapter._throwIfAborted(signal);
1318
- const requestUr = this.urEngine.buildBtcPsbtRequest((0, import_hwk_adapter_core3.stripHex)(params.psbt));
1341
+ const requestUr = this.urEngine.buildBtcPsbtRequest(requestPsbtHex);
1319
1342
  const responseUr = await this._resolveUr(
1320
1343
  record,
1321
1344
  requestUr,
@@ -1325,30 +1348,26 @@ var KeystoneAdapter = class _KeystoneAdapter {
1325
1348
  "btcSignPsbt"
1326
1349
  );
1327
1350
  _KeystoneAdapter._throwIfAborted(signal);
1328
- const signedPsbt = this.urEngine.parseBtcPsbt(responseUr);
1351
+ const signedPsbt = this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex);
1329
1352
  return (0, import_hwk_adapter_core3.success)({ signedPsbt });
1330
1353
  });
1331
1354
  }
1332
- async btcSignMessage(connectIdArg, deviceIdArg, params) {
1333
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1334
- if (!operationTarget.success) return operationTarget;
1335
- const connectId = operationTarget.payload.targetId;
1336
- const deviceId = deviceIdArg ?? void 0;
1337
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcSignMessage requires params");
1355
+ async btcSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1356
+ const call = this._beginCall("btcSignMessage", connectIdArg, deviceIdArg, paramsArg);
1357
+ if (!call.success) return call;
1358
+ const { connectId, deviceId, params } = call.payload;
1338
1359
  if (!params.path || params.message === void 0) {
1339
- return (0, import_hwk_adapter_core3.failure)(
1340
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1341
- "btcSignMessage requires params.path and params.message"
1342
- );
1360
+ return missingParamFailure("btcSignMessage", "params.path and params.message");
1343
1361
  }
1344
- const messageHex = params.hex ? (0, import_hwk_adapter_core3.stripHex)(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1362
+ const messageHex = messageToHex(params.message, params.hex);
1363
+ if (messageHex === void 0) return invalidHexFailure("message");
1345
1364
  const path = normalizePath(params.path);
1346
- if (!isKeystoneSignableBtcAccountPath(splitAccountPath(path).accountPath)) {
1347
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1348
- }
1365
+ const accountFailure = btcAccountFailure(splitAccountPath(path).accountPath);
1366
+ if (accountFailure) return accountFailure;
1349
1367
  return this._signWithWallet({
1350
1368
  connectId,
1351
1369
  deviceId,
1370
+ path,
1352
1371
  chain: "btc",
1353
1372
  operationName: "btcSignMessage",
1354
1373
  buildRequest: (requestId, xfp) => this.urEngine.buildBtcMessageSignRequest({
@@ -1361,8 +1380,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1361
1380
  toPayload: (sig) => ({ signature: sig.signature })
1362
1381
  });
1363
1382
  }
1383
+ /**
1384
+ * Returns the known master fingerprint for the named wallet without asking the device (a QR
1385
+ * round trip only to repeat it would cost a scan). Use it to name the wallet, for example as a
1386
+ * PSBT xfp, which the device itself checks when signing; it cannot check the attached device.
1387
+ */
1364
1388
  async btcGetMasterFingerprint(connectIdArg, deviceIdArg, paramsArg) {
1365
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, paramsArg?.operationId);
1389
+ const operationTarget = this._resolveOperationTarget(connectIdArg, paramsArg?.operationId);
1366
1390
  if (!operationTarget.success) return operationTarget;
1367
1391
  const connectId = operationTarget.payload.targetId;
1368
1392
  const deviceId = deviceIdArg ?? void 0;
@@ -1371,193 +1395,242 @@ var KeystoneAdapter = class _KeystoneAdapter {
1371
1395
  return (0, import_hwk_adapter_core3.success)({ masterFingerprint: record.masterFingerprint });
1372
1396
  });
1373
1397
  }
1374
- // ---------------------------------------------------------------------------
1375
- // SOL
1376
- // ---------------------------------------------------------------------------
1377
- async solGetAddress(connectIdArg, deviceIdArg, params, book) {
1378
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1379
- if (!operationTarget.success) return operationTarget;
1380
- const connectId = operationTarget.payload.targetId;
1381
- const deviceId = deviceIdArg ?? void 0;
1382
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solGetAddress requires params");
1383
- if (!params.path)
1384
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solGetAddress requires params.path");
1398
+ async solGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1399
+ const call = this._beginCall("solGetAddress", connectIdArg, deviceIdArg, paramsArg);
1400
+ if (!call.success) return call;
1401
+ const { connectId, deviceId, params } = call.payload;
1402
+ if (!params.path) return missingParamFailure("solGetAddress", "params.path");
1403
+ const solCoinTypeFailure = coinTypeFailure("sol", params.path);
1404
+ if (solCoinTypeFailure) return solCoinTypeFailure;
1385
1405
  const path = normalizePath(params.path);
1386
- return this._runJob(connectId, deviceId, async (signal) => {
1387
- const { account } = await this._fetchAccount(connectId, deviceId, "sol", path, signal, book);
1388
- _KeystoneAdapter._throwIfAborted(signal);
1389
- const address = import_bs58.default.encode(Buffer.from(account.publicKey, "hex"));
1390
- return (0, import_hwk_adapter_core3.success)({ address, path });
1391
- });
1392
- }
1393
- async solSignTransaction(connectIdArg, deviceIdArg, params) {
1394
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1395
- if (!operationTarget.success) return operationTarget;
1396
- const connectId = operationTarget.payload.targetId;
1397
- const deviceId = deviceIdArg ?? void 0;
1398
- if (!params)
1399
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solSignTransaction requires params");
1400
- if (!params.path || !params.serializedTx) {
1406
+ if (!/^m(\/\d+')+$/.test(path)) {
1401
1407
  return (0, import_hwk_adapter_core3.failure)(
1402
1408
  import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1403
- "solSignTransaction requires params.path and params.serializedTx"
1409
+ "solGetAddress requires a fully hardened path, e.g. m/44'/501'/0'/0'"
1404
1410
  );
1405
1411
  }
1406
- const path = normalizePath(params.path);
1407
- return this._signWithWallet({
1408
- connectId,
1409
- deviceId,
1410
- chain: "sol",
1411
- operationName: "solSignTransaction",
1412
- buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1413
- requestId,
1414
- unsignedPayloadHex: (0, import_hwk_adapter_core3.stripHex)(params.serializedTx),
1415
- dataType: "transaction",
1412
+ return this._runJob(connectId, deviceId, async (signal) => {
1413
+ const { account } = await this._fetchAccount(
1414
+ connectId,
1415
+ deviceId,
1416
+ "sol",
1416
1417
  path,
1417
- xfp,
1418
- origin: this._origin
1419
- }),
1420
- parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1421
- toPayload: (sig) => ({ signature: sig.signature })
1418
+ signal,
1419
+ bundle
1420
+ );
1421
+ _KeystoneAdapter._throwIfAborted(signal);
1422
+ if (!/^[0-9a-f]{64}$/i.test(account.publicKey)) {
1423
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1424
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1425
+ message: "Keystone returned a Solana key that is not a 32-byte Ed25519 public key"
1426
+ });
1427
+ }
1428
+ const address = import_bs58.default.encode(Buffer.from(account.publicKey, "hex"));
1429
+ return (0, import_hwk_adapter_core3.success)({
1430
+ address,
1431
+ path,
1432
+ accountKey: { path, publicKey: account.publicKey }
1433
+ });
1422
1434
  });
1423
1435
  }
1424
- async solSignMessage(connectIdArg, deviceIdArg, params) {
1425
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1426
- if (!operationTarget.success) return operationTarget;
1427
- const connectId = operationTarget.payload.targetId;
1428
- const deviceId = deviceIdArg ?? void 0;
1429
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solSignMessage requires params");
1436
+ async solSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1437
+ const call = this._beginCall("solSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1438
+ if (!call.success) return call;
1439
+ const { params } = call.payload;
1440
+ if (!params.path || !params.serializedTx) {
1441
+ return missingParamFailure("solSignTransaction", "params.path and params.serializedTx");
1442
+ }
1443
+ const unsignedPayloadHex = exactHex(params.serializedTx);
1444
+ if (unsignedPayloadHex === void 0) return invalidHexFailure("serializedTx");
1445
+ return this._solSign(
1446
+ "solSignTransaction",
1447
+ call.payload,
1448
+ params.path,
1449
+ unsignedPayloadHex,
1450
+ "transaction"
1451
+ );
1452
+ }
1453
+ async solSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1454
+ const call = this._beginCall("solSignMessage", connectIdArg, deviceIdArg, paramsArg);
1455
+ if (!call.success) return call;
1456
+ const { params } = call.payload;
1430
1457
  if (!params.path || !params.message) {
1458
+ return missingParamFailure("solSignMessage", "params.path and params.message");
1459
+ }
1460
+ if (params.messageVersion !== void 0) {
1431
1461
  return (0, import_hwk_adapter_core3.failure)(
1432
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1433
- "solSignMessage requires params.path and params.message"
1462
+ import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1463
+ "Keystone signs Solana messages as raw bytes only; off-chain message format is not supported"
1434
1464
  );
1435
1465
  }
1436
- const path = normalizePath(params.path);
1437
- return this._signWithWallet({
1438
- connectId,
1439
- deviceId,
1440
- chain: "sol",
1441
- operationName: "solSignMessage",
1442
- buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1443
- requestId,
1444
- unsignedPayloadHex: (0, import_hwk_adapter_core3.stripHex)(params.message),
1445
- dataType: "message",
1446
- path,
1447
- xfp,
1448
- origin: this._origin
1449
- }),
1450
- parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1451
- toPayload: (sig) => ({ signature: sig.signature })
1452
- });
1466
+ const unsignedPayloadHex = exactHex(params.message);
1467
+ if (unsignedPayloadHex === void 0) return invalidHexFailure("message");
1468
+ return this._solSign(
1469
+ "solSignMessage",
1470
+ call.payload,
1471
+ params.path,
1472
+ unsignedPayloadHex,
1473
+ "message"
1474
+ );
1453
1475
  }
1454
1476
  // ---------------------------------------------------------------------------
1455
1477
  // TRON: keystone-sdk-rust layout (tags 5201/5202, firmware >= 2.5.0), not sdk.tron's
1456
1478
  // protobuf module; OneKey Pro's encoding under the same tag is rejected by the firmware.
1457
1479
  // ---------------------------------------------------------------------------
1458
- async tronGetAddress(connectIdArg, deviceIdArg, params, book) {
1459
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1480
+ async tronGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1481
+ const call = this._beginCall("tronGetAddress", connectIdArg, deviceIdArg, paramsArg);
1482
+ if (!call.success) return call;
1483
+ const { params } = call.payload;
1484
+ if (!params.path) return missingParamFailure("tronGetAddress", "params.path");
1485
+ const tronCoinTypeFailure = coinTypeFailure("tron", params.path);
1486
+ if (tronCoinTypeFailure) return tronCoinTypeFailure;
1487
+ return this._addressFromAccountXpub(
1488
+ "tronGetAddress",
1489
+ "tron",
1490
+ call.payload,
1491
+ params.path,
1492
+ "m/44'/195'/0'/0/0",
1493
+ bundle,
1494
+ (xpub, relativeDerivePath) => this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath)
1495
+ );
1496
+ }
1497
+ async tronSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1498
+ const call = this._beginCall("tronSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1499
+ if (!call.success) return call;
1500
+ const { params } = call.payload;
1501
+ if (!params.path) return missingParamFailure("tronSignTransaction", "params.path");
1502
+ if (!params.rawTxHex) {
1503
+ return (0, import_hwk_adapter_core3.failure)(
1504
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1505
+ "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1506
+ );
1507
+ }
1508
+ const rawTxHex = exactHex(params.rawTxHex);
1509
+ if (rawTxHex === void 0) return invalidHexFailure("rawTxHex");
1510
+ return this._tronSign("tronSignTransaction", call.payload, params.path, rawTxHex);
1511
+ }
1512
+ async tronSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1513
+ const call = this._beginCall("tronSignMessage", connectIdArg, deviceIdArg, paramsArg);
1514
+ if (!call.success) return call;
1515
+ const { params } = call.payload;
1516
+ if (!params.path) return missingParamFailure("tronSignMessage", "params.path");
1517
+ if (!params.messageHex) return missingParamFailure("tronSignMessage", "params.messageHex");
1518
+ if (params.messageType !== "V2") {
1519
+ return (0, import_hwk_adapter_core3.failure)(
1520
+ import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1521
+ 'Keystone signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1522
+ );
1523
+ }
1524
+ const messageHex = exactHex(params.messageHex);
1525
+ if (messageHex === void 0) return invalidHexFailure("messageHex");
1526
+ return this._tronSign(
1527
+ "tronSignMessage",
1528
+ call.payload,
1529
+ params.path,
1530
+ messageHex,
1531
+ 2 /* PersonalMessage */
1532
+ );
1533
+ }
1534
+ /** Resolves the call's target and requires params, before any method-specific check. */
1535
+ _beginCall(method, connectIdArg, deviceIdArg, params) {
1536
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1460
1537
  if (!operationTarget.success) return operationTarget;
1461
- const connectId = operationTarget.payload.targetId;
1462
- const deviceId = deviceIdArg ?? void 0;
1463
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronGetAddress requires params");
1464
- if (!params.path)
1465
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronGetAddress requires params.path");
1466
- const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1538
+ if (!params) return missingParamFailure(method, "params");
1539
+ return (0, import_hwk_adapter_core3.success)({
1540
+ connectId: operationTarget.payload.targetId,
1541
+ deviceId: deviceIdArg ?? void 0,
1542
+ params
1543
+ });
1544
+ }
1545
+ /** Derives a leaf address offline from its account xpub. */
1546
+ async _addressFromAccountXpub(method, chain, { connectId, deviceId }, path, leafExample, bundle, derive) {
1547
+ const normalizedPath = normalizePath(path);
1548
+ const { accountPath, relativeDerivePath } = splitAccountPath(normalizedPath);
1467
1549
  if (!relativeDerivePath) {
1468
1550
  return (0, import_hwk_adapter_core3.failure)(
1469
1551
  import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1470
- "tronGetAddress requires a full leaf path, e.g. m/44'/195'/0'/0/0"
1552
+ `${method} requires a full leaf path, e.g. ${leafExample}`
1471
1553
  );
1472
1554
  }
1555
+ const accountFailure = chain === "btc" ? btcAccountFailure(accountPath) : void 0;
1556
+ if (accountFailure) return accountFailure;
1473
1557
  return this._runJob(connectId, deviceId, async (signal) => {
1474
1558
  const xpub = await this._fetchAccountXpub(
1475
1559
  connectId,
1476
1560
  deviceId,
1477
- "tron",
1561
+ chain,
1478
1562
  accountPath,
1479
1563
  signal,
1480
- book
1564
+ bundle
1481
1565
  );
1482
- const address = this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath);
1483
- return (0, import_hwk_adapter_core3.success)({ address, path: normalizePath(params.path) });
1566
+ return (0, import_hwk_adapter_core3.success)({
1567
+ address: derive(xpub, relativeDerivePath),
1568
+ path: normalizedPath,
1569
+ accountKey: this._exportedAccountKey(accountPath, xpub)
1570
+ });
1484
1571
  });
1485
1572
  }
1486
- async tronSignTransaction(connectIdArg, deviceIdArg, params) {
1487
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1488
- if (!operationTarget.success) return operationTarget;
1489
- const connectId = operationTarget.payload.targetId;
1490
- const deviceId = deviceIdArg ?? void 0;
1491
- if (!params)
1492
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignTransaction requires params");
1493
- if (!params.path) {
1494
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignTransaction requires params.path");
1495
- }
1496
- if (!params.rawTxHex) {
1497
- return (0, import_hwk_adapter_core3.failure)(
1498
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1499
- "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1500
- );
1501
- }
1502
- const rawTxHex = (0, import_hwk_adapter_core3.stripHex)(params.rawTxHex);
1503
- const path = normalizePath(params.path);
1573
+ _evmSign(method, target, rawPath, chainId, signDataHex, dataType, toPayload) {
1574
+ const path = normalizePath(rawPath);
1504
1575
  return this._signWithWallet({
1505
- connectId,
1506
- deviceId,
1507
- chain: "tron",
1508
- operationName: "tronSignTransaction",
1509
- buildRequest: (requestId, xfp) => this.urEngine.buildTronSignRequest({
1576
+ connectId: target.connectId,
1577
+ deviceId: target.deviceId,
1578
+ path,
1579
+ chain: "evm",
1580
+ operationName: method,
1581
+ buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1510
1582
  requestId,
1511
- rawTxHex,
1583
+ unsignedTxHex: signDataHex,
1584
+ dataType,
1512
1585
  path,
1513
1586
  xfp,
1587
+ chainId,
1514
1588
  origin: this._origin
1515
1589
  }),
1516
- parseResponse: (ur) => this.urEngine.parseTronSignature(ur),
1517
- // Keystone signs rawTxHex as given and returns only the signature, so no serializedTx.
1590
+ parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1591
+ toPayload
1592
+ });
1593
+ }
1594
+ _solSign(method, target, rawPath, unsignedPayloadHex, dataType) {
1595
+ const path = normalizePath(rawPath);
1596
+ return this._signWithWallet({
1597
+ connectId: target.connectId,
1598
+ deviceId: target.deviceId,
1599
+ path,
1600
+ chain: "sol",
1601
+ operationName: method,
1602
+ buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1603
+ requestId,
1604
+ unsignedPayloadHex,
1605
+ dataType,
1606
+ path,
1607
+ xfp,
1608
+ origin: this._origin
1609
+ }),
1610
+ parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1518
1611
  toPayload: (sig) => ({ signature: sig.signature })
1519
1612
  });
1520
1613
  }
1521
- async tronSignMessage(connectIdArg, deviceIdArg, params) {
1522
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1523
- if (!operationTarget.success) return operationTarget;
1524
- const connectId = operationTarget.payload.targetId;
1525
- const deviceId = deviceIdArg ?? void 0;
1526
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignMessage requires params");
1527
- if (!params.path) {
1528
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignMessage requires params.path");
1529
- }
1530
- if (!params.messageHex) {
1531
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignMessage requires params.messageHex");
1532
- }
1533
- if (params.messageType !== "V2") {
1534
- return (0, import_hwk_adapter_core3.failure)(
1535
- import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1536
- 'Keystone signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1537
- );
1538
- }
1539
- const messageHex = (0, import_hwk_adapter_core3.stripHex)(params.messageHex);
1540
- const path = normalizePath(params.path);
1614
+ _tronSign(method, target, rawPath, signDataHex, signType) {
1615
+ const path = normalizePath(rawPath);
1541
1616
  return this._signWithWallet({
1542
- connectId,
1543
- deviceId,
1617
+ connectId: target.connectId,
1618
+ deviceId: target.deviceId,
1619
+ path,
1544
1620
  chain: "tron",
1545
- operationName: "tronSignMessage",
1621
+ operationName: method,
1546
1622
  buildRequest: (requestId, xfp) => this.urEngine.buildTronSignRequest({
1547
1623
  requestId,
1548
- rawTxHex: messageHex,
1624
+ rawTxHex: signDataHex,
1549
1625
  path,
1550
1626
  xfp,
1551
- signType: 2 /* PersonalMessage */,
1627
+ signType,
1552
1628
  origin: this._origin
1553
1629
  }),
1554
1630
  parseResponse: (ur) => this.urEngine.parseTronSignature(ur),
1555
1631
  toPayload: (sig) => ({ signature: sig.signature })
1556
1632
  });
1557
1633
  }
1558
- // ---------------------------------------------------------------------------
1559
- // Internals
1560
- // ---------------------------------------------------------------------------
1561
1634
  async _runJob(connectId, deviceId, job) {
1562
1635
  try {
1563
1636
  return await this._jobQueue.enqueue(keystoneQueueKey(connectId, deviceId), job);
@@ -1565,14 +1638,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1565
1638
  return this._errorToFailure(err);
1566
1639
  }
1567
1640
  }
1568
- async _fetchAccountXpub(connectId, deviceId, hwkChain, accountPath, signal, book) {
1641
+ async _fetchAccountXpub(connectId, deviceId, hwkChain, accountPath, signal, bundle) {
1569
1642
  const { account } = await this._fetchAccount(
1570
1643
  connectId,
1571
1644
  deviceId,
1572
1645
  hwkChain,
1573
1646
  accountPath,
1574
1647
  signal,
1575
- book
1648
+ bundle
1576
1649
  );
1577
1650
  _KeystoneAdapter._throwIfAborted(signal);
1578
1651
  if (!account.extendedPublicKey) {
@@ -1581,14 +1654,33 @@ var KeystoneAdapter = class _KeystoneAdapter {
1581
1654
  message: "Keystone did not return an extended public key for this account path"
1582
1655
  });
1583
1656
  }
1657
+ const { publicKey } = this.urEngine.parseXpubMeta(account.extendedPublicKey);
1658
+ if (!/^0[23]/.test(publicKey)) {
1659
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1660
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1661
+ message: "Keystone returned an account key that is not a public key"
1662
+ });
1663
+ }
1584
1664
  return account.extendedPublicKey;
1585
1665
  }
1666
+ /** The exported key behind an address, reduced to the fields that identify it. */
1667
+ _exportedAccountKey(accountPath, xpub) {
1668
+ const { publicKey, chainCode } = this.urEngine.parseXpubMeta(xpub);
1669
+ return { path: normalizePath(accountPath), publicKey, chainCode, xpub };
1670
+ }
1586
1671
  /**
1587
1672
  * Signing needs only the wallet's mfp: the device re-derives the key from path+xfp, so no
1588
1673
  * per-path account lookup happens here.
1589
1674
  */
1590
1675
  _signWithWallet(args) {
1591
1676
  const { connectId, deviceId } = args;
1677
+ if (!isBip32Path(args.path)) {
1678
+ return Promise.resolve(
1679
+ (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `Invalid derivation path (${args.path})`)
1680
+ );
1681
+ }
1682
+ const chainCoinTypeFailure = coinTypeFailure(args.chain, args.path);
1683
+ if (chainCoinTypeFailure) return Promise.resolve(chainCoinTypeFailure);
1592
1684
  return this._runJob(connectId, deviceId, async (signal) => {
1593
1685
  const { record } = await this._ensureWalletKnown(connectId, deviceId, args.chain, signal);
1594
1686
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1613,6 +1705,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1613
1705
  const method = item.methodName;
1614
1706
  const hwkChain = (0, import_hwk_adapter_core3.getAllNetworkMethodChain)(method);
1615
1707
  const path = normalizePath(item.path);
1708
+ if (!hasChainCoinType(hwkChain, path)) return void 0;
1616
1709
  if (hwkChain === "btc" && !isKeystoneSignableBtcAccountPath(splitAccountPath(path).accountPath)) {
1617
1710
  return void 0;
1618
1711
  }
@@ -1624,15 +1717,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1624
1717
  case "btcGetPublicKey":
1625
1718
  case "solGetAddress":
1626
1719
  return { hwkChain, path };
1627
- default:
1628
- return void 0;
1629
1720
  }
1630
1721
  }
1631
1722
  /**
1632
- * QR answers the whole bundle with one request QR and one scan. USB exports one path per
1633
- * request because the device limits that channel.
1723
+ * Picks the bundle's channel. QR answers every item with one request QR and one scan; USB items
1724
+ * each ask the device directly, like other vendors, on the session found here.
1634
1725
  */
1635
- async _prefetchAllNetworkAccounts(connectId, deviceId, params) {
1726
+ async _prepareAllNetworkBundle(connectId, deviceId, params) {
1636
1727
  return this._jobQueue.enqueue(keystoneQueueKey(connectId, deviceId), async (signal) => {
1637
1728
  const target = this._resolveTarget(connectId, deviceId);
1638
1729
  let { record } = target;
@@ -1641,21 +1732,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1641
1732
  const schema = this._allNetworkSyncSchema(item);
1642
1733
  if (schema) requestedByKey.set(accountKey(schema.hwkChain, schema.path), schema);
1643
1734
  }
1644
- const book = /* @__PURE__ */ new Map();
1735
+ const scanned = /* @__PURE__ */ new Map();
1645
1736
  if (!requestedByKey.size) {
1646
- return { book };
1737
+ return { access: { channel: "qr", scanned } };
1647
1738
  }
1648
- const requestedSchemas = Array.from(requestedByKey.values());
1649
- const assertAllBooked = () => {
1650
- for (const schema of requestedSchemas) {
1651
- if (!book.has(accountKey(schema.hwkChain, schema.path))) {
1652
- throw (0, import_hwk_adapter_core3.createHwkError)({
1653
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1654
- message: `Keystone did not return the requested derivation path (${schema.path})`
1655
- });
1656
- }
1657
- }
1658
- };
1659
1739
  const operation = (0, import_hwk_adapter_core3.isHardwareOperationId)(params.operationId) ? this._operations.find(params.operationId) : void 0;
1660
1740
  const operationRoute = operation ? this._operationRoutes.get(operation.connectId) : void 0;
1661
1741
  const routedToQr = operationRoute?.operationId === operation?.operationId && operationRoute?.connectionType === "qr";
@@ -1664,45 +1744,23 @@ var KeystoneAdapter = class _KeystoneAdapter {
1664
1744
  _KeystoneAdapter._throwIfAborted(signal);
1665
1745
  }
1666
1746
  if (this._forcedTransport !== "qr" && !routedToQr && record?.usbSessionId) {
1667
- const bundleSessionId = record.usbSessionId;
1668
- const assertBundleSession = () => {
1669
- if (record?.usbSessionId !== bundleSessionId) {
1670
- throw (0, import_hwk_adapter_core3.createHwkError)({
1671
- code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
1672
- message: "Keystone USB connection was lost during account export"
1673
- });
1674
- }
1747
+ return {
1748
+ access: { channel: "usb", usbSessionId: record.usbSessionId },
1749
+ masterFingerprint: record.masterFingerprint
1675
1750
  };
1676
- for (const schema of requestedSchemas) {
1677
- if (!book.has(accountKey(schema.hwkChain, schema.path))) {
1678
- assertBundleSession();
1679
- const synced = await this._fetchAccount(
1680
- connectId,
1681
- deviceId,
1682
- schema.hwkChain,
1683
- schema.path,
1684
- signal,
1685
- book
1686
- );
1687
- record = synced.record;
1688
- assertBundleSession();
1689
- }
1690
- }
1691
- assertAllBooked();
1692
- return { book, masterFingerprint: record.masterFingerprint };
1693
1751
  }
1694
- if (this._forcedTransport === "usb") {
1752
+ if (this._forcedTransport === "usb" && !routedToQr) {
1695
1753
  throw (0, import_hwk_adapter_core3.createHwkError)({
1696
1754
  code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
1697
1755
  message: "USB channel is not connected for this Keystone wallet"
1698
1756
  });
1699
1757
  }
1700
- const schemas = requestedSchemas;
1758
+ const schemas = Array.from(requestedByKey.values());
1701
1759
  const requestUr = this.urEngine.buildKeyDerivationRequest({
1702
1760
  schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1703
1761
  origin: this._origin
1704
1762
  });
1705
- const responseUr = await this._requestQrDisplayAndAwaitResponse(
1763
+ const responseUr = await this._requestQrAndAwaitResponse(
1706
1764
  record ? toDeviceInfo(record) : placeholderDeviceInfo(),
1707
1765
  { ...requestUr, animated: false },
1708
1766
  signal
@@ -1710,22 +1768,41 @@ var KeystoneAdapter = class _KeystoneAdapter {
1710
1768
  _KeystoneAdapter._throwIfAborted(signal);
1711
1769
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1712
1770
  this._assertParsedIdentity(parsed, target);
1713
- record = this._upsertDeviceRecord(parsed);
1714
- const requestedChainByPath = new Map(
1715
- schemas.map((schema) => [normalizePath(schema.path), schema.hwkChain])
1716
- );
1717
- for (const account of parsed.accounts) {
1718
- const normalizedPath = normalizePath(account.path);
1719
- const hwkChain = requestedChainByPath.get(normalizedPath) ?? inferHwkChainFromPath(normalizedPath);
1720
- if (hwkChain) {
1721
- book.set(accountKey(hwkChain, normalizedPath), { ...account, hwkChain });
1722
- }
1771
+ for (const schema of schemas) {
1772
+ scanned.set(accountKey(schema.hwkChain, schema.path), {
1773
+ ...requireExportedPath(parsed, schema.path),
1774
+ hwkChain: schema.hwkChain
1775
+ });
1723
1776
  }
1724
- assertAllBooked();
1725
- return { book, masterFingerprint: record.masterFingerprint };
1777
+ record = this._upsertDeviceRecord(parsed);
1778
+ return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1726
1779
  });
1727
1780
  }
1728
- /** Resolve the wallet's master fingerprint from the connectId and/or deviceId the caller passed. */
1781
+ /**
1782
+ * A positional wallet id and an operation id must name the same wallet: otherwise the call
1783
+ * would run on the operation's wallet while the caller files the result under the other one.
1784
+ * Ids that do not carry a master fingerprint cannot be compared and pass through.
1785
+ */
1786
+ _resolveOperationTarget(positionalTargetId, operationId) {
1787
+ const target = (0, import_hwk_adapter_core3.resolveHardwareOperationTarget)(
1788
+ positionalTargetId,
1789
+ operationId,
1790
+ "keystone"
1791
+ );
1792
+ if (!target.success || !operationId || !positionalTargetId || (0, import_hwk_adapter_core3.isHardwareOperationId)(positionalTargetId)) {
1793
+ return target;
1794
+ }
1795
+ const operation = this._operations.find(operationId);
1796
+ const positionalMfp = keystoneMfpFromIdentifier(positionalTargetId);
1797
+ const operationMfp = operation ? keystoneMfpFromIdentifier(operation.connectId) : void 0;
1798
+ if (positionalMfp && operationMfp && positionalMfp !== operationMfp) {
1799
+ return (0, import_hwk_adapter_core3.failure)(
1800
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1801
+ "Keystone connectId and operationId name different wallets"
1802
+ );
1803
+ }
1804
+ return target;
1805
+ }
1729
1806
  _resolveTarget(connectId, deviceId) {
1730
1807
  const resolvedConnectId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? this._operations.resolve(connectId).connectId : connectId;
1731
1808
  const identifiers = [deviceId, resolvedConnectId].filter(
@@ -1755,7 +1832,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1755
1832
  if (expected.expectedMasterFingerprint && parsed.masterFingerprint !== expected.expectedMasterFingerprint) {
1756
1833
  throw (0, import_hwk_adapter_core3.createHwkError)({
1757
1834
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1758
- message: `Connected Keystone wallet (mfp ${parsed.masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1835
+ // The master fingerprint identifies the wallet; keep it out of messages that reach logs.
1836
+ message: "Connected Keystone wallet does not match the requested wallet"
1759
1837
  });
1760
1838
  }
1761
1839
  }
@@ -1785,7 +1863,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1785
1863
  * Opens a permitted USB Keystone and takes its mfp as the wallet identity. A known wallet gains
1786
1864
  * USB in place (`device-changed`); an unseen one becomes USB-only.
1787
1865
  */
1788
- async _connectUsb(expected, searchTargetId, signal) {
1866
+ async _connectUsb(connector, expected, searchTargetId, signal) {
1789
1867
  if (this._pendingUsbTeardowns > 0 || this._abandonedUsbConnects > 0) {
1790
1868
  return (0, import_hwk_adapter_core3.failure)(
1791
1869
  import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal,
@@ -1798,28 +1876,33 @@ var KeystoneAdapter = class _KeystoneAdapter {
1798
1876
  abandoned = true;
1799
1877
  this._abandonedUsbConnects += 1;
1800
1878
  };
1801
- signal?.addEventListener("abort", onAbort, { once: true });
1879
+ signal.addEventListener("abort", onAbort, { once: true });
1802
1880
  const pending = this._usbConnectTail.then(async () => {
1803
1881
  _KeystoneAdapter._throwIfAborted(signal);
1804
- return this._connectUsbExclusive(expected, searchTargetId, signal);
1882
+ if (this._unsettledUsbOperations.size > 0) {
1883
+ return (0, import_hwk_adapter_core3.failure)(
1884
+ import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal,
1885
+ "Keystone USB is still finishing an earlier request"
1886
+ );
1887
+ }
1888
+ const releaseConnect = this._retainUsbOperation("connect");
1889
+ try {
1890
+ return await this._connectUsbExclusive(connector, expected, searchTargetId, signal);
1891
+ } finally {
1892
+ releaseConnect();
1893
+ }
1805
1894
  });
1806
1895
  const settled = pending.finally(() => {
1807
- signal?.removeEventListener("abort", onAbort);
1896
+ signal.removeEventListener("abort", onAbort);
1808
1897
  if (abandoned) this._abandonedUsbConnects -= 1;
1809
1898
  });
1810
1899
  this._usbConnectTail = settled.then(
1811
1900
  () => void 0,
1812
1901
  () => void 0
1813
1902
  );
1814
- return signal ? _KeystoneAdapter._abortable(signal, settled) : settled;
1903
+ return _KeystoneAdapter._abortable(signal, settled);
1815
1904
  }
1816
- async _connectUsbExclusive(expected, searchTargetId, signal) {
1817
- if (!this._usbConnector) {
1818
- return (0, import_hwk_adapter_core3.failure)(
1819
- import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
1820
- "No USB connector configured for this Keystone adapter"
1821
- );
1822
- }
1905
+ async _connectUsbExclusive(connector, expected, searchTargetId, signal) {
1823
1906
  let sessionId;
1824
1907
  try {
1825
1908
  let connectTarget = { type: "default" };
@@ -1831,7 +1914,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
1831
1914
  deviceIdentity: expected.expectedMasterFingerprint
1832
1915
  };
1833
1916
  }
1834
- const connector = this._usbConnector;
1835
1917
  const session = await (connector.connectTarget ? connector.connectTarget(connectTarget) : connector.connect(searchTargetId ?? expected.expectedMasterFingerprint));
1836
1918
  sessionId = session.sessionId;
1837
1919
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1845,16 +1927,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
1845
1927
  });
1846
1928
  }
1847
1929
  const masterFingerprint = mfpValue.toLowerCase();
1848
- if (expected.expectedMasterFingerprint && masterFingerprint !== expected.expectedMasterFingerprint) {
1849
- throw (0, import_hwk_adapter_core3.createHwkError)({
1850
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1851
- message: `Connected Keystone wallet (mfp ${masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1852
- });
1853
- }
1930
+ this._assertParsedIdentity({ masterFingerprint, accounts: [] }, expected);
1854
1931
  const previousUsbSessionId = this._devices.get(masterFingerprint)?.usbSessionId;
1855
1932
  if (previousUsbSessionId && previousUsbSessionId !== session.sessionId) {
1856
1933
  try {
1857
- await this._usbConnector.disconnect(previousUsbSessionId);
1934
+ await connector.disconnect(previousUsbSessionId);
1858
1935
  } catch {
1859
1936
  }
1860
1937
  }
@@ -1874,7 +1951,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1874
1951
  } catch (err) {
1875
1952
  if (sessionId) {
1876
1953
  try {
1877
- await this._usbConnector.disconnect(sessionId);
1954
+ await connector.disconnect(sessionId);
1878
1955
  } catch {
1879
1956
  }
1880
1957
  }
@@ -1913,14 +1990,21 @@ var KeystoneAdapter = class _KeystoneAdapter {
1913
1990
  }
1914
1991
  }
1915
1992
  if (!availableDevices.length) {
1993
+ const record = options?.waitForReenumeration ? this._devices.get(expectedMasterFingerprint) : void 0;
1994
+ if (record) record.hadUsbSession = false;
1916
1995
  if (this._forcedTransport === "usb" && lastSearchError) {
1917
1996
  throw lastSearchError instanceof Error ? lastSearchError : new Error(String(lastSearchError));
1918
1997
  }
1919
1998
  return void 0;
1920
1999
  }
1921
- const attached = await this._connectUsb({ expectedMasterFingerprint }, void 0, signal);
2000
+ const attached = await this._connectUsb(
2001
+ this._usbConnector,
2002
+ { expectedMasterFingerprint },
2003
+ void 0,
2004
+ signal
2005
+ );
1922
2006
  _KeystoneAdapter._throwIfAborted(signal);
1923
- if (!attached.success && attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal) {
2007
+ if (!attached.success && (attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal || attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceOneDeviceOnly)) {
1924
2008
  throw (0, import_hwk_adapter_core3.createHwkError)({
1925
2009
  ...attached.payload,
1926
2010
  message: attached.payload.error
@@ -1929,8 +2013,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1929
2013
  return attached.success ? this._devices.get(expectedMasterFingerprint) : void 0;
1930
2014
  }
1931
2015
  /**
1932
- * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session fails closed;
1933
- * otherwise a failed USB reattach leaves the call on QR.
2016
+ * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
2017
+ * and fails closed if that fails; otherwise a failed USB reattach leaves the call on QR.
1934
2018
  */
1935
2019
  async _resolveUr(record, requestUr, animated, operationId, signal, operationName) {
1936
2020
  const releaseOperationRetention = (0, import_hwk_adapter_core3.isHardwareOperationId)(operationId) ? this._operations.retain(operationId) : void 0;
@@ -1961,7 +2045,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1961
2045
  }
1962
2046
  interactionRoute = route;
1963
2047
  }
1964
- if (!interactionRoute && !this._forcedTransport && record && !record.usbSessionId && this._usbConnector) {
2048
+ if (!interactionRoute && this._forcedTransport !== "qr" && record && !record.usbSessionId && this._usbConnector) {
1965
2049
  record = await this._tryUsbAttach(signal, record.masterFingerprint, {
1966
2050
  waitForReenumeration: record.hadUsbSession
1967
2051
  }) ?? record;
@@ -1980,9 +2064,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
1980
2064
  message: "USB channel is not connected for this Keystone wallet"
1981
2065
  });
1982
2066
  }
1983
- const result = await this._callUsbConnector(
2067
+ const result = await this._callUsbResolveUr(
2068
+ this._usbConnector,
1984
2069
  record.usbSessionId,
1985
- "resolveUr",
1986
2070
  requestUr,
1987
2071
  signal
1988
2072
  );
@@ -1992,11 +2076,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1992
2076
  if (usbErrorCode === import_hwk_adapter_core3.HardwareErrorCode.PayloadTooLarge && usbErrorOrigin !== "device") {
1993
2077
  if (!interactionRoute && !this._forcedTransport) {
1994
2078
  const displayDevice2 = toDeviceInfo(record);
1995
- return this._requestQrDisplayAndAwaitResponse(
1996
- displayDevice2,
1997
- { ...requestUr, animated },
1998
- signal
1999
- );
2079
+ return this._requestQrAndAwaitResponse(displayDevice2, { ...requestUr, animated }, signal);
2000
2080
  }
2001
2081
  throw usbError;
2002
2082
  }
@@ -2007,6 +2087,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2007
2087
  this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
2008
2088
  }
2009
2089
  record.usbSessionId = void 0;
2090
+ this.emitter.emit(import_hwk_adapter_core3.DEVICE.CHANGED, { type: import_hwk_adapter_core3.DEVICE.CHANGED, payload: toDeviceInfo(record) });
2010
2091
  if (interactionRoute) {
2011
2092
  throw this._endDisconnectedOperation(
2012
2093
  interactionRoute.operationId,
@@ -2024,11 +2105,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
2024
2105
  });
2025
2106
  }
2026
2107
  }
2108
+ if (operationName && usbError.replyUnreadable === true) {
2109
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2110
+ code: usbErrorCode ?? import_hwk_adapter_core3.HardwareErrorCode.UnknownError,
2111
+ message: `Keystone ${operationName} may have completed but its reply could not be read`,
2112
+ origin: "device",
2113
+ recovery: { scope: "unknown" },
2114
+ params: (0, import_hwk_adapter_core3.operationMayHaveCompletedParams)(operationName)
2115
+ });
2116
+ }
2027
2117
  throw usbError;
2028
2118
  }
2029
2119
  const displayDevice = record ? toDeviceInfo(record) : placeholderDeviceInfo();
2030
2120
  try {
2031
- return await this._requestQrDisplayAndAwaitResponse(
2121
+ return await this._requestQrAndAwaitResponse(
2032
2122
  displayDevice,
2033
2123
  { ...requestUr, animated },
2034
2124
  signal
@@ -2058,35 +2148,41 @@ var KeystoneAdapter = class _KeystoneAdapter {
2058
2148
  });
2059
2149
  }
2060
2150
  /**
2061
- * Fetches one account's key material for this operation only; `book` reuses earlier fetches. A
2062
- * failed USB export ends the operation without replaying or switching transports.
2151
+ * Fetches one account's key material. An all-network QR item takes it from the bundle's scan; a
2152
+ * USB item asks the device on the bundle's session. A failed USB export ends the operation
2153
+ * without replaying or switching transports.
2063
2154
  */
2064
- async _fetchAccount(connectId, deviceId, hwkChain, syncPath, signal, book) {
2155
+ async _fetchAccount(connectId, deviceId, hwkChain, syncPath, signal, bundle) {
2065
2156
  const target = this._resolveTarget(connectId, deviceId);
2157
+ if (bundle?.channel === "qr") {
2158
+ const scanned = bundle.scanned.get(accountKey(hwkChain, syncPath));
2159
+ if (!target.record || !scanned) {
2160
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2161
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2162
+ message: `Keystone did not return the requested derivation path (${syncPath})`
2163
+ });
2164
+ }
2165
+ return { record: target.record, account: scanned };
2166
+ }
2167
+ if (bundle?.channel === "usb" && target.record?.usbSessionId !== bundle.usbSessionId) {
2168
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2169
+ code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
2170
+ message: "Keystone USB connection was lost during the bundle"
2171
+ });
2172
+ }
2066
2173
  const operationConnectionType = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? this._operations.resolve(connectId).connectionType : void 0;
2067
- const key = accountKey(hwkChain, syncPath);
2068
2174
  let existingRecord = target.record;
2069
2175
  if (!existingRecord) {
2070
2176
  existingRecord = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2071
2177
  _KeystoneAdapter._throwIfAborted(signal);
2072
2178
  }
2073
- const booked = book?.get(key);
2074
- if (existingRecord && booked) {
2075
- return { record: existingRecord, account: booked };
2076
- }
2077
- if (!operationConnectionType && existingRecord && !existingRecord.usbSessionId && this._forcedTransport === "usb") {
2078
- await this._tryUsbAttach(signal, existingRecord.masterFingerprint, {
2079
- waitForReenumeration: existingRecord.hadUsbSession
2080
- });
2081
- _KeystoneAdapter._throwIfAborted(signal);
2082
- existingRecord = this._devices.get(existingRecord.masterFingerprint) ?? existingRecord;
2083
- }
2084
- const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2179
+ const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2085
2180
  const schemas = [keySchema(hwkChain, syncPath)];
2086
2181
  const requestUr = this.urEngine.buildKeyDerivationRequest({ schemas, origin: this._origin });
2087
2182
  const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
2088
2183
  _KeystoneAdapter._throwIfAborted(signal);
2089
2184
  const parsed = this.urEngine.parseAccountResponse(responseUr);
2185
+ const account = requireExportedPath(parsed, syncPath);
2090
2186
  let record;
2091
2187
  if (useSinglePathUsbExport && existingRecord) {
2092
2188
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
@@ -2102,27 +2198,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2102
2198
  viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
2103
2199
  });
2104
2200
  }
2105
- const account = parsed.accounts.find((a) => normalizePath(a.path) === syncPath);
2106
- if (!account) {
2107
- throw (0, import_hwk_adapter_core3.createHwkError)({
2108
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2109
- message: `Keystone did not return the requested derivation path (${syncPath})`
2110
- });
2111
- }
2112
- const entry = { ...account, hwkChain };
2113
- if (book) {
2114
- for (const returned of parsed.accounts) {
2115
- const returnedChain = inferHwkChainFromPath(returned.path);
2116
- if (returnedChain) {
2117
- book.set(accountKey(returnedChain, returned.path), {
2118
- ...returned,
2119
- hwkChain: returnedChain
2120
- });
2121
- }
2122
- }
2123
- book.set(key, entry);
2124
- }
2125
- return { record, account: entry };
2201
+ return { record, account: { ...account, hwkChain } };
2126
2202
  }
2127
2203
  /**
2128
2204
  * Resolves which wallet is attached, without a per-path account. `CHAIN_FINGERPRINT_PATHS.evm` is
@@ -2144,7 +2220,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
2144
2220
  });
2145
2221
  const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2146
2222
  _KeystoneAdapter._throwIfAborted(signal);
2147
- return { record: this._upsertDeviceRecord(this.urEngine.parseAccountResponse(responseUr)) };
2223
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
2224
+ requireExportedPath(parsed, normalizePath(accountPath));
2225
+ return { record: this._upsertDeviceRecord(parsed) };
2148
2226
  }
2149
2227
  /**
2150
2228
  * The operation owning the running job, so a mid-call UI request can name it. Unpinned jobs map
@@ -2170,7 +2248,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2170
2248
  * a cancel reach the wait before the QR timeout.
2171
2249
  */
2172
2250
  async _awaitQrResponse(requestType, pending, signal) {
2173
- if (!signal) return pending;
2174
2251
  let settled = false;
2175
2252
  const onAbort = () => {
2176
2253
  if (!settled) this._uiRegistry.cancel(requestType);
@@ -2179,55 +2256,50 @@ var KeystoneAdapter = class _KeystoneAdapter {
2179
2256
  else signal.addEventListener("abort", onAbort, { once: true });
2180
2257
  try {
2181
2258
  return await pending;
2259
+ } catch (error) {
2260
+ const reason = signal.reason;
2261
+ if (signal.aborted && reason?.code === import_hwk_adapter_core3.HardwareErrorCode.OperationEnded) throw signal.reason;
2262
+ throw error;
2182
2263
  } finally {
2183
2264
  settled = true;
2184
2265
  signal.removeEventListener("abort", onAbort);
2185
2266
  }
2186
2267
  }
2187
- async _requestQrDisplayAndAwaitResponse(device, data, signal) {
2268
+ /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
2269
+ async _requestQrAndAwaitResponse(device, data, signal) {
2270
+ const requestType = data ? import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY : import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN;
2188
2271
  const operationId = this._activeOperationId();
2189
- const waitPromise = this._uiRegistry.wait(
2190
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2191
- { timeoutMs: this._qrTimeoutMs, operationId }
2192
- );
2193
- this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY, {
2194
- type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2195
- payload: { device, data, operationId }
2196
- });
2197
- const response = await this._awaitQrResponse(
2198
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2199
- waitPromise,
2200
- signal
2201
- );
2202
- return { urType: response.urType, urData: response.urData };
2203
- }
2204
- async _requestQrScanAndAwaitResponse(device, signal) {
2205
- const operationId = this._activeOperationId();
2206
- const waitPromise = this._uiRegistry.wait(
2207
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN,
2208
- { timeoutMs: this._qrTimeoutMs, operationId }
2209
- );
2210
- this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN, {
2211
- type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN,
2212
- payload: { device, operationId }
2213
- });
2214
- const response = await this._awaitQrResponse(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN, waitPromise, signal);
2215
- return { urType: response.urType, urData: response.urData };
2216
- }
2217
- async _callUsbConnector(sessionId, method, params, signal) {
2218
- if (!this._usbConnector) {
2219
- throw (0, import_hwk_adapter_core3.createHwkError)({
2220
- code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
2221
- message: "No USB connector configured for this Keystone adapter"
2272
+ const release = operationId ? this._operations.retain(operationId) : void 0;
2273
+ try {
2274
+ const waitPromise = this._uiRegistry.wait(requestType, {
2275
+ timeoutMs: this._qrTimeoutMs,
2276
+ operationId
2222
2277
  });
2278
+ if (data) {
2279
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY, {
2280
+ type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2281
+ payload: { device, data, operationId }
2282
+ });
2283
+ } else {
2284
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN, {
2285
+ type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN,
2286
+ payload: { device, operationId }
2287
+ });
2288
+ }
2289
+ const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2290
+ return { urType: response.urType, urData: response.urData };
2291
+ } finally {
2292
+ release?.();
2223
2293
  }
2294
+ }
2295
+ async _callUsbResolveUr(connector, sessionId, requestUr, signal) {
2224
2296
  if (this._pendingUsbTeardowns > 0 || this._unsettledUsbOperations.size > 0) {
2225
2297
  throw (0, import_hwk_adapter_core3.createHwkError)({
2226
2298
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal,
2227
- message: `Keystone USB is busy while calling ${method}`
2299
+ message: "Keystone USB is busy while calling resolveUr"
2228
2300
  });
2229
2301
  }
2230
- if (signal?.aborted) {
2302
+ if (signal.aborted) {
2231
2303
  throw signal.reason instanceof Error ? signal.reason : (0, import_hwk_adapter_core3.createHwkError)({
2232
2304
  code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
2233
2305
  message: "User aborted operation"
@@ -2236,12 +2308,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2236
2308
  const releaseOperation = this._retainUsbOperation(`call:${sessionId}`);
2237
2309
  let rawCall;
2238
2310
  try {
2239
- rawCall = this._usbConnector.call(sessionId, method, params).finally(releaseOperation);
2311
+ rawCall = connector.call(sessionId, "resolveUr", requestUr).finally(releaseOperation);
2240
2312
  } catch (error) {
2241
2313
  releaseOperation();
2242
2314
  throw error;
2243
2315
  }
2244
- return signal ? _KeystoneAdapter._abortable(signal, rawCall) : rawCall;
2316
+ return _KeystoneAdapter._abortable(signal, rawCall);
2245
2317
  }
2246
2318
  _runUsbTeardown(task) {
2247
2319
  const previous = this._usbTeardownTail;
@@ -2303,6 +2375,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
2303
2375
  );
2304
2376
  });
2305
2377
  }
2378
+ /** Settles with `signal`'s reason once it aborts; a later outcome of `promise` is dropped. */
2379
+ static _untilAborted(signal, promise) {
2380
+ promise.catch(() => void 0);
2381
+ if (signal.aborted) return Promise.reject(signal.reason);
2382
+ return new Promise((resolve, reject) => {
2383
+ const onAbort = () => reject(signal.reason);
2384
+ signal.addEventListener("abort", onAbort, { once: true });
2385
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort)).catch(() => void 0);
2386
+ });
2387
+ }
2306
2388
  static _throwIfAborted(signal) {
2307
2389
  if (signal?.aborted) {
2308
2390
  throw signal.reason instanceof Error ? signal.reason : new Error("Operation aborted");