@onekeyfe/hd-transport 1.2.0-alpha.8 → 1.2.0-alpha.80

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 (70) hide show
  1. package/__tests__/messages.test.js +220 -0
  2. package/__tests__/protocol-v2-ble-frame-writer.test.js +119 -0
  3. package/__tests__/protocol-v2-link-manager.test.js +437 -0
  4. package/__tests__/protocol-v2-usb-transport-base.test.js +330 -0
  5. package/__tests__/protocol-v2.test.js +535 -53
  6. package/__tests__/transport-log.test.js +79 -0
  7. package/dist/constants.d.ts +5 -1
  8. package/dist/constants.d.ts.map +1 -1
  9. package/dist/index.d.ts +822 -199
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +853 -229
  12. package/dist/protocols/index.d.ts +14 -5
  13. package/dist/protocols/index.d.ts.map +1 -1
  14. package/dist/protocols/v2/ble-frame-writer.d.ts +15 -0
  15. package/dist/protocols/v2/ble-frame-writer.d.ts.map +1 -0
  16. package/dist/protocols/v2/constants.d.ts +1 -0
  17. package/dist/protocols/v2/constants.d.ts.map +1 -1
  18. package/dist/protocols/v2/decode.d.ts +13 -2
  19. package/dist/protocols/v2/decode.d.ts.map +1 -1
  20. package/dist/protocols/v2/encode.d.ts +2 -3
  21. package/dist/protocols/v2/encode.d.ts.map +1 -1
  22. package/dist/protocols/v2/errors.d.ts +8 -0
  23. package/dist/protocols/v2/errors.d.ts.map +1 -0
  24. package/dist/protocols/v2/frame-assembler.d.ts.map +1 -1
  25. package/dist/protocols/v2/index.d.ts +2 -1
  26. package/dist/protocols/v2/index.d.ts.map +1 -1
  27. package/dist/protocols/v2/link-manager.d.ts +39 -0
  28. package/dist/protocols/v2/link-manager.d.ts.map +1 -0
  29. package/dist/protocols/v2/sequence-cursor.d.ts +5 -0
  30. package/dist/protocols/v2/sequence-cursor.d.ts.map +1 -0
  31. package/dist/protocols/v2/session.d.ts +24 -6
  32. package/dist/protocols/v2/session.d.ts.map +1 -1
  33. package/dist/protocols/v2/usb-transport-base.d.ts +32 -0
  34. package/dist/protocols/v2/usb-transport-base.d.ts.map +1 -0
  35. package/dist/serialization/protobuf/decode.d.ts.map +1 -1
  36. package/dist/serialization/protobuf/encode.d.ts.map +1 -1
  37. package/dist/types/messages.d.ts +386 -110
  38. package/dist/types/messages.d.ts.map +1 -1
  39. package/dist/types/transport.d.ts +21 -4
  40. package/dist/types/transport.d.ts.map +1 -1
  41. package/dist/utils/transportLog.d.ts +9 -0
  42. package/dist/utils/transportLog.d.ts.map +1 -0
  43. package/messages-protocol-v2.json +1138 -441
  44. package/package.json +3 -3
  45. package/scripts/protobuf-build.sh +86 -208
  46. package/scripts/protobuf-patches/index.js +1 -0
  47. package/scripts/protobuf-types.js +19 -1
  48. package/src/constants.ts +34 -14
  49. package/src/index.ts +13 -1
  50. package/src/protocols/index.ts +39 -40
  51. package/src/protocols/v2/ble-frame-writer.ts +77 -0
  52. package/src/protocols/v2/constants.ts +1 -0
  53. package/src/protocols/v2/crc8.ts +1 -1
  54. package/src/protocols/v2/decode.ts +71 -37
  55. package/src/protocols/v2/encode.ts +2 -28
  56. package/src/protocols/v2/errors.ts +25 -0
  57. package/src/protocols/v2/frame-assembler.ts +6 -4
  58. package/src/protocols/v2/index.ts +2 -1
  59. package/src/protocols/v2/link-manager.ts +209 -0
  60. package/src/protocols/v2/sequence-cursor.ts +10 -0
  61. package/src/protocols/v2/session.ts +187 -200
  62. package/src/protocols/v2/usb-transport-base.ts +213 -0
  63. package/src/serialization/protobuf/decode.ts +4 -1
  64. package/src/serialization/protobuf/encode.ts +5 -1
  65. package/src/types/messages.ts +471 -142
  66. package/src/types/transport.ts +29 -4
  67. package/src/utils/transportLog.ts +102 -0
  68. package/dist/protocols/v2/debug.d.ts +0 -13
  69. package/dist/protocols/v2/debug.d.ts.map +0 -1
  70. package/src/protocols/v2/debug.ts +0 -26
package/dist/index.js CHANGED
@@ -140,7 +140,7 @@ function messageToJSON(Message, fields) {
140
140
  res[key] = field.resolvedType.valuesById[value];
141
141
  }
142
142
  else if (field.resolvedType.fields) {
143
- res[key] = messageToJSON(value, field.resolvedType.fields);
143
+ res[key] = value == null ? null : messageToJSON(value, field.resolvedType.fields);
144
144
  }
