@onekeyfe/hwk-keystone-adapter 1.2.5-alpha.4 → 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.js CHANGED
@@ -188,10 +188,9 @@ function requireSignatureBytes(hex, expectedBytes, chain) {
188
188
  }
189
189
  return hex;
190
190
  }
191
- var MISSING_MASTER_FINGERPRINT = "00000000";
192
191
  function requireBip32MasterFingerprint(value) {
193
- const fingerprint = (0, import_hwk_adapter_core.parseBip32MasterFingerprint)(value);
194
- if (!fingerprint || fingerprint === MISSING_MASTER_FINGERPRINT) {
192
+ const fingerprint = (0, import_hwk_adapter_core.parseWalletMasterFingerprint)(value);
193
+ if (!fingerprint) {
195
194
  throw new Error("Keystone master fingerprint must be exactly 4 bytes (8 hex characters)");
196
195
  }
197
196
  return fingerprint;
@@ -206,8 +205,19 @@ function toParsedAccount(key) {
206
205
  name: key.name
207
206
  };
208
207
  }
208
+ var BIP32_HARDENED_OFFSET = 2147483648;
209
209
  function relativeHdPath(relativeDerivePath) {
210
- return `m/${relativeDerivePath.replace(/^m\//i, "")}`;
210
+ const segments = relativeDerivePath.replace(/^m\//i, "").split("/");
211
+ const valid = segments.every(
212
+ (segment) => /^\d+$/.test(segment) && Number(segment) < BIP32_HARDENED_OFFSET
213
+ );
214
+ if (!valid) {
215
+ throw (0, import_hwk_adapter_core.createHwkError)({
216
+ code: import_hwk_adapter_core.HardwareErrorCode.InvalidParams,
217
+ message: `Invalid change/index segments in derivation path (${relativeDerivePath})`
218
+ });
219
+ }
220
+ return `m/${segments.join("/")}`;
211
221
  }
212
222
  var KeystoneUrEngine = class {
213
223
  constructor(origin = "OneKey") {
@@ -532,7 +542,7 @@ function keystoneQueueKey(connectId, deviceId) {
532
542
  }
533
543
  function keystoneMfpFromIdentifier(identifier) {
534
544
  const value = identifier.startsWith(KEYSTONE_WALLET_CONNECT_ID_PREFIX) ? identifier.slice(KEYSTONE_WALLET_CONNECT_ID_PREFIX.length) : identifier;
535
- return (0, import_hwk_adapter_core2.parseBip32MasterFingerprint)(value);
545
+ return (0, import_hwk_adapter_core2.parseWalletMasterFingerprint)(value);
536
546
  }
537
547
  function keystoneCancelQueueKeys(identifiers) {
538
548
  const keys = /* @__PURE__ */ new Set();
@@ -547,11 +557,24 @@ function keystoneCancelQueueKeys(identifiers) {
547
557
  }
548
558
 
549
559
  // src/adapter/KeystoneAdapter.ts
560
+ function keystoneBtcParamsFailure(params) {
561
+ const { coin, addressIndex, change } = params;
562
+ if (coin !== void 0 && !["btc", "bitcoin"].includes(String(coin).toLowerCase())) {
563
+ return (0, import_hwk_adapter_core3.failure)(
564
+ import_hwk_adapter_core3.HardwareErrorCode.ChainNotSupported,
565
+ `Keystone BTC supports Bitcoin mainnet only, not ${String(coin)}`
566
+ );
567
+ }
568
+ if (addressIndex !== void 0 || change !== void 0) {
569
+ return (0, import_hwk_adapter_core3.failure)(
570
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
571
+ "Keystone BTC takes the full address path; addressIndex and change are not supported"
572
+ );
573
+ }
574
+ return void 0;
575
+ }
550
576
  var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
551
577
  var KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS = 500;
552
- function resolveHardwareOperationTarget(positionalTargetId, operationId) {
553
- return (0, import_hwk_adapter_core3.resolveHardwareOperationTarget)(positionalTargetId, operationId, "keystone");
554
- }
555
578
  function keySchema(chain, path) {
556
579
  return { path, curve: chain === "sol" ? "ed25519" : "secp256k1" };
557
580
  }
@@ -572,9 +595,16 @@ var BIP44_COIN_TYPE_TO_CHAIN = {
572
595
  501: "sol",
573
596
  195: "tron"
574
597
  };
575
- function inferHwkChainFromPath(path) {
598
+ function hasChainCoinType(chain, path) {
576
599
  const match = normalizePath(path).match(/^m\/\d+'\/(\d+)'/);
577
- return match ? BIP44_COIN_TYPE_TO_CHAIN[Number(match[1])] : void 0;
600
+ return Boolean(match) && BIP44_COIN_TYPE_TO_CHAIN[Number(match?.[1])] === chain;
601
+ }
602
+ function coinTypeFailure(chain, path) {
603
+ if (hasChainCoinType(chain, path)) return void 0;
604
+ return (0, import_hwk_adapter_core3.failure)(
605
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
606
+ `Keystone ${chain} needs a path with its own BIP44 coin type, not ${path}`
607
+ );
578
608
  }
579
609
  var KeystoneAdapter = class _KeystoneAdapter {
580
610
  constructor(options) {
@@ -630,18 +660,30 @@ var KeystoneAdapter = class _KeystoneAdapter {
630
660
  // All-network bundle, dispatched to the per-chain methods below.
631
661
  // ---------------------------------------------------------------------------
632
662
  this.allNetworkGetAddress = async (connectId, deviceId, params) => {
633
- const operationTarget = resolveHardwareOperationTarget(connectId, params.operationId);
663
+ const operationTarget = this._resolveOperationTarget(connectId, params.operationId);
634
664
  if (!operationTarget.success) return operationTarget;
635
665
  const effectiveConnectId = operationTarget.payload.targetId ?? "";
636
666
  const { operationId } = operationTarget.payload;
667
+ const namedWallets = new Set(
668
+ [deviceId, ...params.bundle.map((item) => item.deviceId)].filter(
669
+ (id) => typeof id === "string" && id.length > 0
670
+ )
671
+ );
672
+ if (namedWallets.size > 1) {
673
+ return (0, import_hwk_adapter_core3.failure)(
674
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
675
+ "Keystone all-network items name different wallets"
676
+ );
677
+ }
678
+ const [expectedDeviceId = ""] = namedWallets;
637
679
  let cancelScope;
638
680
  try {
639
- const prefetched = await this._prefetchAllNetworkAccounts(effectiveConnectId, deviceId, {
681
+ const prepared = await this._prepareAllNetworkBundle(effectiveConnectId, expectedDeviceId, {
640
682
  ...params,
641
683
  operationId
642
684
  });
643
- const { book } = prefetched;
644
- const itemDeviceId = deviceId || prefetched.masterFingerprint || "";
685
+ const { access } = prepared;
686
+ const itemDeviceId = expectedDeviceId || prepared.masterFingerprint || "";
645
687
  const scope = this._jobQueue.createCancelScope(
646
688
  keystoneQueueKey(effectiveConnectId, itemDeviceId)
647
689
  );
@@ -663,15 +705,19 @@ var KeystoneAdapter = class _KeystoneAdapter {
663
705
  };
664
706
  switch (method) {
665
707
  case "evmGetAddress":
666
- return this.evmGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
708
+ return this.evmGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
667
709
  case "btcGetAddress":
668
- return this.btcGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
669
- case "btcGetPublicKey":
670
- return this.btcGetPublicKey(effectiveConnectId, itemDeviceId, commonArgs, book);
710
+ case "btcGetPublicKey": {
711
+ const btcArgs = {
712
+ ...commonArgs,
713
+ coin: item.coin ?? item.network
714
+ };
715
+ return method === "btcGetAddress" ? this.btcGetAddress(effectiveConnectId, itemDeviceId, btcArgs, access) : this.btcGetPublicKey(effectiveConnectId, itemDeviceId, btcArgs, access);
716
+ }
671
717
  case "solGetAddress":
672
- return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
718
+ return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
673
719
  case "tronGetAddress":
674
- return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, book);
720
+ return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
675
721
  default:
676
722
  return (0, import_hwk_adapter_core3.failure)(
677
723
  import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
@@ -695,11 +741,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
695
741
  }
696
742
  });
697
743
  },
698
- // Cancel, refusal or a lost session ends the batch; other per-item
699
- // failures carry on with the next chain.
744
+ // Cancel, refusal, a lost connection or a safety answer (another wallet, a locked
745
+ // device) ends the batch; other per-item failures carry on with the next chain.
700
746
  shouldAbortBundle: (response, { index }) => {
701
747
  const { code } = response.payload ?? {};
702
- return cancelledIndexes.has(index) || (0, import_hwk_adapter_core3.isUserRefusal)(code) || (0, import_hwk_adapter_core3.isConnectionLost)(code);
748
+ const usbSessionLost = access?.channel === "usb" && this._resolveTarget(effectiveConnectId, itemDeviceId).record?.usbSessionId !== access.usbSessionId;
749
+ 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);
703
750
  }
704
751
  });
705
752
  } catch (err) {
@@ -1001,6 +1048,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1001
1048
  this._uiRegistry.cancel();
1002
1049
  }
1003
1050
  }
1051
+ /**
1052
+ * Derived from the wallet's master fingerprint, which the caller already holds as deviceId; the
1053
+ * device is never asked. It names the wallet but cannot check which device is attached.
1054
+ */
1004
1055
  getChainFingerprint(connectId, deviceId, chain) {
1005
1056
  try {
1006
1057
  const target = this._resolveTarget(connectId, deviceId);
@@ -1063,14 +1114,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
1063
1114
  // ---------------------------------------------------------------------------
1064
1115
  // EVM
1065
1116
  // ---------------------------------------------------------------------------
1066
- async evmGetAddress(connectIdArg, deviceIdArg, params, book) {
1067
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1117
+ async evmGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1118
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1068
1119
  if (!operationTarget.success) return operationTarget;
1069
1120
  const connectId = operationTarget.payload.targetId;
1070
1121
  const deviceId = deviceIdArg ?? void 0;
1071
1122
  if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmGetAddress requires params");
1072
1123
  if (!params.path)
1073
1124
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmGetAddress requires params.path");
1125
+ const evmCoinTypeFailure = coinTypeFailure("evm", params.path);
1126
+ if (evmCoinTypeFailure) return evmCoinTypeFailure;
1074
1127
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1075
1128
  if (!relativeDerivePath) {
1076
1129
  return (0, import_hwk_adapter_core3.failure)(
@@ -1085,14 +1138,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1085
1138
  "evm",
1086
1139
  accountPath,
1087
1140
  signal,
1088
- book
1141
+ bundle
1089
1142
  );
1090
1143
  const address = this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath);
1091
1144
  return (0, import_hwk_adapter_core3.success)({ address, path: normalizePath(params.path) });
1092
1145
  });
1093
1146
  }
1094
1147
  async evmSignTransaction(connectIdArg, deviceIdArg, params) {
1095
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1148
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1096
1149
  if (!operationTarget.success) return operationTarget;
1097
1150
  const connectId = operationTarget.payload.targetId;
1098
1151
  const deviceId = deviceIdArg ?? void 0;
@@ -1133,7 +1186,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1133
1186
  });
1134
1187
  }
1135
1188
  async evmSignMessage(connectIdArg, deviceIdArg, params) {
1136
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1189
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1137
1190
  if (!operationTarget.success) return operationTarget;
1138
1191
  const connectId = operationTarget.payload.targetId;
1139
1192
  const deviceId = deviceIdArg ?? void 0;
@@ -1165,7 +1218,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1165
1218
  });
1166
1219
  }
1167
1220
  async evmSignTypedData(connectIdArg, deviceIdArg, params) {
1168
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1221
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1169
1222
  if (!operationTarget.success) return operationTarget;
1170
1223
  const connectId = operationTarget.payload.targetId;
1171
1224
  const deviceId = deviceIdArg ?? void 0;
@@ -1207,14 +1260,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
1207
1260
  // BTC: 44'/49'/84' addresses derive offline from the account xpub; P2TR addresses
1208
1261
  // and structured-field tx signing are unsupported (the host builds a PSBT instead).
1209
1262
  // ---------------------------------------------------------------------------
1210
- async btcGetAddress(connectIdArg, deviceIdArg, params, book) {
1211
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1263
+ async btcGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1264
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1212
1265
  if (!operationTarget.success) return operationTarget;
1213
1266
  const connectId = operationTarget.payload.targetId;
1214
1267
  const deviceId = deviceIdArg ?? void 0;
1215
1268
  if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetAddress requires params");
1216
1269
  if (!params.path)
1217
1270
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetAddress requires params.path");
1271
+ const btcParamsFailure = keystoneBtcParamsFailure(params);
1272
+ if (btcParamsFailure) return btcParamsFailure;
1218
1273
  const scriptType = btcScriptTypeFromPath(params.path);
1219
1274
  if (!scriptType) {
1220
1275
  return (0, import_hwk_adapter_core3.failure)(
@@ -1246,7 +1301,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1246
1301
  "btc",
1247
1302
  accountPath,
1248
1303
  signal,
1249
- book
1304
+ bundle
1250
1305
  );
1251
1306
  const address = this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType);
1252
1307
  return (0, import_hwk_adapter_core3.success)({ address, path: normalizedPath });
@@ -1256,14 +1311,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
1256
1311
  * `params.path` must be an account path (`m/84'/0'/0'`), the level Keystone syncs. An xpub is
1257
1312
  * script-type agnostic, so `86'` works here even though `btcGetAddress` rejects it.
1258
1313
  */
1259
- async btcGetPublicKey(connectIdArg, deviceIdArg, params, book) {
1260
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1314
+ async btcGetPublicKey(connectIdArg, deviceIdArg, params, bundle) {
1315
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1261
1316
  if (!operationTarget.success) return operationTarget;
1262
1317
  const connectId = operationTarget.payload.targetId;
1263
1318
  const deviceId = deviceIdArg ?? void 0;
1264
1319
  if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params");
1265
1320
  if (!params.path)
1266
1321
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params.path");
1322
+ const btcParamsFailure = keystoneBtcParamsFailure(params);
1323
+ if (btcParamsFailure) return btcParamsFailure;
1267
1324
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1268
1325
  if (relativeDerivePath) {
1269
1326
  return (0, import_hwk_adapter_core3.failure)(
@@ -1281,7 +1338,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1281
1338
  "btc",
1282
1339
  accountPath,
1283
1340
  signal,
1284
- book
1341
+ bundle
1285
1342
  );
1286
1343
  const meta = this.urEngine.parseXpubMeta(xpub);
1287
1344
  return (0, import_hwk_adapter_core3.success)({
@@ -1301,7 +1358,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1301
1358
  );
1302
1359
  }
1303
1360
  async btcSignPsbt(connectIdArg, deviceIdArg, params) {
1304
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1361
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1305
1362
  if (!operationTarget.success) return operationTarget;
1306
1363
  const connectId = operationTarget.payload.targetId;
1307
1364
  const deviceId = deviceIdArg ?? void 0;
@@ -1331,7 +1388,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1331
1388
  });
1332
1389
  }
1333
1390
  async btcSignMessage(connectIdArg, deviceIdArg, params) {
1334
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1391
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1335
1392
  if (!operationTarget.success) return operationTarget;
1336
1393
  const connectId = operationTarget.payload.targetId;
1337
1394
  const deviceId = deviceIdArg ?? void 0;
@@ -1362,8 +1419,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
1362
1419
  toPayload: (sig) => ({ signature: sig.signature })
1363
1420
  });
1364
1421
  }
1422
+ /**
1423
+ * Returns the known master fingerprint for the named wallet without asking the device (a QR
1424
+ * round trip only to repeat it would cost a scan). Use it to name the wallet, for example as a
1425
+ * PSBT xfp, which the device itself checks when signing; it cannot check the attached device.
1426
+ */
1365
1427
  async btcGetMasterFingerprint(connectIdArg, deviceIdArg, paramsArg) {
1366
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, paramsArg?.operationId);
1428
+ const operationTarget = this._resolveOperationTarget(connectIdArg, paramsArg?.operationId);
1367
1429
  if (!operationTarget.success) return operationTarget;
1368
1430
  const connectId = operationTarget.payload.targetId;
1369
1431
  const deviceId = deviceIdArg ?? void 0;
@@ -1375,24 +1437,39 @@ var KeystoneAdapter = class _KeystoneAdapter {
1375
1437
  // ---------------------------------------------------------------------------
1376
1438
  // SOL
1377
1439
  // ---------------------------------------------------------------------------
1378
- async solGetAddress(connectIdArg, deviceIdArg, params, book) {
1379
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1440
+ async solGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1441
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1380
1442
  if (!operationTarget.success) return operationTarget;
1381
1443
  const connectId = operationTarget.payload.targetId;
1382
1444
  const deviceId = deviceIdArg ?? void 0;
1383
1445
  if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solGetAddress requires params");
1384
1446
  if (!params.path)
1385
1447
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solGetAddress requires params.path");
1448
+ const solCoinTypeFailure = coinTypeFailure("sol", params.path);
1449
+ if (solCoinTypeFailure) return solCoinTypeFailure;
1386
1450
  const path = normalizePath(params.path);
1451
+ if (!/^m(\/\d+')+$/.test(path)) {
1452
+ return (0, import_hwk_adapter_core3.failure)(
1453
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1454
+ "solGetAddress requires a fully hardened path, e.g. m/44'/501'/0'/0'"
1455
+ );
1456
+ }
1387
1457
  return this._runJob(connectId, deviceId, async (signal) => {
1388
- const { account } = await this._fetchAccount(connectId, deviceId, "sol", path, signal, book);
1458
+ const { account } = await this._fetchAccount(
1459
+ connectId,
1460
+ deviceId,
1461
+ "sol",
1462
+ path,
1463
+ signal,
1464
+ bundle
1465
+ );
1389
1466
  _KeystoneAdapter._throwIfAborted(signal);
1390
1467
  const address = import_bs58.default.encode(Buffer.from(account.publicKey, "hex"));
1391
1468
  return (0, import_hwk_adapter_core3.success)({ address, path });
1392
1469
  });
1393
1470
  }
1394
1471
  async solSignTransaction(connectIdArg, deviceIdArg, params) {
1395
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1472
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1396
1473
  if (!operationTarget.success) return operationTarget;
1397
1474
  const connectId = operationTarget.payload.targetId;
1398
1475
  const deviceId = deviceIdArg ?? void 0;
@@ -1423,7 +1500,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1423
1500
  });
1424
1501
  }
1425
1502
  async solSignMessage(connectIdArg, deviceIdArg, params) {
1426
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1503
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1427
1504
  if (!operationTarget.success) return operationTarget;
1428
1505
  const connectId = operationTarget.payload.targetId;
1429
1506
  const deviceId = deviceIdArg ?? void 0;
@@ -1456,14 +1533,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
1456
1533
  // TRON: keystone-sdk-rust layout (tags 5201/5202, firmware >= 2.5.0), not sdk.tron's
1457
1534
  // protobuf module; OneKey Pro's encoding under the same tag is rejected by the firmware.
1458
1535
  // ---------------------------------------------------------------------------
1459
- async tronGetAddress(connectIdArg, deviceIdArg, params, book) {
1460
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1536
+ async tronGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1537
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1461
1538
  if (!operationTarget.success) return operationTarget;
1462
1539
  const connectId = operationTarget.payload.targetId;
1463
1540
  const deviceId = deviceIdArg ?? void 0;
1464
1541
  if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronGetAddress requires params");
1465
1542
  if (!params.path)
1466
1543
  return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronGetAddress requires params.path");
1544
+ const tronCoinTypeFailure = coinTypeFailure("tron", params.path);
1545
+ if (tronCoinTypeFailure) return tronCoinTypeFailure;
1467
1546
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1468
1547
  if (!relativeDerivePath) {
1469
1548
  return (0, import_hwk_adapter_core3.failure)(
@@ -1478,14 +1557,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1478
1557
  "tron",
1479
1558
  accountPath,
1480
1559
  signal,
1481
- book
1560
+ bundle
1482
1561
  );
1483
1562
  const address = this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath);
1484
1563
  return (0, import_hwk_adapter_core3.success)({ address, path: normalizePath(params.path) });
1485
1564
  });
1486
1565
  }
1487
1566
  async tronSignTransaction(connectIdArg, deviceIdArg, params) {
1488
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1567
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1489
1568
  if (!operationTarget.success) return operationTarget;
1490
1569
  const connectId = operationTarget.payload.targetId;
1491
1570
  const deviceId = deviceIdArg ?? void 0;
@@ -1520,7 +1599,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1520
1599
  });
