-
-
Notifications
You must be signed in to change notification settings - Fork 292
/
Copy pathDevice.ts
1220 lines (1023 loc) · 41.7 KB
/
Device.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// original file https://github.com/trezor/connect/blob/develop/src/js/device/Device.js
import { randomBytes } from 'crypto';
import {
versionUtils,
createDeferred,
Deferred,
TypedEmitter,
createTimeoutPromise,
isArrayMember,
serializeError,
} from '@trezor/utils';
import { Session } from '@trezor/transport';
import { TransportProtocol, v1 as v1Protocol } from '@trezor/protocol';
import { type Transport, type Descriptor, TRANSPORT_ERROR } from '@trezor/transport';
import { DeviceCommands } from './DeviceCommands';
import { PROTO, ERRORS, FIRMWARE } from '../constants';
import {
DEVICE,
DeviceButtonRequestPayload,
UI,
UiResponsePin,
UiResponsePassphrase,
UiResponseWord,
DeviceVersionChanged,
} from '../events';
import { getAllNetworks } from '../data/coinInfo';
import { DataManager } from '../data/DataManager';
import { getFirmwareStatus, getRelease, getReleases } from '../data/firmwareInfo';
import {
parseCapabilities,
getUnavailableCapabilities,
parseRevision,
ensureInternalModelFeature,
} from '../utils/deviceFeaturesUtils';
import { initLog } from '../utils/debug';
import {
Device as DeviceTyped,
DeviceFirmwareStatus,
DeviceStatus,
DeviceState,
Features,
ReleaseInfo,
UnavailableCapabilities,
FirmwareType,
VersionArray,
KnownDevice,
StaticSessionId,
FirmwareHashCheckResult,
FirmwareHashCheckError,
DeviceUniquePath,
DeviceModelInternal,
} from '../types';
import { models } from '../data/models';
import { getLanguage } from '../data/getLanguage';
import { checkFirmwareRevision } from './checkFirmwareRevision';
import { IStateStorage } from './StateStorage';
import type { PromptCallback } from './prompts';
import { calculateFirmwareHash, getBinaryOptional, stripFwHeaders } from '../api/firmware';
import { cancelPrompt } from './prompts';
// custom log
const _log = initLog('Device');
type RunOptions = {
// skipFinalReload - normally, after action, features are reloaded again
// because some actions modify the features
// but sometimes, you don't need that and can skip that
skipFinalReload?: boolean;
keepSession?: boolean;
useCardanoDerivation?: boolean;
};
export const GET_FEATURES_TIMEOUT = 3_000;
// Due to performance issues in suite-native during app start, original timeout is not sufficient.
export const GET_FEATURES_TIMEOUT_REACT_NATIVE = 20_000;
const parseRunOptions = (options?: RunOptions): RunOptions => {
if (!options) options = {};
return options;
};
export interface DeviceEvents {
[DEVICE.PIN]: (
device: Device,
type: PROTO.PinMatrixRequestType | undefined,
callback: PromptCallback<UiResponsePin['payload']>,
) => void;
[DEVICE.WORD]: (
device: Device,
type: PROTO.WordRequestType,
callback: PromptCallback<UiResponseWord['payload']>,
) => void;
[DEVICE.PASSPHRASE]: (
device: Device,
callback: PromptCallback<UiResponsePassphrase['payload']>,
) => void;
[DEVICE.PASSPHRASE_ON_DEVICE]: () => void;
[DEVICE.BUTTON]: (device: Device, payload: DeviceButtonRequestPayload) => void;
[DEVICE.FIRMWARE_VERSION_CHANGED]: (payload: DeviceVersionChanged['payload']) => void;
}
type DeviceLifecycle =
| typeof DEVICE.CONNECT
| typeof DEVICE.CONNECT_UNACQUIRED
| typeof DEVICE.DISCONNECT
| typeof DEVICE.CHANGED;
type DeviceLifecycleListener = (lifecycle: DeviceLifecycle) => void;
type DeviceParams = {
id: DeviceUniquePath;
transport: Transport;
descriptor: Descriptor;
listener: DeviceLifecycleListener;
};
/**
* @export
* @class Device
* @extends {EventEmitter}
*/
export class Device extends TypedEmitter<DeviceEvents> {
public readonly transport: Transport;
public readonly protocol: TransportProtocol;
public readonly transportPath;
private readonly transportSessionOwner;
private readonly transportDescriptorType;
private session;
private lastAcquiredHere;
/**
* descriptor was detected on transport layer but sending any messages (such as GetFeatures) to it failed either
* with some expected error, for example HID device, LIBUSB_ERROR, or it simply timeout out. such device can't be worked
* with and user needs to take some action. for example reconnect the device, update firmware or change transport type
*/
private unreadableError?: string;
// @ts-expect-error: strictPropertyInitialization
private _firmwareStatus: DeviceFirmwareStatus;
public get firmwareStatus() {
return this._firmwareStatus;
}
private _firmwareRelease?: ReleaseInfo | null;
public get firmwareRelease() {
return this._firmwareRelease;
}
// @ts-expect-error: strictPropertyInitialization
private _features: Features;
public get features() {
return this._features;
}
private _featuresNeedsReload = false;
// variables used in one workflow: acquire -> transportSession -> commands -> run -> keepTransportSession -> release
private acquirePromise?: ReturnType<Transport['acquire']>;
private releasePromise?: ReturnType<Transport['release']>;
private runPromise?: Deferred<void>;
private keepTransportSession = false;
public commands?: DeviceCommands;
private cancelableAction?: (err?: Error) => Promise<unknown>;
private loaded = false;
private inconsistent = false;
private firstRunPromise: Deferred<boolean>;
private instance = 0;
// DeviceState list [this.instance]: DeviceState | undefined
private state: DeviceState[] = [];
private stateStorage?: IStateStorage = undefined;
private _unavailableCapabilities: UnavailableCapabilities = {};
public get unavailableCapabilities(): Readonly<UnavailableCapabilities> {
return this._unavailableCapabilities;
}
private _firmwareType?: FirmwareType;
public get firmwareType() {
return this._firmwareType;
}
private name = 'Trezor';
private color?: string;
private availableTranslations: string[] = [];
private authenticityChecks: NonNullable<KnownDevice['authenticityChecks']> = {
firmwareRevision: null,
firmwareHash: null,
};
private readonly uniquePath;
private readonly emitLifecycle;
private sessionDfd?: Deferred<Session | null>;
constructor({ id, transport, descriptor, listener }: DeviceParams) {
super();
this.emitLifecycle = listener;
this.protocol = v1Protocol;
// === immutable properties
this.uniquePath = id;
this.transport = transport;
this.transportPath = descriptor.path;
this.transportSessionOwner = descriptor.sessionOwner;
this.transportDescriptorType = descriptor.type;
this.session = descriptor.session;
this.lastAcquiredHere = false;
// this will be released after first run
this.firstRunPromise = createDeferred();
}
private getSessionChangePromise() {
if (!this.sessionDfd) {
this.sessionDfd = createDeferred();
this.sessionDfd.promise
.catch(() => {}) // So there isn't potential unhandled reject
.finally(() => {
this.sessionDfd = undefined;
});
}
return this.sessionDfd.promise;
}
private async waitAndCompareSession<
T extends { success: true; payload: Session | null } | { success: false },
>(response: T, sessionPromise: Promise<Session | null>) {
if (response.success) {
try {
if ((await sessionPromise) !== response.payload) {
return {
success: false,
error: TRANSPORT_ERROR.SESSION_WRONG_PREVIOUS,
} as const;
}
} catch {
return {
success: false,
error: TRANSPORT_ERROR.DEVICE_DISCONNECTED_DURING_ACTION,
} as const;
}
}
return response;
}
acquire() {
const sessionPromise = this.getSessionChangePromise();
this.acquirePromise = this.transport
.acquire({ input: { path: this.transportPath, previous: this.session } })
.then(result => this.waitAndCompareSession(result, sessionPromise))
.then(result => {
if (result.success) {
this.session = result.payload;
this.lastAcquiredHere = true;
this.commands?.dispose();
this.commands = new DeviceCommands(this, this.transport, this.session);
return result;
} else {
if (this.runPromise) {
this.runPromise.reject(new Error(result.error));
delete this.runPromise;
}
throw result.error;
}
})
.finally(() => {
this.acquirePromise = undefined;
});
return this.acquirePromise;
}
async release() {
const localSession = this.getLocalSession();
if (!localSession || this.keepTransportSession || this.releasePromise) {
return;
}
if (this.commands) {
this.commands.dispose();
if (this.commands.callPromise) {
await this.commands.callPromise;
}
}
const sessionPromise = this.getSessionChangePromise();
this.releasePromise = this.transport
.release({ session: localSession, path: this.transportPath })
.then(result => this.waitAndCompareSession(result, sessionPromise))
.then(result => {
if (result.success) {
this.session = null;
}
return result;
})
.finally(() => {
this.releasePromise = undefined;
});
return this.releasePromise;
}
releaseTransportSession() {
this.keepTransportSession = false;
}
async cleanup(release = true) {
// remove all listeners
this.eventNames().forEach(e => this.removeAllListeners(e as keyof DeviceEvents));
// make sure that Device_CallInProgress will not be thrown
delete this.runPromise;
if (release) {
await this.release();
}
}
// call only once, right after device creation
async handshake(delay?: number) {
if (delay) {
await createTimeoutPromise(501 + delay);
}
while (true) {
if (this.isUsedElsewhere()) {
this.emitLifecycle(DEVICE.CONNECT_UNACQUIRED);
} else {
try {
await this.run();
} catch (error) {
_log.warn(`device.run error.message: ${error.message}, code: ${error.code}`);
if (
error.code === 'Device_NotFound' ||
error.message === TRANSPORT_ERROR.DEVICE_NOT_FOUND ||
error.message === TRANSPORT_ERROR.DEVICE_DISCONNECTED_DURING_ACTION ||
error.message === TRANSPORT_ERROR.DESCRIPTOR_NOT_FOUND ||
error.message === TRANSPORT_ERROR.HTTP_ERROR // bridge died during device initialization
) {
// disconnected, do nothing
} else if (
// we don't know what really happened
error.message === TRANSPORT_ERROR.UNEXPECTED_ERROR ||
// someone else took the device at the same time
error.message === TRANSPORT_ERROR.SESSION_WRONG_PREVIOUS ||
// device had some session when first seen -> we do not read it so that we don't interrupt somebody else's flow
error.code === 'Device_UsedElsewhere' ||
// TODO: is this needed? can't I just use transport error?
error.code === 'Device_InitializeFailed'
) {
this.emitLifecycle(DEVICE.CONNECT_UNACQUIRED);
} else if (
// device was claimed by another application on transport api layer (claimInterface in usb nomenclature) but never released (releaseInterface in usb nomenclature)
// the only remedy for this is to reconnect device manually
error.message === TRANSPORT_ERROR.INTERFACE_UNABLE_TO_OPEN_DEVICE ||
// catch one of trezord LIBUSB_ERRORs
error.message?.indexOf(ERRORS.LIBUSB_ERROR_MESSAGE) >= 0
) {
this.unreadableError = error?.message;
this.emitLifecycle(DEVICE.CONNECT_UNACQUIRED);
} else {
await createTimeoutPromise(501);
continue;
}
}
}
return;
}
}
async updateDescriptor(descriptor: Descriptor) {
this.sessionDfd?.resolve(descriptor.session);
await Promise.all([this.acquirePromise, this.releasePromise]);
// TODO improve these conditions
// Session changed to different than the current one
// -> acquired by someone else
if (descriptor.session && descriptor.session !== this.session) {
this.usedElsewhere();
}
// Session changed to null
// -> released
if (!descriptor.session) {
const methodStillRunning = !this.commands?.isDisposed();
if (methodStillRunning) {
this.releaseTransportSession();
}
}
this.session = descriptor.session;
this.emitLifecycle(DEVICE.CHANGED);
}
// TODO empty fn variant can be split/removed
run(fn?: () => Promise<void>, options?: RunOptions) {
if (this.runPromise) {
_log.warn('Previous call is still running');
throw ERRORS.TypedError('Device_CallInProgress');
}
options = parseRunOptions(options);
const wasUnacquired = this.isUnacquired();
const runPromise = createDeferred();
this.runPromise = runPromise;
this._runInner(fn, options)
.then(() => {
if (wasUnacquired && !this.isUnacquired()) {
this.emitLifecycle(DEVICE.CONNECT);
}
})
.catch(err => {
runPromise.reject(err);
});
return runPromise.promise;
}
async override(error: Error) {
if (this.acquirePromise) {
await this.acquirePromise;
}
if (this.runPromise) {
await this.interruptionFromUser(error);
}
if (this.releasePromise) {
await this.releasePromise;
}
}
setCancelableAction(callback: NonNullable<typeof this.cancelableAction>) {
this.cancelableAction = (e?: Error) =>
callback(e)
.catch(e2 => {
_log.debug('cancelableAction error', e2);
})
.finally(() => {
this.clearCancelableAction();
});
}
clearCancelableAction() {
this.cancelableAction = undefined;
}
async interruptionFromUser(error: Error) {
_log.debug('interruptionFromUser');
await this.cancelableAction?.(error);
await this.commands?.cancel();
if (this.runPromise) {
// reject inner defer
this.runPromise.reject(error);
delete this.runPromise;
}
}
public usedElsewhere() {
// only makes sense to continue when device held by this instance
if (!this.lastAcquiredHere) {
return;
}
this.lastAcquiredHere = false;
this._featuresNeedsReload = true;
_log.debug('interruptionFromOutside');
if (this.commands) {
this.commands.dispose();
}
if (this.runPromise) {
this.runPromise.reject(ERRORS.TypedError('Device_UsedElsewhere'));
delete this.runPromise;
}
// session was acquired by another instance. but another might not have power to release interface
// so it only notified about its session acquiral and the interrupted instance should cooperate
// and release device too.
if (this.session) {
this.transport.releaseDevice(this.session);
}
}
private async _runInner<X>(
fn: (() => Promise<X>) | undefined,
options: RunOptions,
): Promise<void> {
// typically when using cancel/override, device might be releasing
// note: I am tempted to do this check at the beginning of device.acquire but on the other hand I would like
// to have methods as atomic as possible and shift responsibility for deciding when to call them on the caller
if (this.releasePromise) {
await this.releasePromise;
}
const acquireNeeded = !this.isUsedHere() || this.commands?.disposed;
if (acquireNeeded) {
// acquire session
await this.acquire();
}
const { staticSessionId, deriveCardano } = this.getState() || {};
if (acquireNeeded || !staticSessionId || (!deriveCardano && options.useCardanoDerivation)) {
// update features
try {
if (fn) {
await this.initialize(!!options.useCardanoDerivation);
} else {
const getFeaturesTimeout =
DataManager.getSettings('env') === 'react-native'
? GET_FEATURES_TIMEOUT_REACT_NATIVE
: GET_FEATURES_TIMEOUT;
let getFeaturesTimeoutId: ReturnType<typeof setTimeout> | undefined;
// do not initialize while firstRunPromise otherwise `features.session_id` could be affected
await Promise.race([
this.getFeatures().finally(() => clearTimeout(getFeaturesTimeoutId)),
// note: tested on 24.7.2024 and whatever is written below this line is still valid
// We do not support T1B1 <1.9.0 but we still need Features even from not supported devices to determine your version
// and tell you that update is required.
// Edge-case: T1B1 + bootloader < 1.4.0 doesn't know the "GetFeatures" message yet and it will send no response to its
// transport response is pending endlessly, calling any other message will end up with "device call in progress"
// set the timeout for this call so whenever it happens "unacquired device" will be created instead
// next time device should be called together with "Initialize" (calling "acquireDevice" from the UI)
new Promise((_resolve, reject) => {
getFeaturesTimeoutId = setTimeout(() => {
cancelPrompt(this, false).finally(() => {
reject(new Error('GetFeatures timeout'));
});
}, getFeaturesTimeout);
}),
]);
}
} catch (error) {
_log.warn('Device._runInner error: ', error.message);
if (
!this.inconsistent &&
(error.message === 'GetFeatures timeout' || error.message === 'Unknown message')
) {
// handling corner-case T1B1 + bootloader < 1.4.0 (above)
// if GetFeatures fails try again
// this time add empty "fn" param to force Initialize message
this.inconsistent = true;
return this._runInner(() => Promise.resolve({}), options);
}
if (TRANSPORT_ERROR.ABORTED_BY_TIMEOUT === error.message) {
this.unreadableError = 'Connection timeout';
}
this.inconsistent = true;
delete this.runPromise;
return Promise.reject(
ERRORS.TypedError(
'Device_InitializeFailed',
`Initialize failed: ${error.message}${
error.code ? `, code: ${error.code}` : ''
}`,
),
);
}
}
await this.checkFirmwareHashWithRetries();
await this.checkFirmwareRevisionWithRetries();
if (
this.features?.language &&
!this.features.language_version_matches &&
this.atLeast('2.7.0')
) {
_log.info('language version mismatch. silently updating...');
try {
await this.changeLanguage({ language: this.features.language });
} catch (err) {
_log.error('change language failed silently', err);
}
}
// if keepSession is set do not release device
// until method with keepSession: false will be called
if (options.keepSession) {
this.keepTransportSession = true;
}
// call inner function
if (fn) {
await fn();
}
// reload features
if (this.loaded && this.features && !options.skipFinalReload) {
await this.getFeatures();
}
if (
(!this.keepTransportSession && typeof options.keepSession !== 'boolean') ||
options.keepSession === false
) {
this.keepTransportSession = false;
await this.release();
}
if (this.runPromise) {
this.runPromise.resolve();
}
delete this.runPromise;
if (!this.loaded) {
this.loaded = true;
this.firstRunPromise.resolve(true);
}
}
getCommands() {
if (!this.commands) {
throw ERRORS.TypedError('Runtime', `Device: commands not defined`);
}
return this.commands;
}
setInstance(instance = 0) {
if (this.instance !== instance) {
// if requested instance is different than current
// and device wasn't released in previous call (example: interrupted discovery which set "keepSession" to true but never released)
// clear "keepTransportSession" and reset "transportSession" to ensure that "initialize" will be called
if (this.keepTransportSession) {
this.lastAcquiredHere = false;
this.keepTransportSession = false;
}
}
this.instance = instance;
}
getInstance() {
return this.instance;
}
getState(): DeviceState | undefined {
return this.state[this.instance];
}
setState(state?: Partial<DeviceState>) {
if (!state) {
delete this.state[this.instance];
} else {
const prevState = this.state[this.instance];
const newState = {
...prevState,
...state,
};
this.state[this.instance] = newState;
this.stateStorage?.saveState(this, newState);
}
}
async validateState(preauthorized = false) {
if (!this.features) return;
if (!this.features.unlocked && preauthorized) {
// NOTE: auto locked device accepts preauthorized methods (authorizeConjoin, getOwnershipProof, signTransaction) without pin request.
// in that case it's enough to check if session_id is preauthorized...
if (await this.getCommands().preauthorize(false)) {
return;
}
// ...and if it's not then unlock device and proceed to regular GetAddress flow
}
const expectedState = this.getState()?.staticSessionId;
const state = await this.getCommands().getDeviceState();
const uniqueState: StaticSessionId = `${state}@${this.features.device_id}:${this.instance}`;
if (this.features.session_id) {
this.setState({ sessionId: this.features.session_id });
}
if (expectedState && expectedState !== uniqueState) {
return uniqueState;
}
if (!expectedState) {
this.setState({ staticSessionId: uniqueState });
}
}
async initialize(useCardanoDerivation: boolean) {
let payload: PROTO.Initialize | undefined;
if (this.features) {
const { sessionId, deriveCardano } = this.getState() || {};
// If the user has BIP-39 seed, and Initialize(derive_cardano=True) is not sent,
// all Cardano calls will fail because the root secret will not be available.
payload = {
derive_cardano: deriveCardano || useCardanoDerivation,
};
if (sessionId) {
payload.session_id = sessionId;
}
}
const { message } = await this.getCommands().typedCall('Initialize', 'Features', payload);
this._updateFeatures(message);
this.setState({ deriveCardano: payload?.derive_cardano });
}
initStorage(storage: IStateStorage) {
this.stateStorage = storage;
this.setState(storage.loadState(this));
}
async getFeatures() {
// Please keep the method simple - don't add any async logic
const { message } = await this.getCommands().typedCall('GetFeatures', 'Features', {});
this._updateFeatures(message);
}
private async checkFirmwareHashWithRetries() {
const lastResult = this.authenticityChecks.firmwareHash;
const notDoneYet = lastResult === null;
const attemptsDone = lastResult?.attemptCount ?? 0;
if (attemptsDone >= FIRMWARE.HASH_CHECK_MAX_ATTEMPTS) return;
const wasError = lastResult !== null && !lastResult.success;
const wasErrorRetriable =
wasError && isArrayMember(lastResult.error, FIRMWARE.HASH_CHECK_RETRIABLE_ERRORS);
const lastErrorPayload = wasError ? lastResult?.errorPayload : null;
if (notDoneYet || wasErrorRetriable) {
const result = await this.checkFirmwareHash();
this.authenticityChecks.firmwareHash = result;
if (result === null) return;
result.attemptCount = attemptsDone + 1;
// if it suceeeded only after a retry, and there was an `errorPayload` previously, we want to pass that information to suite
if (result.success && lastErrorPayload) {
result.warningPayload = { lastErrorPayload, successOnAttempt: result.attemptCount };
}
}
}
private async checkFirmwareHash(): Promise<FirmwareHashCheckResult | null> {
const createFailResult = (error: FirmwareHashCheckError, errorPayload?: unknown) => ({
success: false,
error,
errorPayload,
});
const baseUrl = DataManager.getSettings('binFilesBaseUrl');
const enabled = DataManager.getSettings('enableFirmwareHashCheck');
if (!enabled || baseUrl === undefined) return createFailResult('check-skipped');
const firmwareVersion = this.getVersion();
// device has no features (not yet connected) or no firmware
if (firmwareVersion === undefined || !this.features || this.features.bootloader_mode) {
return null;
}
const checkSupported = this.atLeast(FIRMWARE.FW_HASH_SUPPORTED_VERSIONS);
if (!checkSupported) return createFailResult('check-unsupported');
const release = getReleases(this.features.internal_model).find(r =>
versionUtils.isEqual(r.version, firmwareVersion),
);
// if version is expected to support hash check, but the release is unknown, then firmware is considered unofficial
if (release === undefined) return createFailResult('unknown-release');
const btcOnly = this.firmwareType === FirmwareType.BitcoinOnly;
const binary = await getBinaryOptional({ baseUrl, btcOnly, release });
// release was found, but not its binary - happens on desktop, where only local files are searched
if (binary === null) {
return createFailResult('check-unsupported');
}
// binary was found, but it's likely a git LFS pointer (can happen on dev) - see onCallFirmwareUpdate.ts
if (binary.byteLength < 200) {
_log.warn(`Firmware binary for hash check suspiciously small (< 200 b)`);
return createFailResult('check-unsupported');
}
const strippedBinary = stripFwHeaders(binary);
const { hash: expectedHash, challenge } = calculateFirmwareHash(
this.features.major_version,
strippedBinary,
randomBytes(32),
);
// handle rejection of call by a counterfeit device. If unhandled, it crashes device initialization,
// so device can't be used, but it's preferable to display proper message about counterfeit device
try {
const deviceResponse = await this.getCommands().typedCall(
'GetFirmwareHash',
'FirmwareHash',
{ challenge },
);
if (!deviceResponse?.message?.hash) {
return createFailResult('other-error', 'Device response is missing hash');
}
if (deviceResponse.message.hash !== expectedHash) {
return createFailResult('hash-mismatch');
}
return { success: true };
} catch (errorPayload) {
return createFailResult('other-error', serializeError(errorPayload));
}
}
private async checkFirmwareRevisionWithRetries() {
const lastResult = this.authenticityChecks.firmwareRevision;
const notDoneYet = lastResult === null;
const wasError = lastResult !== null && !lastResult.success;
const wasErrorRetriable =
wasError && isArrayMember(lastResult.error, FIRMWARE.REVISION_CHECK_RETRIABLE_ERRORS);
if (notDoneYet || wasErrorRetriable) {
await this.checkFirmwareRevision();
}
}
private async checkFirmwareRevision() {
const firmwareVersion = this.getVersion();
if (!firmwareVersion || !this.features) {
return; // This happens when device has no features (not yet connected)
}
if (this.features.bootloader_mode === true) {
return;
}
const releases = getReleases(this.features.internal_model);
const release = releases.find(
r =>
firmwareVersion &&
versionUtils.isVersionArray(firmwareVersion) &&
versionUtils.isEqual(r.version, firmwareVersion),
);
this.authenticityChecks.firmwareRevision = await checkFirmwareRevision({
internalModel: this.features.internal_model,
deviceRevision: this.features.revision,
firmwareVersion,
expectedRevision: release?.firmware_revision,
});
}
async changeLanguage({
language,
binary,
}: { language?: undefined; binary: ArrayBuffer } | { language: string; binary?: undefined }) {
if (language === 'en-US') {
return this._uploadTranslationData(null);
}
if (binary) {
return this._uploadTranslationData(binary);
}
const version = this.getVersion();
if (!version) {
throw ERRORS.TypedError('Runtime', 'changeLanguage: device version unknown');
}
const downloadedBinary = await getLanguage({
language,
version,
internal_model: this.features.internal_model,
});
if (!downloadedBinary) {
throw ERRORS.TypedError('Runtime', 'changeLanguage: translation not found');
}
return this._uploadTranslationData(downloadedBinary);
}
private async _uploadTranslationData(payload: ArrayBuffer | null) {
if (!this.commands) {
throw ERRORS.TypedError('Runtime', 'uploadTranslationData: device.commands is not set');
}
if (payload === null) {
const response = await this.commands.typedCall(
'ChangeLanguage',
['Success'],
{ data_length: 0 }, // For en-US where we just send `ChangeLanguage(size=0)`
);
return response.message;
}
const length = payload.byteLength;
let response = await this.commands.typedCall(
'ChangeLanguage',
['TranslationDataRequest', 'Success'],
{ data_length: length },
);
while (response.type !== 'Success') {
const start = response.message.data_offset!;
const end = response.message.data_offset! + response.message.data_length!;
const chunk = payload.slice(start, end);
response = await this.commands.typedCall(
'TranslationDataAck',
['TranslationDataRequest', 'Success'],
{
data_chunk: Buffer.from(chunk).toString('hex'),
},
);
}
return response.message;
}
private _updateFeatures(feat: Features) {
const capabilities = parseCapabilities(feat);
feat.capabilities = capabilities;
// GetFeatures doesn't return 'session_id'
if (this.features && this.features.session_id && !feat.session_id) {
feat.session_id = this.features.session_id;
}
feat.unlocked = feat.unlocked ?? true;
// fix inconsistency of revision attribute between T1B1 and old T2T1 fw
const revision = parseRevision(feat);
feat.revision = revision;
// Fix missing model and internal_model in older fw, model has to be fixed first
// 1. - old T1B1 is missing features.model
if (!feat.model && feat.major_version === 1) {
feat.model = '1';
}
// 2. - old fw does not include internal_model. T1B1 does not report it yet, T2T1 starts in 2.6.0
// - or reported internal_model is not known to connect
if (!feat.internal_model || !DeviceModelInternal[feat.internal_model]) {
feat.internal_model = ensureInternalModelFeature(feat.model);
}
const version = this.getVersion();
const newVersion = [
feat.major_version,
feat.minor_version,
feat.patch_version,
] satisfies VersionArray;
// check if FW version or capabilities did change
if (!version || !versionUtils.isEqual(version, newVersion)) {
if (version) {
this.emit(DEVICE.FIRMWARE_VERSION_CHANGED, {
oldVersion: version,
newVersion,
device: this.toMessageObject(),
});
}
this._unavailableCapabilities = getUnavailableCapabilities(feat, getAllNetworks());
this._firmwareStatus = getFirmwareStatus(feat);
this._firmwareRelease = getRelease(feat);
this.availableTranslations = this.firmwareRelease?.translations ?? [];
}
this._features = feat;
this._featuresNeedsReload = false;
// Vendor headers have been changed in 2.6.3.
if (feat.fw_vendor === 'Trezor Bitcoin-only') {