Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : App/Sources/Onboarding/ImportWalletFlow.swift8// Module : Onboarding9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI42import QyvoraCore43import QyvoraWallet44import QyvoraUI4546/// Restores a wallet from an existing BIP-39 phrase: word entry with list validation, optional passphrase,47/// a master password for the new vault, then optional quick unlock. With `entry: .backupOrTransfer` it starts on the48/// two ways that need no typing (an encrypted backup file, another iPhone) and joins the same last steps.49struct ImportWalletFlow: View {50 enum Step { case restoreChoice, phrase, password, protect, chains, done }5152 /// Where the flow starts.53 enum Entry { case phrase, backupOrTransfer }5455 let onClose: () -> Void5657 @Environment(WalletStore.self) private var wallet58 @State private var step: Step5960 init(onClose: @escaping () -> Void, entry: Entry = .phrase) {61 self.onClose = onClose62 _step = State(initialValue: entry == .phrase ? .phrase : .restoreChoice)63 }6465 @State private var words = SeedPhraseEntry.emptyWords(12)66 @State private var passphrase = ""67 @State private var password = ""68 @State private var confirmation = ""69 @State private var importing = false70 @State private var error: String?71 @State private var alternative: Alternative?7273 /// Other ways to bring an existing wallet to this device, provided by the security area.74 enum Alternative: String, Identifiable {75 case backup, transfer76 var id: String { rawValue }77 }7879 private let stepCount = 580 static let lengths = [12, 15, 18, 21, 24]81 private static let wordSet = Set(BIP39.wordList)8283 var body: some View {84 // One container view, not a Group: see CreateWalletFlow.85 ZStack {86 switch step {87 case .restoreChoice: restoreChoiceStep88 case .phrase: phraseStep89 case .password: passwordStep90 case .protect: ProtectStep(step: 2, stepCount: stepCount) { step = .chains }91 case .chains: OnboardingChainsStep(step: 3, stepCount: stepCount) { step = .done }92 case .done:93 OnboardingDoneStep(title: "Wallet restored", lines: [94 "The accounts of every supported network were derived from your phrase. Balances and history appear after the first synchronization.",95 "It starts on test networks. More networks can be enabled at any time from the wallet.",96 ], step: 4, stepCount: stepCount, onFinish: onClose)97 }98 }99 .sheet(item: $alternative) { kind in100 NavigationStack {101 Group {102 switch kind {103 case .backup: RestoreBackupView(onRestored: restoredElsewhere)104 case .transfer: TransferReceiveView(onRestored: restoredElsewhere)105 }106 }107 .toolbar {108 ToolbarItem(placement: .cancellationAction) { Button("Close") { alternative = nil } }109 }110 }111 .presentedPrivacyCover()112 }113 .onDisappear(perform: clearSecrets)114 #if DEBUG115 .task {116 if DebugLaunch.onboardingStep == "backup" { alternative = .backup }117 if DebugLaunch.onboardingStep == "transfer" { alternative = .transfer }118 if DebugLaunch.onboardingStep == "filled" { words = DebugLaunch.testVectorWords }119 if DebugLaunch.onboardingStep == "password" { words = DebugLaunch.testVectorWords; step = .password }120 if DebugLaunch.onboardingStep == "run" {121 // The whole flow through the same function as the button, with the public test vector.122 await DebugNavigator.shared.waitUntilWalletPrepared()123 words = DebugLaunch.testVectorWords124 password = DebugLaunch.throwawayPassword125 confirmation = DebugLaunch.throwawayPassword126 step = .password127 importWallet()128 }129 }130 #endif131 }132133 var normalized: [String] { words.map(SeedPhraseInput.normalizeWord) }134 var allWordsKnown: Bool { SeedPhraseInput.isComplete(normalized) { Self.wordSet.contains($0) } }135 var phraseProblem: String? {136 guard allWordsKnown else { return nil }137 return BIP39.isValid(normalized) ? nil : "The checksum of this phrase does not verify: a word is wrong or in the wrong place."138 }139140 /// Entry of "Restore from a backup or another iPhone": the two ways that bring a wallet without typing its phrase.141 var restoreChoiceStep: some View {142 OnboardingScaffold(title: "Restore a wallet", step: 0, stepCount: stepCount, onClose: onClose) {143 Text("Bring an existing QYVORA wallet to this iPhone without typing its recovery phrase.")144 .font(QFont.callout).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)145 OnboardingPoint(systemImage: "doc.badge.arrow.up", title: "From an encrypted backup",146 text: "A .qyvora file made in Quantum Recovery, with the password chosen for that backup.")147 Button { alternative = .backup } label: { Label("Restore from a QYVORA backup", systemImage: "doc.badge.arrow.up") }148 .buttonStyle(.qPrimary)149 OnboardingPoint(systemImage: "iphone.and.arrow.forward", title: "From another iPhone",150 text: "The two iPhones show each other a code. You compare the sender's fingerprint before anything is restored.")151 Button { alternative = .transfer } label: { Label("Transfer from another iPhone", systemImage: "iphone.and.arrow.forward") }152 .buttonStyle(.qSecondary)153 } footer: {154 Button("Enter a recovery phrase instead") { step = .phrase }155 .buttonStyle(.qSecondary)156 }157 }158159 var phraseStep: some View {160 OnboardingScaffold(title: "Enter your recovery phrase", step: 0, stepCount: stepCount, onClose: onClose) {161 CompromisedDeviceNotice()162 Text("Type the words in order. Only enter a phrase into a device you trust, away from cameras.")163 .font(QFont.callout).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)164 WalletNoteLine(text: "One phrase restores your accounts on every supported network: " + OnboardingChains.names + ". You choose which ones to show after the import.",165 systemImage: "point.3.connected.trianglepath.dotted")166 Picker("Number of words", selection: Binding(get: { words.count }, set: { resize($0) })) {167 ForEach(Self.lengths, id: \.self) { Text("\($0) words").tag($0) }168 }169 .pickerStyle(.menu)170 .tint(QColor.violet)171 SeedPhraseEntry(words: $words, isValidWord: { Self.wordSet.contains($0) },172 suggestions: { prefix in prefix.isEmpty ? [] : Array(BIP39.wordList.lazy.filter { $0.hasPrefix(prefix) }.prefix(4)) })173 InlineError(message: phraseProblem)174 PassphraseDisclosure(passphrase: $passphrase, isImport: true)175 VStack(alignment: .leading, spacing: 10) {176 SectionHeader("Without typing the phrase", subtitle: "From an encrypted backup file, or directly from another iPhone running QYVORA.")177 Button { alternative = .backup } label: { Label("Restore from a QYVORA backup", systemImage: "doc.badge.arrow.up") }178 .buttonStyle(.qSecondary)179 Button { alternative = .transfer } label: { Label("Transfer from another iPhone", systemImage: "iphone.and.arrow.forward") }180 .buttonStyle(.qSecondary)181 }182 } footer: {183 Button("Continue") { step = .password }184 .buttonStyle(.qPrimary)185 .disabled(!allWordsKnown || phraseProblem != nil)186 }187 }188189 var passwordStep: some View {190 OnboardingScaffold(title: "Master password", step: 1, stepCount: stepCount, onClose: importing ? nil : onClose) {191 Text("It encrypts the vault that will hold the phrase on this device. It is independent of the phrase and cannot be reset.")192 .font(QFont.callout).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)193 NewPasswordForm(password: $password, confirmation: $confirmation)194 InlineError(message: error)195 } footer: {196 LoadingButton("Restore the wallet", loadingTitle: "Creating the vault", state: importing ? .loading : .idle) { importWallet() }197 .disabled(!passwordAccepted || importing)198 Button("Back") { step = .phrase }.buttonStyle(.qSecondary).disabled(importing)199 }200 }201202 var passwordAccepted: Bool {203 NewPasswordForm.problem(password: password, confirmation: confirmation,204 estimate: password.isEmpty ? nil : wallet.service?.passwordQuality(password)) == nil205 }206207 /// The security area's view restored the wallet (vault created and unlocked): continue with quick unlock.208 func restoredElsewhere() {209 alternative = nil210 clearSecrets()211 step = .protect212 }213214 func resize(_ count: Int) {215 guard count != words.count else { return }216 var next = SeedPhraseEntry.emptyWords(count)217 for (i, word) in words.prefix(count).enumerated() { next[i] = word }218 words = next219 }220221 func importWallet() {222 guard passwordAccepted, !importing else { return }223 importing = true224 error = nil225 let phrase = normalized, extra = passphrase.isEmpty ? nil : passphrase, chosen = password226 Task {227 defer { importing = false }228 do {229 try await wallet.run { try await $0.importWallet(words: phrase, passphrase: extra, password: chosen) }230 clearSecrets()231 step = .protect232 } catch {233 self.error = WalletStore.message(for: error)234 }235 }236 }237238 func clearSecrets() {239 words = SeedPhraseEntry.emptyWords(words.count)240 passphrase = ""241 password = ""242 confirmation = ""243 }244}245