@onekeyfe/hd-core 0.0.1

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 (329) hide show
  1. package/.eslintrc +6 -0
  2. package/README.md +3 -0
  3. package/dist/api/BTCGetAddress.d.ts +8 -0
  4. package/dist/api/BTCGetAddress.d.ts.map +1 -0
  5. package/dist/api/BTCGetPublicKey.d.ts +8 -0
  6. package/dist/api/BTCGetPublicKey.d.ts.map +1 -0
  7. package/dist/api/BTCSignMessage.d.ts +10 -0
  8. package/dist/api/BTCSignMessage.d.ts.map +1 -0
  9. package/dist/api/BTCSignTransaction.d.ts +17 -0
  10. package/dist/api/BTCSignTransaction.d.ts.map +1 -0
  11. package/dist/api/BTCVerifyMessage.d.ts +9 -0
  12. package/dist/api/BTCVerifyMessage.d.ts.map +1 -0
  13. package/dist/api/BaseMethod.d.ts +24 -0
  14. package/dist/api/BaseMethod.d.ts.map +1 -0
  15. package/dist/api/CheckBLEFirmwareRelease.d.ts +6 -0
  16. package/dist/api/CheckBLEFirmwareRelease.d.ts.map +1 -0
  17. package/dist/api/CheckFirmwareRelease.d.ts +6 -0
  18. package/dist/api/CheckFirmwareRelease.d.ts.map +1 -0
  19. package/dist/api/CheckTransportRelease.d.ts +6 -0
  20. package/dist/api/CheckTransportRelease.d.ts.map +1 -0
  21. package/dist/api/DeviceBackup.d.ts +9 -0
  22. package/dist/api/DeviceBackup.d.ts.map +1 -0
  23. package/dist/api/DeviceChangePin.d.ts +9 -0
  24. package/dist/api/DeviceChangePin.d.ts.map +1 -0
  25. package/dist/api/DeviceFlags.d.ts +9 -0
  26. package/dist/api/DeviceFlags.d.ts.map +1 -0
  27. package/dist/api/DeviceRebootToBootloader.d.ts +9 -0
  28. package/dist/api/DeviceRebootToBootloader.d.ts.map +1 -0
  29. package/dist/api/DeviceRecovery.d.ts +9 -0
  30. package/dist/api/DeviceRecovery.d.ts.map +1 -0
  31. package/dist/api/DeviceReset.d.ts +9 -0
  32. package/dist/api/DeviceReset.d.ts.map +1 -0
  33. package/dist/api/DeviceSettings.d.ts +9 -0
  34. package/dist/api/DeviceSettings.d.ts.map +1 -0
  35. package/dist/api/DeviceUpdateReboot.d.ts +9 -0
  36. package/dist/api/DeviceUpdateReboot.d.ts.map +1 -0
  37. package/dist/api/DeviceWipe.d.ts +9 -0
  38. package/dist/api/DeviceWipe.d.ts.map +1 -0
  39. package/dist/api/EVMGetAddress.d.ts +8 -0
  40. package/dist/api/EVMGetAddress.d.ts.map +1 -0
  41. package/dist/api/EVMGetPublicKey.d.ts +8 -0
  42. package/dist/api/EVMGetPublicKey.d.ts.map +1 -0
  43. package/dist/api/EVMSignMessage.d.ts +10 -0
  44. package/dist/api/EVMSignMessage.d.ts.map +1 -0
  45. package/dist/api/EVMSignMessageEIP712.d.ts +10 -0
  46. package/dist/api/EVMSignMessageEIP712.d.ts.map +1 -0
  47. package/dist/api/EVMSignTransaction.d.ts +20 -0
  48. package/dist/api/EVMSignTransaction.d.ts.map +1 -0
  49. package/dist/api/EVMSignTypedData.d.ts +18 -0
  50. package/dist/api/EVMSignTypedData.d.ts.map +1 -0
  51. package/dist/api/EVMVerifyMessage.d.ts +9 -0
  52. package/dist/api/EVMVerifyMessage.d.ts.map +1 -0
  53. package/dist/api/GetFeatures.d.ts +51 -0
  54. package/dist/api/GetFeatures.d.ts.map +1 -0
  55. package/dist/api/SearchDevices.d.ts +16 -0
  56. package/dist/api/SearchDevices.d.ts.map +1 -0
  57. package/dist/api/helpers/bigNumberUtils.d.ts +4 -0
  58. package/dist/api/helpers/bigNumberUtils.d.ts.map +1 -0
  59. package/dist/api/helpers/btc/signtx.d.ts +5 -0
  60. package/dist/api/helpers/btc/signtx.d.ts.map +1 -0
  61. package/dist/api/helpers/btc/signtxLegacy.d.ts +5 -0
  62. package/dist/api/helpers/btc/signtxLegacy.d.ts.map +1 -0
  63. package/dist/api/helpers/btcParamsUtils.d.ts +11 -0
  64. package/dist/api/helpers/btcParamsUtils.d.ts.map +1 -0
  65. package/dist/api/helpers/hexUtils.d.ts +7 -0
  66. package/dist/api/helpers/hexUtils.d.ts.map +1 -0
  67. package/dist/api/helpers/paramsValidator.d.ts +8 -0
  68. package/dist/api/helpers/paramsValidator.d.ts.map +1 -0
  69. package/dist/api/helpers/pathUtils.d.ts +12 -0
  70. package/dist/api/helpers/pathUtils.d.ts.map +1 -0
  71. package/dist/api/helpers/stringUtils.d.ts +2 -0
  72. package/dist/api/helpers/stringUtils.d.ts.map +1 -0
  73. package/dist/api/helpers/typeNameUtils.d.ts +9 -0
  74. package/dist/api/helpers/typeNameUtils.d.ts.map +1 -0
  75. package/dist/api/index.d.ts +27 -0
  76. package/dist/api/index.d.ts.map +1 -0
  77. package/dist/api/utils.d.ts +5 -0
  78. package/dist/api/utils.d.ts.map +1 -0
  79. package/dist/constants/errors.d.ts +25 -0
  80. package/dist/constants/errors.d.ts.map +1 -0
  81. package/dist/constants/index.d.ts +3 -0
  82. package/dist/constants/index.d.ts.map +1 -0
  83. package/dist/constants/ui-request.d.ts +13 -0
  84. package/dist/constants/ui-request.d.ts.map +1 -0
  85. package/dist/core/index.d.ts +14 -0
  86. package/dist/core/index.d.ts.map +1 -0
  87. package/dist/data/version.d.ts +3 -0
  88. package/dist/data/version.d.ts.map +1 -0
  89. package/dist/data-manager/CoinManager.d.ts +13 -0
  90. package/dist/data-manager/CoinManager.d.ts.map +1 -0
  91. package/dist/data-manager/DataManager.d.ts +17 -0
  92. package/dist/data-manager/DataManager.d.ts.map +1 -0
  93. package/dist/data-manager/TransportManager.d.ts +15 -0
  94. package/dist/data-manager/TransportManager.d.ts.map +1 -0
  95. package/dist/data-manager/connectSettings.d.ts +9 -0
  96. package/dist/data-manager/connectSettings.d.ts.map +1 -0
  97. package/dist/data-manager/index.d.ts +3 -0
  98. package/dist/data-manager/index.d.ts.map +1 -0
  99. package/dist/device/Device.d.ts +64 -0
  100. package/dist/device/Device.d.ts.map +1 -0
  101. package/dist/device/DeviceCommands.d.ts +35 -0
  102. package/dist/device/DeviceCommands.d.ts.map +1 -0
  103. package/dist/device/DeviceConnector.d.ts +28 -0
  104. package/dist/device/DeviceConnector.d.ts.map +1 -0
  105. package/dist/device/DeviceList.d.ts +12 -0
  106. package/dist/device/DeviceList.d.ts.map +1 -0
  107. package/dist/events/call.d.ts +41 -0
  108. package/dist/events/call.d.ts.map +1 -0
  109. package/dist/events/core.d.ts +16 -0
  110. package/dist/events/core.d.ts.map +1 -0
  111. package/dist/events/device.d.ts +23 -0
  112. package/dist/events/device.d.ts.map +1 -0
  113. package/dist/events/iframe.d.ts +24 -0
  114. package/dist/events/iframe.d.ts.map +1 -0
  115. package/dist/events/index.d.ts +8 -0
  116. package/dist/events/index.d.ts.map +1 -0
  117. package/dist/events/ui-promise.d.ts +12 -0
  118. package/dist/events/ui-promise.d.ts.map +1 -0
  119. package/dist/events/ui-request.d.ts +20 -0
  120. package/dist/events/ui-request.d.ts.map +1 -0
  121. package/dist/events/ui-response.d.ts +15 -0
  122. package/dist/events/ui-response.d.ts.map +1 -0
  123. package/dist/events/utils.d.ts +15 -0
  124. package/dist/events/utils.d.ts.map +1 -0
  125. package/dist/index.d.ts +823 -0
  126. package/dist/index.d.ts.map +1 -0
  127. package/dist/index.js +12396 -0
  128. package/dist/inject.d.ts +14 -0
  129. package/dist/inject.d.ts.map +1 -0
  130. package/dist/types/api/btcGetAddress.d.ts +14 -0
  131. package/dist/types/api/btcGetAddress.d.ts.map +1 -0
  132. package/dist/types/api/btcGetPublicKey.d.ts +13 -0
  133. package/dist/types/api/btcGetPublicKey.d.ts.map +1 -0
  134. package/dist/types/api/btcSignMessage.d.ts +9 -0
  135. package/dist/types/api/btcSignMessage.d.ts.map +1 -0
  136. package/dist/types/api/btcSignTransaction.d.ts +74 -0
  137. package/dist/types/api/btcSignTransaction.d.ts.map +1 -0
  138. package/dist/types/api/btcVerifyMessage.d.ts +10 -0
  139. package/dist/types/api/btcVerifyMessage.d.ts.map +1 -0
  140. package/dist/types/api/checkBLEFirmwareRelease.d.ts +4 -0
  141. package/dist/types/api/checkBLEFirmwareRelease.d.ts.map +1 -0
  142. package/dist/types/api/checkFirmwareRelease.d.ts +4 -0
  143. package/dist/types/api/checkFirmwareRelease.d.ts.map +1 -0
  144. package/dist/types/api/checkTransportRelease.d.ts +4 -0
  145. package/dist/types/api/checkTransportRelease.d.ts.map +1 -0
  146. package/dist/types/api/deviceBackup.d.ts +4 -0
  147. package/dist/types/api/deviceBackup.d.ts.map +1 -0
  148. package/dist/types/api/deviceChangePin.d.ts +7 -0
  149. package/dist/types/api/deviceChangePin.d.ts.map +1 -0
  150. package/dist/types/api/deviceFlags.d.ts +7 -0
  151. package/dist/types/api/deviceFlags.d.ts.map +1 -0
  152. package/dist/types/api/deviceRebootToBootloader.d.ts +4 -0
  153. package/dist/types/api/deviceRebootToBootloader.d.ts.map +1 -0
  154. package/dist/types/api/deviceRecovery.d.ts +15 -0
  155. package/dist/types/api/deviceRecovery.d.ts.map +1 -0
  156. package/dist/types/api/deviceReset.d.ts +16 -0
  157. package/dist/types/api/deviceReset.d.ts.map +1 -0
  158. package/dist/types/api/deviceSettings.d.ts +16 -0
  159. package/dist/types/api/deviceSettings.d.ts.map +1 -0
  160. package/dist/types/api/deviceUpdateReboot.d.ts +4 -0
  161. package/dist/types/api/deviceUpdateReboot.d.ts.map +1 -0
  162. package/dist/types/api/deviceWipe.d.ts +4 -0
  163. package/dist/types/api/deviceWipe.d.ts.map +1 -0
  164. package/dist/types/api/event.d.ts +4 -0
  165. package/dist/types/api/event.d.ts.map +1 -0
  166. package/dist/types/api/evmGetAddress.d.ts +11 -0
  167. package/dist/types/api/evmGetAddress.d.ts.map +1 -0
  168. package/dist/types/api/evmGetPublicKey.d.ts +11 -0
  169. package/dist/types/api/evmGetPublicKey.d.ts.map +1 -0
  170. package/dist/types/api/evmSignMessage.d.ts +8 -0
  171. package/dist/types/api/evmSignMessage.d.ts.map +1 -0
  172. package/dist/types/api/evmSignMessageEIP712.d.ts +9 -0
  173. package/dist/types/api/evmSignMessageEIP712.d.ts.map +1 -0
  174. package/dist/types/api/evmSignTransaction.d.ts +36 -0
  175. package/dist/types/api/evmSignTransaction.d.ts.map +1 -0
  176. package/dist/types/api/evmSignTypedData.d.ts +33 -0
  177. package/dist/types/api/evmSignTypedData.d.ts.map +1 -0
  178. package/dist/types/api/evmVerifyMessage.d.ts +9 -0
  179. package/dist/types/api/evmVerifyMessage.d.ts.map +1 -0
  180. package/dist/types/api/getFeatures.d.ts +4 -0
  181. package/dist/types/api/getFeatures.d.ts.map +1 -0
  182. package/dist/types/api/index.d.ts +66 -0
  183. package/dist/types/api/index.d.ts.map +1 -0
  184. package/dist/types/api/init.d.ts +3 -0
  185. package/dist/types/api/init.d.ts.map +1 -0
  186. package/dist/types/api/searchDevices.d.ts +4 -0
  187. package/dist/types/api/searchDevices.d.ts.map +1 -0
  188. package/dist/types/api/uiResponse.d.ts +3 -0
  189. package/dist/types/api/uiResponse.d.ts.map +1 -0
  190. package/dist/types/device.d.ts +29 -0
  191. package/dist/types/device.d.ts.map +1 -0
  192. package/dist/types/firmware.d.ts +37 -0
  193. package/dist/types/firmware.d.ts.map +1 -0
  194. package/dist/types/index.d.ts +6 -0
  195. package/dist/types/index.d.ts.map +1 -0
  196. package/dist/types/params.d.ts +16 -0
  197. package/dist/types/params.d.ts.map +1 -0
  198. package/dist/types/settings.d.ts +65 -0
  199. package/dist/types/settings.d.ts.map +1 -0
  200. package/dist/utils/assets.d.ts +3 -0
  201. package/dist/utils/assets.d.ts.map +1 -0
  202. package/dist/utils/deferred.d.ts +9 -0
  203. package/dist/utils/deferred.d.ts.map +1 -0
  204. package/dist/utils/deviceFeaturesUtils.d.ts +52 -0
  205. package/dist/utils/deviceFeaturesUtils.d.ts.map +1 -0
  206. package/dist/utils/findDefectiveBatchDevice.d.ts +3 -0
  207. package/dist/utils/findDefectiveBatchDevice.d.ts.map +1 -0
  208. package/dist/utils/index.d.ts +6 -0
  209. package/dist/utils/index.d.ts.map +1 -0
  210. package/dist/utils/logger.d.ts +24 -0
  211. package/dist/utils/logger.d.ts.map +1 -0
  212. package/dist/utils/networkUtils.d.ts +2 -0
  213. package/dist/utils/networkUtils.d.ts.map +1 -0
  214. package/dist/utils/promiseUtils.d.ts +2 -0
  215. package/dist/utils/promiseUtils.d.ts.map +1 -0
  216. package/dist/utils/versionUtils.d.ts +6 -0
  217. package/dist/utils/versionUtils.d.ts.map +1 -0
  218. package/package.json +39 -0
  219. package/src/api/BTCGetAddress.ts +71 -0
  220. package/src/api/BTCGetPublicKey.ts +70 -0
  221. package/src/api/BTCSignMessage.ts +40 -0
  222. package/src/api/BTCSignTransaction.ts +141 -0
  223. package/src/api/BTCVerifyMessage.ts +40 -0
  224. package/src/api/BaseMethod.ts +71 -0
  225. package/src/api/CheckBLEFirmwareRelease.ts +18 -0
  226. package/src/api/CheckFirmwareRelease.ts +15 -0
  227. package/src/api/CheckTransportRelease.ts +19 -0
  228. package/src/api/DeviceBackup.ts +12 -0
  229. package/src/api/DeviceChangePin.ts +22 -0
  230. package/src/api/DeviceFlags.ts +23 -0
  231. package/src/api/DeviceRebootToBootloader.ts +13 -0
  232. package/src/api/DeviceRecovery.ts +41 -0
  233. package/src/api/DeviceReset.ts +43 -0
  234. package/src/api/DeviceSettings.ts +45 -0
  235. package/src/api/DeviceUpdateReboot.ts +13 -0
  236. package/src/api/DeviceWipe.ts +12 -0
  237. package/src/api/EVMGetAddress.ts +54 -0
  238. package/src/api/EVMGetPublicKey.ts +58 -0
  239. package/src/api/EVMSignMessage.ts +40 -0
  240. package/src/api/EVMSignMessageEIP712.ts +40 -0
  241. package/src/api/EVMSignTransaction.ts +195 -0
  242. package/src/api/EVMSignTypedData.ts +212 -0
  243. package/src/api/EVMVerifyMessage.ts +33 -0
  244. package/src/api/GetFeatures.ts +12 -0
  245. package/src/api/SearchDevices.ts +40 -0
  246. package/src/api/helpers/bigNumberUtils.ts +58 -0
  247. package/src/api/helpers/btc/signtx.ts +232 -0
  248. package/src/api/helpers/btc/signtxLegacy.ts +205 -0
  249. package/src/api/helpers/btcParamsUtils.ts +57 -0
  250. package/src/api/helpers/hexUtils.ts +50 -0
  251. package/src/api/helpers/paramsValidator.ts +95 -0
  252. package/src/api/helpers/pathUtils.ts +111 -0
  253. package/src/api/helpers/stringUtils.ts +8 -0
  254. package/src/api/helpers/typeNameUtils.ts +132 -0
  255. package/src/api/index.ts +26 -0
  256. package/src/api/utils.ts +18 -0
  257. package/src/constants/errors.ts +47 -0
  258. package/src/constants/index.ts +2 -0
  259. package/src/constants/ui-request.ts +12 -0
  260. package/src/core/index.ts +305 -0
  261. package/src/data/coins/bitcoin.json +42 -0
  262. package/src/data/messages/messages.json +8658 -0
  263. package/src/data/version.ts +3 -0
  264. package/src/data-manager/CoinManager.ts +31 -0
  265. package/src/data-manager/DataManager.ts +148 -0
  266. package/src/data-manager/TransportManager.ts +87 -0
  267. package/src/data-manager/connectSettings.ts +109 -0
  268. package/src/data-manager/index.ts +2 -0
  269. package/src/device/Device.ts +411 -0
  270. package/src/device/DeviceCommands.ts +207 -0
  271. package/src/device/DeviceConnector.ts +173 -0
  272. package/src/device/DeviceList.ts +47 -0
  273. package/src/events/call.ts +72 -0
  274. package/src/events/core.ts +41 -0
  275. package/src/events/device.ts +28 -0
  276. package/src/events/iframe.ts +34 -0
  277. package/src/events/index.ts +7 -0
  278. package/src/events/ui-promise.ts +14 -0
  279. package/src/events/ui-request.ts +28 -0
  280. package/src/events/ui-response.ts +25 -0
  281. package/src/events/utils.ts +19 -0
  282. package/src/index.ts +29 -0
  283. package/src/inject.ts +103 -0
  284. package/src/types/api/btcGetAddress.ts +24 -0
  285. package/src/types/api/btcGetPublicKey.ts +19 -0
  286. package/src/types/api/btcSignMessage.ts +13 -0
  287. package/src/types/api/btcSignTransaction.ts +98 -0
  288. package/src/types/api/btcVerifyMessage.ts +14 -0
  289. package/src/types/api/checkBLEFirmwareRelease.ts +6 -0
  290. package/src/types/api/checkFirmwareRelease.ts +4 -0
  291. package/src/types/api/checkTransportRelease.ts +4 -0
  292. package/src/types/api/deviceBackup.ts +4 -0
  293. package/src/types/api/deviceChangePin.ts +11 -0
  294. package/src/types/api/deviceFlags.ts +11 -0
  295. package/src/types/api/deviceRebootToBootloader.ts +4 -0
  296. package/src/types/api/deviceRecovery.ts +19 -0
  297. package/src/types/api/deviceReset.ts +20 -0
  298. package/src/types/api/deviceSettings.ts +17 -0
  299. package/src/types/api/deviceUpdateReboot.ts +4 -0
  300. package/src/types/api/deviceWipe.ts +4 -0
  301. package/src/types/api/event.ts +8 -0
  302. package/src/types/api/evmGetAddress.ts +17 -0
  303. package/src/types/api/evmGetPublicKey.ts +17 -0
  304. package/src/types/api/evmSignMessage.ts +12 -0
  305. package/src/types/api/evmSignMessageEIP712.ts +13 -0
  306. package/src/types/api/evmSignTransaction.ts +43 -0
  307. package/src/types/api/evmSignTypedData.ts +40 -0
  308. package/src/types/api/evmVerifyMessage.ts +13 -0
  309. package/src/types/api/getFeatures.ts +4 -0
  310. package/src/types/api/index.ts +80 -0
  311. package/src/types/api/init.ts +3 -0
  312. package/src/types/api/searchDevices.ts +4 -0
  313. package/src/types/api/uiResponse.ts +3 -0
  314. package/src/types/device.ts +71 -0
  315. package/src/types/firmware.ts +40 -0
  316. package/src/types/global.d.ts +3 -0
  317. package/src/types/index.ts +5 -0
  318. package/src/types/params.ts +15 -0
  319. package/src/types/settings.ts +77 -0
  320. package/src/utils/assets.ts +5 -0
  321. package/src/utils/deferred.ts +35 -0
  322. package/src/utils/deviceFeaturesUtils.ts +49 -0
  323. package/src/utils/findDefectiveBatchDevice.ts +10 -0
  324. package/src/utils/index.ts +7 -0
  325. package/src/utils/logger.ts +113 -0
  326. package/src/utils/networkUtils.ts +18 -0
  327. package/src/utils/promiseUtils.ts +4 -0
  328. package/src/utils/versionUtils.ts +120 -0
  329. package/tsconfig.json +7 -0
