@onekeyfe/hd-core 1.2.8-alpha.2 → 1.2.8-alpha.20

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 (49) hide show
  1. package/README.md +27 -0
  2. package/__tests__/btc-derive-context-hash.test.ts +200 -0
  3. package/__tests__/device-lifecycle-events.test.ts +51 -7
  4. package/__tests__/device-pool-state.test.ts +50 -0
  5. package/__tests__/protocol-v2-bootloader-mode.test.ts +12 -0
  6. package/__tests__/usb-identity-probe.test.ts +293 -0
  7. package/dist/api/SearchDevices.d.ts +21 -1
  8. package/dist/api/SearchDevices.d.ts.map +1 -1
  9. package/dist/api/btc/BTCDeriveContextHash.d.ts +16 -0
  10. package/dist/api/btc/BTCDeriveContextHash.d.ts.map +1 -0
  11. package/dist/api/index.d.ts +1 -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/core/index.d.ts +3 -1
  15. package/dist/core/index.d.ts.map +1 -1
  16. package/dist/device/Device.d.ts +2 -0
  17. package/dist/device/Device.d.ts.map +1 -1
  18. package/dist/device/DevicePool.d.ts.map +1 -1
  19. package/dist/events/logBlockEvent.d.ts.map +1 -1
  20. package/dist/index.d.ts +45 -4
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +2788 -2522
  23. package/dist/inject.d.ts.map +1 -1
  24. package/dist/types/api/btcDeriveContextHash.d.ts +10 -0
  25. package/dist/types/api/btcDeriveContextHash.d.ts.map +1 -0
  26. package/dist/types/api/export.d.ts +1 -0
  27. package/dist/types/api/export.d.ts.map +1 -1
  28. package/dist/types/api/index.d.ts +2 -0
  29. package/dist/types/api/index.d.ts.map +1 -1
  30. package/dist/types/device.d.ts +8 -0
  31. package/dist/types/device.d.ts.map +1 -1
  32. package/dist/utils/patch.d.ts +1 -1
  33. package/dist/utils/patch.d.ts.map +1 -1
  34. package/package.json +4 -4
  35. package/src/api/SearchDevices.ts +163 -7
  36. package/src/api/btc/BTCDeriveContextHash.ts +90 -0
  37. package/src/api/index.ts +1 -0
  38. package/src/api/protocol-v2/DeviceReboot.ts +2 -0
  39. package/src/core/index.ts +23 -7
  40. package/src/data/messages/messages.json +51 -0
  41. package/src/device/Device.ts +10 -0
  42. package/src/device/DevicePool.ts +12 -2
  43. package/src/events/logBlockEvent.ts +1 -0
  44. package/src/index.ts +1 -0
  45. package/src/inject.ts +2 -0
  46. package/src/types/api/btcDeriveContextHash.ts +15 -0
  47. package/src/types/api/export.ts +1 -0
  48. package/src/types/api/index.ts +2 -0
  49. package/src/types/device.ts +10 -0