1521
1600
  }
1522
1601
  async tronSignMessage(connectIdArg, deviceIdArg, params) {
1523
- const operationTarget = resolveHardwareOperationTarget(connectIdArg, params?.operationId);
1602
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1524
1603
  if (!operationTarget.success) return operationTarget;
1525
1604
  const connectId = operationTarget.payload.targetId;
1526
1605
  const deviceId = deviceIdArg ?? void 0;
@@ -1566,14 +1645,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1566
1645
  return this._errorToFailure(err);
1567
1646
  }
1568
1647
  }
1569
- async _fetchAccountXpub(connectId, deviceId, hwkChain, accountPath, signal, book) {
1648
+ async _fetchAccountXpub(connectId, deviceId, hwkChain, accountPath, signal, bundle) {
1570
1649
  const { account } = await this._fetchAccount(
1571
1650
  connectId,
1572
1651
  deviceId,
1573
1652
  hwkChain,
1574
1653
  accountPath,
1575
1654
  signal,
1576
- book
1655
+ bundle
1577
1656
  );
1578
1657
  _KeystoneAdapter._throwIfAborted(signal);
1579
1658
  if (!account.extendedPublicKey) {
@@ -1614,6 +1693,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1614
1693
  const method = item.methodName;
1615
1694
  const hwkChain = (0, import_hwk_adapter_core3.getAllNetworkMethodChain)(method);
1616
1695
  const path = normalizePath(item.path);
1696
+ if (!hasChainCoinType(hwkChain, path)) return void 0;
1617
1697
  if (hwkChain === "btc" && !isKeystoneSignableBtcAccountPath(splitAccountPath(path).accountPath)) {
1618
1698
  return void 0;
1619
1699
  }
@@ -1630,10 +1710,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1630
1710
  }
1631
1711
  }
1632
1712
  /**
1633
- * QR answers the whole bundle with one request QR and one scan. USB exports one path per
1634
- * request because the device limits that channel.
1713
+ * Picks the bundle's channel. QR answers every item with one request QR and one scan; USB items
1714
+ * each ask the device directly, like other vendors, on the session found here.
1635
1715
  */
1636
- async _prefetchAllNetworkAccounts(connectId, deviceId, params) {
1716
+ async _prepareAllNetworkBundle(connectId, deviceId, params) {
1637
1717
  return this._jobQueue.enqueue(keystoneQueueKey(connectId, deviceId), async (signal) => {
1638
1718
  const target = this._resolveTarget(connectId, deviceId);
1639
1719
  let { record } = target;
@@ -1642,21 +1722,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
1642
1722
  const schema = this._allNetworkSyncSchema(item);
1643
1723
  if (schema) requestedByKey.set(accountKey(schema.hwkChain, schema.path), schema);
1644
1724
  }
1645
- const book = /* @__PURE__ */ new Map();
1725
+ const scanned = /* @__PURE__ */ new Map();
1646
1726
  if (!requestedByKey.size) {
1647
- return { book };
1727
+ return { access: { channel: "qr", scanned } };
1648
1728
  }
1649
- const requestedSchemas = Array.from(requestedByKey.values());
1650
- const assertAllBooked = () => {
1651
- for (const schema of requestedSchemas) {
1652
- if (!book.has(accountKey(schema.hwkChain, schema.path))) {
1653
- throw (0, import_hwk_adapter_core3.createHwkError)({
1654
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1655
- message: `Keystone did not return the requested derivation path (${schema.path})`
1656
- });
1657
- }
1658
- }
1659
- };
1660
1729
  const operation = (0, import_hwk_adapter_core3.isHardwareOperationId)(params.operationId) ? this._operations.find(params.operationId) : void 0;
1661
1730
  const operationRoute = operation ? this._operationRoutes.get(operation.connectId) : void 0;
1662
1731
  const routedToQr = operationRoute?.operationId === operation?.operationId && operationRoute?.connectionType === "qr";
@@ -1665,40 +1734,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
1665
1734
  _KeystoneAdapter._throwIfAborted(signal);
1666
1735
  }
1667
1736
  if (this._forcedTransport !== "qr" && !routedToQr && record?.usbSessionId) {
1668
- const bundleSessionId = record.usbSessionId;
1669
- const assertBundleSession = () => {
1670
- if (record?.usbSessionId !== bundleSessionId) {
1671
- throw (0, import_hwk_adapter_core3.createHwkError)({
1672
- code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
1673
- message: "Keystone USB connection was lost during account export"
1674
- });
1675
- }
1737
+ return {
1738
+ access: { channel: "usb", usbSessionId: record.usbSessionId },
1739
+ masterFingerprint: record.masterFingerprint
1676
1740
  };
1677
- for (const schema of requestedSchemas) {
1678
- if (!book.has(accountKey(schema.hwkChain, schema.path))) {
1679
- assertBundleSession();
1680
- const synced = await this._fetchAccount(
1681
- connectId,
1682
- deviceId,
1683
- schema.hwkChain,
1684
- schema.path,
1685
- signal,
1686
- book
1687
- );
1688
- record = synced.record;
1689
- assertBundleSession();
1690
- }
1691
- }
1692
- assertAllBooked();
1693
- return { book, masterFingerprint: record.masterFingerprint };
1694
1741
  }
1695
- if (this._forcedTransport === "usb") {
1742
+ if (this._forcedTransport === "usb" && !routedToQr) {
1696
1743
  throw (0, import_hwk_adapter_core3.createHwkError)({
1697
1744
  code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
1698
1745
  message: "USB channel is not connected for this Keystone wallet"
1699
1746
  });
1700
1747
  }
1701
- const schemas = requestedSchemas;
1748
+ const schemas = Array.from(requestedByKey.values());
1702
1749
  const requestUr = this.urEngine.buildKeyDerivationRequest({
1703
1750
  schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1704
1751
  origin: this._origin
@@ -1712,21 +1759,50 @@ var KeystoneAdapter = class _KeystoneAdapter {
1712
1759
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1713
1760
  this._assertParsedIdentity(parsed, target);
1714
1761
  record = this._upsertDeviceRecord(parsed);
1715
- const requestedChainByPath = new Map(
1716
- schemas.map((schema) => [normalizePath(schema.path), schema.hwkChain])
1717
- );
1718
- for (const account of parsed.accounts) {
1719
- const normalizedPath = normalizePath(account.path);
1720
- const hwkChain = requestedChainByPath.get(normalizedPath) ?? inferHwkChainFromPath(normalizedPath);
1721
- if (hwkChain) {
1722
- book.set(accountKey(hwkChain, normalizedPath), { ...account, hwkChain });
1762
+ for (const schema of schemas) {
1763
+ const account = parsed.accounts.find(
1764
+ (returned) => normalizePath(returned.path) === schema.path
1765
+ );
1766
+ if (!account) {
1767
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1768
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1769
+ message: `Keystone did not return the requested derivation path (${schema.path})`
1770
+ });
1723
1771
  }
1772
+ scanned.set(accountKey(schema.hwkChain, schema.path), {
1773
+ ...account,
1774
+ hwkChain: schema.hwkChain
1775
+ });
1724
1776
  }
1725
- assertAllBooked();
1726
- return { book, masterFingerprint: record.masterFingerprint };
1777
+ return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1727
1778
  });
1728
1779
  }
1729
1780
  /** 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
+ }
1730
1806
  _resolveTarget(connectId, deviceId) {
1731
1807
  const resolvedConnectId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? this._operations.resolve(connectId).connectId : connectId;
1732
1808
  const identifiers = [deviceId, resolvedConnectId].filter(
@@ -1837,11 +1913,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
1837
1913
  sessionId = session.sessionId;
1838
1914
  _KeystoneAdapter._throwIfAborted(signal);
1839
1915
  const raw = session.deviceInfo.raw;
1840
- const mfpValue = (0, import_hwk_adapter_core3.parseBip32MasterFingerprint)(raw?.masterFingerprint);
1916
+ const mfpValue = (0, import_hwk_adapter_core3.parseWalletMasterFingerprint)(raw?.masterFingerprint);
1841
1917
  if (!mfpValue) {
1918
+ const empty = (0, import_hwk_adapter_core3.parseBip32MasterFingerprint)(raw?.masterFingerprint) === import_hwk_adapter_core3.MISSING_BIP32_MASTER_FINGERPRINT;
1842
1919
  throw (0, import_hwk_adapter_core3.createHwkError)({
1843
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1844
- message: "Keystone USB did not report a master fingerprint"
1920
+ code: empty ? import_hwk_adapter_core3.HardwareErrorCode.DeviceNotInitialized : import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1921
+ message: empty ? "Keystone has no wallet yet; it reported an empty master fingerprint" : "Keystone USB did not report a master fingerprint"
1845
1922
  });
1846
1923
  }
1847
1924
  const masterFingerprint = mfpValue.toLowerCase();
@@ -1913,6 +1990,8 @@ 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
  }
@@ -1929,8 +2008,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1929
2008
  return attached.success ? this._devices.get(expectedMasterFingerprint) : void 0;
1930
2009
  }
1931
2010
  /**
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.
2011
+ * Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
2012
+ * and fails closed if that fails; otherwise a failed USB reattach leaves the call on QR.
1934
2013
  */
1935
2014
  async _resolveUr(record, requestUr, animated, operationId, signal, operationName) {
1936
2015
  const releaseOperationRetention = (0, import_hwk_adapter_core3.isHardwareOperationId)(operationId) ? this._operations.retain(operationId) : void 0;
@@ -1961,7 +2040,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1961
2040
  }
1962
2041
  interactionRoute = route;
1963
2042
  }
1964
- if (!interactionRoute && !this._forcedTransport && record && !record.usbSessionId && this._usbConnector) {
2043
+ if (!interactionRoute && this._forcedTransport !== "qr" && record && !record.usbSessionId && this._usbConnector) {
1965
2044
  record = await this._tryUsbAttach(signal, record.masterFingerprint, {
1966
2045
  waitForReenumeration: record.hadUsbSession
1967
2046
  }) ?? record;
@@ -2058,30 +2137,35 @@ var KeystoneAdapter = class _KeystoneAdapter {
2058
2137
  });
2059
2138
  }
2060
2139
  /**
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.
2140
+ * Fetches one account's key material. An all-network QR item takes it from the bundle's scan; a
2141
+ * USB item asks the device on the bundle's session. A failed USB export ends the operation
2142
+ * without replaying or switching transports.
2063
2143
  */
2064
- async _fetchAccount(connectId, deviceId, hwkChain, syncPath, signal, book) {
2144
+ async _fetchAccount(connectId, deviceId, hwkChain, syncPath, signal, bundle) {
2065
2145
  const target = this._resolveTarget(connectId, deviceId);
2146
+ if (bundle?.channel === "qr") {
2147
+ const scanned = bundle.scanned.get(accountKey(hwkChain, syncPath));
2148
+ if (!target.record || !scanned) {
2149
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2150
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2151
+ message: `Keystone did not return the requested derivation path (${syncPath})`
2152
+ });
2153
+ }
2154
+ return { record: target.record, account: scanned };
2155
+ }
2156
+ if (bundle?.channel === "usb" && target.record?.usbSessionId !== bundle.usbSessionId) {
2157
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2158
+ code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
2159
+ message: "Keystone USB connection was lost during the bundle"
2160
+ });
2161
+ }
2066
2162
  const operationConnectionType = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? this._operations.resolve(connectId).connectionType : void 0;
2067
- const key = accountKey(hwkChain, syncPath);
2068
2163
  let existingRecord = target.record;
2069
2164
  if (!existingRecord) {
2070
2165
  existingRecord = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
2071
2166
  _KeystoneAdapter._throwIfAborted(signal);
2072
2167
  }
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);
2168
+ const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
2085
2169
  const schemas = [keySchema(hwkChain, syncPath)];
2086
2170
  const requestUr = this.urEngine.buildKeyDerivationRequest({ schemas, origin: this._origin });
2087
2171
  const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
@@ -2109,20 +2193,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2109
2193
  message: `Keystone did not return the requested derivation path (${syncPath})`
2110
2194
  });
2111
2195
  }
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 };
2196
+ return { record, account: { ...account, hwkChain } };
2126
2197
  }
2127
2198
  /**
2128
2199
  * Resolves which wallet is attached, without a per-path account. `CHAIN_FINGERPRINT_PATHS.evm` is
@@ -2308,11 +2379,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2308
2379
  throw signal.reason instanceof Error ? signal.reason : new Error("Operation aborted");
2309
2380
  }
2310
2381
  }
2382
+ /** A response without the request's id is as unrelated as one with another id. */
2311
2383
  static _assertRequestIdMatches(expected, actual) {
2312
- if (actual && actual.toLowerCase() !== expected.toLowerCase()) {
2384
+ if (!actual || actual.toLowerCase() !== expected.toLowerCase()) {
2313
2385
  throw (0, import_hwk_adapter_core3.createHwkError)({
2314
2386
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2315
- message: "Keystone response requestId does not match the pending request \u2014 discarding a stale or unrelated scan"
2387
+ 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"
2316
2388
  });
2317
2389
  }
2318
2390
  }