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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -105,11 +105,12 @@ var TronSignRequest = class _TronSignRequest extends import_bc_ur_registry.Regis
105
105
  static parsePath(path, xfp) {
106
106
  const segments = path.replace(/^[mM]\//, "").split("/");
107
107
  const components = segments.map((segment) => {
108
- const hardened = segment.endsWith("'");
109
- return new import_bc_ur_registry.PathComponent({
110
- index: parseInt(hardened ? segment.slice(0, -1) : segment, 10),
111
- hardened
112
- });
108
+ const match = /^(\d+)('?)$/.exec(segment);
109
+ const index = match ? Number(match[1]) : NaN;
110
+ if (!match || index >= 2147483648) {
111
+ throw new Error(`Invalid TRON derivation path segment (${segment})`);
112
+ }
113
+ return new import_bc_ur_registry.PathComponent({ index, hardened: match[2] === "'" });
113
114
  });
114
115
  return new import_bc_ur_registry.CryptoKeypath(components, Buffer.from(xfp, "hex"));
115
116
  }
@@ -167,7 +168,7 @@ var DERIVATION_CURVE = {
167
168
  ed25519: import_keystone_sdk.Curve.ed25519
168
169
  };
169
170
  function toSdkUr(ur) {
170
- return new import_keystone_sdk.UR(Buffer.from(ur.urData, "hex"), ur.urType);
171
+ return new import_keystone_sdk.UR((0, import_hwk_adapter_core.boundedCborFromHex)(ur.urData), ur.urType);
171
172
  }
172
173
  function fromSdkUr(ur) {
173
174
  return { urType: ur.type, urData: ur.cbor.toString("hex") };
@@ -219,6 +220,11 @@ function relativeHdPath(relativeDerivePath) {
219
220
  }
220
221
  return `m/${segments.join("/")}`;
221
222
  }
223
+ var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.]{1,20})?$/;
224
+ var DEVICE_TEXT = /^[^\p{Cc}\p{Cf}]{1,64}$/u;
225
+ function deviceText(value, pattern) {
226
+ return typeof value === "string" && pattern.test(value) ? value : void 0;
227
+ }
222
228
  var KeystoneUrEngine = class {
223
229
  constructor(origin = "OneKey") {
224
230
  this.sdk = new import_keystone_sdk.KeystoneSDK({ origin });
@@ -228,9 +234,9 @@ var KeystoneUrEngine = class {
228
234
  const parsed = this.sdk.parseMultiAccounts(toSdkUr(ur));
229
235
  return {
230
236
  masterFingerprint: requireBip32MasterFingerprint(parsed.masterFingerprint),
231
- device: parsed.device,
232
- deviceId: parsed.deviceId,
233
- deviceVersion: parsed.deviceVersion,
237
+ device: deviceText(parsed.device, DEVICE_TEXT),
238
+ deviceId: deviceText(parsed.deviceId, DEVICE_TEXT),
239
+ deviceVersion: deviceText(parsed.deviceVersion, FIRMWARE_VERSION),
234
240
  accounts: parsed.keys.map(toParsedAccount)
235
241
  };
236
242
  }
@@ -292,10 +298,7 @@ var KeystoneUrEngine = class {
292
298
  return (0, import_bc_ur_registry_eth.generateAddressFromXpub)(xpub, relativeHdPath(relativeDerivePath));
293
299
  }
294
300
  // --- BTC (PSBT transaction signing + plain message signing) ---
295
- /**
296
- * `CryptoHDKey` always emits mainnet xpub version bytes (`0488B21E`), so `hdkey` parses it as is.
297
- * `p2tr` needs an ECC lib for BIP-341 tweaking, not wired here.
298
- */
301
+ /** `CryptoHDKey` always emits mainnet xpub version bytes (`0488B21E`), so `hdkey` parses it as is. */
299
302
  deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType) {
300
303
  const node = import_hdkey.default.fromExtendedKey(xpub).derive(relativeHdPath(relativeDerivePath));
301
304
  if (!node.publicKey) throw new Error("HDKey derivation did not produce a public key");
@@ -341,9 +344,27 @@ var KeystoneUrEngine = class {
341
344
  const ur = this.sdk.btc.generatePSBT(Buffer.from(unsignedPsbtHex, "hex"));
342
345
  return fromSdkUr(ur);
343
346
  }
344
- /** Returns the hex-encoded (possibly still-unsigned-in-part) PSBT the device replied with. */
345
- parseBtcPsbt(ur) {
346
- return this.sdk.btc.parsePSBT(toSdkUr(ur));
347
+ /**
348
+ * Returns the hex-encoded (possibly still-unsigned-in-part) PSBT the device replied with. A PSBT
349
+ * carries no request id, so the reply is bound to the request by its unsigned transaction, which
350
+ * signing never changes (BIP-174); a scan of another PSBT's signature is refused.
351
+ */
352
+ parseBtcPsbt(ur, requestPsbtHex) {
353
+ const signedPsbtHex = this.sdk.btc.parsePSBT(toSdkUr(ur));
354
+ let sameTransaction = false;
355
+ try {
356
+ const unsignedTx = (hex) => Buffer.from(bitcoin.Psbt.fromHex(hex).data.globalMap.unsignedTx.toBuffer());
357
+ sameTransaction = unsignedTx(signedPsbtHex).equals(unsignedTx(requestPsbtHex));
358
+ } catch {
359
+ sameTransaction = false;
360
+ }
361
+ if (!sameTransaction) {
362
+ throw (0, import_hwk_adapter_core.createHwkError)({
363
+ code: import_hwk_adapter_core.HardwareErrorCode.DeviceMismatch,
364
+ message: "Keystone returned a PSBT for another transaction than the one requested"
365
+ });
366
+ }
367
+ return signedPsbtHex;
347
368
  }
348
369
  buildBtcMessageSignRequest(params) {
349
370
  const ur = this.sdk.btc.generateSignRequest({
@@ -403,7 +424,7 @@ var KeystoneUrEngine = class {
403
424
  if (ur.urType !== "tron-signature") {
404
425
  throw new Error(`Expected a tron-signature UR, got ${ur.urType}`);
405
426
  }
406
- const signature = TronSignature.fromCBOR(Buffer.from(ur.urData, "hex"));
427
+ const signature = TronSignature.fromCBOR((0, import_hwk_adapter_core.boundedCborFromHex)(ur.urData));
407
428
  const requestId = signature.getRequestId();
408
429
  return {
409
430
  requestId: requestId ? (0, import_uuid.stringify)(requestId) : void 0,
@@ -447,6 +468,14 @@ function normalizePath(path) {
447
468
  const trimmed = path.trim();
448
469
  return /^m\//i.test(trimmed) ? `m/${trimmed.slice(2)}` : `m/${trimmed}`;
449
470
  }
471
+ var BIP32_HARDENED_OFFSET2 = 2147483648;
472
+ function isBip32Path(path) {
473
+ const segments = normalizePath(path).slice(2).split("/");
474
+ return segments.every((segment) => {
475
+ const match = /^(\d+)'?$/.exec(segment);
476
+ return match !== null && Number(match[1]) < BIP32_HARDENED_OFFSET2;
477
+ });
478
+ }
450
479
  function splitAccountPath(path) {
451
480
  const normalized = normalizePath(path);
452
481
  const segments = normalized.slice(2).split("/");
@@ -583,12 +612,6 @@ function waitForKeystoneUsbReattachProbe() {
583
612
  setTimeout(resolve, KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS);
584
613
  });
585
614
  }
586
- function buildCancelledFailure(signal) {
587
- const reason = signal.reason;
588
- const code = typeof reason?.code === "number" ? reason.code : import_hwk_adapter_core3.HardwareErrorCode.UserAborted;
589
- const message = typeof reason?.message === "string" ? reason.message : "";
590
- return (0, import_hwk_adapter_core3.failure)(code, message || "All-network get-address cancelled");
591
- }
592
615
  var BIP44_COIN_TYPE_TO_CHAIN = {
593
616
  60: "evm",
594
617
  0: "btc",
@@ -599,6 +622,23 @@ function hasChainCoinType(chain, path) {
599
622
  const match = normalizePath(path).match(/^m\/\d+'\/(\d+)'/);
600
623
  return Boolean(match) && BIP44_COIN_TYPE_TO_CHAIN[Number(match?.[1])] === chain;
601
624
  }
625
+ function exactHex(value) {
626
+ const hex = value.replace(/^0x/i, "");
627
+ return /^(?:[0-9a-f]{2})*$/i.test(hex) ? hex : void 0;
628
+ }
629
+ function invalidHexFailure(field) {
630
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${field} must be an even-length hex string`);
631
+ }
632
+ function requireExportedPath(parsed, path) {
633
+ const account = parsed.accounts.find((returned) => normalizePath(returned.path) === path);
634
+ if (!account) {
635
+ throw (0, import_hwk_adapter_core3.createHwkError)({
636
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
637
+ message: `Keystone did not return the requested derivation path (${path})`
638
+ });
639
+ }
640
+ return account;
641
+ }
602
642
  function coinTypeFailure(chain, path) {
603
643
  if (hasChainCoinType(chain, path)) return void 0;
604
644
  return (0, import_hwk_adapter_core3.failure)(
@@ -606,6 +646,19 @@ function coinTypeFailure(chain, path) {
606
646
  `Keystone ${chain} needs a path with its own BIP44 coin type, not ${path}`
607
647
  );
608
648
  }
649
+ function btcAccountFailure(accountPath) {
650
+ if (isKeystoneSignableBtcAccountPath(accountPath)) return void 0;
651
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
652
+ }
653
+ function missingParamFailure(method, param) {
654
+ return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `${method} requires ${param}`);
655
+ }
656
+ function messageToHex(message, hex) {
657
+ return hex ? exactHex(message) : Buffer.from(message, "utf8").toString("hex");
658
+ }
659
+ function evmMessageSignature(sig) {
660
+ return { signature: (0, import_hwk_adapter_core3.ensure0x)(sig.r + sig.s + sig.v) };
661
+ }
609
662
  var KeystoneAdapter = class _KeystoneAdapter {
610
663
  constructor(options) {
611
664
  this.vendor = "keystone";
@@ -620,6 +673,19 @@ var KeystoneAdapter = class _KeystoneAdapter {
620
673
  const route = this._operationRoutes.get(operation.connectId);
621
674
  if (route?.operationId === operation.operationId) {
622
675
  this._operationRoutes.delete(operation.connectId);
676
+ if (route.connectionType === "qr") {
677
+ const ended = (0, import_hwk_adapter_core3.createHwkError)({
678
+ code: import_hwk_adapter_core3.HardwareErrorCode.OperationEnded,
679
+ message: "Keystone operation has ended",
680
+ params: { operationId: operation.operationId, reason }
681
+ });
682
+ const queueKey = keystoneQueueKey(operation.operationId);
683
+ const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
684
+ this._jobQueue.cancelActiveAndPending(queueKey, ended);
685
+ if (ownsRunningCall) {
686
+ this._uiRegistry.cancel(void 0, void 0, operation.operationId);
687
+ }
688
+ }
623
689
  }
624
690
  this.emitter.emit(import_hwk_adapter_core3.SDK.OPERATION_ENDED, {
625
691
  type: import_hwk_adapter_core3.SDK.OPERATION_ENDED,
@@ -696,7 +762,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
696
762
  callItem: async ({ method, item, index }) => {
697
763
  if (scope.signal.aborted) {
698
764
  cancelledIndexes.add(index);
699
- return buildCancelledFailure(scope.signal);
765
+ return (0, import_hwk_adapter_core3.buildAllNetworkCancelledFailure)(scope.signal);
700
766
  }
701
767
  const commonArgs = {
702
768
  path: item.path,
@@ -718,11 +784,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
718
784
  return this.solGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
719
785
  case "tronGetAddress":
720
786
  return this.tronGetAddress(effectiveConnectId, itemDeviceId, commonArgs, access);
721
- default:
722
- return (0, import_hwk_adapter_core3.failure)(
723
- import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
724
- `Unsupported method: ${String(method)}`
725
- );
726
787
  }
727
788
  },
728
789
  attachIdentity: (context) => {
@@ -763,9 +824,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
763
824
  this._usbConnector?.on("device-disconnect", this._handleUsbDisconnect);
764
825
  this._usbConnector?.on("ui-event", this._handleUsbUiEvent);
765
826
  }
766
- // ---------------------------------------------------------------------------
767
- // Lifecycle / transport
768
- // ---------------------------------------------------------------------------
769
827
  get activeTransport() {
770
828
  if (this._devices.size === 0) return null;
771
829
  const hasUsbSession = Array.from(this._devices.values()).some((r) => r.usbSessionId);
@@ -795,9 +853,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
795
853
  this._devices.clear();
796
854
  this.emitter.removeAllListeners();
797
855
  }
798
- // ---------------------------------------------------------------------------
799
- // Device table
800
- // ---------------------------------------------------------------------------
801
856
  /**
802
857
  * Returns known wallets plus USB scan results; USB entries have no mfp until `connectDevice()`
803
858
  * claims them. Explicit QR discovery returns one virtual target.
@@ -870,11 +925,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
870
925
  }
871
926
  /** Best-effort disconnect; the session is retired either way so it cannot be selected again. */
872
927
  async _retireUsbSession(sessionId) {
873
- if (this._usbConnector) {
874
- try {
875
- await this._usbConnector.disconnect(sessionId);
876
- } catch {
877
- }
928
+ try {
929
+ await this._usbConnector?.disconnect(sessionId);
930
+ } catch {
878
931
  }
879
932
  this._handleUsbDisconnect({ connectId: sessionId });
880
933
  }
@@ -893,13 +946,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
893
946
  serialNumber: device.serialNumber
894
947
  }));
895
948
  }
896
- async listConnectionTargets(options) {
897
- const targets = await this.searchDeviceTargets(options);
898
- return targets.map(({ searchTargetId, ...target }) => ({
899
- ...target,
900
- targetId: searchTargetId
901
- }));
902
- }
903
949
  async connectDevice(searchTargetId) {
904
950
  const scope = this._jobQueue.createCancelScope(searchTargetId);
905
951
  try {
@@ -908,16 +954,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
908
954
  const discoveredConnectionType = this._searchDeviceTargets.get(searchTargetId);
909
955
  if (discoveredConnectionType === "qr") {
910
956
  selectedConnectionType = "qr";
911
- const abortColdStart = () => this._jobQueue.cancelActiveAndPending(
912
- KEYSTONE_COLD_START_JOB_LABEL,
913
- scope.signal.reason
957
+ connected = await _KeystoneAdapter._untilAborted(
958
+ scope.signal,
959
+ this._importFromQr({}, searchTargetId)
914
960
  );
915
- scope.signal.addEventListener("abort", abortColdStart, { once: true });
916
- try {
917
- connected = await this.importFromQr();
918
- } finally {
919
- scope.signal.removeEventListener("abort", abortColdStart);
920
- }
921
961
  } else if (discoveredConnectionType === "usb") {
922
962
  selectedConnectionType = "usb";
923
963
  if (!this._usbConnector) {
@@ -926,7 +966,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
926
966
  "No USB connector configured for this Keystone adapter"
927
967
  );
928
968
  }
929
- connected = await this._connectUsb({}, searchTargetId, scope.signal);
969
+ connected = await this._connectUsb(this._usbConnector, {}, searchTargetId, scope.signal);
930
970
  } else if ((0, import_hwk_adapter_core3.hasHardwareRuntimeIdPrefix)(searchTargetId)) {
931
971
  return (0, import_hwk_adapter_core3.failure)(
932
972
  import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound,
@@ -947,7 +987,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
947
987
  );
948
988
  } else {
949
989
  selectedConnectionType = "usb";
950
- connected = await this._connectUsb(target, void 0, scope.signal);
990
+ connected = await this._connectUsb(this._usbConnector, target, void 0, scope.signal);
951
991
  }
952
992
  }
953
993
  _KeystoneAdapter._throwIfAborted(scope.signal);
@@ -1006,10 +1046,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1006
1046
  const { record } = this._resolveTarget(connectId, deviceId);
1007
1047
  if (!record) {
1008
1048
  return Promise.resolve(
1009
- (0, import_hwk_adapter_core3.failure)(
1010
- import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound,
1011
- `Unknown Keystone device: ${connectId || deviceId}`
1012
- )
1049
+ (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound, "Unknown Keystone device")
1013
1050
  );
1014
1051
  }
1015
1052
  return Promise.resolve((0, import_hwk_adapter_core3.success)(toDeviceInfo(record)));
@@ -1085,18 +1122,21 @@ var KeystoneAdapter = class _KeystoneAdapter {
1085
1122
  // Explicit account import: call before signing to avoid a cold sync per call.
1086
1123
  // ---------------------------------------------------------------------------
1087
1124
  async importFromQr(options = {}) {
1125
+ return this._importFromQr(options, KEYSTONE_COLD_START_JOB_LABEL);
1126
+ }
1127
+ async _importFromQr(options, jobKey) {
1088
1128
  try {
1089
- return await this._jobQueue.enqueue(KEYSTONE_COLD_START_JOB_LABEL, async (signal) => {
1129
+ return await this._jobQueue.enqueue(jobKey, async (signal) => {
1090
1130
  const displayDevice = placeholderDeviceInfo();
1091
1131
  let responseUr;
1092
1132
  if (options.mode === "scan") {
1093
- responseUr = await this._requestQrScanAndAwaitResponse(displayDevice, signal);
1133
+ responseUr = await this._requestQrAndAwaitResponse(displayDevice, void 0, signal);
1094
1134
  } else {
1095
1135
  const requestUr = this.urEngine.buildKeyDerivationRequest({
1096
1136
  schemas: [keySchema("evm", KEYSTONE_COLD_START_PATH)],
1097
1137
  origin: this._origin
1098
1138
  });
1099
- responseUr = await this._requestQrDisplayAndAwaitResponse(
1139
+ responseUr = await this._requestQrAndAwaitResponse(
1100
1140
  displayDevice,
1101
1141
  { ...requestUr, animated: false },
1102
1142
  signal
@@ -1104,6 +1144,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1104
1144
  }
1105
1145
  _KeystoneAdapter._throwIfAborted(signal);
1106
1146
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1147
+ if (options.mode !== "scan") requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
1107
1148
  const record = this._upsertDeviceRecord(parsed);
1108
1149
  return (0, import_hwk_adapter_core3.success)(toDeviceInfo(record));
1109
1150
  });
@@ -1111,163 +1152,103 @@ var KeystoneAdapter = class _KeystoneAdapter {
1111
1152
  return this._errorToFailure(err);
1112
1153
  }
1113
1154
  }
1114
- // ---------------------------------------------------------------------------
1115
- // EVM
1116
- // ---------------------------------------------------------------------------
1117
- async evmGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1118
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1119
- if (!operationTarget.success) return operationTarget;
1120
- const connectId = operationTarget.payload.targetId;
1121
- const deviceId = deviceIdArg ?? void 0;
1122
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmGetAddress requires params");
1123
- if (!params.path)
1124
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmGetAddress requires params.path");
1155
+ async evmGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1156
+ const call = this._beginCall("evmGetAddress", connectIdArg, deviceIdArg, paramsArg);
1157
+ if (!call.success) return call;
1158
+ const { params } = call.payload;
1159
+ if (!params.path) return missingParamFailure("evmGetAddress", "params.path");
1125
1160
  const evmCoinTypeFailure = coinTypeFailure("evm", params.path);
1126
1161
  if (evmCoinTypeFailure) return evmCoinTypeFailure;
1127
- const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1128
- if (!relativeDerivePath) {
1129
- return (0, import_hwk_adapter_core3.failure)(
1130
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1131
- "evmGetAddress requires a full leaf path, e.g. m/44'/60'/0'/0/0"
1132
- );
1133
- }
1134
- return this._runJob(connectId, deviceId, async (signal) => {
1135
- const xpub = await this._fetchAccountXpub(
1136
- connectId,
1137
- deviceId,
1138
- "evm",
1139
- accountPath,
1140
- signal,
1141
- bundle
1142
- );
1143
- const address = this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath);
1144
- return (0, import_hwk_adapter_core3.success)({ address, path: normalizePath(params.path) });
1145
- });
1162
+ return this._addressFromAccountXpub(
1163
+ "evmGetAddress",
1164
+ "evm",
1165
+ call.payload,
1166
+ params.path,
1167
+ "m/44'/60'/0'/0/0",
1168
+ bundle,
1169
+ (xpub, relativeDerivePath) => this.urEngine.deriveEvmAddressFromXpub(xpub, relativeDerivePath)
1170
+ );
1146
1171
  }
1147
- async evmSignTransaction(connectIdArg, deviceIdArg, params) {
1148
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1149
- if (!operationTarget.success) return operationTarget;
1150
- const connectId = operationTarget.payload.targetId;
1151
- const deviceId = deviceIdArg ?? void 0;
1152
- if (!params)
1153
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignTransaction requires params");
1154
- if (!params.path) {
1155
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignTransaction requires params.path");
1156
- }
1172
+ async evmSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1173
+ const call = this._beginCall("evmSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1174
+ if (!call.success) return call;
1175
+ const { params } = call.payload;
1176
+ if (!params.path) return missingParamFailure("evmSignTransaction", "params.path");
1157
1177
  if (!("serializedTx" in params) || typeof params.serializedTx !== "string" || !params.serializedTx) {
1158
1178
  return (0, import_hwk_adapter_core3.failure)(
1159
1179
  import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1160
1180
  "Keystone only signs a fully RLP-serialized transaction (params.serializedTx) \u2014 structured-field signing is not supported"
1161
1181
  );
1162
1182
  }
1163
- const rawTxHex = (0, import_hwk_adapter_core3.stripHex)(params.serializedTx);
1164
- const path = normalizePath(params.path);
1183
+ const rawTxHex = exactHex(params.serializedTx);
1184
+ if (rawTxHex === void 0) return invalidHexFailure("serializedTx");
1165
1185
  const dataType = parseInt(rawTxHex.slice(0, 2), 16) < 192 ? "typedTransaction" : "transaction";
1166
- return this._signWithWallet({
1167
- connectId,
1168
- deviceId,
1169
- chain: "evm",
1170
- operationName: "evmSignTransaction",
1171
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1172
- requestId,
1173
- unsignedTxHex: rawTxHex,
1174
- dataType,
1175
- path,
1176
- xfp,
1177
- chainId: params.chainId,
1178
- origin: this._origin
1179
- }),
1180
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1181
- toPayload: (sig) => ({
1182
- v: (0, import_hwk_adapter_core3.ensure0x)(sig.v),
1183
- r: (0, import_hwk_adapter_core3.ensure0x)(sig.r),
1184
- s: (0, import_hwk_adapter_core3.ensure0x)(sig.s)
1185
- })
1186
- });
1186
+ return this._evmSign(
1187
+ "evmSignTransaction",
1188
+ call.payload,
1189
+ params.path,
1190
+ params.chainId,
1191
+ rawTxHex,
1192
+ dataType,
1193
+ (sig) => ({ v: (0, import_hwk_adapter_core3.ensure0x)(sig.v), r: (0, import_hwk_adapter_core3.ensure0x)(sig.r), s: (0, import_hwk_adapter_core3.ensure0x)(sig.s) })
1194
+ );
1187
1195
  }
1188
- async evmSignMessage(connectIdArg, deviceIdArg, params) {
1189
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1190
- if (!operationTarget.success) return operationTarget;
1191
- const connectId = operationTarget.payload.targetId;
1192
- const deviceId = deviceIdArg ?? void 0;
1193
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignMessage requires params");
1196
+ async evmSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1197
+ const call = this._beginCall("evmSignMessage", connectIdArg, deviceIdArg, paramsArg);
1198
+ if (!call.success) return call;
1199
+ const { params } = call.payload;
1194
1200
  if (!params.path || params.message === void 0) {
1195
- return (0, import_hwk_adapter_core3.failure)(
1196
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1197
- "evmSignMessage requires params.path and params.message"
1198
- );
1199
- }
1200
- const messageHex = params.hex ? (0, import_hwk_adapter_core3.stripHex)(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1201
- const path = normalizePath(params.path);
1202
- return this._signWithWallet({
1203
- connectId,
1204
- deviceId,
1205
- chain: "evm",
1206
- operationName: "evmSignMessage",
1207
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1208
- requestId,
1209
- unsignedTxHex: messageHex,
1210
- dataType: "personalMessage",
1211
- path,
1212
- xfp,
1213
- chainId: params.chainId,
1214
- origin: this._origin
1215
- }),
1216
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1217
- toPayload: (sig) => ({ signature: (0, import_hwk_adapter_core3.ensure0x)(sig.r + sig.s + sig.v) })
1218
- });
1201
+ return missingParamFailure("evmSignMessage", "params.path and params.message");
1202
+ }
1203
+ const messageHex = messageToHex(params.message, params.hex);
1204
+ if (messageHex === void 0) return invalidHexFailure("message");
1205
+ return this._evmSign(
1206
+ "evmSignMessage",
1207
+ call.payload,
1208
+ params.path,
1209
+ params.chainId,
1210
+ messageHex,
1211
+ "personalMessage",
1212
+ evmMessageSignature
1213
+ );
1219
1214
  }
1220
- async evmSignTypedData(connectIdArg, deviceIdArg, params) {
1221
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1222
- if (!operationTarget.success) return operationTarget;
1223
- const connectId = operationTarget.payload.targetId;
1224
- const deviceId = deviceIdArg ?? void 0;
1225
- if (!params)
1226
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignTypedData requires params");
1227
- if (!params.path) {
1228
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "evmSignTypedData requires params.path");
1229
- }
1215
+ async evmSignTypedData(connectIdArg, deviceIdArg, paramsArg) {
1216
+ const call = this._beginCall("evmSignTypedData", connectIdArg, deviceIdArg, paramsArg);
1217
+ if (!call.success) return call;
1218
+ const { params } = call.payload;
1219
+ if (!params.path) return missingParamFailure("evmSignTypedData", "params.path");
1230
1220
  if (params.mode === "hash") {
1231
1221
  return (0, import_hwk_adapter_core3.failure)(
1232
1222
  import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1233
1223
  "Keystone always displays the full EIP-712 payload for on-device review \u2014 pre-hashed signing is not supported"
1234
1224
  );
1235
1225
  }
1236
- const signDataHex = Buffer.from(
1237
- params.dataJson ?? JSON.stringify(params.data),
1238
- "utf8"
1239
- ).toString("hex");
1240
- const path = normalizePath(params.path);
1241
- return this._signWithWallet({
1242
- connectId,
1243
- deviceId,
1244
- chain: "evm",
1245
- operationName: "evmSignTypedData",
1246
- buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1247
- requestId,
1248
- unsignedTxHex: signDataHex,
1249
- dataType: "typedData",
1250
- path,
1251
- xfp,
1252
- chainId: params.chainId,
1253
- origin: this._origin
1254
- }),
1255
- parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1256
- toPayload: (sig) => ({ signature: (0, import_hwk_adapter_core3.ensure0x)(sig.r + sig.s + sig.v) })
1257
- });
1226
+ if (typeof params.dataJson !== "string" || !params.dataJson) {
1227
+ return (0, import_hwk_adapter_core3.failure)(
1228
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1229
+ "Keystone evmSignTypedData requires params.dataJson, the original typed-data JSON text"
1230
+ );
1231
+ }
1232
+ const signDataHex = Buffer.from(params.dataJson, "utf8").toString("hex");
1233
+ return this._evmSign(
1234
+ "evmSignTypedData",
1235
+ call.payload,
1236
+ params.path,
1237
+ params.chainId,
1238
+ signDataHex,
1239
+ "typedData",
1240
+ evmMessageSignature
1241
+ );
1258
1242
  }
1259
1243
  // ---------------------------------------------------------------------------
1260
1244
  // BTC: 44'/49'/84' addresses derive offline from the account xpub; P2TR addresses
1261
1245
  // and structured-field tx signing are unsupported (the host builds a PSBT instead).
1262
1246
  // ---------------------------------------------------------------------------
1263
- async btcGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1264
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1265
- if (!operationTarget.success) return operationTarget;
1266
- const connectId = operationTarget.payload.targetId;
1267
- const deviceId = deviceIdArg ?? void 0;
1268
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetAddress requires params");
1269
- if (!params.path)
1270
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetAddress requires params.path");
1247
+ async btcGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1248
+ const call = this._beginCall("btcGetAddress", connectIdArg, deviceIdArg, paramsArg);
1249
+ if (!call.success) return call;
1250
+ const { params } = call.payload;
1251
+ if (!params.path) return missingParamFailure("btcGetAddress", "params.path");
1271
1252
  const btcParamsFailure = keystoneBtcParamsFailure(params);
1272
1253
  if (btcParamsFailure) return btcParamsFailure;
1273
1254
  const scriptType = btcScriptTypeFromPath(params.path);
@@ -1283,42 +1264,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
1283
1264
  "P2TR (purpose 86') needs an elliptic-curve library for BIP-341 tweaking, not yet wired in \u2014 44'/49'/84' work"
1284
1265
  );
1285
1266
  }
1286
- const normalizedPath = normalizePath(params.path);
1287
- const { accountPath, relativeDerivePath } = splitAccountPath(normalizedPath);
1288
- if (!relativeDerivePath) {
1289
- return (0, import_hwk_adapter_core3.failure)(
1290
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1291
- "btcGetAddress requires a full leaf path, e.g. m/84'/0'/0'/0/0"
1292
- );
1293
- }
1294
- if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1295
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1296
- }
1297
- return this._runJob(connectId, deviceId, async (signal) => {
1298
- const xpub = await this._fetchAccountXpub(
1299
- connectId,
1300
- deviceId,
1301
- "btc",
1302
- accountPath,
1303
- signal,
1304
- bundle
1305
- );
1306
- const address = this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType);
1307
- return (0, import_hwk_adapter_core3.success)({ address, path: normalizedPath });
1308
- });
1267
+ return this._addressFromAccountXpub(
1268
+ "btcGetAddress",
1269
+ "btc",
1270
+ call.payload,
1271
+ params.path,
1272
+ "m/84'/0'/0'/0/0",
1273
+ bundle,
1274
+ (xpub, relativeDerivePath) => this.urEngine.deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType)
1275
+ );
1309
1276
  }
1310
1277
  /**
1311
1278
  * `params.path` must be an account path (`m/84'/0'/0'`), the level Keystone syncs. An xpub is
1312
1279
  * script-type agnostic, so `86'` works here even though `btcGetAddress` rejects it.
1313
1280
  */
1314
- async btcGetPublicKey(connectIdArg, deviceIdArg, params, bundle) {
1315
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1316
- if (!operationTarget.success) return operationTarget;
1317
- const connectId = operationTarget.payload.targetId;
1318
- const deviceId = deviceIdArg ?? void 0;
1319
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params");
1320
- if (!params.path)
1321
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcGetPublicKey requires params.path");
1281
+ async btcGetPublicKey(connectIdArg, deviceIdArg, paramsArg, bundle) {
1282
+ const call = this._beginCall("btcGetPublicKey", connectIdArg, deviceIdArg, paramsArg);
1283
+ if (!call.success) return call;
1284
+ const { connectId, deviceId, params } = call.payload;
1285
+ if (!params.path) return missingParamFailure("btcGetPublicKey", "params.path");
1322
1286
  const btcParamsFailure = keystoneBtcParamsFailure(params);
1323
1287
  if (btcParamsFailure) return btcParamsFailure;
1324
1288
  const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
@@ -1328,9 +1292,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1328
1292
  "btcGetPublicKey requires an account path, e.g. m/84'/0'/0' (not a leaf path)"
1329
1293
  );
1330
1294
  }
1331
- if (!isKeystoneSignableBtcAccountPath(accountPath)) {
1332
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1333
- }
1295
+ const accountFailure = btcAccountFailure(accountPath);
1296
+ if (accountFailure) return accountFailure;
1334
1297
  return this._runJob(connectId, deviceId, async (signal) => {
1335
1298
  const xpub = await this._fetchAccountXpub(
1336
1299
  connectId,
@@ -1347,7 +1310,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1347
1310
  chainCode: meta.chainCode,
1348
1311
  depth: meta.depth,
1349
1312
  fingerprint: meta.parentFingerprint,
1350
- path: normalizePath(accountPath)
1313
+ path: normalizePath(accountPath),
1314
+ accountKey: this._exportedAccountKey(accountPath, xpub)
1351
1315
  });
1352
1316
  });
1353
1317
  }
@@ -1357,23 +1321,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
1357
1321
  "use btcSignPsbt \u2014 structured input/output signing needs host-side PSBT construction, not yet wired in"
1358
1322
  );
1359
1323
  }
1360
- async btcSignPsbt(connectIdArg, deviceIdArg, params) {
1361
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1362
- if (!operationTarget.success) return operationTarget;
1363
- const connectId = operationTarget.payload.targetId;
1364
- const deviceId = deviceIdArg ?? void 0;
1365
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcSignPsbt requires params");
1366
- if (!params.psbt)
1367
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcSignPsbt requires params.psbt");
1368
- if (!params.path)
1369
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcSignPsbt requires params.path");
1370
- if (!isKeystoneSignableBtcAccountPath(splitAccountPath(params.path).accountPath)) {
1371
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1372
- }
1324
+ async btcSignPsbt(connectIdArg, deviceIdArg, paramsArg) {
1325
+ const call = this._beginCall("btcSignPsbt", connectIdArg, deviceIdArg, paramsArg);
1326
+ if (!call.success) return call;
1327
+ const { connectId, deviceId, params } = call.payload;
1328
+ if (!params.psbt) return missingParamFailure("btcSignPsbt", "params.psbt");
1329
+ if (!params.path) return missingParamFailure("btcSignPsbt", "params.path");
1330
+ const accountFailure = btcAccountFailure(splitAccountPath(params.path).accountPath);
1331
+ if (accountFailure) return accountFailure;
1332
+ const requestPsbtHex = exactHex(params.psbt);
1333
+ if (requestPsbtHex === void 0) return invalidHexFailure("psbt");
1373
1334
  return this._runJob(connectId, deviceId, async (signal) => {
1374
1335
  const { record } = await this._ensureWalletKnown(connectId, deviceId, "btc", signal);
1375
1336
  _KeystoneAdapter._throwIfAborted(signal);
1376
- const requestUr = this.urEngine.buildBtcPsbtRequest((0, import_hwk_adapter_core3.stripHex)(params.psbt));
1337
+ const requestUr = this.urEngine.buildBtcPsbtRequest(requestPsbtHex);
1377
1338
  const responseUr = await this._resolveUr(
1378
1339
  record,
1379
1340
  requestUr,
@@ -1383,30 +1344,26 @@ var KeystoneAdapter = class _KeystoneAdapter {
1383
1344
  "btcSignPsbt"
1384
1345
  );
1385
1346
  _KeystoneAdapter._throwIfAborted(signal);
1386
- const signedPsbt = this.urEngine.parseBtcPsbt(responseUr);
1347
+ const signedPsbt = this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex);
1387
1348
  return (0, import_hwk_adapter_core3.success)({ signedPsbt });
1388
1349
  });
1389
1350
  }
1390
- async btcSignMessage(connectIdArg, deviceIdArg, params) {
1391
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1392
- if (!operationTarget.success) return operationTarget;
1393
- const connectId = operationTarget.payload.targetId;
1394
- const deviceId = deviceIdArg ?? void 0;
1395
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "btcSignMessage requires params");
1351
+ async btcSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1352
+ const call = this._beginCall("btcSignMessage", connectIdArg, deviceIdArg, paramsArg);
1353
+ if (!call.success) return call;
1354
+ const { connectId, deviceId, params } = call.payload;
1396
1355
  if (!params.path || params.message === void 0) {
1397
- return (0, import_hwk_adapter_core3.failure)(
1398
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1399
- "btcSignMessage requires params.path and params.message"
1400
- );
1356
+ return missingParamFailure("btcSignMessage", "params.path and params.message");
1401
1357
  }
1402
- const messageHex = params.hex ? (0, import_hwk_adapter_core3.stripHex)(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1358
+ const messageHex = messageToHex(params.message, params.hex);
1359
+ if (messageHex === void 0) return invalidHexFailure("message");
1403
1360
  const path = normalizePath(params.path);
1404
- if (!isKeystoneSignableBtcAccountPath(splitAccountPath(path).accountPath)) {
1405
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE);
1406
- }
1361
+ const accountFailure = btcAccountFailure(splitAccountPath(path).accountPath);
1362
+ if (accountFailure) return accountFailure;
1407
1363
  return this._signWithWallet({
1408
1364
  connectId,
1409
1365
  deviceId,
1366
+ path,
1410
1367
  chain: "btc",
1411
1368
  operationName: "btcSignMessage",
1412
1369
  buildRequest: (requestId, xfp) => this.urEngine.buildBtcMessageSignRequest({
@@ -1434,17 +1391,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
1434
1391
  return (0, import_hwk_adapter_core3.success)({ masterFingerprint: record.masterFingerprint });
1435
1392
  });
1436
1393
  }
1437
- // ---------------------------------------------------------------------------
1438
- // SOL
1439
- // ---------------------------------------------------------------------------
1440
- async solGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1441
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1442
- if (!operationTarget.success) return operationTarget;
1443
- const connectId = operationTarget.payload.targetId;
1444
- const deviceId = deviceIdArg ?? void 0;
1445
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solGetAddress requires params");
1446
- if (!params.path)
1447
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solGetAddress requires params.path");
1394
+ async solGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1395
+ const call = this._beginCall("solGetAddress", connectIdArg, deviceIdArg, paramsArg);
1396
+ if (!call.success) return call;
1397
+ const { connectId, deviceId, params } = call.payload;
1398
+ if (!params.path) return missingParamFailure("solGetAddress", "params.path");
1448
1399
  const solCoinTypeFailure = coinTypeFailure("sol", params.path);
1449
1400
  if (solCoinTypeFailure) return solCoinTypeFailure;
1450
1401
  const path = normalizePath(params.path);
@@ -1464,180 +1415,218 @@ var KeystoneAdapter = class _KeystoneAdapter {
1464
1415
  bundle
1465
1416
  );
1466
1417
  _KeystoneAdapter._throwIfAborted(signal);
1418
+ if (!/^[0-9a-f]{64}$/i.test(account.publicKey)) {
1419
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1420
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1421
+ message: "Keystone returned a Solana key that is not a 32-byte Ed25519 public key"
1422
+ });
1423
+ }
1467
1424
  const address = import_bs58.default.encode(Buffer.from(account.publicKey, "hex"));
1468
- return (0, import_hwk_adapter_core3.success)({ address, path });
1425
+ return (0, import_hwk_adapter_core3.success)({
1426
+ address,
1427
+ path,
1428
+ accountKey: { path, publicKey: account.publicKey }
1429
+ });
1469
1430
  });
1470
1431
  }
1471
- async solSignTransaction(connectIdArg, deviceIdArg, params) {
1472
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1473
- if (!operationTarget.success) return operationTarget;
1474
- const connectId = operationTarget.payload.targetId;
1475
- const deviceId = deviceIdArg ?? void 0;
1476
- if (!params)
1477
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solSignTransaction requires params");
1432
+ async solSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1433
+ const call = this._beginCall("solSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1434
+ if (!call.success) return call;
1435
+ const { params } = call.payload;
1478
1436
  if (!params.path || !params.serializedTx) {
1479
- return (0, import_hwk_adapter_core3.failure)(
1480
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1481
- "solSignTransaction requires params.path and params.serializedTx"
1482
- );
1483
- }
1484
- const path = normalizePath(params.path);
1485
- return this._signWithWallet({
1486
- connectId,
1487
- deviceId,
1488
- chain: "sol",
1489
- operationName: "solSignTransaction",
1490
- buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1491
- requestId,
1492
- unsignedPayloadHex: (0, import_hwk_adapter_core3.stripHex)(params.serializedTx),
1493
- dataType: "transaction",
1494
- path,
1495
- xfp,
1496
- origin: this._origin
1497
- }),
1498
- parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1499
- toPayload: (sig) => ({ signature: sig.signature })
1500
- });
1437
+ return missingParamFailure("solSignTransaction", "params.path and params.serializedTx");
1438
+ }
1439
+ const unsignedPayloadHex = exactHex(params.serializedTx);
1440
+ if (unsignedPayloadHex === void 0) return invalidHexFailure("serializedTx");
1441
+ return this._solSign(
1442
+ "solSignTransaction",
1443
+ call.payload,
1444
+ params.path,
1445
+ unsignedPayloadHex,
1446
+ "transaction"
1447
+ );
1501
1448
  }