145
145
  else {
146
146
  throw new Error(`case not handled: ${key}`);
@@ -200,7 +200,10 @@ function patch(Message, payload) {
200
200
  }
201
201
  if (field.repeated) {
202
202
  const RefMessage = Message.lookupTypeOrEnum(field.type);
203
- patched[key] = value.map((v) => patch(RefMessage, v));
203
+ patched[key] =
204
+ RefMessage instanceof protobuf.Enum
205
+ ? value.map((v) => transform(field.type, v))
206
+ : value.map((v) => patch(RefMessage, v));
204
207
  }
205
208
  else if (typeof value === 'object' && value !== null) {
206
209
  const RefMessage = Message.lookupType(field.type);
@@ -267,14 +270,18 @@ const PROTOCOL_V1_CHUNK_PAYLOAD_SIZE = 63;
267
270
  const PROTOCOL_V1_USB_PACKET_SIZE = PROTOCOL_V1_CHUNK_PAYLOAD_SIZE + 1;
268
271
  const PROTOCOL_V1_MESSAGE_HEADER_SIZE = 2 + 4;
269
272
  const PROTOCOL_V1_ENVELOPE_HEADER_SIZE = 1 + 1 + PROTOCOL_V1_MESSAGE_HEADER_SIZE;
270
- const PROTOCOL_V2_FRAME_MAX_BYTES = 4608;
273
+ const PROTOCOL_V2_FRAME_MAX_BYTES = 4200;
271
274
  const PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE = 4000;
272
275
  const PROTOCOL_V2_BLE_FILE_CHUNK_SIZE = 1800;
276
+ const PROTOCOL_V2_BLE_FIRMWARE_FILE_CHUNK_SIZE = 1960;
277
+ const PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE = 900;
278
+ const PROTOCOL_V2_BLE_FRAME_MAX_BYTES = 2048;
273
279
  const PROTOCOL_V2_FILE_CHUNK_SIZE = PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
274
280
  const PROTOCOL_V2_CHANNEL_USB = 0;
275
281
  const PROTOCOL_V2_CHANNEL_BLE_UART = 1;
276
282
  const PROTOCOL_V2_CHANNEL_SOCKET = 2;
277
283
  const PROTOCOL_V2_PACKET_SRC_COMMAND = 0;
284
+ const PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS = 5 * 60 * 1000;
278
285
 
279
286
  function encodeEnvelope(data, options) {
280
287
  const { addTrezorHeaders, chunked, messageTypeId } = options;
@@ -381,6 +388,7 @@ const PROTO_HEAD_CRC_SIZE = 8;
381
388
  const CRC8_INIT = 0x30;
382
389
  const PACKET_SIZE = 4096;
383
390
  const PROTO_DATA_TYPE_PACKET = 0;
391
+ const PROTO_DATA_TYPE_ACK = 1;
384
392
 
385
393
  const CRC8_TABLE = new Uint8Array([
386
394
  0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83, 0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41,
@@ -408,16 +416,11 @@ function crc8(data, len) {
408
416
  return crc;
409
417
  }
410
418
 
411
- function logProtocolV2Debug(options, stage, details) {
412
- var _a, _b, _c;
413
- (_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));
414
- }
415
-
416
419
  const PROTO_SEQ_DEFAULT = 1;
417
420
  function nextProtoSeq(current) {
418
421
  return current >= 255 ? 1 : current + 1;
419
422
  }
420
- function encodeFrame(payload, packetSrc, router, debugOptions, seq) {
423
+ function encodeFrame(payload, packetSrc, router, seq) {
421
424
  const resolvedPacketSrc = packetSrc !== null && packetSrc !== void 0 ? packetSrc : 0;
422
425
  const resolvedRouter = router !== null && router !== void 0 ? router : 0;
423
426
  const resolvedSeq = seq !== null && seq !== void 0 ? seq : PROTO_SEQ_DEFAULT;
@@ -427,7 +430,7 @@ function encodeFrame(payload, packetSrc, router, debugOptions, seq) {
427
430
  const payloadLen = payload ? payload.length : 0;
428
431
  const frameLen = payloadLen + PROTO_HEAD_CRC_SIZE;
429
432
  if (frameLen > PROTOCOL_V2_FRAME_MAX_BYTES) {
430
- throw new Error(`Protocol V2 frame too large: ${frameLen}`);
433
+ throw new Error(`Protocol V2 frame too large: ${frameLen} > ${PROTOCOL_V2_FRAME_MAX_BYTES}`);
431
434
  }
432
435
  const frame = new Uint8Array(frameLen);
433
436
  frame[0] = PROTO_HEAD_SOF;
@@ -442,27 +445,17 @@ function encodeFrame(payload, packetSrc, router, debugOptions, seq) {
442
445
  frame.set(payload, 7);
443
446
  }
444
447
  frame[frameLen - 1] = crc8(frame, frameLen - 1);
445
- logProtocolV2Debug(debugOptions, 'encode raw frame', {
446
- frameLen,
447
- payloadLen,
448
- packetSrc: resolvedPacketSrc,
449
- router: frame[4],
450
- attr: frame[5],
451
- seq: frame[6],
452
- headerCrc: frame[3],
453
- frameCrc: frame[frameLen - 1],
454
- });
455
448
  return frame;
456
449
  }
457
- function encodeProtobufFrame(messageTypeId, pbPayload, packetSrc, router, debugOptions, seq) {
450
+ function encodeProtobufFrame(messageTypeId, pbPayload, packetSrc, router, seq) {
458
451
  const payload = new Uint8Array(2 + pbPayload.length);
459
452
  payload[0] = messageTypeId % 256;
460
453
  payload[1] = Math.floor(messageTypeId / 256) % 256;
461
454
  payload.set(pbPayload, 2);
462
- return encodeFrame(payload, packetSrc, router, Object.assign(Object.assign({}, debugOptions), { messageTypeId, pbPayloadLength: pbPayload.length }), seq);
455
+ return encodeFrame(payload, packetSrc, router, seq);
463
456
  }
464
457
 
465
- function decodeFrame(data, debugOptions) {
458
+ function inspectFrameHeader(data) {
466
459
  if (data.length < PROTO_HEAD_CRC_SIZE) {
467
460
  throw new Error(`Protocol V2 frame too short: ${data.length} bytes`);
468
461
  }
@@ -470,8 +463,8 @@ function decodeFrame(data, debugOptions) {
470
463
  throw new Error(`Invalid SOF byte: expected 0x5A, got 0x${data[0].toString(16).padStart(2, '0')}`);
471
464
  }
472
465
  const frameLen = data[1] + data[2] * 256;
473
- if (data.length < frameLen) {
474
- throw new Error(`Frame truncated: expected ${frameLen} bytes, got ${data.length}`);
466
+ if (data.length !== frameLen) {
467
+ throw new Error(`Protocol V2 frame length mismatch: expected ${frameLen} bytes, got ${data.length}`);
475
468
  }
476
469
  const expectedHeaderCrc = crc8(data, 3);
477
470
  if (data[3] !== expectedHeaderCrc) {
@@ -485,29 +478,54 @@ function decodeFrame(data, debugOptions) {
485
478
  .toString(16)
486
479
  .padStart(2, '0')}, got 0x${data[frameLen - 1].toString(16).padStart(2, '0')}`);
487
480
  }
481
+ const dataType = data[5] & 0x03;
482
+ const packetSrc = (data[5] >> 2) & 0x0f;
488
483
  const seq = data[6];
484
+ if (seq === 0) {
485
+ throw new Error('Invalid Protocol V2 sequence: 0 is reserved');
486
+ }
487
+ return {
488
+ frameLen,
489
+ router: data[4],
490
+ packetSrc,
491
+ dataType,
492
+ seq,
493
+ };
494
+ }
495
+ function isAckFrame(data) {
496
+ if (data.length < 6 || (data[5] & 0x03) !== PROTO_DATA_TYPE_ACK) {
497
+ return false;
498
+ }
499
+ const header = inspectFrameHeader(data);
500
+ if (header.frameLen !== PROTO_HEAD_CRC_SIZE) {
501
+ throw new Error(`Invalid Protocol V2 ACK frame length: ${header.frameLen}`);
502
+ }
503
+ return true;
504
+ }
505
+ function decodeFrame(data) {
506
+ const { frameLen, router, packetSrc, dataType, seq } = inspectFrameHeader(data);
507
+ if (dataType !== PROTO_DATA_TYPE_PACKET) {
508
+ throw new Error(`Invalid Protocol V2 data type: expected packet, got ${dataType}`);
509
+ }
489
510
  const payloadData = data.slice(7, frameLen - 1);
490
511
  if (payloadData.length < 2) {
491
512
  throw new Error(`Protocol V2 payload too short (need >=2 bytes for messageTypeId)`);
492
513
  }
493
514
  const messageTypeId = payloadData[0] + payloadData[1] * 256;
494
515
  const pbPayload = payloadData.slice(2);
495
- logProtocolV2Debug(debugOptions, 'decode raw frame', {
496
- frameLen,
497
- dataLength: data.length,
498
- router: data[4],
499
- attr: data[5],
500
- seq,
501
- headerCrc: data[3],
502
- expectedHeaderCrc,
503
- frameCrc: data[frameLen - 1],
504
- expectedFrameCrc,
505
- messageTypeId,
506
- pbPayloadLength: pbPayload.length,
507
- });
508
- return { messageTypeId, pbPayload, seq };
516
+ return { messageTypeId, pbPayload, seq, router, packetSrc, dataType };
509
517
  }
510
518
 
519
+ class ProtocolV2LinkError extends Error {
520
+ constructor(code, message, cause) {
521
+ super(message);
522
+ this.name = 'ProtocolV2LinkError';
523
+ this.code = code;
524
+ this.cause = cause;
525
+ }
526
+ }
527
+ const isProtocolV2LinkError = (error) => error instanceof ProtocolV2LinkError;
528
+
511
529
  function concatUint8Arrays(arrays) {
512
530
  const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
513
531
  const result = new Uint8Array(totalLength);
@@ -551,23 +569,23 @@ class ProtocolV2FrameAssembler {
551
569
  return undefined;
552
570
  if (this.buffer[0] !== PROTO_HEAD_SOF) {
553
571
  this.reset();
554
- throw new Error('Invalid Protocol V2 SOF');
572
+ throw new ProtocolV2LinkError('frame', 'Invalid Protocol V2 SOF');
555
573
  }
556
574
  const expectedLen = this.buffer[1] + this.buffer[2] * 256;
557
575
  if (expectedLen < PROTO_HEAD_CRC_SIZE) {
558
576
  this.reset();
559
- throw new Error(`Protocol V2 frame length too small: ${expectedLen}`);
577
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame length too small: ${expectedLen}`);
560
578
  }
561
579
  if (expectedLen > this.maxFrameBytes) {
562
580
  this.reset();
563
- throw new Error(`Protocol V2 frame too large: ${expectedLen}`);
581
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame too large: ${expectedLen}`);
564
582
  }
565
583
  if (this.buffer.length < PROTO_PRE_HEAD_SIZE)
566
584
  return undefined;
567
585
  const expectedHeaderCrc = crc8(this.buffer, 3);
568
586
  if (this.buffer[3] !== expectedHeaderCrc) {
569
587
  this.reset();
570
- throw new Error(`Protocol V2 header CRC mismatch: expected 0x${expectedHeaderCrc
588
+ throw new ProtocolV2LinkError('frame', `Protocol V2 header CRC mismatch: expected 0x${expectedHeaderCrc
571
589
  .toString(16)
572
590
  .padStart(2, '0')}`);
573
591
  }
@@ -579,6 +597,51 @@ class ProtocolV2FrameAssembler {
579
597
  }
580
598
  }
581
599
 
600
+ const defaultWait = (timeoutMs) => new Promise(resolve => {
601
+ setTimeout(resolve, timeoutMs);
602
+ });
603
+ function writeProtocolV2BleFrame({ frame, packetCapacity, writePacket, assertActive, signal, abortMessage = 'Protocol V2 BLE write aborted', initialDelayMs = 0, burstSize, burstPauseMs = 0, flushDelayMs = 0, wait = defaultWait, }) {
604
+ return __awaiter(this, void 0, void 0, function* () {
605
+ if (!Number.isInteger(packetCapacity) || packetCapacity <= 0) {
606
+ throw new Error('Protocol V2 BLE packet capacity must be a positive integer');
607
+ }
608
+ if (burstSize !== undefined && (!Number.isInteger(burstSize) || burstSize <= 0)) {
609
+ throw new Error('Protocol V2 BLE burst size must be a positive integer');
610
+ }
611
+ const assertWritable = () => {
612
+ assertActive === null || assertActive === void 0 ? void 0 : assertActive();
613
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
614
+ throw new Error(abortMessage);
615
+ }
616
+ };
617
+ if (frame.length > 0 && initialDelayMs > 0) {
618
+ assertWritable();
619
+ yield wait(initialDelayMs);
620
+ assertWritable();
621
+ }
622
+ let packetsWritten = 0;
623
+ for (let offset = 0; offset < frame.length; offset += packetCapacity) {
624
+ assertWritable();
625
+ const packet = frame.slice(offset, offset + packetCapacity);
626
+ yield writePacket(packet, packetsWritten);
627
+ packetsWritten += 1;
628
+ assertWritable();
629
+ const hasMorePackets = offset + packetCapacity < frame.length;
630
+ if (hasMorePackets &&
631
+ burstSize !== undefined &&
632
+ packetsWritten % burstSize === 0 &&
633
+ burstPauseMs > 0) {
634
+ yield wait(burstPauseMs);
635
+ assertWritable();
636
+ }
637
+ }
638
+ if (burstSize !== undefined && packetsWritten > burstSize && flushDelayMs > 0) {
639
+ yield wait(flushDelayMs);
640
+ assertWritable();
641
+ }
642
+ });
643
+ }
644
+
582
645
  var protocolV2Codec = /*#__PURE__*/Object.freeze({
583
646
  __proto__: null,
584
647
  PROTO_HEAD_SOF: PROTO_HEAD_SOF,
@@ -587,15 +650,20 @@ var protocolV2Codec = /*#__PURE__*/Object.freeze({
587
650
  CRC8_INIT: CRC8_INIT,
588
651
  PACKET_SIZE: PACKET_SIZE,
589
652
  PROTO_DATA_TYPE_PACKET: PROTO_DATA_TYPE_PACKET,
653
+ PROTO_DATA_TYPE_ACK: PROTO_DATA_TYPE_ACK,
590
654
  CRC8_TABLE: CRC8_TABLE,
591
655
  crc8: crc8,
592
- logProtocolV2Debug: logProtocolV2Debug,
593
656
  nextProtoSeq: nextProtoSeq,
594
657
  encodeFrame: encodeFrame,
595
658
  encodeProtobufFrame: encodeProtobufFrame,
659
+ inspectFrameHeader: inspectFrameHeader,
660
+ isAckFrame: isAckFrame,
596
661
  decodeFrame: decodeFrame,
662
+ ProtocolV2LinkError: ProtocolV2LinkError,
663
+ isProtocolV2LinkError: isProtocolV2LinkError,
597
664
  concatUint8Arrays: concatUint8Arrays,
598
- ProtocolV2FrameAssembler: ProtocolV2FrameAssembler
665
+ ProtocolV2FrameAssembler: ProtocolV2FrameAssembler,
666
+ writeProtocolV2BleFrame: writeProtocolV2BleFrame
599
667
  });
600
668
 
601
669
  const PROTOCOL_V2_SYS_MESSAGE_THRESHOLD = 60000;
@@ -643,46 +711,46 @@ const ProtocolV1 = {
643
711
  decodeMessage: decodeMessage,
644
712
  };
645
713
  const ProtocolV2 = {
714
+ isAckFrame,
715
+ inspectFrameHeader,
716
+ inspectFrame(schemas, frame) {
717
+ const { messageTypeId, pbPayload, seq, router, packetSrc, dataType } = decodeFrame(frame);
718
+ const { messageName } = createProtocolV2MessageFromType(messageTypeId, schemas);
719
+ return {
720
+ messageName,
721
+ messageTypeId,
722
+ pbPayload,
723
+ seq,
724
+ router,
725
+ packetSrc,
726
+ dataType,
727
+ type: messageName,
728
+ };
729
+ },
646
730
  encodeFrame(schemas, name, data, options = {}) {
647
- var _a, _b, _c, _d, _e, _f, _g;
648
731
  const encodeMessages = resolveProtocolV2EncodeSchema(name, schemas);
649
732
  const { Message, messageTypeId } = createMessageFromName(encodeMessages, name);
650
733
  const pbBuffer = encode(Message, data);
651
734
  pbBuffer.reset();
652
735
  const rawPbBuffer = pbBuffer.toBuffer();
653
736
  const pbBytes = new Uint8Array(rawPbBuffer);
654
- (_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`, {
655
- context: (_d = options.context) !== null && _d !== void 0 ? _d : `encode:${name}`,
656
- messageName: name,
657
- messageTypeId,
658
- pbPayloadLength: pbBytes.length,
659
- packetSrc: (_e = options.packetSrc) !== null && _e !== void 0 ? _e : 0,
660
- router: (_f = options.router) !== null && _f !== void 0 ? _f : 0,
661
- });
662
- return encodeProtobufFrame(messageTypeId, pbBytes, options.packetSrc, options.router, {
663
- logger: options.logger,
664
- logPrefix: options.logPrefix,
665
- context: (_g = options.context) !== null && _g !== void 0 ? _g : `encode:${name}`,
666
- messageName: name,
667
- }, options.seq);
737
+ return encodeProtobufFrame(messageTypeId, pbBytes, options.packetSrc, options.router, options.seq);
668
738
  },
669
- decodeFrame(schemas, frame, options = {}) {
670
- var _a, _b, _c, _d, _e;
671
- const { messageTypeId, pbPayload, seq } = decodeFrame(frame, {
672
- logger: options.logger,
673
- logPrefix: options.logPrefix,
674
- context: (_a = options.context) !== null && _a !== void 0 ? _a : 'decode',
675
- });
676
- const { Message, messageName } = createProtocolV2MessageFromType(messageTypeId, schemas);
739
+ decodeFrame(schemas, frame) {
740
+ const { messageTypeId, pbPayload, seq, messageName } = this.inspectFrame(schemas, frame);
741
+ const { Message } = createProtocolV2MessageFromType(messageTypeId, schemas);
677
742
  const rxByteBuffer = ByteBuffer__default["default"].wrap(Buffer.from(pbPayload));
678
- const message = decode(Message, rxByteBuffer);
679
- (_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`, {
680
- context: (_e = options.context) !== null && _e !== void 0 ? _e : `decode:${messageName}`,
681
- messageName,
682
- messageTypeId,
683
- pbPayloadLength: pbPayload.length,
684
- seq,
685
- });
743
+ let message;
744
+ try {
745
+ message = decode(Message, rxByteBuffer);
746
+ }
747
+ catch (cause) {
748
+ const error = new Error(`Protocol V2 protobuf decode failed for "${messageName}" ` +
749
+ `(${messageTypeId}, ${pbPayload.length}-byte payload); ` +
750
+ 'the payload is malformed or incompatible with the active SDK schema.');
751
+ error.cause = cause;
752
+ throw error;
753
+ }
686
754
  return {
687
755
  message,
688
756
  messageName,
@@ -705,6 +773,16 @@ var index$1 = /*#__PURE__*/Object.freeze({
705
773
  decodeMessage: decodeMessage
706
774
  });
707
775
 
776
+ class ProtocolV2SequenceCursor {
777
+ constructor() {
778
+ this.current = 0;
779
+ }
780
+ next() {
781
+ this.current = nextProtoSeq(this.current);
782
+ return this.current;
783
+ }
784
+ }
785
+
708
786
  const ERROR = 'Wrong result type.';
709
787
  function info(res) {
710
788
  if (typeof res !== 'object' || res == null) {
@@ -821,93 +899,27 @@ function bytesToHex(bytes) {
821
899
  .map(b => b.toString(16).padStart(2, '0'))
822
900
  .join('');
823
901
  }
824
- const PROTOCOL_V2_DEBUG_HEADER_BYTES = 7;
825
- const PROTOCOL_V2_DEBUG_ARRAY_ITEMS_LIMIT = 20;
826
- const PROTOCOL_V2_DEBUG_OBJECT_KEYS_LIMIT = 40;
827
- const PROTOCOL_V2_DEBUG_STRING_LIMIT = 512;
828
- const PROTOCOL_V2_DEBUG_DEPTH_LIMIT = 4;
829
- const HIGH_VOLUME_PROTOCOL_V2_CALLS = new Set([
902
+ const REDUCED_DEBUG_PROTOCOL_V2_CALLS = new Set([
830
903
  ...LogBlockCommand,
831
904
  'FilesystemFileRead',
832
905
  'FileRead',
833
906
  'EmmcFileRead',
834
907
  ]);
835
908
  function shouldReduceProtocolV2Debug(name) {
836
- return HIGH_VOLUME_PROTOCOL_V2_CALLS.has(name);
909
+ return REDUCED_DEBUG_PROTOCOL_V2_CALLS.has(name);
837
910
  }
838
- function frameHeaderDebugHex(frame) {
839
- return bytesToHex(frame.slice(0, PROTOCOL_V2_DEBUG_HEADER_BYTES));
840
- }
841
- function getBinaryByteLength(value) {
842
- if (value instanceof ArrayBuffer) {
843
- return value.byteLength;
844
- }
845
- if (ArrayBuffer.isView(value)) {
846
- return value.byteLength;
847
- }
848
- if (typeof Blob !== 'undefined' && value instanceof Blob) {
849
- return value.size;
850
- }
851
- return undefined;
852
- }
853
- function summarizeRedactedData(value) {
854
- const byteLength = getBinaryByteLength(value);
855
- if (byteLength !== undefined) {
856
- return `[redacted data: ${byteLength} bytes]`;
857
- }
858
- if (typeof value === 'string') {
859
- return `[redacted data: string length=${value.length}]`;
860
- }
861
- if (Array.isArray(value)) {
862
- return `[redacted data: array length=${value.length}]`;
863
- }
864
- if (value && typeof value === 'object') {
865
- return `[redacted data: object keys=${Object.keys(value).length}]`;
866
- }
867
- return `[redacted data: ${typeof value}]`;
868
- }
869
- function sanitizeProtocolV2DebugPayload(value, key = '', depth = 0) {
870
- if (/^(data|payload)$/i.test(key) && value !== null && value !== undefined) {
871
- return summarizeRedactedData(value);
872
- }
873
- if (/(passphrase|pin|mnemonic|seed|private)/i.test(key)) {
874
- return '[redacted sensitive value]';
875
- }
876
- const byteLength = getBinaryByteLength(value);
877
- if (byteLength !== undefined) {
878
- return `[binary: ${byteLength} bytes]`;
879
- }
880
- if (typeof value === 'string') {
881
- return value.length > PROTOCOL_V2_DEBUG_STRING_LIMIT
882
- ? `${value.slice(0, PROTOCOL_V2_DEBUG_STRING_LIMIT)}... (len=${value.length})`
883
- : value;
884
- }
885
- if (!value || typeof value !== 'object') {
886
- return value;
887
- }
888
- if (depth >= PROTOCOL_V2_DEBUG_DEPTH_LIMIT) {
889
- return Array.isArray(value)
890
- ? `[array length=${value.length}]`
891
- : `[object keys=${Object.keys(value).length}]`;
892
- }
893
- if (Array.isArray(value)) {
894
- const items = value
895
- .slice(0, PROTOCOL_V2_DEBUG_ARRAY_ITEMS_LIMIT)
896
- .map(item => sanitizeProtocolV2DebugPayload(item, key, depth + 1));
897
- if (value.length > PROTOCOL_V2_DEBUG_ARRAY_ITEMS_LIMIT) {
898
- items.push(`... (${value.length - PROTOCOL_V2_DEBUG_ARRAY_ITEMS_LIMIT} more)`);
899
- }
900
- return items;
901
- }
902
- const entries = Object.entries(value).slice(0, PROTOCOL_V2_DEBUG_OBJECT_KEYS_LIMIT);
903
- const sanitized = {};
904
- entries.forEach(([entryKey, entryValue]) => {
905
- sanitized[entryKey] = sanitizeProtocolV2DebugPayload(entryValue, entryKey, depth + 1);
906
- });
907
- if (Object.keys(value).length > PROTOCOL_V2_DEBUG_OBJECT_KEYS_LIMIT) {
908
- sanitized.__truncated__ = `${Object.keys(value).length - PROTOCOL_V2_DEBUG_OBJECT_KEYS_LIMIT} more keys`;
909
- }
910
- return sanitized;
911
+ const HIGH_THROUGHPUT_PROTOCOL_V2_CALLS = new Set([
912
+ 'FilesystemFileWrite',
913
+ 'FileWrite',
914
+ 'EmmcFileWrite',
915
+ 'FirmwareUpload',
916
+ 'ResourceAck',
917
+ 'FilesystemFileRead',
918
+ 'FileRead',
919
+ 'EmmcFileRead',
920
+ ]);
921
+ function isProtocolV2HighThroughputCall(name) {
922
+ return HIGH_THROUGHPUT_PROTOCOL_V2_CALLS.has(name);
911
923
  }
912
924
  const COMMON_TERMINAL_RESPONSE_TYPES = new Set([
913
925
  'Failure',
@@ -934,11 +946,12 @@ function getErrorMessage(error) {
934
946
  }
935
947
  return String(error);
936
948
  }
937
- function withProtocolTimeout(promise, timeoutMs, createTimeoutError, onTimeout) {
949
+ function withProtocolTimeout(promise, timeoutMs, createTimeoutError, onTimeout, abortSignal) {
938
950
  return __awaiter(this, void 0, void 0, function* () {
939
951
  if (!timeoutMs)
940
952
  return promise;
941
953
  let timer;
954
+ let abortHandler;
942
955
  try {
943
956
  return yield Promise.race([
944
957
  promise,
@@ -948,20 +961,38 @@ function withProtocolTimeout(promise, timeoutMs, createTimeoutError, onTimeout)
948
961
  reject(createTimeoutError());
949
962
  }, timeoutMs);
950
963
  }),
964
+ ...(abortSignal
965
+ ? [
966
+ new Promise((_, reject) => {
967
+ abortHandler = () => {
968
+ reject(new Error('Protocol V2 operation aborted'));
969
+ };
970
+ if (abortSignal.aborted) {
971
+ abortHandler();
972
+ }
973
+ else {
974
+ abortSignal.addEventListener('abort', abortHandler, { once: true });
975
+ }
976
+ }),
977
+ ]
978
+ : []),
951
979
  ]);
952
980
  }
953
981
  finally {
954
982
  if (timer)
955
983
  clearTimeout(timer);
984
+ if (abortHandler) {
985
+ abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener('abort', abortHandler);
986
+ }
956
987
  }
957
988
  });
958
989
  }
959
- const PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS = 0;
960
990
  class ProtocolV2Session {
961
991
  constructor(options) {
992
+ var _a;
962
993
  this.pendingCall = Promise.resolve();
963
- this.protoSeq = 0;
964
994
  this.options = options;
995
+ this.sequenceCursor = (_a = options.sequenceCursor) !== null && _a !== void 0 ? _a : new ProtocolV2SequenceCursor();
965
996
  }
966
997
  call(name, data, callOptions = {}) {
967
998
  const run = () => this.executeCall(name, data, callOptions);
@@ -970,69 +1001,97 @@ class ProtocolV2Session {
970
1001
  return result;
971
1002
  }
972
1003
  executeCall(name, data, callOptions) {
973
- var _a, _b;
974
- return __awaiter(this, void 0, void 0, function* () {
975
- const { schemas, router, packetSrc = PROTOCOL_V2_PACKET_SRC_COMMAND, writeFrame, readFrame, logger, logPrefix = 'ProtocolV2', createTimeoutError, } = this.options;
976
- const shouldReduceDebug = shouldReduceProtocolV2Debug(name);
977
- this.protoSeq = nextProtoSeq(this.protoSeq);
1004
+ const { schemas, router, packetSrc = PROTOCOL_V2_PACKET_SRC_COMMAND, maxFrameBytes, prepareCall, writeFrame, readFrame, logger, logPrefix = 'ProtocolV2', createTimeoutError, generation = 0, } = this.options;
1005
+ const timeoutMs = callOptions.timeoutMs && callOptions.timeoutMs > 0
1006
+ ? callOptions.timeoutMs
1007
+ : PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS;
1008
+ const abortController = new AbortController();
1009
+ const shouldReduceDebug = shouldReduceProtocolV2Debug(name);
1010
+ const baseCallContext = Object.assign(Object.assign({ messageName: name, timeoutMs, highThroughput: isProtocolV2HighThroughputCall(name) }, (callOptions.writeWithResponse === undefined
1011
+ ? {}
1012
+ : { writeWithResponse: callOptions.writeWithResponse })), { generation, signal: abortController.signal });
1013
+ const runCall = () => __awaiter(this, void 0, void 0, function* () {
1014
+ var _a, _b, _c, _d, _e, _f;
1015
+ yield (prepareCall === null || prepareCall === void 0 ? void 0 : prepareCall(baseCallContext));
1016
+ const protoSeq = this.sequenceCursor.next();
978
1017
  const frame = ProtocolV2.encodeFrame(schemas, name, data, {
979
1018
  packetSrc,
980
1019
  router,
981
- seq: this.protoSeq,
982
- logger: shouldReduceDebug ? undefined : logger,
983
- logPrefix,
984
- context: `tx:${name}`,
1020
+ seq: protoSeq,
985
1021
  });
986
- const expectedSeq = frame[6];
987
- if (!shouldReduceDebug) {
988
- (_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));
989
- (_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)}`);
1022
+ if (maxFrameBytes !== undefined && frame.length > maxFrameBytes) {
1023
+ throw new Error(`Protocol V2 frame too large for transport: ${frame.length} > ${maxFrameBytes}`);
990
1024
  }
991
- 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}`));
992
- const cancellation = { cancelled: false };
993
- const readResponse = () => __awaiter(this, void 0, void 0, function* () {
994
- var _c, _d, _e, _f, _g, _h, _j, _k;
995
- while (!cancellation.cancelled) {
996
- const rxFrame = yield readFrame();
997
- if (cancellation.cancelled) {
998
- break;
1025
+ const writeStartedAt = Date.now();
1026
+ yield writeFrame(frame, baseCallContext);
1027
+ try {
1028
+ (_a = callOptions.onWriteCompleted) === null || _a === void 0 ? void 0 : _a.call(callOptions, {
1029
+ elapsedMs: Math.max(Date.now() - writeStartedAt, 0),
1030
+ frameBytes: frame.byteLength,
1031
+ });
1032
+ }
1033
+ catch (error) {
1034
+ (_b = logger === null || logger === void 0 ? void 0 : logger.error) === null || _b === void 0 ? void 0 : _b.call(logger, `${logPrefix} write metrics callback failed: ${String(error)}`);
1035
+ }
1036
+ while (!abortController.signal.aborted) {
1037
+ const rxFrame = yield readFrame(baseCallContext);
1038
+ if (abortController.signal.aborted)
1039
+ break;
1040
+ let header;
1041
+ try {
1042
+ header = ProtocolV2.inspectFrameHeader(rxFrame);
1043
+ }
1044
+ catch (cause) {
1045
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame validation failed: ${getErrorMessage(cause)}`, cause);
1046
+ }
1047
+ if (header.router !== router) {
1048
+ throw new ProtocolV2LinkError('router', `Protocol V2 router mismatch: expected ${router}, got ${header.router}`);
1049
+ }
1050
+ if (header.packetSrc !== packetSrc) {
1051
+ throw new ProtocolV2LinkError('packet-source', `Protocol V2 packet source mismatch: expected ${packetSrc}, got ${header.packetSrc}`);
1052
+ }
1053
+ let isAck;
1054
+ try {
1055
+ isAck = ProtocolV2.isAckFrame(rxFrame);
1056
+ }
1057
+ catch (cause) {
1058
+ throw new ProtocolV2LinkError('frame', `Protocol V2 ACK validation failed: ${getErrorMessage(cause)}`, cause);
1059
+ }
1060
+ if (isAck) {
1061
+ if (header.seq !== protoSeq) {
1062
+ throw new ProtocolV2LinkError('ack-sequence', `Protocol V2 ACK sequence mismatch: expected ${protoSeq}, got ${header.seq}`);
999
1063
  }
1000
- if (!shouldReduceDebug) {
1001
- (_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)}`);
1064
+ }
1065
+ else {
1066
+ let decoded;
1067
+ try {
1068
+ decoded = ProtocolV2.decodeFrame(schemas, rxFrame);
1002
1069
  }
1003
- const decoded = ProtocolV2.decodeFrame(schemas, rxFrame, {
1004
- logger: shouldReduceDebug ? undefined : logger,
1005
- logPrefix,
1006
- context: `rx:${name}`,
1007
- });
1008
- if (!shouldReduceDebug && decoded.seq !== expectedSeq) {
1009
- (_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}`);
1070
+ catch (cause) {
1071
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame decode failed: ${getErrorMessage(cause)}`, cause);
1010
1072
  }
1011
- if (!shouldReduceDebug) {
1012
- (_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`);
1013
- (_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));
1073
+ if (this.lastResponseSequence === decoded.seq) {
1074
+ throw new ProtocolV2LinkError('response-sequence', `Protocol V2 duplicate response sequence: ${decoded.seq}`);
1014
1075
  }
1076
+ this.lastResponseSequence = decoded.seq;
1015
1077
  const response = call(decoded);
1016
- if ((_g = callOptions.intermediateTypes) === null || _g === void 0 ? void 0 : _g.includes(response.type)) {
1017
- (_h = callOptions.onIntermediateResponse) === null || _h === void 0 ? void 0 : _h.call(callOptions, response);
1078
+ if ((_c = callOptions.intermediateTypes) === null || _c === void 0 ? void 0 : _c.includes(response.type)) {
1079
+ (_d = callOptions.onIntermediateResponse) === null || _d === void 0 ? void 0 : _d.call(callOptions, response);
1018
1080
  }
1019
1081
  else if (isExpectedTerminalResponse(response, callOptions.expectedTypes)) {
1020
1082
  return response;
1021
1083
  }
1022
1084
  else if (!shouldReduceDebug) {
1023
- (_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}`);
1085
+ (_e = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _e === void 0 ? void 0 : _e.call(logger, `[${logPrefix}] skip unexpected response for ${name}: expected=${(_f = callOptions.expectedTypes) === null || _f === void 0 ? void 0 : _f.join('|')} got=${response.type}`);
1024
1086
  }
1025
1087
  }
1026
- throw new Error(`Protocol V2 read loop cancelled after timeout for ${name}`);
1027
- });
1028
- return withProtocolTimeout(readResponse(), callOptions.timeoutMs, () => {
1029
- var _a;
1030
- return createTimeoutError
1031
- ? createTimeoutError(name, (_a = callOptions.timeoutMs) !== null && _a !== void 0 ? _a : 0)
1032
- : new Error(`Protocol V2 response timeout after ${callOptions.timeoutMs}ms for ${name}`);
1033
- }, () => {
1034
- cancellation.cancelled = true;
1035
- });
1088
+ }
1089
+ throw new Error(`Protocol V2 read loop cancelled after timeout for ${name}`);
1090
+ });
1091
+ return withProtocolTimeout(runCall(), timeoutMs, () => createTimeoutError
1092
+ ? createTimeoutError(name, timeoutMs)
1093
+ : new Error(`Protocol V2 response timeout after ${timeoutMs}ms for ${name}`), () => {
1094
+ abortController.abort();
1036
1095
  });
1037
1096
  }
1038
1097
  }
@@ -1042,7 +1101,10 @@ function probeProtocolV2({ call, timeoutMs, logger, logPrefix = 'ProtocolV2', on
1042
1101
  let probeError;
1043
1102
  try {
1044
1103
  yield (onBeforeProbe === null || onBeforeProbe === void 0 ? void 0 : onBeforeProbe());
1045
- const response = yield call('Ping', { message: 'protocol-v2-probe' }, { timeoutMs, expectedTypes: ['Success'] });
1104
+ const response = yield call('Ping', { message: 'protocol-v2-probe' }, {
1105
+ timeoutMs,
1106
+ expectedTypes: ['Success'],
1107
+ });
1046
1108
  if (response.type === 'Success') {
1047
1109
  return true;
1048
1110
  }
@@ -1057,6 +1119,305 @@ function probeProtocolV2({ call, timeoutMs, logger, logPrefix = 'ProtocolV2', on
1057
1119
  });
1058
1120
  }
1059
1121
 
1122
+ class ProtocolV2LinkManager {
1123
+ constructor(options) {
1124
+ this.links = new Map();
1125
+ this.sequences = new Map();
1126
+ this.callQueues = new Map();
1127
+ this.generations = new Map();
1128
+ this.invalidationReasons = new Map();
1129
+ this.invalidations = new Map();
1130
+ this.options = options;
1131
+ }
1132
+ call(key, createAdapter, name, data, options) {
1133
+ var _a, _b;
1134
+ const generation = (_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0;
1135
+ const run = () => {
1136
+ this.assertCallGeneration(key, generation);
1137
+ return this.executeCall(key, createAdapter, name, data, options);
1138
+ };
1139
+ const previous = (_b = this.callQueues.get(key)) !== null && _b !== void 0 ? _b : Promise.resolve();
1140
+ const result = previous.then(run, run);
1141
+ const queue = result.catch(() => undefined);
1142
+ this.callQueues.set(key, queue);
1143
+ result
1144
+ .then(() => this.clearSettledCallQueue(key, queue), () => this.clearSettledCallQueue(key, queue))
1145
+ .catch(() => undefined);
1146
+ return result;
1147
+ }
1148
+ invalidateLink(key, reason) {
1149
+ var _a;
1150
+ return __awaiter(this, void 0, void 0, function* () {
1151
+ const generation = ((_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0) + 1;
1152
+ this.generations.set(key, generation);
1153
+ this.invalidationReasons.set(key, { generation, reason });
1154
+ const pendingInvalidation = this.invalidations.get(key);
1155
+ const link = this.links.get(key);
1156
+ if (!link) {
1157
+ yield pendingInvalidation;
1158
+ return;
1159
+ }
1160
+ this.links.delete(key);
1161
+ link.state.invalidatedReason = reason;
1162
+ const invalidation = (() => __awaiter(this, void 0, void 0, function* () {
1163
+ var _b, _c;
1164
+ yield (pendingInvalidation === null || pendingInvalidation === void 0 ? void 0 : pendingInvalidation.catch(() => undefined));
1165
+ yield link.adapter.reset(reason);
1166
+ yield ((_c = (_b = this.options).onLinkInvalidated) === null || _c === void 0 ? void 0 : _c.call(_b, key, reason));
1167
+ }))();
1168
+ this.invalidations.set(key, invalidation);
1169
+ try {
1170
+ yield invalidation;
1171
+ }
1172
+ finally {
1173
+ if (this.invalidations.get(key) === invalidation) {
1174
+ this.invalidations.delete(key);
1175
+ }
1176
+ }
1177
+ });
1178
+ }
1179
+ invalidateAllLinks(reason) {
1180
+ return __awaiter(this, void 0, void 0, function* () {
1181
+ const keys = new Set([
1182
+ ...this.links.keys(),
1183
+ ...this.callQueues.keys(),
1184
+ ...this.invalidations.keys(),
1185
+ ]);
1186
+ yield Promise.all(Array.from(keys, key => this.invalidateLink(key, reason)));
1187
+ });
1188
+ }
1189
+ dispose(reason) {
1190
+ return __awaiter(this, void 0, void 0, function* () {
1191
+ yield this.invalidateAllLinks(reason);
1192
+ this.sequences.clear();
1193
+ this.callQueues.clear();
1194
+ this.invalidations.clear();
1195
+ });
1196
+ }
1197
+ getOrCreateLink(key, createAdapter) {
1198
+ const existing = this.links.get(key);
1199
+ if (existing)
1200
+ return existing;
1201
+ const adapter = createAdapter();
1202
+ const state = {};
1203
+ const assertLinkActive = () => {
1204
+ if (state.invalidatedReason) {
1205
+ throw new Error(state.invalidatedReason);
1206
+ }
1207
+ };
1208
+ let sequenceCursor = this.sequences.get(key);
1209
+ if (!sequenceCursor) {
1210
+ sequenceCursor = new ProtocolV2SequenceCursor();
1211
+ this.sequences.set(key, sequenceCursor);
1212
+ }
1213
+ const session = new ProtocolV2Session({
1214
+ schemas: this.options.getSchemas(),
1215
+ router: adapter.router,
1216
+ maxFrameBytes: adapter.maxFrameBytes,
1217
+ generation: adapter.generation,
1218
+ sequenceCursor,
1219
+ prepareCall: (context) => __awaiter(this, void 0, void 0, function* () {
1220
+ assertLinkActive();
1221
+ yield adapter.prepareCall(context);
1222
+ assertLinkActive();
1223
+ }),
1224
+ writeFrame: (frame, context) => __awaiter(this, void 0, void 0, function* () {
1225
+ assertLinkActive();
1226
+ yield adapter.writeFrame(frame, context);
1227
+ assertLinkActive();
1228
+ }),
1229
+ readFrame: (context) => __awaiter(this, void 0, void 0, function* () {
1230
+ assertLinkActive();
1231
+ const frame = yield adapter.readFrame(context);
1232
+ assertLinkActive();
1233
+ return frame;
1234
+ }),
1235
+ logger: adapter.logger,
1236
+ logPrefix: adapter.logPrefix,
1237
+ createTimeoutError: adapter.createTimeoutError,
1238
+ });
1239
+ const link = { adapter, session, state };
1240
+ this.links.set(key, link);
1241
+ return link;
1242
+ }
1243
+ executeCall(key, createAdapter, name, data, options) {
1244
+ return __awaiter(this, void 0, void 0, function* () {
1245
+ try {
1246
+ return yield this.getOrCreateLink(key, createAdapter).session.call(name, data, options);
1247
+ }
1248
+ catch (error) {
1249
+ if (this.options.classifyError(error) === 'link-fatal') {
1250
+ const errorMessage = getErrorMessage(error) || 'unknown error';
1251
+ yield this.invalidateLink(key, `Protocol V2 link-fatal error: ${errorMessage}`);
1252
+ }
1253
+ throw error;
1254
+ }
1255
+ });
1256
+ }
1257
+ clearSettledCallQueue(key, queue) {
1258
+ if (this.callQueues.get(key) === queue) {
1259
+ this.callQueues.delete(key);
1260
+ }
1261
+ }
1262
+ assertCallGeneration(key, generation) {
1263
+ var _a;
1264
+ const currentGeneration = (_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0;
1265
+ if (currentGeneration === generation)
1266
+ return;
1267
+ const invalidation = this.invalidationReasons.get(key);
1268
+ const reason = (invalidation === null || invalidation === void 0 ? void 0 : invalidation.generation) === currentGeneration
1269
+ ? invalidation.reason
1270
+ : 'Protocol V2 link generation changed';
1271
+ throw new ProtocolV2LinkError('generation', reason);
1272
+ }
1273
+ }
1274
+
1275
+ class ProtocolV2UsbTransportBase {
1276
+ constructor(options) {
1277
+ this.protocolV2UsbAssemblers = new Map();
1278
+ this.protocolV2UsbGenerations = new Map();
1279
+ this.protocolV2UsbCancellations = new Map();
1280
+ this.protocolV2UsbOptions = options;
1281
+ this.protocolV2UsbLinks = new ProtocolV2LinkManager({
1282
+ getSchemas: () => this.getProtocolV2UsbSchemas(),
1283
+ classifyError: error => (isProtocolV2LinkError(error) ? 'link-fatal' : 'recoverable'),
1284
+ onLinkInvalidated: (key, reason) => __awaiter(this, void 0, void 0, function* () {
1285
+ var _a;
1286
+ (_a = this.protocolV2UsbAssemblers.get(key)) === null || _a === void 0 ? void 0 : _a.reset();
1287
+ yield this.resetProtocolV2UsbNativeLink(key, reason);
1288
+ yield this.onProtocolV2UsbLinkInvalidated(key, reason);
1289
+ }),
1290
+ });
1291
+ }
1292
+ onProtocolV2UsbLinkInvalidated(_key, _reason) {
1293
+ }
1294
+ rotateProtocolV2UsbGeneration(key, reason) {
1295
+ var _a;
1296
+ return __awaiter(this, void 0, void 0, function* () {
1297
+ yield this.protocolV2UsbLinks.invalidateLink(key, reason);
1298
+ const generation = ((_a = this.protocolV2UsbGenerations.get(key)) !== null && _a !== void 0 ? _a : 0) + 1;
1299
+ this.protocolV2UsbGenerations.set(key, generation);
1300
+ this.protocolV2UsbCancellations.set(key, this.createProtocolV2UsbCancellation(generation));
1301
+ this.protocolV2UsbAssemblers.set(key, new ProtocolV2FrameAssembler(this.protocolV2UsbOptions.maxFrameBytes));
1302
+ return generation;
1303
+ });
1304
+ }
1305
+ callProtocolV2Usb(key, name, data, options) {
1306
+ return this.protocolV2UsbLinks.call(key, () => this.createProtocolV2UsbAdapter(key), name, data, options);
1307
+ }
1308
+ invalidateProtocolV2UsbLink(key, reason) {
1309
+ return this.protocolV2UsbLinks.invalidateLink(key, reason);
1310
+ }
1311
+ invalidateAllProtocolV2UsbLinks(reason) {
1312
+ return this.protocolV2UsbLinks.invalidateAllLinks(reason);
1313
+ }
1314
+ disposeProtocolV2UsbLinks(reason) {
1315
+ return __awaiter(this, void 0, void 0, function* () {
1316
+ yield this.protocolV2UsbLinks.dispose(reason);
1317
+ this.protocolV2UsbAssemblers.clear();
1318
+ this.protocolV2UsbGenerations.clear();
1319
+ this.protocolV2UsbCancellations.clear();
1320
+ });
1321
+ }
1322
+ createProtocolV2UsbAdapter(key) {
1323
+ const generation = this.protocolV2UsbGenerations.get(key);
1324
+ if (generation === undefined) {
1325
+ throw new Error('Protocol V2 USB generation has not been initialized');
1326
+ }
1327
+ const cancellation = this.protocolV2UsbCancellations.get(key);
1328
+ if (!cancellation || cancellation.generation !== generation) {
1329
+ throw new Error('Protocol V2 USB cancellation state has not been initialized');
1330
+ }
1331
+ const assertCurrentGeneration = () => {
1332
+ if (cancellation.reason) {
1333
+ throw new ProtocolV2LinkError('generation', cancellation.reason);
1334
+ }
1335
+ if (this.protocolV2UsbGenerations.get(key) !== generation) {
1336
+ throw new ProtocolV2LinkError('generation', 'Protocol V2 USB connection generation changed');
1337
+ }
1338
+ };
1339
+ return {
1340
+ router: this.protocolV2UsbOptions.router,
1341
+ maxFrameBytes: this.protocolV2UsbOptions.maxFrameBytes,
1342
+ generation,
1343
+ prepareCall: () => {
1344
+ assertCurrentGeneration();
1345
+ },
1346
+ writeFrame: (frame, context) => __awaiter(this, void 0, void 0, function* () {
1347
+ assertCurrentGeneration();
1348
+ try {
1349
+ yield this.writeProtocolV2UsbPacket(key, frame, context);
1350
+ }
1351
+ catch (error) {
1352
+ throw this.createProtocolV2UsbIoError('write', error);
1353
+ }
1354
+ assertCurrentGeneration();
1355
+ }),
1356
+ readFrame: (context) => __awaiter(this, void 0, void 0, function* () {
1357
+ assertCurrentGeneration();
1358
+ const assembler = this.getProtocolV2UsbAssembler(key);
1359
+ let frame = assembler.push(new Uint8Array(0));
1360
+ while (!frame) {
1361
+ const packetRead = this.readProtocolV2UsbPacket(key, context)
1362
+ .then(packet => ({ packet }))
1363
+ .catch(error => {
1364
+ throw this.createProtocolV2UsbIoError('read', error);
1365
+ });
1366
+ const cancelled = cancellation.promise.then(reason => ({ reason }));
1367
+ const result = yield Promise.race([packetRead, cancelled]);
1368
+ if ('reason' in result) {
1369
+ throw new ProtocolV2LinkError('generation', result.reason);
1370
+ }
1371
+ assertCurrentGeneration();
1372
+ frame = assembler.push(result.packet);
1373
+ }
1374
+ assertCurrentGeneration();
1375
+ return frame;
1376
+ }),
1377
+ reset: (reason) => {
1378
+ var _a;
1379
+ cancellation.cancel(reason);
1380
+ (_a = this.protocolV2UsbAssemblers.get(key)) === null || _a === void 0 ? void 0 : _a.reset();
1381
+ },
1382
+ logger: this.getProtocolV2UsbLogger(),
1383
+ logPrefix: this.protocolV2UsbOptions.logPrefix,
1384
+ createTimeoutError: (messageName, timeoutMs) => this.createProtocolV2UsbTimeoutError(messageName, timeoutMs),
1385
+ };
1386
+ }
1387
+ getProtocolV2UsbAssembler(key) {
1388
+ const assembler = this.protocolV2UsbAssemblers.get(key);
1389
+ if (!assembler) {
1390
+ throw new Error('Protocol V2 USB assembler has not been initialized');
1391
+ }
1392
+ return assembler;
1393
+ }
1394
+ createProtocolV2UsbCancellation(generation) {
1395
+ let resolveCancellation = () => undefined;
1396
+ const cancellation = {
1397
+ generation,
1398
+ promise: new Promise(resolve => {
1399
+ resolveCancellation = resolve;
1400
+ }),
1401
+ cancel: reason => {
1402
+ if (cancellation.reason)
1403
+ return;
1404
+ cancellation.reason = reason;
1405
+ resolveCancellation(reason);
1406
+ },
1407
+ };
1408
+ return cancellation;
1409
+ }
1410
+ createProtocolV2UsbIoError(operation, error) {
1411
+ if (isProtocolV2LinkError(error))
1412
+ return error;
1413
+ return new ProtocolV2LinkError('io', `Protocol V2 USB ${operation} failed: ${getErrorMessage(error) || 'unknown error'}`, error);
1414
+ }
1415
+ }
1416
+
1417
+ const TRANSPORT_EVENT = {
1418
+ DEVICE_DISCONNECT: 'transport-device-disconnect',
1419
+ };
1420
+
1060
1421
  exports.AptosTransactionType = void 0;
1061
1422
  (function (AptosTransactionType) {
1062
1423
  AptosTransactionType[AptosTransactionType["STANDARD"] = 0] = "STANDARD";
@@ -1303,6 +1664,24 @@ exports.EthereumDataType = void 0;
1303
1664
  EthereumDataType[EthereumDataType["ARRAY"] = 7] = "ARRAY";
1304
1665
  EthereumDataType[EthereumDataType["STRUCT"] = 8] = "STRUCT";
1305
1666
  })(exports.EthereumDataType || (exports.EthereumDataType = {}));
1667
+ exports.Enum_KaspaInputScriptType = void 0;
1668
+ (function (Enum_KaspaInputScriptType) {
1669
+ Enum_KaspaInputScriptType[Enum_KaspaInputScriptType["KASPA_SPEND_P2PK_SCHNORR"] = 0] = "KASPA_SPEND_P2PK_SCHNORR";
1670
+ Enum_KaspaInputScriptType[Enum_KaspaInputScriptType["KASPA_SPEND_P2PK_ECDSA"] = 1] = "KASPA_SPEND_P2PK_ECDSA";
1671
+ })(exports.Enum_KaspaInputScriptType || (exports.Enum_KaspaInputScriptType = {}));
1672
+ exports.Enum_KaspaOutputScriptType = void 0;
1673
+ (function (Enum_KaspaOutputScriptType) {
1674
+ Enum_KaspaOutputScriptType[Enum_KaspaOutputScriptType["KASPA_PAYTOADDRESS"] = 0] = "KASPA_PAYTOADDRESS";
1675
+ Enum_KaspaOutputScriptType[Enum_KaspaOutputScriptType["KASPA_PAYTOCHANGE"] = 1] = "KASPA_PAYTOCHANGE";
1676
+ })(exports.Enum_KaspaOutputScriptType || (exports.Enum_KaspaOutputScriptType = {}));
1677
+ exports.Enum_KaspaRequestType = void 0;
1678
+ (function (Enum_KaspaRequestType) {
1679
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_INPUT"] = 0] = "KASPA_TX_INPUT";
1680
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_OUTPUT"] = 1] = "KASPA_TX_OUTPUT";
1681
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_PAYLOAD"] = 2] = "KASPA_TX_PAYLOAD";
1682
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_FINISHED"] = 3] = "KASPA_TX_FINISHED";
1683
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_PREV_META"] = 4] = "KASPA_TX_PREV_META";
1684
+ })(exports.Enum_KaspaRequestType || (exports.Enum_KaspaRequestType = {}));
1306
1685
  exports.Enum_BackupType = void 0;
1307
1686
  (function (Enum_BackupType) {
1308
1687
  Enum_BackupType[Enum_BackupType["Bip39"] = 0] = "Bip39";
@@ -1496,11 +1875,6 @@ exports.CommandFlags = void 0;
1496
1875
  CommandFlags[CommandFlags["Default"] = 0] = "Default";
1497
1876
  CommandFlags[CommandFlags["Factory_Only"] = 1] = "Factory_Only";
1498
1877
  })(exports.CommandFlags || (exports.CommandFlags = {}));
1499
- exports.WallpaperTarget = void 0;
1500
- (function (WallpaperTarget) {
1501
- WallpaperTarget[WallpaperTarget["Home"] = 0] = "Home";
1502
- WallpaperTarget[WallpaperTarget["Lock"] = 1] = "Lock";
1503
- })(exports.WallpaperTarget || (exports.WallpaperTarget = {}));
1504
1878
  exports.MoneroNetworkType = void 0;
1505
1879
  (function (MoneroNetworkType) {
1506
1880
  MoneroNetworkType[MoneroNetworkType["MAINNET"] = 0] = "MAINNET";
@@ -1508,20 +1882,49 @@ exports.MoneroNetworkType = void 0;
1508
1882
  MoneroNetworkType[MoneroNetworkType["STAGENET"] = 2] = "STAGENET";
1509
1883
  MoneroNetworkType[MoneroNetworkType["FAKECHAIN"] = 3] = "FAKECHAIN";
1510
1884
  })(exports.MoneroNetworkType || (exports.MoneroNetworkType = {}));
1511
- exports.ViewTipType = void 0;
1512
- (function (ViewTipType) {
1513
- ViewTipType[ViewTipType["Default"] = 0] = "Default";
1514
- ViewTipType[ViewTipType["Highlight"] = 1] = "Highlight";
1515
- ViewTipType[ViewTipType["Recommend"] = 2] = "Recommend";
1516
- ViewTipType[ViewTipType["Warning"] = 3] = "Warning";
1517
- ViewTipType[ViewTipType["Danger"] = 4] = "Danger";
1518
- })(exports.ViewTipType || (exports.ViewTipType = {}));
1885
+ exports.UiAnimationType = void 0;
1886
+ (function (UiAnimationType) {
1887
+ UiAnimationType[UiAnimationType["Unknown"] = 0] = "Unknown";
1888
+ UiAnimationType[UiAnimationType["Signing"] = 1] = "Signing";
1889
+ })(exports.UiAnimationType || (exports.UiAnimationType = {}));
1890
+ exports.UiAnimationCommand = void 0;
1891
+ (function (UiAnimationCommand) {
1892
+ UiAnimationCommand[UiAnimationCommand["CommandUnknown"] = 0] = "CommandUnknown";
1893
+ UiAnimationCommand[UiAnimationCommand["Start"] = 1] = "Start";
1894
+ UiAnimationCommand[UiAnimationCommand["Stop"] = 2] = "Stop";
1895
+ UiAnimationCommand[UiAnimationCommand["Refresh"] = 3] = "Refresh";
1896
+ })(exports.UiAnimationCommand || (exports.UiAnimationCommand = {}));
1897
+ exports.DeviceErrorCode = void 0;
1898
+ (function (DeviceErrorCode) {
1899
+ DeviceErrorCode[DeviceErrorCode["DeviceError_None"] = 0] = "DeviceError_None";
1900
+ DeviceErrorCode[DeviceErrorCode["DeviceError_Busy"] = 1] = "DeviceError_Busy";
1901
+ DeviceErrorCode[DeviceErrorCode["DeviceError_NotInitialized"] = 2] = "DeviceError_NotInitialized";
1902
+ DeviceErrorCode[DeviceErrorCode["DeviceError_ActionCancelled"] = 3] = "DeviceError_ActionCancelled";
1903
+ DeviceErrorCode[DeviceErrorCode["DeviceError_PinAlreadyUsed"] = 4] = "DeviceError_PinAlreadyUsed";
1904
+ DeviceErrorCode[DeviceErrorCode["DeviceError_PersistFailed"] = 5] = "DeviceError_PersistFailed";
1905
+ DeviceErrorCode[DeviceErrorCode["DeviceError_SeError"] = 6] = "DeviceError_SeError";
1906
+ DeviceErrorCode[DeviceErrorCode["DeviceError_InvalidLanguage"] = 7] = "DeviceError_InvalidLanguage";
1907
+ DeviceErrorCode[DeviceErrorCode["DeviceError_WallpaperNotUsable"] = 8] = "DeviceError_WallpaperNotUsable";
1908
+ DeviceErrorCode[DeviceErrorCode["DeviceError_DeviceLocked"] = 9] = "DeviceError_DeviceLocked";
1909
+ })(exports.DeviceErrorCode || (exports.DeviceErrorCode = {}));
1519
1910
  exports.DeviceRebootType = void 0;
1520
1911
  (function (DeviceRebootType) {
1521
1912
  DeviceRebootType[DeviceRebootType["Normal"] = 0] = "Normal";
1522
1913
  DeviceRebootType[DeviceRebootType["Romloader"] = 1] = "Romloader";
1523
1914
  DeviceRebootType[DeviceRebootType["Bootloader"] = 2] = "Bootloader";
1524
1915
  })(exports.DeviceRebootType || (exports.DeviceRebootType = {}));
1916
+ exports.DeviceSettingsPage = void 0;
1917
+ (function (DeviceSettingsPage) {
1918
+ DeviceSettingsPage[DeviceSettingsPage["DeviceReset"] = 0] = "DeviceReset";
1919
+ DeviceSettingsPage[DeviceSettingsPage["DevicePinChange"] = 1] = "DevicePinChange";
1920
+ DeviceSettingsPage[DeviceSettingsPage["DevicePassphrase"] = 2] = "DevicePassphrase";
1921
+ DeviceSettingsPage[DeviceSettingsPage["DeviceAirgap"] = 3] = "DeviceAirgap";
1922
+ })(exports.DeviceSettingsPage || (exports.DeviceSettingsPage = {}));
1923
+ exports.DeviceFactoryAck = void 0;
1924
+ (function (DeviceFactoryAck) {
1925
+ DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_SUCCESS"] = 0] = "FACTORY_ACK_SUCCESS";
1926
+ DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_FAIL"] = 1] = "FACTORY_ACK_FAIL";
1927
+ })(exports.DeviceFactoryAck || (exports.DeviceFactoryAck = {}));
1525
1928
  exports.DeviceFirmwareTargetType = void 0;
1526
1929
  (function (DeviceFirmwareTargetType) {
1527
1930
  DeviceFirmwareTargetType[DeviceFirmwareTargetType["FW_MGMT_TARGET_INVALID"] = 0] = "FW_MGMT_TARGET_INVALID";
@@ -1550,11 +1953,6 @@ exports.DeviceFirmwareUpdateTaskStatus = void 0;
1550
1953
  DeviceFirmwareUpdateTaskStatus[DeviceFirmwareUpdateTaskStatus["FW_MGMT_UPDATER_TASK_STATUS_FAILED_BUSY"] = 9] = "FW_MGMT_UPDATER_TASK_STATUS_FAILED_BUSY";
1551
1954
  DeviceFirmwareUpdateTaskStatus[DeviceFirmwareUpdateTaskStatus["FW_MGMT_UPDATER_TASK_STATUS_FAILED_ENTRY_OUT_OF_BOUNDS"] = 10] = "FW_MGMT_UPDATER_TASK_STATUS_FAILED_ENTRY_OUT_OF_BOUNDS";
1552
1955
  })(exports.DeviceFirmwareUpdateTaskStatus || (exports.DeviceFirmwareUpdateTaskStatus = {}));
1553
- exports.DeviceFactoryAck = void 0;
1554
- (function (DeviceFactoryAck) {
1555
- DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_SUCCESS"] = 0] = "FACTORY_ACK_SUCCESS";
1556
- DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_FAIL"] = 1] = "FACTORY_ACK_FAIL";
1557
- })(exports.DeviceFactoryAck || (exports.DeviceFactoryAck = {}));
1558
1956
  exports.DeviceType = void 0;
1559
1957
  (function (DeviceType) {
1560
1958
  DeviceType[DeviceType["CLASSIC1"] = 0] = "CLASSIC1";
@@ -1577,6 +1975,116 @@ exports.DeviceSEState = void 0;
1577
1975
  DeviceSEState[DeviceSEState["APP_FACTORY"] = 51] = "APP_FACTORY";
1578
1976
  DeviceSEState[DeviceSEState["APP"] = 85] = "APP";
1579
1977
  })(exports.DeviceSEState || (exports.DeviceSEState = {}));
1978
+ exports.DeviceSessionErrorCode = void 0;
1979
+ (function (DeviceSessionErrorCode) {
1980
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_None"] = 0] = "DeviceSessionError_None";
1981
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_UserCancelled"] = 1] = "DeviceSessionError_UserCancelled";
1982
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_InvalidSession"] = 2] = "DeviceSessionError_InvalidSession";
1983
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_AttachPinUnavailable"] = 3] = "DeviceSessionError_AttachPinUnavailable";
1984
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_PassphraseDisabled"] = 4] = "DeviceSessionError_PassphraseDisabled";
1985
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_Busy"] = 5] = "DeviceSessionError_Busy";
1986
+ })(exports.DeviceSessionErrorCode || (exports.DeviceSessionErrorCode = {}));
1987
+ exports.DeviceSessionSeedDomain = void 0;
1988
+ (function (DeviceSessionSeedDomain) {
1989
+ DeviceSessionSeedDomain[DeviceSessionSeedDomain["SeedDomain_Standard"] = 1] = "SeedDomain_Standard";
1990
+ DeviceSessionSeedDomain[DeviceSessionSeedDomain["SeedDomain_Cardano"] = 2] = "SeedDomain_Cardano";
1991
+ })(exports.DeviceSessionSeedDomain || (exports.DeviceSessionSeedDomain = {}));
1992
+ exports.DeviceSessionPinType = void 0;
1993
+ (function (DeviceSessionPinType) {
1994
+ DeviceSessionPinType[DeviceSessionPinType["Any"] = 1] = "Any";
1995
+ DeviceSessionPinType[DeviceSessionPinType["Main"] = 2] = "Main";
1996
+ DeviceSessionPinType[DeviceSessionPinType["AttachToPin"] = 3] = "AttachToPin";
1997
+ })(exports.DeviceSessionPinType || (exports.DeviceSessionPinType = {}));
1998
+ exports.DeviceSessionAskPin_FailureSubCodes = void 0;
1999
+ (function (DeviceSessionAskPin_FailureSubCodes) {
2000
+ DeviceSessionAskPin_FailureSubCodes[DeviceSessionAskPin_FailureSubCodes["UserCancel"] = 1] = "UserCancel";
2001
+ })(exports.DeviceSessionAskPin_FailureSubCodes || (exports.DeviceSessionAskPin_FailureSubCodes = {}));
2002
+ exports.OnboardingStep = void 0;
2003
+ (function (OnboardingStep) {
2004
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_UNKNOWN"] = 0] = "ONBOARDING_STEP_UNKNOWN";
2005
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_CHECKING"] = 1] = "ONBOARDING_STEP_CHECKING";
2006
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_PERSONALIZATION"] = 2] = "ONBOARDING_STEP_PERSONALIZATION";
2007
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_PIN"] = 3] = "ONBOARDING_STEP_PIN";
2008
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_SETUP"] = 4] = "ONBOARDING_STEP_SETUP";
2009
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_DONE"] = 5] = "ONBOARDING_STEP_DONE";
2010
+ })(exports.OnboardingStep || (exports.OnboardingStep = {}));
2011
+ exports.OnboardingPhase = void 0;
2012
+ (function (OnboardingPhase) {
2013
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_UNKNOWN"] = 0] = "ONBOARDING_PHASE_UNKNOWN";
2014
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SAFETY_CHECK"] = 1] = "ONBOARDING_PHASE_SAFETY_CHECK";
2015
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_PIN_SETUP"] = 2] = "ONBOARDING_PHASE_PIN_SETUP";
2016
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_FINGERPRINT_SETUP"] = 3] = "ONBOARDING_PHASE_FINGERPRINT_SETUP";
2017
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SETUP_CHOICE"] = 4] = "ONBOARDING_PHASE_SETUP_CHOICE";
2018
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_WALLET_CREATE_START"] = 5] = "ONBOARDING_PHASE_WALLET_CREATE_START";
2019
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RECOVERY_PHRASE_VIEW"] = 6] = "ONBOARDING_PHASE_RECOVERY_PHRASE_VIEW";
2020
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RECOVERY_PHRASE_CONFIRM"] = 7] = "ONBOARDING_PHASE_RECOVERY_PHRASE_CONFIRM";
2021
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RESTORE_METHOD_CHOICE"] = 8] = "ONBOARDING_PHASE_RESTORE_METHOD_CHOICE";
2022
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RECOVERY_PHRASE_RESTORE"] = 9] = "ONBOARDING_PHASE_RECOVERY_PHRASE_RESTORE";
2023
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SEEDCARD_RESTORE"] = 10] = "ONBOARDING_PHASE_SEEDCARD_RESTORE";
2024
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_WALLET_READY"] = 11] = "ONBOARDING_PHASE_WALLET_READY";
2025
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SEEDCARD_BACKUP_PROMPT"] = 12] = "ONBOARDING_PHASE_SEEDCARD_BACKUP_PROMPT";
2026
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SEEDCARD_BACKUP"] = 13] = "ONBOARDING_PHASE_SEEDCARD_BACKUP";
2027
+ })(exports.OnboardingPhase || (exports.OnboardingPhase = {}));
2028
+ exports.OnboardingSetupKind = void 0;
2029
+ (function (OnboardingSetupKind) {
2030
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_UNKNOWN"] = 0] = "ONBOARDING_SETUP_KIND_UNKNOWN";
2031
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_CHOICE"] = 1] = "ONBOARDING_SETUP_KIND_CHOICE";
2032
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_CREATE"] = 2] = "ONBOARDING_SETUP_KIND_CREATE";
2033
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_RESTORE"] = 3] = "ONBOARDING_SETUP_KIND_RESTORE";
2034
+ })(exports.OnboardingSetupKind || (exports.OnboardingSetupKind = {}));
2035
+ exports.OnboardingSetupMethod = void 0;
2036
+ (function (OnboardingSetupMethod) {
2037
+ OnboardingSetupMethod[OnboardingSetupMethod["ONBOARDING_SETUP_METHOD_UNKNOWN"] = 0] = "ONBOARDING_SETUP_METHOD_UNKNOWN";
2038
+ OnboardingSetupMethod[OnboardingSetupMethod["ONBOARDING_SETUP_METHOD_RECOVERY_PHRASE"] = 1] = "ONBOARDING_SETUP_METHOD_RECOVERY_PHRASE";
2039
+ OnboardingSetupMethod[OnboardingSetupMethod["ONBOARDING_SETUP_METHOD_SEEDCARD"] = 2] = "ONBOARDING_SETUP_METHOD_SEEDCARD";
2040
+ })(exports.OnboardingSetupMethod || (exports.OnboardingSetupMethod = {}));
2041
+ exports.ViewTipType = void 0;
2042
+ (function (ViewTipType) {
2043
+ ViewTipType[ViewTipType["Default"] = 0] = "Default";
2044
+ ViewTipType[ViewTipType["Highlight"] = 1] = "Highlight";
2045
+ ViewTipType[ViewTipType["Recommend"] = 2] = "Recommend";
2046
+ ViewTipType[ViewTipType["Warning"] = 3] = "Warning";
2047
+ ViewTipType[ViewTipType["Danger"] = 4] = "Danger";
2048
+ })(exports.ViewTipType || (exports.ViewTipType = {}));
2049
+ exports.ViewSignLayout = void 0;
2050
+ (function (ViewSignLayout) {
2051
+ ViewSignLayout[ViewSignLayout["LayoutDefault"] = 0] = "LayoutDefault";
2052
+ ViewSignLayout[ViewSignLayout["LayoutSafeTxCreate"] = 1] = "LayoutSafeTxCreate";
2053
+ ViewSignLayout[ViewSignLayout["LayoutFinalConfirm"] = 2] = "LayoutFinalConfirm";
2054
+ ViewSignLayout[ViewSignLayout["Layout7702"] = 3] = "Layout7702";
2055
+ ViewSignLayout[ViewSignLayout["LayoutFlat"] = 4] = "LayoutFlat";
2056
+ ViewSignLayout[ViewSignLayout["LayoutEthApprove"] = 5] = "LayoutEthApprove";
2057
+ })(exports.ViewSignLayout || (exports.ViewSignLayout = {}));
2058
+ exports.ProtocolV2FailureType = void 0;
2059
+ (function (ProtocolV2FailureType) {
2060
+ ProtocolV2FailureType[ProtocolV2FailureType["Failure_InvalidMessage"] = 1] = "Failure_InvalidMessage";
2061
+ ProtocolV2FailureType[ProtocolV2FailureType["Failure_UndefinedError"] = 2] = "Failure_UndefinedError";
2062
+ ProtocolV2FailureType[ProtocolV2FailureType["Failure_UsageError"] = 3] = "Failure_UsageError";
2063
+ ProtocolV2FailureType[ProtocolV2FailureType["Failure_DataError"] = 4] = "Failure_DataError";
2064
+ ProtocolV2FailureType[ProtocolV2FailureType["Failure_ProcessError"] = 5] = "Failure_ProcessError";
2065
+ })(exports.ProtocolV2FailureType || (exports.ProtocolV2FailureType = {}));
2066
+ exports.Enum_ProtocolV2Capability = void 0;
2067
+ (function (Enum_ProtocolV2Capability) {
2068
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Bitcoin"] = 1] = "Capability_Bitcoin";
2069
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Bitcoin_like"] = 2] = "Capability_Bitcoin_like";
2070
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Binance"] = 3] = "Capability_Binance";
2071
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Cardano"] = 4] = "Capability_Cardano";
2072
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Crypto"] = 5] = "Capability_Crypto";
2073
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_EOS"] = 6] = "Capability_EOS";
2074
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Ethereum"] = 7] = "Capability_Ethereum";
2075
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Lisk"] = 8] = "Capability_Lisk";
2076
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Monero"] = 9] = "Capability_Monero";
2077
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_NEM"] = 10] = "Capability_NEM";
2078
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Ripple"] = 11] = "Capability_Ripple";
2079
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Stellar"] = 12] = "Capability_Stellar";
2080
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Tezos"] = 13] = "Capability_Tezos";
2081
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_U2F"] = 14] = "Capability_U2F";
2082
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Shamir"] = 15] = "Capability_Shamir";
2083
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_ShamirGroups"] = 16] = "Capability_ShamirGroups";
2084
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_PassphraseEntry"] = 17] = "Capability_PassphraseEntry";
2085
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_AttachToPin"] = 18] = "Capability_AttachToPin";
2086
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_EthereumTypedData"] = 1000] = "Capability_EthereumTypedData";
2087
+ })(exports.Enum_ProtocolV2Capability || (exports.Enum_ProtocolV2Capability = {}));
1580
2088
 
1581
2089
  var messages = /*#__PURE__*/Object.freeze({
1582
2090
  __proto__: null,
@@ -1609,6 +2117,9 @@ var messages = /*#__PURE__*/Object.freeze({
1609
2117
  get EthereumGnosisSafeTxOperation () { return exports.EthereumGnosisSafeTxOperation; },
1610
2118
  get EthereumDataTypeOneKey () { return exports.EthereumDataTypeOneKey; },
1611
2119
  get EthereumDataType () { return exports.EthereumDataType; },
2120
+ get Enum_KaspaInputScriptType () { return exports.Enum_KaspaInputScriptType; },
2121
+ get Enum_KaspaOutputScriptType () { return exports.Enum_KaspaOutputScriptType; },
2122
+ get Enum_KaspaRequestType () { return exports.Enum_KaspaRequestType; },
1612
2123
  get Enum_BackupType () { return exports.Enum_BackupType; },
1613
2124
  get Enum_SafetyCheckLevel () { return exports.Enum_SafetyCheckLevel; },
1614
2125
  get OneKeyDeviceType () { return exports.OneKeyDeviceType; },
@@ -1640,18 +2151,114 @@ var messages = /*#__PURE__*/Object.freeze({
1640
2151
  get TronResourceCode () { return exports.TronResourceCode; },
1641
2152
  get TronMessageType () { return exports.TronMessageType; },
1642
2153
  get CommandFlags () { return exports.CommandFlags; },
1643
- get WallpaperTarget () { return exports.WallpaperTarget; },
1644
2154
  get MoneroNetworkType () { return exports.MoneroNetworkType; },
1645
- get ViewTipType () { return exports.ViewTipType; },
2155
+ get UiAnimationType () { return exports.UiAnimationType; },
2156
+ get UiAnimationCommand () { return exports.UiAnimationCommand; },
2157
+ get DeviceErrorCode () { return exports.DeviceErrorCode; },
1646
2158
  get DeviceRebootType () { return exports.DeviceRebootType; },
2159
+ get DeviceSettingsPage () { return exports.DeviceSettingsPage; },
2160
+ get DeviceFactoryAck () { return exports.DeviceFactoryAck; },
1647
2161
  get DeviceFirmwareTargetType () { return exports.DeviceFirmwareTargetType; },
1648
2162
  get DeviceFirmwareUpdateTaskStatus () { return exports.DeviceFirmwareUpdateTaskStatus; },
1649
- get DeviceFactoryAck () { return exports.DeviceFactoryAck; },
1650
2163
  get DeviceType () { return exports.DeviceType; },
1651
2164
  get DeviceSeType () { return exports.DeviceSeType; },
1652
- get DeviceSEState () { return exports.DeviceSEState; }
2165
+ get DeviceSEState () { return exports.DeviceSEState; },
2166
+ get DeviceSessionErrorCode () { return exports.DeviceSessionErrorCode; },
2167
+ get DeviceSessionSeedDomain () { return exports.DeviceSessionSeedDomain; },
2168
+ get DeviceSessionPinType () { return exports.DeviceSessionPinType; },
2169
+ get DeviceSessionAskPin_FailureSubCodes () { return exports.DeviceSessionAskPin_FailureSubCodes; },
2170
+ get OnboardingStep () { return exports.OnboardingStep; },
2171
+ get OnboardingPhase () { return exports.OnboardingPhase; },
2172
+ get OnboardingSetupKind () { return exports.OnboardingSetupKind; },
2173
+ get OnboardingSetupMethod () { return exports.OnboardingSetupMethod; },
2174
+ get ViewTipType () { return exports.ViewTipType; },
2175
+ get ViewSignLayout () { return exports.ViewSignLayout; },
2176
+ get ProtocolV2FailureType () { return exports.ProtocolV2FailureType; },
2177
+ get Enum_ProtocolV2Capability () { return exports.Enum_ProtocolV2Capability; }
1653
2178
  });
1654
2179
 
2180
+ const REDACTED = '[REDACTED]';
2181
+ const SENSITIVE_LOG_KEYS = new Set([
2182
+ 'accesstoken',
2183
+ 'address',
2184
+ 'apikey',
2185
+ 'connectid',
2186
+ 'devicestate',
2187
+ 'deviceid',
2188
+ 'entropy',
2189
+ 'expectedpassphrasestate',
2190
+ 'mnemonic',
2191
+ 'passphrase',
2192
+ 'passphrasestate',
2193
+ 'password',
2194
+ 'pin',
2195
+ 'privatekey',
2196
+ 'publickey',
2197
+ 'seed',
2198
+ 'serialnumber',
2199
+ 'session',
2200
+ 'sessionid',
2201
+ 'signature',
2202
+ 'token',
2203
+ 'uuid',
2204
+ 'walletsessionid',
2205
+ 'xprv',
2206
+ 'xpub',
2207
+ ]);
2208
+ const normalizeLogKey = (key) => key.replace(/[_-]/g, '').toLowerCase();
2209
+ const isSensitiveLogKey = (key) => {
2210
+ const normalizedKey = normalizeLogKey(key);
2211
+ return (SENSITIVE_LOG_KEYS.has(normalizedKey) ||
2212
+ normalizedKey.endsWith('address') ||
2213
+ normalizedKey.endsWith('privatekey') ||
2214
+ normalizedKey.endsWith('publickey') ||
2215
+ normalizedKey.endsWith('signature'));
2216
+ };
2217
+ const isSigningMessage = (messageName) => Boolean(messageName && /(?:sign|txack|transaction)/i.test(messageName));
2218
+ const redactLogValue = (value, seen) => {
2219
+ if (ArrayBuffer.isView(value)) {
2220
+ return `[BINARY:${value.byteLength}]`;
2221
+ }
2222
+ if (value instanceof ArrayBuffer) {
2223
+ return `[BINARY:${value.byteLength}]`;
2224
+ }
2225
+ if (Array.isArray(value)) {
2226
+ return value.map(item => redactLogValue(item, seen));
2227
+ }
2228
+ if (!value || typeof value !== 'object') {
2229
+ return value;
2230
+ }
2231
+ if (seen.has(value)) {
2232
+ return '[CIRCULAR]';
2233
+ }
2234
+ seen.add(value);
2235
+ const redacted = Object.fromEntries(Object.entries(value).map(([key, item]) => [
2236
+ key,
2237
+ isSensitiveLogKey(key) && item !== null && item !== undefined
2238
+ ? REDACTED
2239
+ : redactLogValue(item, seen),
2240
+ ]));
2241
+ seen.delete(value);
2242
+ return redacted;
2243
+ };
2244
+ function getSafeTransportLogPayload(value, messageName) {
2245
+ if (isSigningMessage(messageName)) {
2246
+ return REDACTED;
2247
+ }
2248
+ return redactLogValue(value, new WeakSet());
2249
+ }
2250
+ function createTransportCallLog(name, protocol, data) {
2251
+ return {
2252
+ name,
2253
+ protocol,
2254
+ request: getSafeTransportLogPayload(data, name),
2255
+ };
2256
+ }
2257
+ const HIGH_VOLUME_CALLS = new Set(['FileWrite', 'FilesystemFileWrite', 'EmmcFileWrite']);
2258
+ function shouldSuppressHighVolumeCallLog(name) {
2259
+ return HIGH_VOLUME_CALLS.has(name);
2260
+ }
2261
+
1655
2262
  protobuf__namespace.util.Long = Long__default["default"];
1656
2263
  protobuf__namespace.configure();
1657
2264
  var index = {
@@ -1662,7 +2269,10 @@ var index = {
1662
2269
  ProtocolV2,
1663
2270
  PROTOCOL_V2_SYS_MESSAGE_THRESHOLD,
1664
2271
  ProtocolV2FrameAssembler,
2272
+ ProtocolV2LinkManager,
2273
+ ProtocolV2SequenceCursor,
1665
2274
  ProtocolV2Session,
2275
+ ProtocolV2UsbTransportBase,
1666
2276
  bytesToHex,
1667
2277
  concatUint8Arrays,
1668
2278
  createMessageFromName,
@@ -1684,25 +2294,39 @@ exports.PROTOCOL_V1_MESSAGE_HEADER_SIZE = PROTOCOL_V1_MESSAGE_HEADER_SIZE;
1684
2294
  exports.PROTOCOL_V1_REPORT_ID = PROTOCOL_V1_REPORT_ID;
1685
2295
  exports.PROTOCOL_V1_USB_PACKET_SIZE = PROTOCOL_V1_USB_PACKET_SIZE;
1686
2296
  exports.PROTOCOL_V2_BLE_FILE_CHUNK_SIZE = PROTOCOL_V2_BLE_FILE_CHUNK_SIZE;
2297
+ exports.PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE = PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE;
2298
+ exports.PROTOCOL_V2_BLE_FIRMWARE_FILE_CHUNK_SIZE = PROTOCOL_V2_BLE_FIRMWARE_FILE_CHUNK_SIZE;
2299
+ exports.PROTOCOL_V2_BLE_FRAME_MAX_BYTES = PROTOCOL_V2_BLE_FRAME_MAX_BYTES;
1687
2300
  exports.PROTOCOL_V2_CHANNEL_BLE_UART = PROTOCOL_V2_CHANNEL_BLE_UART;
1688
2301
  exports.PROTOCOL_V2_CHANNEL_SOCKET = PROTOCOL_V2_CHANNEL_SOCKET;
1689
2302
  exports.PROTOCOL_V2_CHANNEL_USB = PROTOCOL_V2_CHANNEL_USB;
2303
+ exports.PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS = PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS;
1690
2304
  exports.PROTOCOL_V2_FILE_CHUNK_SIZE = PROTOCOL_V2_FILE_CHUNK_SIZE;
1691
2305
  exports.PROTOCOL_V2_FRAME_MAX_BYTES = PROTOCOL_V2_FRAME_MAX_BYTES;
1692
2306
  exports.PROTOCOL_V2_PACKET_SRC_COMMAND = PROTOCOL_V2_PACKET_SRC_COMMAND;
1693
2307
  exports.PROTOCOL_V2_SYS_MESSAGE_THRESHOLD = PROTOCOL_V2_SYS_MESSAGE_THRESHOLD;
1694
2308
  exports.PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE = PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
1695
- exports.PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS = PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS;
1696
2309
  exports.ProtocolV1 = ProtocolV1;
1697
2310
  exports.ProtocolV2 = ProtocolV2;
1698
2311
  exports.ProtocolV2FrameAssembler = ProtocolV2FrameAssembler;
2312
+ exports.ProtocolV2LinkError = ProtocolV2LinkError;
2313
+ exports.ProtocolV2LinkManager = ProtocolV2LinkManager;
2314
+ exports.ProtocolV2SequenceCursor = ProtocolV2SequenceCursor;
1699
2315
  exports.ProtocolV2Session = ProtocolV2Session;
2316
+ exports.ProtocolV2UsbTransportBase = ProtocolV2UsbTransportBase;
2317
+ exports.TRANSPORT_EVENT = TRANSPORT_EVENT;
1700
2318
  exports.bytesToHex = bytesToHex;
1701
2319
  exports.concatUint8Arrays = concatUint8Arrays;
2320
+ exports.createTransportCallLog = createTransportCallLog;
1702
2321
  exports["default"] = index;
1703
2322
  exports.getErrorMessage = getErrorMessage;
2323
+ exports.getSafeTransportLogPayload = getSafeTransportLogPayload;
1704
2324
  exports.hexToBytes = hexToBytes;
2325
+ exports.isProtocolV2HighThroughputCall = isProtocolV2HighThroughputCall;
2326
+ exports.isProtocolV2LinkError = isProtocolV2LinkError;
1705
2327
  exports.probeProtocolV2 = probeProtocolV2;
1706
2328
  exports.protocolV1 = index$1;
1707
2329
  exports.protocolV2 = protocolV2Codec;
2330
+ exports.shouldSuppressHighVolumeCallLog = shouldSuppressHighVolumeCallLog;
1708
2331
  exports.withProtocolTimeout = withProtocolTimeout;
2332
+ exports.writeProtocolV2BleFrame = writeProtocolV2BleFrame;