@onekeyfe/hd-core 1.1.31 → 1.1.32-alpha.4

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.
@@ -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'>,
@@ -149,6 +213,190 @@ export default class KaspaSignTransaction extends BaseMethod<KaspaSignTransactio
149
213
  return signature;
150
214
  }
151
215
 
216
+ /**
217
+ * Answer a previous-transaction request (selected by prev_tx_id) from
218
+ * refTxs; the device uses them to verify input amounts.
219
+ */
220
+ async ackPrevRequest(typedCall: TypedCall, request: KaspaTxRequest, requestIndex: number) {
221
+ const prevTxId = (request.prev_tx_id ?? '').toLowerCase();
222
+ const refTx = (this.params.refTxs ?? []).find(tx => tx.txId.toLowerCase() === prevTxId);
223
+ if (!refTx) {
224
+ throw ERRORS.TypedError(
225
+ HardwareErrorCode.CallMethodInvalidParameter,
226
+ `KaspaSignTransaction: device requested previous transaction ${
227
+ prevTxId || '(unknown)'
228
+ }; provide it via refTxs`
229
+ );
230
+ }
231
+
232
+ const requestType = request.request_type;
233
+
234
+ if (requestType === 'KASPA_TX_PREV_META') {
235
+ return typedCall('KaspaTxAckPrevMeta', 'KaspaTxRequest', {
236
+ version: refTx.version,
237
+ input_count: refTx.inputs.length,
238
+ output_count: refTx.outputs.length,
239
+ lock_time: (refTx.lockTime ?? 0) as number,
240
+ subnetwork_id: refTx.subNetworkID ?? bytesToHex(zeroSubnetworkID()),
241
+ gas: (refTx.gas ?? 0) as number,
242
+ payload_length: (refTx.payload ?? '').length / 2,
243
+ });
244
+ }
245
+
246
+ if (requestType === 'KASPA_TX_INPUT') {
247
+ const input = refTx.inputs[requestIndex];
248
+ if (!input) {
249
+ throw ERRORS.TypedError(
250
+ HardwareErrorCode.RuntimeError,
251
+ `KaspaSignTransaction: device requested input ${requestIndex} of previous tx out of range`
252
+ );
253
+ }
254
+ return typedCall('KaspaTxAckPrevInput', 'KaspaTxRequest', {
255
+ previous_outpoint: {
256
+ tx_id: input.prevTxId,
257
+ index: input.outputIndex,
258
+ },
259
+ sequence: input.sequenceNumber as number,
260
+ });
261
+ }
262
+
263
+ if (requestType === 'KASPA_TX_OUTPUT') {
264
+ const output = refTx.outputs[requestIndex];
265
+ if (!output) {
266
+ throw ERRORS.TypedError(
267
+ HardwareErrorCode.RuntimeError,
268
+ `KaspaSignTransaction: device requested output ${requestIndex} of previous tx out of range`
269
+ );
270
+ }
271
+ return typedCall('KaspaTxAckPrevOutput', 'KaspaTxRequest', {
272
+ amount: output.satoshis,
273
+ script_version: output.scriptVersion ?? 0,
274
+ script_public_key: output.script,
275
+ });
276
+ }
277
+
278
+ if (requestType === 'KASPA_TX_PAYLOAD') {
279
+ const payloadHex = refTx.payload ?? '';
280
+ const payloadLength = payloadHex.length / 2;
281
+ const length = request.request_payload_length ?? payloadLength - requestIndex;
282
+ return typedCall('KaspaTxAckPayloadChunk', 'KaspaTxRequest', {
283
+ payload_chunk: payloadHex.substring(requestIndex * 2, (requestIndex + length) * 2),
284
+ });
285
+ }
286
+
287
+ throw ERRORS.TypedError(
288
+ HardwareErrorCode.RuntimeError,
289
+ `KaspaSignTransaction: unknown previous-tx request type ${requestType ?? 'undefined'}`
290
+ );
291
+ }
292
+
293
+ /**
294
+ * Streaming flow (device computes the sighash): the device drives via
295
+ * KaspaTxRequest, asking for inputs/outputs/payload chunks and carrying
296
+ * finished signatures back, until FINISHED. Mirrors BTC signtx.
297
+ */
298
+ async signTxStream(
299
+ typedCall: TypedCall,
300
+ firstResponse: TypedResponseMessage<'KaspaTxRequest'>
301
+ ): Promise<KaspaSignature[]> {
302
+ const { params } = this;
303
+ const signatures: KaspaSignature[] = [];
304
+
305
+ const inputScriptType: KaspaInputScriptType =
306
+ params.scheme === 'ecdsa' ? 'KASPA_SPEND_P2PK_ECDSA' : 'KASPA_SPEND_P2PK_SCHNORR';
307
+
308
+ const saveSignature = (signature?: KaspaTxRequestSignature) => {
309
+ if (signature && typeof signature.signature_index === 'number' && signature.signature) {
310
+ signatures[signature.signature_index] = {
311
+ index: signature.signature_index,
312
+ signature: signature.signature,
313
+ };
314
+ }
315
+ };
316
+
317
+ const payloadHex = params.payload ?? '';
318
+ const payloadLength = payloadHex.length / 2;
319
+
320
+ let response = firstResponse;
321
+
322
+ // eslint-disable-next-line no-constant-condition
323
+ while (true) {
324
+ const request = response.message;
325
+ // Save first so the last input's signature (carried on the FINISHED request) is captured.
326
+ saveSignature(request.signature);
327
+
328
+ const requestType = request.request_type;
329
+ if (requestType === 'KASPA_TX_FINISHED') {
330
+ break;
331
+ }
332
+
333
+ const requestIndex = request.request_index ?? 0;
334
+
335
+ // prev_tx_id selects a previous-transaction request; answer from refTxs.
336
+ if (request.prev_tx_id || requestType === 'KASPA_TX_PREV_META') {
337
+ response = await this.ackPrevRequest(typedCall, request, requestIndex);
338
+ } else if (requestType === 'KASPA_TX_INPUT') {
339
+ const input = params.inputs[requestIndex];
340
+ if (!input) {
341
+ throw ERRORS.TypedError(
342
+ HardwareErrorCode.RuntimeError,
343
+ `KaspaSignTransaction: device requested input ${requestIndex} out of range`
344
+ );
345
+ }
346
+ response = await typedCall('KaspaTxAckInput', 'KaspaTxRequest', {
347
+ address_n: input.path as number[],
348
+ previous_outpoint: {
349
+ tx_id: input.prevTxId,
350
+ index: input.outputIndex,
351
+ },
352
+ amount: input.output.satoshis,
353
+ sequence: input.sequenceNumber as number,
354
+ sig_op_count: input.sigOpCount ?? 1,
355
+ script_type: inputScriptType,
356
+ use_tweak: params.useTweak,
357
+ });
358
+ } else if (requestType === 'KASPA_TX_OUTPUT') {
359
+ const output = params.outputs[requestIndex];
360
+ if (!output) {
361
+ throw ERRORS.TypedError(
362
+ HardwareErrorCode.RuntimeError,
363
+ `KaspaSignTransaction: device requested output ${requestIndex} out of range`
364
+ );
365
+ }
366
+ const isChange = !!output.addressN;
367
+ response = await typedCall('KaspaTxAckOutput', 'KaspaTxRequest', {
368
+ script_type: isChange ? 'KASPA_PAYTOCHANGE' : 'KASPA_PAYTOADDRESS',
369
+ amount: output.satoshis,
370
+ address_n: (output.addressN as number[]) ?? [],
371
+ address: output.address,
372
+ scheme: params.scheme,
373
+ use_tweak: params.useTweak,
374
+ });
375
+ } else if (requestType === 'KASPA_TX_PAYLOAD') {
376
+ const offset = requestIndex;
377
+ const length = request.request_payload_length ?? payloadLength - offset;
378
+ const chunk = payloadHex.substring(offset * 2, (offset + length) * 2);
379
+ response = await typedCall('KaspaTxAckPayloadChunk', 'KaspaTxRequest', {
380
+ payload_chunk: chunk,
381
+ });
382
+ } else {
383
+ throw ERRORS.TypedError(
384
+ HardwareErrorCode.RuntimeError,
385
+ `KaspaSignTransaction: unknown request type ${requestType ?? 'undefined'}`
386
+ );
387
+ }
388
+ }
389
+
390
+ const collected = signatures.filter(Boolean);
391
+ if (collected.length !== params.inputs.length) {
392
+ throw ERRORS.TypedError(
393
+ HardwareErrorCode.RuntimeError,
394
+ `KaspaSignTransaction: expected ${params.inputs.length} signatures, received ${collected.length}`
395
+ );
396
+ }
397
+ return collected;
398
+ }
399
+
152
400
  async run() {
153
401
  this.checkFeatureVersionLimit(
154
402
  // exists use_tweak is false check firmware version
@@ -159,25 +407,86 @@ export default class KaspaSignTransaction extends BaseMethod<KaspaSignTransactio
159
407
  }
160
408
  );
