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

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.mjs CHANGED
@@ -5,7 +5,11 @@ import bs58check from "bs58check";
5
5
  import * as bitcoin from "bitcoinjs-lib";
6
6
  import HDKey from "hdkey";
7
7
  import { parse as uuidParse, stringify as uuidStringify } from "uuid";
8
- import { parseWalletMasterFingerprint } from "@onekeyfe/hwk-adapter-core";
8
+ import {
9
+ HardwareErrorCode,
10
+ createHwkError,
11
+ parseWalletMasterFingerprint
12
+ } from "@onekeyfe/hwk-adapter-core";
9
13
 
10
14
  // src/urEngine/TronSignRequest.ts
11
15
  import {
@@ -172,8 +176,19 @@ function toParsedAccount(key) {
172
176
  name: key.name
173
177
  };
174
178
  }
179
+ var BIP32_HARDENED_OFFSET = 2147483648;
175
180
  function relativeHdPath(relativeDerivePath) {
176
- return `m/${relativeDerivePath.replace(/^m\//i, "")}`;
181
+ const segments = relativeDerivePath.replace(/^m\//i, "").split("/");
182
+ const valid = segments.every(
183
+ (segment) => /^\d+$/.test(segment) && Number(segment) < BIP32_HARDENED_OFFSET
184
+ );
185
+ if (!valid) {
186
+ throw createHwkError({
187
+ code: HardwareErrorCode.InvalidParams,
188
+ message: `Invalid change/index segments in derivation path (${relativeDerivePath})`
189
+ });
190
+ }
191
+ return `m/${segments.join("/")}`;
177
192
  }
178
193
  var KeystoneUrEngine = class {
179
194
  constructor(origin = "OneKey") {
@@ -400,7 +415,7 @@ import {
400
415
  CHAIN_FINGERPRINT_PATHS,
401
416
  DEVICE,
402
417
  DeviceJobQueue,
403
- HardwareErrorCode,
418
+ HardwareErrorCode as HardwareErrorCode2,
404
419
  MISSING_BIP32_MASTER_FINGERPRINT,
405
420
  OperationRegistry,
406
421
  SDK,
@@ -412,7 +427,7 @@ import {
412
427
  UI_RESPONSE,
413
428
  UiRequestRegistry,
414
429
  createHardwareSearchTargetId,
415
- createHwkError,
430
+ createHwkError as createHwkError2,
416
431
  deriveDeviceFingerprint,
417
432
  ensure0x,
418
433
  failure,
@@ -423,6 +438,7 @@ import {
423
438
  isHardwareOperationId as isHardwareOperationId2,
424
439
  isHwkRecoveryHint,
425
440
  isUserRefusal,
441
+ isWalletSafetyFailure,
426
442
  operationMayHaveCompletedParams,
427
443
  parseBip32MasterFingerprint,
428
444
  parseWalletMasterFingerprint as parseWalletMasterFingerprint3,
@@ -548,11 +564,24 @@ function keystoneCancelQueueKeys(identifiers) {
548
564
  }
549
565
 
550
566
  // src/adapter/KeystoneAdapter.ts
567
+ function keystoneBtcParamsFailure(params) {
568
+ const { coin, addressIndex, change } = params;
569
+ if (coin !== void 0 && !["btc", "bitcoin"].includes(String(coin).toLowerCase())) {
570
+ return failure(
571
+ HardwareErrorCode2.ChainNotSupported,
572
+ `Keystone BTC supports Bitcoin mainnet only, not ${String(coin)}`
573
+ );
574
+ }
575
+ if (addressIndex !== void 0 || change !== void 0) {
576
+ return failure(
577
+ HardwareErrorCode2.InvalidParams,
578
+ "Keystone BTC takes the full address path; addressIndex and change are not supported"
579
+ );
580
+ }
581
+ return void 0;
582
+ }
551
583
  var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
552
584
  var KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS = 500;
553
- function resolveHardwareOperationTarget(positionalTargetId, operationId) {
554
- return resolveGenericHardwareOperationTarget(positionalTargetId, operationId, "keystone");
555
- }
556
585
  function keySchema(chain, path) {
557
586
  return { path, curve: chain === "sol" ? "ed25519" : "secp256k1" };
558
587
  }
@@ -563,7 +592,7 @@ function waitForKeystoneUsbReattachProbe() {
563
592
  }
564
593
  function buildCancelledFailure(signal) {
565
594
  const reason = signal.reason;
566
- const code = typeof reason?.code === "number" ? reason.code : HardwareErrorCode.UserAborted;
595
+ const code = typeof reason?.code === "number" ? reason.code : HardwareErrorCode2.UserAborted;
567
596
  const message = typeof reason?.message === "string" ? reason.message : "";
568
597
  return failure(code, message || "All-network get-address cancelled");
569
598
  }
@@ -573,9 +602,16 @@ var BIP44_COIN_TYPE_TO_CHAIN = {
573
602
  501: "sol",
574
603
  195: "tron"
575
604
  };
576
- function inferHwkChainFromPath(path) {
605
+ function hasChainCoinType(chain, path) {
577
606
  const match = normalizePath(path).match(/^m\/\d+'\/(\d+)'/);
578
- return match ? BIP44_COIN_TYPE_TO_CHAIN[Number(match[1])] : void 0;
607
+ return Boolean(match) && BIP44_COIN_TYPE_TO_CHAIN[Number(match?.[1])] === chain;
608
+ }
609
+ function coinTypeFailure(chain, path) {
610
+ if (hasChainCoinType(chain, path)) return void 0;
611
+ return failure(
612
+ HardwareErrorCode2.InvalidParams,
613
+ `Keystone ${chain} needs a path with its own BIP44 coin type, not ${path}`
614
+ );
579
615
  }
580
616
  var KeystoneAdapter = class _KeystoneAdapter {
581
617
  constructor(options) {
@@ -631,18 +667,30 @@ var KeystoneAdapter = class _KeystoneAdapter {
631
667
  // All-network bundle, dispatched to the per-chain methods below.
632
668
  // ---------------------------------------------------------------------------
633
669
  this.allNetworkGetAddress = async (connectId, deviceId, params) => {
634
- const operationTarget = resolveHardwareOperationTarget(connectId, params.operationId);
670
+ const operationTarget = this._resolveOperationTarget(connectId, params.operationId);
635
671
  if (!operationTarget.success) return operationTarget;
636
672
  const effectiveConnectId = operationTarget.payload.targetId ?? "";
637
673
  const { operationId } = operationTarget.payload;
674
+ const namedWallets = new Set(
675
+ [deviceId, ...params.bundle.map((item) => item.deviceId)].filter(
676
+ (id) => typeof id === "string" && id.length > 0
677
+ )
678
+ );
679
+ if (namedWallets.size > 1) {
680
+ return failure(
681
+ HardwareErrorCode2.InvalidParams,
682
+ "Keystone all-network items name different wallets"
683
+ );
684
+ }
685
+ const [expectedDeviceId = ""] = namedWallets;
638
686
  let cancelScope;
639
687
  try {
640
- const prefetched = await this._prefetchAllNetworkAccounts(effectiveConnectId, deviceId, {
688
+ const prepared = await this._prepareAllNetworkBundle(effectiveConnectId, expectedDeviceId, {
641
689
  ...params,
642
690
  operationId
643
691
  });
644
- const { book } = prefetched;
645
- const itemDeviceId = deviceId || prefetched.masterFingerprint || "";
692
+ const { access } = prepared;
693
+ const itemDeviceId = expectedDeviceId || prepared.masterFingerprint || "";
646
694
  const scope = this._jobQueue.createCancelScope(
647
695
  keystoneQueueKey(effectiveConnectId, itemDeviceId)
648
696
  );
@@ -664,18 +712,22 @@ var KeystoneAdapter = class _KeystoneAdapter {
664
712
  };
665
713
  switch (method) {
666
714
  case "evmGetAddress":
667
- return this.evmGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
715
+ return this.evmGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
668
716
  case "btcGetAddress":
669
- return this.btcGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
670
- case "btcGetPublicKey":
671
- return this.btcGetPublicKey(effectiveConnectId, itemDeviceId, commonArgs, book);
717
+ case "btcGetPublicKey": {
718
+ const btcArgs = {
719
+ ...commonArgs,
720
+ coin: item.coin ?? item.network
721
+ };
722
+ return method === "btcGetAddress" ? this.btcGetAddress(effectiveConnectId, itemDeviceId, btcArgs, access) : this.btcGetPublicKey(effectiveConnectId, itemDeviceId, btcArgs, access);
723
+ }
672
724
  case "solGetAddress":
673
- return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
725
+ return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
674
726
  case "tronGetAddress":
675
- return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
727
+ return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
676
728
  default:
677
729
  return failure(
678
- HardwareErrorCode.MethodNotSupported,
730
+ HardwareErrorCode2.MethodNotSupported,
679
731
  `Unsupported method: ${String(method)}`
680
732
  );
681
733
  }
@@ -696,11 +748,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
696
748
  }
697
749
  });
698
750
  },
699
- // Cancel, refusal or a lost session ends the batch; other per-item
700
- // failures carry on with the next chain.
751
+ // Cancel, refusal, a lost connection or a safety answer (another wallet, a locked
752
+ // device) ends the batch; other per-item failures carry on with the next chain.
701
753
  shouldAbortBundle: (response, { index }) => {
702
754
  const { code } = response.payload ?? {};
703
- return cancelledIndexes.has(index) || isUserRefusal(code) || isConnectionLost(code);
755
+ const usbSessionLost = access?.channel === "usb" && this._resolveTarget(effectiveConnectId, itemDeviceId).record?.usbSessionId !== access.usbSessionId;
756
+ return cancelledIndexes.has(index) || usbSessionLost || isWalletSafetyFailure(code) || isUserRefusal(code) || isConnectionLost(code);
704
757
  }
705
758
  });
706
759
  } catch (err) {
@@ -876,14 +929,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
876
929
  selectedConnectionType = "usb";
877
930
  if (!this._usbConnector) {
878
931
  return failure(
879
- HardwareErrorCode.TransportNotAvailable,
932
+ HardwareErrorCode2.TransportNotAvailable,
880
933
  "No USB connector configured for this Keystone adapter"
881
934
  );
882
935
  }
883
936
  connected = await this._connectUsb({}, searchTargetId, scope.signal);
884
937
  } else if (hasHardwareRuntimeIdPrefix(searchTargetId)) {
885
938
  return failure(
886
- HardwareErrorCode.DeviceNotFound,
939
+ HardwareErrorCode2.DeviceNotFound,
887
940
  "Keystone search target has expired; search for devices again",
888
941
  void 0,
889
942
  void 0,
@@ -896,7 +949,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
896
949
  connected = success(toDeviceInfo(target.record));
897
950
  } else if (!this._usbConnector) {
898
951
  return failure(
899
- HardwareErrorCode.DeviceNotFound,
952
+ HardwareErrorCode2.DeviceNotFound,
900
953
  `Unknown Keystone device search target: ${searchTargetId}`
901
954
  );
902
955
  } else {
@@ -961,7 +1014,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
961
1014
  if (!record) {
962
1015
  return Promise.resolve(
963
1016
  failure(
964
- HardwareErrorCode.DeviceNotFound,
1017
+ HardwareErrorCode2.DeviceNotFound,
965
1018
  `Unknown Keystone device: ${connectId || deviceId}`
966
1019
  )
967
1020
  );
@@ -980,8 +1033,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
980
1033
  return;
981
1034
  }
982
1035
  }
983
- const reason = createHwkError({
984
- code: HardwareErrorCode.UserAborted,
1036
+ const reason = createHwkError2({
1037
+ code: HardwareErrorCode2.UserAborted,
985
1038
  message: "User aborted operation"
986
1039
  });
987
1040
  if (connectId) {
@@ -1002,13 +1055,17 @@ var KeystoneAdapter = class _KeystoneAdapter {
1002
1055
  this._uiRegistry.cancel();
1003
1056
  }
1004
1057
  }
1058
+ /**
1059
+ * Derived from the wallet's master fingerprint, which the caller already holds as deviceId; the
1060
+ * device is never asked. It names the wallet but cannot check which device is attached.
1061
+ */
1005
1062
  getChainFingerprint(connectId, deviceId, chain) {
1006
1063
  try {
1007
1064
  const target = this._resolveTarget(connectId, deviceId);
1008
1065
  const masterFingerprint = target.expectedMasterFingerprint;
1009
1066
  if (!masterFingerprint) {
1010
1067
  return Promise.resolve(
1011
- failure(HardwareErrorCode.DeviceNotFound, "Unknown Keystone wallet identity")
1068
+ failure(HardwareErrorCode2.DeviceNotFound, "Unknown Keystone wallet identity")
1012
1069
  );
1013
1070
  }
1014
1071
  return Promise.resolve(
@@ -1064,18 +1121,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1064
1121
  // ---------------------------------------------------------------------------
1065
1122
  // EVM
1066
1123
  // ---------------------------------------------------------------------------
1067
- async evmGetAddress(connectIdArg, deviceIdArg, params, book) {
1068
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1124
+ async evmGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1125
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1069
1126
  if (!operationTarget.success) return operationTarget;
1070
1127
  const connectId = operationTarget.payload.targetId;
1071
1128
  const deviceId = deviceIdArg ?? void 0;
1072
- if (!params) return failure(HardwareErrorCode.InvalidParams, "evmGetAddress requires params");
1129
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "evmGetAddress requires params");
1073
1130
  if (!params.path)
1074
- return failure(HardwareErrorCode.InvalidParams, "evmGetAddress requires params.path");
1131
+ return failure(HardwareErrorCode2.InvalidParams, "evmGetAddress requires params.path");
1132
+ const evmCoinTypeFailure = coinTypeFailure("evm", params.path);
1133
+ if (evmCoinTypeFailure) return evmCoinTypeFailure;
1075
1134
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1076
1135
  if (!relativeDerivePath) {
1077
1136
  return failure(
1078
- HardwareErrorCode.InvalidParams,
1137
+ HardwareErrorCode2.InvalidParams,
1079
1138
  "evmGetAddress requires a full leaf path, e.g. m/44'/60'/0'/0/0"
1080
1139
  );
1081
1140
  }
@@ -1086,25 +1145,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
1086
1145
  "evm",
1087
1146
  accountPath,
1088
1147
  signal,
1089
- book
1148
+ bundle
1090
1149
  );
1091
1150
  const address = this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath);
1092
1151
  return success({ address, path: normalizePath(params.path) });
1093
1152
  });
1094
1153
  }
1095
1154
  async evmSignTransaction(connectIdArg, deviceIdArg, params) {
1096
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1155
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1097
1156
  if (!operationTarget.success) return operationTarget;
1098
1157
  const connectId = operationTarget.payload.targetId;
1099
1158
  const deviceId = deviceIdArg ?? void 0;
1100
1159
  if (!params)
1101
- return failure(HardwareErrorCode.InvalidParams, "evmSignTransaction requires params");
1160
+ return failure(HardwareErrorCode2.InvalidParams, "evmSignTransaction requires params");
1102
1161
  if (!params.path) {
1103
- return failure(HardwareErrorCode.InvalidParams, "evmSignTransaction requires params.path");
1162
+ return failure(HardwareErrorCode2.InvalidParams, "evmSignTransaction requires params.path");
1104
1163
  }
1105
1164
  if (!("serializedTx" in params) || typeof params.serializedTx !== "string" || !params.serializedTx) {
1106
1165
  return failure(
1107
- HardwareErrorCode.MethodNotSupported,
1166
+ HardwareErrorCode2.MethodNotSupported,
1108
1167
  "Keystone only signs a fully RLP-serialized transaction (params.serializedTx) \u2014 structured-field signing is not supported"
1109
1168
  );
1110
1169
  }
@@ -1134,14 +1193,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1134
1193
  });
1135
1194
  }
1136
1195
  async evmSignMessage(connectIdArg, deviceIdArg, params) {
1137
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1196
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1138
1197
  if (!operationTarget.success) return operationTarget;
1139
1198
  const connectId = operationTarget.payload.targetId;
1140
1199
  const deviceId = deviceIdArg ?? void 0;
1141
- if (!params) return failure(HardwareErrorCode.InvalidParams, "evmSignMessage requires params");
1200
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "evmSignMessage requires params");
1142
1201
  if (!params.path || params.message === void 0) {
1143
1202
  return failure(
1144
- HardwareErrorCode.InvalidParams,
1203
+ HardwareErrorCode2.InvalidParams,
1145
1204
  "evmSignMessage requires params.path and params.message"
1146
1205
  );
1147
1206
  }
@@ -1166,18 +1225,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
1166
1225
  });
1167
1226
  }
1168
1227
  async evmSignTypedData(connectIdArg, deviceIdArg, params) {
1169
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1228
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1170
1229
  if (!operationTarget.success) return operationTarget;
1171
1230
  const connectId = operationTarget.payload.targetId;
1172
1231
  const deviceId = deviceIdArg ?? void 0;
1173
1232
  if (!params)
1174
- return failure(HardwareErrorCode.InvalidParams, "evmSignTypedData requires params");
1233
+ return failure(HardwareErrorCode2.InvalidParams, "evmSignTypedData requires params");
1175
1234
  if (!params.path) {
1176
- return failure(HardwareErrorCode.InvalidParams, "evmSignTypedData requires params.path");
1235
+ return failure(HardwareErrorCode2.InvalidParams, "evmSignTypedData requires params.path");
1177
1236
  }
1178
1237
  if (params.mode === "hash") {
1179
1238
  return failure(
1180
- HardwareErrorCode.MethodNotSupported,
1239
+ HardwareErrorCode2.MethodNotSupported,
1181
1240
  "Keystone always displays the full EIP-712 payload for on-device review \u2014 pre-hashed signing is not supported"
1182
1241
  );
1183
1242
  }
@@ -1208,18 +1267,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1208
1267
  // BTC: 44'/49'/84' addresses derive offline from the account xpub; P2TR addresses
1209
1268
  // and structured-field tx signing are unsupported (the host builds a PSBT instead).
1210
1269
  // ---------------------------------------------------------------------------
1211
- async btcGetAddress(connectIdArg, deviceIdArg, params, book) {
1212
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1270
+ async btcGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1271
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1213
1272
  if (!operationTarget.success) return operationTarget;
1214
1273
  const connectId = operationTarget.payload.targetId;
1215
1274
  const deviceId = deviceIdArg ?? void 0;
1216
- if (!params) return failure(HardwareErrorCode.InvalidParams, "btcGetAddress requires params");
1275
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "btcGetAddress requires params");
1217
1276
  if (!params.path)
1218
- return failure(HardwareErrorCode.InvalidParams, "btcGetAddress requires params.path");
1277
+ return failure(HardwareErrorCode2.InvalidParams, "btcGetAddress requires params.path");
1278
+ const btcParamsFailure = keystoneBtcParamsFailure(params);
1279
+ if (btcParamsFailure) return btcParamsFailure;
1219
1280
  const scriptType = btcScriptTypeFromPath(params.path);
1220
1281
  if (!scriptType) {
1221
1282
  return failure(
1222
- HardwareErrorCode.InvalidParams,
1283
+ HardwareErrorCode2.InvalidParams,
1223
1284
  "btcGetAddress requires a path whose purpose is 44'/49'/84'/86' (P2PKH/P2SH-P2WPKH/P2WPKH/P2TR)"
1224
1285
  );
1225
1286
  }
@@ -1233,12 +1294,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
1233
1294
  const { accountPath, relativeDerivePath } = splitAccountPath(normalizedPath);
1234
1295
  if (!relativeDerivePath) {
1235
1296
  return failure(
1236
- HardwareErrorCode.InvalidParams,
1297
+ HardwareErrorCode2.InvalidParams,
1237
1298
  "btcGetAddress requires a full leaf path, e.g. m/84'/0'/0'/0/0"
1238
1299
  );
1239
1300
  }
1240
1301
  if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1241
- return failure(HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1302
+ return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1242
1303
  }
1243
1304
  return this._runJob(connectId, deviceId, async (signal) => {
1244
1305
  const xpub = await this._fetchAccountXpub(
@@ -1247,7 +1308,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1247
1308
  "btc",
1248
1309
  accountPath,
1249
1310
  signal,
1250
- book
1311
+ bundle
1251
1312
  );
1252
1313
  const address = this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType);
1253
1314
  return success({ address, path: normalizedPath });
@@ -1257,23 +1318,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
1257
1318
  * `params.path` must be an account path (`m/84'/0'/0'`), the level Keystone syncs. An xpub is
1258
1319
  * script-type agnostic, so `86'` works here even though `btcGetAddress` rejects it.
1259
1320
  */
1260
- async btcGetPublicKey(connectIdArg, deviceIdArg, params, book) {
1261
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1321
+ async btcGetPublicKey(connectIdArg, deviceIdArg, params, bundle) {
1322
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1262
1323
  if (!operationTarget.success) return operationTarget;
1263
1324
  const connectId = operationTarget.payload.targetId;
1264
1325
  const deviceId = deviceIdArg ?? void 0;
1265
- if (!params) return failure(HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params");
1326
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "btcGetPublicKey requires params");
1266
1327
  if (!params.path)
1267
- return failure(HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params.path");
1328
+ return failure(HardwareErrorCode2.InvalidParams, "btcGetPublicKey requires params.path");
1329
+ const btcParamsFailure = keystoneBtcParamsFailure(params);
1330
+ if (btcParamsFailure) return btcParamsFailure;
1268
1331
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1269
1332
  if (relativeDerivePath) {
1270
1333
  return failure(
1271
- HardwareErrorCode.InvalidParams,
1334
+ HardwareErrorCode2.InvalidParams,
1272
1335
  "btcGetPublicKey requires an account path, e.g. m/84'/0'/0' (not a leaf path)"
1273
1336
  );
1274
1337
  }
1275
1338
  if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1276
- return failure(HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1339
+ return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1277
1340
  }
1278
1341
  return this._runJob(connectId, deviceId, async (signal) => {
1279
1342
  const xpub = await this._fetchAccountXpub(
@@ -1282,7 +1345,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1282
1345
  "btc",
1283
1346
  accountPath,
1284
1347
  signal,
1285
- book
1348
+ bundle
1286
1349
  );
1287
1350
  const meta = this.urEngine.parseXpubMeta(xpub);
1288
1351
  return success({
@@ -1302,17 +1365,17 @@ var KeystoneAdapter = class _KeystoneAdapter {
1302
1365
  );
1303
1366
  }
1304
1367
  async btcSignPsbt(connectIdArg, deviceIdArg, params) {
1305
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1368
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1306
1369
  if (!operationTarget.success) return operationTarget;
1307
1370
  const connectId = operationTarget.payload.targetId;
1308
1371
  const deviceId = deviceIdArg ?? void 0;
1309
- if (!params) return failure(HardwareErrorCode.InvalidParams, "btcSignPsbt requires params");
1372
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "btcSignPsbt requires params");
1310
1373
  if (!params.psbt)
1311
- return failure(HardwareErrorCode.InvalidParams, "btcSignPsbt requires params.psbt");
1374
+ return failure(HardwareErrorCode2.InvalidParams, "btcSignPsbt requires params.psbt");
1312
1375
  if (!params.path)
1313
- return failure(HardwareErrorCode.InvalidParams, "btcSignPsbt requires params.path");
1376
+ return failure(HardwareErrorCode2.InvalidParams, "btcSignPsbt requires params.path");
1314
1377
  if (!isKeystoneSignableBtcAccountPath(splitAccountPath(params.path).accountPath)) {
1315
- return failure(HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1378
+ return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1316
1379
  }
1317
1380
  return this._runJob(connectId, deviceId, async (signal) => {
1318
1381
  const { record } = await this._ensureWalletKnown(connectId, deviceId, "btc", signal);
@@ -1332,21 +1395,21 @@ var KeystoneAdapter = class _KeystoneAdapter {
1332
1395
  });
1333
1396
  }
1334
1397
  async btcSignMessage(connectIdArg, deviceIdArg, params) {
1335
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1398
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1336
1399
  if (!operationTarget.success) return operationTarget;
1337
1400
  const connectId = operationTarget.payload.targetId;
1338
1401
  const deviceId = deviceIdArg ?? void 0;
1339
- if (!params) return failure(HardwareErrorCode.InvalidParams, "btcSignMessage requires params");
1402
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "btcSignMessage requires params");
1340
1403
  if (!params.path || params.message === void 0) {
1341
1404
  return failure(
1342
- HardwareErrorCode.InvalidParams,
1405
+ HardwareErrorCode2.InvalidParams,
1343
1406
  "btcSignMessage requires params.path and params.message"
1344
1407
  );
1345
1408
  }
1346
1409
  const messageHex = params.hex ? stripHex(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1347
1410
  const path = normalizePath(params.path);
1348
1411
  if (!isKeystoneSignableBtcAccountPath(splitAccountPath(path).accountPath)) {
1349
- return failure(HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1412
+ return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1350
1413
  }
1351
1414
  return this._signWithWallet({
1352
1415
  connectId,
@@ -1363,8 +1426,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1363
1426
  toPayload: (sig) => ({ signature: sig.signature })
1364
1427
  });
1365
1428
  }
1429
+ /**
1430
+ * Returns the known master fingerprint for the named wallet without asking the device (a QR
1431
+ * round trip only to repeat it would cost a scan). Use it to name the wallet, for example as a
1432
+ * PSBT xfp, which the device itself checks when signing; it cannot check the attached device.
1433
+ */
1366
1434
  async btcGetMasterFingerprint(connectIdArg, deviceIdArg, paramsArg) {
1367
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, paramsArg?.operationId);
1435
+ const operationTarget = this._resolveOperationTarget(connectIdArg, paramsArg?.operationId);
1368
1436
  if (!operationTarget.success) return operationTarget;
1369
1437
  const connectId = operationTarget.payload.targetId;
1370
1438
  const deviceId = deviceIdArg ?? void 0;
@@ -1376,32 +1444,47 @@ var KeystoneAdapter = class _KeystoneAdapter {
1376
1444
  // ---------------------------------------------------------------------------
1377
1445
  // SOL
1378
1446
  // ---------------------------------------------------------------------------
1379
- async solGetAddress(connectIdArg, deviceIdArg, params, book) {
1380
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1447
+ async solGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1448
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1381
1449
  if (!operationTarget.success) return operationTarget;
1382
1450
  const connectId = operationTarget.payload.targetId;
1383
1451
  const deviceId = deviceIdArg ?? void 0;
1384
- if (!params) return failure(HardwareErrorCode.InvalidParams, "solGetAddress requires params");
1452
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "solGetAddress requires params");
1385
1453
  if (!params.path)
1386
- return failure(HardwareErrorCode.InvalidParams, "solGetAddress requires params.path");
1454
+ return failure(HardwareErrorCode2.InvalidParams, "solGetAddress requires params.path");
1455
+ const solCoinTypeFailure = coinTypeFailure("sol", params.path);
1456
+ if (solCoinTypeFailure) return solCoinTypeFailure;
1387
1457
  const path = normalizePath(params.path);
1458
+ if (!/^m(\/\d+')+$/.test(path)) {
1459
+ return failure(
1460
+ HardwareErrorCode2.InvalidParams,
1461
+ "solGetAddress requires a fully hardened path, e.g. m/44'/501'/0'/0'"
1462
+ );
1463
+ }
1388
1464
  return this._runJob(connectId, deviceId, async (signal) => {
1389
- const { account } = await this._fetchAccount(connectId, deviceId, "sol", path, signal, book);
1465
+ const { account } = await this._fetchAccount(
1466
+ connectId,
1467
+ deviceId,
1468
+ "sol",
1469
+ path,
1470
+ signal,
1471
+ bundle
1472
+ );
1390
1473
  _KeystoneAdapter._throwIfAborted(signal);
1391
1474
  const address = bs58.encode(Buffer.from(account.publicKey, "hex"));
1392
1475
  return success({ address, path });
1393
1476
  });
1394
1477
  }
1395
1478
  async solSignTransaction(connectIdArg, deviceIdArg, params) {
1396
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1479
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1397
1480
  if (!operationTarget.success) return operationTarget;
1398
1481
  const connectId = operationTarget.payload.targetId;
1399
1482
  const deviceId = deviceIdArg ?? void 0;
1400
1483
  if (!params)
1401
- return failure(HardwareErrorCode.InvalidParams, "solSignTransaction requires params");
1484
+ return failure(HardwareErrorCode2.InvalidParams, "solSignTransaction requires params");
1402
1485
  if (!params.path || !params.serializedTx) {
1403
1486
  return failure(
1404
- HardwareErrorCode.InvalidParams,
1487
+ HardwareErrorCode2.InvalidParams,
1405
1488
  "solSignTransaction requires params.path and params.serializedTx"
1406
1489
  );
1407
1490
  }
@@ -1424,14 +1507,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1424
1507
  });
1425
1508
  }
1426
1509
  async solSignMessage(connectIdArg, deviceIdArg, params) {
1427
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1510
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1428
1511
  if (!operationTarget.success) return operationTarget;
1429
1512
  const connectId = operationTarget.payload.targetId;
1430
1513
  const deviceId = deviceIdArg ?? void 0;
1431
- if (!params) return failure(HardwareErrorCode.InvalidParams, "solSignMessage requires params");
1514
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "solSignMessage requires params");
1432
1515
  if (!params.path || !params.message) {
1433
1516
  return failure(
1434
- HardwareErrorCode.InvalidParams,
1517
+ HardwareErrorCode2.InvalidParams,
1435
1518
  "solSignMessage requires params.path and params.message"
1436
1519
  );
1437
1520
  }
@@ -1457,18 +1540,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1457
1540
  // TRON: keystone-sdk-rust layout (tags 5201/5202, firmware >= 2.5.0), not sdk.tron's
1458
1541
  // protobuf module; OneKey Pro's encoding under the same tag is rejected by the firmware.
1459
1542
  // ---------------------------------------------------------------------------
1460
- async tronGetAddress(connectIdArg, deviceIdArg, params, book) {
1461
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1543
+ async tronGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1544
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1462
1545
  if (!operationTarget.success) return operationTarget;
1463
1546
  const connectId = operationTarget.payload.targetId;
1464
1547
  const deviceId = deviceIdArg ?? void 0;
1465
- if (!params) return failure(HardwareErrorCode.InvalidParams, "tronGetAddress requires params");
1548
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "tronGetAddress requires params");
1466
1549
  if (!params.path)
1467
- return failure(HardwareErrorCode.InvalidParams, "tronGetAddress requires params.path");
1550
+ return failure(HardwareErrorCode2.InvalidParams, "tronGetAddress requires params.path");
1551
+ const tronCoinTypeFailure = coinTypeFailure("tron", params.path);
1552
+ if (tronCoinTypeFailure) return tronCoinTypeFailure;
1468
1553
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1469
1554
  if (!relativeDerivePath) {
1470
1555
  return failure(
1471
- HardwareErrorCode.InvalidParams,
1556
+ HardwareErrorCode2.InvalidParams,
1472
1557
  "tronGetAddress requires a full leaf path, e.g. m/44'/195'/0'/0/0"
1473
1558
  );
1474
1559
  }
@@ -1479,25 +1564,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
1479
1564
  "tron",
1480
1565
  accountPath,
1481
1566
  signal,
1482
- book
1567
+ bundle
1483
1568
  );
1484
1569
  const address = this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath);
1485
1570
  return success({ address, path: normalizePath(params.path) });
1486
1571
  });
1487
1572
  }
1488
1573
  async tronSignTransaction(connectIdArg, deviceIdArg, params) {
1489
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1574
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1490
1575
  if (!operationTarget.success) return operationTarget;
1491
1576
  const connectId = operationTarget.payload.targetId;
1492
1577
  const deviceId = deviceIdArg ?? void 0;
1493
1578
  if (!params)
1494
- return failure(HardwareErrorCode.InvalidParams, "tronSignTransaction requires params");
1579
+ return failure(HardwareErrorCode2.InvalidParams, "tronSignTransaction requires params");
1495
1580
  if (!params.path) {
1496
- return failure(HardwareErrorCode.InvalidParams, "tronSignTransaction requires params.path");
1581
+ return failure(HardwareErrorCode2.InvalidParams, "tronSignTransaction requires params.path");
1497
1582
  }
1498
1583
  if (!params.rawTxHex) {
1499
1584
  return failure(
1500
- HardwareErrorCode.InvalidParams,
1585
+ HardwareErrorCode2.InvalidParams,
1501
1586
  "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1502
1587
  );
1503
1588
  }
@@ -1521,20 +1606,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1521
1606
  });
1522
1607
  }
1523
1608
  async tronSignMessage(connectIdArg, deviceIdArg, params) {
1524
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1609
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1525
1610
  if (!operationTarget.success) return operationTarget;
1526
1611
  const connectId = operationTarget.payload.targetId;
1527
1612
  const deviceId = deviceIdArg ?? void 0;
1528
- if (!params) return failure(HardwareErrorCode.InvalidParams, "tronSignMessage requires params");
1613
+ if (!params) return failure(HardwareErrorCode2.InvalidParams, "tronSignMessage requires params");
1529
1614
  if (!params.path) {
1530
- return failure(HardwareErrorCode.InvalidParams, "tronSignMessage requires params.path");
1615
+ return failure(HardwareErrorCode2.InvalidParams, "tronSignMessage requires params.path");
1531
1616
  }
1532
1617
  if (!params.messageHex) {
1533
- return failure(HardwareErrorCode.InvalidParams, "tronSignMessage requires params.messageHex");
1618
+ return failure(HardwareErrorCode2.InvalidParams, "tronSignMessage requires params.messageHex");
1534
1619
  }
1535
1620
  if (params.messageType !== "V2") {
1536
1621
  return failure(
1537
- HardwareErrorCode.MethodNotSupported,
1622
+ HardwareErrorCode2.MethodNotSupported,
1538
1623
  'Keystone signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1539
1624
  );
1540
1625
  }
@@ -1567,19 +1652,19 @@ var KeystoneAdapter = class _KeystoneAdapter {
1567
1652
  return this._errorToFailure(err);
1568
1653
  }
1569
1654
  }
1570
- async _fetchAccountXpub(connectId, deviceId, hwkChain, accountPath, signal, book) {
1655
+ async _fetchAccountXpub(connectId, deviceId, hwkChain, accountPath, signal, bundle) {
1571
1656
  const { account } = await this._fetchAccount(
1572
1657
  connectId,
1573
1658
  deviceId,
1574
1659
  hwkChain,
1575
1660
  accountPath,
1576
1661
  signal,
1577
- book
1662
+ bundle
1578
1663
  );
1579
1664
  _KeystoneAdapter._throwIfAborted(signal);
1580
1665
  if (!account.extendedPublicKey) {
1581
- throw createHwkError({
1582
- code: HardwareErrorCode.MethodNotSupported,
1666
+ throw createHwkError2({
1667
+ code: HardwareErrorCode2.MethodNotSupported,
1583
1668
  message: "Keystone did not return an extended public key for this account path"
1584
1669
  });
1585
1670
  }
@@ -1615,6 +1700,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1615
1700
  const method = item.methodName;
1616
1701
  const hwkChain = getAllNetworkMethodChain(method);
1617
1702
  const path = normalizePath(item.path);
1703
+ if (!hasChainCoinType(hwkChain, path)) return void 0;
1618
1704
  if (hwkChain === "btc" && !isKeystoneSignableBtcAccountPath(splitAccountPath(path).accountPath)) {
1619
1705
  return void 0;
1620
1706
  }
@@ -1631,10 +1717,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1631
1717
  }
1632
1718
  }
1633
1719
  /**
1634
- * QR answers the whole bundle with one request QR and one scan. USB exports one path per
1635
- * request because the device limits that channel.
1720
+ * Picks the bundle's channel. QR answers every item with one request QR and one scan; USB items
1721
+ * each ask the device directly, like other vendors, on the session found here.
1636
1722
  */
1637
- async _prefetchAllNetworkAccounts(connectId, deviceId, params) {
1723
+ async _prepareAllNetworkBundle(connectId, deviceId, params) {
1638
1724
  return this._jobQueue.enqueue(keystoneQueueKey(connectId, deviceId), async (signal) => {
1639
1725
  const target = this._resolveTarget(connectId, deviceId);
1640
1726
  let { record } = target;
@@ -1643,21 +1729,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1643
1729
  const schema = this._allNetworkSyncSchema(item);
1644
1730
  if (schema) requestedByKey.set(accountKey(schema.hwkChain, schema.path), schema);
1645
1731
  }
1646
- const book = /* @__PURE__ */ new Map();
1732
+ const scanned = /* @__PURE__ */ new Map();
1647
1733
  if (!requestedByKey.size) {
1648
- return { book };
1734
+ return { access: { channel: "qr", scanned } };
1649
1735
  }
1650
- const requestedSchemas = Array.from(requestedByKey.values());
1651
- const assertAllBooked = () => {
1652
- for (const schema of requestedSchemas) {
1653
- if (!book.has(accountKey(schema.hwkChain, schema.path))) {
1654
- throw createHwkError({
1655
- code: HardwareErrorCode.DeviceMismatch,
1656
- message: `Keystone did not return the requested derivation path (${schema.path})`
1657
- });
1658
- }
1659
- }
1660
- };
1661
1736
  const operation = isHardwareOperationId2(params.operationId) ? this._operations.find(params.operationId) : void 0;
1662
1737
  const operationRoute = operation ? this._operationRoutes.get(operation.connectId) : void 0;
1663
1738
  const routedToQr = operationRoute?.operationId === operation?.operationId && operationRoute?.connectionType === "qr";
@@ -1666,40 +1741,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
1666
1741
  _KeystoneAdapter._throwIfAborted(signal);
1667
1742
  }
1668
1743
  if (this._forcedTransport !== "qr" && !routedToQr && record?.usbSessionId) {
1669
- const bundleSessionId = record.usbSessionId;
1670
- const assertBundleSession = () => {
1671
- if (record?.usbSessionId !== bundleSessionId) {
1672
- throw createHwkError({
1673
- code: HardwareErrorCode.TransportNotAvailable,
1674
- message: "Keystone USB connection was lost during account export"
1675
- });
1676
- }
1744
+ return {
1745
+ access: { channel: "usb", usbSessionId: record.usbSessionId },
1746
+ masterFingerprint: record.masterFingerprint
1677
1747
  };
1678
- for (const schema of requestedSchemas) {
1679
- if (!book.has(accountKey(schema.hwkChain, schema.path))) {
1680
- assertBundleSession();
1681
- const synced = await this._fetchAccount(
1682
- connectId,
1683
- deviceId,
1684
- schema.hwkChain,
1685
- schema.path,
1686
- signal,
1687
- book
1688
- );
1689
- record = synced.record;
1690
- assertBundleSession();
1691
- }
1692
- }
1693
- assertAllBooked();
1694
- return { book, masterFingerprint: record.masterFingerprint };
1695
1748
  }
1696
- if (this._forcedTransport === "usb") {
1697
- throw createHwkError({
1698
- code: HardwareErrorCode.TransportNotAvailable,
1749
+ if (this._forcedTransport === "usb" && !routedToQr) {
1750
+ throw createHwkError2({
1751
+ code: HardwareErrorCode2.TransportNotAvailable,
1699
1752
  message: "USB channel is not connected for this Keystone wallet"
1700
1753
  });
1701
1754
  }
1702
- const schemas = requestedSchemas;
1755
+ const schemas = Array.from(requestedByKey.values());
1703
1756
  const requestUr = this.urEngine.buildKeyDerivationRequest({
1704
1757
  schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1705
1758
  origin: this._origin
@@ -1713,21 +1766,50 @@ var KeystoneAdapter = class _KeystoneAdapter {
1713
1766
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1714
1767
  this._assertParsedIdentity(parsed, target);
1715
1768
  record = this._upsertDeviceRecord(parsed);
1716
- const requestedChainByPath = new Map(
1717
- schemas.map((schema) => [normalizePath(schema.path), schema.hwkChain])
1718
- );
1719
- for (const account of parsed.accounts) {
1720
- const normalizedPath = normalizePath(account.path);
1721
- const hwkChain = requestedChainByPath.get(normalizedPath) ?? inferHwkChainFromPath(normalizedPath);
1722
- if (hwkChain) {
1723
- book.set(accountKey(hwkChain, normalizedPath), { ...account, hwkChain });
1769
+ for (const schema of schemas) {
1770
+ const account = parsed.accounts.find(
1771
+ (returned) => normalizePath(returned.path) === schema.path
1772
+ );
1773
+ if (!account) {
1774
+ throw createHwkError2({
1775
+ code: HardwareErrorCode2.DeviceMismatch,
1776
+ message: `Keystone did not return the requested derivation path (${schema.path})`
1777
+ });
1724
1778
  }
1779
+ scanned.set(accountKey(schema.hwkChain, schema.path), {
1780
+ ...account,
1781
+ hwkChain: schema.hwkChain
1782
+ });
1725
1783
  }
1726
- assertAllBooked();
1727
- return { book, masterFingerprint: record.masterFingerprint };
1784
+ return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1728
1785
  });
1729
1786
  }
1730
1787
  /** Resolve the wallet's master fingerprint from the connectId and/or deviceId the caller passed. */
1788
+ /**
1789
+ * A positional wallet id and an operation id must name the same wallet: otherwise the call
1790
+ * would run on the operation's wallet while the caller files the result under the other one.
1791
+ * Ids that do not carry a master fingerprint cannot be compared and pass through.
1792
+ */
1793
+ _resolveOperationTarget(positionalTargetId, operationId) {
1794
+ const target = resolveGenericHardwareOperationTarget(
1795
+ positionalTargetId,
1796
+ operationId,
1797
+ "keystone"
1798
+ );
1799
+ if (!target.success || !operationId || !positionalTargetId || isHardwareOperationId2(positionalTargetId)) {
1800
+ return target;
1801
+ }
1802
+ const operation = this._operations.find(operationId);
1803
+ const positionalMfp = keystoneMfpFromIdentifier(positionalTargetId);
1804
+ const operationMfp = operation ? keystoneMfpFromIdentifier(operation.connectId) : void 0;
1805
+ if (positionalMfp && operationMfp && positionalMfp !== operationMfp) {
1806
+ return failure(
1807
+ HardwareErrorCode2.InvalidParams,
1808
+ "Keystone connectId and operationId name different wallets"
1809
+ );
1810
+ }
1811
+ return target;
1812
+ }
1731
1813
  _resolveTarget(connectId, deviceId) {
1732
1814
  const resolvedConnectId = isHardwareOperationId2(connectId) ? this._operations.resolve(connectId).connectId : connectId;
1733
1815
  const identifiers = [deviceId, resolvedConnectId].filter(
@@ -1737,14 +1819,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1737
1819
  const fingerprints = identifiers.map((identifier) => keystoneMfpFromIdentifier(identifier));
1738
1820
  const expectedMasterFingerprint = fingerprints[0];
1739
1821
  if (!expectedMasterFingerprint || fingerprints.some((value) => !value)) {
1740
- throw createHwkError({
1741
- code: HardwareErrorCode.DeviceNotFound,
1822
+ throw createHwkError2({
1823
+ code: HardwareErrorCode2.DeviceNotFound,
1742
1824
  message: "Keystone device lookup requires the wallet master fingerprint"
1743
1825
  });
1744
1826
  }
1745
1827
  if (fingerprints.some((value) => value !== expectedMasterFingerprint)) {
1746
- throw createHwkError({
1747
- code: HardwareErrorCode.DeviceMismatch,
1828
+ throw createHwkError2({
1829
+ code: HardwareErrorCode2.DeviceMismatch,
1748
1830
  message: "Keystone connectId and deviceId identify different wallets"
1749
1831
  });
1750
1832
  }
@@ -1755,8 +1837,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1755
1837
  }
1756
1838
  _assertParsedIdentity(parsed, expected) {
1757
1839
  if (expected.expectedMasterFingerprint && parsed.masterFingerprint !== expected.expectedMasterFingerprint) {
1758
- throw createHwkError({
1759
- code: HardwareErrorCode.DeviceMismatch,
1840
+ throw createHwkError2({
1841
+ code: HardwareErrorCode2.DeviceMismatch,
1760
1842
  message: `Connected Keystone wallet (mfp ${parsed.masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1761
1843
  });
1762
1844
  }
@@ -1790,7 +1872,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1790
1872
  async _connectUsb(expected, searchTargetId, signal) {
1791
1873
  if (this._pendingUsbTeardowns > 0 || this._abandonedUsbConnects > 0) {
1792
1874
  return failure(
1793
- HardwareErrorCode.DeviceBusyInternal,
1875
+ HardwareErrorCode2.DeviceBusyInternal,
1794
1876
  "Keystone USB session is being released"
1795
1877
  );
1796
1878
  }
@@ -1818,7 +1900,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1818
1900
  async _connectUsbExclusive(expected, searchTargetId, signal) {
1819
1901
  if (!this._usbConnector) {
1820
1902
  return failure(
1821
- HardwareErrorCode.TransportNotAvailable,
1903
+ HardwareErrorCode2.TransportNotAvailable,
1822
1904
  "No USB connector configured for this Keystone adapter"
1823
1905
  );
1824
1906
  }
@@ -1841,15 +1923,15 @@ var KeystoneAdapter = class _KeystoneAdapter {
1841
1923
  const mfpValue = parseWalletMasterFingerprint3(raw?.masterFingerprint);
1842
1924
  if (!mfpValue) {
1843
1925
  const empty = parseBip32MasterFingerprint(raw?.masterFingerprint) === MISSING_BIP32_MASTER_FINGERPRINT;
1844
- throw createHwkError({
1845
- code: empty ? HardwareErrorCode.DeviceNotInitialized : HardwareErrorCode.DeviceMismatch,
1926
+ throw createHwkError2({
1927
+ code: empty ? HardwareErrorCode2.DeviceNotInitialized : HardwareErrorCode2.DeviceMismatch,
1846
1928
  message: empty ? "Keystone has no wallet yet; it reported an empty master fingerprint" : "Keystone USB did not report a master fingerprint"
1847
1929
  });
1848
1930
  }
1849
1931
  const masterFingerprint = mfpValue.toLowerCase();
1850
1932
  if (expected.expectedMasterFingerprint && masterFingerprint !== expected.expectedMasterFingerprint) {
1851
- throw createHwkError({
1852
- code: HardwareErrorCode.DeviceMismatch,
1933
+ throw createHwkError2({
1934
+ code: HardwareErrorCode2.DeviceMismatch,
1853
1935
  message: `Connected Keystone wallet (mfp ${masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1854
1936
  });
1855
1937
  }
@@ -1915,6 +1997,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1915
1997
  }
1916
1998
  }
1917
1999
  if (!availableDevices.length) {
2000
+ const record = options?.waitForReenumeration ? this._devices.get(expectedMasterFingerprint) : void 0;
2001
+ if (record) record.hadUsbSession = false;
1918
2002
  if (this._forcedTransport === "usb" && lastSearchError) {
1919
2003
  throw lastSearchError instanceof Error ? lastSearchError : new Error(String(lastSearchError));
1920
2004
  }
@@ -1922,8 +2006,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1922
2006
  }
1923
2007
  const attached = await this._connectUsb({ expectedMasterFingerprint }, void 0, signal);
1924
2008
  _KeystoneAdapter._throwIfAborted(signal);
1925
- if (!attached.success && attached.payload.code === HardwareErrorCode.DeviceBusyInternal) {
1926
- throw createHwkError({
2009
+ if (!attached.success && attached.payload.code === HardwareErrorCode2.DeviceBusyInternal) {
2010
+ throw createHwkError2({
1927
2011
  ...attached.payload,
1928
2012
  message: attached.payload.error
1929
2013
  });
@@ -1931,8 +2015,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1931
2015
  return attached.success ? this._devices.get(expectedMasterFingerprint) : void 0;
1932
2016
  }
1933
2017
  /**
1934
- * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session fails closed;
1935
- * otherwise a failed USB reattach leaves the call on QR.
2018
+ * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
2019
+ * and fails closed if that fails; otherwise a failed USB reattach leaves the call on QR.
1936
2020
  */
1937
2021
  async _resolveUr(record, requestUr, animated, operationId, signal, operationName) {
1938
2022
  const releaseOperationRetention = isHardwareOperationId2(operationId) ? this._operations.retain(operationId) : void 0;
@@ -1963,7 +2047,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1963
2047
  }
1964
2048
  interactionRoute = route;
1965
2049
  }
1966
- if (!interactionRoute && !this._forcedTransport && record && !record.usbSessionId && this._usbConnector) {
2050
+ if (!interactionRoute && this._forcedTransport !== "qr" && record && !record.usbSessionId && this._usbConnector) {
1967
2051
  record = await this._tryUsbAttach(signal, record.masterFingerprint, {
1968
2052
  waitForReenumeration: record.hadUsbSession
1969
2053
  }) ?? record;
@@ -1977,8 +2061,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1977
2061
  "Keystone operation USB connection was lost"
1978
2062
  );
1979
2063
  }
1980
- throw createHwkError({
1981
- code: HardwareErrorCode.TransportNotAvailable,
2064
+ throw createHwkError2({
2065
+ code: HardwareErrorCode2.TransportNotAvailable,
1982
2066
  message: "USB channel is not connected for this Keystone wallet"
1983
2067
  });
1984
2068
  }
@@ -1991,7 +2075,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1991
2075
  if (result.success) return result.payload;
1992
2076
  const usbError = rehydrateConnectorError(result.error);
1993
2077
  const { origin: usbErrorOrigin, code: usbErrorCode } = usbError;
1994
- if (usbErrorCode === HardwareErrorCode.PayloadTooLarge && usbErrorOrigin !== "device") {
2078
+ if (usbErrorCode === HardwareErrorCode2.PayloadTooLarge && usbErrorOrigin !== "device") {
1995
2079
  if (!interactionRoute && !this._forcedTransport) {
1996
2080
  const displayDevice2 = toDeviceInfo(record);
1997
2081
  return this._requestQrDisplayAndAwaitResponse(
@@ -2002,7 +2086,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2002
2086
  }
2003
2087
  throw usbError;
2004
2088
  }
2005
- const deviceAnswered = usbErrorOrigin !== void 0 ? usbErrorOrigin === "device" : usbErrorCode === HardwareErrorCode.UserRejected || usbErrorCode === HardwareErrorCode.UserAborted || usbErrorCode === HardwareErrorCode.DeviceLocked || usbErrorCode === HardwareErrorCode.DeviceMismatch;
2089
+ const deviceAnswered = usbErrorOrigin !== void 0 ? usbErrorOrigin === "device" : usbErrorCode === HardwareErrorCode2.UserRejected || usbErrorCode === HardwareErrorCode2.UserAborted || usbErrorCode === HardwareErrorCode2.DeviceLocked || usbErrorCode === HardwareErrorCode2.DeviceMismatch;
2006
2090
  if (!deviceAnswered) {
2007
2091
  const lostSessionId = record.usbSessionId;
2008
2092
  if (lostSessionId) {
@@ -2017,8 +2101,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
2017
2101
  );
2018
2102
  }
2019
2103
  if (operationName) {
2020
- throw createHwkError({
2021
- code: usbErrorCode ?? HardwareErrorCode.TransportError,
2104
+ throw createHwkError2({
2105
+ code: usbErrorCode ?? HardwareErrorCode2.TransportError,
2022
2106
  message: `Keystone ${operationName} may have completed before the USB connection was lost`,
2023
2107
  origin: "transport",
2024
2108
  recovery: { scope: "unknown" },
@@ -2037,9 +2121,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
2037
2121
  );
2038
2122
  } catch (error) {
2039
2123
  const { code, _tag: tag } = error;
2040
- if (operationName && (code === HardwareErrorCode.OperationTimeout || tag === UI_REQUEST_TIMEOUT_TAG)) {
2041
- throw createHwkError({
2042
- code: HardwareErrorCode.OperationTimeout,
2124
+ if (operationName && (code === HardwareErrorCode2.OperationTimeout || tag === UI_REQUEST_TIMEOUT_TAG)) {
2125
+ throw createHwkError2({
2126
+ code: HardwareErrorCode2.OperationTimeout,
2043
2127
  message: `Keystone ${operationName} may have completed before the QR response timed out`,
2044
2128
  recovery: { scope: "unknown" },
2045
2129
  params: operationMayHaveCompletedParams(operationName)
@@ -2052,38 +2136,43 @@ var KeystoneAdapter = class _KeystoneAdapter {
2052
2136
  _endDisconnectedOperation(operationId, message, operationName) {
2053
2137
  this._operations.end(operationId, "disconnect");
2054
2138
  const params = { operationId, reason: "disconnect" };
2055
- return createHwkError({
2056
- code: HardwareErrorCode.OperationEnded,
2139
+ return createHwkError2({
2140
+ code: HardwareErrorCode2.OperationEnded,
2057
2141
  message,
2058
2142
  recovery: operationName ? { scope: "unknown" } : void 0,
2059
2143
  params: operationName ? operationMayHaveCompletedParams(operationName, params) : params
2060
2144
  });
2061
2145
  }
2062
2146
  /**
2063
- * Fetches one account's key material for this operation only; `book` reuses earlier fetches. A
2064
- * failed USB export ends the operation without replaying or switching transports.
2147
+ * Fetches one account's key material. An all-network QR item takes it from the bundle's scan; a
2148
+ * USB item asks the device on the bundle's session. A failed USB export ends the operation
2149
+ * without replaying or switching transports.
2065
2150
  */
2066
- async _fetchAccount(connectId, deviceId, hwkChain, syncPath, signal, book) {
2151
+ async _fetchAccount(connectId, deviceId, hwkChain, syncPath, signal, bundle) {
2067
2152
  const target = this._resolveTarget(connectId, deviceId);
2153
+ if (bundle?.channel === "qr") {
2154
+ const scanned = bundle.scanned.get(accountKey(hwkChain, syncPath));
2155
+ if (!target.record || !scanned) {
2156
+ throw createHwkError2({
2157
+ code: HardwareErrorCode2.DeviceMismatch,
2158
+ message: `Keystone did not return the requested derivation path (${syncPath})`
2159
+ });
2160
+ }
2161
+ return { record: target.record, account: scanned };
2162
+ }
2163
+ if (bundle?.channel === "usb" && target.record?.usbSessionId !== bundle.usbSessionId) {
2164
+ throw createHwkError2({
2165
+ code: HardwareErrorCode2.TransportNotAvailable,
2166
+ message: "Keystone USB connection was lost during the bundle"
2167
+ });
2168
+ }
2068
2169
  const operationConnectionType = isHardwareOperationId2(connectId) ? this._operations.resolve(connectId).connectionType : void 0;
2069
- const key = accountKey(hwkChain, syncPath);
2070
2170
  let existingRecord = target.record;
2071
2171
  if (!existingRecord) {
2072
2172
  existingRecord = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2073
2173
  _KeystoneAdapter._throwIfAborted(signal);
2074
2174
  }
2075
- const booked = book?.get(key);
2076
- if (existingRecord && booked) {
2077
- return { record: existingRecord, account: booked };
2078
- }
2079
- if (!operationConnectionType && existingRecord && !existingRecord.usbSessionId && this._forcedTransport === "usb") {
2080
- await this._tryUsbAttach(signal, existingRecord.masterFingerprint, {
2081
- waitForReenumeration: existingRecord.hadUsbSession
2082
- });
2083
- _KeystoneAdapter._throwIfAborted(signal);
2084
- existingRecord = this._devices.get(existingRecord.masterFingerprint) ?? existingRecord;
2085
- }
2086
- const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2175
+ const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2087
2176
  const schemas = [keySchema(hwkChain, syncPath)];
2088
2177
  const requestUr = this.urEngine.buildKeyDerivationRequest({ schemas, origin: this._origin });
2089
2178
  const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
@@ -2092,8 +2181,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
2092
2181
  let record;
2093
2182
  if (useSinglePathUsbExport && existingRecord) {
2094
2183
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
2095
- throw createHwkError({
2096
- code: HardwareErrorCode.DeviceMismatch,
2184
+ throw createHwkError2({
2185
+ code: HardwareErrorCode2.DeviceMismatch,
2097
2186
  message: "Keystone USB account export returned a different master fingerprint"
2098
2187
  });
2099
2188
  }
@@ -2106,25 +2195,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2106
2195
  }
2107
2196
  const account = parsed.accounts.find((a) => normalizePath(a.path) === syncPath);
2108
2197
  if (!account) {
2109
- throw createHwkError({
2110
- code: HardwareErrorCode.DeviceMismatch,
2198
+ throw createHwkError2({
2199
+ code: HardwareErrorCode2.DeviceMismatch,
2111
2200
  message: `Keystone did not return the requested derivation path (${syncPath})`
2112
2201
  });
2113
2202
  }
2114
- const entry = { ...account, hwkChain };
2115
- if (book) {
2116
- for (const returned of parsed.accounts) {
2117
- const returnedChain = inferHwkChainFromPath(returned.path);
2118
- if (returnedChain) {
2119
- book.set(accountKey(returnedChain, returned.path), {
2120
- ...returned,
2121
- hwkChain: returnedChain
2122
- });
2123
- }
2124
- }
2125
- book.set(key, entry);
2126
- }
2127
- return { record, account: entry };
2203
+ return { record, account: { ...account, hwkChain } };
2128
2204
  }
2129
2205
  /**
2130
2206
  * Resolves which wallet is attached, without a per-path account. `CHAIN_FINGERPRINT_PATHS.evm` is
@@ -2218,20 +2294,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
2218
2294
  }
2219
2295
  async _callUsbConnector(sessionId, method, params, signal) {
2220
2296
  if (!this._usbConnector) {
2221
- throw createHwkError({
2222
- code: HardwareErrorCode.TransportNotAvailable,
2297
+ throw createHwkError2({
2298
+ code: HardwareErrorCode2.TransportNotAvailable,
2223
2299
  message: "No USB connector configured for this Keystone adapter"
2224
2300
  });
2225
2301
  }
2226
2302
  if (this._pendingUsbTeardowns > 0 || this._unsettledUsbOperations.size > 0) {
2227
- throw createHwkError({
2228
- code: HardwareErrorCode.DeviceBusyInternal,
2303
+ throw createHwkError2({
2304
+ code: HardwareErrorCode2.DeviceBusyInternal,
2229
2305
  message: `Keystone USB is busy while calling ${method}`
2230
2306
  });
2231
2307
  }
2232
2308
  if (signal?.aborted) {
2233
- throw signal.reason instanceof Error ? signal.reason : createHwkError({
2234
- code: HardwareErrorCode.UserAborted,
2309
+ throw signal.reason instanceof Error ? signal.reason : createHwkError2({
2310
+ code: HardwareErrorCode2.UserAborted,
2235
2311
  message: "User aborted operation"
2236
2312
  });
2237
2313
  }
@@ -2313,8 +2389,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
2313
2389
  /** A response without the request's id is as unrelated as one with another id. */
2314
2390
  static _assertRequestIdMatches(expected, actual) {
2315
2391
  if (!actual || actual.toLowerCase() !== expected.toLowerCase()) {
2316
- throw createHwkError({
2317
- code: HardwareErrorCode.DeviceMismatch,
2392
+ throw createHwkError2({
2393
+ code: HardwareErrorCode2.DeviceMismatch,
2318
2394
  message: actual ? "Keystone response requestId does not match the pending request \u2014 discarding a stale or unrelated scan" : "Keystone response carries no requestId \u2014 discarding a stale or unrelated scan"
2319
2395
  });
2320
2396
  }
@@ -2322,7 +2398,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2322
2398
  _unsupported(method, reason) {
2323
2399
  return Promise.resolve(
2324
2400
  failure(
2325
- HardwareErrorCode.MethodNotSupported,
2401
+ HardwareErrorCode2.MethodNotSupported,
2326
2402
  `KeystoneAdapter.${method} is not implemented yet: ${reason}`
2327
2403
  )
2328
2404
  );
@@ -2342,20 +2418,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
2342
2418
  }
2343
2419
  if (e._tag === UI_REQUEST_CANCELLED_TAG || e._tag === UI_REQUEST_PREEMPTED_TAG) {
2344
2420
  return failure(
2345
- HardwareErrorCode.UserAborted,
2421
+ HardwareErrorCode2.UserAborted,
2346
2422
  e.message ?? "Keystone QR operation was cancelled"
2347
2423
  );
2348
2424
  }
2349
2425
  if (e._tag === UI_REQUEST_TIMEOUT_TAG) {
2350
2426
  return failure(
2351
- HardwareErrorCode.OperationTimeout,
2427
+ HardwareErrorCode2.OperationTimeout,
2352
2428
  e.message ?? "Keystone QR operation timed out"
2353
2429
  );
2354
2430
  }
2355
2431
  }
2356
2432
  const message = err instanceof Error ? err.message : String(err);
2357
2433
  const params = err instanceof Error && err.stack ? { stack: err.stack } : void 0;
2358
- return failure(HardwareErrorCode.UnknownError, message, params);
2434
+ return failure(HardwareErrorCode2.UnknownError, message, params);
2359
2435
  }
2360
2436
  };
2361
2437
  export {