@onekeyfe/hd-core 1.2.0-alpha.16 → 1.2.0-alpha.18

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 (125) hide show
  1. package/__tests__/DeviceEventRegistration.test.ts +3 -0
  2. package/__tests__/deviceFeaturesUtils.test.ts +27 -0
  3. package/__tests__/evmLedgerLegacySafety.test.ts +3 -0
  4. package/__tests__/homescreen.test.ts +24 -0
  5. package/__tests__/kaspaSignTransaction.test.ts +591 -0
  6. package/__tests__/protocol-v2.test.ts +1006 -204
  7. package/__tests__/protocolV2FileWrite.test.ts +28 -3
  8. package/__tests__/protocolV2UiInteraction.test.ts +266 -0
  9. package/dist/api/BaseMethod.d.ts +4 -0
  10. package/dist/api/BaseMethod.d.ts.map +1 -1
  11. package/dist/api/FirmwareUpdateV4.d.ts +3 -3
  12. package/dist/api/FirmwareUpdateV4.d.ts.map +1 -1
  13. package/dist/api/GetDeviceInfo.d.ts.map +1 -1
  14. package/dist/api/GetPassphraseState.d.ts.map +1 -1
  15. package/dist/api/UploadPortfolio.d.ts.map +1 -1
  16. package/dist/api/device/DeviceCancel.d.ts.map +1 -1
  17. package/dist/api/device/DeviceChangePin.d.ts.map +1 -1
  18. package/dist/api/device/DeviceLock.d.ts.map +1 -1
  19. package/dist/api/device/DeviceUnlock.d.ts.map +1 -1
  20. package/dist/api/device/DeviceWipe.d.ts.map +1 -1
  21. package/dist/api/helpers/protocolV2FileWrite.d.ts +1 -0
  22. package/dist/api/helpers/protocolV2FileWrite.d.ts.map +1 -1
  23. package/dist/api/index.d.ts +1 -1
  24. package/dist/api/index.d.ts.map +1 -1
  25. package/dist/api/kaspa/KaspaSignTransaction.d.ts +5 -1
  26. package/dist/api/kaspa/KaspaSignTransaction.d.ts.map +1 -1
  27. package/dist/api/kaspa/helpers/TransferSerialize.d.ts.map +1 -1
  28. package/dist/api/protocol-v2/DeviceInfoGet.d.ts.map +1 -1
  29. package/dist/api/protocol-v2/DeviceSessionOpen.d.ts +28 -0
  30. package/dist/api/protocol-v2/DeviceSessionOpen.d.ts.map +1 -0
  31. package/dist/api/protocol-v2/DeviceSettingsPageShow.d.ts.map +1 -1
  32. package/dist/api/protocol-v2/DeviceSettingsSet.d.ts.map +1 -1
  33. package/dist/api/protocol-v2/DeviceStatusGet.d.ts.map +1 -1
  34. package/dist/api/protocol-v2/DeviceUploadWallpaper.d.ts.map +1 -1
  35. package/dist/core/deviceEventRegistration.d.ts +1 -0
  36. package/dist/core/deviceEventRegistration.d.ts.map +1 -1
  37. package/dist/core/index.d.ts.map +1 -1
  38. package/dist/device/Device.d.ts +3 -3
  39. package/dist/device/Device.d.ts.map +1 -1
  40. package/dist/device/DeviceCommands.d.ts +7 -5
  41. package/dist/device/DeviceCommands.d.ts.map +1 -1
  42. package/dist/device/DevicePool.d.ts +2 -2
  43. package/dist/device/DevicePool.d.ts.map +1 -1
  44. package/dist/deviceProfile/buildDeviceFeatures.d.ts +6 -2
  45. package/dist/deviceProfile/buildDeviceFeatures.d.ts.map +1 -1
  46. package/dist/deviceProfile/buildDeviceProfile.d.ts +3 -2
  47. package/dist/deviceProfile/buildDeviceProfile.d.ts.map +1 -1
  48. package/dist/events/device.d.ts +4 -0
  49. package/dist/events/device.d.ts.map +1 -1
  50. package/dist/events/ui-request.d.ts +18 -2
  51. package/dist/events/ui-request.d.ts.map +1 -1
  52. package/dist/index.d.ts +85 -15
  53. package/dist/index.js +1515 -554
  54. package/dist/protocols/protocol-v2/features.d.ts +6 -18
  55. package/dist/protocols/protocol-v2/features.d.ts.map +1 -1
  56. package/dist/protocols/protocol-v2/index.d.ts +1 -1
  57. package/dist/protocols/protocol-v2/index.d.ts.map +1 -1
  58. package/dist/protocols/protocol-v2/uiInteraction.d.ts +39 -0
  59. package/dist/protocols/protocol-v2/uiInteraction.d.ts.map +1 -0
  60. package/dist/protocols/protocol-v2/unlockRetry.d.ts +5 -3
  61. package/dist/protocols/protocol-v2/unlockRetry.d.ts.map +1 -1
  62. package/dist/protocols/protocol-v2/walletSession.d.ts +2 -1
  63. package/dist/protocols/protocol-v2/walletSession.d.ts.map +1 -1
  64. package/dist/types/api/getDeviceInfo.d.ts +2 -1
  65. package/dist/types/api/getDeviceInfo.d.ts.map +1 -1
  66. package/dist/types/api/index.d.ts +2 -2
  67. package/dist/types/api/index.d.ts.map +1 -1
  68. package/dist/types/api/kaspaSignTransaction.d.ts +27 -2
  69. package/dist/types/api/kaspaSignTransaction.d.ts.map +1 -1
  70. package/dist/types/api/protocolV2.d.ts +4 -2
  71. package/dist/types/api/protocolV2.d.ts.map +1 -1
  72. package/dist/types/device.d.ts +2 -1
  73. package/dist/types/device.d.ts.map +1 -1
  74. package/dist/utils/deviceFeaturesUtils.d.ts.map +1 -1
  75. package/dist/utils/homescreen.d.ts.map +1 -1
  76. package/dist/utils/patch.d.ts +1 -1
  77. package/dist/utils/patch.d.ts.map +1 -1
  78. package/package.json +4 -4
  79. package/src/api/BaseMethod.ts +10 -2
  80. package/src/api/FirmwareUpdateV4.ts +27 -73
  81. package/src/api/GetDeviceInfo.ts +9 -2
  82. package/src/api/GetPassphraseState.ts +5 -2
  83. package/src/api/UploadPortfolio.ts +2 -0
  84. package/src/api/device/DeviceCancel.ts +1 -0
  85. package/src/api/device/DeviceChangePin.ts +23 -0
  86. package/src/api/device/DeviceLock.ts +1 -0
  87. package/src/api/device/DeviceUnlock.ts +9 -0
  88. package/src/api/device/DeviceWipe.ts +18 -0
  89. package/src/api/helpers/protocolV2FileWrite.ts +35 -11
  90. package/src/api/index.ts +1 -1
  91. package/src/api/kaspa/KaspaSignTransaction.ts +341 -22
  92. package/src/api/kaspa/helpers/TransferSerialize.ts +14 -0
  93. package/src/api/protocol-v2/DeviceInfoGet.ts +0 -1
  94. package/src/api/protocol-v2/DeviceSessionOpen.ts +100 -0
  95. package/src/api/protocol-v2/DeviceSettingsPageShow.ts +9 -1
  96. package/src/api/protocol-v2/DeviceSettingsSet.ts +11 -1
  97. package/src/api/protocol-v2/DeviceStatusGet.ts +1 -0
  98. package/src/api/protocol-v2/DeviceUploadWallpaper.ts +2 -1
  99. package/src/core/deviceEventRegistration.ts +2 -0
  100. package/src/core/index.ts +36 -3
  101. package/src/data/messages/messages-protocol-v2.json +122 -23
  102. package/src/data/messages/messages.json +286 -1
  103. package/src/device/Device.ts +33 -41
  104. package/src/device/DeviceCommands.ts +22 -4
  105. package/src/device/DevicePool.ts +14 -6
  106. package/src/deviceProfile/buildDeviceFeatures.ts +21 -9
  107. package/src/deviceProfile/buildDeviceProfile.ts +27 -11
  108. package/src/events/device.ts +4 -0
  109. package/src/events/ui-request.ts +24 -2
  110. package/src/inject.ts +2 -2
  111. package/src/protocols/protocol-v2/features.ts +27 -20
  112. package/src/protocols/protocol-v2/index.ts +0 -1
  113. package/src/protocols/protocol-v2/uiInteraction.ts +209 -0
  114. package/src/protocols/protocol-v2/unlockRetry.ts +43 -3
  115. package/src/protocols/protocol-v2/walletSession.ts +122 -31
  116. package/src/types/api/getDeviceInfo.ts +6 -1
  117. package/src/types/api/index.ts +2 -2
  118. package/src/types/api/kaspaSignTransaction.ts +40 -2
  119. package/src/types/api/protocolV2.ts +5 -3
  120. package/src/types/device.ts +6 -1
  121. package/src/utils/deviceFeaturesUtils.ts +13 -0
  122. package/src/utils/homescreen.ts +10 -0
  123. package/dist/api/protocol-v2/DeviceSessionGet.d.ts +0 -6
  124. package/dist/api/protocol-v2/DeviceSessionGet.d.ts.map +0 -1
  125. package/src/api/protocol-v2/DeviceSessionGet.ts +0 -15