1502
- async solSignMessage(connectIdArg, deviceIdArg, params) {
1503
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1504
- if (!operationTarget.success) return operationTarget;
1505
- const connectId = operationTarget.payload.targetId;
1506
- const deviceId = deviceIdArg ?? void 0;
1507
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "solSignMessage requires params");
1449
+ async solSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1450
+ const call = this._beginCall("solSignMessage", connectIdArg, deviceIdArg, paramsArg);
1451
+ if (!call.success) return call;
1452
+ const { params } = call.payload;
1508
1453
  if (!params.path || !params.message) {
1454
+ return missingParamFailure("solSignMessage", "params.path and params.message");
1455
+ }
1456
+ if (params.messageVersion !== void 0) {
1509
1457
  return (0, import_hwk_adapter_core3.failure)(
1510
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1511
- "solSignMessage requires params.path and params.message"
1458
+ import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1459
+ "Keystone signs Solana messages as raw bytes only; off-chain message format is not supported"
1512
1460
  );
1513
1461
  }
1514
- const path = normalizePath(params.path);
1515
- return this._signWithWallet({
1516
- connectId,
1517
- deviceId,
1518
- chain: "sol",
1519
- operationName: "solSignMessage",
1520
- buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1521
- requestId,
1522
- unsignedPayloadHex: (0, import_hwk_adapter_core3.stripHex)(params.message),
1523
- dataType: "message",
1524
- path,
1525
- xfp,
1526
- origin: this._origin
1527
- }),
1528
- parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1529
- toPayload: (sig) => ({ signature: sig.signature })
1530
- });
1462
+ const unsignedPayloadHex = exactHex(params.message);
1463
+ if (unsignedPayloadHex === void 0) return invalidHexFailure("message");
1464
+ return this._solSign(
1465
+ "solSignMessage",
1466
+ call.payload,
1467
+ params.path,
1468
+ unsignedPayloadHex,
1469
+ "message"
1470
+ );
1531
1471
  }
