@onekeyfe/hd-transport 1.1.27 → 1.2.0-alpha.0

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 (87) hide show
  1. package/README.md +2 -4
  2. package/__tests__/build-receive.test.js +6 -8
  3. package/__tests__/decode-features.test.js +3 -2
  4. package/__tests__/messages.test.js +8 -0
  5. package/__tests__/protocol-v2.test.js +754 -0
  6. package/dist/constants.d.ts +14 -5
  7. package/dist/constants.d.ts.map +1 -1
  8. package/dist/index.d.ts +934 -41
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +827 -84
  11. package/dist/protocols/index.d.ts +45 -0
  12. package/dist/protocols/index.d.ts.map +1 -0
  13. package/dist/protocols/v1/decode.d.ts +11 -0
  14. package/dist/protocols/v1/decode.d.ts.map +1 -0
  15. package/dist/protocols/v1/encode.d.ts +11 -0
  16. package/dist/protocols/v1/encode.d.ts.map +1 -0
  17. package/dist/protocols/v1/index.d.ts +5 -0
  18. package/dist/protocols/v1/index.d.ts.map +1 -0
  19. package/dist/protocols/v1/packets.d.ts +7 -0
  20. package/dist/protocols/v1/packets.d.ts.map +1 -0
  21. package/dist/{serialization → protocols/v1}/receive.d.ts +1 -1
  22. package/dist/protocols/v1/receive.d.ts.map +1 -0
  23. package/dist/protocols/v2/constants.d.ts +7 -0
  24. package/dist/protocols/v2/constants.d.ts.map +1 -0
  25. package/dist/protocols/v2/crc8.d.ts +3 -0
  26. package/dist/protocols/v2/crc8.d.ts.map +1 -0
  27. package/dist/protocols/v2/debug.d.ts +13 -0
  28. package/dist/protocols/v2/debug.d.ts.map +1 -0
  29. package/dist/protocols/v2/decode.d.ts +8 -0
  30. package/dist/protocols/v2/decode.d.ts.map +1 -0
  31. package/dist/protocols/v2/encode.d.ts +5 -0
  32. package/dist/protocols/v2/encode.d.ts.map +1 -0
  33. package/dist/protocols/v2/frame-assembler.d.ts +12 -0
  34. package/dist/protocols/v2/frame-assembler.d.ts.map +1 -0
  35. package/dist/protocols/v2/index.d.ts +7 -0
  36. package/dist/protocols/v2/index.d.ts.map +1 -0
  37. package/dist/protocols/v2/session.d.ts +50 -0
  38. package/dist/protocols/v2/session.d.ts.map +1 -0
  39. package/dist/serialization/index.d.ts +6 -3
  40. package/dist/serialization/index.d.ts.map +1 -1
  41. package/dist/serialization/protobuf/decode.d.ts.map +1 -1
  42. package/dist/serialization/protobuf/messages.d.ts +1 -1
  43. package/dist/serialization/protobuf/messages.d.ts.map +1 -1
  44. package/dist/types/messages.d.ts +461 -11
  45. package/dist/types/messages.d.ts.map +1 -1
  46. package/dist/types/transport.d.ts +14 -2
  47. package/dist/types/transport.d.ts.map +1 -1
  48. package/dist/utils/logBlockCommand.d.ts.map +1 -1
  49. package/messages-protocol-v2.json +13369 -0
  50. package/package.json +3 -3
  51. package/scripts/protobuf-build.sh +314 -20
  52. package/scripts/protobuf-patches/TxInputType.js +1 -0
  53. package/scripts/protobuf-patches/index.js +2 -0
  54. package/scripts/protobuf-types.js +224 -18
  55. package/src/constants.ts +42 -6
  56. package/src/index.ts +39 -11
  57. package/src/protocols/index.ts +144 -0
  58. package/src/{serialization/protocol → protocols/v1}/decode.ts +4 -4
  59. package/src/{serialization/protocol → protocols/v1}/encode.ts +18 -13
  60. package/src/protocols/v1/index.ts +4 -0
  61. package/src/protocols/v1/packets.ts +53 -0
  62. package/src/{serialization → protocols/v1}/receive.ts +5 -5
  63. package/src/protocols/v2/constants.ts +6 -0
  64. package/src/protocols/v2/crc8.ts +34 -0
  65. package/src/protocols/v2/debug.ts +26 -0
  66. package/src/protocols/v2/decode.ts +92 -0
  67. package/src/protocols/v2/encode.ts +116 -0
  68. package/src/protocols/v2/frame-assembler.ts +98 -0
  69. package/src/protocols/v2/index.ts +6 -0
  70. package/src/protocols/v2/session.ts +429 -0
  71. package/src/serialization/index.ts +6 -5
  72. package/src/serialization/protobuf/decode.ts +7 -0
  73. package/src/serialization/protobuf/messages.ts +8 -4
  74. package/src/types/messages.ts +606 -13
  75. package/src/types/transport.ts +26 -2
  76. package/src/utils/logBlockCommand.ts +9 -1
  77. package/dist/serialization/protocol/decode.d.ts +0 -11
  78. package/dist/serialization/protocol/decode.d.ts.map +0 -1
  79. package/dist/serialization/protocol/encode.d.ts +0 -11
  80. package/dist/serialization/protocol/encode.d.ts.map +0 -1
  81. package/dist/serialization/protocol/index.d.ts +0 -3
  82. package/dist/serialization/protocol/index.d.ts.map +0 -1
  83. package/dist/serialization/receive.d.ts.map +0 -1
  84. package/dist/serialization/send.d.ts +0 -7
  85. package/dist/serialization/send.d.ts.map +0 -1
  86. package/src/serialization/protocol/index.ts +0 -2
  87. package/src/serialization/send.ts +0 -58
package/dist/index.js CHANGED
@@ -28,7 +28,7 @@ function _interopNamespace(e) {
28
28
  }
29
29
 
30
30
  var protobuf__namespace = /*#__PURE__*/_interopNamespace(protobuf);
31
- var Long__namespace = /*#__PURE__*/_interopNamespace(Long);
31
+ var Long__default = /*#__PURE__*/_interopDefaultLegacy(Long);
32
32
  var ByteBuffer__default = /*#__PURE__*/_interopDefaultLegacy(ByteBuffer);
33
33
 
