@onekeyfe/hd-core 1.2.8-alpha.10 → 1.2.8-alpha.100

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 (56) hide show
  1. package/__tests__/DeviceCommands.test.ts +66 -13
  2. package/__tests__/core-error-output.test.ts +34 -3
  3. package/__tests__/device-lifecycle-events.test.ts +22 -17
  4. package/__tests__/logBlockEvent.test.ts +43 -0
  5. package/__tests__/protocol-v2-bootloader-mode.test.ts +43 -2
  6. package/__tests__/protocol-v2.test.ts +0 -47
  7. package/__tests__/refresh-device-state.test.ts +19 -17
  8. package/__tests__/zcash-sign-pczt.test.ts +212 -0
  9. package/dist/api/FirmwareUpdateV4.d.ts.map +1 -1
  10. package/dist/api/GetDeviceState.d.ts.map +1 -1
  11. package/dist/api/index.d.ts +2 -0
  12. package/dist/api/index.d.ts.map +1 -1
  13. package/dist/api/protocol-v2/DeviceReboot.d.ts.map +1 -1
  14. package/dist/api/zcash/ZcashGetAddress.d.ts +12 -0
  15. package/dist/api/zcash/ZcashGetAddress.d.ts.map +1 -0
  16. package/dist/api/zcash/ZcashSignPczt.d.ts +17 -0
  17. package/dist/api/zcash/ZcashSignPczt.d.ts.map +1 -0
  18. package/dist/core/index.d.ts +0 -1
  19. package/dist/core/index.d.ts.map +1 -1
  20. package/dist/device/DeviceCommands.d.ts +4 -4
  21. package/dist/device/DeviceCommands.d.ts.map +1 -1
  22. package/dist/events/logBlockEvent.d.ts.map +1 -1
  23. package/dist/index.d.ts +39 -5
  24. package/dist/index.js +351 -27
  25. package/dist/inject.d.ts.map +1 -1
  26. package/dist/types/api/export.d.ts +2 -0
  27. package/dist/types/api/export.d.ts.map +1 -1
  28. package/dist/types/api/index.d.ts +4 -0
  29. package/dist/types/api/index.d.ts.map +1 -1
  30. package/dist/types/api/zcashGetAddress.d.ts +22 -0
  31. package/dist/types/api/zcashGetAddress.d.ts.map +1 -0
  32. package/dist/types/api/zcashSignPczt.d.ts +9 -0
  33. package/dist/types/api/zcashSignPczt.d.ts.map +1 -0
  34. package/dist/types/params.d.ts +1 -0
  35. package/dist/types/params.d.ts.map +1 -1
  36. package/dist/utils/patch.d.ts +1 -1
  37. package/dist/utils/patch.d.ts.map +1 -1
  38. package/package.json +4 -4
  39. package/src/api/FirmwareUpdateV4.ts +8 -25
  40. package/src/api/GetDeviceState.ts +2 -5
  41. package/src/api/index.ts +2 -0
  42. package/src/api/protocol-v2/DeviceReboot.ts +2 -0
  43. package/src/api/zcash/ZcashGetAddress.ts +121 -0
  44. package/src/api/zcash/ZcashSignPczt.ts +153 -0
  45. package/src/core/index.ts +2 -6
  46. package/src/data/messages/messages-protocol-v2.json +138 -1
  47. package/src/device/Device.ts +1 -1
  48. package/src/device/DeviceCommands.ts +15 -1
  49. package/src/events/core.ts +2 -2
  50. package/src/events/logBlockEvent.ts +5 -2
  51. package/src/inject.ts +4 -0
  52. package/src/types/api/export.ts +2 -0
  53. package/src/types/api/index.ts +8 -0
  54. package/src/types/api/zcashGetAddress.ts +36 -0
  55. package/src/types/api/zcashSignPczt.ts +18 -0
  56. package/src/types/params.ts +1 -1
@@ -130,19 +130,6 @@ describe('DeviceCommands failure mapping', () => {
130
130
  );
131
131
  });
132
132
 