1532
1472
  // ---------------------------------------------------------------------------
1533
1473
  // TRON: keystone-sdk-rust layout (tags 5201/5202, firmware >= 2.5.0), not sdk.tron's
1534
1474
  // protobuf module; OneKey Pro's encoding under the same tag is rejected by the firmware.
1535
1475
  // ---------------------------------------------------------------------------
1536
- async tronGetAddress(connectIdArg, deviceIdArg, params, bundle) {
1537
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1538
- if (!operationTarget.success) return operationTarget;
1539
- const connectId = operationTarget.payload.targetId;
1540
- const deviceId = deviceIdArg ?? void 0;
1541
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronGetAddress requires params");
1542
- if (!params.path)
1543
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronGetAddress requires params.path");
1476
+ async tronGetAddress(connectIdArg, deviceIdArg, paramsArg, bundle) {
1477
+ const call = this._beginCall("tronGetAddress", connectIdArg, deviceIdArg, paramsArg);
1478
+ if (!call.success) return call;
1479
+ const { params } = call.payload;
1480
+ if (!params.path) return missingParamFailure("tronGetAddress", "params.path");
1544
1481
  const tronCoinTypeFailure = coinTypeFailure("tron", params.path);
1545
1482
  if (tronCoinTypeFailure) return tronCoinTypeFailure;
1546
- const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1483
+ return this._addressFromAccountXpub(
1484
+ "tronGetAddress",
1485
+ "tron",
1486
+ call.payload,
1487
+ params.path,
1488
+ "m/44'/195'/0'/0/0",
1489
+ bundle,
1490
+ (xpub, relativeDerivePath) => this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath)
1491
+ );
1492
+ }
1493
+ async tronSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1494
+ const call = this._beginCall("tronSignTransaction", connectIdArg, deviceIdArg, paramsArg);
1495
+ if (!call.success) return call;
1496
+ const { params } = call.payload;
1497
+ if (!params.path) return missingParamFailure("tronSignTransaction", "params.path");
1498
+ if (!params.rawTxHex) {
1499
+ return (0, import_hwk_adapter_core3.failure)(
1500
+ import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1501
+ "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1502
+ );
1503
+ }
1504
+ const rawTxHex = exactHex(params.rawTxHex);
1505
+ if (rawTxHex === void 0) return invalidHexFailure("rawTxHex");
1506
+ return this._tronSign("tronSignTransaction", call.payload, params.path, rawTxHex);
1507
+ }
1508
+ async tronSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1509
+ const call = this._beginCall("tronSignMessage", connectIdArg, deviceIdArg, paramsArg);
1510
+ if (!call.success) return call;
1511
+ const { params } = call.payload;
1512
+ if (!params.path) return missingParamFailure("tronSignMessage", "params.path");
1513
+ if (!params.messageHex) return missingParamFailure("tronSignMessage", "params.messageHex");
1514
+ if (params.messageType !== "V2") {
1515
+ return (0, import_hwk_adapter_core3.failure)(
1516
+ import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1517
+ 'Keystone signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1518
+ );
1519
+ }
1520
+ const messageHex = exactHex(params.messageHex);
1521
+ if (messageHex === void 0) return invalidHexFailure("messageHex");
1522
+ return this._tronSign(
1523
+ "tronSignMessage",
1524
+ call.payload,
1525
+ params.path,
1526
+ messageHex,
1527
+ 2 /* PersonalMessage */
1528
+ );
1529
+ }
1530
+ /** Resolves the call's target and requires params, before any method-specific check. */
1531
+ _beginCall(method, connectIdArg, deviceIdArg, params) {
1532
+ const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1533
+ if (!operationTarget.success) return operationTarget;
1534
+ if (!params) return missingParamFailure(method, "params");
1535
+ return (0, import_hwk_adapter_core3.success)({
1536
+ connectId: operationTarget.payload.targetId,
1537
+ deviceId: deviceIdArg ?? void 0,
1538
+ params
1539
+ });
1540
+ }
1541
+ /** Derives a leaf address offline from its account xpub. */
1542
+ async _addressFromAccountXpub(method, chain, { connectId, deviceId }, path, leafExample, bundle, derive) {
1543
+ const normalizedPath = normalizePath(path);
1544
+ const { accountPath, relativeDerivePath } = splitAccountPath(normalizedPath);
1547
1545
  if (!relativeDerivePath) {
1548
1546
  return (0, import_hwk_adapter_core3.failure)(
1549
1547
  import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1550
- "tronGetAddress requires a full leaf path, e.g. m/44'/195'/0'/0/0"
1548
+ `${method} requires a full leaf path, e.g. ${leafExample}`
1551
1549
  );
1552
1550
  }
1551
+ const accountFailure = chain === "btc" ? btcAccountFailure(accountPath) : void 0;
1552
+ if (accountFailure) return accountFailure;
1553
1553
  return this._runJob(connectId, deviceId, async (signal) => {
1554
1554
  const xpub = await this._fetchAccountXpub(
1555
1555
  connectId,
1556
1556
  deviceId,
1557
- "tron",
1557
+ chain,
1558
1558
  accountPath,
1559
1559
  signal,
1560
1560
  bundle
1561
1561
  );
1562
- const address = this.urEngine.deriveTronAddressFromXpub(xpub, relativeDerivePath);
1563
- return (0, import_hwk_adapter_core3.success)({ address, path: normalizePath(params.path) });
1562
+ return (0, import_hwk_adapter_core3.success)({
1563
+ address: derive(xpub, relativeDerivePath),
1564
+ path: normalizedPath,
1565
+ accountKey: this._exportedAccountKey(accountPath, xpub)
1566
+ });
1564
1567
  });
1565
1568
  }