161
409
 
162
- const { raw: rawMessage } = serialize(this.params, 0);
163
- const input = this.params.inputs[0];
164
-
165
410
  const { device, params } = this;
411
+ const payloadHex = params.payload ?? '';
166
412
 
167
- // @ts-expect-error
168
- const response = await device.commands.typedCall(
169
- 'KaspaSignTx',
170
- ['KaspaTxInputRequest', 'KaspaSignedTx'],
171
- {
172
- address_n: input.path,
173
- raw_message: bytesToHex(rawMessage),
174
- scheme: params.scheme,
175
- prefix: params.prefix,
176
- input_count: params.inputs.length,
177
- use_tweak: params.useTweak,
413
+ // output_count is the protocol discriminator: attach streaming fields only
414
+ // when the tx can stream. Streaming verification needs refTxs, so without
415
+ // them prefer blind signing when available; a streaming-only tx still
416
+ // streams and fails clearly if the device requests previous txs.
417
+ const hasRefTxs = (params.refTxs?.length ?? 0) > 0;
418
+ const streamingReady = this.supportsStreaming && (hasRefTxs || !this.supportsLegacy);
419
+
420
+ const streamingFields = streamingReady
421
+ ? {
422
+ output_count: params.outputs.length,
423
+ version: params.version,
424
+ lock_time: params.lockTime as number,
425
+ subnetwork_id: params.subNetworkID,
426
+ gas: params.gas as number,
427
+ payload_length: payloadHex.length / 2,
428
+ }
429
+ : {};
430
+
431
+ // raw_message (input 0's prehash) is only computable/correct when legacy-signable.
432
+ const legacyFields = this.supportsLegacy
433
+ ? { raw_message: bytesToHex(serialize(params, 0).raw) }
434
+ : {};
435
+
436
+ // Legacy firmware reads raw_message and skips unknown streaming fields;
437
+ // new firmware streams iff output_count is present.
438
+ let response;
439
+ try {
440
+ response = await device.commands.typedCall(
441
+ 'KaspaSignTx',
442
+ ['KaspaTxRequest', 'KaspaTxInputRequest', 'KaspaSignedTx'],
443
+ {
444
+ address_n: params.inputs[0].path as number[],
445
+ scheme: params.scheme,
446
+ prefix: params.prefix,
447
+ input_count: params.inputs.length,
448
+ use_tweak: params.useTweak,
449
+ ...streamingFields,
450
+ ...legacyFields,
451
+ }
452
+ );
453
+ } catch (error) {
454
+ // Old firmware cannot decode a packet without raw_message
455
+ // (Failure_DataError); map it to an actionable upgrade error.
456
+ if (
457
+ !this.supportsLegacy &&
458
+ error instanceof HardwareError &&
459
+ error.errorCode === HardwareErrorCode.RuntimeError &&
460
+ String(error.message).includes('Failure_DataError')
461
+ ) {
462
+ throw ERRORS.TypedError(
463
+ HardwareErrorCode.CallMethodNeedUpgradeFirmware,
464
+ 'KaspaSignTransaction: this transaction requires firmware with Kaspa streaming support'
465
+ );
178
466
  }
179
- );
467
+ throw error;
468
+ }
469
+
470
+ const typedCall = device.commands.typedCall.bind(device.commands);
471
+
472
+ if (response.type === 'KaspaTxRequest') {
473
+ if (!this.supportsStreaming) {
474
+ throw ERRORS.TypedError(
475
+ HardwareErrorCode.CallMethodInvalidParameter,
476
+ 'KaspaSignTransaction: device firmware uses the streaming protocol; every output requires address or addressN'
477
+ );
478
+ }
479
+ return this.signTxStream(typedCall, response);
480
+ }
481
+
482
+ // Legacy answer to a streaming-only packet: no prehash material exists.
483
+ if (!this.supportsLegacy) {
484
+ throw ERRORS.TypedError(
485
+ HardwareErrorCode.RuntimeError,
486
+ 'KaspaSignTransaction: device chose the legacy protocol but the transaction is not legacy-signable'
487
+ );
488
+ }
180
489
 
181
- return this.processTxRequest(device.commands.typedCall.bind(device.commands), response, 0, []);
490
+ return this.processTxRequest(typedCall, response, 0, []);
182
491
  }
