@onekeyfe/hd-core 1.1.26-alpha.9 → 1.1.27-alpha.30

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.
Files changed (158) hide show
  1. package/__tests__/protocol-v2.test.ts +940 -0
  2. package/dist/api/BaseMethod.d.ts.map +1 -1
  3. package/dist/api/DirList.d.ts +10 -0
  4. package/dist/api/DirList.d.ts.map +1 -0
  5. package/dist/api/DirMake.d.ts +9 -0
  6. package/dist/api/DirMake.d.ts.map +1 -0
  7. package/dist/api/DirRemove.d.ts +9 -0
  8. package/dist/api/DirRemove.d.ts.map +1 -0
  9. package/dist/api/FileDelete.d.ts +9 -0
  10. package/dist/api/FileDelete.d.ts.map +1 -0
  11. package/dist/api/FileRead.d.ts +19 -0
  12. package/dist/api/FileRead.d.ts.map +1 -0
  13. package/dist/api/FileWrite.d.ts +23 -0
  14. package/dist/api/FileWrite.d.ts.map +1 -0
  15. package/dist/api/FirmwareUpdateV3.d.ts +1 -0
  16. package/dist/api/FirmwareUpdateV3.d.ts.map +1 -1
  17. package/dist/api/FirmwareUpdateV4.d.ts +32 -0
  18. package/dist/api/FirmwareUpdateV4.d.ts.map +1 -0
  19. package/dist/api/GetOnekeyFeatures.d.ts.map +1 -1
  20. package/dist/api/PathInfo.d.ts +9 -0
  21. package/dist/api/PathInfo.d.ts.map +1 -0
  22. package/dist/api/SearchDevices.d.ts +2 -1
  23. package/dist/api/SearchDevices.d.ts.map +1 -1
  24. package/dist/api/alephium/AlephiumSignTransaction.d.ts +1 -1
  25. package/dist/api/alephium/AlephiumSignTransaction.d.ts.map +1 -1
  26. package/dist/api/allnetwork/AllNetworkGetAddressBase.d.ts.map +1 -1
  27. package/dist/api/device/DeviceRebootToBoardloader.d.ts +1 -1
  28. package/dist/api/device/DeviceRebootToBoardloader.d.ts.map +1 -1
  29. package/dist/api/device/DeviceRebootToBootloader.d.ts.map +1 -1
  30. package/dist/api/firmware/FirmwareUpdateBaseMethod.d.ts +10 -2
  31. package/dist/api/firmware/FirmwareUpdateBaseMethod.d.ts.map +1 -1
  32. package/dist/api/index.d.ts +26 -0
  33. package/dist/api/index.d.ts.map +1 -1
  34. package/dist/api/protocol-v2/DevFirmwareUpdate.d.ts +7 -0
  35. package/dist/api/protocol-v2/DevFirmwareUpdate.d.ts.map +1 -0
  36. package/dist/api/protocol-v2/DevGetDeviceInfo.d.ts +7 -0
  37. package/dist/api/protocol-v2/DevGetDeviceInfo.d.ts.map +1 -0
  38. package/dist/api/protocol-v2/DevGetFirmwareUpdateStatus.d.ts +6 -0
  39. package/dist/api/protocol-v2/DevGetFirmwareUpdateStatus.d.ts.map +1 -0
  40. package/dist/api/protocol-v2/DevGetOnboardingStatus.d.ts +6 -0
  41. package/dist/api/protocol-v2/DevGetOnboardingStatus.d.ts.map +1 -0
  42. package/dist/api/protocol-v2/DevReboot.d.ts +7 -0
  43. package/dist/api/protocol-v2/DevReboot.d.ts.map +1 -0
  44. package/dist/api/protocol-v2/FactoryDeviceInfoSettings.d.ts +7 -0
  45. package/dist/api/protocol-v2/FactoryDeviceInfoSettings.d.ts.map +1 -0
  46. package/dist/api/protocol-v2/FactoryGetDeviceInfo.d.ts +6 -0
  47. package/dist/api/protocol-v2/FactoryGetDeviceInfo.d.ts.map +1 -0
  48. package/dist/api/protocol-v2/FilesystemFixPermission.d.ts +6 -0
  49. package/dist/api/protocol-v2/FilesystemFixPermission.d.ts.map +1 -0
  50. package/dist/api/protocol-v2/FilesystemFormat.d.ts +6 -0
  51. package/dist/api/protocol-v2/FilesystemFormat.d.ts.map +1 -0
  52. package/dist/api/protocol-v2/GetProtoVersion.d.ts +6 -0
  53. package/dist/api/protocol-v2/GetProtoVersion.d.ts.map +1 -0
  54. package/dist/api/protocol-v2/Ping.d.ts +8 -0
  55. package/dist/api/protocol-v2/Ping.d.ts.map +1 -0
  56. package/dist/api/protocol-v2/helpers.d.ts +49 -0
  57. package/dist/api/protocol-v2/helpers.d.ts.map +1 -0
  58. package/dist/api/ton/TonSignData.d.ts.map +1 -1
  59. package/dist/core/index.d.ts.map +1 -1
  60. package/dist/data-manager/DataManager.d.ts +4 -2
  61. package/dist/data-manager/DataManager.d.ts.map +1 -1
  62. package/dist/data-manager/TransportManager.d.ts +2 -1
  63. package/dist/data-manager/TransportManager.d.ts.map +1 -1
  64. package/dist/device/Device.d.ts +5 -3
  65. package/dist/device/Device.d.ts.map +1 -1
  66. package/dist/device/DeviceCommands.d.ts +8 -8
  67. package/dist/device/DeviceCommands.d.ts.map +1 -1
  68. package/dist/device/DeviceConnector.d.ts +2 -1
  69. package/dist/device/DeviceConnector.d.ts.map +1 -1
  70. package/dist/events/ui-request.d.ts +8 -0
  71. package/dist/events/ui-request.d.ts.map +1 -1
  72. package/dist/index.d.ts +188 -20
  73. package/dist/index.js +15627 -699
  74. package/dist/inject.d.ts.map +1 -1
  75. package/dist/protocols/protocol-v2/features.d.ts +56 -0
  76. package/dist/protocols/protocol-v2/features.d.ts.map +1 -0
  77. package/dist/protocols/protocol-v2/firmware.d.ts +12 -0
  78. package/dist/protocols/protocol-v2/firmware.d.ts.map +1 -0
  79. package/dist/protocols/protocol-v2/index.d.ts +3 -0
  80. package/dist/protocols/protocol-v2/index.d.ts.map +1 -0
  81. package/dist/types/api/export.d.ts +1 -1
  82. package/dist/types/api/export.d.ts.map +1 -1
  83. package/dist/types/api/firmwareUpdate.d.ts +7 -0
  84. package/dist/types/api/firmwareUpdate.d.ts.map +1 -1
  85. package/dist/types/api/index.d.ts +28 -1
  86. package/dist/types/api/index.d.ts.map +1 -1
  87. package/dist/types/api/protocolV2.d.ts +123 -0
  88. package/dist/types/api/protocolV2.d.ts.map +1 -0
  89. package/dist/types/api/searchDevices.d.ts +2 -2
  90. package/dist/types/api/searchDevices.d.ts.map +1 -1
  91. package/dist/types/device.d.ts +1 -1
  92. package/dist/types/device.d.ts.map +1 -1
  93. package/dist/types/params.d.ts +2 -0
  94. package/dist/types/params.d.ts.map +1 -1
  95. package/dist/types/settings.d.ts +1 -1
  96. package/dist/types/settings.d.ts.map +1 -1
  97. package/dist/utils/deviceInfoUtils.d.ts +1 -0
  98. package/dist/utils/deviceInfoUtils.d.ts.map +1 -1
  99. package/dist/utils/index.d.ts +1 -1
  100. package/dist/utils/index.d.ts.map +1 -1
  101. package/dist/utils/patch.d.ts +1 -1
  102. package/dist/utils/patch.d.ts.map +1 -1
  103. package/dist/utils/versionUtils.d.ts +1 -1
  104. package/package.json +5 -5
  105. package/src/api/BaseMethod.ts +10 -0
  106. package/src/api/DirList.ts +25 -0
  107. package/src/api/DirMake.ts +20 -0
  108. package/src/api/DirRemove.ts +20 -0
  109. package/src/api/FileDelete.ts +20 -0
  110. package/src/api/FileRead.ts +158 -0
  111. package/src/api/FileWrite.ts +191 -0
  112. package/src/api/FirmwareUpdateV3.ts +21 -4
  113. package/src/api/FirmwareUpdateV4.ts +810 -0
  114. package/src/api/GetOnekeyFeatures.ts +75 -3
  115. package/src/api/PathInfo.ts +24 -0
  116. package/src/api/SearchDevices.ts +7 -2
  117. package/src/api/alephium/AlephiumSignTransaction.ts +6 -5
  118. package/src/api/allnetwork/AllNetworkGetAddressBase.ts +10 -1
  119. package/src/api/device/DeviceRebootToBoardloader.ts +10 -1
  120. package/src/api/device/DeviceRebootToBootloader.ts +10 -1
  121. package/src/api/firmware/FirmwareUpdateBaseMethod.ts +27 -4
  122. package/src/api/index.ts +28 -0
  123. package/src/api/protocol-v2/DevFirmwareUpdate.ts +33 -0
  124. package/src/api/protocol-v2/DevGetDeviceInfo.ts +35 -0
  125. package/src/api/protocol-v2/DevGetFirmwareUpdateStatus.ts +18 -0
  126. package/src/api/protocol-v2/DevGetOnboardingStatus.ts +18 -0
  127. package/src/api/protocol-v2/DevReboot.ts +22 -0
  128. package/src/api/protocol-v2/FactoryDeviceInfoSettings.ts +27 -0
  129. package/src/api/protocol-v2/FactoryGetDeviceInfo.ts +18 -0
  130. package/src/api/protocol-v2/FilesystemFixPermission.ts +14 -0
  131. package/src/api/protocol-v2/FilesystemFormat.ts +14 -0
  132. package/src/api/protocol-v2/GetProtoVersion.ts +14 -0
  133. package/src/api/protocol-v2/Ping.ts +16 -0
  134. package/src/api/protocol-v2/helpers.ts +138 -0
  135. package/src/api/ton/TonSignData.ts +4 -1
  136. package/src/core/index.ts +26 -4
  137. package/src/data/messages/messages-pro2.json +13102 -0
  138. package/src/data-manager/DataManager.ts +6 -2
  139. package/src/data-manager/TransportManager.ts +29 -3
  140. package/src/device/Device.ts +68 -8
  141. package/src/device/DeviceCommands.ts +162 -26
  142. package/src/device/DeviceConnector.ts +29 -4
  143. package/src/device/DevicePool.ts +1 -1
  144. package/src/events/ui-request.ts +8 -0
  145. package/src/inject.ts +42 -1
  146. package/src/protocols/protocol-v2/features.ts +266 -0
  147. package/src/protocols/protocol-v2/firmware.ts +26 -0
  148. package/src/protocols/protocol-v2/index.ts +2 -0
  149. package/src/types/api/export.ts +1 -0
  150. package/src/types/api/firmwareUpdate.ts +12 -0
  151. package/src/types/api/index.ts +63 -1
  152. package/src/types/api/protocolV2.ts +221 -0
  153. package/src/types/api/searchDevices.ts +2 -2
  154. package/src/types/device.ts +3 -1
  155. package/src/types/params.ts +7 -0
  156. package/src/types/settings.ts +1 -1
  157. package/src/utils/deviceInfoUtils.ts +14 -5
  158. package/src/utils/index.ts +1 -0