1566
- async tronSignTransaction(connectIdArg, deviceIdArg, params) {
1567
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1568
- if (!operationTarget.success) return operationTarget;
1569
- const connectId = operationTarget.payload.targetId;
1570
- const deviceId = deviceIdArg ?? void 0;
1571
- if (!params)
1572
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignTransaction requires params");
1573
- if (!params.path) {
1574
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignTransaction requires params.path");
1575
- }
1576
- if (!params.rawTxHex) {
1577
- return (0, import_hwk_adapter_core3.failure)(
1578
- import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
1579
- "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1580
- );
1581
- }
1582
- const rawTxHex = (0, import_hwk_adapter_core3.stripHex)(params.rawTxHex);
1583
- const path = normalizePath(params.path);
1569
+ _evmSign(method, target, rawPath, chainId, signDataHex, dataType, toPayload) {
1570
+ const path = normalizePath(rawPath);
1584
1571
  return this._signWithWallet({
1585
- connectId,
1586
- deviceId,
1587
- chain: "tron",
1588
- operationName: "tronSignTransaction",
1589
- buildRequest: (requestId, xfp) => this.urEngine.buildTronSignRequest({
1572
+ connectId: target.connectId,
1573
+ deviceId: target.deviceId,
1574
+ path,
1575
+ chain: "evm",
1576
+ operationName: method,
1577
+ buildRequest: (requestId, xfp) => this.urEngine.buildEthSignRequest({
1578
+ requestId,
1579
+ unsignedTxHex: signDataHex,
1580
+ dataType,
1581
+ path,
1582
+ xfp,
1583
+ chainId,
1584
+ origin: this._origin
1585
+ }),
1586
+ parseResponse: (ur) => this.urEngine.parseEthSignature(ur),
1587
+ toPayload
1588
+ });
1589
+ }
1590
+ _solSign(method, target, rawPath, unsignedPayloadHex, dataType) {
1591
+ const path = normalizePath(rawPath);
1592
+ return this._signWithWallet({
1593
+ connectId: target.connectId,
1594
+ deviceId: target.deviceId,
1595
+ path,
1596
+ chain: "sol",
1597
+ operationName: method,
1598
+ buildRequest: (requestId, xfp) => this.urEngine.buildSolSignRequest({
1590
1599
  requestId,
1591
- rawTxHex,
1600
+ unsignedPayloadHex,
1601
+ dataType,
1592
1602
  path,
1593
1603
  xfp,
1594
1604
  origin: this._origin
1595
1605
  }),
1596
- parseResponse: (ur) => this.urEngine.parseTronSignature(ur),
1597
- // Keystone signs rawTxHex as given and returns only the signature, so no serializedTx.
1606
+ parseResponse: (ur) => this.urEngine.parseSolSignature(ur),
1598
1607
  toPayload: (sig) => ({ signature: sig.signature })
1599
1608
  });
1600
1609
  }
1601
- async tronSignMessage(connectIdArg, deviceIdArg, params) {
1602
- const operationTarget = this._resolveOperationTarget(connectIdArg, params?.operationId);
1603
- if (!operationTarget.success) return operationTarget;
1604
- const connectId = operationTarget.payload.targetId;
1605
- const deviceId = deviceIdArg ?? void 0;
1606
- if (!params) return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignMessage requires params");
1607
- if (!params.path) {
1608
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignMessage requires params.path");
1609
- }
1610
- if (!params.messageHex) {
1611
- return (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, "tronSignMessage requires params.messageHex");
1612
- }
1613
- if (params.messageType !== "V2") {
1614
- return (0, import_hwk_adapter_core3.failure)(
1615
- import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1616
- 'Keystone signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1617
- );
1618
- }
1619
- const messageHex = (0, import_hwk_adapter_core3.stripHex)(params.messageHex);
1620
- const path = normalizePath(params.path);
1610
+ _tronSign(method, target, rawPath, signDataHex, signType) {
1611
+ const path = normalizePath(rawPath);
1621
1612
  return this._signWithWallet({
1622
- connectId,
1623
- deviceId,
1613
+ connectId: target.connectId,
1614
+ deviceId: target.deviceId,
1615
+ path,
1624
1616
  chain: "tron",
1625
- operationName: "tronSignMessage",
1617
+ operationName: method,
1626
1618
  buildRequest: (requestId, xfp) => this.urEngine.buildTronSignRequest({
1627
1619
  requestId,
1628
- rawTxHex: messageHex,
1620
+ rawTxHex: signDataHex,
1629
1621
  path,
1630
1622
  xfp,
1631
- signType: 2 /* PersonalMessage */,
1623
+ signType,
1632
1624
  origin: this._origin
1633
1625
  }),
1634
1626
  parseResponse: (ur) => this.urEngine.parseTronSignature(ur),
1635
1627
  toPayload: (sig) => ({ signature: sig.signature })
1636
1628
  });
1637
1629
  }
1638
- // ---------------------------------------------------------------------------
1639
- // Internals
1640
- // ---------------------------------------------------------------------------
1641
1630
  async _runJob(connectId, deviceId, job) {
1642
1631
  try {
1643
1632
  return await this._jobQueue.enqueue(keystoneQueueKey(connectId, deviceId), job);
@@ -1661,14 +1650,33 @@ var KeystoneAdapter = class _KeystoneAdapter {
1661
1650
  message: "Keystone did not return an extended public key for this account path"
1662
1651
  });
1663
1652
  }
1653
+ const { publicKey } = this.urEngine.parseXpubMeta(account.extendedPublicKey);
1654
+ if (!/^0[23]/.test(publicKey)) {
1655
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1656
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1657
+ message: "Keystone returned an account key that is not a public key"
1658
+ });
1659
+ }
1664
1660
  return account.extendedPublicKey;
1665
1661
  }
1662
+ /** The exported key behind an address, reduced to the fields that identify it. */
1663
+ _exportedAccountKey(accountPath, xpub) {
1664
+ const { publicKey, chainCode } = this.urEngine.parseXpubMeta(xpub);
1665
+ return { path: normalizePath(accountPath), publicKey, chainCode, xpub };
1666
+ }
1666
1667
  /**
1667
1668
  * Signing needs only the wallet's mfp: the device re-derives the key from path+xfp, so no
1668
1669
  * per-path account lookup happens here.
1669
1670
  */
1670
1671
  _signWithWallet(args) {
1671
1672
  const { connectId, deviceId } = args;
1673
+ if (!isBip32Path(args.path)) {
1674
+ return Promise.resolve(
1675
+ (0, import_hwk_adapter_core3.failure)(import_hwk_adapter_core3.HardwareErrorCode.InvalidParams, `Invalid derivation path (${args.path})`)
1676
+ );
1677
+ }
1678
+ const chainCoinTypeFailure = coinTypeFailure(args.chain, args.path);
1679
+ if (chainCoinTypeFailure) return Promise.resolve(chainCoinTypeFailure);
1672
1680
  return this._runJob(connectId, deviceId, async (signal) => {
1673
1681
  const { record } = await this._ensureWalletKnown(connectId, deviceId, args.chain, signal);
1674
1682
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1705,8 +1713,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
1705
1713
  case "btcGetPublicKey":
1706
1714
  case "solGetAddress":
1707
1715
  return { hwkChain, path };
1708
- default:
1709
- return void 0;
1710
1716
  }
1711
1717
  }
1712
1718
  /**
@@ -1750,7 +1756,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1750
1756
  schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
1751
1757
  origin: this._origin
1752
1758
  });
1753
- const responseUr = await this._requestQrDisplayAndAwaitResponse(
1759
+ const responseUr = await this._requestQrAndAwaitResponse(
1754
1760
  record ? toDeviceInfo(record) : placeholderDeviceInfo(),
1755
1761
  { ...requestUr, animated: false },
1756
1762
  signal
@@ -1758,26 +1764,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
1758
1764
  _KeystoneAdapter._throwIfAborted(signal);
1759
1765
  const parsed = this.urEngine.parseAccountResponse(responseUr);
1760
1766
  this._assertParsedIdentity(parsed, target);
1761
- record = this._upsertDeviceRecord(parsed);
1762
1767
  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
- });
1771
- }
1772
1768
  scanned.set(accountKey(schema.hwkChain, schema.path), {
1773
- ...account,
1769
+ ...requireExportedPath(parsed, schema.path),
1774
1770
  hwkChain: schema.hwkChain
1775
1771
  });
1776
1772
  }
1773
+ record = this._upsertDeviceRecord(parsed);
1777
1774
  return { access: { channel: "qr", scanned }, masterFingerprint: record.masterFingerprint };
1778
1775
  });
1779
1776
  }
1780
- /** Resolve the wallet's master fingerprint from the connectId and/or deviceId the caller passed. */
1781
1777
  /**
1782
1778
  * A positional wallet id and an operation id must name the same wallet: otherwise the call
1783
1779
  * would run on the operation's wallet while the caller files the result under the other one.
@@ -1832,7 +1828,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
1832
1828
  if (expected.expectedMasterFingerprint && parsed.masterFingerprint !== expected.expectedMasterFingerprint) {
1833
1829
  throw (0, import_hwk_adapter_core3.createHwkError)({
1834
1830
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1835
- message: `Connected Keystone wallet (mfp ${parsed.masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1831
+ // The master fingerprint identifies the wallet; keep it out of messages that reach logs.
1832
+ message: "Connected Keystone wallet does not match the requested wallet"
1836
1833
  });
1837
1834
  }
1838
1835
  }
@@ -1862,7 +1859,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1862
1859
  * Opens a permitted USB Keystone and takes its mfp as the wallet identity. A known wallet gains
1863
1860
  * USB in place (`device-changed`); an unseen one becomes USB-only.
1864
1861
  */
1865
- async _connectUsb(expected, searchTargetId, signal) {
1862
+ async _connectUsb(connector, expected, searchTargetId, signal) {
1866
1863
  if (this._pendingUsbTeardowns > 0 || this._abandonedUsbConnects > 0) {
1867
1864
  return (0, import_hwk_adapter_core3.failure)(
1868
1865
  import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal,
@@ -1875,28 +1872,22 @@ var KeystoneAdapter = class _KeystoneAdapter {
1875
1872
  abandoned = true;
1876
1873
  this._abandonedUsbConnects += 1;
1877
1874
  };
1878
- signal?.addEventListener("abort", onAbort, { once: true });
1875
+ signal.addEventListener("abort", onAbort, { once: true });
1879
1876
  const pending = this._usbConnectTail.then(async () => {
1880
1877
  _KeystoneAdapter._throwIfAborted(signal);
1881
- return this._connectUsbExclusive(expected, searchTargetId, signal);
1878
+ return this._connectUsbExclusive(connector, expected, searchTargetId, signal);
1882
1879
  });
1883
1880
  const settled = pending.finally(() => {
1884
- signal?.removeEventListener("abort", onAbort);
1881
+ signal.removeEventListener("abort", onAbort);
1885
1882
  if (abandoned) this._abandonedUsbConnects -= 1;
1886
1883
  });
1887
1884
  this._usbConnectTail = settled.then(
1888
1885
  () => void 0,
1889
1886
  () => void 0
1890
1887
  );
1891
- return signal ? _KeystoneAdapter._abortable(signal, settled) : settled;
1888
+ return _KeystoneAdapter._abortable(signal, settled);
1892
1889
  }
1893
- async _connectUsbExclusive(expected, searchTargetId, signal) {
1894
- if (!this._usbConnector) {
1895
- return (0, import_hwk_adapter_core3.failure)(
1896
- import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
1897
- "No USB connector configured for this Keystone adapter"
1898
- );
1899
- }
1890
+ async _connectUsbExclusive(connector, expected, searchTargetId, signal) {
1900
1891
  let sessionId;
1901
1892
  try {
1902
1893
  let connectTarget = { type: "default" };
@@ -1908,7 +1899,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
1908
1899
  deviceIdentity: expected.expectedMasterFingerprint
1909
1900
  };
1910
1901
  }
1911
- const connector = this._usbConnector;
1912
1902
  const session = await (connector.connectTarget ? connector.connectTarget(connectTarget) : connector.connect(searchTargetId ?? expected.expectedMasterFingerprint));
1913
1903
  sessionId = session.sessionId;
1914
1904
  _KeystoneAdapter._throwIfAborted(signal);
@@ -1922,16 +1912,11 @@ var KeystoneAdapter = class _KeystoneAdapter {
1922
1912
  });
1923
1913
  }
1924
1914
  const masterFingerprint = mfpValue.toLowerCase();
1925
- if (expected.expectedMasterFingerprint && masterFingerprint !== expected.expectedMasterFingerprint) {
1926
- throw (0, import_hwk_adapter_core3.createHwkError)({
1927
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1928
- message: `Connected Keystone wallet (mfp ${masterFingerprint}) does not match the requested wallet fingerprint (${expected.expectedMasterFingerprint})`
1929
- });
1930
- }
1915
+ this._assertParsedIdentity({ masterFingerprint, accounts: [] }, expected);
1931
1916
  const previousUsbSessionId = this._devices.get(masterFingerprint)?.usbSessionId;
1932
1917
  if (previousUsbSessionId && previousUsbSessionId !== session.sessionId) {
1933
1918
  try {
1934
- await this._usbConnector.disconnect(previousUsbSessionId);
1919
+ await connector.disconnect(previousUsbSessionId);
1935
1920
  } catch {
1936
1921
  }
1937
1922
  }
@@ -1951,7 +1936,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
1951
1936
  } catch (err) {
1952
1937
  if (sessionId) {
1953
1938
  try {
1954
- await this._usbConnector.disconnect(sessionId);
1939
+ await connector.disconnect(sessionId);
1955
1940
  } catch {
1956
1941
  }
1957
1942
  }
@@ -1997,9 +1982,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
1997
1982
  }
1998
1983
  return void 0;
1999
1984
  }
2000
- const attached = await this._connectUsb({ expectedMasterFingerprint }, void 0, signal);
1985
+ const attached = await this._connectUsb(
1986
+ this._usbConnector,
1987
+ { expectedMasterFingerprint },
1988
+ void 0,
1989
+ signal
1990
+ );
2001
1991
  _KeystoneAdapter._throwIfAborted(signal);
2002
- if (!attached.success && attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal) {
1992
+ if (!attached.success && (attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal || attached.payload.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceOneDeviceOnly)) {
2003
1993
  throw (0, import_hwk_adapter_core3.createHwkError)({
2004
1994
  ...attached.payload,
2005
1995
  message: attached.payload.error
@@ -2059,9 +2049,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
2059
2049
  message: "USB channel is not connected for this Keystone wallet"
2060
2050
  });
2061
2051
  }
2062
- const result = await this._callUsbConnector(
2052
+ const result = await this._callUsbResolveUr(
2053
+ this._usbConnector,
2063
2054
  record.usbSessionId,
2064
- "resolveUr",
2065
2055
  requestUr,
2066
2056
  signal
2067
2057
  );
@@ -2071,11 +2061,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2071
2061
  if (usbErrorCode === import_hwk_adapter_core3.HardwareErrorCode.PayloadTooLarge && usbErrorOrigin !== "device") {
2072
2062
  if (!interactionRoute && !this._forcedTransport) {
2073
2063
  const displayDevice2 = toDeviceInfo(record);
2074
- return this._requestQrDisplayAndAwaitResponse(
2075
- displayDevice2,
2076
- { ...requestUr, animated },
2077
- signal
2078
- );
2064
+ return this._requestQrAndAwaitResponse(displayDevice2, { ...requestUr, animated }, signal);
2079
2065
  }
2080
2066
  throw usbError;
2081
2067
  }
@@ -2086,6 +2072,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2086
2072
  this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
2087
2073
  }
2088
2074
  record.usbSessionId = void 0;
2075
+ this.emitter.emit(import_hwk_adapter_core3.DEVICE.CHANGED, { type: import_hwk_adapter_core3.DEVICE.CHANGED, payload: toDeviceInfo(record) });
2089
2076
  if (interactionRoute) {
2090
2077
  throw this._endDisconnectedOperation(
2091
2078
  interactionRoute.operationId,
@@ -2103,11 +2090,20 @@ var KeystoneAdapter = class _KeystoneAdapter {
2103
2090
  });
2104
2091
  }
2105
2092
  }
2093
+ if (operationName && usbError.replyUnreadable === true) {
2094
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2095
+ code: usbErrorCode ?? import_hwk_adapter_core3.HardwareErrorCode.UnknownError,
2096
+ message: `Keystone ${operationName} may have completed but its reply could not be read`,
2097
+ origin: "device",
2098
+ recovery: { scope: "unknown" },
2099
+ params: (0, import_hwk_adapter_core3.operationMayHaveCompletedParams)(operationName)
2100
+ });
2101
+ }
2106
2102
  throw usbError;
