-
Notifications
You must be signed in to change notification settings - Fork 362
/
saga.ts
361 lines (325 loc) · 12.1 KB
/
saga.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
import { deriveCEK } from '@celo/utils/src/commentEncryption'
import { getAccountAddressFromPrivateKey } from '@celo/walletkit'
import * as Crypto from 'crypto'
import { generateMnemonic, mnemonicToSeedHex } from 'react-native-bip39'
import * as RNFS from 'react-native-fs'
import { REHYDRATE } from 'redux-persist/es/constants'
import { call, delay, put, race, select, spawn, take, takeLatest } from 'redux-saga/effects'
import { setAccountCreationTime } from 'src/account/actions'
import { getPincode } from 'src/account/saga'
import CeloAnalytics from 'src/analytics/CeloAnalytics'
import { CustomEventNames } from 'src/analytics/constants'
import { ErrorMessages } from 'src/app/ErrorMessages'
import { currentLanguageSelector } from 'src/app/reducers'
import { getWordlist } from 'src/backup/utils'
import { UNLOCK_DURATION } from 'src/geth/consts'
import { deleteChainData } from 'src/geth/geth'
import { navigateToError } from 'src/navigator/NavigationService'
import { waitWeb3LastBlock } from 'src/networkInfo/saga'
import { setKey } from 'src/utils/keyStore'
import Logger from 'src/utils/Logger'
import {
Actions,
getLatestBlock,
setAccount,
SetIsZeroSyncAction,
setLatestBlockNumber,
setPrivateCommentKey,
updateWeb3SyncProgress,
} from 'src/web3/actions'
import { addLocalAccount, isZeroSyncMode, web3 } from 'src/web3/contracts'
import { currentAccountSelector } from 'src/web3/selectors'
import { Block } from 'web3/eth/types'
const ETH_PRIVATE_KEY_LENGTH = 64
const MNEMONIC_BIT_LENGTH = (ETH_PRIVATE_KEY_LENGTH * 8) / 2
const TAG = 'web3/saga'
// The timeout for web3 to complete syncing and the latestBlock to be > 0
export const SYNC_TIMEOUT = 60000
const BLOCK_CHAIN_CORRUPTION_ERROR = "Error: CONNECTION ERROR: Couldn't connect to node on IPC."
// checks if web3 claims it is currently syncing and attempts to wait for it to complete
export function* checkWeb3SyncProgress() {
if (isZeroSyncMode()) {
// In this mode, the check seems to fail with
// web3/saga/checking web3 sync progress: Error: Invalid JSON RPC response: "":
return true
}
while (true) {
try {
Logger.debug(TAG, 'checkWeb3SyncProgress', 'Checking sync progress')
// isSyncing returns a syncProgress object when it's still syncing, false otherwise
const syncProgress = yield web3.eth.isSyncing()
if (typeof syncProgress === 'boolean' && !syncProgress) {
Logger.debug(TAG, 'checkWeb3SyncProgress', 'Sync maybe complete, checking')
const latestBlock: Block = yield call(getLatestBlock)
if (latestBlock && latestBlock.number > 0) {
yield put(setLatestBlockNumber(latestBlock.number))
Logger.debug(TAG, 'checkWeb3SyncProgress', 'Sync is complete')
return true
} else {
Logger.debug(TAG, 'checkWeb3SyncProgress', 'Sync not actually complete, still waiting')
}
} else {
yield put(updateWeb3SyncProgress(syncProgress))
}
yield delay(100) // wait 100ms while web3 syncs
} catch (error) {
if (error.toString().toLowerCase() === BLOCK_CHAIN_CORRUPTION_ERROR.toLowerCase()) {
CeloAnalytics.track(CustomEventNames.blockChainCorruption, {}, true)
const deleted = yield call(deleteChainData)
if (deleted) {
navigateToError('corruptedChainDeleted')
}
} else {
Logger.error(TAG, 'Unexpected sync error', error)
}
return false
}
}
}
export function* waitForWeb3Sync() {
try {
const { syncComplete, timeout } = yield race({
syncComplete: call(checkWeb3SyncProgress),
timeout: delay(SYNC_TIMEOUT),
})
if (timeout || !syncComplete) {
Logger.error(TAG, 'Could not complete sync')
navigateToError('web3FailedToSync')
return false
}
return true
} catch (error) {
Logger.error(TAG, 'checkWeb3Sync', error)
navigateToError('errorDuringSync')
return false
}
}
export function* getOrCreateAccount() {
const account = yield select(currentAccountSelector)
if (account) {
Logger.debug(
TAG + '@getOrCreateAccount',
'Tried to create account twice, returning the existing one'
)
return account
}
Logger.debug(TAG + '@getOrCreateAccount', 'Creating a new account')
const wordlist = getWordlist(yield select(currentLanguageSelector))
const mnemonic = String(yield call(generateMnemonic, MNEMONIC_BIT_LENGTH, null, wordlist))
const privateKey = yield call(mnemonicToSeedHex, mnemonic)
const accountAddress = yield call(assignAccountFromPrivateKey, privateKey)
if (accountAddress) {
try {
yield call(setKey, 'mnemonic', mnemonic)
} catch (e) {
Logger.error(TAG + '@getOrCreateAccount', 'Failed to set mnemonic', e)
}
return accountAddress
} else {
return null
}
}
export function* assignAccountFromPrivateKey(key: string) {
const currentAccount = yield select(currentAccountSelector)
try {
const pincode = yield call(getPincode)
if (!pincode) {
Logger.error(TAG + '@assignAccountFromPrivateKey', 'Got falsy pin')
throw Error('Cannot create account without having the pin set')
}
let account: string
if (isZeroSyncMode()) {
const privateKey = String(key)
Logger.debug(TAG + '@assignAccountFromPrivateKey', 'Init web3 with private key')
addLocalAccount(web3, privateKey)
// Save the account to a local file on the disk.
// This is only required in Geth free mode because if geth is running
// it has its own mechanism to save the encrypted key in its keystore.
account = getAccountAddressFromPrivateKey(privateKey)
yield savePrivateKeyToLocalDisk(account, privateKey, pincode)
} else {
try {
// @ts-ignore
account = yield call(web3.eth.personal.importRawKey, String(key), pincode)
} catch (e) {
if (e.toString().includes('account already exists')) {
account = currentAccount
Logger.debug(
TAG + '@assignAccountFromPrivateKey',
'Importing same account as current one'
)
} else {
Logger.error(TAG + '@assignAccountFromPrivateKey', 'Error importing raw key')
throw e
}
}
yield call(web3.eth.personal.unlockAccount, account, pincode, UNLOCK_DURATION)
}
Logger.debug(
TAG + '@assignAccountFromPrivateKey',
`Created account from mnemonic and added to wallet: ${account}`
)
yield put(setAccount(account))
yield put(setAccountCreationTime())
yield call(assignDataKeyFromPrivateKey, key)
if (!isZeroSyncMode()) {
web3.eth.defaultAccount = account
}
return account
} catch (e) {
Logger.error(
TAG + '@assignAccountFromPrivateKey',
'Error assigning account from private key',
e
)
return null
}
}
function* assignDataKeyFromPrivateKey(key: string) {
const privateCEK = deriveCEK(key).toString('hex')
yield put(setPrivateCommentKey(privateCEK))
}
function getPrivateKeyFilePath(account: string): string {
return `${RNFS.DocumentDirectoryPath}/private_key_for_${account}.txt`
}
function ensureAddressAndKeyMatch(address: string, privateKey: string) {
const generatedAddress = getAccountAddressFromPrivateKey(privateKey)
if (!generatedAddress) {
throw new Error(`Failed to generate address from private key`)
}
if (address.toLowerCase() !== generatedAddress.toLowerCase()) {
throw new Error(
`Address from private key: ${generatedAddress}, ` + `address of sender ${address}`
)
}
Logger.debug(TAG + '@ensureAddressAndKeyMatch', `Sender and private key match`)
}
async function savePrivateKeyToLocalDisk(
account: string,
privateKey: string,
encryptionPassword: string
) {
ensureAddressAndKeyMatch(account, privateKey)
const filePath = getPrivateKeyFilePath(account)
const plainTextData = privateKey
const encryptedData: Buffer = getEncryptedData(plainTextData, encryptionPassword)
Logger.debug('savePrivateKeyToLocalDisk', `Writing encrypted private key to ${filePath}`)
await RNFS.writeFile(getPrivateKeyFilePath(account), encryptedData.toString('hex'))
}
// Reads and returns unencrypted private key
export async function readPrivateKeyFromLocalDisk(
account: string,
encryptionPassword: string
): Promise<string> {
const filePath = getPrivateKeyFilePath(account)
Logger.debug('readPrivateKeyFromLocalDisk', `Reading private key from ${filePath}`)
const hexEncodedEncryptedData: string = await RNFS.readFile(filePath)
const encryptedDataBuffer: Buffer = new Buffer(hexEncodedEncryptedData, 'hex')
const privateKey: string = getDecryptedData(encryptedDataBuffer, encryptionPassword)
ensureAddressAndKeyMatch(account, privateKey)
return privateKey
}
// Exported for testing
export function getEncryptedData(plainTextData: string, password: string): Buffer {
try {
const cipher = Crypto.createCipher('aes-256-cbc', password)
return Buffer.concat([cipher.update(new Buffer(plainTextData, 'utf8')), cipher.final()])
} catch (e) {
Logger.error(TAG + '@getEncryptedData', 'Failed to write private key', e)
throw e // Re-throw
}
}
// Exported for testing
export function getDecryptedData(encryptedData: Buffer, password: string): string {
try {
const decipher = Crypto.createDecipher('aes-256-cbc', password)
const decrypted = Buffer.concat([decipher.update(encryptedData), decipher.final()])
return decrypted.toString('utf8')
} catch (e) {
Logger.error(TAG + '@getDecryptedData', 'Failed to read private key', e)
throw e // Re-throw
}
}
// Wait for account to exist and then return it
export function* getAccount() {
while (true) {
const account = yield select(currentAccountSelector)
if (account) {
return account
}
const action = yield take([Actions.SET_ACCOUNT, REHYDRATE])
if (action.type === REHYDRATE) {
// Wait for rehydrate and select the state again
continue
}
if (action.address) {
// account exists
return action.address
}
}
}
async function isLocked(address: string) {
try {
// Test account to see if it is unlocked
await web3.eth.sign('', address)
} catch (e) {
return true
}
return false
}
let accountAlreadyAddedInZeroSyncMode = false
export function* unlockAccount(account: string) {
Logger.debug(TAG + '@unlockAccount', `Unlocking account: ${account}`)
try {
const isAccountLocked = yield call(isLocked, account)
if (!isAccountLocked) {
return true
}
const pincode = yield call(getPincode)
if (isZeroSyncMode()) {
if (accountAlreadyAddedInZeroSyncMode) {
Logger.info(TAG + 'unlockAccount', `Account ${account} already added to web3 for signing`)
} else {
Logger.info(TAG + '@unlockAccount', `unlockDuration is ignored in Geth free mode`)
const privateKey: string = yield readPrivateKeyFromLocalDisk(account, pincode)
addLocalAccount(web3, privateKey)
accountAlreadyAddedInZeroSyncMode = true
}
return true
} else {
yield call(web3.eth.personal.unlockAccount, account, pincode, UNLOCK_DURATION)
Logger.debug(TAG + '@unlockAccount', `Account unlocked: ${account}`)
return true
}
} catch (error) {
Logger.error(TAG + '@unlockAccount', 'Web3 account unlock failed', error)
return false
}
}
// Wait for geth to be connected and account ready
export function* getConnectedAccount() {
yield call(waitWeb3LastBlock)
const account: string = yield getAccount()
return account
}
// Wait for geth to be connected, geth ready, and get unlocked account
export function* getConnectedUnlockedAccount() {
const account: string = yield call(getConnectedAccount)
const success: boolean = yield call(unlockAccount, account)
if (success) {
return account
} else {
throw new Error(ErrorMessages.INCORRECT_PIN)
}
}
export function* switchZeroSyncMode(action: SetIsZeroSyncAction) {
Logger.info(TAG + '@switchZeroSyncMode', `Zero sync mode will change to: ${action.zeroSyncMode}`)
// TODO(anna) implement switching geth on/off, changing web3 provider
return true
}
export function* watchZeroSyncMode() {
yield takeLatest(Actions.SET_IS_ZERO_SYNC, switchZeroSyncMode)
}
export function* web3Saga() {
yield spawn(watchZeroSyncMode)
}