package/README.md CHANGED
@@ -29,4 +29,31 @@ import Core from '@onekeyfe/hd-core';
29
29
  Documentation is available [Hardware SDK Getting Started](https://developer.onekey.so/en/hardware-sdk/getting-started)
30
30
 
31
31
  ## Examples
32
+
33
+ ### Babylon context hash
34
+
35
+ `btcDeriveContextHash(connectId, deviceId, params)` requires Classic 1s firmware
36
+ 3.21.0 or later and Protocol V1. It uses the existing wallet session and device
37
+ confirmation flow. Other device families and Protocol V2 are not supported.
38
+
39
+ ```typescript
40
+ const result = await HardwareSDK.btcDeriveContextHash(connectId, deviceId, {
41
+ path: "m/84'/0'/0'/0/0", // The currently selected Bitcoin key, not the IKM path.
42
+ appName: 'babylon-btc-vault',
43
+ context: 'deadbeef',
44
+ network: 'bitcoin-mainnet',
45
+ });
46
+ // result.payload.secret is a 32-byte value encoded as 64 lowercase hex characters.
47
+ ```
48
+
49
+ `appName` must contain 1–64 ASCII lowercase letters, digits or hyphens. `context`
50
+ must be lowercase hex without `0x`, containing 1–1024 decoded bytes. `network` is
51
+ required: `bitcoin-mainnet`, `bitcoin-testnet` (testnet3/testnet4), `bitcoin-signet`,
52
+ or `bitcoin-regtest`. The SDK infers the Bitcoin input script type from `path` and
53
+ encodes `appName` as ASCII bytes; the device performs the derivation internally.
54
+ Device rejection and unsupported firmware errors propagate through the normal
55
+ SDK response. Treat the returned secret as sensitive and do not log or persist it.
56
+
57
+ See the [Babylon specification](https://github.com/babylonlabs-io/babylon-toolkit/blob/main/docs/specs/derive-context-hash.md).
58
+
32
59
  // TODO: add example url
@@ -0,0 +1,200 @@
1
+ import { EDeviceType, EFirmwareType, HardwareErrorCode } from '@onekeyfe/hd-shared';
2
+
3
+ import BTCDeriveContextHash from '../src/api/btc/BTCDeriveContextHash';
4
+ import { findMethod } from '../src/api/utils';
5
+ import { getLogBlockLabel, getSafeLogPayload } from '../src/events/logBlockEvent';
6
+ import { createCoreApi } from '../src/inject';
7
+ import { Device } from '../src/device/Device';
8
+
9
+ import type { DeviceFirmwareRange } from '../src/types';
10
+
11
+ jest.mock('../src/data/config', () => ({
12
+ getSDKVersion: jest.fn(() => '1.0.0'),
13
+ DEFAULT_DOMAIN: 'https://jssdk.onekey.so/1.0.0/',
14
+ }));
15
+
16
+ const createMethod = (overrides: Record<string, unknown> = {}) =>
17
+ new BTCDeriveContextHash({
18
+ id: 1,
19
+ payload: {
20
+ method: 'btcDeriveContextHash',
21
+ path: "m/84'/0'/0'/0/0",
22
+ appName: 'test-app',
23
+ context: 'deadbeef',
24
+ network: 'bitcoin-mainnet',
25
+ ...overrides,
26
+ },
27
+ });
28
+
29
+ describe('btcDeriveContextHash', () => {
30
+ test('forwards the public API call through the existing dispatcher', async () => {
31
+ const call = jest
32
+ .fn()
33
+ .mockResolvedValue({ success: true, payload: { secret: '00'.repeat(32) } });
34
+ const api = createCoreApi(call);
35
+ const params = {
36
+ path: "m/84'/0'/0'/0/0",
37
+ appName: 'test-app',
38
+ context: 'deadbeef',
39
+ network: 'bitcoin-mainnet' as const,
40
+ };
41
+ await api.btcDeriveContextHash('connect-id', 'device-id', params);
42
+ expect(call).toHaveBeenCalledWith({
43
+ ...params,
44
+ connectId: 'connect-id',
45
+ deviceId: 'device-id',
46
+ method: 'btcDeriveContextHash',
47
+ });
48
+ });
49
+
50
+ test.each([
51
+ ['bitcoin-mainnet', 'BITCOIN_MAINNET'],
52
+ ['bitcoin-testnet', 'BITCOIN_TESTNET'],
53
+ ['bitcoin-signet', 'BITCOIN_SIGNET'],
54
+ ['bitcoin-regtest', 'BITCOIN_REGTEST'],
55
+ ])('maps %s and returns the device result', async (network, wireNetwork) => {
56
+ const method = createMethod({ network });
57
+ method.init();
58
+ const response = { secret: '00'.repeat(32) };
59
+ const typedCall = jest.fn().mockResolvedValue({ message: response });
60
+ method.device = { commands: { typedCall } } as unknown as Device;
61
+
62
+ await expect(method.run()).resolves.toBe(response);
63
+ expect(typedCall).toHaveBeenCalledWith(
64
+ 'BabylonDeriveContextHash',
65
+ 'BabylonDerivedContextHash',
66
+ {
67
+ address_n: [2147483732, 2147483648, 2147483648, 0, 0],
68
+ script_type: 'SPENDWITNESS',
69
+ app_name: '746573742d617070',
70
+ context: 'deadbeef',
71
+ network: wireNetwork,
72
+ }
73
+ );
74
+ });
75
+
76
+ test.each([
77
+ ["m/44'/0'/0'/0/0", 'SPENDADDRESS'],
78
+ ["m/49'/0'/0'/0/0", 'SPENDP2SHWITNESS'],
79
+ [[2147483734, 2147483648, 2147483648, 0, 0], 'SPENDTAPROOT'],
80
+ ])('uses the selected path script type for %s', (path, scriptType) => {
81
+ const method = createMethod({ path });
82
+ method.init();
83
+ expect(method.params.script_type).toBe(scriptType);
84
+ });
85
+
86
+ test('accepts the maximum app name and context sizes', () => {
87
+ const method = createMethod({ appName: 'a'.repeat(64), context: 'ab'.repeat(1024) });
88
+ expect(() => method.init()).not.toThrow();
89
+ expect(method.params.context).toHaveLength(2048);
90
+ });
91
+
92
+ test.each([
93
+ { appName: '' },
94
+ { appName: 'a'.repeat(65) },
95
+ { appName: 'Test-App' },
96
+ { appName: 'test_app' },
97
+ { appName: '你好' },
98
+ { appName: null },
99
+ { context: '' },
100
+ { context: 'abc' },
101
+ { context: 'DEADBEEF' },
102
+ { context: '0xdeadbeef' },
103
+ { context: 'gg' },
104
+ { context: 'ab'.repeat(1025) },
105
+ { context: null },
106
+ { network: '' },
107
+ { network: 'litecoin' },
108
+ { network: 'toString' },
109
+ { network: 1 },
110
+ { path: 'm' },
111
+ { path: "m/84x'/0'/0'/0/0" },
112
+ { path: "m/2147483648'/0'/0'/0/0" },
113
+ { path: [2147483732, 2147483648, 2147483648, 0, 0.5] },
114
+ { path: [2147483732, 2147483648, 2147483648, 0, 4294967296] },
115
+ ])('rejects invalid inputs before a device call: %j', overrides => {
116
+ expect(() => createMethod(overrides).init()).toThrow(
117
+ expect.objectContaining({ errorCode: HardwareErrorCode.CallMethodInvalidParameter })
118
+ );
119
+ });
120
+
121
+ test('rejects sparse numeric paths before a device call', () => {
122
+ const sparsePath = [2147483732, 2147483648, 2147483648, 0, 5];
123
+ delete sparsePath[3];
124
+
125
+ [Array<number>(3), sparsePath].forEach(path => {
126
+ expect(() => createMethod({ path }).init()).toThrow(
127
+ expect.objectContaining({ errorCode: HardwareErrorCode.CallMethodInvalidParameter })
128
+ );
129
+ });
130
+ });
131
+
132
+ test('registers the public method and restricts it to supported firmware and protocol', () => {
133
+ const method = findMethod({ id: 1, payload: { ...createMethod().payload } });
134
+ method.init();
135
+ expect(method).toBeInstanceOf(BTCDeriveContextHash);
136
+ expect(method.strictCheckDeviceSupport).toBe(true);
137
+ expect(() => method.assertProtocolSupported('V2', EFirmwareType.Universal)).toThrow(
138
+ expect.objectContaining({ errorCode: HardwareErrorCode.DeviceNotSupportMethod })
139
+ );
140
+ });
141
+
142
+ test.each([EDeviceType.Classic1s, EDeviceType.ClassicPure])(
143
+ 'resolves the firmware requirement for %s through the device support check',
144
+ deviceType => {
145
+ const method = createMethod();
146
+ const device = Object.create(Device.prototype) as Device;
147
+ device.getCurrentDeviceType = jest.fn(() => deviceType);
148
+ const range: DeviceFirmwareRange = method.getVersionRange();
149
+
150
+ expect(device.getCurrentMethodVersionRange(type => range[type])).toEqual({ min: '3.21.0' });
151
+ expect(() => method.assertProtocolSupported('V1', EFirmwareType.Universal)).not.toThrow();
152
+ }
153
+ );
154
+
155
+ test.each([EDeviceType.Classic, EDeviceType.Mini, EDeviceType.Touch, EDeviceType.Pro])(
156
+ 'keeps %s outside the supported firmware range',
157
+ deviceType => {
158
+ const method = createMethod();
159
+ const device = Object.create(Device.prototype) as Device;
160
+ device.getCurrentDeviceType = jest.fn(() => deviceType);
161
+ const range: DeviceFirmwareRange = method.getVersionRange();
162
+
163
+ expect(device.getCurrentMethodVersionRange(type => range[type])).toBeUndefined();
164
+ }
165
+ );
166
+
167
+ test('propagates device rejection without returning a secret', async () => {
168
+ const method = createMethod();
169
+ method.init();
170
+ const error = new Error('User rejected');
171
+ method.device = {
172
+ commands: { typedCall: jest.fn().mockRejectedValue(error) },
173
+ } as unknown as Device;
174
+ await expect(method.run()).rejects.toBe(error);
175
+ });
176
+
177
+ test.each([undefined, '00', '00'.repeat(33)])(
178
+ 'rejects malformed device responses',
179
+ async secret => {
180
+ const method = createMethod();
181
+ method.init();
182
+ method.device = {
183
+ commands: { typedCall: jest.fn().mockResolvedValue({ message: { secret } }) },
184
+ } as unknown as Device;
185
+ await expect(method.run()).rejects.toMatchObject({
186
+ errorCode: HardwareErrorCode.CallMethodError,
187
+ });
188
+ }
189
+ );
190
+
191
+ test('blocks API request and response payloads in logs', () => {
192
+ const request = { payload: { method: 'btcDeriveContextHash' } };
193
+ const label = getLogBlockLabel(request);
194
+ expect(label).toBe('btcDeriveContextHash');
195
+ expect(getSafeLogPayload({ payload: { secret: '00'.repeat(32) } }, label)).toEqual({
196
+ method: 'btcDeriveContextHash',
197
+ payload: '[REDACTED]',
198
+ });
199
+ });
200
+ });
@@ -363,11 +363,11 @@ describe('public device lifecycle events', () => {
363
363
 
364
364
  test('clears the cleanup barrier when its deadline expires', async () => {
365
365
  const realSetTimeout = setTimeout;
366
- jest
367
- .spyOn(global, 'setTimeout')
368
- .mockImplementation((callback, delay, ...args) =>
369
- realSetTimeout(callback, delay === 5_000 ? 0 : delay, ...args)
370
- );
366
+ const cleanupDeadline = createDeferred<() => void>();
367
+ jest.spyOn(global, 'setTimeout').mockImplementation((callback, delay, ...args) => {
368
+ if (delay === 5_000) cleanupDeadline.resolve(() => callback(...args));
369
+ return realSetTimeout(callback, delay, ...args);
370
+ });
371
371
  {
372
372
  jest.spyOn(DataManager, 'getSettings').mockReturnValue('react-native' as never);
373
373
  const acquire = jest.spyOn(Device.prototype, 'acquire').mockResolvedValue(undefined);
@@ -381,13 +381,15 @@ describe('public device lifecycle events', () => {
381
381
  type: IFRAME.CALL,
382
382
  payload: { method: 'getDeviceState', connectId: 'draining-device', connectProtocol: 'V2' },
383
383
  } as CoreMessage);
384
- setImmediate(() => cancel(context, 'draining-device'));
384
+ const expireCleanupDeadline = await cleanupDeadline.promise;
385
+ cancel(context, 'draining-device');
386
+ expireCleanupDeadline();
385
387
  await expect(result).resolves.toBeDefined();
386
- gate.resolve();
387
388
  await new Promise(resolve => {
388
389
  setImmediate(resolve);
389
390
  });
390
391
  expect(context.getPrePendingCallPromise('draining-device')).toBeUndefined();
392
+ gate.resolve();
391
393
  }
392
394
  });
393
395
 
@@ -712,6 +714,48 @@ describe('public device lifecycle events', () => {
712
714
  expect(() => JSON.stringify(disconnectMessage?.payload.device)).not.toThrow();
713
715
  });
714
716
 
717
+ test.each(['V1', 'V2'] as const)(
718
+ 'preserves the %s connection identity for a transport disconnect after wipe',
719
+ protocol => {
720
+ jest.spyOn(DataManager, 'getSettings').mockReturnValue('webusb' as never);
721
+ core = initCore();
722
+ initConnector();
723
+ const messages: CoreMessage[] = [];
724
+ core.on(CORE_EVENT, message => messages.push(message));
725
+ const device = createInitializedDevice(protocol);
726
+ const connectId = device.getConnectId();
727
+ DevicePool.devicesCache[connectId] = device;
728
+
729
+ device.invalidateAfterWipe();
730
+ expect(device.toMessageObject()).toBeNull();
731
+ DevicePool.emitter.emit(DEVICE.CONNECT, device);
732
+ expect(messages.some(message => message.type === DEVICE.CONNECT)).toBe(false);
733
+ DevicePool.emitter.emit(TRANSPORT_EVENT.DEVICE_DISCONNECT, { connectId });
734
+
735
+ const disconnects = messages.filter(message => message.type === DEVICE.DISCONNECT);
736
+ expect(disconnects).toHaveLength(1);
737
+ expect(disconnects[0].payload.device).toMatchObject({
738
+ connectId,
739
+ serialNo: 'SERIAL-001',
740
+ deviceId: 'wallet-device-id',
741
+ });
742
+ expect(() => JSON.stringify(disconnects[0].payload.device)).not.toThrow();
743
+
744
+ device.features = {
745
+ ...createInitializedDevice(protocol).features,
746
+ deviceId: 'new-device-id',
747
+ initialized: false,
748
+ mode: 'notInitialized',
749
+ } as never;
750
+ DevicePool.emitter.emit(TRANSPORT_EVENT.DEVICE_DISCONNECT, { connectId });
751
+ const nextDisconnects = messages.filter(message => message.type === DEVICE.DISCONNECT);
752
+ expect(nextDisconnects[1].payload.device).toMatchObject({
753
+ deviceId: 'new-device-id',
754
+ mode: 'notInitialized',
755
+ });
756
+ }
757
+ );
758
+
715
759
  test('treats an acquired BLE device as reusable until the transport disconnects', async () => {
716
760
  jest.spyOn(DataManager, 'getSettings').mockReturnValue('desktop-web-ble' as never);
717
761
  const device = createInitializedDevice('V2');
@@ -85,6 +85,56 @@ describe('DevicePool state lifecycle', () => {
85
85
  expect(result.deviceList).toEqual([device]);
86
86
  });
87
87
 
88
+ test.each([
89
+ ['V1', undefined],
90
+ ['V1', 'wipe-path'],
91
+ ['V2', undefined],
92
+ ['V2', 'wipe-path'],
93
+ ] as const)('rediscovers a wiped %s device with connect id %s', async (protocol, connectId) => {
94
+ const descriptor = { path: 'wipe-path', protocolType: protocol } as never;
95
+ const device = Device.fromDescriptor(descriptor);
96
+ device.features = {
97
+ protocol,
98
+ deviceType: protocol === 'V2' ? 'pro2' : 'classic',
99
+ deviceId: 'old-device-id',
100
+ serialNo: 'wipe-path',
101
+ initialized: true,
102
+ mode: 'normal',
103
+ } as never;
104
+ DevicePool.devicesCache = { 'wipe-path': device };
105
+ device.invalidateAfterWipe();
106
+ expect(device.toMessageObject()).toBeNull();
107
+ const connect = jest.spyOn(device, 'connect').mockResolvedValue(true);
108
+ const initialize = jest.spyOn(device, 'initialize').mockImplementation(() => {
109
+ device.features = {
110
+ protocol,
111
+ deviceType: protocol === 'V2' ? 'pro2' : 'classic',
112
+ deviceId: 'new-device-id',
113
+ serialNo: 'wipe-path',
114
+ initialized: false,
115
+ mode: 'notInitialized',
116
+ } as never;
117
+ return Promise.resolve();
118
+ });
119
+ const release = jest.spyOn(device, 'release').mockResolvedValue(undefined);
120
+
121
+ try {
122
+ const result = await DevicePool.getDevices([descriptor], connectId);
123
+ expect(initialize).toHaveBeenCalledTimes(1);
124
+ expect(connect).toHaveBeenCalledTimes(1);
125
+ expect(release).toHaveBeenCalledTimes(1);
126
+ expect(result.deviceList[0].toMessageObject()).toMatchObject({
127
+ deviceId: 'new-device-id',
128
+ mode: 'notInitialized',
129
+ features: { initialized: false },
130
+ });
131
+ await DevicePool.getDevices([descriptor], connectId);
132
+ expect(initialize).toHaveBeenCalledTimes(1);
133
+ } finally {
134
+ jest.restoreAllMocks();
135
+ }
136
+ });
137
+
88
138
  test('keeps a discovered device when its Protocol V2 label cannot be read', async () => {
89
139
  const labelError = new Error('settings unavailable');
90
140
  const getDeviceState = jest
@@ -1,5 +1,6 @@
1
1
  import { EDeviceType } from '@onekeyfe/hd-shared';
2
2
 
3
+ import DeviceReboot from '../src/api/protocol-v2/DeviceReboot';
3
4
  import { Device } from '../src/device/Device';
4
5
  import { UI_REQUEST } from '../src/events/ui-request';
5
6
 
@@ -25,6 +26,17 @@ const createBootloaderDevice = (protocolType: 'V1' | 'V2') => {
25
26
  };
26
27
 
27
28
  describe('Pro2 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
+
28
40
  test('blocks Protocol V2 methods that are not allowed in bootloader mode', () => {
29
41
  const device = createBootloaderDevice('V2');
30
42