2107
2103
  }
2108
2104
  const displayDevice = record ? toDeviceInfo(record) : placeholderDeviceInfo();
2109
2105
  try {
2110
- return await this._requestQrDisplayAndAwaitResponse(
2106
+ return await this._requestQrAndAwaitResponse(
2111
2107
  displayDevice,
2112
2108
  { ...requestUr, animated },
2113
2109
  signal
@@ -2171,6 +2167,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
2171
2167
  const responseUr = await this._resolveUr(existingRecord, requestUr, false, connectId, signal);
2172
2168
  _KeystoneAdapter._throwIfAborted(signal);
2173
2169
  const parsed = this.urEngine.parseAccountResponse(responseUr);
2170
+ const account = requireExportedPath(parsed, syncPath);
2174
2171
  let record;
2175
2172
  if (useSinglePathUsbExport && existingRecord) {
2176
2173
  if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
@@ -2186,13 +2183,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2186
2183
  viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
2187
2184
  });
2188
2185
  }
2189
- const account = parsed.accounts.find((a) => normalizePath(a.path) === syncPath);
2190
- if (!account) {
2191
- throw (0, import_hwk_adapter_core3.createHwkError)({
2192
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2193
- message: `Keystone did not return the requested derivation path (${syncPath})`
2194
- });
2195
- }
2196
2186
  return { record, account: { ...account, hwkChain } };
2197
2187
  }