@@ -19,10 +19,13 @@ export default class GetPassphraseState extends BaseMethod {
19
19
 
20
20
  const passphraseProtection = this.device.getCurrentPassphraseProtection();
21
21
  const deviceType = this.device.getCurrentDeviceType();
22
- const isProSeries = deviceType === EDeviceType.Pro || deviceType === EDeviceType.Pro2;
22
+
23
+ if (deviceType === EDeviceType.Pro2) {
24
+ return Promise.resolve(passphraseProtection === true ? passphraseState : undefined);
25
+ }
23
26
 
24
27
  return Promise.resolve(
25
- isProSeries || passphraseProtection === true ? passphraseState : undefined
28
+ deviceType === EDeviceType.Pro || passphraseProtection === true ? passphraseState : undefined
26
29
  );
27
30
  }
28
31
  }
@@ -25,6 +25,8 @@ export default class UploadPortfolio extends FileWrite {
25
25
  };
26
26
  super.init();
27
27
  this.unlockPolicy = 'retry-on-locked';
28
+ // Portfolio 是后台数据写入与应用流程,设备不需要用户确认;包括自动解锁阶段在内均不合成 UI Event。
29
+ this.protocolV2UiMode = 'none';
28
30
  }
29
31
 
30
32
  async run() {
@@ -5,6 +5,7 @@ import type { Cancel } from '@onekeyfe/hd-transport';
5
5
  export default class DeviceCancel extends BaseMethod<Cancel> {
6
6
  init() {
7
7
  this.useDevicePassphraseState = false;
8
+ this.unlockPolicy = 'none';
8
9
  }
9
10
 
10
11
  async run() {
@@ -1,5 +1,8 @@
1
+ import { DeviceSettingsPage } from '@onekeyfe/hd-transport';
2
+
1
3
  import { BaseMethod } from '../BaseMethod';
2
4
  import { validateParams } from '../helpers/paramsValidator';
5
+ import { invalidParameter } from '../helpers/filesystemValidation';
3
6
 
4
7
  import type { ChangePin } from '@onekeyfe/hd-transport';
5
8
 
@@ -13,9 +16,29 @@ export default class DeviceChangePin extends BaseMethod<ChangePin> {
13
16
  this.params = {
14
17
  remove: this.payload.remove,
15
18
  };
19
+ this.protocolV2UiInteraction = {
20
+ request: 'button',
21
+ source: 'method-lifecycle',
22
+ reason: 'change-pin',
23
+ completion: 'operation-completed',
24
+ deviceOnly: true,
25
+ page: DeviceSettingsPage.DevicePinChange,
26
+ };
16
27
  }
17
28
 
18
29
  async run() {
30
+ if (this.device.isProtocolV2()) {
31
+ if (this.params.remove) {
32
+ throw invalidParameter(
33
+ 'Parameter [remove=true] is not supported by the Pro2 device PIN page.'
34
+ );
35
+ }
36
+ const res = await this.device.commands.typedCall('DeviceSettingsPageShow', 'Success', {
37
+ page: DeviceSettingsPage.DevicePinChange,
38
+ });
39
+ return Promise.resolve(res.message);
40
+ }
41
+
19
42
  const res = await this.device.commands.typedCall('ChangePin', 'Success', {
20
43
  ...this.params,
21
44
  });
@@ -5,6 +5,7 @@ import type { LockDevice } from '@onekeyfe/hd-transport';
5
5
  export default class DeviceLock extends BaseMethod<LockDevice> {
6
6
  init() {
7
7
  this.useDevicePassphraseState = false;
8
+ this.unlockPolicy = 'none';
8
9
  }
9
10
 
10
11
  async run() {
@@ -5,6 +5,15 @@ import type { LockDevice } from '@onekeyfe/hd-transport';
5
5
  export default class DeviceUnlock extends BaseMethod<LockDevice> {
6
6
  init() {
7
7
  this.useDevicePassphraseState = false;
8
+ this.unlockPolicy = 'none';
9
+ this.protocolV2UiInteraction = {
10
+ request: 'pin',
11
+ source: 'method-lifecycle',
12
+ reason: 'device-unlock',
13
+ completion: 'operation-completed',
14
+ deviceOnly: true,
15
+ operation: 'unlock-device',
16
+ };
8
17
  }
9
18
 
10
19
  async run() {
@@ -1,3 +1,5 @@
1
+ import { DeviceSettingsPage } from '@onekeyfe/hd-transport';
2
+
1
3
  import { BaseMethod } from '../BaseMethod';
2
4
 
3
5
  import type { WipeDevice } from '@onekeyfe/hd-transport';
@@ -5,9 +7,25 @@ import type { WipeDevice } from '@onekeyfe/hd-transport';
5
7
  export default class DeviceWipe extends BaseMethod<WipeDevice> {
6
8
  init() {
7
9
  this.useDevicePassphraseState = false;
10
+ this.protocolV2UiInteraction = {
11
+ request: 'button',
12
+ source: 'method-lifecycle',
13
+ reason: 'device-management',
14
+ completion: 'operation-completed',
15
+ deviceOnly: true,
16
+ page: DeviceSettingsPage.DeviceReset,
17
+ operation: 'wipe-device',
18
+ };
8
19
  }
9
20
 
10
21
  async run() {
22
+ if (this.device.isProtocolV2()) {
23
+ const res = await this.device.commands.typedCall('DeviceSettingsPageShow', 'Success', {
24
+ page: DeviceSettingsPage.DeviceReset,
25
+ });
26
+ return Promise.resolve(res.message);
27
+ }
28
+
11
29
  const res = await this.device.commands.typedCall('WipeDevice', 'Success');
12
30
 
13
31
  return Promise.resolve(res.message);
@@ -30,12 +30,23 @@ export type ProtocolV2FileWriteOptions = {
30
30
  append?: boolean;
31
31
  uiPercentage?: number;
32
32
  timeoutMs?: number;
33
+ maxChunkRetries?: number;
33
34
  throwIfAborted?: () => void;
34
35
  onProgress?: (progress: ProtocolV2FileWriteProgress) => void;
35
36
  };
36
37
 
37
38
  const MIN_FILE_CHUNK_SIZE = 64;
38
39
 
40
+ function isRetryableFileWriteTimeout(error: unknown) {
41
+ if (!error || typeof error !== 'object') return false;
42
+ const candidate = error as { errorCode?: number; code?: number; message?: string };
43
+ const code = candidate.errorCode ?? candidate.code;
44
+ return (
45
+ code === HardwareErrorCode.BleTimeoutError ||
46
+ /Lowlevel response timeout/i.test(candidate.message ?? '')
47
+ );
48
+ }
49
+
39
50
  function getProtocolV2FileChunkLimit() {
40
51
  const env = DataManager.getSettings('env');
41
52
  return env && DataManager.isBleConnect(env)
@@ -116,17 +127,30 @@ export async function writeProtocolV2File(options: ProtocolV2FileWriteOptions) {
116
127
  const progress =
117
128
  options.uiPercentage ??
118
129
  getDeviceTransferProgress(offset, offset + chunk.byteLength, totalSize);
119
- const response = await options.commands.typedCall(
120
- 'FilesystemFileWrite',
121
- 'FilesystemFile',
122
- {
123
- file: { path: options.path, offset, total_size: totalSize, data: chunk },
124
- overwrite: chunks === 0 ? options.overwrite ?? false : false,
125
- append: options.append ?? false,
126
- ui_percentage: progress,
127
- },
128
- { timeoutMs: options.timeoutMs }
129
- );
130
+ const request = {
131
+ file: { path: options.path, offset, total_size: totalSize, data: chunk },
132
+ overwrite: chunks === 0 ? options.overwrite ?? false : false,
133
+ append: options.append ?? false,
134
+ ui_percentage: progress,
135
+ };
136
+ const maxChunkRetries = Math.max(Math.floor(options.maxChunkRetries ?? 0), 0);
137
+ let retryCount = 0;
138
+ let response;
139
+ while (true) {
140
+ try {
141
+ response = await options.commands.typedCall(
142
+ 'FilesystemFileWrite',
143
+ 'FilesystemFile',
144
+ request,
145
+ { timeoutMs: options.timeoutMs }
146
+ );
147
+ break;
148
+ } catch (error) {
149
+ if (retryCount >= maxChunkRetries || !isRetryableFileWriteTimeout(error)) throw error;
150
+ retryCount += 1;
151
+ options.throwIfAborted?.();
152
+ }
153
+ }
130
154
  options.throwIfAborted?.();
131
155
  lastMessage = response.message;
132
156
  const rawProcessedByte = response.message?.processed_byte;
package/src/api/index.ts CHANGED
@@ -50,7 +50,7 @@ export { default as deviceReboot } from './protocol-v2/DeviceReboot';
50
50
  export { default as deviceInfoGet } from './protocol-v2/DeviceInfoGet';
51
51
  export { default as deviceStatusGet } from './protocol-v2/DeviceStatusGet';
52
52
  export { default as deviceGetOnboardingStatus } from './protocol-v2/DeviceGetOnboardingStatus';
53
- export { default as deviceSessionGet } from './protocol-v2/DeviceSessionGet';
53
+ export { default as deviceSessionOpen } from './protocol-v2/DeviceSessionOpen';
54
54
  export { default as deviceFirmwareUpdate } from './protocol-v2/DeviceFirmwareUpdate';
55
55
  export { default as deviceGetFirmwareUpdateStatus } from './protocol-v2/DeviceGetFirmwareUpdateStatus';
56
56
  export { default as deviceFactoryInfoSet } from './protocol-v2/DeviceFactoryInfoSet';
@@ -1,4 +1,5 @@
1
1
  import { bytesToHex } from '@noble/hashes/utils';
2
+ import { ERRORS, HardwareError, HardwareErrorCode } from '@onekeyfe/hd-shared';
2
3
 
3
4
  import { UI_REQUEST } from '../../constants/ui-request';
4
5
  import { validatePath } from '../helpers/pathUtils';
@@ -14,11 +15,27 @@ import type {
14
15
  KaspaSignTransactionParams,
15
16
  KaspaSignature,
16
17
  } from '../../types';
17
- import type { TypedCall } from '@onekeyfe/hd-transport';
18
+ import type {
19
+ KaspaInputScriptType,
20
+ KaspaTxRequest,
21
+ KaspaTxRequestSignature,
22
+ TypedCall,
23
+ } from '@onekeyfe/hd-transport';
24
+
25
+ // Streaming only handles plain P2PK scripts; anything else (e.g. KRC20 P2SH)
26
+ // must blind-sign. Absent script means a streaming-only caller.
27
+ const P2PK_SCRIPT = /^(20[0-9a-f]{64}ac|21[0-9a-f]{66}ab)$/i;
28
+
29
+ const isStreamableScript = (script?: string) => !script || P2PK_SCRIPT.test(script);
18
30
 
19
31
  export default class KaspaSignTransaction extends BaseMethod<KaspaSignTransactionParams> {
20
32
  hasBundle = false;
21
33
 
34
+ // Protocols this tx can be signed with; the device picks via its first response.
35
+ supportsLegacy = false;
36
+
37
+ supportsStreaming = false;
38
+
22
39
  init() {
23
40
  this.checkDeviceId = true;
24
41
  this.allowDeviceMode = [...this.allowDeviceMode, UI_REQUEST.NOT_INITIALIZE];
@@ -29,17 +46,17 @@ export default class KaspaSignTransaction extends BaseMethod<KaspaSignTransactio
29
46
  // check payload
30
47
  validateParams(payload, [
31
48
  { name: 'version', type: 'number' },
32
- { name: 'sigHashType', type: 'number', required: true },
49
+ { name: 'sigHashType', type: 'number' },
33
50
  { name: 'inputs', type: 'array', required: true },
34
51
  { name: 'outputs', type: 'array', required: true },
35
52
  { name: 'lockTime', required: true },
36
53
  { name: 'sigOpCount', type: 'number' },
37
54
  { name: 'subNetworkID', type: 'string' },
55
+ { name: 'payload', type: 'hexString' },
56
+ { name: 'refTxs', type: 'array', allowEmpty: true },
38
57
  { name: 'useTweak', type: 'boolean' },
39
58
  ]);
40
59
 
41
- // if(!payload.inputs.length) throw
42
-
43
60
  const inputs: KaspaSignInputParams[] = payload.inputs.map(input => {
44
61
  validateParams(input, [
45
62
  { name: 'path', type: 'string', required: true },
@@ -47,6 +64,7 @@ export default class KaspaSignTransaction extends BaseMethod<KaspaSignTransactio
47
64
  { name: 'outputIndex', type: 'number', required: true },
48
65
  { name: 'sequenceNumber', required: true },
49
66
  ]);
67
+ validateParams(input.output, [{ name: 'satoshis', required: true }]);
50
68
 
51
69
  const addressN = validatePath(input.path, 3);
52
70
 
@@ -57,15 +75,28 @@ export default class KaspaSignTransaction extends BaseMethod<KaspaSignTransactio
57
75
  };
58
76
  });
59
77
 
78
+ payload.refTxs?.forEach(refTx => {
79
+ validateParams(refTx, [
80
+ { name: 'txId', type: 'string', required: true },
81
+ { name: 'version', type: 'number', required: true },
82
+ // Coinbase transactions legitimately have zero inputs.
83
+ { name: 'inputs', type: 'array', required: true, allowEmpty: true },
84
+ { name: 'outputs', type: 'array', required: true, allowEmpty: true },
85
+ { name: 'payload', type: 'hexString' },
86
+ ]);
87
+ });
88
+
60
89
  const outputs: KaspaSignOutputParams[] = payload.outputs.map(output => {
61
90
  validateParams(output, [
62
91
  { name: 'satoshis', required: true },
63
- { name: 'script', type: 'string', required: true },
92
+ { name: 'address', type: 'string' },
93
+ { name: 'script', type: 'string' },
64
94
  { name: 'scriptVersion', type: 'number' },
65
95
  ]);
66
96
 
67
97
  return {
68
98
  ...output,
99
+ addressN: output.addressN ? validatePath(output.addressN, 3) : undefined,
69
100
  scriptVersion: output.scriptVersion ?? 0,
70
101
  };
71
102
  });
@@ -80,8 +111,37 @@ export default class KaspaSignTransaction extends BaseMethod<KaspaSignTransactio
80
111
  sigHashType: payload.sigHashType ?? SignatureType.SIGHASH_ALL | SignatureType.SIGHASH_FORKID,
81
112
  sigOpCount: payload.sigOpCount ?? 1,
82
113
  subNetworkID: payload.subNetworkID ?? bytesToHex(zeroSubnetworkID()),
114
+ gas: payload.gas ?? 0,
83
115
  useTweak: payload.useTweak,
84
116
  };
117
+
118
+ // Legacy prehashes on the host with payload/gas/subnetworkID hardcoded to
119
+ // zero (TransferSerialize), so those rule it out.
120
+ this.supportsLegacy =
121
+ this.params.outputs.every(output => !!output.script) &&
122
+ this.params.inputs.every(input => !!input.output.script) &&
123
+ !this.params.payload &&
124
+ Number(this.params.gas ?? 0) === 0 &&
125
+ /^0*$/.test(this.params.subNetworkID ?? '');
126
+
127
+ // The streaming protocol has no sighash-type field (device signs SIGHASH_ALL).
128
+ const isDefaultSigHashType =
129
+ this.params.sigHashType === SignatureType.SIGHASH_ALL ||
130
+ // eslint-disable-next-line no-bitwise
131
+ this.params.sigHashType === (SignatureType.SIGHASH_ALL | SignatureType.SIGHASH_FORKID);
132
+
133
+ this.supportsStreaming =
134
+ isDefaultSigHashType &&
135
+ this.params.outputs.every(output => !!output.address || !!output.addressN) &&
136
+ this.params.inputs.every(input => isStreamableScript(input.output.script)) &&
137
+ this.params.outputs.every(output => isStreamableScript(output.script));
138
+
139
+ if (!this.supportsLegacy && !this.supportsStreaming) {
140
+ throw ERRORS.TypedError(
141
+ HardwareErrorCode.CallMethodInvalidParameter,
142
+ 'KaspaSignTransaction: outputs require either address/addressN (streaming protocol) or script (legacy protocol)'
143
+ );
144
+ }
85
145
  }
86
146
 
87
147
  getVersionRange() {
@@ -106,6 +166,10 @@ export default class KaspaSignTransaction extends BaseMethod<KaspaSignTransactio
106
166
  };
107
167
  }
108
168
 
169
+ /**
170
+ * Legacy blind-sign flow: run() sent input 0's prehash in raw_message; feed
171
+ * each next prehash via KaspaTxInputAck until KaspaSignedTx.
172
+ */
109
173
  async processTxRequest(
110
174
  typedCall: TypedCall,
111
175
  res: TypedResponseMessage<'KaspaTxInputRequest'> | TypedResponseMessage<'KaspaSignedTx'>,
@@ -136,7 +200,6 @@ export default class KaspaSignTransaction extends BaseMethod<KaspaSignTransactio
136
200
  'KaspaTxInputAck',
137
201
  ['KaspaTxInputRequest', 'KaspaSignedTx'],
138
202
  {
139
- // params.inputs 的 path 可能是字符串或已解析数组,统一归一为 address_n 数组
140
203
  address_n: validatePath(input.path, 3),
141
204
  raw_message: bytesToHex(rawMessage),
142
205
  }
@@ -148,6 +211,190 @@ export default class KaspaSignTransaction extends BaseMethod<KaspaSignTransactio
148
211
  return signature;
149
212
  }
150
213
 
214
+ /**
215
+ * Answer a previous-transaction request (selected by prev_tx_id) from
216
+ * refTxs; the device uses them to verify input amounts.
217
+ */
218
+ async ackPrevRequest(typedCall: TypedCall, request: KaspaTxRequest, requestIndex: number) {
219
+ const prevTxId = (request.prev_tx_id ?? '').toLowerCase();
220
+ const refTx = (this.params.refTxs ?? []).find(tx => tx.txId.toLowerCase() === prevTxId);
221
+ if (!refTx) {
222
+ throw ERRORS.TypedError(
223
+ HardwareErrorCode.CallMethodInvalidParameter,
224
+ `KaspaSignTransaction: device requested previous transaction ${
225
+ prevTxId || '(unknown)'
226
+ }; provide it via refTxs`
227
+ );
228
+ }
229
+
230
+ const requestType = request.request_type;
231
+
232
+ if (requestType === 'KASPA_TX_PREV_META') {
233
+ return typedCall('KaspaTxAckPrevMeta', 'KaspaTxRequest', {
234
+ version: refTx.version,
235
+ input_count: refTx.inputs.length,
236
+ output_count: refTx.outputs.length,
237
+ lock_time: (refTx.lockTime ?? 0) as number,
238
+ subnetwork_id: refTx.subNetworkID ?? bytesToHex(zeroSubnetworkID()),
239
+ gas: (refTx.gas ?? 0) as number,
240
+ payload_length: (refTx.payload ?? '').length / 2,
241
+ });
242
+ }
243
+
244
+ if (requestType === 'KASPA_TX_INPUT') {
245
+ const input = refTx.inputs[requestIndex];
246
+ if (!input) {
247
+ throw ERRORS.TypedError(
248
+ HardwareErrorCode.RuntimeError,
249
+ `KaspaSignTransaction: device requested input ${requestIndex} of previous tx out of range`
250
+ );
251
+ }
252
+ return typedCall('KaspaTxAckPrevInput', 'KaspaTxRequest', {
253
+ previous_outpoint: {
254
+ tx_id: input.prevTxId,
255
+ index: input.outputIndex,
256
+ },
257
+ sequence: input.sequenceNumber as number,
258
+ });
259
+ }
260
+
261
+ if (requestType === 'KASPA_TX_OUTPUT') {
262
+ const output = refTx.outputs[requestIndex];
263
+ if (!output) {
264
+ throw ERRORS.TypedError(
265
+ HardwareErrorCode.RuntimeError,
266
+ `KaspaSignTransaction: device requested output ${requestIndex} of previous tx out of range`
267
+ );
268
+ }
269
+ return typedCall('KaspaTxAckPrevOutput', 'KaspaTxRequest', {
270
+ amount: output.satoshis,
271
+ script_version: output.scriptVersion ?? 0,
272
+ script_public_key: output.script,
273
+ });
274
+ }
275
+
276
+ if (requestType === 'KASPA_TX_PAYLOAD') {
277
+ const payloadHex = refTx.payload ?? '';
278
+ const payloadLength = payloadHex.length / 2;
279
+ const length = request.request_payload_length ?? payloadLength - requestIndex;
280
+ return typedCall('KaspaTxAckPayloadChunk', 'KaspaTxRequest', {
281
+ payload_chunk: payloadHex.substring(requestIndex * 2, (requestIndex + length) * 2),
282
+ });
283
+ }
284
+
285
+ throw ERRORS.TypedError(
286
+ HardwareErrorCode.RuntimeError,
287
+ `KaspaSignTransaction: unknown previous-tx request type ${requestType ?? 'undefined'}`
288
+ );
289
+ }
290
+
291
+ /**
292
+ * Streaming flow (device computes the sighash): the device drives via
293
+ * KaspaTxRequest, asking for inputs/outputs/payload chunks and carrying
294
+ * finished signatures back, until FINISHED. Mirrors BTC signtx.
295
+ */
296
+ async signTxStream(
297
+ typedCall: TypedCall,
298
+ firstResponse: TypedResponseMessage<'KaspaTxRequest'>
299
+ ): Promise<KaspaSignature[]> {
300
+ const { params } = this;
301
+ const signatures: KaspaSignature[] = [];
302
+
303
+ const inputScriptType: KaspaInputScriptType =
304
+ params.scheme === 'ecdsa' ? 'KASPA_SPEND_P2PK_ECDSA' : 'KASPA_SPEND_P2PK_SCHNORR';
305
+
306
+ const saveSignature = (signature?: KaspaTxRequestSignature) => {
307
+ if (signature && typeof signature.signature_index === 'number' && signature.signature) {
308
+ signatures[signature.signature_index] = {
309
+ index: signature.signature_index,
310
+ signature: signature.signature,
311
+ };
312
+ }
313
+ };
314
+
315
+ const payloadHex = params.payload ?? '';
316
+ const payloadLength = payloadHex.length / 2;
317
+
318
+ let response = firstResponse;
319
+
320
+ // eslint-disable-next-line no-constant-condition
321
+ while (true) {
322
+ const request = response.message;
323
+ // Save first so the last input's signature (carried on the FINISHED request) is captured.
324
+ saveSignature(request.signature);
325
+
326
+ const requestType = request.request_type;
327
+ if (requestType === 'KASPA_TX_FINISHED') {
328
+ break;
329
+ }
330
+
331
+ const requestIndex = request.request_index ?? 0;
332
+
333
+ // prev_tx_id selects a previous-transaction request; answer from refTxs.
334
+ if (request.prev_tx_id || requestType === 'KASPA_TX_PREV_META') {
335
+ response = await this.ackPrevRequest(typedCall, request, requestIndex);
336
+ } else if (requestType === 'KASPA_TX_INPUT') {
337
+ const input = params.inputs[requestIndex];
338
+ if (!input) {
339
+ throw ERRORS.TypedError(
340
+ HardwareErrorCode.RuntimeError,
341
+ `KaspaSignTransaction: device requested input ${requestIndex} out of range`
342
+ );
343
+ }
344
+ response = await typedCall('KaspaTxAckInput', 'KaspaTxRequest', {
345
+ address_n: input.path as number[],
346
+ previous_outpoint: {
347
+ tx_id: input.prevTxId,
348
+ index: input.outputIndex,
349
+ },
350
+ amount: input.output.satoshis,
351
+ sequence: input.sequenceNumber as number,
352
+ sig_op_count: input.sigOpCount ?? 1,
353
+ script_type: inputScriptType,
354
+ use_tweak: params.useTweak,
355
+ });
356
+ } else if (requestType === 'KASPA_TX_OUTPUT') {
357
+ const output = params.outputs[requestIndex];
358
+ if (!output) {
359
+ throw ERRORS.TypedError(
360
+ HardwareErrorCode.RuntimeError,
361
+ `KaspaSignTransaction: device requested output ${requestIndex} out of range`
362
+ );
363
+ }
364
+ const isChange = !!output.addressN;
365
+ response = await typedCall('KaspaTxAckOutput', 'KaspaTxRequest', {
366
+ script_type: isChange ? 'KASPA_PAYTOCHANGE' : 'KASPA_PAYTOADDRESS',
367
+ amount: output.satoshis,
368
+ address_n: (output.addressN as number[]) ?? [],
369
+ address: output.address,
370
+ scheme: params.scheme,
371
+ use_tweak: params.useTweak,
372
+ });
373
+ } else if (requestType === 'KASPA_TX_PAYLOAD') {
374
+ const offset = requestIndex;
375
+ const length = request.request_payload_length ?? payloadLength - offset;
376
+ const chunk = payloadHex.substring(offset * 2, (offset + length) * 2);
377
+ response = await typedCall('KaspaTxAckPayloadChunk', 'KaspaTxRequest', {
378
+ payload_chunk: chunk,
379
+ });
380
+ } else {
381
+ throw ERRORS.TypedError(
382
+ HardwareErrorCode.RuntimeError,
383
+ `KaspaSignTransaction: unknown request type ${requestType ?? 'undefined'}`
384
+ );
385
+ }
386
+ }
387
+
388
+ const collected = signatures.filter(Boolean);
389
+ if (collected.length !== params.inputs.length) {
390
+ throw ERRORS.TypedError(
391
+ HardwareErrorCode.RuntimeError,
392
+ `KaspaSignTransaction: expected ${params.inputs.length} signatures, received ${collected.length}`
393
+ );
394
+ }
395
+ return collected;
396
+ }
397
+
151
398
  async run() {
152
399
  this.checkFeatureVersionLimit(
153
400
  // exists use_tweak is false check firmware version
@@ -158,25 +405,97 @@ export default class KaspaSignTransaction extends BaseMethod<KaspaSignTransactio
158
405
  }
159
406
  );
160
407
 
161
- const { raw: rawMessage } = serialize(this.params, 0);
162
- const input = this.params.inputs[0];
163
-
164
408
  const { device, params } = this;
409
+ const payloadHex = params.payload ?? '';
165
410
 
166
- const response = await device.commands.typedCall(
167
- 'KaspaSignTx',
168
- ['KaspaTxInputRequest', 'KaspaSignedTx'],
169
- {
170
- // init() 已把 path 归一为数组,这里再过一遍 validatePath 收窄类型
171
- address_n: validatePath(input.path, 3),
172
- raw_message: bytesToHex(rawMessage),
173
- scheme: params.scheme,
174
- prefix: params.prefix,
175
- input_count: params.inputs.length,
176
- use_tweak: params.useTweak,
411
+ // output_count is the protocol discriminator: attach streaming fields only
412
+ // when the tx can stream. Streaming verification needs refTxs, so without
413
+ // them prefer blind signing when available; a streaming-only tx still
414
+ // streams and fails clearly if the device requests previous txs.
415
+ const hasRefTxs = (params.refTxs?.length ?? 0) > 0;
416
+ const streamingReady = this.supportsStreaming && (hasRefTxs || !this.supportsLegacy);
417
+
418
+ const streamingFields = streamingReady
419
+ ? {
420
+ output_count: params.outputs.length,
421
+ version: params.version,
422
+ lock_time: params.lockTime as number,
423
+ subnetwork_id: params.subNetworkID,
424
+ gas: params.gas as number,
425
+ payload_length: payloadHex.length / 2,
426
+ }
427
+ : {};
428
+
429
+ // raw_message (input 0's prehash) is only computable/correct when legacy-signable.
430
+ const legacyFields = this.supportsLegacy
431
+ ? { raw_message: bytesToHex(serialize(params, 0).raw) }
432
+ : {};
433
+
434
+ // Legacy firmware reads raw_message and skips unknown streaming fields;
435
+ // new firmware streams iff output_count is present.
436
+ let response;
437
+ try {
438
+ response = await device.commands.typedCall(
439
+ 'KaspaSignTx',
440
+ ['KaspaTxRequest', 'KaspaTxInputRequest', 'KaspaSignedTx'],
441
+ {
442
+ address_n: params.inputs[0].path as number[],
443
+ scheme: params.scheme,
444
+ prefix: params.prefix,
445
+ input_count: params.inputs.length,
446
+ use_tweak: params.useTweak,
447
+ ...streamingFields,
448
+ ...legacyFields,
449
+ }
450
+ );
451
+ } catch (error) {
452
+ // Old firmware cannot decode a packet without raw_message
453
+ // (Failure_DataError); map it to an actionable upgrade error.
454
+ if (
455
+ !this.supportsLegacy &&
456
+ error instanceof HardwareError &&
457
+ error.errorCode === HardwareErrorCode.RuntimeError &&
458
+ String(error.message).includes('Failure_DataError')
459
+ ) {
460
+ throw ERRORS.TypedError(
461
+ HardwareErrorCode.CallMethodNeedUpgradeFirmware,
462
+ 'KaspaSignTransaction: this transaction requires firmware with Kaspa streaming support'
463
+ );
177
464
  }
178
- );
465
+ throw error;
466
+ }
467
+
468
+ const typedCall = device.commands.typedCall.bind(device.commands);
469
+
470
+ if (response.type === 'KaspaTxRequest') {
471
+ if (!this.supportsStreaming) {
472
+ throw ERRORS.TypedError(
473
+ HardwareErrorCode.CallMethodInvalidParameter,
474
+ 'KaspaSignTransaction: device firmware uses the streaming protocol; every output requires address or addressN'
475
+ );
476
+ }
477
+ try {
478
+ return await this.signTxStream(typedCall, response);
479
+ } catch (error) {
480
+ // Device rejected our refTxs; the caller decides whether to sign without them.
481
+ if (
482
+ error instanceof HardwareError &&
483
+ String(error.message).toLowerCase().includes('previous transaction id mismatch')
484
+ ) {
485
+ throw ERRORS.TypedError(HardwareErrorCode.KaspaPrevTxIdMismatch, String(error.message));
486
+ }
487
+ throw error;
488
+ }
489
+ }
490
+
491
+ // Legacy answer to a streaming-only packet: no prehash material exists.
492
+ if (!this.supportsLegacy) {
493
+ throw ERRORS.TypedError(
494
+ HardwareErrorCode.RuntimeError,
495
+ 'KaspaSignTransaction: device chose the legacy protocol but the transaction is not legacy-signable'
496
+ );
497
+ }
179
498
 
180
- return this.processTxRequest(device.commands.typedCall.bind(device.commands), response, 0, []);
499
+ return this.processTxRequest(typedCall, response, 0, []);
181
500
  }
182
501
  }