@@ -4,6 +4,7 @@ import { EDeviceType, EFirmwareType } from '@onekeyfe/hd-shared';
4
4
 
5
5
  import MessagesJSON from '../data/messages/messages.json';
6
6
  import MessagesLegacyV1JSON from '../data/messages/messages_legacy_v1.json';
7
+ import MessagesPro2JSON from '../data/messages/messages-pro2.json';
7
8
  import {
8
9
  LoggerNames,
9
10
  getDeviceBLEFirmwareVersion,
@@ -40,7 +41,7 @@ export const FIRMWARE_FIELDS = [
40
41
 
41
42
  export type IFirmwareField = (typeof FIRMWARE_FIELDS)[number];
42
43
 
43
- export type MessageVersion = 'latest' | 'v1';
44
+ export type MessageVersion = 'latest' | 'v1' | 'protocolV2';
44
45
 
45
46
  const FIRMWARE_FIELD_TYPE_MAP: Readonly<Record<IFirmwareField, EFirmwareType>> = {
46
47
  firmware: EFirmwareType.Universal,
@@ -62,7 +63,9 @@ function getFirmwareTypeFromField(firmwareField: IFirmwareField): EFirmwareType
62
63
  }
63
64
 
64
65
  export default class DataManager {
65
- static deviceMap: DeviceTypeMap = {
66
+ static deviceMap: DeviceTypeMap & {
67
+ [k: string]: DeviceTypeMap[keyof DeviceTypeMap] | undefined;
68
+ } = {
66
69
  [EDeviceType.Classic]: {
67
70
  firmware: [],
68
71
  ble: [],
@@ -96,6 +99,7 @@ export default class DataManager {
96
99
  static messages: { [version in MessageVersion]: JSON } = {
97
100
  latest: MessagesJSON as unknown as JSON,
98
101
  v1: MessagesLegacyV1JSON as unknown as JSON,
102
+ protocolV2: MessagesPro2JSON as unknown as JSON,
99
103
  };
100
104
 
101
105
  static lastCheckTimestamp = 0;
@@ -17,6 +17,7 @@ const LowLevelLogger = getLogger(LoggerNames.HdTransportLowLevel);
17
17
  const NodeUsbLogger = getLogger(LoggerNames.HdTransportNodeUsb);
18
18
  const WebBleLogger = getLogger(LoggerNames.HdWebBleTransport);
19
19
  const WebUsbLogger = getLogger(LoggerNames.HdTransportWebUsb);
20
+ const REACT_NATIVE_BLE_SCAN_TIMEOUT_MS = 8000;
20
21
 
21
22
  /**
22
23
  * transport 在同一个环境中只会存在一个
@@ -74,6 +75,9 @@ export default class TransportManager {
74
75
  }
75
76
  Log.debug('Configuring transports');
76
77
  await this.transport.configure(JSON.stringify(this.defaultMessages));
78
+ this.currentMessages = this.defaultMessages;
79
+ this.messageVersion = 'latest';
80
+ await this.configureProtocolV2Messages();
77
81
  Log.debug('Configuring transports done');
78
82
  } catch (error) {
79
83
  Log.debug('Initializing transports error: ', error);
@@ -83,8 +87,19 @@ export default class TransportManager {
83
87
  }
84
88
  }
85
89
 
86
- static async reconfigure(features?: Features | undefined) {
87
- Log.debug(`Begin reconfiguring transports`);
90
+ /**
91
+ * Re-load the transport's main protobuf schema based on a device's reported features.
92
+ *
93
+ * This handles message-version compatibility within Protocol V1 (e.g. Touch's classic
94
+ * vs latest schema). It is NOT used to switch between Protocol V1 and Protocol V2 —
95
+ * the transport already holds both schemas after initial configure(), and routes per
96
+ * device by `getProtocolType()`.
97
+ */
98
+ static async reconfigure(features?: Features) {
99
+ if (!features) {
100
+ return;
101
+ }
102
+
88
103
  const { messageVersion, messages } = getSupportMessageVersion(features);
89
104
 
90
105
  if (this.currentMessages === messages || !messages) {
@@ -109,7 +124,9 @@ export default class TransportManager {
109
124
  const env = DataManager.getSettings('env');
110
125
  if (env === 'react-native') {
111
126
  /** Actually initializes the ReactNativeTransport */
112
- this.transport = new TransportConstructor({ scanTimeout: 3000 }) as unknown as Transport;
127
+ this.transport = new TransportConstructor({
128
+ scanTimeout: REACT_NATIVE_BLE_SCAN_TIMEOUT_MS,
129
+ }) as unknown as Transport;
113
130
  } else {
114
131
  /** Actually initializes the HttpTransport */
115
132
  this.transport = new TransportConstructor() as unknown as Transport;
@@ -130,6 +147,15 @@ export default class TransportManager {
130
147
  return this.transport;
131
148
  }
132
149
 
150
+ private static async configureProtocolV2Messages() {
151
+ const protocolV2Messages = DataManager.getProtobufMessages('protocolV2');
152
+ const { configureProtocolV2 } = this.transport;
153
+ if (protocolV2Messages && typeof configureProtocolV2 === 'function') {
154
+ await configureProtocolV2.call(this.transport, JSON.stringify(protocolV2Messages));
155
+ Log.debug('Protocol V2 messages configured');
156
+ }
157
+ }
158
+
133
159
  static getDefaultMessages() {
134
160
  return this.defaultMessages;
135
161
  }
@@ -41,6 +41,7 @@ import { DataManager } from '../data-manager';
41
41
  import TransportManager from '../data-manager/TransportManager';
42
42
  import { toHardened } from '../api/helpers/pathUtils';
43
43
  import { existCapability } from '../utils/capabilitieUtils';
44
+ import { getProtocolV2Features } from '../protocols/protocol-v2';
44
45
 
45
46
  import type { PROTO } from '../constants';
46
47
  import type {
@@ -49,7 +50,7 @@ import type {
49
50
  PassphraseRequestPayload,
50
51
  } from '../events';
51
52
  import type { PassphrasePromptResponse } from './DeviceCommands';
52
- import type { Deferred } from '@onekeyfe/hd-shared';
53
+ import type { Deferred, HardwareConnectProtocol } from '@onekeyfe/hd-shared';
53
54
  import type { OneKeyDeviceInfo as DeviceDescriptor } from '@onekeyfe/hd-transport';
54
55
  import type DeviceConnector from './DeviceConnector';
55
56
 
@@ -58,6 +59,7 @@ export type InitOptions = {
58
59
  deviceId?: string;
59
60
  passphraseState?: string;
60
61
  deriveCardano?: boolean;
62
+ connectProtocol?: HardwareConnectProtocol;
61
63
  };
62
64
 
63
65
  export type RunOptions = {
@@ -252,13 +254,13 @@ export class Device extends EventEmitter {
252
254
  * Device connect
253
255
  * @returns {Promise<boolean>}
254
256
  */
255
- connect() {
257
+ connect(connectProtocol?: HardwareConnectProtocol) {
256
258
  const env = DataManager.getSettings('env');
257
259
  // eslint-disable-next-line no-async-promise-executor
258
260
  return new Promise<boolean>(async (resolve, reject) => {
259
261
  if (DataManager.isBleConnect(env)) {
260
262
  try {
261
- await this.acquire();
263
+ await this.acquire(connectProtocol);
262
264
  resolve(true);
263
265
  } catch (error) {
264
266
  reject(error);
@@ -268,7 +270,7 @@ export class Device extends EventEmitter {
268
270
  // 不存在 Session ID 或存在 Session ID 但设备在别处使用,都需要 acquire 获取最新 sessionID
269
271
  if (!this.mainId || (!this.isUsedHere() && this.originalDescriptor)) {
270
272
  try {
271
- await this.acquire();
273
+ await this.acquire(connectProtocol);
272
274
  resolve(true);
273
275
  } catch (error) {
274
276
  reject(error);
@@ -283,23 +285,40 @@ export class Device extends EventEmitter {
283
285
  });
284
286
  }
285
287
 
286
- async acquire() {
288
+ async acquire(connectProtocol?: HardwareConnectProtocol) {
287
289
  const env = DataManager.getSettings('env');
288
290
  const mainIdKey = DataManager.isBleConnect(env) ? 'id' : 'session';
291
+ const expectedProtocol = connectProtocol ?? this.originalDescriptor.protocolType;
289
292
  try {
290
293
  if (DataManager.isBleConnect(env)) {
291
- const res = await this.deviceConnector?.acquire(this.originalDescriptor.id);
294
+ const res = await this.deviceConnector?.acquire(
295
+ this.originalDescriptor.id,
296
+ undefined,
297
+ true,
298
+ expectedProtocol
299
+ );
292
300
  this.mainId = (res as unknown as any).uuid ?? '';
293
301
  Log.debug('Expected uuid:', this.mainId);
294
302
  } else {
295
303
  this.mainId = await this.deviceConnector?.acquire(
296
304
  this.originalDescriptor.path,
297
- this.originalDescriptor.session
305
+ this.originalDescriptor.session,
306
+ undefined,
307
+ expectedProtocol
298
308
  );
299
309
  Log.debug('Expected session id:', this.mainId);
300
310
  }
301
311
  this.deviceAcquired = true;
302
312
  this.updateDescriptor({ [mainIdKey]: this.mainId } as unknown as DeviceDescriptor);
313
+
314
+ // Propagate protocol version detected during acquire.
315
+ const detectedProtocol = TransportManager.transport?.getProtocolType?.(
316
+ DataManager.isBleConnect(env) ? this.originalDescriptor.id : this.originalDescriptor.path
317
+ );
318
+ if (detectedProtocol) {
319
+ this.originalDescriptor.protocolType = detectedProtocol;
320
+ }
321
+
303
322
  if (this.commands) {
304
323
  await this.commands.dispose(false);
305
324
  }
@@ -462,6 +481,17 @@ export class Device extends EventEmitter {
462
481
  }
463
482
 
464
483
  async initialize(options?: InitOptions) {
484
+ // Protocol V2 不支持传统 Initialize,直接使用协议专用初始化流程。
485
+ if (this.originalDescriptor.protocolType === 'V2') {
486
+ this.passphraseState = options?.passphraseState;
487
+ if (this.features && !this.featuresNeedsReload && !options?.initSession) {
488
+ Log.debug('Skip Protocol V2 feature adapter; cached features are available');
489
+ return;
490
+ }
491
+ await this._initializeProtocolV2();
492
+ return;
493
+ }
494
+
465
495
  // Log.debug('initialize param:', options);
466
496
 
467
497
  this.passphraseState = options?.passphraseState;
@@ -510,6 +540,36 @@ export class Device extends EventEmitter {
510
540
  }
511
541
  }
512
542
 
543
+ /**
544
+ * Device initialization over Protocol V2.
545
+ *
546
+ * Protocol V2 不走传统 Initialize/GetFeatures。当前固件暂不支持
547
+ * DevGetDeviceInfo,初始化阶段只通过 Ping 建立基础 Features 视图。
548
+ */
549
+ private async _initializeProtocolV2() {
550
+ Log.debug('Initialize device via Protocol V2 feature adapter');
551
+
552
+ try {
553
+ const features = await Promise.race([
554
+ getProtocolV2Features({
555
+ commands: this.commands,
556
+ descriptor: this.originalDescriptor,
557
+ timeoutMs: 10 * 1000,
558
+ }),
559
+ new Promise<never>((_, reject) => {
560
+ setTimeout(() => {
561
+ reject(ERRORS.TypedError(HardwareErrorCode.DeviceInitializeFailed));
562
+ }, 10 * 1000);
563
+ }),
564
+ ]);
565
+ Log.debug('Protocol V2 normalized features:', features);
566
+ this._updateFeatures(features);
567
+ } catch (error) {
568
+ Log.error('Protocol V2 initialization failed:', error);
569
+ throw error;
570
+ }
571
+ }
572
+
513
573
  async getFeatures() {
514
574
  const { message } = await this.commands.typedCall('GetFeatures', 'Features', {});
515
575
  this._updateFeatures(message);
@@ -580,7 +640,7 @@ export class Device extends EventEmitter {
580
640
  const env = DataManager.getSettings('env');
581
641
  if (env !== 'react-native') {
582
642
  try {
583
- await this.acquire();
643
+ await this.acquire(options.connectProtocol);
584
644
  } catch (error) {
585
645
  this.runPromise = null;
586
646
  return Promise.reject(error);
@@ -12,7 +12,12 @@ import {
12
12
  } from '../utils/tracing';
13
13
 
14
14
  import type { Device } from './Device';
15
- import type { FailureType, Messages, Transport } from '@onekeyfe/hd-transport';
15
+ import type {
16
+ FailureType,
17
+ Messages,
18
+ Transport,
19
+ TransportCallOptions,
20
+ } from '@onekeyfe/hd-transport';
16
21
 
17
22
  export type PassphrasePromptResponse = {
18
23
  passphrase?: string;
@@ -22,16 +27,119 @@ export type PassphrasePromptResponse = {
22
27
  };
23
28
 
24
29
  type MessageType = Messages.MessageType;
25
- type MessageKey = keyof MessageType;
30
+ type MessageKey = Extract<keyof MessageType, string>;
26
31
  export type TypedResponseMessage<T extends MessageKey> = {
27
32
  type: T;
28
33
  message: MessageType[T];
29
34
  };
30
35
  type TypedCallResponseMap = {
31
- [K in keyof MessageType]: TypedResponseMessage<K>;
36
+ [K in MessageKey]: TypedResponseMessage<K>;
32
37
  };
33
38
  export type DefaultMessageResponse = TypedCallResponseMap[keyof MessageType];
34
39
 
40
+ const MAX_DEBUG_ARRAY_ITEMS = 20;
41
+ const MAX_DEBUG_OBJECT_KEYS = 40;
42
+ const MAX_DEBUG_STRING_LENGTH = 512;
43
+ const MAX_DEBUG_DEPTH = 4;
44
+ const HIGH_VOLUME_DEBUG_CALLS = new Set([
45
+ 'FilesystemFileRead',
46
+ 'FilesystemFileWrite',
47
+ 'FileRead',
48
+ 'FileWrite',
49
+ 'EmmcFileRead',
50
+ 'EmmcFileWrite',
51
+ 'FirmwareUpload',
52
+ 'ResourceAck',
53
+ ]);
54
+
55
+ function shouldReduceDebugForCall(type: string) {
56
+ return HIGH_VOLUME_DEBUG_CALLS.has(type);
57
+ }
58
+
59
+ function getBinaryByteLength(value: unknown): number | undefined {
60
+ if (value instanceof ArrayBuffer) {
61
+ return value.byteLength;
62
+ }
63
+
64
+ if (ArrayBuffer.isView(value)) {
65
+ return value.byteLength;
66
+ }
67
+
68
+ if (typeof Blob !== 'undefined' && value instanceof Blob) {
69
+ return value.size;
70
+ }
71
+
72
+ return undefined;
73
+ }
74
+
75
+ function summarizeRedactedData(value: unknown): string {
76
+ const byteLength = getBinaryByteLength(value);
77
+ if (byteLength !== undefined) {
78
+ return `[redacted data: ${byteLength} bytes]`;
79
+ }
80
+
81
+ if (typeof value === 'string') {
82
+ return `[redacted data: string length=${value.length}]`;
83
+ }
84
+
85
+ if (Array.isArray(value)) {
86
+ return `[redacted data: array length=${value.length}]`;
87
+ }
88
+
89
+ if (value && typeof value === 'object') {
90
+ return `[redacted data: object keys=${Object.keys(value).length}]`;
91
+ }
92
+
93
+ return `[redacted data: ${typeof value}]`;
94
+ }
95
+
96
+ function sanitizeDebugPayload(value: unknown, key = '', depth = 0): unknown {
97
+ if (key === 'data' && value !== null && value !== undefined) {
98
+ return summarizeRedactedData(value);
99
+ }
100
+
101
+ const byteLength = getBinaryByteLength(value);
102
+ if (byteLength !== undefined) {
103
+ return `[binary: ${byteLength} bytes]`;
104
+ }
105
+
106
+ if (typeof value === 'string') {
107
+ return value.length > MAX_DEBUG_STRING_LENGTH
108
+ ? `${value.slice(0, MAX_DEBUG_STRING_LENGTH)}... (len=${value.length})`
109
+ : value;
110
+ }
111
+
112
+ if (!value || typeof value !== 'object') {
113
+ return value;
114
+ }
115
+
116
+ if (depth >= MAX_DEBUG_DEPTH) {
117
+ return Array.isArray(value)
118
+ ? `[array length=${value.length}]`
119
+ : `[object keys=${Object.keys(value).length}]`;
120
+ }
121
+
122
+ if (Array.isArray(value)) {
123
+ const items = value
124
+ .slice(0, MAX_DEBUG_ARRAY_ITEMS)
125
+ .map(item => sanitizeDebugPayload(item, key, depth + 1));
126
+ if (value.length > MAX_DEBUG_ARRAY_ITEMS) {
127
+ items.push(`... (${value.length - MAX_DEBUG_ARRAY_ITEMS} more)`);
128
+ }
129
+ return items;
130
+ }
131
+
132
+ const entries = Object.entries(value).slice(0, MAX_DEBUG_OBJECT_KEYS);
133
+ const sanitized: Record<string, unknown> = {};
134
+ entries.forEach(([entryKey, entryValue]) => {
135
+ sanitized[entryKey] = sanitizeDebugPayload(entryValue, entryKey, depth + 1);
136
+ });
137
+ if (Object.keys(value).length > MAX_DEBUG_OBJECT_KEYS) {
138
+ sanitized.__truncated__ = `${Object.keys(value).length - MAX_DEBUG_OBJECT_KEYS} more keys`;
139
+ }
140
+ return sanitized;
141
+ }
142
+
35
143
  const assertType = (res: DefaultMessageResponse, resType: string | string[]) => {
36
144
  const splitResTypes = Array.isArray(resType) ? resType : resType.split('|');
37
145
  if (!splitResTypes.includes(res.type)) {
@@ -224,17 +332,21 @@ export class DeviceCommands {
224
332
  // Sends an async message to the opened device.
225
333
  async call(
226
334
  type: MessageKey,
227
- msg: DefaultMessageResponse['message'] = {}
335
+ msg?: DefaultMessageResponse['message'],
336
+ options?: TransportCallOptions
228
337
  ): Promise<DefaultMessageResponse> {
229
- Log.debug('[DeviceCommands] [call] Sending', type);
338
+ const shouldReduceDebug = shouldReduceDebugForCall(type);
339
+ if (!shouldReduceDebug) {
340
+ Log.debug('[DeviceCommands] [call] Sending', type);
341
+ }
230
342
 
231
343
  try {
232
- const promise = this.transport.call(this.mainId, type, msg) as any;
344
+ const promise = this.transport.call(this.mainId, type, msg ?? {}, options) as any;
233
345
  this.callPromise = promise;
234
346
  const res = await promise;
235
347
  if (res.type === 'Failure') {
236
348
  LogCore.debug('[DeviceCommands] [call] Received', res.type, res.message);
237
- } else {
349
+ } else if (!shouldReduceDebug) {
238
350
  LogCore.debug('[DeviceCommands] [call] Received', res.type);
239
351
  }
240
352
  return res;
@@ -283,19 +395,22 @@ export class DeviceCommands {
283
395
  typedCall<T extends MessageKey, R extends MessageKey[]>(
284
396
  type: T,
285
397
  resType: R,
286
- msg?: MessageType[T]
398
+ msg?: MessageType[T],
399
+ options?: TransportCallOptions
287
400
  ): Promise<TypedCallResponseMap[R[number]]>;
288
401
 
289
402
  typedCall<T extends MessageKey, R extends MessageKey>(
290
403
  type: T,
291
404
  resType: R,
292
- msg?: MessageType[T]
405
+ msg?: MessageType[T],
406
+ options?: TransportCallOptions
293
407
  ): Promise<TypedResponseMessage<R>>;
294
408
 
295
409
  async typedCall(
296
410
  type: MessageKey,
297
411
  resType: MessageKey | MessageKey[],
298
- msg?: DefaultMessageResponse['message']
412
+ msg?: DefaultMessageResponse['message'],
413
+ options?: TransportCallOptions
299
414
  ) {
300
415
  if (this.disposed) {
301
416
  throw ERRORS.TypedError(
@@ -312,16 +427,24 @@ export class DeviceCommands {
312
427
  'PassphraseAck',
313
428
  'Cancel',
314
429
  'BixinPinInputOnDevice',
430
+ 'FilesystemFileRead',
431
+ 'FilesystemFileWrite',
432
+ 'FileRead',
433
+ 'FileWrite',
434
+ 'EmmcFileRead',
435
+ 'EmmcFileWrite',
436
+ 'FirmwareUpload',
437
+ 'ResourceAck',
315
438
  ] as any;
316
439
  if (!skipTypes.includes(type) && msg) {
317
440
  // Use debug channel to avoid noise escalation
318
- Log.debug('[DeviceCommands] [typedCall] Sending payload', type, msg);
441
+ Log.debug('[DeviceCommands] [typedCall] Sending payload', type, sanitizeDebugPayload(msg));
319
442
  }
320
443
  } catch (e) {
321
444
  // ignore logging errors
322
445
  }
323
446
 
324
- const response = await this._commonCall(type, msg);
447
+ const response = await this._commonCall(type, msg, options);
325
448
  try {
326
449
  assertType(response, resType);
327
450
  } catch (error) {
@@ -334,6 +457,12 @@ export class DeviceCommands {
334
457
  // throw bridge network error
335
458
  if (error instanceof HardwareError) {
336
459
  if (error.errorCode === HardwareErrorCode.ResponseUnexpectTypeError) {
460
+ Log.debug('[DeviceCommands] [typedCall] Unexpected response type', {
461
+ request: type,
462
+ expected: resType,
463
+ received: response.type,
464
+ response: sanitizeDebugPayload(response.message),
465
+ });
337
466
  // Do not intercept CallMethodError
338
467
  // Do not intercept “assertType: Response of unexpected type” error
339
468
  // Blocking the above two messages will not know what the specific error message is, and the specific error should be handled by the subsequent business logic.
@@ -347,7 +476,7 @@ export class DeviceCommands {
347
476
  if (error.message.indexOf('BridgeDeviceDisconnected') > -1) {
348
477
  throw ERRORS.TypedError(HardwareErrorCode.BridgeDeviceDisconnected);
349
478
  }
350
- throw ERRORS.TypedError(HardwareErrorCode.ResponseUnexpectTypeError);
479
+ throw error;
351
480
  }
352
481
  } else {
353
482
  // throw error anyway, next call should be resolved properly// throw error anyway, next call should be resolved properly
@@ -357,20 +486,27 @@ export class DeviceCommands {
357
486
  return response;
358
487
  }
359
488
 
360
- async _commonCall(type: MessageKey, msg?: DefaultMessageResponse['message']) {
361
- const resp = await this.call(type, msg);
362
- return this._filterCommonTypes(resp, type);
489
+ async _commonCall(
490
+ type: MessageKey,
491
+ msg?: DefaultMessageResponse['message'],
492
+ options?: TransportCallOptions
493
+ ) {
494
+ const resp = await this.call(type, msg, options);
495
+ return this._filterCommonTypes(resp, type, options);
363
496
  }
364
497
 
365
498
  _filterCommonTypes(
366
499
  res: DefaultMessageResponse,
367
- callType: MessageKey
500
+ callType: MessageKey,
501
+ options?: TransportCallOptions
368
502
  ): Promise<DefaultMessageResponse> {
369
503
  try {
370
- if (DataManager.getSettings('env') === 'react-native') {
371
- Log.debug('_filterCommonTypes: ', JSON.stringify(res));
504
+ if (shouldReduceDebugForCall(callType)) {
505
+ // 高频文件写入每个 chunk 都会经过这里,避免 debug log 反向拖慢传输。
506
+ } else if (DataManager.getSettings('env') === 'react-native') {
507
+ Log.debug('_filterCommonTypes: ', JSON.stringify(sanitizeDebugPayload(res)));
372
508
  } else {
373
- Log.debug('_filterCommonTypes: ', res);
509
+ Log.debug('_filterCommonTypes: ', sanitizeDebugPayload(res));
374
510
  }
375
511
  } catch (error) {
376
512
  // ignore
@@ -472,7 +608,7 @@ export class DeviceCommands {
472
608
  } else {
473
609
  this.device.emit(DEVICE.BUTTON, this.device, res.message);
474
610
  }
475
- return this._commonCall('ButtonAck', {});
611
+ return this._commonCall('ButtonAck', {}, options);
476
612
  }
477
613
 
478
614
  if (res.type === 'EntropyRequest') {
@@ -485,11 +621,11 @@ export class DeviceCommands {
485
621
  if (pin === '@@ONEKEY_INPUT_PIN_IN_DEVICE') {
486
622
  // only classic\1s\mini\pure
487
623
  this.device.setCancelableAction(() => this.cancelDeviceOnOneKeyDevice());
488
- return this._commonCall('BixinPinInputOnDevice').finally(() => {
624
+ return this._commonCall('BixinPinInputOnDevice', {}, options).finally(() => {
489
625
  this.device.clearCancelableAction();
490
626
  });
491
627
  }
492
- return this._commonCall('PinMatrixAck', { pin });
628
+ return this._commonCall('PinMatrixAck', { pin }, options);
493
629
  },
494
630
  error => Promise.reject(error)
495
631
  );
@@ -504,12 +640,12 @@ export class DeviceCommands {
504
640
 
505
641
  // Attach PIN on device
506
642
  if (attachPinOnDevice && existsAttachPinUser) {
507
- return this._commonCall('PassphraseAck', { on_device_attach_pin: true });
643
+ return this._commonCall('PassphraseAck', { on_device_attach_pin: true }, options);
508
644
  }
509
645
 
510
646
  return !passphraseOnDevice
511
- ? this._commonCall('PassphraseAck', { passphrase })
512
- : this._commonCall('PassphraseAck', { on_device: true });
647
+ ? this._commonCall('PassphraseAck', { passphrase }, options)
648
+ : this._commonCall('PassphraseAck', { on_device: true }, options);
513
649
  });
514
650
  }
515
651
 
@@ -1,3 +1,5 @@
1
+ import { ERRORS, HardwareErrorCode } from '@onekeyfe/hd-shared';
2
+
1
3
  import { safeThrowError } from '../constants';
2
4
  import { DataManager } from '../data-manager';
3
5
  import TransportManager from '../data-manager/TransportManager';
@@ -6,6 +8,7 @@ import { resolveAfter } from '../utils/promiseUtils';
6
8
  import { LoggerNames, getLogger } from '../utils';
7
9
 
8
10
  import type { DeviceDescriptorDiff } from './DevicePool';
11
+ import type { HardwareConnectProtocol } from '@onekeyfe/hd-shared';
9
12
  import type { OneKeyDeviceInfo as DeviceDescriptor, Transport } from '@onekeyfe/hd-transport';
10
13
 
11
14
  const Log = getLogger(LoggerNames.DeviceConnector);
@@ -75,15 +78,37 @@ export default class DeviceConnector {
75
78
  this.listening = false;
76
79
  }
77
80
 
78
- async acquire(path: string, session?: string | null, forceCleanRunPromise?: boolean) {
79
- Log.debug('acquire', path, session);
81
+ async acquire(
82
+ path: string,
83
+ session?: string | null,
84
+ forceCleanRunPromise?: boolean,
85
+ connectProtocol?: HardwareConnectProtocol
86
+ ) {
87
+ Log.debug('acquire', path, session, connectProtocol);
80
88
  const env = DataManager.getSettings('env');
81
89
  try {
82
90
  let res;
83
91
  if (DataManager.isBleConnect(env)) {
84
- res = await this.transport.acquire({ uuid: path, forceCleanRunPromise });
92
+ res = await this.transport.acquire({
93
+ uuid: path,
94
+ forceCleanRunPromise,
95
+ expectedProtocol: connectProtocol,
96
+ });
85
97
  } else {
86
- res = await this.transport.acquire({ path, previous: session ?? null });
98
+ res = await this.transport.acquire({
99
+ path,
100
+ previous: session ?? null,
101
+ expectedProtocol: connectProtocol,
102
+ });
103
+ }
104
+ if (connectProtocol) {
105
+ const detectedProtocol = this.transport.getProtocolType(path);
106
+ if (detectedProtocol !== connectProtocol) {
107
+ throw ERRORS.TypedError(
108
+ HardwareErrorCode.RuntimeError,
109
+ `Device protocol mismatch: expected ${connectProtocol}, detected ${detectedProtocol}`
110
+ );
111
+ }
87
112
  }
88
113
  return res;
89
114
  } catch (error) {
@@ -150,7 +150,7 @@ export class DevicePool extends EventEmitter {
150
150
  if (!device) {
151
151
  device = Device.fromDescriptor(descriptor);
152
152
  device.deviceConnector = this.connector;
153
- await device.connect();
153
+ await device.connect(initOptions?.connectProtocol);
154
154
  await device.initialize(initOptions);
155
155
  await device.release();
156
156
  }
@@ -129,6 +129,10 @@ export interface FirmwareProgress {
129
129
  device: Device;
130
130
  progress: number;
131
131
  progressType: IFirmwareUpdateProgressType;
132
+ transferredBytes?: number;
133
+ totalBytes?: number;
134
+ rateBytesPerSecond?: number;
135
+ elapsedMs?: number;
132
136
  };
133
137
  }
134
138
 
@@ -144,6 +148,10 @@ export interface DeviceProgress {
144
148
  type: typeof UI_REQUEST.DEVICE_PROGRESS;
145
149
  payload: {
146
150
  progress?: number;
151
+ transferredBytes?: number;
152
+ totalBytes?: number;
153
+ rateBytesPerSecond?: number;
154
+ elapsedMs?: number;
147
155
  };
148
156
  }
149
157