34
34
  /******************************************************************************
@@ -58,6 +58,16 @@ function __rest(s, e) {
58
58
  return t;
59
59
  }
60
60
 
61
+ function __awaiter(thisArg, _arguments, P, generator) {
62
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
63
+ return new (P || (P = Promise))(function (resolve, reject) {
64
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
65
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
66
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
67
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
68
+ });
69
+ }
70
+
61
71
  typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
62
72
  var e = new Error(message);
63
73
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
@@ -103,6 +113,12 @@ function messageToJSON(Message, fields) {
103
113
  Object.keys(fields).forEach(key => {
104
114
  const field = fields[key];
105
115
  const value = message[key];
116
+ if (value == null) {
117
+ if (field.optional) {
118
+ res[key] = null;
119
+ }
120
+ return;
121
+ }
106
122
  if (field.repeated) {
107
123
  if (isPrimitiveField(field.type)) {
108
124
  res[key] = value.map((v) => transform$1(field, v));
@@ -132,7 +148,7 @@ function messageToJSON(Message, fields) {
132
148
  });
133
149
  return res;
134
150
  }
135
- const decode$1 = (Message, data) => {
151
+ const decode = (Message, data) => {
136
152
  const buff = data.toBuffer();
137
153
  const a = new Uint8Array(buff);
138
154
  let decoded;
@@ -200,7 +216,7 @@ function patch(Message, payload) {
200
216
  });
201
217
  return patched;
202
218
  }
203
- const encode$1 = (Message, data) => {
219
+ const encode = (Message, data) => {
204
220
  const payload = patch(Message, data);
205
221
  const message = Message.fromObject(payload);
206
222
  const buffer = Message.encode(message).finish();
@@ -219,13 +235,16 @@ function parseConfigure(data) {
219
235
  const createMessageFromName = (messages, name) => {
220
236
  const Message = messages.lookupType(name);
221
237
  const MessageType = messages.lookupEnum('MessageType');
222
- let messageType = MessageType.values[`MessageType_${name}`];
223
- if (!messageType && Message.options) {
224
- messageType = Message.options['(wire_type)'];
238
+ let messageTypeId = MessageType.values[`MessageType_${name}`];
239
+ if (messageTypeId == null && Message.options) {
240
+ messageTypeId = Message.options['(wire_type)'];
241
+ }
242
+ if (!Number.isInteger(messageTypeId)) {
243
+ throw new Error(`MessageType for "${name}" is not defined in protobuf schema`);
225
244
  }
226
245
  return {
227
246
  Message,
228
- messageType,
247
+ messageTypeId,
229
248
  };
230
249
  };
231
250
  const createMessageFromType = (messages, typeId) => {
@@ -238,55 +257,31 @@ const createMessageFromType = (messages, typeId) => {
238
257
  };
239
258
  };
240
259
 
241
- const MESSAGE_TOP_CHAR = 0x003f;
242
- const MESSAGE_HEADER_BYTE = 0x23;
243
- const HEADER_SIZE = 1 + 1 + 4 + 2;
244
- const BUFFER_SIZE = 63;
245
- const COMMON_HEADER_SIZE = 6;
260
+ const PROTOCOL_V1_REPORT_ID = 0x3f;
261
+ const PROTOCOL_V1_HEADER_BYTE = 0x23;
262
+ const PROTOCOL_V1_CHUNK_PAYLOAD_SIZE = 63;
263
+ const PROTOCOL_V1_USB_PACKET_SIZE = PROTOCOL_V1_CHUNK_PAYLOAD_SIZE + 1;
264
+ const PROTOCOL_V1_MESSAGE_HEADER_SIZE = 2 + 4;
265
+ const PROTOCOL_V1_ENVELOPE_HEADER_SIZE = 1 + 1 + PROTOCOL_V1_MESSAGE_HEADER_SIZE;
266
+ const PROTOCOL_V2_FRAME_MAX_BYTES = 4608;
267
+ const PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE = 4096;
268
+ const PROTOCOL_V2_BLE_FILE_CHUNK_SIZE = 1800;
269
+ const PROTOCOL_V2_FILE_CHUNK_SIZE = PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
270
+ const PROTOCOL_V2_CHANNEL_USB = 0;
271
+ const PROTOCOL_V2_CHANNEL_BLE_UART = 1;
272
+ const PROTOCOL_V2_CHANNEL_SOCKET = 2;
273
+ const PROTOCOL_V2_PACKET_SRC_COMMAND = 0;
246
274
 
247
- const readHeader = (buffer) => {
248
- const typeId = buffer.readUint16();
249
- const length = buffer.readUint32();
250
- return { typeId, length };
251
- };
252
- const readHeaderChunked = (buffer) => {
253
- const sharp1 = buffer.readByte();
254
- const sharp2 = buffer.readByte();
255
- const typeId = buffer.readUint16();
256
- const length = buffer.readUint32();
257
- return { sharp1, sharp2, typeId, length };
258
- };
259
- const decode = (byteBuffer) => {
260
- const { typeId } = readHeader(byteBuffer);
261
- return {
262
- typeId,
263
- buffer: byteBuffer,
264
- };
265
- };
266
- const decodeChunked = (bytes) => {
267
- const byteBuffer = ByteBuffer__default["default"].wrap(bytes, undefined, undefined, true);
268
- const { sharp1, sharp2, typeId, length } = readHeaderChunked(byteBuffer);
269
- if (sharp1 !== MESSAGE_HEADER_BYTE || sharp2 !== MESSAGE_HEADER_BYTE) {
270
- throw new Error("Didn't receive expected header signature.");
271
- }
272
- return { length, typeId, restBuffer: byteBuffer };
273
- };
274
-
275
- var decodeProtocol = /*#__PURE__*/Object.freeze({
276
- __proto__: null,
277
- decode: decode,
278
- decodeChunked: decodeChunked
279
- });
280
-
281
- function encode(data, options) {
282
- const { addTrezorHeaders, chunked, messageType } = options;
283
- const fullSize = (addTrezorHeaders ? HEADER_SIZE : HEADER_SIZE - 2) + data.limit;
275
+ function encodeEnvelope(data, options) {
276
+ const { addTrezorHeaders, chunked, messageTypeId } = options;
277
+ const fullSize = (addTrezorHeaders ? PROTOCOL_V1_ENVELOPE_HEADER_SIZE : PROTOCOL_V1_ENVELOPE_HEADER_SIZE - 2) +
278
+ Number(data.limit);
284
279
  const encodedByteBuffer = new ByteBuffer__default["default"](fullSize);
285
280
  if (addTrezorHeaders) {
286
- encodedByteBuffer.writeByte(MESSAGE_HEADER_BYTE);
287
- encodedByteBuffer.writeByte(MESSAGE_HEADER_BYTE);
281
+ encodedByteBuffer.writeByte(PROTOCOL_V1_HEADER_BYTE);
282
+ encodedByteBuffer.writeByte(PROTOCOL_V1_HEADER_BYTE);
288
283
  }
289
- encodedByteBuffer.writeUint16(messageType);
284
+ encodedByteBuffer.writeUint16(messageTypeId);
290
285
  encodedByteBuffer.writeUint32(data.limit);
291
286
  encodedByteBuffer.append(data.buffer);
292
287
  encodedByteBuffer.reset();
@@ -294,7 +289,7 @@ function encode(data, options) {
294
289
  return encodedByteBuffer;
295
290
  }
296
291
  const result = [];
297
- const size = BUFFER_SIZE;
292
+ const size = PROTOCOL_V1_CHUNK_PAYLOAD_SIZE;
298
293
  const count = Math.floor((encodedByteBuffer.limit - 1) / size) + 1 || 1;
299
294
  for (let i = 0; i < count; i++) {
300
295
  const start = i * size;
@@ -306,30 +301,30 @@ function encode(data, options) {
306
301
  return result;
307
302
  }
308
303
 
309
- function buildOne(messages, name, data) {
310
- const { Message, messageType } = createMessageFromName(messages, name);
311
- const buffer = encode$1(Message, data);
312
- return encode(buffer, {
304
+ function encodeEnvelopeMessage(messages, name, data) {
305
+ const { Message, messageTypeId } = createMessageFromName(messages, name);
306
+ const buffer = encode(Message, data);
307
+ return encodeEnvelope(buffer, {
313
308
  addTrezorHeaders: false,
314
309
  chunked: false,
315
- messageType,
310
+ messageTypeId,
316
311
  });
317
312
  }
318
- const buildEncodeBuffers = (messages, name, data) => {
319
- const { Message, messageType } = createMessageFromName(messages, name);
320
- const buffer = encode$1(Message, data);
321
- return encode(buffer, {
313
+ const encodeMessageChunks = (messages, name, data) => {
314
+ const { Message, messageTypeId } = createMessageFromName(messages, name);
315
+ const buffer = encode(Message, data);
316
+ return encodeEnvelope(buffer, {
322
317
  addTrezorHeaders: true,
323
318
  chunked: true,
324
- messageType,
319
+ messageTypeId,
325
320
  });
326
321
  };
327
- const buildBuffers = (messages, name, data) => {
328
- const encodeBuffers = buildEncodeBuffers(messages, name, data);
322
+ const encodeTransportPackets = (messages, name, data) => {
323
+ const encodeBuffers = encodeMessageChunks(messages, name, data);
329
324
  const outBuffers = [];
330
325
  for (const buf of encodeBuffers) {
331
- const chunkBuffer = new ByteBuffer__default["default"](BUFFER_SIZE + 1);
332
- chunkBuffer.writeByte(MESSAGE_TOP_CHAR);
326
+ const chunkBuffer = new ByteBuffer__default["default"](PROTOCOL_V1_CHUNK_PAYLOAD_SIZE + 1);
327
+ chunkBuffer.writeByte(PROTOCOL_V1_REPORT_ID);
333
328
  chunkBuffer.append(buf);
334
329
  chunkBuffer.reset();
335
330
  outBuffers.push(chunkBuffer);
@@ -337,17 +332,374 @@ const buildBuffers = (messages, name, data) => {
337
332
  return outBuffers;
338
333
  };
339
334
 
340
- function receiveOne(messages, data) {
335
+ const readHeader = (buffer) => {
336
+ const typeId = buffer.readUint16();
337
+ const length = buffer.readUint32();
338
+ return { typeId, length };
339
+ };
340
+ const readHeaderChunked = (buffer) => {
341
+ const sharp1 = buffer.readByte();
342
+ const sharp2 = buffer.readByte();
343
+ const typeId = buffer.readUint16();
344
+ const length = buffer.readUint32();
345
+ return { sharp1, sharp2, typeId, length };
346
+ };
347
+ const decodeEnvelope = (byteBuffer) => {
348
+ const { typeId } = readHeader(byteBuffer);
349
+ return {
350
+ typeId,
351
+ buffer: byteBuffer,
352
+ };
353
+ };
354
+ const decodeFirstChunk = (bytes) => {
355
+ const byteBuffer = ByteBuffer__default["default"].wrap(bytes, undefined, undefined, true);
356
+ const { sharp1, sharp2, typeId, length } = readHeaderChunked(byteBuffer);
357
+ if (sharp1 !== PROTOCOL_V1_HEADER_BYTE || sharp2 !== PROTOCOL_V1_HEADER_BYTE) {
358
+ throw new Error("Didn't receive expected header signature.");
359
+ }
360
+ return { length, typeId, restBuffer: byteBuffer };
361
+ };
362
+
363
+ function decodeMessage(messages, data) {
341
364
  const bytebuffer = ByteBuffer__default["default"].wrap(data, 'hex');
342
- const { typeId, buffer } = decode(bytebuffer);
365
+ const { typeId, buffer } = decodeEnvelope(bytebuffer);
343
366
  const { Message, messageName } = createMessageFromType(messages, typeId);
344
- const message = decode$1(Message, buffer);
367
+ const message = decode(Message, buffer);
345
368
  return {
346
369
  message,
347
370
  type: messageName,
348
371
  };
349
372
  }
350
373
 
374
+ const PROTO_HEAD_SOF = 0x5a;
375
+ const PROTO_PRE_HEAD_SIZE = 4;
376
+ const PROTO_HEAD_CRC_SIZE = 8;
377
+ const CRC8_INIT = 0x30;
378
+ const PACKET_SIZE = 4096;
379
+ const PROTO_DATA_TYPE_PACKET = 0;
380
+
381
+ const CRC8_TABLE = new Uint8Array([
382
+ 0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83, 0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41,
383
+ 0x9d, 0xc3, 0x21, 0x7f, 0xfc, 0xa2, 0x40, 0x1e, 0x5f, 0x01, 0xe3, 0xbd, 0x3e, 0x60, 0x82, 0xdc,
384
+ 0x23, 0x7d, 0x9f, 0xc1, 0x42, 0x1c, 0xfe, 0xa0, 0xe1, 0xbf, 0x5d, 0x03, 0x80, 0xde, 0x3c, 0x62,
385
+ 0xbe, 0xe0, 0x02, 0x5c, 0xdf, 0x81, 0x63, 0x3d, 0x7c, 0x22, 0xc0, 0x9e, 0x1d, 0x43, 0xa1, 0xff,
386
+ 0x46, 0x18, 0xfa, 0xa4, 0x27, 0x79, 0x9b, 0xc5, 0x84, 0xda, 0x38, 0x66, 0xe5, 0xbb, 0x59, 0x07,
387
+ 0xdb, 0x85, 0x67, 0x39, 0xba, 0xe4, 0x06, 0x58, 0x19, 0x47, 0xa5, 0xfb, 0x78, 0x26, 0xc4, 0x9a,
388
+ 0x65, 0x3b, 0xd9, 0x87, 0x04, 0x5a, 0xb8, 0xe6, 0xa7, 0xf9, 0x1b, 0x45, 0xc6, 0x98, 0x7a, 0x24,
389
+ 0xf8, 0xa6, 0x44, 0x1a, 0x99, 0xc7, 0x25, 0x7b, 0x3a, 0x64, 0x86, 0xd8, 0x5b, 0x05, 0xe7, 0xb9,
390
+ 0x8c, 0xd2, 0x30, 0x6e, 0xed, 0xb3, 0x51, 0x0f, 0x4e, 0x10, 0xf2, 0xac, 0x2f, 0x71, 0x93, 0xcd,
391
+ 0x11, 0x4f, 0xad, 0xf3, 0x70, 0x2e, 0xcc, 0x92, 0xd3, 0x8d, 0x6f, 0x31, 0xb2, 0xec, 0x0e, 0x50,
392
+ 0xaf, 0xf1, 0x13, 0x4d, 0xce, 0x90, 0x72, 0x2c, 0x6d, 0x33, 0xd1, 0x8f, 0x0c, 0x52, 0xb0, 0xee,
393
+ 0x32, 0x6c, 0x8e, 0xd0, 0x53, 0x0d, 0xef, 0xb1, 0xf0, 0xae, 0x4c, 0x12, 0x91, 0xcf, 0x2d, 0x73,
394
+ 0xca, 0x94, 0x76, 0x28, 0xab, 0xf5, 0x17, 0x49, 0x08, 0x56, 0xb4, 0xea, 0x69, 0x37, 0xd5, 0x8b,
395
+ 0x57, 0x09, 0xeb, 0xb5, 0x36, 0x68, 0x8a, 0xd4, 0x95, 0xcb, 0x29, 0x77, 0xf4, 0xaa, 0x48, 0x16,
396
+ 0xe9, 0xb7, 0x55, 0x0b, 0x88, 0xd6, 0x34, 0x6a, 0x2b, 0x75, 0x97, 0xc9, 0x4a, 0x14, 0xf6, 0xa8,
397
+ 0x74, 0x2a, 0xc8, 0x96, 0x15, 0x4b, 0xa9, 0xf7, 0xb6, 0xe8, 0x0a, 0x54, 0xd7, 0x89, 0x6b, 0x35,
398
+ ]);
399
+ function crc8(data, len) {
400
+ let crc = CRC8_INIT;
401
+ for (let i = 0; i < len; i++) {
402
+ crc = CRC8_TABLE[crc ^ data[i]];
403
+ }
404
+ return crc;
405
+ }
406
+
407
+ function logProtocolV2Debug(options, stage, details) {
408
+ var _a, _b, _c;
409
+ (_b = (_a = options === null || options === void 0 ? void 0 : options.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, `[${(_c = options.logPrefix) !== null && _c !== void 0 ? _c : 'ProtocolV2'}] ${stage}`, Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (options.context ? { context: options.context } : {})), (options.messageName ? { messageName: options.messageName } : {})), (options.messageTypeId !== undefined ? { messageTypeId: options.messageTypeId } : {})), (options.pbPayloadLength !== undefined ? { pbPayloadLength: options.pbPayloadLength } : {})), details));
410
+ }
411
+
412
+ const PROTO_SEQ_DEFAULT = 1;
413
+ function nextProtoSeq(current) {
414
+ return current >= 255 ? 1 : current + 1;
415
+ }
416
+ function encodeFrame(payload, packetSrc, router, debugOptions, seq) {
417
+ const resolvedPacketSrc = packetSrc !== null && packetSrc !== void 0 ? packetSrc : 0;
418
+ const resolvedRouter = router !== null && router !== void 0 ? router : 0;
419
+ const resolvedSeq = seq !== null && seq !== void 0 ? seq : PROTO_SEQ_DEFAULT;
420
+ if (!Number.isInteger(resolvedSeq) || resolvedSeq < 1 || resolvedSeq > 255) {
421
+ throw new Error(`Protocol V2 seq out of range (1-255): ${resolvedSeq}`);
422
+ }
423
+ const payloadLen = payload ? payload.length : 0;
424
+ const frameLen = payloadLen + PROTO_HEAD_CRC_SIZE;
425
+ if (frameLen > PROTOCOL_V2_FRAME_MAX_BYTES) {
426
+ throw new Error(`Protocol V2 frame too large: ${frameLen}`);
427
+ }
428
+ const frame = new Uint8Array(frameLen);
429
+ frame[0] = PROTO_HEAD_SOF;
430
+ frame[1] = frameLen % 256;
431
+ frame[2] = Math.floor(frameLen / 256) % 256;
432
+ frame[3] = 0;
433
+ frame[4] = resolvedRouter % 256;
434
+ frame[5] = (resolvedPacketSrc % 16) * 4 + (PROTO_DATA_TYPE_PACKET % 4);
435
+ frame[6] = resolvedSeq;
436
+ frame[3] = crc8(frame, 3);
437
+ if (payload && payloadLen > 0) {
438
+ frame.set(payload, 7);
439
+ }
440
+ frame[frameLen - 1] = crc8(frame, frameLen - 1);
441
+ logProtocolV2Debug(debugOptions, 'encode raw frame', {
442
+ frameLen,
443
+ payloadLen,
444
+ packetSrc: resolvedPacketSrc,
445
+ router: frame[4],
446
+ attr: frame[5],
447
+ seq: frame[6],
448
+ headerCrc: frame[3],
449
+ frameCrc: frame[frameLen - 1],
450
+ });
451
+ return frame;
452
+ }
453
+ function encodeProtobufFrame(messageTypeId, pbPayload, packetSrc, router, debugOptions, seq) {
454
+ const payload = new Uint8Array(2 + pbPayload.length);
455
+ payload[0] = messageTypeId % 256;
456
+ payload[1] = Math.floor(messageTypeId / 256) % 256;
457
+ payload.set(pbPayload, 2);
458
+ return encodeFrame(payload, packetSrc, router, Object.assign(Object.assign({}, debugOptions), { messageTypeId, pbPayloadLength: pbPayload.length }), seq);
459
+ }
460
+
461
+ function decodeFrame(data, debugOptions) {
462
+ if (data.length < PROTO_HEAD_CRC_SIZE) {
463
+ throw new Error(`Protocol V2 frame too short: ${data.length} bytes`);
464
+ }
465
+ if (data[0] !== PROTO_HEAD_SOF) {
466
+ throw new Error(`Invalid SOF byte: expected 0x5A, got 0x${data[0].toString(16).padStart(2, '0')}`);
467
+ }
468
+ const frameLen = data[1] + data[2] * 256;
469
+ if (data.length < frameLen) {
470
+ throw new Error(`Frame truncated: expected ${frameLen} bytes, got ${data.length}`);
471
+ }
472
+ const expectedHeaderCrc = crc8(data, 3);
473
+ if (data[3] !== expectedHeaderCrc) {
474
+ throw new Error(`Header CRC mismatch: expected 0x${expectedHeaderCrc
475
+ .toString(16)
476
+ .padStart(2, '0')}, got 0x${data[3].toString(16).padStart(2, '0')}`);
477
+ }
478
+ const expectedFrameCrc = crc8(data, frameLen - 1);
479
+ if (data[frameLen - 1] !== expectedFrameCrc) {
480
+ throw new Error(`Frame CRC mismatch: expected 0x${expectedFrameCrc
481
+ .toString(16)
482
+ .padStart(2, '0')}, got 0x${data[frameLen - 1].toString(16).padStart(2, '0')}`);
483
+ }
484
+ const seq = data[6];
485
+ const payloadData = data.slice(7, frameLen - 1);
486
+ if (payloadData.length < 2) {
487
+ throw new Error(`Protocol V2 payload too short (need >=2 bytes for messageTypeId)`);
488
+ }
489
+ const messageTypeId = payloadData[0] + payloadData[1] * 256;
490
+ const pbPayload = payloadData.slice(2);
491
+ logProtocolV2Debug(debugOptions, 'decode raw frame', {
492
+ frameLen,
493
+ dataLength: data.length,
494
+ router: data[4],
495
+ attr: data[5],
496
+ seq,
497
+ headerCrc: data[3],
498
+ expectedHeaderCrc,
499
+ frameCrc: data[frameLen - 1],
500
+ expectedFrameCrc,
501
+ messageTypeId,
502
+ pbPayloadLength: pbPayload.length,
503
+ });
504
+ return { messageTypeId, pbPayload, seq };
505
+ }
506
+
507
+ function concatUint8Arrays(arrays) {
508
+ const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
509
+ const result = new Uint8Array(totalLength);
510
+ let offset = 0;
511
+ for (const arr of arrays) {
512
+ result.set(arr, offset);
513
+ offset += arr.length;
514
+ }
515
+ return result;
516
+ }
517
+ class ProtocolV2FrameAssembler {
518
+ constructor(maxFrameBytes = PROTOCOL_V2_FRAME_MAX_BYTES) {
519
+ this.buffer = new Uint8Array(0);
520
+ this.maxFrameBytes = maxFrameBytes;
521
+ }
522
+ reset() {
523
+ this.buffer = new Uint8Array(0);
524
+ }
525
+ push(chunk) {
526
+ this.append(chunk);
527
+ return this.extractFrame();
528
+ }
529
+ drain(chunk = new Uint8Array(0)) {
530
+ this.append(chunk);
531
+ const frames = [];
532
+ for (;;) {
533
+ const frame = this.extractFrame();
534
+ if (!frame)
535
+ break;
536
+ frames.push(frame);
537
+ }
538
+ return frames;
539
+ }
540
+ append(chunk) {
541
+ if (chunk.length > 0) {
542
+ this.buffer = concatUint8Arrays([this.buffer, chunk]);
543
+ }
544
+ }
545
+ extractFrame() {
546
+ if (this.buffer.length < 3)
547
+ return undefined;
548
+ if (this.buffer[0] !== PROTO_HEAD_SOF) {
549
+ this.reset();
550
+ throw new Error('Invalid Protocol V2 SOF');
551
+ }
552
+ const expectedLen = this.buffer[1] + this.buffer[2] * 256;
553
+ if (expectedLen < PROTO_HEAD_CRC_SIZE) {
554
+ this.reset();
555
+ throw new Error(`Protocol V2 frame length too small: ${expectedLen}`);
556
+ }
557
+ if (expectedLen > this.maxFrameBytes) {
558
+ this.reset();
559
+ throw new Error(`Protocol V2 frame too large: ${expectedLen}`);
560
+ }
561
+ if (this.buffer.length < PROTO_PRE_HEAD_SIZE)
562
+ return undefined;
563
+ const expectedHeaderCrc = crc8(this.buffer, 3);
564
+ if (this.buffer[3] !== expectedHeaderCrc) {
565
+ this.reset();
566
+ throw new Error(`Protocol V2 header CRC mismatch: expected 0x${expectedHeaderCrc
567
+ .toString(16)
568
+ .padStart(2, '0')}`);
569
+ }
570
+ if (this.buffer.length < expectedLen)
571
+ return undefined;
572
+ const frame = this.buffer.slice(0, expectedLen);
573
+ this.buffer = this.buffer.slice(expectedLen);
574
+ return frame;
575
+ }
576
+ }
577
+
578
+ var protocolV2Codec = /*#__PURE__*/Object.freeze({
579
+ __proto__: null,
580
+ PROTO_HEAD_SOF: PROTO_HEAD_SOF,
581
+ PROTO_PRE_HEAD_SIZE: PROTO_PRE_HEAD_SIZE,
582
+ PROTO_HEAD_CRC_SIZE: PROTO_HEAD_CRC_SIZE,
583
+ CRC8_INIT: CRC8_INIT,
584
+ PACKET_SIZE: PACKET_SIZE,
585
+ PROTO_DATA_TYPE_PACKET: PROTO_DATA_TYPE_PACKET,
586
+ CRC8_TABLE: CRC8_TABLE,
587
+ crc8: crc8,
588
+ logProtocolV2Debug: logProtocolV2Debug,
589
+ nextProtoSeq: nextProtoSeq,
590
+ encodeFrame: encodeFrame,
591
+ encodeProtobufFrame: encodeProtobufFrame,
592
+ decodeFrame: decodeFrame,
593
+ concatUint8Arrays: concatUint8Arrays,
594
+ ProtocolV2FrameAssembler: ProtocolV2FrameAssembler
595
+ });
596
+
597
+ const PROTOCOL_V2_SYS_MESSAGE_THRESHOLD = 60000;
598
+ const resolveProtocolV2EncodeSchema = (name, schemas) => {
599
+ try {
600
+ schemas.protocolV2.lookupType(name);
601
+ return schemas.protocolV2;
602
+ }
603
+ catch (_a) {
604
+ throw new Error(`Protocol V2 message "${name}" is not defined in Protocol V2 schema`);
605
+ }
606
+ };
607
+ const PROTOCOL_V2_LEGACY_DECODE_ALLOWLIST = new Set([
608
+ 'ButtonRequest',
609
+ 'EntropyRequest',
610
+ 'PinMatrixRequest',
611
+ 'PassphraseRequest',
612
+ 'Deprecated_PassphraseStateRequest',
613
+ 'WordRequest',
614
+ ]);
615
+ const createProtocolV2MessageFromType = (messageTypeId, schemas) => {
616
+ try {
617
+ return createMessageFromType(schemas.protocolV2, messageTypeId);
618
+ }
619
+ catch (protocolV2Error) {
620
+ let legacyMessage;
621
+ try {
622
+ legacyMessage = createMessageFromType(schemas.protocolV1, messageTypeId);
623
+ }
624
+ catch (_a) {
625
+ throw protocolV2Error;
626
+ }
627
+ if (PROTOCOL_V2_LEGACY_DECODE_ALLOWLIST.has(legacyMessage.messageName)) {
628
+ return legacyMessage;
629
+ }
630
+ throw protocolV2Error;
631
+ }
632
+ };
633
+ const ProtocolV1 = {
634
+ encodeEnvelope: encodeEnvelopeMessage,
635
+ encodeMessageChunks,
636
+ encodeTransportPackets,
637
+ decodeFirstChunk,
638
+ decodeMessage: decodeMessage,
639
+ };
640
+ const ProtocolV2 = {
641
+ encodeFrame(schemas, name, data, options = {}) {
642
+ var _a, _b, _c, _d, _e, _f, _g;
643
+ const encodeMessages = resolveProtocolV2EncodeSchema(name, schemas);
644
+ const { Message, messageTypeId } = createMessageFromName(encodeMessages, name);
645
+ const pbBuffer = encode(Message, data);
646
+ pbBuffer.reset();
647
+ const rawPbBuffer = pbBuffer.toBuffer();
648
+ const pbBytes = new Uint8Array(rawPbBuffer);
649
+ (_b = (_a = options.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, `[${(_c = options.logPrefix) !== null && _c !== void 0 ? _c : 'ProtocolV2'}] encode protobuf`, {
650
+ context: (_d = options.context) !== null && _d !== void 0 ? _d : `encode:${name}`,
651
+ messageName: name,
652
+ messageTypeId,
653
+ pbPayloadLength: pbBytes.length,
654
+ packetSrc: (_e = options.packetSrc) !== null && _e !== void 0 ? _e : 0,
655
+ router: (_f = options.router) !== null && _f !== void 0 ? _f : 0,
656
+ });
657
+ return encodeProtobufFrame(messageTypeId, pbBytes, options.packetSrc, options.router, {
658
+ logger: options.logger,
659
+ logPrefix: options.logPrefix,
660
+ context: (_g = options.context) !== null && _g !== void 0 ? _g : `encode:${name}`,
661
+ messageName: name,
662
+ }, options.seq);
663
+ },
664
+ decodeFrame(schemas, frame, options = {}) {
665
+ var _a, _b, _c, _d, _e;
666
+ const { messageTypeId, pbPayload, seq } = decodeFrame(frame, {
667
+ logger: options.logger,
668
+ logPrefix: options.logPrefix,
669
+ context: (_a = options.context) !== null && _a !== void 0 ? _a : 'decode',
670
+ });
671
+ const { Message, messageName } = createProtocolV2MessageFromType(messageTypeId, schemas);
672
+ const rxByteBuffer = ByteBuffer__default["default"].wrap(Buffer.from(pbPayload));
673
+ const message = decode(Message, rxByteBuffer);
674
+ (_c = (_b = options.logger) === null || _b === void 0 ? void 0 : _b.debug) === null || _c === void 0 ? void 0 : _c.call(_b, `[${(_d = options.logPrefix) !== null && _d !== void 0 ? _d : 'ProtocolV2'}] decode protobuf`, {
675
+ context: (_e = options.context) !== null && _e !== void 0 ? _e : `decode:${messageName}`,
676
+ messageName,
677
+ messageTypeId,
678
+ pbPayloadLength: pbPayload.length,
679
+ seq,
680
+ });
681
+ return {
682
+ message,
683
+ messageName,
684
+ messageTypeId,
685
+ pbPayload,
686
+ seq,
687
+ type: messageName,
688
+ };
689
+ },
690
+ };
691
+
692
+ var index$1 = /*#__PURE__*/Object.freeze({
693
+ __proto__: null,
694
+ decodeEnvelope: decodeEnvelope,
695
+ decodeFirstChunk: decodeFirstChunk,
696
+ encodeEnvelope: encodeEnvelope,
697
+ encodeEnvelopeMessage: encodeEnvelopeMessage,
698
+ encodeMessageChunks: encodeMessageChunks,
699
+ encodeTransportPackets: encodeTransportPackets,
700
+ decodeMessage: decodeMessage
701
+ });
702
+
351
703
  const ERROR = 'Wrong result type.';
352
704
  function info(res) {
353
705
  if (typeof res !== 'object' || res == null) {
@@ -435,6 +787,271 @@ var check = /*#__PURE__*/Object.freeze({
435
787
  call: call
436
788
  });
437
789
 
790
+ const LogBlockCommand = new Set([
791
+ 'PassphraseAck',
792
+ 'PinMatrixAck',
793
+ 'FilesystemFileWrite',
794
+ 'FileWrite',
795
+ 'EmmcFileWrite',
796
+ 'FirmwareUpload',
797
+ 'ResourceAck',
798
+ ]);
799
+
800
+ function hexToBytes(hex) {
801
+ const clean = hex.replace(/\s+/g, '');
802
+ if (clean.length % 2 !== 0) {
803
+ throw new Error(`Invalid hex string: odd length ${clean.length}`);
804
+ }
805
+ if (!/^[0-9a-fA-F]*$/.test(clean)) {
806
+ throw new Error('Invalid hex string: contains non-hex characters');
807
+ }
808
+ const bytes = new Uint8Array(clean.length / 2);
809
+ for (let i = 0; i < bytes.length; i += 1) {
810
+ bytes[i] = parseInt(clean.substring(i * 2, i * 2 + 2), 16);
811
+ }
812
+ return bytes;
813
+ }
814
+ function bytesToHex(bytes) {
815
+ return Array.from(bytes)
816
+ .map(b => b.toString(16).padStart(2, '0'))
817
+ .join('');
818
+ }
819
+ const PROTOCOL_V2_DEBUG_HEADER_BYTES = 7;
820
+ const PROTOCOL_V2_DEBUG_ARRAY_ITEMS_LIMIT = 20;
821
+ const PROTOCOL_V2_DEBUG_OBJECT_KEYS_LIMIT = 40;
822
+ const PROTOCOL_V2_DEBUG_STRING_LIMIT = 512;
823
+ const PROTOCOL_V2_DEBUG_DEPTH_LIMIT = 4;
824
+ const HIGH_VOLUME_PROTOCOL_V2_CALLS = new Set([
825
+ ...LogBlockCommand,
826
+ 'FilesystemFileRead',
827
+ 'FileRead',
828
+ 'EmmcFileRead',
829
+ ]);
830
+ function shouldReduceProtocolV2Debug(name) {
831
+ return HIGH_VOLUME_PROTOCOL_V2_CALLS.has(name);
832
+ }
833
+ function frameHeaderDebugHex(frame) {
834
+ return bytesToHex(frame.slice(0, PROTOCOL_V2_DEBUG_HEADER_BYTES));
835
+ }
836
+ function getBinaryByteLength(value) {
837
+ if (value instanceof ArrayBuffer) {
838
+ return value.byteLength;
839
+ }
840
+ if (ArrayBuffer.isView(value)) {
841
+ return value.byteLength;
842
+ }
843
+ if (typeof Blob !== 'undefined' && value instanceof Blob) {
844
+ return value.size;
845
+ }
846
+ return undefined;
847
+ }
848
+ function summarizeRedactedData(value) {
849
+ const byteLength = getBinaryByteLength(value);
850
+ if (byteLength !== undefined) {
851
+ return `[redacted data: ${byteLength} bytes]`;
852
+ }
853
+ if (typeof value === 'string') {
854
+ return `[redacted data: string length=${value.length}]`;
855
+ }
856
+ if (Array.isArray(value)) {
857
+ return `[redacted data: array length=${value.length}]`;
858
+ }
859
+ if (value && typeof value === 'object') {
860
+ return `[redacted data: object keys=${Object.keys(value).length}]`;
861
+ }
862
+ return `[redacted data: ${typeof value}]`;
863
+ }
864
+ function sanitizeProtocolV2DebugPayload(value, key = '', depth = 0) {
865
+ if (/^(data|payload)$/i.test(key) && value !== null && value !== undefined) {
866
+ return summarizeRedactedData(value);
867
+ }
868
+ if (/(passphrase|pin|mnemonic|seed|private)/i.test(key)) {
869
+ return '[redacted sensitive value]';
870
+ }
871
+ const byteLength = getBinaryByteLength(value);
872
+ if (byteLength !== undefined) {
873
+ return `[binary: ${byteLength} bytes]`;
874
+ }
875
+ if (typeof value === 'string') {
876
+ return value.length > PROTOCOL_V2_DEBUG_STRING_LIMIT
877
+ ? `${value.slice(0, PROTOCOL_V2_DEBUG_STRING_LIMIT)}... (len=${value.length})`
878
+ : value;
879
+ }
880
+ if (!value || typeof value !== 'object') {
881
+ return value;
882
+ }
883
+ if (depth >= PROTOCOL_V2_DEBUG_DEPTH_LIMIT) {
884
+ return Array.isArray(value)
885
+ ? `[array length=${value.length}]`
886
+ : `[object keys=${Object.keys(value).length}]`;
887
+ }
888
+ if (Array.isArray(value)) {
889
+ const items = value
890
+ .slice(0, PROTOCOL_V2_DEBUG_ARRAY_ITEMS_LIMIT)
891
+ .map(item => sanitizeProtocolV2DebugPayload(item, key, depth + 1));
892
+ if (value.length > PROTOCOL_V2_DEBUG_ARRAY_ITEMS_LIMIT) {
893
+ items.push(`... (${value.length - PROTOCOL_V2_DEBUG_ARRAY_ITEMS_LIMIT} more)`);
894
+ }
895
+ return items;
896
+ }
897
+ const entries = Object.entries(value).slice(0, PROTOCOL_V2_DEBUG_OBJECT_KEYS_LIMIT);
898
+ const sanitized = {};
899
+ entries.forEach(([entryKey, entryValue]) => {
900
+ sanitized[entryKey] = sanitizeProtocolV2DebugPayload(entryValue, entryKey, depth + 1);
901
+ });
902
+ if (Object.keys(value).length > PROTOCOL_V2_DEBUG_OBJECT_KEYS_LIMIT) {
903
+ sanitized.__truncated__ = `${Object.keys(value).length - PROTOCOL_V2_DEBUG_OBJECT_KEYS_LIMIT} more keys`;
904
+ }
905
+ return sanitized;
906
+ }
907
+ const COMMON_TERMINAL_RESPONSE_TYPES = new Set([
908
+ 'Failure',
909
+ 'ButtonRequest',
910
+ 'EntropyRequest',
911
+ 'PinMatrixRequest',
912
+ 'PassphraseRequest',
913
+ 'Deprecated_PassphraseStateRequest',
914
+ 'WordRequest',
915
+ ]);
916
+ function isExpectedTerminalResponse(response, expectedTypes) {
917
+ if (!expectedTypes || expectedTypes.length === 0)
918
+ return true;
919
+ return expectedTypes.includes(response.type) || COMMON_TERMINAL_RESPONSE_TYPES.has(response.type);
920
+ }
921
+ function getErrorMessage(error) {
922
+ if (!error)
923
+ return '';
924
+ if (typeof error === 'string')
925
+ return error;
926
+ if (typeof error === 'object' && 'message' in error) {
927
+ const { message } = error;
928
+ return typeof message === 'string' ? message : String(message !== null && message !== void 0 ? message : '');
929
+ }
930
+ return String(error);
931
+ }
932
+ function withProtocolTimeout(promise, timeoutMs, createTimeoutError, onTimeout) {
933
+ return __awaiter(this, void 0, void 0, function* () {
934
+ if (!timeoutMs)
935
+ return promise;
936
+ let timer;
937
+ try {
938
+ return yield Promise.race([
939
+ promise,
940
+ new Promise((_, reject) => {
941
+ timer = setTimeout(() => {
942
+ onTimeout === null || onTimeout === void 0 ? void 0 : onTimeout();
943
+ reject(createTimeoutError());
944
+ }, timeoutMs);
945
+ }),
946
+ ]);
947
+ }
948
+ finally {
949
+ if (timer)
950
+ clearTimeout(timer);
951
+ }
952
+ });
953
+ }
954
+ const PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS = 30000;
955
+ class ProtocolV2Session {
956
+ constructor(options) {
957
+ this.pendingCall = Promise.resolve();
958
+ this.protoSeq = 0;
959
+ this.options = options;
960
+ }
961
+ call(name, data, callOptions = {}) {
962
+ const run = () => this.executeCall(name, data, callOptions);
963
+ const result = this.pendingCall.then(run, run);
964
+ this.pendingCall = result.catch(() => undefined);
965
+ return result;
966
+ }
967
+ executeCall(name, data, callOptions) {
968
+ var _a, _b;
969
+ return __awaiter(this, void 0, void 0, function* () {
970
+ const { schemas, router, packetSrc = PROTOCOL_V2_PACKET_SRC_COMMAND, writeFrame, readFrame, logger, logPrefix = 'ProtocolV2', createTimeoutError, } = this.options;
971
+ const shouldReduceDebug = shouldReduceProtocolV2Debug(name);
972
+ this.protoSeq = nextProtoSeq(this.protoSeq);
973
+ const frame = ProtocolV2.encodeFrame(schemas, name, data, {
974
+ packetSrc,
975
+ router,
976
+ seq: this.protoSeq,
977
+ logger: shouldReduceDebug ? undefined : logger,
978
+ logPrefix,
979
+ context: `tx:${name}`,
980
+ });
981
+ const expectedSeq = frame[6];
982
+ if (!shouldReduceDebug) {
983
+ (_a = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _a === void 0 ? void 0 : _a.call(logger, `[${logPrefix}] TX payload name=${name}`, sanitizeProtocolV2DebugPayload(data));
984
+ (_b = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _b === void 0 ? void 0 : _b.call(logger, `[${logPrefix}] TX frame name=${name} len=${frame.length} router=${frame[4]} attr=${frame[5]} seq=${expectedSeq} headerHex=${frameHeaderDebugHex(frame)}`);
985
+ }
986
+ yield withProtocolTimeout(writeFrame(frame), PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS, () => new Error(`Protocol V2 write timeout after ${PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS}ms for ${name}`));
987
+ const cancellation = { cancelled: false };
988
+ const readResponse = () => __awaiter(this, void 0, void 0, function* () {
989
+ var _c, _d, _e, _f, _g, _h, _j, _k;
990
+ while (!cancellation.cancelled) {
991
+ const rxFrame = yield readFrame();
992
+ if (cancellation.cancelled) {
993
+ break;
994
+ }
995
+ if (!shouldReduceDebug) {
996
+ (_c = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _c === void 0 ? void 0 : _c.call(logger, `[${logPrefix}] RX frame len=${rxFrame.length} router=${rxFrame[4]} attr=${rxFrame[5]} seq=${rxFrame[6]} headerHex=${frameHeaderDebugHex(rxFrame)}`);
997
+ }
998
+ const decoded = ProtocolV2.decodeFrame(schemas, rxFrame, {
999
+ logger: shouldReduceDebug ? undefined : logger,
1000
+ logPrefix,
1001
+ context: `rx:${name}`,
1002
+ });
1003
+ if (!shouldReduceDebug && decoded.seq !== expectedSeq) {
1004
+ (_d = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _d === void 0 ? void 0 : _d.call(logger, `[${logPrefix}] seq differs for ${name}: tx=${expectedSeq}, rx=${decoded.seq}`);
1005
+ }
1006
+ if (!shouldReduceDebug) {
1007
+ (_e = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _e === void 0 ? void 0 : _e.call(logger, `[${logPrefix}] TX name=${name} seq=${expectedSeq} | RX seq=${decoded.seq} messageTypeId=${decoded.messageTypeId} pbPayload=${decoded.pbPayload.length}B`);
1008
+ (_f = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _f === void 0 ? void 0 : _f.call(logger, `[${logPrefix}] RX payload type=${decoded.type} messageTypeId=${decoded.messageTypeId}`, sanitizeProtocolV2DebugPayload(decoded.message));
1009
+ }
1010
+ const response = call(decoded);
1011
+ if ((_g = callOptions.intermediateTypes) === null || _g === void 0 ? void 0 : _g.includes(response.type)) {
1012
+ (_h = callOptions.onIntermediateResponse) === null || _h === void 0 ? void 0 : _h.call(callOptions, response);
1013
+ }
1014
+ else if (isExpectedTerminalResponse(response, callOptions.expectedTypes)) {
1015
+ return response;
1016
+ }
1017
+ else if (!shouldReduceDebug) {
1018
+ (_j = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _j === void 0 ? void 0 : _j.call(logger, `[${logPrefix}] skip unexpected response for ${name}: expected=${(_k = callOptions.expectedTypes) === null || _k === void 0 ? void 0 : _k.join('|')} got=${response.type}`);
1019
+ }
1020
+ }
1021
+ throw new Error(`Protocol V2 read loop cancelled after timeout for ${name}`);
1022
+ });
1023
+ return withProtocolTimeout(readResponse(), callOptions.timeoutMs, () => {
1024
+ var _a;
1025
+ return createTimeoutError
1026
+ ? createTimeoutError(name, (_a = callOptions.timeoutMs) !== null && _a !== void 0 ? _a : 0)
1027
+ : new Error(`Protocol V2 response timeout after ${callOptions.timeoutMs}ms for ${name}`);
1028
+ }, () => {
1029
+ cancellation.cancelled = true;
1030
+ });
1031
+ });
1032
+ }
1033
+ }
1034
+ function probeProtocolV2({ call, timeoutMs, logger, logPrefix = 'ProtocolV2', onBeforeProbe, onProbeFailed, }) {
1035
+ var _a;
1036
+ return __awaiter(this, void 0, void 0, function* () {
1037
+ let pingError;
1038
+ try {
1039
+ yield (onBeforeProbe === null || onBeforeProbe === void 0 ? void 0 : onBeforeProbe());
1040
+ const response = yield call('Ping', { message: 'probe' }, { timeoutMs, expectedTypes: ['Success'] });
1041
+ if (response.type === 'Success') {
1042
+ return true;
1043
+ }
1044
+ pingError = new Error(`unexpected response type ${response.type}`);
1045
+ }
1046
+ catch (error) {
1047
+ pingError = error;
1048
+ }
1049
+ (_a = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _a === void 0 ? void 0 : _a.call(logger, `[${logPrefix}] Protocol V2 ping probe failed:`, getErrorMessage(pingError));
1050
+ yield (onProbeFailed === null || onProbeFailed === void 0 ? void 0 : onProbeFailed(pingError));
1051
+ return false;
1052
+ });
1053
+ }
1054
+
438
1055
  exports.AptosTransactionType = void 0;
439
1056
  (function (AptosTransactionType) {
440
1057
  AptosTransactionType[AptosTransactionType["STANDARD"] = 0] = "STANDARD";
@@ -500,6 +1117,7 @@ exports.Enum_RequestType = void 0;
500
1117
  Enum_RequestType[Enum_RequestType["TXEXTRADATA"] = 4] = "TXEXTRADATA";
501
1118
  Enum_RequestType[Enum_RequestType["TXORIGINPUT"] = 5] = "TXORIGINPUT";
502
1119
  Enum_RequestType[Enum_RequestType["TXORIGOUTPUT"] = 6] = "TXORIGOUTPUT";
1120
+ Enum_RequestType[Enum_RequestType["TXPAYMENTREQ"] = 7] = "TXPAYMENTREQ";
503
1121
  })(exports.Enum_RequestType || (exports.Enum_RequestType = {}));
504
1122
  exports.RebootType = void 0;
505
1123
  (function (RebootType) {
@@ -682,6 +1300,9 @@ exports.Enum_BackupType = void 0;
682
1300
  Enum_BackupType[Enum_BackupType["Bip39"] = 0] = "Bip39";
683
1301
  Enum_BackupType[Enum_BackupType["Slip39_Basic"] = 1] = "Slip39_Basic";
684
1302
  Enum_BackupType[Enum_BackupType["Slip39_Advanced"] = 2] = "Slip39_Advanced";
1303
+ Enum_BackupType[Enum_BackupType["Slip39_Single_Extendable"] = 3] = "Slip39_Single_Extendable";
1304
+ Enum_BackupType[Enum_BackupType["Slip39_Basic_Extendable"] = 4] = "Slip39_Basic_Extendable";
1305
+ Enum_BackupType[Enum_BackupType["Slip39_Advanced_Extendable"] = 5] = "Slip39_Advanced_Extendable";
685
1306
  })(exports.Enum_BackupType || (exports.Enum_BackupType = {}));
686
1307
  exports.Enum_SafetyCheckLevel = void 0;
687
1308
  (function (Enum_SafetyCheckLevel) {
@@ -867,6 +1488,86 @@ exports.CommandFlags = void 0;
867
1488
  CommandFlags[CommandFlags["Default"] = 0] = "Default";
868
1489
  CommandFlags[CommandFlags["Factory_Only"] = 1] = "Factory_Only";
869
1490
  })(exports.CommandFlags || (exports.CommandFlags = {}));
1491
+ exports.MoneroNetworkType = void 0;
1492
+ (function (MoneroNetworkType) {
1493
+ MoneroNetworkType[MoneroNetworkType["MAINNET"] = 0] = "MAINNET";
1494
+ MoneroNetworkType[MoneroNetworkType["TESTNET"] = 1] = "TESTNET";
1495
+ MoneroNetworkType[MoneroNetworkType["STAGENET"] = 2] = "STAGENET";
1496
+ MoneroNetworkType[MoneroNetworkType["FAKECHAIN"] = 3] = "FAKECHAIN";
1497
+ })(exports.MoneroNetworkType || (exports.MoneroNetworkType = {}));
1498
+ exports.TxDetailsDisplayType = void 0;
1499
+ (function (TxDetailsDisplayType) {
1500
+ TxDetailsDisplayType[TxDetailsDisplayType["DISPLAY_TYPE_INFO"] = 0] = "DISPLAY_TYPE_INFO";
1501
+ TxDetailsDisplayType[TxDetailsDisplayType["DISPLAY_TYPE_SIGN"] = 1] = "DISPLAY_TYPE_SIGN";
1502
+ })(exports.TxDetailsDisplayType || (exports.TxDetailsDisplayType = {}));
1503
+ exports.DevRebootType = void 0;
1504
+ (function (DevRebootType) {
1505
+ DevRebootType[DevRebootType["Normal"] = 0] = "Normal";
1506
+ DevRebootType[DevRebootType["Boardloader"] = 1] = "Boardloader";
1507
+ DevRebootType[DevRebootType["Bootloader"] = 2] = "Bootloader";
1508
+ })(exports.DevRebootType || (exports.DevRebootType = {}));
1509
+ exports.DeviceRebootType = void 0;
1510
+ (function (DeviceRebootType) {
1511
+ DeviceRebootType[DeviceRebootType["Normal"] = 0] = "Normal";
1512
+ DeviceRebootType[DeviceRebootType["Romloader"] = 1] = "Romloader";
1513
+ DeviceRebootType[DeviceRebootType["Bootloader"] = 2] = "Bootloader";
1514
+ })(exports.DeviceRebootType || (exports.DeviceRebootType = {}));
1515
+ exports.DeviceType = void 0;
1516
+ (function (DeviceType) {
1517
+ DeviceType[DeviceType["CLASSIC1"] = 0] = "CLASSIC1";
1518
+ DeviceType[DeviceType["CLASSIC1S"] = 1] = "CLASSIC1S";
1519
+ DeviceType[DeviceType["MINI"] = 2] = "MINI";
1520
+ DeviceType[DeviceType["TOUCH"] = 3] = "TOUCH";
1521
+ DeviceType[DeviceType["PRO"] = 5] = "PRO";
1522
+ DeviceType[DeviceType["CLASSIC1S_PURE"] = 6] = "CLASSIC1S_PURE";
1523
+ })(exports.DeviceType || (exports.DeviceType = {}));
1524
+ exports.DevSeType = void 0;
1525
+ (function (DevSeType) {
1526
+ DevSeType[DevSeType["THD89"] = 0] = "THD89";
1527
+ DevSeType[DevSeType["SE608A"] = 1] = "SE608A";
1528
+ })(exports.DevSeType || (exports.DevSeType = {}));
1529
+ exports.DevSEState = void 0;
1530
+ (function (DevSEState) {
1531
+ DevSEState[DevSEState["BOOT"] = 0] = "BOOT";
1532
+ DevSEState[DevSEState["APP_FACTORY"] = 51] = "APP_FACTORY";
1533
+ DevSEState[DevSEState["APP"] = 85] = "APP";
1534
+ })(exports.DevSEState || (exports.DevSEState = {}));
1535
+ exports.DevFirmwareTargetType = void 0;
1536
+ (function (DevFirmwareTargetType) {
1537
+ DevFirmwareTargetType[DevFirmwareTargetType["TARGET_INVALID"] = 0] = "TARGET_INVALID";
1538
+ DevFirmwareTargetType[DevFirmwareTargetType["TARGET_ROMLOADER"] = 1] = "TARGET_ROMLOADER";
1539
+ DevFirmwareTargetType[DevFirmwareTargetType["TARGET_BOOTLOADER"] = 2] = "TARGET_BOOTLOADER";
1540
+ DevFirmwareTargetType[DevFirmwareTargetType["TARGET_APPLICATION_P1"] = 3] = "TARGET_APPLICATION_P1";
1541
+ DevFirmwareTargetType[DevFirmwareTargetType["TARGET_APPLICATION_P2"] = 4] = "TARGET_APPLICATION_P2";
1542
+ DevFirmwareTargetType[DevFirmwareTargetType["TARGET_COPROCESSOR"] = 5] = "TARGET_COPROCESSOR";
1543
+ DevFirmwareTargetType[DevFirmwareTargetType["TARGET_SE01"] = 6] = "TARGET_SE01";
1544
+ DevFirmwareTargetType[DevFirmwareTargetType["TARGET_SE02"] = 7] = "TARGET_SE02";
1545
+ DevFirmwareTargetType[DevFirmwareTargetType["TARGET_SE03"] = 8] = "TARGET_SE03";
1546
+ DevFirmwareTargetType[DevFirmwareTargetType["TARGET_SE04"] = 9] = "TARGET_SE04";
1547
+ DevFirmwareTargetType[DevFirmwareTargetType["TARGET_RESOURCE"] = 10] = "TARGET_RESOURCE";
1548
+ })(exports.DevFirmwareTargetType || (exports.DevFirmwareTargetType = {}));
1549
+ exports.DeviceFirmwareTargetType = void 0;
1550
+ (function (DeviceFirmwareTargetType) {
1551
+ DeviceFirmwareTargetType[DeviceFirmwareTargetType["TARGET_INVALID"] = 0] = "TARGET_INVALID";
1552
+ DeviceFirmwareTargetType[DeviceFirmwareTargetType["TARGET_ROMLOADER"] = 1] = "TARGET_ROMLOADER";
1553
+ DeviceFirmwareTargetType[DeviceFirmwareTargetType["TARGET_BOOTLOADER"] = 2] = "TARGET_BOOTLOADER";
1554
+ DeviceFirmwareTargetType[DeviceFirmwareTargetType["TARGET_APPLICATION_P1"] = 3] = "TARGET_APPLICATION_P1";
1555
+ DeviceFirmwareTargetType[DeviceFirmwareTargetType["TARGET_APPLICATION_P2"] = 4] = "TARGET_APPLICATION_P2";
1556
+ DeviceFirmwareTargetType[DeviceFirmwareTargetType["TARGET_COPROCESSOR"] = 5] = "TARGET_COPROCESSOR";
1557
+ DeviceFirmwareTargetType[DeviceFirmwareTargetType["TARGET_SE01"] = 6] = "TARGET_SE01";
1558
+ DeviceFirmwareTargetType[DeviceFirmwareTargetType["TARGET_SE02"] = 7] = "TARGET_SE02";
1559
+ DeviceFirmwareTargetType[DeviceFirmwareTargetType["TARGET_SE03"] = 8] = "TARGET_SE03";
1560
+ DeviceFirmwareTargetType[DeviceFirmwareTargetType["TARGET_SE04"] = 9] = "TARGET_SE04";
1561
+ DeviceFirmwareTargetType[DeviceFirmwareTargetType["TARGET_RESOURCE"] = 10] = "TARGET_RESOURCE";
1562
+ })(exports.DeviceFirmwareTargetType || (exports.DeviceFirmwareTargetType = {}));
1563
+ exports.OnboardingStep = void 0;
1564
+ (function (OnboardingStep) {
1565
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_UNKNOWN"] = 0] = "ONBOARDING_STEP_UNKNOWN";
1566
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_DEVICE_VERIFICATION"] = 1] = "ONBOARDING_STEP_DEVICE_VERIFICATION";
1567
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_PERSONALIZATION"] = 2] = "ONBOARDING_STEP_PERSONALIZATION";
1568
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_SETUP"] = 3] = "ONBOARDING_STEP_SETUP";
1569
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_FIRMWARE"] = 4] = "ONBOARDING_STEP_FIRMWARE";
1570
+ })(exports.OnboardingStep || (exports.OnboardingStep = {}));
870
1571
 
871
1572
  var messages = /*#__PURE__*/Object.freeze({
872
1573
  __proto__: null,
@@ -929,28 +1630,70 @@ var messages = /*#__PURE__*/Object.freeze({
929
1630
  get TonSignDataType () { return exports.TonSignDataType; },
930
1631
  get TronResourceCode () { return exports.TronResourceCode; },
931
1632
  get TronMessageType () { return exports.TronMessageType; },
932
- get CommandFlags () { return exports.CommandFlags; }
1633
+ get CommandFlags () { return exports.CommandFlags; },
1634
+ get MoneroNetworkType () { return exports.MoneroNetworkType; },
1635
+ get TxDetailsDisplayType () { return exports.TxDetailsDisplayType; },
1636
+ get DevRebootType () { return exports.DevRebootType; },
1637
+ get DeviceRebootType () { return exports.DeviceRebootType; },
1638
+ get DeviceType () { return exports.DeviceType; },
1639
+ get DevSeType () { return exports.DevSeType; },
1640
+ get DevSEState () { return exports.DevSEState; },
1641
+ get DevFirmwareTargetType () { return exports.DevFirmwareTargetType; },
1642
+ get DeviceFirmwareTargetType () { return exports.DeviceFirmwareTargetType; },
1643
+ get OnboardingStep () { return exports.OnboardingStep; }
933
1644
  });
934
1645
 
935
- const LogBlockCommand = new Set(['PassphraseAck', 'PinMatrixAck']);
936
-
937
- protobuf__namespace.util.Long = Long__namespace;
1646
+ protobuf__namespace.util.Long = Long__default["default"];
938
1647
  protobuf__namespace.configure();
939
1648
  var index = {
940
1649
  check,
941
- buildOne,
942
- buildBuffers,
943
- buildEncodeBuffers,
944
- receiveOne,
945
1650
  parseConfigure,
946
- decodeProtocol,
1651
+ protocolV2: protocolV2Codec,
1652
+ ProtocolV1,
1653
+ ProtocolV2,
1654
+ PROTOCOL_V2_SYS_MESSAGE_THRESHOLD,
1655
+ ProtocolV2FrameAssembler,
1656
+ ProtocolV2Session,
1657
+ bytesToHex,
1658
+ concatUint8Arrays,
1659
+ createMessageFromName,
1660
+ createMessageFromType,
1661
+ encodeProtobuf: encode,
1662
+ decodeProtobuf: decode,
1663
+ getErrorMessage,
1664
+ hexToBytes,
1665
+ probeProtocolV2,
1666
+ withProtocolTimeout,
947
1667
  };
948
1668
 
949
- exports.BUFFER_SIZE = BUFFER_SIZE;
950
- exports.COMMON_HEADER_SIZE = COMMON_HEADER_SIZE;
951
- exports.HEADER_SIZE = HEADER_SIZE;
952
1669
  exports.LogBlockCommand = LogBlockCommand;
953
- exports.MESSAGE_HEADER_BYTE = MESSAGE_HEADER_BYTE;
954
- exports.MESSAGE_TOP_CHAR = MESSAGE_TOP_CHAR;
955
1670
  exports.Messages = messages;
1671
+ exports.PROTOCOL_V1_CHUNK_PAYLOAD_SIZE = PROTOCOL_V1_CHUNK_PAYLOAD_SIZE;
1672
+ exports.PROTOCOL_V1_ENVELOPE_HEADER_SIZE = PROTOCOL_V1_ENVELOPE_HEADER_SIZE;
1673
+ exports.PROTOCOL_V1_HEADER_BYTE = PROTOCOL_V1_HEADER_BYTE;
1674
+ exports.PROTOCOL_V1_MESSAGE_HEADER_SIZE = PROTOCOL_V1_MESSAGE_HEADER_SIZE;
1675
+ exports.PROTOCOL_V1_REPORT_ID = PROTOCOL_V1_REPORT_ID;
1676
+ exports.PROTOCOL_V1_USB_PACKET_SIZE = PROTOCOL_V1_USB_PACKET_SIZE;
1677
+ exports.PROTOCOL_V2_BLE_FILE_CHUNK_SIZE = PROTOCOL_V2_BLE_FILE_CHUNK_SIZE;
1678
+ exports.PROTOCOL_V2_CHANNEL_BLE_UART = PROTOCOL_V2_CHANNEL_BLE_UART;
1679
+ exports.PROTOCOL_V2_CHANNEL_SOCKET = PROTOCOL_V2_CHANNEL_SOCKET;
1680
+ exports.PROTOCOL_V2_CHANNEL_USB = PROTOCOL_V2_CHANNEL_USB;
1681
+ exports.PROTOCOL_V2_FILE_CHUNK_SIZE = PROTOCOL_V2_FILE_CHUNK_SIZE;
1682
+ exports.PROTOCOL_V2_FRAME_MAX_BYTES = PROTOCOL_V2_FRAME_MAX_BYTES;
1683
+ exports.PROTOCOL_V2_PACKET_SRC_COMMAND = PROTOCOL_V2_PACKET_SRC_COMMAND;
1684
+ exports.PROTOCOL_V2_SYS_MESSAGE_THRESHOLD = PROTOCOL_V2_SYS_MESSAGE_THRESHOLD;
1685
+ exports.PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE = PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
1686
+ exports.PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS = PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS;
1687
+ exports.ProtocolV1 = ProtocolV1;
1688
+ exports.ProtocolV2 = ProtocolV2;
1689
+ exports.ProtocolV2FrameAssembler = ProtocolV2FrameAssembler;
1690
+ exports.ProtocolV2Session = ProtocolV2Session;
1691
+ exports.bytesToHex = bytesToHex;
1692
+ exports.concatUint8Arrays = concatUint8Arrays;
956
1693
  exports["default"] = index;
1694
+ exports.getErrorMessage = getErrorMessage;
1695
+ exports.hexToBytes = hexToBytes;
1696
+ exports.probeProtocolV2 = probeProtocolV2;
1697
+ exports.protocolV1 = index$1;
1698
+ exports.protocolV2 = protocolV2Codec;
1699
+ exports.withProtocolTimeout = withProtocolTimeout;