-
Notifications
You must be signed in to change notification settings - Fork 47
/
actions.js
517 lines (439 loc) · 16.6 KB
/
actions.js
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
// @flow
import {type IntlShape} from 'react-intl'
import {Alert, AppState, Keyboard, Platform} from 'react-native'
import RNBootSplash from 'react-native-bootsplash'
import DeviceInfo from 'react-native-device-info'
import {type Dispatch} from 'redux'
import uuid from 'uuid'
import {clearAccountState} from './actions/account'
import {mirrorTxHistory, setBackgroundSyncError, updateHistory} from './actions/history'
import {changeAndSaveLanguage} from './actions/language'
import {fetchTokenInfo} from './actions/tokenInfo'
import {clearUTXOs} from './actions/utxo'
import * as api from './api/shelley/api'
import {CONFIG, isNightly} from './config/config'
import {getCardanoNetworkConfigById} from './config/networks'
import type {NetworkId, WalletImplementationId, YoroiProvider} from './config/types'
import {encryptCustomPin} from './crypto/customPin'
import {ISignRequest} from './crypto/ISignRequest'
import KeyStore from './crypto/KeyStore'
import type {HWDeviceInfo} from './crypto/shelley/ledgerUtils'
import walletManager from './crypto/walletManager'
import {
type AppSettingsKey,
APP_SETTINGS_KEYS,
AppSettingsError,
readAppSettings,
removeAppSettings,
writeAppSettings,
} from './helpers/appSettings'
import {backgroundLockListener} from './helpers/backgroundLockHelper'
import crashReporting from './helpers/crashReporting'
import {canBiometricEncryptionBeEnabled, recreateAppSignInKeys, removeAppSignInKeys} from './helpers/deviceSettings'
import globalMessages, {errorMessages} from './i18n/global-messages'
import {
currentVersionSelector,
installationIdSelector,
isAppSetupCompleteSelector,
isSystemAuthEnabledSelector,
sendCrashReportsSelector,
} from './selectors'
import type {ServerStatusCache, State} from './state'
import assert from './utils/assert'
import {Logger} from './utils/logging'
import networkInfo from './utils/networkInfo'
const updateCrashlytics = (fieldName: AppSettingsKey, value: any) => {
const handlers = {
[APP_SETTINGS_KEYS.LANG]: () => crashReporting.setStringValue('language_code', value),
[APP_SETTINGS_KEYS.BIOMETRIC_HW_SUPPORT]: () => crashReporting.setBoolValue('biometric_hw_support', value),
[APP_SETTINGS_KEYS.CAN_ENABLE_BIOMETRIC_ENCRYPTION]: () =>
crashReporting.setBoolValue('can_enable_biometric_encryption', value),
}
// $FlowFixMe flow does not like undefined access but we are dealing with it
const handler = handlers[fieldName] || null
handler && handler()
}
export const setAppSettingField = (fieldName: AppSettingsKey, value: any) => async (dispatch: Dispatch<any>) => {
await writeAppSettings(fieldName, value)
dispatch({
path: ['appSettings', fieldName],
payload: value,
type: 'SET_APP_SETTING_FIELD',
reducer: (state, payload) => payload,
})
updateCrashlytics(fieldName, value)
}
export const clearAppSettingField = (fieldName: AppSettingsKey) => async (dispatch: Dispatch<any>) => {
await removeAppSettings(fieldName)
updateCrashlytics(fieldName, null)
dispatch({
path: ['appSettings', fieldName],
payload: null,
type: 'REMOVE_APP_SETTING_FIELD',
reducer: (state, payload) => payload,
})
}
export const setEasyConfirmation = (enable: boolean) => ({
path: ['wallet', 'isEasyConfirmationEnabled'],
payload: enable,
reducer: (state: State, value: boolean) => value,
type: 'SET_EASY_CONFIRMATION',
})
const _updateWallets = (wallets) => ({
path: ['wallets'],
payload: wallets,
reducer: (state, value) => value,
type: 'UPDATE_WALLETS',
})
export const updateWallets = () => (dispatch: Dispatch<any>) => {
const wallets = walletManager.getWallets()
dispatch(_updateWallets(wallets))
}
const _setAppSettings = (appSettings) => ({
path: ['appSettings'],
payload: appSettings,
type: 'SET_APP_SETTINGS',
reducer: (state, payload) => payload,
})
const reloadAppSettings = () => async (dispatch: Dispatch<any>) => {
const appSettings = await readAppSettings()
Object.entries(appSettings).forEach(([key, value]) => {
updateCrashlytics(key, value)
})
dispatch(_setAppSettings(appSettings))
if (appSettings.languageCode) {
dispatch(changeAndSaveLanguage(appSettings.languageCode))
}
}
export const encryptAndStoreCustomPin = (pin: string) => async (dispatch: Dispatch<any>, getState: () => State) => {
const state = getState()
const installationId = state.appSettings.installationId
if (installationId == null) {
throw new AppSettingsError(APP_SETTINGS_KEYS.INSTALLATION_ID)
}
const customPinHash = await encryptCustomPin(installationId, pin)
await dispatch(setAppSettingField(APP_SETTINGS_KEYS.CUSTOM_PIN_HASH, customPinHash))
}
export const removeCustomPin = () => async (dispatch: Dispatch<any>) => {
await dispatch(clearAppSettingField(APP_SETTINGS_KEYS.CUSTOM_PIN_HASH))
}
export const acceptAndSaveTos = () => async (dispatch: Dispatch<any>) => {
await dispatch(setAppSettingField(APP_SETTINGS_KEYS.ACCEPTED_TOS, true))
}
const initInstallationId =
() =>
async (dispatch: Dispatch<any>, getState: any): Promise<string> => {
let installationId = installationIdSelector(getState())
if (installationId != null) {
return installationId
}
installationId = uuid.v4()
await dispatch(setAppSettingField(APP_SETTINGS_KEYS.INSTALLATION_ID, installationId))
return installationId
}
export const updateVersion =
() =>
async (dispatch: Dispatch<any>, getState: any): Promise<string> => {
let currentVersion = currentVersionSelector(getState())
Logger.debug('current version from state', currentVersion)
if (currentVersion != null && currentVersion === DeviceInfo.getVersion()) {
return currentVersion
}
currentVersion = DeviceInfo.getVersion()
await dispatch(setAppSettingField(APP_SETTINGS_KEYS.CURRENT_VERSION, currentVersion))
Logger.debug('updated version', currentVersion)
return currentVersion
}
export const closeWallet = () => async (_dispatch: Dispatch<any>) => {
await walletManager.closeWallet()
}
// note(v-almonacid): authentication occurs after entering pin or biometrics,
// it does not mean we opened a wallet
export const signin = () => (dispatch: Dispatch<any>) => {
dispatch({
path: ['isAuthenticated'],
payload: true,
type: 'SIGN_IN',
reducer: (state, payload) => payload,
})
}
export const signout = () => (dispatch: Dispatch<any>) => {
dispatch({
path: ['isAuthenticated'],
payload: false,
type: 'SIGN_OUT',
reducer: (state, payload) => payload,
})
}
// logout closes the active wallet and signout
export const logout = () => async (dispatch: Dispatch<any>) => {
await closeWallet()
dispatch(signout())
}
const _setServerStatus = (serverStatus: ServerStatusCache) => (dispatch: Dispatch<any>) =>
dispatch({
path: ['serverStatus'],
payload: serverStatus,
type: 'SET_SERVER_STATUS',
reducer: (state, payload) => payload,
})
export const initApp = () => async (dispatch: Dispatch<any>, getState: any) => {
try {
// check status of default network
const backendConfig = getCardanoNetworkConfigById(CONFIG.NETWORKS.HASKELL_SHELLEY.NETWORK_ID).BACKEND
const status = await api.checkServerStatus(backendConfig)
dispatch(
_setServerStatus({
isServerOk: status.isServerOk,
isMaintenance: status.isMaintenance,
serverTime: new Date(status.serverTime),
}),
)
} catch (e) {
Logger.warn('actions::initApp could not retrieve server status', e)
}
if (isNightly()) {
dispatch(setAppSettingField(APP_SETTINGS_KEYS.SEND_CRASH_REPORTS, true))
}
await dispatch(reloadAppSettings())
const installationId = await dispatch(initInstallationId())
const state = getState()
if (sendCrashReportsSelector(getState())) {
crashReporting.enable()
// TODO(ppershing): just update crashlytic variables here
await dispatch(reloadAppSettings())
}
crashReporting.setUserId(installationIdSelector(getState()))
/**
* note(v-almonacid): temporary disable biometric auth for Android >= 10
* (SDK >= 29), as our java auth module is currently outdated, causing
* issues in some devices
*/
let shouldNotEnableBiometricAuth = false
if (
!isAppSetupCompleteSelector(state) &&
Platform.OS === 'android' &&
CONFIG.ANDROID_BIO_AUTH_EXCLUDED_SDK.includes(Platform.Version)
) {
shouldNotEnableBiometricAuth = true
}
Logger.debug('shouldDisableBiometricAuth:', shouldNotEnableBiometricAuth)
Logger.debug('isSystemAuthEnabled:', isSystemAuthEnabledSelector(state))
const canEnableBiometricEncryption = (await canBiometricEncryptionBeEnabled()) && !shouldNotEnableBiometricAuth
await dispatch(setAppSettingField(APP_SETTINGS_KEYS.CAN_ENABLE_BIOMETRIC_ENCRYPTION, canEnableBiometricEncryption))
await walletManager.initialize()
await dispatch(updateWallets())
if (canEnableBiometricEncryption && isSystemAuthEnabledSelector(state)) {
// On android 6 signin keys can get invalidated
// (e. g. when you change fingerprint),
// if that happens we want to regenerate them.
// As for the invalidate PIN case -> that should only
// happen when user removes PIN and re-creates it, but that should
// not be possible without first removing biometrics?
// So the biometrics key would be invalidated first.
// Also there is no way we know of to check if the key is valid
// in SYSTEM_PIN case without user typing the correct PIN.
const isKeyValid = await KeyStore.isKeyValid(installationId, 'BIOMETRICS')
if (!isKeyValid) {
await recreateAppSignInKeys(installationId)
}
}
dispatch({
path: ['isAppInitialized'],
payload: true,
reducer: (state, value) => value,
type: 'INITIALIZE_APP',
})
RNBootSplash.hide({fade: true})
}
const _setOnline = (isOnline: boolean) => (dispatch, getState) => {
const state = getState()
if (state.isOnline === isOnline) return // avoid useless state updates
dispatch({
type: 'Set isOnline',
path: ['isOnline'],
payload: isOnline,
reducer: (state, payload) => payload,
})
}
const setIsKeyboardOpen = (isOpen) => ({
type: 'Set isKeyboardOpen',
path: ['isKeyboardOpen'],
payload: isOpen,
reducer: (state, payload) => payload,
})
export const setupHooks = () => (dispatch: Dispatch<any>) => {
Logger.debug('setting up isOnline callback')
networkInfo.subscribe(({isOnline}) => dispatch(_setOnline(isOnline)))
dispatch(_setOnline(networkInfo.getConnectionInfo().isOnline))
Logger.debug('setting wallet manager hook')
walletManager.subscribe(() => dispatch(mirrorTxHistory()))
walletManager.subscribeBackgroundSyncError((err) => dispatch(setBackgroundSyncError(err)))
walletManager.subscribeServerSync((status) => dispatch(_setServerStatus(status)))
walletManager.subscribeOnOpen(() => dispatch(fetchTokenInfo()))
walletManager.subscribeOnClose(() => dispatch(clearUTXOs()))
walletManager.subscribeOnClose(() => dispatch(clearAccountState()))
walletManager.subscribeOnTxHistoryUpdate(() => dispatch(fetchTokenInfo()))
Logger.debug('setting up app lock')
const onTimeoutAction = () => {
dispatch(logout())
}
AppState.addEventListener('change', () => {
backgroundLockListener(onTimeoutAction)
})
Logger.debug('setting up keyboard manager')
Keyboard.addListener('keyboardDidShow', () => dispatch(setIsKeyboardOpen(true)))
Keyboard.addListener('keyboardDidHide', () => dispatch(setIsKeyboardOpen(false)))
}
export const generateNewReceiveAddress = () => async (_dispatch: Dispatch<any>) => {
return await walletManager.generateNewUiReceiveAddress()
}
export const generateNewReceiveAddressIfNeeded = () => async (_dispatch: Dispatch<any>) => {
return await walletManager.generateNewUiReceiveAddressIfNeeded()
}
export const changeWalletName = (newName: string) => async (dispatch: Dispatch<any>) => {
await walletManager.rename(newName)
dispatch(updateWallets())
}
export const createWallet =
(
name: string,
mnemonic: string,
password: string,
networkId: NetworkId,
implementationId: WalletImplementationId,
provider: YoroiProvider,
) =>
async (dispatch: Dispatch<any>) => {
const wallet = await walletManager.createWallet(name, mnemonic, password, networkId, implementationId, provider)
dispatch(updateWallets())
return wallet
}
export const createWalletWithBip44Account =
(
name: string,
bip44AccountPublic: string,
networkId: NetworkId,
implementationId: WalletImplementationId,
hwDeviceInfo: ?HWDeviceInfo,
readOnly: boolean,
) =>
async (dispatch: Dispatch<any>) => {
const wallet = await walletManager.createWalletWithBip44Account(
name,
bip44AccountPublic,
networkId,
implementationId,
hwDeviceInfo,
readOnly,
)
dispatch(updateWallets())
return wallet
}
type DialogOptions = {|
title: string,
message: string,
yesButton?: string,
noButton?: string,
|}
export const DIALOG_BUTTONS = Object.freeze({
YES: 'Yes',
NO: 'No',
})
type DialogButton = $Values<typeof DIALOG_BUTTONS>
const showDialog = (translations: DialogOptions): Promise<DialogButton> =>
new Promise((resolve) => {
const {title, message, yesButton, noButton} = translations
const buttons = []
assert.assert(yesButton, 'Yes button should be provided')
if (noButton != null) {
buttons.push({
text: noButton,
onPress: () => resolve(DIALOG_BUTTONS.NO),
})
}
buttons.push({text: yesButton, onPress: () => resolve(DIALOG_BUTTONS.YES)})
Alert.alert(title, message, buttons, {cancelable: false})
})
export const showErrorDialog = (
dialog: {title: Object, message: Object},
intl: ?IntlShape,
msgOptions?: {message: string},
): Promise<DialogButton> => {
let title, message, yesButton
if (intl != null) {
title = intl.formatMessage(dialog.title)
message = intl.formatMessage(dialog.message, msgOptions)
yesButton = intl.formatMessage(globalMessages.ok)
} else {
// in this case the function was called without providing the IntlShape
// object, so only an english dialog will be displayed
title = dialog.title.defaultMessage
// seems impossible to pass eslint check using a ternary operator here
if (msgOptions != null && 'message' in msgOptions) {
message = dialog.message.defaultMessage.replace(new RegExp('{message}', 'gi'), msgOptions.message)
} else {
message = 'unknown error'
}
yesButton = globalMessages.ok.defaultMessage
}
return showDialog({title, message, yesButton})
}
export const showConfirmationDialog = (dialog: DialogOptions, intl: IntlShape): Promise<DialogButton> =>
showDialog({
// $FlowFixMe
title: intl.formatMessage(dialog.title),
// $FlowFixMe
message: intl.formatMessage(dialog.message),
// $FlowFixMe
yesButton: intl.formatMessage(dialog.yesButton),
// $FlowFixMe
noButton: intl.formatMessage(dialog.noButton),
})
export const setSystemAuth = (enable: boolean) => async (dispatch: Dispatch<any>, getState: any) => {
await dispatch(setAppSettingField(APP_SETTINGS_KEYS.SYSTEM_AUTH_ENABLED, enable))
const installationId = installationIdSelector(getState())
if (installationId == null) {
throw new Error('Installation id is not defined')
}
if (enable) {
await recreateAppSignInKeys(installationId)
await dispatch(removeCustomPin())
} else {
await removeAppSignInKeys(installationId)
}
}
export const handleGeneralError = async (message: string, e: Error, intl: ?IntlShape) => {
Logger.error(`${message}: ${e.message}`, e)
await showErrorDialog(errorMessages.generalError, intl, {message})
}
export const submitSignedTx = (signedTx: string) => async (dispatch: Dispatch<any>) => {
Logger.info('submitting tx...')
await walletManager.submitTransaction(signedTx)
dispatch(updateHistory())
}
// note: eslint doesn't like polymorphic types
export const submitTransaction =
<T>(signRequest: ISignRequest<T>, decryptedKey: string) =>
async (dispatch: Dispatch<any>) => {
const {encodedTx} = await walletManager.signTx(signRequest, decryptedKey)
Logger.info('submitTransaction::encodedTx', Buffer.from(encodedTx).toString('hex'))
const signedTxBase64 = Buffer.from(encodedTx).toString('base64')
await dispatch(submitSignedTx(signedTxBase64))
}
export const checkForFlawedWallets = () => (dispatch: Dispatch<any>) => {
let isFlawed = false
Logger.debug('actions::checkForFlawedWallets:: checking wallet...')
try {
isFlawed = walletManager.checkForFlawedWallets()
Logger.debug('actions::checkForFlawedWallets::isFlawed', isFlawed)
dispatch({
path: ['isFlawedWallet'],
payload: isFlawed,
reducer: (state, isFlawed) => isFlawed,
type: 'SET_FLAWED_WALLET',
})
} catch (e) {
Logger.warn('actions::checkForFlawedWallets error', e)
}
}