133
- it('preserves the Protocol V2 peer-removed pairing error code', async () => {
134
- const commands = createCommands();
135
- const transportError = Object.assign(new Error('Peer removed pairing information'), {
136
- errorCode: HardwareErrorCode.BlePeerRemovedPairingInformation,
137
- });
138
- commands.mainId = 'main-id';
139
- commands.transport = {
140
- call: jest.fn().mockRejectedValue(transportError),
141
- } as any;
142
-
143
- await expect(commands._commonCall('DeviceInfoGet', {})).rejects.toBe(transportError);
144
- });
145
-
146
133
  it('logs canonical DeviceStatus response fields without exposing the device ID', async () => {
147
134
  const commands = createCommands();
148
135
  const log = getLogger(LoggerNames.DeviceCommands);
@@ -414,6 +401,27 @@ describe('DeviceCommands failure mapping', () => {
414
401
  ).rejects.toMatchObject({ errorCode: HardwareErrorCode.DeviceBusy });
415
402
  });
416
403
 
404
+ it('maps commands rejected during a Protocol V2 firmware update to DeviceBusy', async () => {
405
+ const commands = createCommands();
406
+ const message = 'Requested command not allowed while a firmware update is in progress';
407
+
408
+ await expect(
409
+ commands._filterCommonTypes(
410
+ {
411
+ type: 'Failure',
412
+ message: { code: 'Failure_ProcessError', message },
413
+ } as any,
414
+ 'ProtocolInfoRequest'
415
+ )
416
+ ).rejects.toMatchObject({
417
+ errorCode: HardwareErrorCode.DeviceBusy,
418
+ params: {
419
+ failureCode: 'Failure_ProcessError',
420
+ firmwareMessage: message,
421
+ },
422
+ });
423
+ });
424
+
417
425
  it('maps the current AskPin passphrase-disabled response without relying on a subcode', async () => {
418
426
  const commands = createCommands();
419
427
 
@@ -551,6 +559,51 @@ describe('DeviceCommands failure mapping', () => {
551
559
  }
552
560
  );
553
561
 
562
+ it('maps the Protocol V2 seed-session busy response to DeviceBusy', async () => {
563
+ const commands = createCommands();
564
+
565
+ await expect(
566
+ commands._filterCommonTypes(
567
+ {
568
+ type: 'Failure',
569
+ message: {
570
+ code: 'Failure_ProcessError',
571
+ subcode: DeviceSessionErrorCode.DeviceSessionError_UserCancelled,
572
+ message: 'PIN cancelled',
573
+ },
574
+ } as any,
575
+ 'SignTx'
576
+ )
577
+ ).rejects.toMatchObject({
578
+ errorCode: HardwareErrorCode.DeviceBusy,
579
+ params: {
580
+ failureCode: 'Failure_ProcessError',
581
+ subcode: DeviceSessionErrorCode.DeviceSessionError_UserCancelled,
582
+ firmwareMessage: 'PIN cancelled',
583
+ },
584
+ });
585
+ });
586
+
587
+ it('keeps the same Protocol V2 response as ActionCancelled for DeviceSession calls', async () => {
588
+ const commands = createCommands();
589
+
590
+ await expect(
591
+ commands._filterCommonTypes(
592
+ {
593
+ type: 'Failure',
594
+ message: {
595
+ code: 'Failure_ProcessError',
596
+ subcode: DeviceSessionErrorCode.DeviceSessionError_UserCancelled,
597
+ message: 'PIN cancelled',
598
+ },
599
+ } as any,
600
+ 'DeviceSessionAskPin'
601
+ )
602
+ ).rejects.toMatchObject({
603
+ errorCode: HardwareErrorCode.ActionCancelled,
604
+ });
605
+ });
606
+
554
607
  it('does not use the legacy cancellation-message fallback for Protocol V1', async () => {
555
608
  const commands = createCommands();
556
609
  (commands.device.isProtocolV2 as jest.Mock).mockReturnValue(false);
@@ -3,7 +3,7 @@ import { ERRORS, HardwareErrorCode } from '@onekeyfe/hd-shared';
3
3
  import { initConnector, initCore } from '../src/core';
4
4
  import { DataManager } from '../src/data-manager';
5
5
  import TransportManager from '../src/data-manager/TransportManager';
6
- import { IFRAME } from '../src/events';
6
+ import { IFRAME, createErrorMessage } from '../src/events';
7
7
  import SearchDevices from '../src/api/SearchDevices';
8
8
  import { DeviceList } from '../src/device/DeviceList';
9
9
  import { Device } from '../src/device/Device';
@@ -28,6 +28,23 @@ describe('Core 错误输出边界', () => {
28
28
  jest.restoreAllMocks();
29
29
  });
30
30
 
31
+ test('entry-point errors preserve USB recovery context across JSON serialization', () => {
32
+ const params = {
33
+ operation: 'open',
34
+ nativeErrorName: 'SecurityError',
35
+ nativeErrorMessage: 'Access denied',
36
+ };
37
+ const error = ERRORS.TypedError(
38
+ HardwareErrorCode.BridgeNeedsPermission,
39
+ 'Access denied',
40
+ params
41
+ );
42
+ expect(JSON.parse(JSON.stringify(createErrorMessage(error)))).toEqual({
43
+ success: false,
44
+ payload: { code: HardwareErrorCode.BridgeNeedsPermission, error: 'Access denied', params },
45
+ });
46
+ });
47
+
31
48
  test.each([
32
49
  ['webusb', false],
33
50
  ['desktop-webusb', false],
@@ -108,14 +125,28 @@ describe('Core 错误输出边界', () => {
108
125
  HardwareErrorCode.BleDeviceBondedCanceled,
109
126
  HardwareErrorCode.BleDeviceDisconnected,
110
127
  HardwareErrorCode.PollingTimeout,
128
+ HardwareErrorCode.BlePoweredOff,
129
+ HardwareErrorCode.BleUnsupported,
130
+ HardwareErrorCode.BridgeNeedsPermission,
131
+ HardwareErrorCode.WebUsbDeviceAccessError,
111
132
  ])(
112
- 'preserves terminal BLE error %s in the public response without polling again',
133
+ 'preserves terminal transport error %s in the public response without polling again',
113
134
  async errorCode => {
114
- jest.spyOn(DataManager, 'getSettings').mockReturnValue('react-native' as never);
135
+ jest
136
+ .spyOn(DataManager, 'getSettings')
137
+ .mockReturnValue(
138
+ [
139
+ HardwareErrorCode.BridgeNeedsPermission,
140
+ HardwareErrorCode.WebUsbDeviceAccessError,
141
+ ].includes(errorCode)
142
+ ? ('desktop-webusb' as never)
143
+ : ('react-native' as never)
144
+ );
115
145
  const error = ERRORS.TypedError(errorCode);
116
146
  const acquire = jest.fn().mockRejectedValue(error);
117
147
  jest.spyOn(TransportManager, 'getTransport').mockReturnValue({
118
148
  acquire,
149
+ enumerate: jest.fn().mockResolvedValue([{ path: 'ble-pairing-test' }]),
119
150
  release: jest.fn().mockResolvedValue(true),
120
151
  stop: jest.fn().mockResolvedValue(undefined),
121
152
  } as never);
@@ -10,7 +10,6 @@ import {
10
10
  isMissingDetectedProtocolV2Error,
11
11
  isRetryableBleConnectionError,
12
12
  isRetryableBleProtocolV2ProbeError,
13
- isTerminalBleStaleBondError,
14
13
  resolveBleConnectProtocol,
15
14
  } from '../src/core';
16
15
  import { DataManager } from '../src/data-manager';
@@ -613,7 +612,6 @@ describe('public device lifecycle events', () => {
613
612
  test.each([
614
613
  [HardwareErrorCode.RuntimeError, true],
615
614
  [HardwareErrorCode.BleDeviceBondError, false],
616
- [HardwareErrorCode.BlePeerRemovedPairingInformation, false],
617
615
  ] as const)(
618
616
  'retries a Protocol V2 probe mismatch with error code %s: %s',
619
617
  (errorCode, expected) => {
@@ -633,8 +631,6 @@ describe('public device lifecycle events', () => {
633
631
  [HardwareErrorCode.BleTimeoutError, true],
634
632
  [HardwareErrorCode.PollingTimeout, false],
635
633
  [HardwareErrorCode.BleDeviceBondError, false],
636
- [HardwareErrorCode.BlePeerRemovedPairingInformation, false],
637
- [HardwareErrorCode.BleBondInvalid, false],
638
634
  ] as const)('retries a BLE connection error with error code %s: %s', (errorCode, expected) => {
639
635
  const method = { payload: { connectProtocol: 'V2' } } as never;
640
636
  const error = {
@@ -687,19 +683,6 @@ describe('public device lifecycle events', () => {
687
683
  }
688
684
  );
689
685
 
690
- test.each([
691
- [HardwareErrorCode.BleDeviceBondError, true],
692
- [HardwareErrorCode.BlePeerRemovedPairingInformation, true],
693
- [HardwareErrorCode.BleBondInvalid, true],
694
- [HardwareErrorCode.DeviceNotFound, false],
695
- ] as const)('treats BLE stale-bond error code %s as terminal: %s', (errorCode, expected) => {
696
- const error = {
697
- errorCode,
698
- };
699
-
700
- expect(isTerminalBleStaleBondError(error)).toBe(expected);
701
- });
702
-
703
686
  test.each([
704
687
  [HardwareErrorCode.DeviceCheckDeviceIdError, true],
705
688
  [HardwareErrorCode.DeviceNotFound, false],
@@ -1058,6 +1041,28 @@ describe('public device lifecycle events', () => {
1058
1041
  expect(device.wasInterruptedByUser()).toBe(false);
1059
1042
  });
1060
1043
 
1044
+ test.each(['V1', 'V2'] as const)(
1045
+ 'retires a failed USB %s session before the next user attempt',
1046
+ async protocol => {
1047
+ jest.spyOn(DataManager, 'getSettings').mockReturnValue('desktop-webusb' as never);
1048
+ const device = createInitializedDevice(protocol);
1049
+ device.originalDescriptor = { ...device.originalDescriptor, session: device.mainId };
1050
+ const disconnect = jest.fn().mockResolvedValue(undefined);
1051
+ const release = jest.fn().mockResolvedValue(undefined);
1052
+ device.deviceConnector = { disconnect, release } as never;
1053
+ device.commands = { disposed: false, dispose: jest.fn() } as never;
1054
+ (device as unknown as { deviceAcquired: boolean }).deviceAcquired = true;
1055
+ const error = ERRORS.TypedError(HardwareErrorCode.WebUsbDeviceAccessError);
1056
+ await expect(device.run(() => Promise.reject(error))).rejects.toBe(error);
1057
+ await new Promise(resolve => {
1058
+ setImmediate(resolve);
1059
+ });
1060
+ expect(disconnect).toHaveBeenCalledWith(device.mainId);
1061
+ expect(release).toHaveBeenCalledTimes(1);
1062
+ expect(device.hasDeviceAcquire()).toBe(false);
1063
+ }
1064
+ );
1065
+
1061
1066
  test('waits for the canceled run to finish releasing before cancellation completes', async () => {
1062
1067
  jest.spyOn(DataManager, 'getSettings').mockReturnValue('react-native' as never);
1063
1068
  const device = createInitializedDevice('V2');
@@ -5,6 +5,7 @@ import {
5
5
  getLogBlockLabel,
6
6
  getSafeLogPayload,
7
7
  } from '../src/events';
8
+ import { getLog, initLog, setLoggerPostMessage } from '../src/utils/logger';
8
9
 
9
10
  describe('getLogBlockLabel', () => {
10
11
  it('keeps existing sensitive UI response blocking', () => {
@@ -96,4 +97,46 @@ describe('getLogBlockLabel', () => {
96
97
  it('does not classify events without an API method as method calls', () => {
97
98
  expect(getLogBlockLabel({ event: 'DEVICE_EVENT', type: 'device-connect' })).toBeUndefined();
98
99
  });
100
+
101
+ it.each(['zcashGetAddress', 'zcashGetUnifiedAddress', 'zcashSignPczt'])(
102
+ 'keeps %s wallet data out of logger caches and events with debug disabled',
103
+ method => {
104
+ const postMessage = jest.fn();
105
+ const prefix = `sensitive-zcash-${method}`;
106
+ const logger = initLog(prefix, false);
107
+ setLoggerPostMessage(postMessage);
108
+ const request = {
109
+ event: 'iframe-call',
110
+ payload: { method, pczt: 'synthetic-pczt-marker', includeUfvk: true },
111
+ };
112
+ const response = {
113
+ success: true,
114
+ payload: [
115
+ {
116
+ ufvk: 'synthetic-viewing-key-marker',
117
+ seedFingerprint: 'synthetic-fingerprint-marker',
118
+ pczt: 'synthetic-signed-pczt-marker',
119
+ },
120
+ ],
121
+ };
122
+ const blockLabel = getLogBlockLabel(request);
123
+
124
+ expect(blockLabel).toBe(method);
125
+ expect(getLogBlockLabel(request.payload)).toBe(method);
126
+ logger.debug('request:', getSafeLogPayload(request, blockLabel));
127
+ logger.debug('response:', getSafeLogPayload(response, blockLabel));
128
+
129
+ const cached = getLog().filter(entry => entry.prefix === prefix);
130
+ expect(cached.map(entry => entry.message[1])).toEqual([
131
+ { method, payload: '[REDACTED]' },
132
+ { method, payload: '[REDACTED]' },
133
+ ]);
134
+ expect(postMessage).toHaveBeenCalledTimes(2);
135
+ for (const output of [JSON.stringify(cached), JSON.stringify(postMessage.mock.calls)]) {
136
+ expect(output).not.toContain('synthetic-');
137
+ expect(output).toContain('[REDACTED]');
138
+ }
139
+ expect(response.payload[0].ufvk).toBe('synthetic-viewing-key-marker');
140
+ }
141
+ );
99
142
  });
@@ -1,3 +1,6 @@
1
+ import { EDeviceType } from '@onekeyfe/hd-shared';
2
+
3
+ import DeviceReboot from '../src/api/protocol-v2/DeviceReboot';
1
4
  import { Device } from '../src/device/Device';
2
5
  import { UI_REQUEST } from '../src/events/ui-request';
3
6
 
@@ -23,12 +26,50 @@ const createBootloaderDevice = (protocolType: 'V1' | 'V2') => {
23
26
  };
24
27
 
25
28
  describe('Pro2 bootloader mode', () => {
26
- test('does not block Protocol V2 methods in bootloader mode', () => {
29
+ test('allows deviceReboot to return a Protocol V2 bootloader to normal mode', () => {
30
+ const device = createBootloaderDevice('V2');
31
+ const method = new DeviceReboot({
32
+ id: 1,
33
+ payload: { method: 'deviceReboot', rebootType: 'normal' },
34
+ });
35
+ method.init();
36
+
37
+ expect(device.hasUnexpectedMode(method.allowDeviceMode, method.requireDeviceMode)).toBeNull();
38
+ });
39
+
40
+ test('blocks Protocol V2 methods that are not allowed in bootloader mode', () => {
41
+ const device = createBootloaderDevice('V2');
42
+
43
+ expect(device.hasUnexpectedMode([], [])).toBe(UI_REQUEST.BOOTLOADER);
44
+ });
45
+
46
+ test('allows Protocol V2 methods that explicitly support bootloader mode', () => {
27
47
  const device = createBootloaderDevice('V2');
28
48
 
29
- expect(device.hasUnexpectedMode([], [])).toBeNull();
49
+ expect(device.hasUnexpectedMode([UI_REQUEST.BOOTLOADER], [])).toBeNull();
30
50
  });
31
51
 
52
+ test.each([EDeviceType.Pro2, EDeviceType.Neo])(
53
+ 'blocks unsupported Protocol V2 methods in %s romloader mode',
54
+ deviceType => {
55
+ const device = createBootloaderDevice('V2');
56
+ device.updateState(
57
+ {
58
+ protocol: 'V2',
59
+ identity: { deviceType },
60
+ status: { mode: 'romloader', initialized: null },
61
+ },
62
+ 'initialize'
63
+ );
64
+
65
+ expect(device.hasUnexpectedMode([], [])).toBe(UI_REQUEST.BOOTLOADER);
66
+ expect(device.hasUnexpectedMode([UI_REQUEST.NOT_INITIALIZE], [])).toBe(UI_REQUEST.BOOTLOADER);
67
+ expect(
68
+ device.hasUnexpectedMode([UI_REQUEST.BOOTLOADER, UI_REQUEST.NOT_INITIALIZE], [])
69
+ ).toBeNull();
70
+ }
71
+ );
72
+
32
73
  test('keeps the Protocol V1 bootloader restriction', () => {
33
74
  const device = createBootloaderDevice('V1');
34
75
 
@@ -4991,23 +4991,6 @@ describe('Protocol V2 firmware update targets', () => {
4991
4991
  expect(typedCall.mock.calls.map(call => call[0])).toEqual(['DeviceInfoGet']);
4992
4992
  });
4993
4993
 
4994
- test('stops V4 bootloader reconnect polling on a stale BLE bond', async () => {
4995
- const method = new FirmwareUpdateV4({
4996
- id: 1,
4997
- payload: {
4998
- method: 'firmwareUpdateV4',
4999
- },
5000
- });
5001
- const staleBondError = ERRORS.TypedError(HardwareErrorCode.BlePeerRemovedPairingInformation);
5002
- const reconnectProtocolV2Device = jest.fn().mockRejectedValue(staleBondError);
5003
- (method as any).reconnectProtocolV2Device = reconnectProtocolV2Device;
5004
-
5005
- await expect((method as any).waitForProtocolV2BootloaderMode(60_000, 0)).rejects.toBe(
5006
- staleBondError
5007
- );
5008
- expect(reconnectProtocolV2Device).toHaveBeenCalledTimes(1);
5009
- });
5010
-
5011
4994
  test('polls again when Protocol V2 bootloader serial is temporarily unavailable', async () => {
5012
4995
  const method = new FirmwareUpdateV4({
5013
4996
  id: 1,
@@ -9009,36 +8992,6 @@ describe('Protocol V2 firmware update targets', () => {
9009
8992
  );
9010
8993
  });
9011
8994
 
9012
- test('does not retry or wrap a stale BLE bond during a V4 file transfer', async () => {
9013
- const method = new FirmwareUpdateV4({
9014
- id: 1,
9015
- payload: {
9016
- method: 'firmwareUpdateV4',
9017
- },
9018
- });
9019
- const staleBondError = ERRORS.TypedError(HardwareErrorCode.BlePeerRemovedPairingInformation);
9020
- (method as any).fileWriteChunk = jest.fn().mockRejectedValue(staleBondError);
9021
- const recoverProtocolV2FileTransfer = jest.fn();
9022
- (method as any).recoverProtocolV2FileTransfer = recoverProtocolV2FileTransfer;
9023
- const source = await openFirmwareByteSource({
9024
- binary: new Uint8Array([1]).buffer,
9025
- });
9026
-
9027
- try {
9028
- await expect(
9029
- (method as any).protocolV2SourceUpdateProcess({
9030
- source,
9031
- filePath: 'vol1:firmware.bin',
9032
- processedSize: 0,
9033
- totalSize: 1,
9034
- })
9035
- ).rejects.toBe(staleBondError);
9036
- } finally {
9037
- await source?.close();
9038
- }
9039
- expect(recoverProtocolV2FileTransfer).not.toHaveBeenCalled();
9040
- });
9041
-
9042
8995
  test('does not recover or wrap a cancelled V4 file transfer', async () => {
9043
8996
  const method = new FirmwareUpdateV4({
9044
8997
  id: 1,
@@ -73,24 +73,26 @@ describe('live device state reads', () => {
73
73
  }
74
74
  );
75
75
 
76
- test('rejects settings scope in loader mode after minimal mode detection', async () => {
77
- const getDeviceState = jest.fn().mockResolvedValue({ status: { mode: 'bootloader' } });
78
- const method = new GetDeviceState({
79
- id: 1,
80
- payload: { method: 'getDeviceState', scope: 'settings' },
81
- });
82
- method.init();
83
- (method as any).device = {
84
- isProtocolV2: () => true,
85
- getCurrentFirmwareType: () => 'universal',
86
- getDeviceState,
87
- };
76
+ test.each(['bootloader', 'romloader'] as const)(
77
+ 'reports %s mode for settings scope after minimal mode detection',
78
+ async mode => {
79
+ const getDeviceState = jest.fn().mockResolvedValue({ status: { mode } });
80
+ const method = new GetDeviceState({
81
+ id: 1,
82
+ payload: { method: 'getDeviceState', scope: 'settings' },
83
+ });
84
+ method.init();
85
+ (method as any).device = {
86
+ isProtocolV2: () => true,
87
+ getDeviceState,
88
+ };
88
89
 
89
- await expect(method.run()).rejects.toMatchObject({
90
- errorCode: HardwareErrorCode.DeviceNotSupportMethod,
91
- });
92
- expect(getDeviceState).toHaveBeenCalledWith({ refreshSections: ['status', 'settings'] });
93
- });
90
+ await expect(method.run()).rejects.toMatchObject({
91
+ errorCode: HardwareErrorCode.NotAllowInBootloaderMode,
92
+ });
93
+ expect(getDeviceState).toHaveBeenCalledWith({ refreshSections: ['status', 'settings'] });
94
+ }
95
+ );
94
96
 
95
97
  test('rejects an unknown scope', () => {
96
98
  const method = new GetDeviceState({
@@ -0,0 +1,212 @@
1
+ import ZcashSignPczt, { ZCASH_PCZT_MAX_BYTES } from '../src/api/zcash/ZcashSignPczt';
2
+ import ZcashGetAddress from '../src/api/zcash/ZcashGetAddress';
3
+
4
+ import type { Device } from '../src/device/Device';
5
+
6
+ jest.mock('../src/data/config', () => ({
7
+ getSDKVersion: jest.fn(() => '1.0.0'),
8
+ DEFAULT_DOMAIN: 'https://jssdk.onekey.so/1.0.0/',
9
+ }));
10
+
11
+ const hex = (byte: number, length: number) => byte.toString(16).padStart(2, '0').repeat(length);
12
+
13
+ const createSignMethod = (pczt: string) =>
14
+ new ZcashSignPczt({ id: 1, payload: { method: 'zcashSignPczt', pczt } });
15
+
16
+ const attachDevice = (method: ZcashSignPczt | ZcashGetAddress, typedCall: jest.Mock) => {
17
+ const commands = { typedCall };
18
+ method.device = {
19
+ commands,
20
+ getCommands: () => commands,
21
+ toMessageObject: () => ({}),
22
+ } as unknown as Device;
23
+ method.postMessage = jest.fn();
24
+ };
25
+
26
+ describe('ZcashSignPczt', () => {
27
+ test('uploads device-sized chunks and downloads host-sized chunks', async () => {
28
+ // 2500 bytes: initial 1024, then device asks 1000 + 476.
29
+ const pczt = hex(0xab, 2500);
30
+ const signed = Buffer.alloc(1500, 0xcd);
31
+ const method = createSignMethod(pczt);
32
+ method.init();
33
+
34
+ const typedCall = jest
35
+ .fn()
36
+ .mockResolvedValueOnce({ type: 'ZcashPcztChunkRequest', message: { chunk_length: 1000 } })
37
+ .mockResolvedValueOnce({ type: 'ZcashPcztChunkRequest', message: { chunk_length: 476 } })
38
+ .mockResolvedValueOnce({
39
+ type: 'ZcashSignedPczt',
40
+ message: {
41
+ pczt_length: signed.length,
42
+ pczt_initial_chunk: signed.subarray(0, 1024).toString('hex'),
43
+ },
44
+ })
45
+ .mockResolvedValueOnce({
46
+ type: 'ZcashPcztChunkAck',
47
+ message: { data_chunk: signed.subarray(1024).toString('hex') },
48
+ });
49
+ attachDevice(method, typedCall);
50
+
51
+ await expect(method.run()).resolves.toEqual({ pczt: signed.toString('hex') });
52
+
53
+ expect(typedCall.mock.calls[0]).toEqual([
54
+ 'ZcashSignPczt',
55
+ ['ZcashSignedPczt', 'ZcashPcztChunkRequest'],
56
+ { pczt_length: 2500, pczt_initial_chunk: hex(0xab, 1024) },
57
+ ]);
58
+ expect(typedCall.mock.calls[1]).toEqual([
59
+ 'ZcashPcztChunkAck',
60
+ ['ZcashSignedPczt', 'ZcashPcztChunkRequest'],
61
+ { data_chunk: hex(0xab, 1000) },
62
+ ]);
63
+ expect(typedCall.mock.calls[2][2]).toEqual({ data_chunk: hex(0xab, 476) });
64
+ expect(typedCall.mock.calls[3]).toEqual([
65
+ 'ZcashSignedPcztChunkRequest',
66
+ 'ZcashPcztChunkAck',
67
+ { chunk_length: 476 },
68
+ ]);
69
+ expect(typedCall).toHaveBeenCalledTimes(4);
70
+ });
71
+
72
+ test('single-message round trip when both sides fit in the initial chunk', async () => {
73
+ const method = createSignMethod(hex(0x01, 100));
74
+ method.init();
75
+ const typedCall = jest.fn().mockResolvedValueOnce({
76
+ type: 'ZcashSignedPczt',
77
+ message: { pczt_length: 80, pczt_initial_chunk: hex(0x02, 80) },
78
+ });
79
+ attachDevice(method, typedCall);
80
+
81
+ await expect(method.run()).resolves.toEqual({ pczt: hex(0x02, 80) });
82
+ expect(typedCall).toHaveBeenCalledTimes(1);
83
+ });
84
+
85
+ test('rejects a device chunk request past the end of the pczt', async () => {
86
+ const method = createSignMethod(hex(0x01, 1100));
87
+ method.init();
88
+ const typedCall = jest
89
+ .fn()
90
+ .mockResolvedValueOnce({ type: 'ZcashPcztChunkRequest', message: { chunk_length: 200 } });
91
+ attachDevice(method, typedCall);
92
+
93
+ await expect(method.run()).rejects.toThrow('device requested 200 bytes at offset 1024');
94
+ });
95
+
96
+ test('rejects completion before the entire input has been uploaded', async () => {
97
+ const method = createSignMethod(hex(0x01, 1100));
98
+ method.init();
99
+ const typedCall = jest.fn().mockResolvedValueOnce({
100
+ type: 'ZcashSignedPczt',
101
+ message: { pczt_length: 80, pczt_initial_chunk: hex(0x02, 80) },
102
+ });
103
+ attachDevice(method, typedCall);
104
+ await expect(method.run()).rejects.toThrow('before receiving the whole pczt');
105
+ expect(typedCall).toHaveBeenCalledTimes(1);
106
+ });
107
+
108
+ test('rejects an initial signed chunk larger than its announced total', async () => {
109
+ const method = createSignMethod(hex(0x01, 100));
110
+ method.init();
111
+ const typedCall = jest.fn().mockResolvedValueOnce({
112
+ type: 'ZcashSignedPczt',
113
+ message: { pczt_length: 80, pczt_initial_chunk: hex(0x02, 81) },
114
+ });
115
+ attachDevice(method, typedCall);
116
+ await expect(method.run()).rejects.toThrow('more initial pczt bytes than announced');
117
+ expect(typedCall).toHaveBeenCalledTimes(1);
118
+ });
119
+
120
+ test('rejects oversized and empty input', () => {
121
+ expect(() => createSignMethod('').init()).toThrow();
122
+ expect(() => createSignMethod(hex(0x00, ZCASH_PCZT_MAX_BYTES + 1)).init()).toThrow('exceeds');
123
+ expect(() => createSignMethod(hex(0x00, ZCASH_PCZT_MAX_BYTES)).init()).not.toThrow();
124
+ });
125
+ });
126
+
127
+ describe('ZcashGetAddress', () => {
128
+ test('maps params and response', async () => {
129
+ const method = new ZcashGetAddress({
130
+ id: 1,
131
+ payload: {
132
+ method: 'zcashGetAddress',
133
+ path: "m/32'/133'/0'",
134
+ showOnOneKey: false,
135
+ includeUfvk: true,
136
+ includeSeedFingerprint: true,
137
+ },
138
+ });
139
+ method.init();
140
+ const typedCall = jest.fn().mockResolvedValue({
141
+ message: { address: 'u1abc', ufvk: 'uview1abc', seed_fingerprint: hex(0x0f, 32) },
142
+ });
143
+ attachDevice(method, typedCall);
144
+
145
+ await expect(method.run()).resolves.toEqual({
146
+ path: "m/32'/133'/0'",
147
+ address: 'u1abc',
148
+ ufvk: 'uview1abc',
149
+ seedFingerprint: hex(0x0f, 32),
150
+ });
151
+ expect(typedCall).toHaveBeenCalledWith('ZcashGetAddress', 'ZcashAddress', {
152
+ address_n: [2147483680, 2147483781, 2147483648],
153
+ address_type: 0,
154
+ scope: 0,
155
+ diversifier_index: 0,
156
+ show_display: false,
157
+ include_ufvk: true,
158
+ include_seed_fingerprint: true,
159
+ });
160
+ });
161
+ });
162
+
163
+ describe('Zcash address protocol selection', () => {
164
+ const createAddress = (params: Record<string, unknown> = {}) =>
165
+ new ZcashGetAddress({
166
+ id: 1,
167
+ payload: { method: 'zcashGetAddress', path: "m/32'/133'/0'", ...params },
168
+ });
169
+ test('supports only Pro2 and protocol V2', () => {
170
+ for (const method of [createAddress(), createSignMethod(hex(1, 1))]) {
171
+ method.init();
172
+ expect(method.supportsProtocol('V1')).toBe(false);
173
+ expect(method.supportsProtocol('V2')).toBe(true);
174
+ expect(method.strictCheckDeviceSupport).toBe(true);
175
+ expect(Object.keys(method.getVersionRange())).toEqual(['model_pro2']);
176
+ }
177
+ });
178
+ test.each([0, 1, 2])('maps address type %s with internal scope and index', async addressType => {
179
+ const method = createAddress({ addressType, scope: 1, diversifierIndex: 37 });
180
+ method.init();
181
+ const typedCall = jest.fn().mockResolvedValue({ message: { address: 'device-address' } });
182
+ attachDevice(method, typedCall);
183
+ await method.run();
184
+ expect(typedCall).toHaveBeenCalledWith(
185
+ 'ZcashGetAddress',
186
+ 'ZcashAddress',
187
+ expect.objectContaining({
188
+ address_type: addressType,
189
+ scope: 1,
190
+ diversifier_index: 37,
191
+ show_display: true,
192
+ })
193
+ );
194
+ });
195
+ test.each([
196
+ { addressType: 3 },
197
+ { scope: 2 },
198
+ { diversifierIndex: -1 },
199
+ { diversifierIndex: 1.5 },
200
+ { diversifierIndex: 0x80000000 },
201
+ { addressType: 2, diversifierIndex: 0x100000000 },
202
+ { path: "m/44'/133'/0'" },
203
+ { path: "m/32'/133'/0'/0/0" },
204
+ ])('rejects invalid address requests %j', params => {
205
+ expect(() => createAddress(params).init()).toThrow();
206
+ });
207
+ test('accepts the uint32 limit only for an Orchard-only address', () => {
208
+ expect(() =>
209
+ createAddress({ addressType: 2, diversifierIndex: 0xffffffff }).init()
210
+ ).not.toThrow();
211
+ });
212
+ });