forked from LedgerHQ/ledger-live-common
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logic.ts
532 lines (489 loc) · 15.4 KB
/
logic.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
import { $Shape } from "utility-types";
import { Subject } from "rxjs";
import flatMap from "lodash/flatMap";
import invariant from "invariant";
import semver from "semver";
import { getDeviceModel } from "@ledgerhq/devices";
import type { App } from "../types/manager";
import type {
AppOp,
State,
Action,
ListAppsResult,
AppsDistribution,
} from "./types";
import {
findCryptoCurrency,
findCryptoCurrencyById,
isCurrencySupported,
} from "../currencies";
import { LatestFirmwareVersionRequired } from "../errors";
export const initState = (
{
deviceModelId,
appsListNames,
installed,
appByName,
...listAppsResult
}: ListAppsResult,
appsToRestore?: string[]
): State => {
let state: State = {
...listAppsResult,
installed,
appByName,
apps: appsListNames.map((name) => appByName[name]).filter(Boolean),
deviceModel: getDeviceModel(deviceModelId),
recentlyInstalledApps: [],
installQueue: [],
uninstallQueue: [],
updateAllQueue: [],
currentProgressSubject: new Subject(),
currentError: null,
currentAppOp: null,
};
if (appsToRestore) {
state = appsToRestore
.filter(
(name) => appByName[name] && !installed.some((a) => a.name === name)
)
.map(
(name) =>
<Action>{
type: "install",
name,
}
)
.reduce(reducer, state);
}
return state;
};
// ^TODO move this to legacyDependencies.js
// we should have dependency as part of the data!
const reorderInstallQueue = (
appByName: Record<string, App>,
apps: string[]
): string[] => {
const list: string[] = [];
apps.forEach((app) => {
if (list.includes(app)) return;
if (app in appByName) {
const deps = appByName[app].dependencies;
deps.forEach((dep) => {
if (apps.includes(dep) && !list.includes(dep)) {
list.push(dep);
}
});
}
list.push(app);
});
return list;
};
const reorderUninstallQueue = (
appByName: Record<string, App>,
apps: string[]
): string[] =>
reorderInstallQueue(appByName, apps.slice(0).reverse()).reverse();
const findDependents = (
appByName: Record<string, App>,
name: string
): string[] => {
const all: string[] = [];
for (const k in appByName) {
const app = appByName[k];
if (app.dependencies.includes(name)) {
all.push(app.name);
}
}
return all;
};
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "onRunnerEvent": {
// an app operation was correctly prefered. update state accordingly
const { event } = action;
const { appOp } = event;
if (event.type === "runStart") {
return {
...state,
currentAppOp: appOp,
currentProgressSubject: new Subject(),
};
} else if (event.type === "runSuccess") {
if (state.currentProgressSubject) {
state.currentProgressSubject.complete();
}
let nextState;
if (appOp.type === "install") {
const app = state.apps.find((a) => a.name === appOp.name);
nextState = {
...state,
currentAppOp: null,
currentProgressSubject: null,
currentError: null,
recentlyInstalledApps: state.recentlyInstalledApps.concat(
appOp.name
),
// append the app to known installed apps
installed: state.installed
.filter((o) => o.name !== appOp.name)
.concat({
name: appOp.name,
updated: true,
hash: app ? app.hash : "",
blocks:
app && app.bytes
? Math.ceil(app.bytes / getBlockSize(state))
: 0,
version: app ? app.version : "",
availableVersion: app ? app.version : "",
}),
// remove the install action
installQueue: state.installQueue.filter(
(name) => appOp.name !== name
),
};
} else {
nextState = {
...state,
currentAppOp: null,
currentProgressSubject: null,
currentError: null,
// remove apps to known installed apps
installed: state.installed.filter((i) => appOp.name !== i.name),
// remove the uninstall action
uninstallQueue: state.uninstallQueue.filter(
(name) => appOp.name !== name
),
};
}
if (
nextState.installQueue.length + nextState.uninstallQueue.length ===
0
) {
nextState.updateAllQueue = [];
}
return nextState;
} else if (event.type === "runError") {
// TO BE CONTINUED LL-2138
// to handle recovering from error. however we are not correctly using it at the moment.
/*
const error = event.error;
if (error instanceof ManagerDeviceLockedError) {
return {
...state,
currentError: {
appOp: appOp,
error: event.error
}
};
}
*/
if (state.currentProgressSubject) {
state.currentProgressSubject.complete();
}
// any other error stops everything
return {
...state,
uninstallQueue: [],
installQueue: [],
updateAllQueue: [],
currentAppOp: null,
currentProgressSubject: null,
currentError: {
appOp: appOp,
error: event.error,
},
};
} else if (event.type === "runProgress") {
// we just emit on the subject
if (state.currentProgressSubject) {
state.currentProgressSubject.next(event.progress);
}
return state; // identity state will not re-render the UI
}
return state;
}
case "recover":
return { ...state, currentError: null };
case "wipe":
return {
...state,
currentError: null,
installQueue: [],
uninstallQueue: reorderUninstallQueue(
state.appByName,
state.installed.map(({ name }) => name)
),
};
case "updateAll": {
let installList = state.installQueue.slice(0);
let uninstallList = state.uninstallQueue.slice(0);
state.installed
.filter(({ updated, name }) => !updated && state.appByName[name])
.forEach((app) => {
const dependents = state.installed
.filter((a) => {
const depApp = state.appByName[a.name];
return depApp && depApp.dependencies.includes(app.name);
})
.map((a) => a.name);
uninstallList = uninstallList.concat([app.name, ...dependents]);
installList = installList.concat([app.name, ...dependents]);
});
const installQueue = reorderInstallQueue(state.appByName, installList);
const uninstallQueue = reorderUninstallQueue(
state.appByName,
uninstallList
);
/** since install queue === uninstall queue in this case we can map the update queue to either one */
const updateAllQueue = installQueue;
return {
...state,
currentError: null,
installQueue,
uninstallQueue,
updateAllQueue,
};
}
case "install": {
const { name } = action;
if (state.installQueue.includes(name)) {
// already queued for install
return state;
}
const existing = state.installed.find((app) => app.name === name);
if (existing && existing.updated && state.installedAvailable) {
// already installed and up to date
return state;
}
const depApp: App | null | undefined = state.appByName[name];
// No app found but fw update is available
if (
!depApp &&
semver.lt(
state.deviceInfo.version,
state.firmware?.updateAvailable?.final?.version
)
) {
throw new LatestFirmwareVersionRequired(
"LatestFirmwareVersionRequired",
{
current: state.deviceInfo.version,
latest: state.firmware?.updateAvailable?.final?.version,
}
);
}
invariant(depApp, "no such app '%s'", name);
const deps = depApp.dependencies;
const dependentsOfDep = flatMap(deps, (dep) =>
findDependents(state.appByName, dep)
);
const depsInstalledOutdated = state.installed.filter(
(a) => deps.includes(a.name) && !a.updated
);
let installList = state.installQueue;
// installing an app will remove if planned for uninstalling
let uninstallList = state.uninstallQueue.filter(
(u) => name !== u && !deps.includes(u)
);
if (state.uninstallQueue.length !== uninstallList.length) {
// app was asked for uninstall so it means we need to just cancel.
// TODO cover this in tests...
} else {
// if app is already installed but outdated, we'll need to update related deps
if ((existing && !existing.updated) || depsInstalledOutdated.length) {
// if app has installed direct dependent apps, we'll need to update them too
const directDependents = findDependents(state.appByName, name).filter(
(d) => state.installed.some((a) => a.name === d)
);
const outdated = state.installed
.filter(
(a) =>
!a.updated &&
[
name,
...deps,
...directDependents,
...dependentsOfDep,
].includes(a.name)
)
.map((a) => a.name);
uninstallList = uninstallList.concat(outdated);
installList = installList.concat(outdated);
}
installList = installList.concat([
...deps.filter((d) => !state.installed.some((a) => a.name === d)),
name,
]);
}
const installQueue = reorderInstallQueue(state.appByName, installList);
const uninstallQueue = reorderUninstallQueue(
state.appByName,
uninstallList
);
return { ...state, currentError: null, installQueue, uninstallQueue };
}
case "uninstall": {
const { name } = action;
if (state.uninstallQueue.includes(name)) {
// already queued
return state;
}
// uninstalling an app will remove from installQueue as well as direct deps
const installQueue = state.installQueue.filter((u) => name !== u);
let uninstallQueue = state.uninstallQueue;
if (
state.installed.some((a) => a.name === name || a.name === "") ||
action.force || // if installed unavailable and it was not a cancellation
// TODO cover this in tests...
(!state.installedAvailable && !state.installQueue.includes(name))
) {
uninstallQueue = reorderUninstallQueue(
state.appByName,
uninstallQueue.concat([
...findDependents(state.appByName, name).filter((d) =>
state.installed.some((a) => a.name === d)
),
name,
])
);
}
return { ...state, currentError: null, installQueue, uninstallQueue };
}
}
};
const defaultConfig = {
warnMemoryRatio: 0.1,
sortApps: false,
};
// calculate all size information useful for display
export const distribute = (
state: State,
config?: $Shape<typeof defaultConfig>
): AppsDistribution => {
const { warnMemoryRatio, sortApps } = { ...defaultConfig, ...config };
const blockSize = getBlockSize(state);
const totalBytes = state.deviceModel.memorySize;
const totalBlocks = Math.floor(totalBytes / blockSize);
const osBytes = (state.firmware && state.firmware.bytes) || 0;
const osBlocks = Math.ceil(osBytes / blockSize);
const appsSpaceBlocks = totalBlocks - osBlocks;
const appsSpaceBytes = appsSpaceBlocks * blockSize;
let totalAppsBlocks = 0;
const apps = state.installed.map((app) => {
const { name, blocks } = app;
totalAppsBlocks += blocks;
const currency = findCryptoCurrency((c) => c.managerAppName === name);
return {
currency,
name,
blocks,
bytes: blocks * blockSize,
};
});
if (sortApps) {
apps.sort((a, b) => b.blocks - a.blocks);
}
const totalAppsBytes = totalAppsBlocks * blockSize;
const freeSpaceBlocks = appsSpaceBlocks - totalAppsBlocks;
const freeSpaceBytes = freeSpaceBlocks * blockSize;
const shouldWarnMemory = freeSpaceBlocks / appsSpaceBlocks < warnMemoryRatio;
return {
totalBlocks,
totalBytes,
osBlocks,
osBytes,
apps,
appsSpaceBlocks,
appsSpaceBytes,
totalAppsBlocks,
totalAppsBytes,
freeSpaceBlocks,
freeSpaceBytes,
shouldWarnMemory,
};
};
export function getBlockSize(state: State): number {
return state.deviceModel.getBlockSize(state.deviceInfo.version);
}
// tells if the state is "incomplete" to implement the Manager v2 feature
// this happens when some apps are unrecognized
export const isIncompleteState = (state: State): boolean =>
state.installed.some((a) => !a.name);
// calculate if a given state (typically a predicted one) is out of memory (meaning impossible to reach with a device)
export const isOutOfMemoryState = (state: State): boolean => {
const blockSize = getBlockSize(state);
const totalBytes = state.deviceModel.memorySize;
const totalBlocks = Math.floor(totalBytes / blockSize);
const osBytes = (state.firmware && state.firmware.bytes) || 0;
const osBlocks = Math.ceil(osBytes / blockSize);
const appsSpaceBlocks = totalBlocks - osBlocks;
const totalAppsBlocks = state.installed.reduce(
(sum, app) => sum + app.blocks,
0
);
return totalAppsBlocks > appsSpaceBlocks;
};
export const isLiveSupportedApp = (app: App): boolean => {
const currency = app.currencyId
? findCryptoCurrencyById(app.currencyId)
: null;
return currency ? isCurrencySupported(currency) : false;
};
export const updateAllProgress = (state: State): number => {
const total = state.updateAllQueue.length;
/** each uninstall and install comes in a pair and have a weight of 0.5 in the progress */
const current = (state.uninstallQueue.length + state.installQueue.length) / 2;
if (total === 0 || current === 0) return 1;
return Math.max(0, Math.min((total - current) / total, 1));
};
// a series of operation to perform on the device for current state
export const getActionPlan = (state: State): AppOp[] =>
state.uninstallQueue
.map(
(name) =>
<AppOp>{
type: "uninstall",
name,
}
)
.concat(
state.installQueue.map(
(name) =>
<AppOp>{
type: "install",
name,
}
)
);
// get next operation to perform
export const getNextAppOp = (state: State): AppOp | null | undefined => {
if (state.uninstallQueue.length) {
return {
type: "uninstall",
name: state.uninstallQueue[0],
};
} else if (state.installQueue.length) {
return {
type: "install",
name: state.installQueue[0],
};
}
};
// resolve the State to predict when all queued ops are done
export const predictOptimisticState = (state: State): State => {
const s = { ...state, currentProgressSubject: null };
return getActionPlan(s)
.map(
(appOp) =>
<Action>{
type: "onRunnerEvent",
event: {
type: "runSuccess",
appOp,
},
}
)
.reduce(reducer, s);
};