This repository has been archived by the owner on May 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 441
/
KeyringStore.swift
594 lines (540 loc) · 19.7 KB
/
KeyringStore.swift
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
/* Copyright 2021 The Brave Authors. All rights reserved.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import SwiftUI
import BraveCore
import BraveShared
import Security
import Strings
import LocalAuthentication
import Combine
import Data
import Preferences
struct AutoLockInterval: Identifiable, Hashable {
var value: Int32
var label: String
init(value: Int32) {
self.value = value
self.label = Self.formatter.string(
from: Measurement<UnitDuration>(value: Double(value), unit: .minutes)
)
}
var id: Int32 {
value
}
static let minute = AutoLockInterval(value: 1)
static let fiveMinutes = AutoLockInterval(value: 5)
static let tenMinutes = AutoLockInterval(value: 10)
static let thirtyMinutes = AutoLockInterval(value: 30)
static let allOptions: [AutoLockInterval] = [
.minute,
.fiveMinutes,
.tenMinutes,
.thirtyMinutes,
]
private static let formatter = MeasurementFormatter().then {
$0.locale = Locale.current
$0.unitOptions = .providedUnit
$0.unitStyle = .medium
}
}
/// Defines a single word in a bip32 mnemonic recovery prhase.
///
/// Since a single phrase can have duplicate words, index matters in a SwiftUI context
struct RecoveryWord: Hashable, Identifiable {
/// The word itself
var value: String
/// The index of that word within the entire phrase
var index: Int
var id: String {
"\(index)-\(value)"
}
}
/// Validate if password is weak/medium/strong
enum PasswordStatus: Equatable {
case none // empty
case invalid // less than 8
case weak // between 8 to 12
case medium // more than 12
case strong // more than 16
var description: String {
switch self {
case .none:
return ""
case .invalid, .weak:
return Strings.Wallet.passwordStatusWeak
case .medium:
return Strings.Wallet.passwordStatusMedium
case .strong:
return Strings.Wallet.passwordStatusStrong
}
}
var tintColor: Color {
switch self {
case .none:
return Color.clear
case .invalid, .weak:
return Color(uiColor: WalletV2Design.passwordWeakRed)
case .medium:
return Color(uiColor: WalletV2Design.passwordMediumYellow)
case .strong:
return Color(uiColor: WalletV2Design.passwordStrongGreen)
}
}
var percentage: CGFloat {
switch self {
case .none:
return 0
case .invalid, .weak:
return 1 / 3
case .medium:
return 2 / 3
case .strong:
return 1
}
}
}
/// An interface that helps you interact with a users keyring
///
/// This wraps a KeyringService that you would obtain through BraveCore and makes it observable
public class KeyringStore: ObservableObject, WalletObserverStore {
/// A boolean indciates front-end has or has not loaded accounts from the core
@Published var isLoaded = false
/// Whether or not the user should be viewing the onboarding flow to setup a keyring
@Published private(set) var isOnboardingVisible: Bool = false
/// Whether or not the last time the wallet was locked was due to the user manually locking it
///
/// Affects whether or not we automatically fill the password from the keychain immediately on
/// `UnlockWalletView` appearing
@Published private(set) var lockedManually: Bool = false
/// Whether or not the biometrics prompt is currently visible in the unlock view
///
/// Needed as a workaround that we show the prompt _after_ the restore completes, which unlocks the wallet
/// and dismisses the `UnlockWalletView`. We need to keep the unlock view/biometrics prompt up until
/// the user dismisess it or enables it.
@Published var isRestoreFromUnlockBiometricsPromptVisible: Bool = false
/// The users selected account when buying/sending/swapping currencies
@Published var selectedAccount: BraveWallet.AccountInfo = .init() {
didSet {
guard oldValue.address != selectedAccount.address, // Same account
!oldValue.address.isEmpty // initializing `KeyringStore`
else {
return
}
setSelectedAccount(to: selectedAccount)
}
}
/// Indicates if the wallet has been created. This value used for display wallet related settings if created.
@Published var isWalletCreated: Bool = false
/// Indicates if the wallet has been locked.
@Published var isWalletLocked: Bool = true
/// Indicates if the wallet has been backed up.
@Published var isWalletBackedUp: Bool = false
/// All `AccountInfo` for all available keyrings
@Published var allAccounts: [BraveWallet.AccountInfo] = []
/// A list of default account with all support coin types
@Published var defaultAccounts: [BraveWallet.AccountInfo] = []
var passwordToSaveInBiometric: String?
/// The origin of the active tab (if applicable). Used for fetching/selecting network for the DApp origin.
public var origin: URLOrigin?
/// If this KeyringStore instance is creating a wallet.
/// Note: Flag is reset prior to onboarding completion step.
@Published var isCreatingWallet = false
/// If this KeyringStore instance is restoring a wallet.
/// Note: Flag is reset prior to onboarding completion step.
@Published var isRestoringWallet = false
/// If this KeyringStore instance is creating a wallet or restoring a wallet.
/// This flag is used to know when to dismiss onboarding when multiple windows are visible.
private var isOnboarding: Bool = false
private let keyringService: BraveWalletKeyringService
private let walletService: BraveWalletBraveWalletService
private let rpcService: BraveWalletJsonRpcService
private var cancellable: AnyCancellable?
private let keychain: KeychainType
private var keyringServiceObserver: KeyringServiceObserver?
private var rpcServiceObserver: JsonRpcServiceObserver?
var isObserving: Bool {
keyringServiceObserver != nil && rpcServiceObserver != nil
}
public init(
keyringService: BraveWalletKeyringService,
walletService: BraveWalletBraveWalletService,
rpcService: BraveWalletJsonRpcService,
keychain: KeychainType = Keychain()
) {
self.keyringService = keyringService
self.walletService = walletService
self.rpcService = rpcService
self.keychain = keychain
setupObservers()
updateInfo()
Task { @MainActor in
let isWalletCreated = await keyringService.isWalletCreated()
self.isOnboardingVisible = !isWalletCreated
if isKeychainPasswordStored && isOnboardingVisible {
// If a user deletes the app and they had a stored user password in the past that keychain item
// stays persisted. When we grab the keyring for the first time we should check to see if they have
// a wallet created _and_ also have a password stored because if they do then it is no longer valid
// and should be removed.
resetKeychainStoredPassword()
}
}
cancellable = NotificationCenter.default
.publisher(for: UIApplication.didBecomeActiveNotification, object: nil)
.sink { [weak self] _ in
self?.updateInfo()
}
}
public func setupObservers() {
guard !isObserving else { return }
Task { @MainActor in
// For case where Wallet is dismissed while wallet is being created.
// Ex. User creates wallet, dismisses & re-opens Wallet before
// create wallet completion callback. Callback is held with
// strong ref which keeps `KeyringStore` alive.
let isWalletCreated = await keyringService.isWalletCreated()
self.isOnboardingVisible = !isWalletCreated
}
self.keyringServiceObserver = KeyringServiceObserver(
keyringService: keyringService,
_walletReset: { [weak self] in
self?.isOnboardingVisible = true
self?.updateInfo()
},
_walletCreated: { [weak self] in
guard let self else { return }
if self.isOnboardingVisible, !self.isOnboarding {
// Another window has created a wallet. We should dismiss onboarding on this
// window and allow the other window to continue with it's onboarding flow.
self.isOnboardingVisible = false
}
self.updateInfo()
},
_walletRestored: { [weak self] in
guard let self else { return }
if self.isOnboardingVisible && !self.isOnboarding {
// Another window has restored a wallet. We should dismiss onboarding on this
// window and allow the other window to continue with it's onboarding flow.
self.isOnboardingVisible = false
}
self.updateInfo()
},
_locked: { [weak self] in
// Put this in the background since biometrics prompt will block the main queue
DispatchQueue.main.async {
self?.updateInfo()
}
},
_unlocked: { [weak self] in
self?.updateInfo()
},
_backedUp: { [weak self] in
self?.updateInfo()
},
_accountsChanged: { [weak self] in
self?.updateInfo()
},
_selectedWalletAccountChanged: { [weak self] _ in
self?.updateInfo()
},
_selectedDappAccountChanged: { [weak self] _, _ in
self?.updateInfo()
}
)
self.rpcServiceObserver = JsonRpcServiceObserver(
rpcService: rpcService,
_chainChangedEvent: { [weak self] _, _, _ in
self?.updateInfo()
}
)
}
public func tearDown() {
Task { @MainActor in
// For case where Wallet is dismissed while wallet is being created.
// Ex. User creates wallet, dismisses & re-opens Wallet before
// create wallet completion callback. Callback is held with
// strong ref which keeps `KeyringStore` alive.
let isWalletCreated = await keyringService.isWalletCreated()
self.isOnboardingVisible = !isWalletCreated
if isRestoringWallet && isWalletCreated {
// user dismissed wallet while restoring, but after wallet was created in core.
keyringService.notifyWalletBackupComplete()
self.isWalletBackedUp = await keyringService.isWalletBackedUp()
}
}
keyringServiceObserver = nil
rpcServiceObserver = nil
}
private func updateInfo() {
if UIApplication.shared.applicationState != .active {
// Changes made in the backgroud due to timers going off at launch don't
// re-render things properly.
//
// This function is called again on `didBecomeActiveNotification` anyways.
return
}
Task { @MainActor in // fetch all KeyringInfo for all coin types
let allAccounts = await keyringService.allAccounts()
self.allAccounts = allAccounts.accounts
if let selectedAccount = allAccounts.selectedAccount {
self.selectedAccount = selectedAccount
}
self.isWalletCreated = await keyringService.isWalletCreated()
// fallback case where user completed front-end onboarding, but has no keyring created/accounts.
// this can occur if we crash prior to saving, ex. brave-ios #8291
if !isWalletCreated && Preferences.Wallet.isOnboardingCompleted.value {
Preferences.Wallet.isOnboardingCompleted.reset()
}
self.isWalletLocked = await keyringService.isLocked()
self.isWalletBackedUp = await keyringService.isWalletBackedUp()
self.isLoaded = true
}
}
private func setSelectedAccount(to account: BraveWallet.AccountInfo) {
Task { @MainActor in
let currentlySelectedAccount = await keyringService.allAccounts().selectedAccount
guard currentlySelectedAccount?.accountId.uniqueKey != account.accountId.uniqueKey else {
// account is already selected
return
}
let success = await keyringService.setSelectedAccount(account.accountId)
if success {
self.selectedAccount = account
}
}
}
func markOnboardingCompleted() {
self.isOnboarding = false
self.isOnboardingVisible = false
updateInfo()
}
func notifyWalletBackupComplete() {
keyringService.notifyWalletBackupComplete()
}
func lock() {
lockedManually = true
keyringService.lock()
isWalletLocked = true
}
func unlock(password: String, completion: @escaping (Bool) -> Void) {
if !isWalletCreated {
completion(false)
return
}
keyringService.unlock(password) { [weak self] unlocked in
completion(unlocked)
if unlocked {
// Reset this state for next unlock
self?.lockedManually = false
self?.isWalletLocked = false
}
self?.updateInfo()
}
}
func validate(password: String, completion: @escaping (Bool) -> Void) {
if !isWalletCreated {
completion(false)
return
}
keyringService.validatePassword(password, completion: completion)
}
func validatePassword(_ password: String, completion: @escaping (PasswordStatus) -> Void) {
if password.count >= 16 {
completion(.strong)
} else if password.count >= 12 {
completion(.medium)
} else if password.isEmpty {
completion(.none)
} else if password.count >= 8 {
completion(.weak)
} else {
completion(.invalid)
}
}
@MainActor func validatePassword(_ password: String) async -> PasswordStatus {
await withCheckedContinuation { continuation in
validatePassword(password) { isStrong in
continuation.resume(returning: isStrong)
}
}
}
func createWallet(password: String, completion: ((String?) -> Void)? = nil) {
guard !isCreatingWallet else {
completion?(nil)
return
}
isOnboarding = true
isCreatingWallet = true
keyringService.isWalletCreated { [weak self] isWalletCreated in
guard let self else { return }
guard !isWalletCreated else {
// Wallet was created already (possible with multi-window) #8425
self.isOnboarding = false
self.isCreatingWallet = false
// Dismiss onboarding if wallet is already setup
self.isOnboardingVisible = false
return
}
keyringService.createWallet(password) { mnemonic in
self.isCreatingWallet = false
self.updateInfo()
if !mnemonic.isEmpty {
self.passwordToSaveInBiometric = password
}
completion?(mnemonic)
}
}
}
func recoveryPhrase(password: String, completion: @escaping ([RecoveryWord]) -> Void) {
keyringService.mnemonic(forDefaultKeyring: password) { phrase in
let words = phrase
.split(separator: " ")
.enumerated()
.map { RecoveryWord(value: String($0.element), index: $0.offset) }
completion(words)
}
}
func restoreWallet(words: [String], password: String, isLegacyBraveWallet: Bool, completion: ((Bool) -> Void)? = nil) {
restoreWallet(phrase: words.joined(separator: " "), password: password, isLegacyBraveWallet: isLegacyBraveWallet, completion: completion)
}
func restoreWallet(phrase: String, password: String, isLegacyBraveWallet: Bool, completion: ((Bool) -> Void)? = nil) {
guard !isRestoringWallet else { // wallet is already being restored.
completion?(false)
return
}
isOnboarding = true
isRestoringWallet = true
keyringService.restoreWallet(
phrase,
password: password,
isLegacyBraveWallet: isLegacyBraveWallet
) { [weak self] isMnemonicValid in
guard let self = self else { return }
self.isRestoringWallet = false
if isMnemonicValid {
// Restoring from wallet means you already have your phrase backed up
self.passwordToSaveInBiometric = password
self.notifyWalletBackupComplete()
self.updateInfo()
self.resetKeychainStoredPassword()
}
for coin in WalletConstants.supportedCoinTypes(.dapps) { // only coin types support dapps have permission management
Domain.clearAllWalletPermissions(for: coin)
}
Preferences.Wallet.sortOrderFilter.reset()
Preferences.Wallet.isHidingSmallBalancesFilter.reset()
Preferences.Wallet.isHidingUnownedNFTsFilter.reset()
Preferences.Wallet.isShowingNFTNetworkLogoFilter.reset()
Preferences.Wallet.nonSelectedAccountsFilter.reset()
Preferences.Wallet.nonSelectedNetworksFilter.reset()
completion?(isMnemonicValid)
}
}
/// `chainId` is only for .fil or .btc coin type
/// correct `BraveWallet.KeyringId` will be returned from `keyringIdForNewAccount`
func addPrimaryAccount(
_ name: String,
coin: BraveWallet.CoinType,
chainId: String,
completion: ((Bool) -> Void)? = nil
) {
keyringService.addAccount(
coin,
keyringId: BraveWallet.KeyringId.keyringId(for: coin, on: chainId),
accountName: name
) { accountInfo in
self.updateInfo()
completion?(accountInfo != nil)
}
}
/// `chainId` is only for .fil or .btc coin type
func addSecondaryAccount(
_ name: String,
coin: BraveWallet.CoinType,
chainId: String,
privateKey: String,
completion: ((BraveWallet.AccountInfo?) -> Void)? = nil
) {
if coin == .fil {
keyringService.importFilecoinAccount(name, privateKey: privateKey, network: chainId) { accountInfo in
completion?(accountInfo)
}
} else {
keyringService.importAccount(name, privateKey: privateKey, coin: coin) { accountInfo in
self.updateInfo()
completion?(accountInfo)
}
}
}
func addSecondaryAccount(
_ name: String,
json: String,
password: String,
completion: ((BraveWallet.AccountInfo?) -> Void)? = nil
) {
keyringService.importAccount(fromJson: name, password: password, json: json) { accountInfo in
completion?(accountInfo)
}
}
func removeSecondaryAccount(for account: BraveWallet.AccountInfo, password: String, completion: ((Bool) -> Void)? = nil) {
keyringService.removeAccount(
account.accountId,
password: password
) { success in
completion?(success)
if success {
self.updateInfo()
}
}
}
func renameAccount(_ account: BraveWallet.AccountInfo, name: String, completion: ((Bool) -> Void)? = nil) {
let handler: (Bool) -> Void = { success in
self.updateInfo()
completion?(success)
}
keyringService.setAccountName(account.accountId, name: name, completion: handler)
}
func privateKey(for account: BraveWallet.AccountInfo, password: String, completion: @escaping (String?) -> Void) {
keyringService.encodePrivateKey(forExport: account.accountId, password: password, completion: { key in
completion(key.isEmpty ? nil : key)
})
}
func notifyUserInteraction() {
if isWalletLocked {
// Auto-lock isn't running until the keyring is unlocked
return
}
keyringService.notifyUserInteraction()
}
@MainActor func selectedDappAccount(for coin: BraveWallet.CoinType) async -> BraveWallet.AccountInfo? {
let allAccounts = await keyringService.allAccounts()
switch coin {
case .eth:
return allAccounts.ethDappSelectedAccount
case .sol:
return allAccounts.solDappSelectedAccount
default:
return nil
}
}
// MARK: - Keychain
static let passwordKeychainKey = "brave-wallet-password"
/// Stores the users wallet password in the keychain so that they may unlock using biometrics/passcode
func storePasswordInKeychain(_ password: String) -> OSStatus {
keychain.storePasswordInKeychain(key: Self.passwordKeychainKey, password: password)
}
@discardableResult
func resetKeychainStoredPassword() -> Bool {
keychain.resetPasswordInKeychain(key: Self.passwordKeychainKey)
}
var isKeychainPasswordStored: Bool {
keychain.isPasswordStoredInKeychain(key: Self.passwordKeychainKey)
}
/// Retreives a users stored wallet password using biometrics or passcode or nil if they have not saved
/// it to the keychain
func retrievePasswordFromKeychain() -> String? {
keychain.getPasswordFromKeychain(key: Self.passwordKeychainKey)
}
}