183
492
  }
@@ -76,7 +76,7 @@ function getSigOpCountsHash(transaction: KaspaSignTransactionParams, sighashType
76
76
  function hashTxOut(hashWriter: HashWriter, output: KaspaSignOutputParams) {
77
77
  hashWriter.writeUInt64LE(output.satoshis);
78
78
  hashWriter.writeUInt16LE(0); // TODO: USE REAL SCRIPT VERSION
79
- hashWriter.writeVarBytes(Buffer.from(output.script, 'hex'));
79
+ hashWriter.writeVarBytes(Buffer.from(output.script ?? '', 'hex'));
80
80
  }
81
81
 
82
82
  function getOutputsHash(
@@ -126,7 +126,7 @@ export function serialize(transaction: KaspaSignTransactionParams, inputNumber:
126
126
  const input = transaction.inputs[inputNumber];
127
127
  hashOutpoint(hashWriter, input);
128
128
  hashWriter.writeUInt16LE(0); // TODO: USE REAL SCRIPT VERSION
129
- hashWriter.writeVarBytes(Buffer.from(input.output.script, 'hex'));
129
+ hashWriter.writeVarBytes(Buffer.from(input.output.script!, 'hex'));
130
130
  hashWriter.writeUInt64LE(input.output.satoshis);
131
131
  hashWriter.writeUInt64LE(input.sequenceNumber);
132
132
  hashWriter.writeUInt8(transaction.sigOpCount ?? 1); // sigOpCount