-
Notifications
You must be signed in to change notification settings - Fork 9
/
ImportMnemonicControllingAccounts.swift
252 lines (215 loc) · 7.79 KB
/
ImportMnemonicControllingAccounts.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
import ComposableArchitecture
import SwiftUI
// MARK: - ImportMnemonicControllingAccounts
public struct ImportMnemonicControllingAccounts: Sendable, FeatureReducer {
public struct State: Sendable, Hashable, Identifiable {
public var id: EntitiesControlledByFactorSource.ID {
entitiesControlledByFactorSource.id
}
public let entitiesControlledByFactorSource: EntitiesControlledByFactorSource
public let entities: DisplayEntitiesControlledByMnemonic.State
@PresentationState
public var destination: Destination.State? = nil
public var isMainBDFS: Bool
public init(
entitiesControlledByFactorSource ents: EntitiesControlledByFactorSource,
isMainBDFS: Bool
) {
self.isMainBDFS = isMainBDFS
self.entitiesControlledByFactorSource = ents
let accounts: IdentifiedArrayOf<Profile.Network.Account> = switch (ents.babylonAccounts.isEmpty, ents.olympiaAccounts.isEmpty) {
case (false, _):
// We prefer Babylon, always.
ents.babylonAccounts
case (true, false):
ents.olympiaAccounts
case (true, true):
// no accounts... still possible! i.e. Profile -> Create HARDWARE Account ->
// delete passcode -> import missing Mnemonic, which... does not control any
// accounts
[]
}
self.entities = .init(
id: .mixedCurves(
ents.factorSourceID
),
isMnemonicMarkedAsBackedUp: ents.isMnemonicMarkedAsBackedUp,
isMnemonicPresentInKeychain: ents.isMnemonicPresentInKeychain,
accounts: accounts,
hasHiddenAccounts: !ents.hiddenAccounts.isEmpty,
mode: .displayAccountListOnly
)
}
}
public enum InternalAction: Sendable, Equatable {
case validated(PrivateHDFactorSource)
}
public enum ViewAction: Sendable, Equatable {
case appeared
case inputMnemonicButtonTapped
case skipButtonTapped
}
public enum DelegateAction: Sendable, Equatable {
case persistedMnemonicInKeychain(FactorSourceID.FromHash)
case skippedMnemonic(FactorSourceID.FromHash)
case createdNewMainBDFS(oldSkipped: FactorSourceID.FromHash, DeviceFactorSource)
case failedToSaveInKeychain(FactorSourceID.FromHash)
}
public enum ChildAction: Sendable, Equatable {
case entities(DisplayEntitiesControlledByMnemonic.Action)
}
// MARK: - Destination
public struct Destination: DestinationReducer {
public enum State: Sendable, Hashable {
case importMnemonic(ImportMnemonic.State)
case confirmSkippingBDFS(ConfirmSkippingBDFS.State)
}
public enum Action: Sendable, Equatable {
case importMnemonic(ImportMnemonic.Action)
/// **B**abylon **D**evice **F**actor **S**ource
case confirmSkippingBDFS(ConfirmSkippingBDFS.Action)
}
public var body: some ReducerOf<Self> {
Scope(state: /State.importMnemonic, action: /Action.importMnemonic) {
ImportMnemonic()
}
Scope(state: /State.confirmSkippingBDFS, action: /Action.confirmSkippingBDFS) {
ConfirmSkippingBDFS()
}
}
}
@Dependency(\.errorQueue) var errorQueue
@Dependency(\.secureStorageClient) var secureStorageClient
@Dependency(\.overlayWindowClient) var overlayWindowClient
@Dependency(\.userDefaults) var userDefaults
@Dependency(\.factorSourcesClient) var factorSourcesClient
public init() {}
public var body: some ReducerOf<Self> {
Reduce(core)
.ifLet(destinationPath, action: /Action.destination) {
Destination()
}
}
private let destinationPath: WritableKeyPath<State, PresentationState<Destination.State>> = \.$destination
public func reduce(into state: inout State, viewAction: ViewAction) -> Effect<Action> {
switch viewAction {
case .appeared:
return .none
case .inputMnemonicButtonTapped:
state.destination = .importMnemonic(.init(
warning: L10n.RevealSeedPhrase.warning,
showCloseButton: true,
isWordCountFixed: true,
persistStrategy: nil,
wordCount: state.entitiesControlledByFactorSource.mnemonicWordCount
))
return .none
case .skipButtonTapped:
if state.isMainBDFS {
state.destination = .confirmSkippingBDFS(.init())
return .none
} else {
return .send(.delegate(.skippedMnemonic(state.entitiesControlledByFactorSource.factorSourceID)))
}
}
}
public func reduce(into state: inout State, presentedAction: Destination.Action) -> Effect<Action> {
switch presentedAction {
case let .importMnemonic(.delegate(delegateAction)):
switch delegateAction {
case let .notPersisted(mnemonicWithPassphrase):
// FIXME: should always work... but please tidy up!
let factorSourceID = try! FactorSourceID.FromHash(
kind: .device,
mnemonicWithPassphrase: mnemonicWithPassphrase
)
guard factorSourceID == state.entitiesControlledByFactorSource.factorSourceID else {
overlayWindowClient.scheduleHUD(.wrongMnemonic)
return .none
}
return validate(
mnemonicWithPassphrase: mnemonicWithPassphrase,
accounts: state.entitiesControlledByFactorSource.accounts,
factorSource: state.entitiesControlledByFactorSource.deviceFactorSource
)
case .persistedMnemonicInKeychainOnly, .doneViewing, .persistedNewFactorSourceInProfile:
preconditionFailure("Incorrect implementation")
}
case .confirmSkippingBDFS(.delegate(.cancel)):
state.destination = nil
return .none
case .confirmSkippingBDFS(.delegate(.confirmed)):
loggerGlobal.notice("Skipping BDFS! Generating a new one and hiding affected accounts/personas.")
state.destination = nil
return .run { [entitiesControlledByFactorSource = state.entitiesControlledByFactorSource] send in
loggerGlobal.info("Generating mnemonic for new main BDFS")
let newMainBDFS = try await factorSourcesClient.createNewMainBDFS()
loggerGlobal.info("Delegating done with creating new BDFS (skipped old)")
await send(.delegate(.createdNewMainBDFS(
oldSkipped: entitiesControlledByFactorSource.factorSourceID,
newMainBDFS.factorSource
)))
} catch: { error, _ in
loggerGlobal.critical("Failed to create new main BDFS error: \(error)")
}
default:
return .none
}
}
public func reduce(into state: inout State, internalAction: InternalAction) -> Effect<Action> {
switch internalAction {
case let .validated(privateHDFactorSource):
state.destination = nil
return .run { send in
try userDefaults.addFactorSourceIDOfBackedUpMnemonic(privateHDFactorSource.factorSource.id)
try secureStorageClient.saveMnemonicForFactorSource(
privateHDFactorSource
)
await send(.delegate(.persistedMnemonicInKeychain(privateHDFactorSource.factorSource.id)))
} catch: { error, send in
errorQueue.schedule(error)
loggerGlobal.error("Failed to saved mnemonic in keychain")
await send(.delegate(.failedToSaveInKeychain(privateHDFactorSource.factorSource.id)))
}
}
}
private func validate(
mnemonicWithPassphrase: MnemonicWithPassphrase,
accounts: [Profile.Network.Account],
factorSource: DeviceFactorSource
) -> Effect<Action> {
func fail(error: Swift.Error?) -> Effect<Action> {
loggerGlobal.error("Failed to validate all accounts against mnemonic, underlying error: \(String(describing: error))")
errorQueue.schedule(MnemonicDidNotValidateAllAccounts())
return .none
}
do {
guard try mnemonicWithPassphrase.validatePublicKeys(of: accounts) else {
return fail(error: nil)
}
let privateHDFactorSource = try PrivateHDFactorSource(
mnemonicWithPassphrase: mnemonicWithPassphrase,
factorSource: factorSource
)
return .send(.internal(.validated(privateHDFactorSource)))
} catch {
return fail(error: error)
}
}
}
// MARK: - MnemonicDidNotValidateAllAccounts
struct MnemonicDidNotValidateAllAccounts: LocalizedError {
init() {}
var errorDescription: String? {
L10n.ImportMnemonic.failedToValidateAllAccounts
}
}
extension OverlayWindowClient.Item.HUD {
fileprivate static let wrongMnemonic = Self(
text: L10n.ImportMnemonic.wrongMnemonicHUD,
icon: .init(
kind: .system("exclamationmark.octagon"),
foregroundColor: Color.app.red1
)
)
}