2198
2188
  /**
@@ -2215,7 +2205,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
2215
2205
  });
2216
2206
  const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
2217
2207
  _KeystoneAdapter._throwIfAborted(signal);
2218
- return { record: this._upsertDeviceRecord(this.urEngine.parseAccountResponse(responseUr)) };
2208
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
2209
+ requireExportedPath(parsed, normalizePath(accountPath));
2210
+ return { record: this._upsertDeviceRecord(parsed) };
2219
2211
  }
2220
2212
  /**
2221
2213
  * The operation owning the running job, so a mid-call UI request can name it. Unpinned jobs map
@@ -2241,7 +2233,6 @@ var KeystoneAdapter = class _KeystoneAdapter {
2241
2233
  * a cancel reach the wait before the QR timeout.
2242
2234
  */
2243
2235
  async _awaitQrResponse(requestType, pending, signal) {
2244
- if (!signal) return pending;
2245
2236
  let settled = false;
2246
2237
  const onAbort = () => {
2247
2238
  if (!settled) this._uiRegistry.cancel(requestType);
@@ -2250,55 +2241,50 @@ var KeystoneAdapter = class _KeystoneAdapter {
2250
2241
  else signal.addEventListener("abort", onAbort, { once: true });
2251
2242
  try {
2252
2243
  return await pending;
2244
+ } catch (error) {
2245
+ const reason = signal.reason;
2246
+ if (signal.aborted && reason?.code === import_hwk_adapter_core3.HardwareErrorCode.OperationEnded) throw signal.reason;
2247
+ throw error;
2253
2248
  } finally {
2254
2249
  settled = true;
2255
2250
  signal.removeEventListener("abort", onAbort);
2256
2251
  }
2257
2252
  }
2258
- async _requestQrDisplayAndAwaitResponse(device, data, signal) {
2253
+ /** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
2254
+ async _requestQrAndAwaitResponse(device, data, signal) {
2255
+ const requestType = data ? import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY : import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN;
2259
2256
  const operationId = this._activeOperationId();
2260
- const waitPromise = this._uiRegistry.wait(
2261
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2262
- { timeoutMs: this._qrTimeoutMs, operationId }
2263
- );
2264
- this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY, {
2265
- type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2266
- payload: { device, data, operationId }
2267
- });
2268
- const response = await this._awaitQrResponse(
2269
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2270
- waitPromise,
2271
- signal
2272
- );
2273
- return { urType: response.urType, urData: response.urData };
2274
- }
2275
- async _requestQrScanAndAwaitResponse(device, signal) {
2276
- const operationId = this._activeOperationId();
2277
- const waitPromise = this._uiRegistry.wait(
2278
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN,
2279
- { timeoutMs: this._qrTimeoutMs, operationId }
2280
- );
2281
- this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN, {
2282
- type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN,
2283
- payload: { device, operationId }
2284
- });
2285
- const response = await this._awaitQrResponse(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN, waitPromise, signal);
2286
- return { urType: response.urType, urData: response.urData };
2287
- }
2288
- async _callUsbConnector(sessionId, method, params, signal) {
2289
- if (!this._usbConnector) {
2290
- throw (0, import_hwk_adapter_core3.createHwkError)({
2291
- code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
2292
- message: "No USB connector configured for this Keystone adapter"
2257
+ const release = operationId ? this._operations.retain(operationId) : void 0;
2258
+ try {
2259
+ const waitPromise = this._uiRegistry.wait(requestType, {
2260
+ timeoutMs: this._qrTimeoutMs,
2261
+ operationId
2293
2262
  });
2263
+ if (data) {
2264
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY, {
2265
+ type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_DISPLAY,
2266
+ payload: { device, data, operationId }
2267
+ });
2268
+ } else {
2269
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN, {
2270
+ type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_QR_SCAN,
2271
+ payload: { device, operationId }
2272
+ });
2273
+ }
2274
+ const response = await this._awaitQrResponse(requestType, waitPromise, signal);
2275
+ return { urType: response.urType, urData: response.urData };
2276
+ } finally {
2277
+ release?.();
2294
2278
  }
2279
+ }
2280
+ async _callUsbResolveUr(connector, sessionId, requestUr, signal) {
2295
2281
  if (this._pendingUsbTeardowns > 0 || this._unsettledUsbOperations.size > 0) {
2296
2282
  throw (0, import_hwk_adapter_core3.createHwkError)({
2297
2283
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceBusyInternal,
2298
- message: `Keystone USB is busy while calling ${method}`
2284
+ message: "Keystone USB is busy while calling resolveUr"
2299
2285
  });
2300
2286
  }
2301
- if (signal?.aborted) {
2287
+ if (signal.aborted) {
2302
2288
  throw signal.reason instanceof Error ? signal.reason : (0, import_hwk_adapter_core3.createHwkError)({
2303
2289
  code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
2304
2290
  message: "User aborted operation"
@@ -2307,12 +2293,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
2307
2293
  const releaseOperation = this._retainUsbOperation(`call:${sessionId}`);
2308
2294
  let rawCall;
2309
2295
  try {
2310
- rawCall = this._usbConnector.call(sessionId, method, params).finally(releaseOperation);
2296
+ rawCall = connector.call(sessionId, "resolveUr", requestUr).finally(releaseOperation);
2311
2297
  } catch (error) {
2312
2298
  releaseOperation();
2313
2299
  throw error;
2314
2300
  }
2315
- return signal ? _KeystoneAdapter._abortable(signal, rawCall) : rawCall;
2301
+ return _KeystoneAdapter._abortable(signal, rawCall);
2316
2302
  }
2317
2303
  _runUsbTeardown(task) {
2318
2304
  const previous = this._usbTeardownTail;
@@ -2374,6 +2360,16 @@ var KeystoneAdapter = class _KeystoneAdapter {
2374
2360
  );
2375
2361
  });
2376
2362
  }
2363
+ /** Settles with `signal`'s reason once it aborts; a later outcome of `promise` is dropped. */
2364
+ static _untilAborted(signal, promise) {
2365
+ promise.catch(() => void 0);
2366
+ if (signal.aborted) return Promise.reject(signal.reason);
2367
+ return new Promise((resolve, reject) => {
2368
+ const onAbort = () => reject(signal.reason);
2369
+ signal.addEventListener("abort", onAbort, { once: true });
2370
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort)).catch(() => void 0);
2371
+ });
2372
+ }
2377
2373
  static _throwIfAborted(signal) {
2378
2374
  if (signal?.aborted) {
2379
2375
  throw signal.reason instanceof Error ? signal.reason : new Error("Operation aborted");