@@ -0,0 +1,411 @@
1
+ import EventEmitter from 'events';
2
+ import { OneKeyDeviceInfo as DeviceDescriptor } from '@onekeyfe/hd-transport';
3
+
4
+ import DeviceConnector from './DeviceConnector';
5
+ import { DeviceCommands } from './DeviceCommands';
6
+
7
+ import { initLog, Deferred, create as createDeferred } from '../utils';
8
+ import {
9
+ getDeviceFirmwareVersion,
10
+ getDeviceLabel,
11
+ getDeviceType,
12
+ getDeviceUUID,
13
+ getDeviceBLEFirmwareVersion,
14
+ } from '../utils/deviceFeaturesUtils';
15
+ import type { Features, Device as DeviceTyped, UnavailableCapabilities } from '../types';
16
+ import { DEVICE, DeviceButtonRequestPayload } from '../events';
17
+ import { UI_REQUEST } from '../constants/ui-request';
18
+ import { ERRORS, PROTO } from '../constants';
19
+ import { DataManager } from '../data-manager';
20
+
21
+ type RunOptions = {
22
+ keepSession?: boolean;
23
+ };
24
+
25
+ const parseRunOptions = (options?: RunOptions): RunOptions => {
26
+ if (!options) options = {};
27
+ return options;
28
+ };
29
+
30
+ const Log = initLog('Device');
31
+
32
+ export interface DeviceEvents {
33
+ [DEVICE.PIN]: [Device, PROTO.PinMatrixRequestType | undefined, (err: any, pin: string) => void];
34
+ [DEVICE.PASSPHRASE_ON_DEVICE]: [Device, ((response: any) => void)?];
35
+ [DEVICE.BUTTON]: [Device, DeviceButtonRequestPayload];
36
+ }
37
+
38
+ export interface Device {
39
+ on<K extends keyof DeviceEvents>(type: K, listener: (...event: DeviceEvents[K]) => void): this;
40
+ off<K extends keyof DeviceEvents>(type: K, listener: (...event: DeviceEvents[K]) => void): this;
41
+ emit<K extends keyof DeviceEvents>(type: K, ...args: DeviceEvents[K]): boolean;
42
+ }
43
+
44
+ export class Device extends EventEmitter {
45
+ /**
46
+ * 设备标识对象
47
+ */
48
+ originalDescriptor: DeviceDescriptor;
49
+
50
+ /**
51
+ * 设备主 ID
52
+ * 蓝牙连接时是设备的 UUID
53
+ * USB连接时是设备的 sessionID
54
+ */
55
+ mainId?: string | null;
56
+
57
+ /**
58
+ * 通信管道,向设备发送请求
59
+ */
60
+ deviceConnector?: DeviceConnector | null = null;
61
+
62
+ /**
63
+ * 固件命令
64
+ */
65
+ // @ts-expect-error: strictPropertyInitialization
66
+ commands: DeviceCommands;
67
+
68
+ /**
69
+ * 设备信息
70
+ */
71
+ features: Features | undefined = undefined;
72
+
73
+ /**
74
+ * 是否需要更新设备信息
75
+ */
76
+ featuresNeedsReload = false;
77
+
78
+ runPromise?: Deferred<void> | null;
79
+
80
+ externalState: string[] = [];
81
+
82
+ unavailableCapabilities: UnavailableCapabilities = {};
83
+
84
+ instance = 0;
85
+
86
+ internalState: string[] = [];
87
+
88
+ loaded = false;
89
+
90
+ needReloadDevice = false;
91
+
92
+ /**
93
+ * 执行 API 方法后是否保留 SessionID
94
+ */
95
+ keepSession = false;
96
+
97
+ constructor(descriptor: DeviceDescriptor) {
98
+ super();
99
+ this.originalDescriptor = descriptor;
100
+ }
101
+
102
+ static fromDescriptor(originalDescriptor: DeviceDescriptor) {
103
+ const descriptor = { ...originalDescriptor };
104
+ return new Device(descriptor);
105
+ }
106
+
107
+ // simplified object to pass via postMessage
108
+ toMessageObject(): DeviceTyped | null {
109
+ if (this.isUnacquired() || !this.features) return null;
110
+
111
+ const env = DataManager.getSettings('env');
112
+
113
+ return {
114
+ /** Android uses Mac address, iOS uses uuid, USB uses uuid */
115
+ connectId: env === 'react-native' ? this.mainId || null : getDeviceUUID(this.features),
116
+ /** Hardware ID, will not change at any time */
117
+ uuid: getDeviceUUID(this.features),
118
+ deviceType: getDeviceType(this.features),
119
+ /** ID for current seeds, will clear after replace a new seed at device */
120
+ deviceId: this.features.device_id || null,
121
+ path: this.originalDescriptor.path,
122
+ label: getDeviceLabel(this.features),
123
+ mode: this.getMode(),
124
+ features: this.features,
125
+ firmwareVersion: this.getFirmwareVersion(),
126
+ bleFirmwareVersion: this.getBLEFirmwareVersion(),
127
+ unavailableCapabilities: this.unavailableCapabilities,
128
+ };
129
+ }
130
+
131
+ /**
132
+ * Device connect
133
+ * @returns {Promise<boolean>}
134
+ */
135
+ connect() {
136
+ const env = DataManager.getSettings('env');
137
+ // eslint-disable-next-line no-async-promise-executor
138
+ return new Promise<boolean>(async resolve => {
139
+ if (env === 'react-native') {
140
+ try {
141
+ await this.acquire();
142
+ resolve(true);
143
+ } catch (error) {
144
+ resolve(error);
145
+ }
146
+ return;
147
+ }
148
+ // 不存在 Session ID 或存在 Session ID 但设备在别处使用,都需要 acquire 获取最新 sessionID
149
+ if (!this.mainId || (!this.isUsedHere() && this.originalDescriptor)) {
150
+ try {
151
+ await this.acquire();
152
+ resolve(true);
153
+ } catch (error) {
154
+ resolve(error);
155
+ }
156
+ return;
157
+ }
158
+ if (this.isUsedHere()) {
159
+ resolve(true);
160
+ return;
161
+ }
162
+ resolve(false);
163
+ });
164
+ }
165
+
166
+ async acquire() {
167
+ const env = DataManager.getSettings('env');
168
+ const mainIdKey = env === 'react-native' ? 'id' : 'session';
169
+ try {
170
+ if (env === 'react-native') {
171
+ const res = await this.deviceConnector?.acquire(this.originalDescriptor.id);
172
+ this.mainId = (res as unknown as any).uuid ?? '';
173
+ Log.debug('Expected uuid:', this.mainId);
174
+ } else {
175
+ this.mainId = await this.deviceConnector?.acquire(
176
+ this.originalDescriptor.path,
177
+ this.originalDescriptor.session
178
+ );
179
+ Log.debug('Expected session id:', this.mainId);
180
+ }
181
+ this.updateDescriptor({ [mainIdKey]: this.mainId } as unknown as DeviceDescriptor);
182
+ if (this.commands) {
183
+ this.commands.dispose();
184
+ }
185
+
186
+ this.commands = new DeviceCommands(this, this.mainId ?? '');
187
+ } catch (error) {
188
+ if (this.runPromise) {
189
+ this.runPromise.reject(error);
190
+ } else {
191
+ throw error;
192
+ }
193
+ this.runPromise = null;
194
+ }
195
+ }
196
+
197
+ async release() {
198
+ const env = DataManager.getSettings('env');
199
+ if (
200
+ (this.isUsedHere() && !this.keepSession && this.mainId) ||
201
+ (this.mainId && env === 'react-native')
202
+ ) {
203
+ if (this.commands) {
204
+ this.commands.dispose();
205
+ if (this.commands.callPromise) {
206
+ try {
207
+ await this.commands.callPromise;
208
+ } catch (error) {
209
+ this.commands.callPromise = undefined;
210
+ }
211
+ }
212
+ }
213
+ try {
214
+ await this.deviceConnector?.release(this.mainId, false);
215
+ this.updateDescriptor({ session: null } as DeviceDescriptor);
216
+ } catch (err) {
217
+ Log.error('[Device] release error: ', err);
218
+ } finally {
219
+ this.needReloadDevice = true;
220
+ }
221
+ }
222
+ }
223
+
224
+ getInternalState() {
225
+ return this.internalState[this.instance];
226
+ }
227
+
228
+ async initialize() {
229
+ let payload: any;
230
+ if (this.features) {
231
+ const internalState = this.getInternalState();
232
+ payload = {};
233
+ if (internalState) {
234
+ payload.session_id = internalState;
235
+ }
236
+ }
237
+
238
+ const { message } = await this.commands.typedCall('Initialize', 'Features', payload);
239
+ this._updateFeatures(message);
240
+ }
241
+
242
+ async getFeatures() {
243
+ const { message } = await this.commands.typedCall('GetFeatures', 'Features', {});
244
+ this._updateFeatures(message);
245
+ }
246
+
247
+ _updateFeatures(feat: Features) {
248
+ // GetFeatures doesn't return 'session_id'
249
+ if (this.features && this.features.session_id && !feat.session_id) {
250
+ feat.session_id = this.features.session_id;
251
+ }
252
+ feat.unlocked = feat.unlocked || true;
253
+
254
+ this.features = feat;
255
+ this.featuresNeedsReload = false;
256
+ }
257
+
258
+ /**
259
+ * 暂时只在 acquire 后更新 Session ID
260
+ * 后续看是否有需要依据 listen 返回结果更新
261
+ * @param descriptor
262
+ */
263
+ updateDescriptor(descriptor: DeviceDescriptor) {
264
+ const env = DataManager.getSettings('env');
265
+ if (env === 'react-native') {
266
+ return;
267
+ }
268
+ const originalSession = this.originalDescriptor.session;
269
+ const upcomingSession = descriptor.session;
270
+
271
+ if (originalSession !== upcomingSession) {
272
+ this.originalDescriptor.session = upcomingSession;
273
+ }
274
+ }
275
+
276
+ async run(fn?: () => Promise<void>, options?: RunOptions) {
277
+ if (this.runPromise) {
278
+ Log.error('[Device] run error:', 'Device is running');
279
+ throw ERRORS.TypedError('Device_CallInProgress');
280
+ }
281
+
282
+ options = parseRunOptions(options);
283
+
284
+ this.runPromise = createDeferred(this._runInner.bind(this, fn, options));
285
+ return this.runPromise.promise;
286
+ }
287
+
288
+ async _runInner<T>(fn: (() => Promise<T>) | undefined, options: RunOptions) {
289
+ if (!this.isUsedHere() || this.commands.disposed) {
290
+ await this.acquire();
291
+ try {
292
+ if (fn) {
293
+ await this.initialize();
294
+ }
295
+ } catch (error) {
296
+ this.runPromise = null;
297
+ return Promise.reject(
298
+ ERRORS.TypedError(
299
+ 'Device_InitializeFailed',
300
+ `Initialize failed: ${error.message as string}, code: ${error.code as string}`
301
+ )
302
+ );
303
+ }
304
+ }
305
+
306
+ if (options.keepSession) {
307
+ this.keepSession = true;
308
+ }
309
+
310
+ if (fn) {
311
+ await fn();
312
+ }
313
+
314
+ // reload features
315
+ if (this.loaded && this.features) {
316
+ await this.getFeatures();
317
+ }
318
+
319
+ if (
320
+ (!this.keepSession && typeof options.keepSession !== 'boolean') ||
321
+ options.keepSession === false
322
+ ) {
323
+ this.keepSession = false;
324
+ await this.release();
325
+ Log.debug('release device, mainId: ', this.mainId);
326
+ }
327
+
328
+ if (this.runPromise) {
329
+ this.runPromise.resolve();
330
+ }
331
+
332
+ this.runPromise = null;
333
+
334
+ if (!this.loaded) {
335
+ this.loaded = true;
336
+ }
337
+ }
338
+
339
+ getMode() {
340
+ if (this.features?.bootloader_mode) return 'bootloader';
341
+ if (!this.features?.initialized) return 'initialize';
342
+ if (this.features?.no_backup) return 'seedless';
343
+ return 'normal';
344
+ }
345
+
346
+ getFirmwareVersion() {
347
+ if (!this.features) return null;
348
+ return getDeviceFirmwareVersion(this.features);
349
+ }
350
+
351
+ getBLEFirmwareVersion() {
352
+ if (!this.features) return null;
353
+ return getDeviceBLEFirmwareVersion(this.features);
354
+ }
355
+
356
+ isUsed() {
357
+ return typeof this.originalDescriptor.session === 'string';
358
+ }
359
+
360
+ isUsedHere() {
361
+ const env = DataManager.getSettings('env');
362
+ if (env === 'react-native') {
363
+ return false;
364
+ }
365
+ return this.isUsed() && this.originalDescriptor.session === this.mainId;
366
+ }
367
+
368
+ isUsedElsewhere(): boolean {
369
+ return this.isUsed() && !this.isUsedHere();
370
+ }
371
+
372
+ isBootloader() {
373
+ return this.features && !!this.features.bootloader_mode;
374
+ }
375
+
376
+ isInitialized() {
377
+ return this.features && !!this.features.initialized;
378
+ }
379
+
380
+ isSeedless() {
381
+ return this.features && !!this.features.no_backup;
382
+ }
383
+
384
+ isUnacquired(): boolean {
385
+ return this.features === undefined;
386
+ }
387
+
388
+ hasUnexpectedMode(allow: string[], require: string[]) {
389
+ // both allow and require cases might generate single unexpected mode
390
+ if (this.features) {
391
+ // allow cases
392
+ if (this.isBootloader() && !allow.includes(UI_REQUEST.BOOTLOADER)) {
393
+ return UI_REQUEST.BOOTLOADER;
394
+ }
395
+ if (!this.isInitialized() && !allow.includes(UI_REQUEST.INITIALIZE)) {
396
+ return UI_REQUEST.INITIALIZE;
397
+ }
398
+ if (this.isSeedless() && !allow.includes(UI_REQUEST.SEEDLESS)) {
399
+ return UI_REQUEST.SEEDLESS;
400
+ }
401
+
402
+ // require cases
403
+ if (!this.isBootloader() && require.includes(UI_REQUEST.BOOTLOADER)) {
404
+ return UI_REQUEST.NOT_IN_BOOTLOADER;
405
+ }
406
+ }
407
+ return null;
408
+ }
409
+ }
410
+
411
+ export default Device;
@@ -0,0 +1,207 @@
1
+ import type { Transport, Messages } from '@onekeyfe/hd-transport';
2
+ import TransportManager from '../data-manager/TransportManager';
3
+ import { ERRORS } from '../constants';
4
+ import { initLog } from '../utils';
5
+ import type { Device } from './Device';
6
+ import { DEVICE } from '../events';
7
+
8
+ type MessageType = Messages.MessageType;
9
+ type MessageKey = keyof MessageType;
10
+ export type TypedResponseMessage<T extends MessageKey> = {
11
+ type: T;
12
+ message: MessageType[T];
13
+ };
14
+ type TypedCallResponseMap = {
15
+ [K in keyof MessageType]: TypedResponseMessage<K>;
16
+ };
17
+ export type DefaultMessageResponse = TypedCallResponseMap[keyof MessageType];
18
+
19
+ export type PassphrasePromptResponse = {
20
+ passphrase?: string;
21
+ passphraseOnDevice?: boolean;
22
+ cache?: boolean;
23
+ };
24
+
25
+ const assertType = (res: DefaultMessageResponse, resType: string | string[]) => {
26
+ const splitResTypes = Array.isArray(resType) ? resType : resType.split('|');
27
+ if (!splitResTypes.includes(res.type)) {
28
+ throw ERRORS.TypedError(
29
+ 'Runtime',
30
+ `assertType: Response of unexpected type: ${res.type}. Should be ${resType as string}`
31
+ );
32
+ }
33
+ };
34
+
35
+ const Log = initLog('DeviceCommands');
36
+
37
+ export class DeviceCommands {
38
+ device: Device;
39
+
40
+ transport: Transport;
41
+
42
+ mainId: string;
43
+
44
+ disposed: boolean;
45
+
46
+ callPromise?: Promise<DefaultMessageResponse>;
47
+
48
+ _cancelableRequest?: (error?: any) => void;
49
+
50
+ constructor(device: Device, mainId: string) {
51
+ this.device = device;
52
+ this.mainId = mainId;
53
+ this.transport = TransportManager.getTransport();
54
+ this.disposed = false;
55
+ }
56
+
57
+ dispose() {
58
+ this.disposed = true;
59
+ this._cancelableRequest = undefined;
60
+ }
61
+
62
+ // Sends an async message to the opened device.
63
+ async call(
64
+ type: MessageKey,
65
+ msg: DefaultMessageResponse['message'] = {}
66
+ ): Promise<DefaultMessageResponse> {
67
+ console.log('[DeviceCommands] [call] Sending', type, this.transport);
68
+
69
+ try {
70
+ const promise = this.transport.call(this.mainId, type, msg) as any;
71
+ this.callPromise = promise;
72
+ const res = await promise;
73
+ Log.debug('[DeviceCommands] [call] Received', res.type);
74
+ return res;
75
+ } catch (error) {
76
+ Log.debug('[DeviceCommands] [call] Received error', error);
77
+ throw error;
78
+ }
79
+ }
80
+
81
+ typedCall<T extends MessageKey, R extends MessageKey[]>(
82
+ type: T,
83
+ resType: R,
84
+ msg?: MessageType[T]
85
+ ): Promise<TypedCallResponseMap[R[number]]>;
86
+
87
+ typedCall<T extends MessageKey, R extends MessageKey>(
88
+ type: T,
89
+ resType: R,
90
+ msg?: MessageType[T]
91
+ ): Promise<TypedResponseMessage<R>>;
92
+
93
+ async typedCall(
94
+ type: MessageKey,
95
+ resType: MessageKey | MessageKey[],
96
+ msg?: DefaultMessageResponse['message']
97
+ ) {
98
+ if (this.disposed) {
99
+ throw ERRORS.TypedError('Runtime', 'typedCall: DeviceCommands already disposed');
100
+ }
101
+
102
+ const response = await this._commonCall(type, msg);
103
+ try {
104
+ assertType(response, resType);
105
+ } catch (error) {
106
+ // handle possible race condition
107
+ // Bridge may have some unread message in buffer, read it
108
+ // await this.transport.read(this.mainId);
109
+ // throw error anyway, next call should be resolved properly
110
+ console.log('DeviceCommands typedcall error: ', error);
111
+ throw error;
112
+ }
113
+ return response;
114
+ }
115
+
116
+ async _commonCall(type: MessageKey, msg?: DefaultMessageResponse['message']) {
117
+ const resp = await this.call(type, msg);
118
+ return this._filterCommonTypes(resp);
119
+ }
120
+
121
+ _filterCommonTypes(res: DefaultMessageResponse): Promise<DefaultMessageResponse> {
122
+ console.log('_filterCommonTypes: ', res);
123
+ if (res.type === 'Failure') {
124
+ const { code } = res.message;
125
+ let { message } = res.message;
126
+ // Model One does not send any message in firmware update
127
+ if (code === 'Failure_FirmwareError' && !message) {
128
+ message = 'Firmware installation failed';
129
+ }
130
+ // Failure_ActionCancelled message could be also missing
131
+ if (code === 'Failure_ActionCancelled' && !message) {
132
+ message = 'Action cancelled by user';
133
+ }
134
+ // pass code and message from firmware error
135
+ return Promise.reject(
136
+ new ERRORS.OnekeyError(
137
+ (code as any) || 'Failure_UnknownCode',
138
+ message || 'Failure_UnknownMessage'
139
+ )
140
+ );
141
+ }
142
+
143
+ if (res.type === 'Features') {
144
+ return Promise.resolve(res);
145
+ }
146
+
147
+ if (res.type === 'ButtonRequest') {
148
+ if (res.message.code === 'ButtonRequest_PassphraseEntry') {
149
+ this.device.emit(DEVICE.PASSPHRASE_ON_DEVICE, this.device);
150
+ } else {
151
+ this.device.emit(DEVICE.BUTTON, this.device, res.message);
152
+ }
153
+ return this._commonCall('ButtonAck', {});
154
+ }
155
+
156
+ if (res.type === 'EntropyRequest') {
157
+ // TODO: EntropyRequest
158
+ }
159
+
160
+ if (res.type === 'PinMatrixRequest') {
161
+ return this._promptPin(res.message.type).then(
162
+ pin => {
163
+ if (pin === '@@ONEKEY_INPUT_PIN_IN_DEVICE') {
164
+ // @ts-expect-error
165
+ return this._commonCall('BixinPinInputOnDevice');
166
+ }
167
+ return this._commonCall('PinMatrixAck', { pin });
168
+ },
169
+ () => this._commonCall('Cancel', {})
170
+ );
171
+ }
172
+
173
+ if (res.type === 'PassphraseRequest') {
174
+ // TODO: PassphraseRequest
175
+ }
176
+
177
+ // TT fw lower than 2.3.0, device send his current state
178
+ // new passphrase design set this value from `features.session_id`
179
+ if (res.type === 'Deprecated_PassphraseStateRequest') {
180
+ // TODO: Deprecated_PassphraseStateRequest
181
+ }
182
+
183
+ if (res.type === 'WordRequest') {
184
+ // TODO: WordRequest
185
+ }
186
+ return Promise.resolve(res);
187
+ }
188
+
189
+ _promptPin(type?: Messages.PinMatrixRequestType) {
190
+ return new Promise<string>((resolve, reject) => {
191
+ if (this.device.listenerCount(DEVICE.PIN) > 0) {
192
+ this._cancelableRequest = reject;
193
+ this.device.emit(DEVICE.PIN, this.device, type, (err, pin) => {
194
+ this._cancelableRequest = undefined;
195
+ if (err) {
196
+ reject(err);
197
+ } else {
198
+ resolve(pin);
199
+ }
200
+ });
201
+ } else {
202
+ console.warn('[DeviceCommands] [call] PIN callback not configured, cancelling request');
203
+ reject(ERRORS.TypedError('Runtime', '_promptPin: PIN callback not configured'));
204
+ }
205
+ });
206
+ }
207
+ }