diff --git a/Bitkit.xcodeproj/project.pbxproj b/Bitkit.xcodeproj/project.pbxproj
index 160cc18f40..dfddc90742 100644
--- a/Bitkit.xcodeproj/project.pbxproj
+++ b/Bitkit.xcodeproj/project.pbxproj
@@ -178,6 +178,7 @@
Services/HwActivityTagBackup.swift,
Services/HwSnapshotMerge.swift,
Services/LightningService.swift,
+ Services/NodeEventListener.swift,
Services/MigrationsService.swift,
Services/RNBackupClient.swift,
Services/ServiceQueue.swift,
@@ -210,6 +211,7 @@
Services/HwActivityTagBackup.swift,
Services/HwSnapshotMerge.swift,
Services/LightningService.swift,
+ Services/NodeEventListener.swift,
Services/ServiceQueue.swift,
Services/VssStoreIdProvider.swift,
Services/WatchOnlyAccountService.swift,
diff --git a/Bitkit/AppScene.swift b/Bitkit/AppScene.swift
index 7905bdcb08..d23654bece 100644
--- a/Bitkit/AppScene.swift
+++ b/Bitkit/AppScene.swift
@@ -463,6 +463,8 @@ struct AppScene: View {
@State private var walletIsInitializing: Bool? = nil
@State private var isWalletBackupRestoreRunning = false
@State private var didWalletBackupRestoreFail = false
+ @ObservedObject private var connectionRecovery = ConnectionRecoveryService.shared
+ @State private var connectionEditor: ConnectionRecoveryService.Editor?
@State private var isPinVerified: Bool = false
@State private var showRecoveryScreen = false
/// Lets only a return from the background retry a failed node start, not a brief inactive phase.
@@ -1033,7 +1035,14 @@ struct AppScene: View {
@ViewBuilder
private var existingWalletContent: some View {
- if walletIsInitializing == true {
+ if let connectionEditor, connectionRecovery.isCurrent(connectionEditor) {
+ WalletConnectionRecoveryView(
+ editor: connectionEditor,
+ onBack: { self.connectionEditor = nil },
+ onRetry: retryWalletStart,
+ recovery: connectionRecovery
+ )
+ } else if walletIsInitializing == true {
// New wallet is being created or restored
initializingContent
} else if wallet.isRestoringWallet {
@@ -1056,20 +1065,24 @@ struct AppScene: View {
@ViewBuilder
private var initializingContent: some View {
if didWalletBackupRestoreFail {
- WalletRestoreError {
- didWalletBackupRestoreFail = false
- await restoreWalletBackupAndStart()
- }
+ WalletRestoreError(onRetry: retryWalletStart, onConnectionSettings: connectionRecovery.isBusy ? nil : openConnectionRecovery)
} else if case .errorStarting = wallet.nodeLifecycleState {
- WalletRestoreError(onRetry: retryWalletStart)
+ WalletRestoreError(onRetry: retryWalletStart, onConnectionSettings: connectionRecovery.isBusy ? nil : openConnectionRecovery)
} else {
+ let initializationLifecycle = connectionRecovery.lifecycleID
InitializingWalletView(nodeLifecycleState: $wallet.nodeLifecycleState) {
Logger.debug("Wallet finished initializing but node state is \(wallet.nodeLifecycleState)")
- if wallet.nodeLifecycleState == .running {
+ if connectionRecovery.canFinishInitialization(
+ lifecycle: initializationLifecycle,
+ isRunning: wallet.nodeLifecycleState == .running,
+ hasPendingRestore: BackupService.shared.hasPendingWalletRestore(),
+ didFail: didWalletBackupRestoreFail
+ ) {
walletIsInitializing = false
}
}
+ .id(connectionRecovery.isBusy)
}
}
@@ -1099,6 +1112,15 @@ struct AppScene: View {
}
}
+ private func openConnectionRecovery() {
+ guard !connectionRecovery.isBusy else { return }
+ do {
+ connectionEditor = try connectionRecovery.editor()
+ } catch {
+ app.toast(error)
+ }
+ }
+
private func handleWalletExistsChange(_: Bool?) {
Logger.info("Wallet exists state changed: \(wallet.walletExists?.description ?? "nil")")
@@ -1113,7 +1135,10 @@ struct AppScene: View {
}
}
- guard wallet.walletExists == true, !wipeCoordinator.isGateUp else { return }
+ guard wallet.walletExists == true, !wipeCoordinator.isGateUp else {
+ connectionEditor = nil
+ return
+ }
// Don't start wallet if we're in recovery mode
guard !showRecoveryScreen else { return }
@@ -1123,7 +1148,7 @@ struct AppScene: View {
}
let shouldRestoreWalletBackup = wallet.isRestoringWallet || BackupService.shared.hasPendingWalletRestore()
- if shouldRestoreWalletBackup {
+ if connectionRecovery.requiresRestrictedStartup(hasPendingRestore: shouldRestoreWalletBackup) {
walletIsInitializing = true
}
@@ -1143,7 +1168,26 @@ struct AppScene: View {
}
private func startWallet(completingBackupRestore: Bool = false, playsErrorHaptic: Bool = true) async {
+ let lifecycle = connectionRecovery.lifecycleID
+ do {
+ try await connectionRecovery.perform(cancelsWithCaller: false) {
+ await startAdmittedWallet(completingBackupRestore: completingBackupRestore, playsErrorHaptic: playsErrorHaptic)
+ }
+ } catch ConnectionRecoveryService.AdmissionError.busy {
+ return
+ } catch {
+ guard !Task.isCancelled, connectionRecovery.isCurrentLifecycle(lifecycle) else { return }
+ Logger.error(error, context: "Wallet connection recovery")
+ didWalletBackupRestoreFail = true
+ walletIsInitializing = true
+ }
+ }
+
+ private func startAdmittedWallet(completingBackupRestore: Bool, playsErrorHaptic: Bool) async {
let hasPendingRestore = BackupService.shared.hasPendingWalletRestore()
+ if connectionRecovery.requiresRestrictedStartup(hasPendingRestore: hasPendingRestore) {
+ walletIsInitializing = true
+ }
guard !WalletBackupRestoreGate.blocksWalletStart(
isRestoreRunning: isWalletBackupRestoreRunning,
hasPendingRestore: hasPendingRestore,
@@ -1166,8 +1210,19 @@ struct AppScene: View {
}
do {
+ let revision = try connectionRecovery.replay()
+ if revision != nil, wallet.nodeLifecycleState != .stopped, wallet.nodeLifecycleState != .initializing {
+ try await wallet.stopLightningNode()
+ try connectionRecovery.checkCurrentOperation()
+ }
try await wallet.start()
guard !wipeCoordinator.isGateUp else { return }
+ try connectionRecovery.checkCurrentOperation()
+ try connectionRecovery.complete(revision: revision, hasPendingRestore: BackupService.shared.hasPendingWalletRestore(),
+ isRunning: wallet.nodeLifecycleState == .running)
+ {
+ didWalletBackupRestoreFail = false
+ }
try await activity.syncLdkNodePayments()
// Open the swap updates stream so any pending LN -> onchain swaps resume
@@ -1177,7 +1232,11 @@ struct AppScene: View {
// Schedule full backup after wallet create/restore to prevent epoch dates in backup status
await BackupService.shared.scheduleFullBackup()
} catch {
+ guard connectionRecovery.canReportOperationFailure() else { return }
Logger.error(error, context: "Failed to start wallet")
+ if walletIsInitializing == true, connectionRecovery.canReportStartupFailure() {
+ didWalletBackupRestoreFail = true
+ }
if playsErrorHaptic {
Haptics.notify(.error)
}
@@ -1284,6 +1343,22 @@ struct AppScene: View {
}
private func restoreWalletBackupAndStart() async {
+ let lifecycle = connectionRecovery.lifecycleID
+ do {
+ try await connectionRecovery.perform(cancelsWithCaller: false) {
+ await restoreAdmittedWalletBackupAndStart()
+ }
+ } catch ConnectionRecoveryService.AdmissionError.busy {
+ return
+ } catch {
+ guard !Task.isCancelled, connectionRecovery.isCurrentLifecycle(lifecycle) else { return }
+ Logger.error(error, context: "Restore connection recovery")
+ didWalletBackupRestoreFail = true
+ walletIsInitializing = true
+ }
+ }
+
+ private func restoreAdmittedWalletBackupAndStart() async {
guard !isWalletBackupRestoreRunning, !wipeCoordinator.isGateUp else { return }
isWalletBackupRestoreRunning = true
walletIsInitializing = true
@@ -1295,6 +1370,14 @@ struct AppScene: View {
} else {
await restoreFromMostRecentBackup()
}
+ do {
+ try connectionRecovery.checkCurrentOperation()
+ } catch {
+ guard connectionRecovery.canReportOperationFailure() else { return }
+ didWalletBackupRestoreFail = true
+ app.toast(error)
+ return
+ }
guard didRestore else {
didWalletBackupRestoreFail = true
return
@@ -1307,12 +1390,45 @@ struct AppScene: View {
}
private func retryWalletStart() async {
+ let lifecycle = connectionRecovery.lifecycleID
do {
- wallet.nodeLifecycleState = .initializing
- try await wallet.start()
- try wallet.setWalletExistsState()
+ try await connectionRecovery.perform(cancelsWithCaller: false) {
+ do {
+ walletIsInitializing = true
+ didWalletBackupRestoreFail = false
+ let needsRestore = wallet.isRestoringWallet || BackupService.shared.hasPendingWalletRestore()
+ if !needsRestore {
+ _ = try connectionRecovery.replay()
+ }
+ try await wallet.stopLightningNode()
+ try connectionRecovery.checkCurrentOperation()
+ if needsRestore || BackupService.shared.hasPendingWalletRestore() {
+ await restoreAdmittedWalletBackupAndStart()
+ } else {
+ await startAdmittedWallet(completingBackupRestore: false, playsErrorHaptic: true)
+ }
+ try connectionRecovery.checkCurrentOperation()
+ if connectionRecovery.canReportStartupFailure() {
+ didWalletBackupRestoreFail = true
+ }
+ if wallet.nodeLifecycleState == .running, !BackupService.shared.hasPendingWalletRestore(), !didWalletBackupRestoreFail {
+ connectionEditor = nil
+ }
+ } catch {
+ guard connectionRecovery.canReportOperationFailure() else { return }
+ walletIsInitializing = true
+ didWalletBackupRestoreFail = true
+ app.toast(error)
+ }
+ }
+ } catch ConnectionRecoveryService.AdmissionError.busy {
+ return
} catch {
+ guard !Task.isCancelled, connectionRecovery.isCurrentLifecycle(lifecycle) else { return }
+ walletIsInitializing = true
+ didWalletBackupRestoreFail = true
Logger.error("Failed to start wallet on retry", context: "AppScene")
+ app.toast(error)
Haptics.notify(.error)
}
}
@@ -1371,6 +1487,7 @@ struct AppScene: View {
try await BackupService.shared.restoreUsdtRecoveryAfterLegacyMigration()
return true
} catch {
+ guard connectionRecovery.canReportOperationFailure() else { return false }
app.toast(error)
return false
}
@@ -1384,6 +1501,7 @@ struct AppScene: View {
try await BackupService.shared.performFullRestoreFromLatestBackup()
return true
} catch {
+ guard connectionRecovery.canReportOperationFailure() else { return false }
app.toast(error)
return false
}
diff --git a/Bitkit/Managers/PubkyProfileManager.swift b/Bitkit/Managers/PubkyProfileManager.swift
index a5075b567a..9e32b5bead 100644
--- a/Bitkit/Managers/PubkyProfileManager.swift
+++ b/Bitkit/Managers/PubkyProfileManager.swift
@@ -1320,6 +1320,9 @@ class PubkyProfileManager: ObservableObject {
let resolve = remoteProfileResolver
do {
+ #if DEBUG
+ try ConnectionRecoveryTestFault.check("profile:load")
+ #endif
let loadedProfile = try await Task.detached {
try await resolve(pk)
}.value
diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings
index fbda9edd38..e6f7077035 100644
--- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings
+++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings
@@ -1746,6 +1746,8 @@
"subscriptions__allowance_limit_description" = "طلب بقيمة {amount} من {name} يتجاوز مخصصك. راجعه للدفع.";
"subscriptions__allowance_auto_paid" = "مدفوع تلقائيًا";
+"onboarding__connection_settings" = "إعدادات الاتصال";
+"onboarding__connection_saved" = "تم الحفظ. أعد المحاولة لمتابعة الاستعادة.";
"wallet__balance_updating" = "جارٍ تحديث الرصيد…";
"other__error_keychain" = "مشكلة في الاتصال بالبيانات";
"other__error_keychain_msg" = "تعذر تحميل المفتاح الأساسي من سلسلة المفاتيح.";
diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings
index 65e05f224f..42436be406 100644
--- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings
+++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings
@@ -1930,6 +1930,8 @@
"subscriptions__allowance_limit_description" = "Una sol·licitud de {amount} de {name} supera la teva assignació. Revisa-la per pagar.";
"subscriptions__allowance_auto_paid" = "Pagat automàticament";
+"onboarding__connection_settings" = "Configuració de connexió";
+"onboarding__connection_saved" = "Desat. Torna-ho a provar per continuar restaurant.";
"wallet__balance_updating" = "S’està actualitzant el saldo…";
"other__error_keychain" = "Problema de connexió de dades";
"other__error_keychain_msg" = "No s'ha pogut carregar la clau principal del clauer.";
diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings
index f5c4f52ce8..3bfea53c48 100644
--- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings
+++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings
@@ -2069,4 +2069,6 @@
"subscriptions__allowance_limit_description" = "Žádost o {amount} od {name} přesahuje vaše povolení. Zkontrolujte ji a zaplaťte.";
"subscriptions__allowance_auto_paid" = "Zaplaceno automaticky";
+"onboarding__connection_settings" = "Nastavení připojení";
+"onboarding__connection_saved" = "Uloženo. Zkuste to znovu a pokračujte v obnově.";
"wallet__balance_updating" = "Aktualizace zůstatku…";
diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings
index 4f12e6c691..b4c449ad43 100644
--- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings
+++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings
@@ -2066,4 +2066,6 @@
"subscriptions__allowance_limit_description" = "Eine Anforderung über {amount} von {name} übersteigt dein Kontingent. Prüfe sie, um zu bezahlen.";
"subscriptions__allowance_auto_paid" = "Automatisch bezahlt";
+"onboarding__connection_settings" = "Verbindungseinstellungen";
+"onboarding__connection_saved" = "Gespeichert. Versuche es erneut, um die Wiederherstellung fortzusetzen.";
"wallet__balance_updating" = "Kontostand wird aktualisiert…";
diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings
index 4258654bfe..37d8af219d 100644
--- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings
+++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings
@@ -1801,6 +1801,8 @@
"subscriptions__allowance_limit_description" = "Ένα αίτημα {amount} από {name} υπερβαίνει την προέγκρισή σου. Έλεγξέ το για να πληρώσεις.";
"subscriptions__allowance_auto_paid" = "Πληρώθηκε αυτόματα";
+"onboarding__connection_settings" = "Ρυθμίσεις σύνδεσης";
+"onboarding__connection_saved" = "Αποθηκεύτηκε. Δοκιμάστε ξανά για να συνεχίσετε την επαναφορά.";
"wallet__balance_updating" = "Ενημέρωση υπολοίπου…";
"other__error_keychain" = "Πρόβλημα Σύνδεσης Δεδομένων";
"other__error_keychain_msg" = "Δεν ήταν δυνατή η φόρτωση του κύριου κλειδιού από την κλειδοθήκη.";
diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings
index 36ba4b736a..998a59d679 100644
--- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings
+++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings
@@ -2191,6 +2191,8 @@
"usdt__error_bridge_liquidity" = "This route cannot complete the transfer right now. Try another network or try again later.";
"usdt__receive_copied" = "Address copied to clipboard.\nMake sure USDT is only sent on the selected network.";
+"onboarding__connection_settings" = "Connection settings";
+"onboarding__connection_saved" = "Saved. Retry to continue restoring.";
"wallet__balance_updating" = "Updating balance…";
"lightning__move_to_spark__in_flight_text" = "The payment is on its way and shows in Spark once it settles. If it fails, the amount stays in your connection.";
"lightning__move_to_spark__in_flight_title" = "Moving to\nSpark";
diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings
index 3fef18314b..e8adfa0772 100644
--- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings
+++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings
@@ -2072,4 +2072,6 @@
"subscriptions__allowance_limit_description" = "Una solicitud de {amount} de {name} supera su asignación. Revísela para pagar.";
"subscriptions__allowance_auto_paid" = "Pagado automáticamente";
+"onboarding__connection_settings" = "Configuración de conexión";
+"onboarding__connection_saved" = "Guardado. Reintenta para continuar la restauración.";
"wallet__balance_updating" = "Actualizando saldo…";
diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings
index ccbc2f230c..48be36d6d2 100644
--- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings
+++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings
@@ -1951,4 +1951,6 @@
"subscriptions__allowance_limit_description" = "Una solicitud de {amount} de {name} supera su asignación. Revísela para pagar.";
"subscriptions__allowance_auto_paid" = "Pagado automáticamente";
+"onboarding__connection_settings" = "Ajustes de conexión";
+"onboarding__connection_saved" = "Guardado. Reintenta para continuar la restauración.";
"wallet__balance_updating" = "Actualizando saldo…";
diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings
index 57735fe7e3..34920d6ff8 100644
--- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings
+++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings
@@ -2080,4 +2080,6 @@
"subscriptions__allowance_limit_description" = "Une demande de {amount} de {name} dépasse votre allocation. Examinez-la pour payer.";
"subscriptions__allowance_auto_paid" = "Payé automatiquement";
+"onboarding__connection_settings" = "Paramètres de connexion";
+"onboarding__connection_saved" = "Enregistré. Réessayez pour poursuivre la restauration.";
"wallet__balance_updating" = "Mise à jour du solde…";
diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings
index 998346c2ca..60def0f3e2 100644
--- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings
+++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings
@@ -2039,4 +2039,6 @@
"subscriptions__allowance_limit_description" = "Una richiesta di {amount} da {name} supera il tuo plafond. Controllala per pagare.";
"subscriptions__allowance_auto_paid" = "Pagato automaticamente";
+"onboarding__connection_settings" = "Impostazioni di connessione";
+"onboarding__connection_saved" = "Salvato. Riprova per continuare il ripristino.";
"wallet__balance_updating" = "Aggiornamento del saldo…";
diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings
index ef7e2dc79a..287150c3d2 100644
--- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings
+++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings
@@ -2074,4 +2074,6 @@
"subscriptions__allowance_limit_description" = "Een verzoek van {amount} van {name} overschrijdt uw toelage. Bekijk het om te betalen.";
"subscriptions__allowance_auto_paid" = "Automatisch betaald";
+"onboarding__connection_settings" = "Verbindingsinstellingen";
+"onboarding__connection_saved" = "Opgeslagen. Probeer opnieuw om het herstel voort te zetten.";
"wallet__balance_updating" = "Saldo bijwerken…";
diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings
index cbc29d3dd0..122ced44cb 100644
--- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings
+++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings
@@ -2079,4 +2079,6 @@
"subscriptions__allowance_limit_description" = "Żądanie {amount} od {name} przekracza Twój przydział. Przejrzyj je, aby zapłacić.";
"subscriptions__allowance_auto_paid" = "Opłacono automatycznie";
+"onboarding__connection_settings" = "Ustawienia połączenia";
+"onboarding__connection_saved" = "Zapisano. Spróbuj ponownie, aby kontynuować przywracanie.";
"wallet__balance_updating" = "Aktualizowanie salda…";
diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings
index d13474250d..9951fc5481 100644
--- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings
+++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings
@@ -2080,4 +2080,6 @@
"subscriptions__allowance_limit_description" = "Uma solicitação de {amount} de {name} excede sua pré-aprovação. Revise-a para pagar.";
"subscriptions__allowance_auto_paid" = "Pago automaticamente";
+"onboarding__connection_settings" = "Configurações de conexão";
+"onboarding__connection_saved" = "Salvo. Tente novamente para continuar a restauração.";
"wallet__balance_updating" = "Atualizando saldo…";
diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings
index fbb3fccaa8..43b3d4e855 100644
--- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings
+++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings
@@ -1726,6 +1726,8 @@
"subscriptions__allowance_limit_description" = "Um pedido de {amount} de {name} excede a sua pré-aprovação. Reveja-o para pagar.";
"subscriptions__allowance_auto_paid" = "Pago automaticamente";
+"onboarding__connection_settings" = "Definições de ligação";
+"onboarding__connection_saved" = "Guardado. Tente novamente para continuar o restauro.";
"wallet__balance_updating" = "A atualizar o saldo…";
"other__error_keychain" = "Problema de Ligação de Dados";
"other__error_keychain_msg" = "Não foi possível carregar a chave principal do porta-chaves.";
diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings
index 4b84db822e..018ae3ab7c 100644
--- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings
+++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings
@@ -2060,4 +2060,6 @@
"subscriptions__allowance_limit_description" = "Запрос на {amount} от {name} превышает ваш лимит автооплаты. Проверьте его, чтобы оплатить.";
"subscriptions__allowance_auto_paid" = "Оплачено автоматически";
+"onboarding__connection_settings" = "Настройки подключения";
+"onboarding__connection_saved" = "Сохранено. Повторите попытку, чтобы продолжить восстановление.";
"wallet__balance_updating" = "Обновление баланса…";
diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift
index 72b5647f80..bcfc8345ad 100644
--- a/Bitkit/Services/BackupService.swift
+++ b/Bitkit/Services/BackupService.swift
@@ -138,6 +138,11 @@ class BackupService {
/// Set while the Spark exit data restore hasn't succeeded or found no older backup, kept across launches, so a fresh
/// export never replaces the remote backup it couldn't read yet.
private static let sparkExitRestorePendingKey = "sparkExitRestorePending"
+ private let connectionRecovery: ConnectionRecoveryService?
+ @MainActor private var connectionRecoveryService: ConnectionRecoveryService {
+ connectionRecovery ?? .shared
+ }
+
private let backupData: ((BackupCategory) async throws -> Data)?
private let isSparkExitActive: () async -> Bool
private let uploadBackup: (String, Data) async throws -> Void
@@ -170,6 +175,7 @@ class BackupService {
init(
defaults: UserDefaults = .standard,
+ connectionRecovery: ConnectionRecoveryService? = nil,
backupData: ((BackupCategory) async throws -> Data)? = nil,
isSparkExitActive: @escaping () async -> Bool = { @MainActor in SparkExitManager.shared.isExiting },
usdtRecoveryBackup: UsdtRecoveryBackupStore = UsdtRecoveryBackupStore(),
@@ -193,6 +199,7 @@ class BackupService {
self.defaults = defaults
self.isSparkExitActive = isSparkExitActive
self.fetchBackup = fetchBackup
+ self.connectionRecovery = connectionRecovery
self.backupData = backupData
self.usdtRecoveryBackup = usdtRecoveryBackup
self.uploadBackup = uploadBackup
@@ -703,6 +710,12 @@ class BackupService {
/// Performs full restore from latest backup
func performFullRestoreFromLatestBackup() async throws {
+ try await connectionRecoveryService.perform {
+ try await self.restoreLatestWalletBackup()
+ }
+ }
+
+ private func restoreLatestWalletBackup() async throws {
if UsdtRecoveryRestoreGate.isPending, try !walletRestoreGate.hasPendingRestore() {
try await restoreUsdtRecoveryAfterLegacyMigration()
return
@@ -715,7 +728,7 @@ class BackupService {
Logger.debug("Full restore starting", context: "BackupService")
do {
- _ = try await walletRestoreGate.performRestore { retainedWalletBackup in
+ _ = try await connectionRecoveryService.restoreRequired(gate: walletRestoreGate) { [self] retainedWalletBackup in
try UsdtRecoveryRestoreGate.begin()
await usdtWallet?.pauseForRecoveryRestore()
await usdtBackupWriter.waitUntilIdle()
@@ -760,7 +773,14 @@ class BackupService {
}
func restoreUsdtRecoveryAfterLegacyMigration() async throws {
+ try await connectionRecoveryService.perform {
+ try await self.restoreLegacyUsdtRecovery()
+ }
+ }
+
+ private func restoreLegacyUsdtRecovery() async throws {
let retained = try UsdtRecoveryRestoreGate.begin()
+ _ = try await connectionRecoveryService.replay()
await usdtWallet?.pauseForRecoveryRestore()
await usdtBackupWriter.waitUntilIdle()
await walletBackupWriter.waitUntilIdle()
@@ -789,6 +809,7 @@ class BackupService {
try await PaykitUsdtPaymentService.shared.restoreBackup($0)
}
)
+ _ = try await connectionRecoveryService.replay()
try UsdtRecoveryRestoreGate.complete()
await usdtWallet?.resumeAfterRecoveryRestore()
markRestoreComplete(category: .usdt)
@@ -798,9 +819,12 @@ class BackupService {
do {
try await performRestore(category: .settings) { dataBytes in
let payload = try SettingsBackupV1.decode(from: dataBytes)
- await SettingsViewModel.shared.restoreSettingsDictionary(payload.settings)
+ let settings = try await connectionRecoveryService.mergeRestoredSettings(payload.settings)
+ await SettingsViewModel.shared.restoreSettingsDictionary(settings)
}
+ _ = try await connectionRecoveryService.replay()
+
try await performRestore(category: .widgets) { dataBytes in
let payload = try WidgetsBackupV1.decode(from: dataBytes)
let widgets = try WidgetsBackupConverter.convertFromAndroidFormat(jsonDict: payload.widgets)
diff --git a/Bitkit/Services/ConnectionRecoveryService.swift b/Bitkit/Services/ConnectionRecoveryService.swift
new file mode 100644
index 0000000000..9189de7fcc
--- /dev/null
+++ b/Bitkit/Services/ConnectionRecoveryService.swift
@@ -0,0 +1,343 @@
+import Combine
+import Foundation
+import VssRustClientFfi
+
+@MainActor
+final class ConnectionRecoveryService: ObservableObject {
+ enum AdmissionError: Error {
+ case busy
+ }
+
+ struct Owner: Codable, Equatable {
+ let walletIndex: Int
+ let network: String
+ let binding: String
+ }
+
+ struct Record: Codable, Equatable {
+ let version: Int
+ let owner: Owner
+ let revision: UUID
+ var electrum: ElectrumServer?
+ var rgs: String?
+ }
+
+ struct Editor {
+ let owner: Owner
+ let generation: UUID
+ let revision: UUID?
+ let electrum: ElectrumServer
+ let rgs: String
+ }
+
+ private final class Access {
+ let service: ConnectionRecoveryService
+ let id: UUID
+ let generation: UUID
+ var owner: Owner?
+
+ init(service: ConnectionRecoveryService, id: UUID, generation: UUID) {
+ self.service = service
+ self.id = id
+ self.generation = generation
+ }
+ }
+
+ @TaskLocal private static var access: Access?
+
+ static let shared = ConnectionRecoveryService(
+ owner: {
+ guard let mnemonic = try Keychain.loadString(key: .bip39Mnemonic(index: 0)) else {
+ throw CustomServiceError.mnemonicNotFound
+ }
+ let passphrase = try Keychain.loadString(key: .bip39Passphrase(index: 0))
+ let namespace = try vssDeriveStoreId(
+ prefix: Env.vssStoreIdPrefix, mnemonic: mnemonic,
+ passphrase: passphrase?.isEmpty == true ? nil : passphrase
+ )
+ return Owner(walletIndex: 0, network: Env.networkName,
+ binding: PaykitPaymentStateBackup.ActiveOnchainAttempt.Wallet.binding(storeId: namespace))
+ },
+ load: { try Keychain.load(key: .connectionRecovery) },
+ store: { try Keychain.upsert(key: .connectionRecovery, data: $0) },
+ clear: { try Keychain.delete(key: .connectionRecovery) }
+ )
+
+ @Published private(set) var isBusy = false
+ var lifecycleID: UUID {
+ generation
+ }
+
+ private var generation = UUID()
+ private var readyGeneration: UUID?
+ private var wipeID: UUID?
+ private var isWiping: Bool {
+ wipeID != nil
+ }
+
+ private var activeID: UUID?
+ private var cancelActive: (() -> Void)?
+ private var drainActive: (() async -> Void)?
+ private let owner: () throws -> Owner
+ private let load: () throws -> Data?
+ private let store: (Data) throws -> Void
+ private let clear: () throws -> Void
+ private let defaults: UserDefaults
+
+ init(
+ owner: @escaping () throws -> Owner,
+ load: @escaping () throws -> Data?,
+ store: @escaping (Data) throws -> Void,
+ clear: @escaping () throws -> Void,
+ defaults: UserDefaults = .standard
+ ) {
+ self.owner = owner
+ self.load = load
+ self.store = store
+ self.clear = clear
+ self.defaults = defaults
+ }
+
+ func perform(cancelsWithCaller: Bool = true, _ body: @escaping @MainActor () async throws -> T) async throws -> T {
+ if let access = Self.access, access.service === self {
+ try validate(access)
+ return try await body()
+ }
+ try Task.checkCancellation()
+ guard !isWiping, activeID == nil else { throw AdmissionError.busy }
+ let access = Access(service: self, id: UUID(), generation: generation)
+ activeID = access.id
+ readyGeneration = nil
+ isBusy = true
+ let task = Task { @MainActor in
+ try await Self.$access.withValue(access) {
+ try self.validate(access)
+ let value = try await body()
+ try self.validate(access)
+ return value
+ }
+ }
+ cancelActive = { task.cancel() }
+ drainActive = { _ = await task.result }
+ defer {
+ if activeID == access.id {
+ activeID = nil
+ cancelActive = nil
+ drainActive = nil
+ isBusy = false
+ }
+ }
+ return try await withTaskCancellationHandler {
+ try await task.value
+ } onCancel: {
+ if cancelsWithCaller {
+ task.cancel()
+ }
+ }
+ }
+
+ func beginWipe(timeout: Duration = .seconds(30)) async throws -> UUID {
+ guard wipeID == nil else { throw AdmissionError.busy }
+ let id = UUID()
+ wipeID = id
+ readyGeneration = nil
+ generation = UUID()
+ cancelActive?()
+ if let drainActive, await withDeadline(timeout, { await drainActive() }) == nil {
+ // The original operation still owns activeID until it really finishes. A timeout
+ // releases only this wipe attempt, so Retry can wait again without admitting new work.
+ endWipe(id)
+ throw WipeWaitTimeoutError(wait: "connection recovery")
+ }
+ return id
+ }
+
+ func endWipe(_ id: UUID) {
+ guard wipeID == id else { return }
+ wipeID = nil
+ }
+
+ func isCurrentLifecycle(_ id: UUID) -> Bool {
+ !isWiping && generation == id
+ }
+
+ func requiresRestrictedStartup(hasPendingRestore: Bool) -> Bool {
+ if hasPendingRestore {
+ return true
+ }
+ do { return try load() != nil } catch { return true }
+ }
+
+ func canFinishInitialization(lifecycle: UUID, isRunning: Bool, hasPendingRestore: Bool, didFail: Bool) -> Bool {
+ isCurrentLifecycle(lifecycle) && readyGeneration == lifecycle && !isBusy && isRunning && !hasPendingRestore && !didFail
+ }
+
+ func editor() throws -> Editor {
+ guard !isWiping, !isBusy else { throw failure("Connection recovery is already in progress") }
+ let currentOwner = try owner()
+ let record = try read(for: currentOwner)
+ return Editor(owner: currentOwner, generation: generation, revision: record?.revision,
+ electrum: record?.electrum ?? ElectrumConfigService(defaults: defaults).getCurrentServer(),
+ rgs: record?.rgs ?? RgsConfigService(defaults: defaults).getCurrentServerUrl())
+ }
+
+ func isCurrent(_ editor: Editor) -> Bool {
+ !isWiping && editor.generation == generation && (try? owner()) == editor.owner
+ }
+
+ func save(
+ editor: Editor,
+ electrum: ElectrumServer? = nil,
+ rgs: String? = nil,
+ validateEndpoint: @escaping () async throws -> Void = {}
+ ) async throws {
+ try await perform {
+ try self.requireCurrent(editor)
+ try await validateEndpoint()
+ try self.requireCurrent(editor)
+ var record = try self.read(for: editor.owner)
+ guard record?.revision == editor.revision else { throw self.failure("Connection settings changed; reopen the editor") }
+ record = Record(version: 1, owner: editor.owner, revision: UUID(),
+ electrum: electrum ?? record?.electrum, rgs: rgs ?? record?.rgs)
+ guard let record, record.electrum != nil || record.rgs != nil else { return }
+ let data = try JSONEncoder().encode(record)
+ try self.store(data)
+ guard try self.load() == data else { throw self.failure("Connection settings could not be saved") }
+ try self.apply(record)
+ }
+ }
+
+ func replay() throws -> UUID? {
+ let access = try currentAccess()
+ guard let record = try read(for: boundOwner(access)) else { return nil }
+ try apply(record)
+ return record.revision
+ }
+
+ func restoreRequired(
+ gate: WalletBackupRestoreGate,
+ restore: @escaping (Data?) async throws -> Bool
+ ) async throws -> Bool {
+ try await perform {
+ try await gate.performRestore { retained in
+ _ = try self.replay()
+ let restored = try await restore(retained)
+ _ = try self.replay()
+ return restored
+ }
+ }
+ }
+
+ func mergeRestoredSettings(_ settings: [String: Any]) throws -> [String: Any] {
+ let access = try currentAccess()
+ guard let record = try read(for: boundOwner(access)) else { return settings }
+ var merged = settings
+ if let electrum = record.electrum {
+ merged["electrumServer"] = electrum.fullUrl
+ }
+ if let rgs = record.rgs {
+ merged["rgsServerUrl"] = rgs
+ }
+ return merged
+ }
+
+ func complete(revision: UUID?, hasPendingRestore: Bool, isRunning: Bool, onReady: () -> Void = {}) throws {
+ let access = try currentAccess()
+ guard !hasPendingRestore, isRunning else { return }
+ if let revision {
+ guard let record = try read(for: boundOwner(access)), record.revision == revision else { return }
+ try apply(record)
+ try clear()
+ guard try load() == nil else { throw failure("Connection recovery could not be finalized") }
+ } else {
+ guard try read(for: boundOwner(access)) == nil else { return }
+ }
+ readyGeneration = generation
+ onReady()
+ }
+
+ func checkCurrentOperation() throws {
+ guard let access = Self.access, access.service === self else { throw failure("Connection recovery requires an active wallet operation") }
+ try validate(access)
+ }
+
+ func canReportOperationFailure() -> Bool {
+ guard let access = Self.access, access.service === self else { return false }
+ return !isWiping && activeID == access.id && generation == access.generation
+ }
+
+ func canReportStartupFailure() -> Bool {
+ canReportOperationFailure() && readyGeneration != generation
+ }
+
+ private func currentAccess() throws -> Access {
+ guard let access = Self.access, access.service === self else { throw failure("Connection recovery requires an active wallet operation") }
+ try validate(access)
+ _ = try boundOwner(access)
+ return access
+ }
+
+ private func boundOwner(_ access: Access) throws -> Owner {
+ if let original = access.owner {
+ return original
+ }
+ let original = try owner()
+ access.owner = original
+ return original
+ }
+
+ private func validate(_ access: Access) throws {
+ try Task.checkCancellation()
+ guard !isWiping, activeID == access.id, generation == access.generation else {
+ throw failure("Wallet changed during connection recovery")
+ }
+ if let original = access.owner, try owner() != original {
+ throw failure("Wallet changed during connection recovery")
+ }
+ }
+
+ private func requireCurrent(_ editor: Editor) throws {
+ _ = try currentAccess()
+ guard isCurrent(editor) else { throw failure("Wallet changed; reopen connection settings") }
+ }
+
+ private func read(for owner: Owner) throws -> Record? {
+ guard let data = try load() else { return nil }
+ let record = try JSONDecoder().decode(Record.self, from: data)
+ guard record.version == 1, record.owner.walletIndex >= 0,
+ !record.owner.network.isEmpty, !record.owner.binding.isEmpty,
+ record.electrum != nil || record.rgs != nil else { throw failure("Saved connection recovery is unavailable") }
+ if let server = record.electrum, server.host.isEmpty || !(1 ... 65535).contains(server.port) {
+ throw failure("Saved Electrum settings are invalid")
+ }
+ guard record.owner == owner else { throw failure("Saved connection recovery belongs to another wallet") }
+ return record
+ }
+
+ private func apply(_ record: Record) throws {
+ _ = try currentAccess()
+ if let electrum = record.electrum {
+ let data = try JSONEncoder().encode(electrum)
+ defaults.set(data, forKey: "electrumServer")
+ #if DEBUG
+ try ConnectionRecoveryTestFault.check("preferences:readback")
+ #endif
+ guard defaults.data(forKey: "electrumServer") == data else { throw failure("Electrum settings could not be saved") }
+ }
+ if let rgs = record.rgs {
+ defaults.set(rgs, forKey: "rapidGossipSyncUrl")
+ #if DEBUG
+ try ConnectionRecoveryTestFault.check("preferences:readback")
+ #endif
+ guard defaults.string(forKey: "rapidGossipSyncUrl") == rgs else { throw failure("RGS settings could not be saved") }
+ }
+ #if DEBUG
+ try ConnectionRecoveryTestFault.check("preferences:flush")
+ #endif
+ guard defaults.synchronize() else { throw failure("Connection settings could not be persisted") }
+ }
+
+ private func failure(_ message: String) -> Error {
+ AppError(message: message, debugMessage: nil)
+ }
+}
diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift
index 4e512d8b4a..5b86bc2705 100644
--- a/Bitkit/Services/LightningService.swift
+++ b/Bitkit/Services/LightningService.swift
@@ -97,7 +97,7 @@ enum LightningPaymentRail {
protocol NodeLifecycleService: AnyObject {
var hasNode: Bool { get }
func setup(walletIndex: Int, electrumServerUrl: String?, rgsServerUrl: String?, channelMigration: ChannelDataMigration?) async throws
- func start(onEvent: ((Event) -> Void)?) async throws
+ func start(onEvent: (@MainActor (Event) -> Void)?) async throws
func stop(clearEventCallback: Bool) async throws
func isNodeRunning() async -> Bool
func wipeStorage(walletIndex: Int) async throws
@@ -136,7 +136,8 @@ class LightningService: NodeLifecycleService {
/// Guards the event callback and the rail events waiting for it, which the node and the rail set from different threads.
private let eventCallbackLock = NSLock()
- private var storedEventCallback: ((Event) -> Void)?
+ private var storedEventCallback: (@MainActor (Event) -> Void)?
+ @MainActor private var eventListener = NodeEventListener()
/// Rail events that arrived before the node's event callback was set, delivered once it is.
private var pendingChannelFreeRailEvents: [Event] = []
/// The rail each payment hash's latest attempt went out on, so a stale failure from the other rail can't settle a
@@ -308,14 +309,7 @@ class LightningService: NodeLifecycleService {
// Stop the current node if it exists, ignore errors if already stopped
if node != nil {
- do {
- try await stop()
- } catch {
- Logger.debug("Node was already stopped or failed to stop: \(error)")
- // Clear the node reference anyway
- node = nil
- try? StateLocker.unlock(.lightning)
- }
+ try await stop()
}
// Restart the node with the current configuration
@@ -344,13 +338,7 @@ class LightningService: NodeLifecycleService {
// Stop the current node if it exists
if node != nil {
- do {
- try await stop()
- } catch {
- Logger.error("Failed to stop node during recovery: \(error)")
- node = nil
- try? StateLocker.unlock(.lightning)
- }
+ try await stop()
}
Logger.debug("Starting node with previous config for recovery")
@@ -368,7 +356,7 @@ class LightningService: NodeLifecycleService {
/// Pass onEvent when being used in the background to listen for payments, channels, closes, etc
/// - Parameter onEvent: Triggered on any LDK node event
- func start(onEvent: ((Event) -> Void)? = nil) async throws {
+ func start(onEvent: (@MainActor (Event) -> Void)? = nil) async throws {
guard let node else {
throw AppError(serviceError: .nodeNotSetup)
}
@@ -377,11 +365,9 @@ class LightningService: NodeLifecycleService {
setEventCallback(onEvent)
}
- listenForEvents(onEvent: eventCallbackLock.withLock { storedEventCallback })
-
Logger.debug("Starting node...")
- try await ServiceQueue.background(.ldk) {
- try node.start()
+ try await eventListener.start(node: node) { [weak self] event in
+ await self?.handleEvent(event)
}
#if !BITKIT_NOTIFICATION_EXTENSION
@@ -426,8 +412,8 @@ class LightningService: NodeLifecycleService {
}
Logger.debug("Stopping node...")
- try await ServiceQueue.background(.ldk) {
- try Self.stopReleasingFinishedNode(node.stop)
+ try await eventListener.stop(node: node) { [weak self] event in
+ await self?.handleEvent(event)
}
self.node = nil
@@ -2207,13 +2193,23 @@ extension LightningService {
extension LightningService {
/// Delivers a channel-free rail's payment as an LDK event, so flows that wait on node events cover both rails.
/// Sets the callback node and rail events are delivered to, and delivers the rail events that arrived before it.
- func setEventCallback(_ onEvent: @escaping (Event) -> Void) {
+ func setEventCallback(_ onEvent: @escaping @MainActor (Event) -> Void) {
let pending = eventCallbackLock.withLock {
storedEventCallback = onEvent
defer { pendingChannelFreeRailEvents = [] }
return pendingChannelFreeRailEvents
}
- pending.forEach(onEvent)
+ Self.deliverOnMainActor(pending, to: onEvent)
+ }
+
+ /// The node's event callback runs on the main actor; rail events from elsewhere hop there, in order.
+ private static func deliverOnMainActor(_ events: [Event], to callback: @escaping @MainActor (Event) -> Void) {
+ guard !events.isEmpty else { return }
+ if Thread.isMainThread {
+ MainActor.assumeIsolated { events.forEach(callback) }
+ } else {
+ Task { @MainActor in events.forEach(callback) }
+ }
}
/// Drops the event callback and the rail events waiting for it.
@@ -2247,7 +2243,9 @@ extension LightningService {
}
return storedEventCallback
}
- callback?(event)
+ if let callback {
+ Self.deliverOnMainActor([event], to: callback)
+ }
}
func noteAttempt(on rail: LightningPaymentRail, paymentHash: String) {
@@ -2310,7 +2308,7 @@ extension LightningService {
return []
}
- func deliverEvent(_ event: Event, onEvent: ((Event) -> Void)?) async -> OnchainActivityCompletion? {
+ func deliverEvent(_ event: Event, onEvent: (@MainActor (Event) -> Void)?) async -> OnchainActivityCompletion? {
let completion: OnchainActivityCompletion? = switch event {
case .onchainTransactionReceived, .onchainTransactionConfirmed, .onchainTransactionReplaced,
.onchainTransactionReorged, .onchainTransactionEvicted:
@@ -2319,7 +2317,7 @@ extension LightningService {
default:
nil
}
- onEvent?(event)
+ await onEvent?(event)
return completion
}
@@ -2328,214 +2326,197 @@ extension LightningService {
await completion?()
}
- func listenForEvents(onEvent: ((Event) -> Void)? = nil) {
- Task {
- while true {
- guard let node = self.node else {
- Logger.error("LDK node not started")
- return
- }
+ private func handleEvent(_ event: Event) async {
+ if case .channelReady = event {
+ await refreshChannelCache()
+ }
+
+ if isStaleFailure(event, from: .ldk) {
+ Logger.info("Ignored an LDK failure for a payment retried over Spark: \(event)", context: "LightningService")
+ return
+ }
- let event = await node.nextEventAsync()
+ let onchainActivityCompletion = await deliverEvent(event, onEvent: eventCallbackLock.withLock { storedEventCallback })
+ switch event {
+ case let .paymentSuccessful(paymentId, paymentHash, _, feePaidMsat):
+ Logger.info("✅ Payment successful: paymentId: \(paymentId ?? "?") paymentHash: \(paymentHash) feePaidMsat: \(feePaidMsat ?? 0)")
+ Task {
+ let hash = paymentId ?? paymentHash
do {
- try node.eventHandled()
+ try await CoreService.shared.activity.handlePaymentEvent(paymentHash: hash)
} catch {
- Logger.error(error, context: "node.eventHandled()")
+ Logger.error("Failed to handle payment success for \(hash): \(error)", context: "LightningService")
}
-
- if case .channelReady = event {
- await refreshChannelCache()
+ }
+ case let .paymentFailed(paymentId, paymentHash, reason):
+ Logger.info(
+ "❌ Payment failed: paymentId: \(paymentId ?? "?") paymentHash: \(paymentHash ?? "") reason: \(reason.debugDescription)"
+ )
+ Task {
+ if let hash = paymentId ?? paymentHash {
+ do {
+ try await CoreService.shared.activity.handlePaymentEvent(paymentHash: hash)
+ } catch {
+ Logger.error("Failed to handle payment failure for \(hash): \(error)", context: "LightningService")
+ }
+ } else {
+ Logger.warn("No paymentId or paymentHash available for failed payment", context: "LightningService")
}
-
- if self.isStaleFailure(event, from: .ldk) {
- Logger.info("Ignored an LDK failure for a payment retried over Spark: \(event)", context: "LightningService")
- continue
+ }
+ case let .paymentReceived(paymentId, paymentHash, amountMsat, _):
+ Logger.info("🤑 Payment received: paymentId: \(paymentId ?? "?") paymentHash: \(paymentHash) amountMsat: \(amountMsat)")
+ Task {
+ let hash = paymentId ?? paymentHash
+ do {
+ try await CoreService.shared.activity.handlePaymentEvent(paymentHash: hash)
+ } catch {
+ Logger.error("Failed to handle payment received for \(hash): \(error)", context: "LightningService")
}
+ }
+ case let .paymentClaimable(paymentId, paymentHash, claimableAmountMsat, _, _):
+ Logger.info(
+ "🫰 Payment claimable: paymentId: \(paymentId) paymentHash: \(paymentHash) claimableAmountMsat: \(claimableAmountMsat)"
+ )
+ case let .probeSuccessful(paymentId, paymentHash, _):
+ Logger.info("🤑 Probe successful: paymentId: \(paymentId) paymentHash: \(paymentHash)")
+ case let .probeFailed(paymentId, paymentHash, shortChannelId, _):
+ Logger
+ .info(
+ "❌ Probe failed: paymentId: \(paymentId) paymentHash: \(paymentHash) shortChannelId: \(String(describing: shortChannelId))"
+ )
+ // Payment claimable doesn't need activity update - it's still pending
+ // The payment will be updated when it succeeds or fails via paymentSuccessful/paymentFailed events
+ case let .channelPending(channelId, userChannelId, formerTemporaryChannelId, counterpartyNodeId, fundingTxo):
+ Logger.info(
+ "⏳ Channel pending: channelId: \(channelId) userChannelId: \(userChannelId) formerTemporaryChannelId: \(formerTemporaryChannelId) counterpartyNodeId: \(counterpartyNodeId) fundingTxo: \(fundingTxo)"
+ )
+ await refreshChannelCache()
+ case let .channelReady(channelId, userChannelId, counterpartyNodeId, fundingTxo):
+ Logger.info(
+ "👐 Channel ready: channelId: \(channelId) userChannelId: \(userChannelId) counterpartyNodeId: \(counterpartyNodeId ?? "?") fundingTxo: \(fundingTxo != nil ? "\(fundingTxo!.txid):\(fundingTxo!.vout)" : "nil")"
+ )
+ case let .channelClosed(channelId, userChannelId, counterpartyNodeId, reason):
+ let reasonString = reason.map { String(describing: $0) } ?? ""
+ Logger.info(
+ "⛔ Channel closed: channelId: \(channelId) userChannelId: \(userChannelId) counterpartyNodeId: \(counterpartyNodeId ?? "?") reason: \(reasonString)"
+ )
- let onchainActivityCompletion = await deliverEvent(event, onEvent: onEvent)
-
- switch event {
- case let .paymentSuccessful(paymentId, paymentHash, _, feePaidMsat):
- Logger.info("✅ Payment successful: paymentId: \(paymentId ?? "?") paymentHash: \(paymentHash) feePaidMsat: \(feePaidMsat ?? 0)")
- Task {
- let hash = paymentId ?? paymentHash
- do {
- try await CoreService.shared.activity.handlePaymentEvent(paymentHash: hash)
- } catch {
- Logger.error("Failed to handle payment success for \(hash): \(error)", context: "LightningService")
- }
- }
- case let .paymentFailed(paymentId, paymentHash, reason):
- Logger.info(
- "❌ Payment failed: paymentId: \(paymentId ?? "?") paymentHash: \(paymentHash ?? "") reason: \(reason.debugDescription)"
- )
- Task {
- if let hash = paymentId ?? paymentHash {
- do {
- try await CoreService.shared.activity.handlePaymentEvent(paymentHash: hash)
- } catch {
- Logger.error("Failed to handle payment failure for \(hash): \(error)", context: "LightningService")
- }
- } else {
- Logger.warn("No paymentId or paymentHash available for failed payment", context: "LightningService")
- }
- }
- case let .paymentReceived(paymentId, paymentHash, amountMsat, _):
- Logger.info("🤑 Payment received: paymentId: \(paymentId ?? "?") paymentHash: \(paymentHash) amountMsat: \(amountMsat)")
- Task {
- let hash = paymentId ?? paymentHash
- do {
- try await CoreService.shared.activity.handlePaymentEvent(paymentHash: hash)
- } catch {
- Logger.error("Failed to handle payment received for \(hash): \(error)", context: "LightningService")
- }
- }
- case let .paymentClaimable(paymentId, paymentHash, claimableAmountMsat, _, _):
- Logger.info(
- "🫰 Payment claimable: paymentId: \(paymentId) paymentHash: \(paymentHash) claimableAmountMsat: \(claimableAmountMsat)"
- )
- case let .probeSuccessful(paymentId, paymentHash, _):
- Logger.info("🤑 Probe successful: paymentId: \(paymentId) paymentHash: \(paymentHash)")
- case let .probeFailed(paymentId, paymentHash, shortChannelId, _):
- Logger
- .info(
- "❌ Probe failed: paymentId: \(paymentId) paymentHash: \(paymentHash) shortChannelId: \(String(describing: shortChannelId))"
- )
- // Payment claimable doesn't need activity update - it's still pending
- // The payment will be updated when it succeeds or fails via paymentSuccessful/paymentFailed events
- case let .channelPending(channelId, userChannelId, formerTemporaryChannelId, counterpartyNodeId, fundingTxo):
- Logger.info(
- "⏳ Channel pending: channelId: \(channelId) userChannelId: \(userChannelId) formerTemporaryChannelId: \(formerTemporaryChannelId) counterpartyNodeId: \(counterpartyNodeId) fundingTxo: \(fundingTxo)"
- )
- await refreshChannelCache()
- case let .channelReady(channelId, userChannelId, counterpartyNodeId, fundingTxo):
- Logger.info(
- "👐 Channel ready: channelId: \(channelId) userChannelId: \(userChannelId) counterpartyNodeId: \(counterpartyNodeId ?? "?") fundingTxo: \(fundingTxo != nil ? "\(fundingTxo!.txid):\(fundingTxo!.vout)" : "nil")"
- )
- case let .channelClosed(channelId, userChannelId, counterpartyNodeId, reason):
- let reasonString = reason.map { String(describing: $0) } ?? ""
- Logger.info(
- "⛔ Channel closed: channelId: \(channelId) userChannelId: \(userChannelId) counterpartyNodeId: \(counterpartyNodeId ?? "?") reason: \(reasonString)"
- )
-
- let channelIdString = channelId.description
- let channel = await MainActor.run {
- channelCache[channelIdString]
- }
+ let channelIdString = channelId.description
+ let channel = await MainActor.run {
+ channelCache[channelIdString]
+ }
- if let channel {
- await registerClosedChannel(channel: channel, reason: reasonString)
- _ = await MainActor.run {
- channelCache.removeValue(forKey: channelIdString)
- }
- } else {
- Logger.error(
- "Could not find channel details for closed channel: channelId=\(channelIdString) userChannelId=\(userChannelId) in cache",
- context: "LightningService"
- )
- }
- case .paymentForwarded:
- break
+ if let channel {
+ await registerClosedChannel(channel: channel, reason: reasonString)
+ _ = await MainActor.run {
+ channelCache.removeValue(forKey: channelIdString)
+ }
+ } else {
+ Logger.error(
+ "Could not find channel details for closed channel: channelId=\(channelIdString) userChannelId=\(userChannelId) in cache",
+ context: "LightningService"
+ )
+ }
+ case .paymentForwarded:
+ break
- // MARK: New Onchain Transaction Events
+ // MARK: New Onchain Transaction Events
- case let .onchainTransactionReceived(txid, details):
- Logger.info("📥 Onchain transaction received: txid=\(txid) amountSats=\(details.amountSats)")
- Task {
- await self.onchainTransactionReceived?(txid)
- do {
- try await self.persistOnchainActivity(completion: onchainActivityCompletion) {
- try await CoreService.shared.activity.handleOnchainTransactionReceived(txid: txid, details: details)
- }
- } catch {
- Logger.error("Failed to handle transaction received for \(txid): \(error)", context: "LightningService")
- }
+ case let .onchainTransactionReceived(txid, details):
+ Logger.info("📥 Onchain transaction received: txid=\(txid) amountSats=\(details.amountSats)")
+ Task {
+ await self.onchainTransactionReceived?(txid)
+ do {
+ try await self.persistOnchainActivity(completion: onchainActivityCompletion) {
+ try await CoreService.shared.activity.handleOnchainTransactionReceived(txid: txid, details: details)
}
- case let .onchainTransactionConfirmed(txid, _, blockHeight, _, details):
- Logger.info("✅ Onchain transaction confirmed: txid=\(txid) blockHeight=\(blockHeight) amountSats=\(details.amountSats)")
- Task {
- if let onchainTransactionConfirmed = self.onchainTransactionConfirmed {
- await onchainTransactionConfirmed(txid)
- }
- do {
- try await self.persistOnchainActivity(completion: onchainActivityCompletion) {
- try await CoreService.shared.activity.handleOnchainTransactionConfirmed(
- txid: txid,
- details: details
- )
- }
- } catch {
- Logger.error("Failed to handle transaction confirmed for \(txid): \(error)", context: "LightningService")
- }
+ } catch {
+ Logger.error("Failed to handle transaction received for \(txid): \(error)", context: "LightningService")
+ }
+ }
+ case let .onchainTransactionConfirmed(txid, _, blockHeight, _, details):
+ Logger.info("✅ Onchain transaction confirmed: txid=\(txid) blockHeight=\(blockHeight) amountSats=\(details.amountSats)")
+ Task {
+ if let onchainTransactionConfirmed = self.onchainTransactionConfirmed {
+ await onchainTransactionConfirmed(txid)
+ }
+ do {
+ try await self.persistOnchainActivity(completion: onchainActivityCompletion) {
+ try await CoreService.shared.activity.handleOnchainTransactionConfirmed(
+ txid: txid,
+ details: details
+ )
}
- case let .onchainTransactionReplaced(txid, conflicts):
- Logger.info("🔄 Onchain transaction replaced (RBF): txid=\(txid) by \(conflicts.count) conflict(s)")
- Task {
- do {
- try await self.persistOnchainActivity(completion: onchainActivityCompletion) {
- try await CoreService.shared.activity.handleOnchainTransactionReplaced(txid: txid, conflicts: conflicts)
- }
- } catch {
- Logger.error("Failed to handle transaction replaced for \(txid): \(error)", context: "LightningService")
- }
+ } catch {
+ Logger.error("Failed to handle transaction confirmed for \(txid): \(error)", context: "LightningService")
+ }
+ }
+ case let .onchainTransactionReplaced(txid, conflicts):
+ Logger.info("🔄 Onchain transaction replaced (RBF): txid=\(txid) by \(conflicts.count) conflict(s)")
+ Task {
+ do {
+ try await self.persistOnchainActivity(completion: onchainActivityCompletion) {
+ try await CoreService.shared.activity.handleOnchainTransactionReplaced(txid: txid, conflicts: conflicts)
}
- case let .onchainTransactionReorged(txid):
- Logger.warn("⚠️ Onchain transaction reorged (unconfirmed): txid=\(txid)")
- Task {
- do {
- try await self.persistOnchainActivity(completion: onchainActivityCompletion) {
- try await CoreService.shared.activity.handleOnchainTransactionReorged(txid: txid)
- }
- } catch {
- Logger.error("Failed to handle transaction reorged for \(txid): \(error)", context: "LightningService")
- }
+ } catch {
+ Logger.error("Failed to handle transaction replaced for \(txid): \(error)", context: "LightningService")
+ }
+ }
+ case let .onchainTransactionReorged(txid):
+ Logger.warn("⚠️ Onchain transaction reorged (unconfirmed): txid=\(txid)")
+ Task {
+ do {
+ try await self.persistOnchainActivity(completion: onchainActivityCompletion) {
+ try await CoreService.shared.activity.handleOnchainTransactionReorged(txid: txid)
}
- case let .onchainTransactionEvicted(txid):
- Logger.warn("🗑️ Onchain transaction removed from mempool: txid=\(txid)")
- Task {
- do {
- try await self.persistOnchainActivity(completion: onchainActivityCompletion) {
- try await CoreService.shared.activity.handleOnchainTransactionEvicted(txid: txid)
- }
- } catch {
- Logger.error("Failed to handle transaction evicted for \(txid): \(error)", context: "LightningService")
- }
+ } catch {
+ Logger.error("Failed to handle transaction reorged for \(txid): \(error)", context: "LightningService")
+ }
+ }
+ case let .onchainTransactionEvicted(txid):
+ Logger.warn("🗑️ Onchain transaction removed from mempool: txid=\(txid)")
+ Task {
+ do {
+ try await self.persistOnchainActivity(completion: onchainActivityCompletion) {
+ try await CoreService.shared.activity.handleOnchainTransactionEvicted(txid: txid)
}
+ } catch {
+ Logger.error("Failed to handle transaction evicted for \(txid): \(error)", context: "LightningService")
+ }
+ }
- // MARK: Sync Events
+ // MARK: Sync Events
- case let .syncProgress(syncType, progressPercent, currentBlockHeight, targetBlockHeight):
- Logger
- .debug(
- "🔄 Sync progress: type=\(syncType) progress=\(progressPercent)% current=\(currentBlockHeight) target=\(targetBlockHeight)"
- )
- case let .syncCompleted(syncType, syncedBlockHeight):
- Logger.info("✅ Sync completed: type=\(syncType) height=\(syncedBlockHeight)")
- // Send sync status update - PassthroughSubject is thread-safe
- syncStatusChangedSubject.send(UInt64(Date().timeIntervalSince1970))
+ case let .syncProgress(syncType, progressPercent, currentBlockHeight, targetBlockHeight):
+ Logger
+ .debug(
+ "🔄 Sync progress: type=\(syncType) progress=\(progressPercent)% current=\(currentBlockHeight) target=\(targetBlockHeight)"
+ )
+ case let .syncCompleted(syncType, syncedBlockHeight):
+ Logger.info("✅ Sync completed: type=\(syncType) height=\(syncedBlockHeight)")
+ // Send sync status update - PassthroughSubject is thread-safe
+ syncStatusChangedSubject.send(UInt64(Date().timeIntervalSince1970))
- // MARK: Balance Events
+ // MARK: Balance Events
- case let .balanceChanged(oldSpendableOnchain, newSpendableOnchain, _, _, oldLightning, newLightning):
- Logger
- .info("💰 Balance changed: onchain=\(oldSpendableOnchain)->\(newSpendableOnchain) lightning=\(oldLightning)->\(newLightning)")
+ case let .balanceChanged(oldSpendableOnchain, newSpendableOnchain, _, _, oldLightning, newLightning):
+ Logger
+ .info("💰 Balance changed: onchain=\(oldSpendableOnchain)->\(newSpendableOnchain) lightning=\(oldLightning)->\(newLightning)")
- // MARK: Splice Events
+ // MARK: Splice Events
- case let .splicePending(channelId, userChannelId, counterpartyNodeId, newFundingTxo):
- Logger
- .info(
- "🔀 Splice pending: channelId=\(channelId) userChannelId=\(userChannelId) counterpartyNodeId=\(counterpartyNodeId) newFundingTxo=\(newFundingTxo)"
- )
- await refreshChannelCache()
- case let .spliceFailed(channelId, userChannelId, counterpartyNodeId, abandonedFundingTxo):
- Logger
- .warn(
- "❌ Splice failed: channelId=\(channelId) userChannelId=\(userChannelId) counterpartyNodeId=\(counterpartyNodeId) abandonedFundingTxo=\(abandonedFundingTxo != nil ? "\(abandonedFundingTxo!.txid):\(abandonedFundingTxo!.vout)" : "nil")"
- )
- }
- }
+ case let .splicePending(channelId, userChannelId, counterpartyNodeId, newFundingTxo):
+ Logger
+ .info(
+ "🔀 Splice pending: channelId=\(channelId) userChannelId=\(userChannelId) counterpartyNodeId=\(counterpartyNodeId) newFundingTxo=\(newFundingTxo)"
+ )
+ await refreshChannelCache()
+ case let .spliceFailed(channelId, userChannelId, counterpartyNodeId, abandonedFundingTxo):
+ Logger
+ .warn(
+ "❌ Splice failed: channelId=\(channelId) userChannelId=\(userChannelId) counterpartyNodeId=\(counterpartyNodeId) abandonedFundingTxo=\(abandonedFundingTxo != nil ? "\(abandonedFundingTxo!.txid):\(abandonedFundingTxo!.vout)" : "nil")"
+ )
}
}
diff --git a/Bitkit/Services/NodeEventListener.swift b/Bitkit/Services/NodeEventListener.swift
new file mode 100644
index 0000000000..42ddbc36a1
--- /dev/null
+++ b/Bitkit/Services/NodeEventListener.swift
@@ -0,0 +1,77 @@
+import Foundation
+import LDKNode
+
+@MainActor
+final class NodeEventListener {
+ private var task: Task?
+ private var isStarting = false
+ private var isStopping = false
+ private var startWaiter: CheckedContinuation?
+
+ private enum LifecycleError: Error {
+ case transitionInProgress
+ }
+
+ func start(node: Node, onEvent: @escaping (Event) async -> Void) async throws {
+ guard !isStarting, !isStopping, task == nil else { throw LifecycleError.transitionInProgress }
+ isStarting = true
+ defer {
+ isStarting = false
+ let waiter = startWaiter
+ startWaiter = nil
+ waiter?.resume()
+ }
+ try await ServiceQueue.background(.ldk) { try node.start() }
+ listen(node: node, onEvent: onEvent)
+ }
+
+ func stop(node: Node, onEvent: @escaping (Event) async -> Void) async throws {
+ guard !isStopping else { throw LifecycleError.transitionInProgress }
+ isStopping = true
+ defer { isStopping = false }
+ if isStarting {
+ await withCheckedContinuation { startWaiter = $0 }
+ }
+ let previous = task
+ previous?.cancel()
+ await previous?.value
+ task = nil
+
+ do {
+ try await ServiceQueue.background(.ldk) {
+ try LightningService.stopReleasingFinishedNode(node.stop)
+ }
+ } catch {
+ if previous != nil {
+ listen(node: node, onEvent: onEvent)
+ }
+ throw error
+ }
+ }
+
+ private func listen(node: Node, onEvent: @escaping (Event) async -> Void) {
+ task = Task {
+ while !Task.isCancelled {
+ // The pinned UniFFI nextEventAsync wait ignores Swift cancellation. Polling
+ // keeps empty-queue waits cancellable and binds this consumer to one node.
+ let event = try? await ServiceQueue.background(.ldkEvents) { () -> Event? in
+ guard let event = node.nextEvent() else { return nil }
+ do {
+ try node.eventHandled()
+ } catch {
+ Logger.error(error, context: "node.eventHandled()")
+ }
+ return event
+ }
+ if let event {
+ // Finish delivery of an already acknowledged event before stop can return.
+ await onEvent(event)
+ } else {
+ do {
+ try await Task.sleep(for: .milliseconds(250))
+ } catch { return }
+ }
+ }
+ }
+ }
+}
diff --git a/Bitkit/Services/ServiceQueue.swift b/Bitkit/Services/ServiceQueue.swift
index ffd6ceebbc..156cb4e8ea 100644
--- a/Bitkit/Services/ServiceQueue.swift
+++ b/Bitkit/Services/ServiceQueue.swift
@@ -3,6 +3,7 @@ import Foundation
/// Handles app services each on it's own dedicated queue
class ServiceQueue {
private static let ldkQueue = DispatchQueue(label: "ldk-queue", qos: .userInteractive)
+ private static let ldkEventsQueue = DispatchQueue(label: "ldk-events-queue", qos: .userInitiated)
private static let coreQueue = DispatchQueue(label: "core-queue", qos: .userInteractive)
private static let migrationQueue = DispatchQueue(label: "migration-queue", qos: .userInteractive)
private static let forexQueue = DispatchQueue(label: "forex-queue", qos: .userInteractive)
@@ -12,6 +13,7 @@ class ServiceQueue {
enum ServiceTypes {
case ldk
+ case ldkEvents
case core
case migration
case forex
@@ -21,6 +23,8 @@ class ServiceQueue {
switch self {
case .ldk:
return ServiceQueue.ldkQueue
+ case .ldkEvents:
+ return ServiceQueue.ldkEventsQueue
case .core:
return ServiceQueue.coreQueue
case .migration:
diff --git a/Bitkit/Utilities/AppReset.swift b/Bitkit/Utilities/AppReset.swift
index 5f488ab2d3..3a8188e4f8 100644
--- a/Bitkit/Utilities/AppReset.swift
+++ b/Bitkit/Utilities/AppReset.swift
@@ -54,14 +54,26 @@ final class AppReset: WipeStepExecutor {
TrezorUiHandler.shared.allowPinRequests()
TrezorTransport.shared.allowPairingCodeRequests()
}
- try await PaykitSdkService.shared.withWalletWipe(acquireTimeout: Self.waitTimeout) {
- // A server switch restarts the node, so one under way finishes first, and no new one starts until the wipe ends.
- defer { SettingsViewModel.shared.endServerSettingsWipe() }
- try await Self.bounded("server settings") { await SettingsViewModel.shared.beginServerSettingsWipe() }
- try await steps()
+ try await Self.withConnectionRecoveryPaused(recovery: .shared) {
+ try await PaykitSdkService.shared.withWalletWipe(acquireTimeout: Self.waitTimeout) {
+ try await steps()
+ }
}
}
+ static func withConnectionRecoveryPaused(
+ recovery: ConnectionRecoveryService,
+ timeout: Duration = waitTimeout,
+ operation: () async throws -> Void
+ ) async throws {
+ let connectionWipe = try await recovery.beginWipe(timeout: timeout)
+ defer { recovery.endWipe(connectionWipe) }
+ // A server switch restarts the node, so drain it before acquiring the wipe's SDK scope.
+ defer { SettingsViewModel.shared.endServerSettingsWipe() }
+ try await bounded("server settings") { await SettingsViewModel.shared.beginServerSettingsWipe() }
+ try await operation()
+ }
+
func withLocalStateWipeScope(_ steps: () async throws -> Void) async throws {
try await VssBackupClient.shared.withSuspendedClients(steps)
}
diff --git a/Bitkit/Utilities/Keychain.swift b/Bitkit/Utilities/Keychain.swift
index 4ecbdf0025..c7ca94d2f8 100644
--- a/Bitkit/Utilities/Keychain.swift
+++ b/Bitkit/Utilities/Keychain.swift
@@ -22,6 +22,7 @@ enum KeychainEntryType {
case paykitAllowanceState
case paykitAllowancesPausedAfterRestore
case pubkySecretKey
+ case connectionRecovery
var storageKey: String {
switch self {
@@ -45,6 +46,7 @@ enum KeychainEntryType {
case .paykitAllowanceState: "paykit_allowance_state"
case .paykitAllowancesPausedAfterRestore: "paykit_allowances_paused_after_restore"
case .pubkySecretKey: "pubky_secret_key"
+ case .connectionRecovery: "connection_recovery"
}
}
}
@@ -64,6 +66,10 @@ class Keychain {
}
class func save(key: KeychainEntryType, data: Data) throws {
+ #if DEBUG
+ try ConnectionRecoveryTestFault.checkKeychain(key: key, operation: "write")
+ #endif
+
Logger.debug("Saving \(key.storageKey)", context: "Keychain")
let query = addQuery(key: key, data: data)
@@ -118,6 +124,10 @@ class Keychain {
}
class func update(key: KeychainEntryType, data: Data) throws {
+ #if DEBUG
+ try ConnectionRecoveryTestFault.checkKeychain(key: key, operation: "write")
+ #endif
+
Logger.debug("Updating \(key.storageKey)", context: "Keychain")
let query = [
@@ -163,6 +173,10 @@ class Keychain {
}
class func delete(key: KeychainEntryType) throws {
+ #if DEBUG
+ try ConnectionRecoveryTestFault.checkKeychain(key: key, operation: "delete")
+ #endif
+
let query = [
kSecClass as String: kSecClassGenericPassword as String,
kSecAttrAccount as String: account(for: key),
@@ -186,6 +200,10 @@ class Keychain {
/// Inserts or updates a keychain entry in one keychain call each, with no delete in between, so the entry never goes missing.
class func upsert(key: KeychainEntryType, data: Data) throws {
+ #if DEBUG
+ try ConnectionRecoveryTestFault.checkKeychain(key: key, operation: "write")
+ #endif
+
Logger.debug("Upserting \(key.storageKey)", context: "Keychain")
let addStatus = SecItemAdd(addQuery(key: key, data: data) as CFDictionary, nil)
@@ -224,6 +242,10 @@ class Keychain {
/// NOTE: throws if fails but return nil if not found
class func load(key: KeychainEntryType) throws -> Data? {
+ #if DEBUG
+ try ConnectionRecoveryTestFault.checkKeychain(key: key, operation: "read")
+ #endif
+
let query = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: account(for: key),
@@ -344,3 +366,48 @@ class Keychain {
return SecItemDelete(query as CFDictionary)
}
}
+
+#if DEBUG
+ /// Disposable simulator acceptance only. The control never changes a stored value or reports success.
+ enum ConnectionRecoveryTestFault {
+ static let allowed = Set([
+ "connection_recovery:read", "connection_recovery:write", "connection_recovery:delete",
+ "paykit_pending_backup_restore:read", "paykit_pending_backup_restore:write", "paykit_pending_backup_restore:delete",
+ "usdt_pending_backup_restore:read", "usdt_pending_backup_restore:write", "usdt_pending_backup_restore:delete",
+ "preferences:readback", "preferences:flush", "profile:load",
+ ])
+
+ private static func selected() -> String? {
+ #if targetEnvironment(simulator)
+ guard Env.isE2E, Env.network == .regtest, !Env.isUnitTest,
+ ProcessInfo.processInfo.arguments.contains("-E2E_CONNECTION_RECOVERY_FAULTS") else { return nil }
+ let url = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent("connection-recovery-test-fault")
+ guard let data = try? Data(contentsOf: url), data.count <= 128,
+ let value = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines),
+ allowed.contains(value) else { return nil }
+ return value
+ #else
+ return nil
+ #endif
+ }
+
+ static func checkKeychain(key: KeychainEntryType, operation: String) throws {
+ try check("\(key.storageKey):\(operation)")
+ }
+
+ static func check(_ point: String) throws {
+ try check(point, selected: selected())
+ }
+
+ static func check(_ point: String, selected: String?) throws {
+ guard allowed.contains(point), selected == point else { return }
+ Logger.warn("Injected local recovery storage failure: \(point)", context: "ConnectionRecoveryTestFault")
+ throw NSError(
+ domain: "ConnectionRecoveryTestFault",
+ code: 1,
+ userInfo: [NSLocalizedDescriptionKey: "Local recovery storage unavailable (\(point))"]
+ )
+ }
+ }
+#endif
diff --git a/Bitkit/ViewModels/WalletViewModel.swift b/Bitkit/ViewModels/WalletViewModel.swift
index be9e3d75db..1106754b1d 100644
--- a/Bitkit/ViewModels/WalletViewModel.swift
+++ b/Bitkit/ViewModels/WalletViewModel.swift
@@ -318,118 +318,116 @@ class WalletViewModel: ObservableObject {
)
}
try await nodeLifecycle.start(onEvent: { event in
- Task { @MainActor in
- self.notifyEventHandlers(event)
+ self.notifyEventHandlers(event)
- // Handle specific events for targeted UI updates
- switch event {
- case let .probeSuccessful(paymentId, paymentHash: paymentHash, routeFeeMsat: routeFeeMsat):
- self.cacheProbeOutcome(
- success: true,
- paymentId: paymentId,
- paymentHash: paymentHash,
- shortChannelId: nil,
- routeFeeMsat: routeFeeMsat
+ // Handle specific events for targeted UI updates
+ switch event {
+ case let .probeSuccessful(paymentId, paymentHash: paymentHash, routeFeeMsat: routeFeeMsat):
+ self.cacheProbeOutcome(
+ success: true,
+ paymentId: paymentId,
+ paymentHash: paymentHash,
+ shortChannelId: nil,
+ routeFeeMsat: routeFeeMsat
+ )
+ case let .probeFailed(paymentId, paymentHash: paymentHash, shortChannelId: shortChannelId, routeFeeMsat: routeFeeMsat):
+ self.cacheProbeOutcome(
+ success: false,
+ paymentId: paymentId,
+ paymentHash: paymentHash,
+ shortChannelId: shortChannelId.map(String.init),
+ routeFeeMsat: routeFeeMsat
+ )
+ case let .paymentReceived(_, paymentHash, _, _):
+ self.invalidateReceiveInvoice()
+ let rotatedPublicInvoice = self.isPaykitUIActive && self.rotatePublicPaykitInvoiceIfNeeded(paymentHash: paymentHash)
+ let isSessionCurrent = self.publicPaykitPublicationAdmission()
+ Task {
+ await self.refreshAfterPaymentReceived(
+ paymentHash: paymentHash, rotatedPublicInvoice: rotatedPublicInvoice, isSessionCurrent: isSessionCurrent
)
- case let .probeFailed(paymentId, paymentHash: paymentHash, shortChannelId: shortChannelId, routeFeeMsat: routeFeeMsat):
- self.cacheProbeOutcome(
- success: false,
- paymentId: paymentId,
- paymentHash: paymentHash,
- shortChannelId: shortChannelId.map(String.init),
- routeFeeMsat: routeFeeMsat
+ }
+ case .channelReady:
+ self.invalidateReceiveInvoice()
+ Task {
+ await self.refreshAndSyncState()
+ try? await self.refreshBip21(reportsError: false)
+ await self.refreshPaykitEndpointsAfterChannelAvailabilityChanged(reason: "channel-ready refresh")
+ try? await Task.sleep(nanoseconds: Self.paykitChannelUsabilityRefreshDelay)
+ guard !Task.isCancelled else { return }
+ await self.refreshAndSyncState()
+ try? await self.refreshBip21(reportsError: false)
+ await self.refreshPaykitEndpointsAfterChannelAvailabilityChanged(
+ reason: "channel-ready delayed refresh",
+ forceRefreshLightning: true
)
- case let .paymentReceived(_, paymentHash, _, _):
- self.invalidateReceiveInvoice()
- let rotatedPublicInvoice = self.isPaykitUIActive && self.rotatePublicPaykitInvoiceIfNeeded(paymentHash: paymentHash)
- let isSessionCurrent = self.publicPaykitPublicationAdmission()
- Task {
- await self.refreshAfterPaymentReceived(
- paymentHash: paymentHash, rotatedPublicInvoice: rotatedPublicInvoice, isSessionCurrent: isSessionCurrent
- )
- }
- case .channelReady:
- self.invalidateReceiveInvoice()
- Task {
- await self.refreshAndSyncState()
- try? await self.refreshBip21(reportsError: false)
- await self.refreshPaykitEndpointsAfterChannelAvailabilityChanged(reason: "channel-ready refresh")
- try? await Task.sleep(nanoseconds: Self.paykitChannelUsabilityRefreshDelay)
- guard !Task.isCancelled else { return }
- await self.refreshAndSyncState()
- try? await self.refreshBip21(reportsError: false)
- await self.refreshPaykitEndpointsAfterChannelAvailabilityChanged(
- reason: "channel-ready delayed refresh",
- forceRefreshLightning: true
- )
- }
+ }
- case let .channelClosed(channelId, _, _, reason):
- self.invalidateReceiveInvoice()
- Task {
- await self.refreshAfterChannelClosed(channelId: channelId, reason: reason)
- }
+ case let .channelClosed(channelId, _, _, reason):
+ self.invalidateReceiveInvoice()
+ Task {
+ await self.refreshAfterChannelClosed(channelId: channelId, reason: reason)
+ }
+
+ // MARK: Onchain Transaction Events
- // MARK: Onchain Transaction Events
-
- case let .onchainTransactionReceived(_, details):
- Task {
- await self.refreshAndSyncState()
- if self.isPaykitUIActive {
- await PrivatePaykitService.shared.handleOnchainActivity(
- receivedAddresses: details.outputs.compactMap(\.scriptpubkeyAddress),
- wallet: self
- )
- }
+ case let .onchainTransactionReceived(_, details):
+ Task {
+ await self.refreshAndSyncState()
+ if self.isPaykitUIActive {
+ await PrivatePaykitService.shared.handleOnchainActivity(
+ receivedAddresses: details.outputs.compactMap(\.scriptpubkeyAddress),
+ wallet: self
+ )
}
+ }
- case let .onchainTransactionConfirmed(_, _, _, _, details):
- Task {
- await self.refreshAndSyncState()
- if self.isPaykitUIActive {
- await PrivatePaykitService.shared.handleOnchainActivity(
- receivedAddresses: details.outputs.compactMap(\.scriptpubkeyAddress),
- wallet: self
- )
- }
+ case let .onchainTransactionConfirmed(_, _, _, _, details):
+ Task {
+ await self.refreshAndSyncState()
+ if self.isPaykitUIActive {
+ await PrivatePaykitService.shared.handleOnchainActivity(
+ receivedAddresses: details.outputs.compactMap(\.scriptpubkeyAddress),
+ wallet: self
+ )
}
+ }
- case .onchainTransactionReplaced, .onchainTransactionReorged, .onchainTransactionEvicted:
- Task {
- await self.refreshAndSyncState()
- if self.isPaykitUIActive {
- await PrivatePaykitService.shared.handleOnchainActivity(wallet: self)
- }
+ case .onchainTransactionReplaced, .onchainTransactionReorged, .onchainTransactionEvicted:
+ Task {
+ await self.refreshAndSyncState()
+ if self.isPaykitUIActive {
+ await PrivatePaykitService.shared.handleOnchainActivity(wallet: self)
}
+ }
- // MARK: Sync Events
+ // MARK: Sync Events
- case let .syncProgress(syncType, progressPercent, syncCurrentBlockHeight, _):
- self.isSyncingWallet = true
- if syncCurrentBlockHeight > self.currentBlockHeight {
- self.currentBlockHeight = syncCurrentBlockHeight
- }
- Logger.debug("Sync progress: \(syncType) \(progressPercent)%")
-
- case let .syncCompleted(syncType, syncedBlockHeight):
- self.isSyncingWallet = false
- self.currentBlockHeight = syncedBlockHeight
- Logger.info("Sync completed: \(syncType) at height \(syncedBlockHeight)")
- let isSessionCurrent = self.publicPaykitPublicationAdmission()
- Task {
- await self.refreshAndSyncState()
- await self.refreshPublicPaykitAddressIfNeeded(isSessionCurrent: isSessionCurrent)
- }
+ case let .syncProgress(syncType, progressPercent, syncCurrentBlockHeight, _):
+ self.isSyncingWallet = true
+ if syncCurrentBlockHeight > self.currentBlockHeight {
+ self.currentBlockHeight = syncCurrentBlockHeight
+ }
+ Logger.debug("Sync progress: \(syncType) \(progressPercent)%")
+
+ case let .syncCompleted(syncType, syncedBlockHeight):
+ self.isSyncingWallet = false
+ self.currentBlockHeight = syncedBlockHeight
+ Logger.info("Sync completed: \(syncType) at height \(syncedBlockHeight)")
+ let isSessionCurrent = self.publicPaykitPublicationAdmission()
+ Task {
+ await self.refreshAndSyncState()
+ await self.refreshPublicPaykitAddressIfNeeded(isSessionCurrent: isSessionCurrent)
+ }
- // MARK: Balance Events
+ // MARK: Balance Events
- case .balanceChanged:
- Task {
- await self.refreshAndSyncState()
- }
- default:
- break
+ case .balanceChanged:
+ Task {
+ await self.refreshAndSyncState()
}
+ default:
+ break
}
})
} catch {
diff --git a/Bitkit/Views/Onboarding/WalletConnectionRecoveryView.swift b/Bitkit/Views/Onboarding/WalletConnectionRecoveryView.swift
new file mode 100644
index 0000000000..2ae8995821
--- /dev/null
+++ b/Bitkit/Views/Onboarding/WalletConnectionRecoveryView.swift
@@ -0,0 +1,140 @@
+import SwiftUI
+
+struct WalletConnectionRecoveryView: View {
+ let onBack: () -> Void
+ let onRetry: () async -> Void
+ @ObservedObject var recovery = ConnectionRecoveryService.shared
+ @State private var editor: ConnectionRecoveryService.Editor
+ @State private var electrum = ""
+ @State private var rgs = ""
+ @State private var saved = false
+ @State private var error: String?
+ @State private var work: Task?
+
+ init(editor: ConnectionRecoveryService.Editor, onBack: @escaping () -> Void,
+ onRetry: @escaping () async -> Void, recovery: ConnectionRecoveryService)
+ {
+ self.onBack = onBack
+ self.onRetry = onRetry
+ self.recovery = recovery
+ _editor = State(initialValue: editor)
+ _electrum = State(initialValue: editor.electrum.fullUrl)
+ _rgs = State(initialValue: editor.rgs)
+ }
+
+ private var canEdit: Bool {
+ !recovery.isBusy && recovery.isCurrent(editor)
+ }
+
+ var body: some View {
+ VStack(spacing: 16) {
+ HStack {
+ Button(t("common__back"), action: onBack).accessibilityIdentifier("NavigationBack")
+ Spacer()
+ BodyMText(t("onboarding__connection_settings"))
+ }
+ ScrollView {
+ VStack(alignment: .leading, spacing: 16) {
+ BodyMText(t("settings__adv__electrum_server"))
+ TextField("ssl://host:50002", text: $electrum)
+ .textInputAutocapitalization(.never).autocorrectionDisabled()
+ .accessibilityIdentifier("RecoveryElectrumInput")
+ .disabled(!canEdit)
+ CustomButton(title: t("settings__es__button_reset"), variant: .secondary,
+ isDisabled: !canEdit)
+ {
+ electrum = ElectrumConfigService().getDefaultServer().fullUrl
+ }.accessibilityIdentifier("RecoveryElectrumReset")
+ CustomButton(title: t("common__save"), isDisabled: !canEdit) {
+ saveElectrum()
+ }.accessibilityIdentifier("RecoveryElectrumSave")
+
+ BodyMText(t("settings__rgs__server_url"))
+ TextField("https://host", text: $rgs)
+ .textInputAutocapitalization(.never).autocorrectionDisabled()
+ .accessibilityIdentifier("RecoveryRgsInput")
+ .disabled(!canEdit)
+ CustomButton(title: t("settings__es__button_reset"), variant: .secondary,
+ isDisabled: !canEdit)
+ {
+ rgs = RgsConfigService().getDefaultServerUrl()
+ }.accessibilityIdentifier("RecoveryRgsReset")
+ CustomButton(title: t("common__save"), isDisabled: !canEdit) {
+ saveRgs()
+ }.accessibilityIdentifier("RecoveryRgsSave")
+
+ if saved {
+ BodyMText(t("onboarding__connection_saved")).accessibilityIdentifier("RecoverySaved")
+ }
+ if let error {
+ BodyMText(error, textColor: .redAccent).accessibilityIdentifier("RecoveryError")
+ }
+ CustomButton(title: t("common__try_again"), isDisabled: !canEdit, isLoading: recovery.isBusy) {
+ work = Task {
+ guard canEdit else { return }
+ await onRetry()
+ }
+ }.accessibilityIdentifier("RecoveryRetry")
+ }
+ }
+ }
+ .padding(16)
+ .bottomSafeAreaPadding()
+ .accessibilityElement(children: .contain)
+ .accessibilityIdentifier("WalletConnectionRecovery")
+ .onDisappear { work?.cancel() }
+ .onChange(of: electrum) { saved = false }
+ .onChange(of: rgs) { saved = false }
+ }
+
+ private func saveElectrum() {
+ let input = electrum.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard let components = URLComponents(string: input),
+ let host = components.host, let port = components.port,
+ let scheme = components.scheme, ["tcp", "ssl"].contains(scheme),
+ components.user == nil, components.password == nil, components.path.isEmpty,
+ components.query == nil, components.fragment == nil,
+ SettingsViewModel.shared.validateElectrumInput(host: host, port: String(port)) == nil
+ else {
+ error = t("settings__es__server_error_description")
+ return
+ }
+ let server = ElectrumServer(host: host, port: port, protocolType: scheme == "ssl" ? .ssl : .tcp)
+ save { owner in try await recovery.save(editor: owner, electrum: server) }
+ }
+
+ private func saveRgs() {
+ let input = rgs.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !input.isEmpty || RgsConfigService().getDefaultServerUrl().isEmpty,
+ SettingsViewModel.shared.isValidRgsUrl(input)
+ else {
+ error = t("settings__rgs__server_error_description")
+ return
+ }
+ save { owner in
+ try await recovery.save(editor: owner, rgs: input) {
+ if !input.isEmpty, await !SettingsViewModel.shared.isRgsEndpointReachable(input) {
+ throw AppError(message: t("settings__rgs__server_error_description"), debugMessage: nil)
+ }
+ }
+ }
+ }
+
+ private func save(_ action: @escaping (ConnectionRecoveryService.Editor) async throws -> Void) {
+ guard canEdit else { return }
+ let editor = editor
+ error = nil
+ saved = false
+ work = Task {
+ do {
+ try await action(editor)
+ guard !Task.isCancelled, recovery.isCurrent(editor) else { return }
+ self.editor = try recovery.editor()
+ saved = true
+ } catch {
+ guard !Task.isCancelled, recovery.isCurrentLifecycle(editor.generation) else { return }
+ self.error = error.localizedDescription
+ }
+ }
+ }
+}
diff --git a/Bitkit/Views/Onboarding/WalletRestoreError.swift b/Bitkit/Views/Onboarding/WalletRestoreError.swift
index eb41c052e5..3c94797c4c 100644
--- a/Bitkit/Views/Onboarding/WalletRestoreError.swift
+++ b/Bitkit/Views/Onboarding/WalletRestoreError.swift
@@ -4,6 +4,7 @@ struct WalletRestoreError: View {
var title = t("onboarding__restore_failed_header")
var message = t("onboarding__restore_failed_text")
let onRetry: () async -> Void
+ var onConnectionSettings: (() -> Void)?
var onExportLogs: (() -> Void)?
var body: some View {
@@ -26,6 +27,12 @@ struct WalletRestoreError: View {
Spacer()
+ if let onConnectionSettings {
+ CustomButton(title: t("onboarding__connection_settings"), variant: .secondary, action: onConnectionSettings)
+ .accessibilityIdentifier("ConnectionRecoveryButton")
+ .padding(.bottom, 16)
+ }
+
CustomButton(title: t("common__try_again")) {
Haptics.play(.light)
Task {
diff --git a/BitkitTests/ConnectionRecoveryServiceTests.swift b/BitkitTests/ConnectionRecoveryServiceTests.swift
new file mode 100644
index 0000000000..48bb6f5219
--- /dev/null
+++ b/BitkitTests/ConnectionRecoveryServiceTests.swift
@@ -0,0 +1,795 @@
+@testable import Bitkit
+import SwiftUI
+import XCTest
+
+@MainActor
+final class ConnectionRecoveryServiceTests: XCTestCase {
+ private var defaults: UserDefaults!
+ private var suite: String!
+ private var data: Data?
+ private var currentOwner = ConnectionRecoveryService.Owner(walletIndex: 0, network: "regtest", binding: "original")
+ private var service: ConnectionRecoveryService!
+
+ override func setUp() async throws {
+ suite = "ConnectionRecoveryTests.\(UUID())"
+ defaults = UserDefaults(suiteName: suite)
+ data = nil
+ currentOwner = .init(walletIndex: 0, network: "regtest", binding: "original")
+ service = makeService()
+ }
+
+ override func tearDown() async throws {
+ defaults.removePersistentDomain(forName: suite)
+ service = nil
+ defaults = nil
+ }
+
+ func testStorageFaultSelectorRejectsOnlyItsExactAllowedBoundary() throws {
+ for selected in ConnectionRecoveryTestFault.allowed {
+ for point in ConnectionRecoveryTestFault.allowed {
+ if selected == point {
+ XCTAssertThrowsError(try ConnectionRecoveryTestFault.check(point, selected: selected))
+ } else {
+ XCTAssertNoThrow(try ConnectionRecoveryTestFault.check(point, selected: selected))
+ }
+ }
+ XCTAssertNoThrow(try ConnectionRecoveryTestFault.check("bip39_mnemonic_0:delete", selected: selected))
+ XCTAssertNoThrow(try ConnectionRecoveryTestFault.check("paykit_session:write", selected: selected))
+ }
+ XCTAssertNoThrow(try ConnectionRecoveryTestFault.check("connection_recovery:write", selected: nil))
+ XCTAssertNoThrow(try ConnectionRecoveryTestFault.check("connection_recovery:write", selected: "*"))
+ }
+
+ private func makeService() -> ConnectionRecoveryService {
+ ConnectionRecoveryService(owner: { self.currentOwner }, load: { self.data },
+ store: { self.data = $0 }, clear: { self.data = nil }, defaults: defaults)
+ }
+
+ private var server: ElectrumServer {
+ ElectrumServer(host: "localhost", port: 50001, protocolType: .tcp)
+ }
+
+ func testRestrictedEditorRendersWithLocalCorrectionOnCompactDisplay() async throws {
+ try await service.save(editor: service.editor(), electrum: server)
+ let editor = try service.editor()
+ let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)
+ let previousWindow = scene.windows.first(where: \.isKeyWindow)
+ let window = UIWindow(windowScene: scene)
+ window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
+ window.overrideUserInterfaceStyle = .dark
+ let appeared = expectation(description: "Editor appears in the test window")
+ let host = UIHostingController(rootView: WalletConnectionRecoveryView(editor: editor, onBack: {}, onRetry: {}, recovery: service)
+ .onAppear { appeared.fulfill() })
+ window.rootViewController = host
+ window.makeKeyAndVisible()
+ defer {
+ window.isHidden = true
+ window.rootViewController = nil
+ previousWindow?.makeKey()
+ }
+ await fulfillment(of: [appeared], timeout: 2)
+ try await Task.sleep(for: .milliseconds(100))
+ host.view.layoutIfNeeded()
+ let size = host.sizeThatFits(in: window.bounds.size)
+ XCTAssertGreaterThan(size.width, 300)
+ XCTAssertGreaterThan(size.height, 500)
+ XCTAssertLessThanOrEqual(size.width, window.bounds.width)
+ XCTAssertLessThanOrEqual(size.height, window.bounds.height)
+ var didDraw = false
+ let rendered = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in
+ didDraw = window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
+ }
+ XCTAssertTrue(didDraw)
+ let pixels = try XCTUnwrap(rendered.cgImage?.dataProvider?.data) as Data
+ XCTAssertGreaterThan(Set(pixels).count, 8, "An empty black attachment is not rendered editor evidence")
+ let attachment = XCTAttachment(image: rendered)
+ attachment.name = "Restricted connection editor with synthetic local settings"
+ attachment.lifetime = .keepAlways
+ add(attachment)
+ }
+
+ func testEditorPresentedDuringStartupRemainsUsableAfterFailure() async throws {
+ let editor = try service.editor()
+ let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)
+ let previousWindow = scene.windows.first(where: \.isKeyWindow)
+ let window = UIWindow(windowScene: scene)
+ window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
+ let entered = expectation(description: "Startup is awaiting its native result")
+ var release: CheckedContinuation?
+ let startup = Task {
+ try await service.perform {
+ await withCheckedContinuation { release = $0; entered.fulfill() }
+ throw URLError(.cannotConnectToHost)
+ }
+ }
+ await fulfillment(of: [entered], timeout: 2)
+ let appeared = expectation(description: "Editor is presented during startup")
+ let host = UIHostingController(rootView: WalletConnectionRecoveryView(editor: editor, onBack: {}, onRetry: {}, recovery: service)
+ .onAppear { appeared.fulfill() })
+ window.rootViewController = host
+ window.makeKeyAndVisible()
+ defer {
+ window.isHidden = true
+ window.rootViewController = nil
+ previousWindow?.makeKey()
+ }
+ await fulfillment(of: [appeared], timeout: 2)
+ release?.resume()
+ do { try await startup.value; XCTFail("Startup must retain its failure") } catch {}
+ try await Task.sleep(for: .milliseconds(100))
+ host.view.layoutIfNeeded()
+ func textFields(in view: UIView) -> [UITextField] {
+ (view as? UITextField).map { [$0] } ?? view.subviews.flatMap { textFields(in: $0) }
+ }
+ let fields = textFields(in: host.view)
+ XCTAssertEqual(fields.count, 2)
+ XCTAssertTrue(fields.allSatisfy(\.isEnabled), "The original editor must become usable when startup fails")
+ }
+
+ func testIndependentSaveSurvivesReconstructionAndOldSettings() async throws {
+ try await service.save(editor: service.editor(), electrum: server)
+ let saved = try XCTUnwrap(data)
+ let restored = makeService()
+ try await restored.perform {
+ let settings = try restored.mergeRestoredSettings(["electrumServer": "ssl://old:50002", "hideBalance": true])
+ XCTAssertEqual(settings["electrumServer"] as? String, self.server.fullUrl)
+ XCTAssertEqual(settings["hideBalance"] as? Bool, true)
+ self.defaults.removeObject(forKey: "electrumServer")
+ XCTAssertNotNil(try restored.replay())
+ XCTAssertEqual(ElectrumConfigService(defaults: self.defaults).getCurrentServer(), self.server)
+ }
+ XCTAssertEqual(data, saved)
+ try await restored.save(editor: restored.editor(), rgs: "")
+ XCTAssertEqual(try JSONDecoder().decode(ConnectionRecoveryService.Record.self, from: XCTUnwrap(data)).rgs, "")
+ XCTAssertEqual(ElectrumConfigService(defaults: defaults).getCurrentServer(), server)
+ }
+
+ func testFailedProbeDoesNotOverwriteAcknowledgedCorrection() async throws {
+ try await service.save(editor: service.editor(), electrum: server)
+ let saved = data
+ do {
+ try await service.save(editor: service.editor(), rgs: "https://invalid.example") {
+ throw URLError(.cannotConnectToHost)
+ }
+ XCTFail("Failed probe must be reported")
+ } catch {}
+ XCTAssertEqual(data, saved)
+ XCTAssertNil(defaults.string(forKey: "rapidGossipSyncUrl"))
+ }
+
+ func testMarkerWriteFailureDoesNotChangePreferences() async throws {
+ let failing = ConnectionRecoveryService(owner: { self.currentOwner }, load: { nil },
+ store: { _ in throw CocoaError(.fileWriteNoPermission) }, clear: {}, defaults: defaults)
+ do {
+ try await failing.save(editor: failing.editor(), electrum: server)
+ XCTFail("Unacknowledged record must block settings mutation")
+ } catch {}
+ XCTAssertNil(defaults.data(forKey: "electrumServer"))
+ }
+
+ func testMissingOptionalSettingsCannotConsumeRequiredMarkerWhenReplayFails() async throws {
+ var marker: Data? = Data("complete-wallet".utf8)
+ let gate = WalletBackupRestoreGate(load: { marker }, store: { marker = $0 }, clear: { marker = nil })
+ data = Data("unreadable-connection-record".utf8)
+ do {
+ _ = try await service.restoreRequired(gate: gate) { _ in true }
+ XCTFail("Mandatory replay must fail outside optional SETTINGS handling")
+ } catch {}
+ XCTAssertEqual(marker, Data("complete-wallet".utf8))
+ XCTAssertEqual(data, Data("unreadable-connection-record".utf8))
+ }
+
+ func testFreshRestoreArmsMarkerBeforeOwnerOrCorrectionReadFailure() async throws {
+ for failOwner in [true, false] {
+ var marker: Data?
+ let gate = WalletBackupRestoreGate(load: { marker }, store: { marker = $0 }, clear: { marker = nil })
+ let unavailable = ConnectionRecoveryService(owner: {
+ if failOwner {
+ throw CocoaError(.fileReadNoPermission)
+ }
+ return self.currentOwner
+ }, load: { throw CocoaError(.fileReadNoPermission) }, store: { _ in }, clear: {}, defaults: defaults)
+ do {
+ _ = try await unavailable.restoreRequired(gate: gate) { _ in
+ XCTFail("Unavailable recovery state must prevent import")
+ return true
+ }
+ XCTFail("Read failure must propagate")
+ } catch {}
+ let recreatedGate = WalletBackupRestoreGate(load: { marker }, store: { marker = $0 }, clear: { marker = nil })
+ XCTAssertTrue(try recreatedGate.hasPendingRestore())
+ XCTAssertTrue(try WalletBackupRestoreGate.blocksWalletStart(isRestoreRunning: false,
+ hasPendingRestore: recreatedGate.hasPendingRestore(),
+ isRestoreCompletionStart: false))
+ }
+ }
+
+ func testActualFullAndLegacyEntriesRetainTheirRequiredMarkersOnUnavailableCorrection() async throws {
+ let originalWallet = try Keychain.load(key: .paykitPendingBackupRestore)
+ let originalUsdt = try Keychain.load(key: .usdtPendingBackupRestore)
+ defer {
+ do {
+ if let originalWallet {
+ try Keychain.upsert(key: .paykitPendingBackupRestore, data: originalWallet)
+ } else {
+ try Keychain.delete(key: .paykitPendingBackupRestore)
+ }
+ if let originalUsdt {
+ try Keychain.upsert(key: .usdtPendingBackupRestore, data: originalUsdt)
+ } else {
+ try Keychain.delete(key: .usdtPendingBackupRestore)
+ }
+ } catch { XCTFail("Could not restore test marker state: \(error)") }
+ }
+ let unavailable = ConnectionRecoveryService(owner: { self.currentOwner },
+ load: { throw CocoaError(.fileReadNoPermission) },
+ store: { _ in }, clear: {}, defaults: defaults)
+ let backup = BackupService(defaults: defaults, connectionRecovery: unavailable)
+ for path in ["full", "legacy", "retained-usdt"] {
+ try Keychain.delete(key: .paykitPendingBackupRestore)
+ try Keychain.delete(key: .usdtPendingBackupRestore)
+ let retained = Data("retained-complete-legacy-wallet".utf8)
+ if path == "retained-usdt" {
+ try Keychain.upsert(key: .usdtPendingBackupRestore, data: retained)
+ }
+ do {
+ if path == "legacy" {
+ try await backup.restoreUsdtRecoveryAfterLegacyMigration()
+ } else {
+ try await backup.performFullRestoreFromLatestBackup()
+ }
+ XCTFail("Unavailable correction must stop restore before remote work")
+ } catch {}
+ if path == "full" {
+ XCTAssertEqual(try Keychain.load(key: .paykitPendingBackupRestore), Data())
+ XCTAssertNil(try Keychain.load(key: .usdtPendingBackupRestore))
+ } else {
+ XCTAssertNil(try Keychain.load(key: .paykitPendingBackupRestore))
+ XCTAssertEqual(try Keychain.load(key: .usdtPendingBackupRestore), path == "legacy" ? Data() : retained)
+ }
+ XCTAssertTrue(BackupService(defaults: defaults, connectionRecovery: unavailable).hasPendingWalletRestore())
+ }
+ }
+
+ func testFailedLocalPromotionRetainsDurableCorrectionForReplay() async throws {
+ let denied = try XCTUnwrap(FailingConnectionPreferences(suiteName: suite))
+ denied.rejectWrites = true
+ let failing = ConnectionRecoveryService(owner: { self.currentOwner }, load: { self.data },
+ store: { self.data = $0 }, clear: { self.data = nil }, defaults: denied)
+ do {
+ try await failing.save(editor: failing.editor(), electrum: server)
+ XCTFail("Failed settings promotion must not report saved")
+ } catch {}
+ XCTAssertNotNil(data)
+ denied.rejectWrites = false
+ try await failing.perform { XCTAssertNotNil(try failing.replay()) }
+ XCTAssertEqual(ElectrumConfigService(defaults: denied).getCurrentServer(), server)
+ }
+
+ func testStaleEditorAndOldSuccessfulRevisionCannotEraseLaterCorrection() async throws {
+ let stale = try service.editor()
+ try await service.save(editor: stale, electrum: server)
+ let earlier = try service.editor().revision
+ try await service.save(editor: service.editor(), rgs: "https://rgs.example")
+ let latest = data
+ do {
+ try await service.save(editor: stale, rgs: "https://old.example")
+ XCTFail("Stale confirmation must not replace a newer correction")
+ } catch {}
+ try await service.perform {
+ try self.service.complete(revision: earlier, hasPendingRestore: false, isRunning: true)
+ }
+ XCTAssertEqual(data, latest)
+ }
+
+ func testCompletionRequiresNodeAndRestoreThenClearsOnlySameRevision() async throws {
+ try await service.save(editor: service.editor(), electrum: server)
+ try await service.perform {
+ let revision = try self.service.replay()
+ try self.service.complete(revision: revision, hasPendingRestore: true, isRunning: true)
+ XCTAssertNotNil(self.data)
+ try self.service.complete(revision: revision, hasPendingRestore: false, isRunning: false)
+ XCTAssertNotNil(self.data)
+ try self.service.complete(revision: revision, hasPendingRestore: false, isRunning: true)
+ }
+ XCTAssertNil(data)
+ XCTAssertEqual(ElectrumConfigService(defaults: defaults).getCurrentServer(), server)
+ }
+
+ func testColdStartupRetainsRestrictedHostUntilCorrectionCompletes() async throws {
+ XCTAssertFalse(service.requiresRestrictedStartup(hasPendingRestore: false))
+ try await service.save(editor: service.editor(), electrum: server)
+ let restarted = makeService()
+ XCTAssertTrue(restarted.requiresRestrictedStartup(hasPendingRestore: false))
+ try await restarted.perform {
+ let revision = try restarted.replay()
+ try restarted.complete(revision: revision, hasPendingRestore: false, isRunning: false)
+ }
+ XCTAssertTrue(makeService().requiresRestrictedStartup(hasPendingRestore: false))
+ try await restarted.perform {
+ let revision = try restarted.replay()
+ try restarted.complete(revision: revision, hasPendingRestore: false, isRunning: true)
+ }
+ XCTAssertFalse(makeService().requiresRestrictedStartup(hasPendingRestore: false))
+ }
+
+ func testColdStartupUnavailableCorrectionFailsClosedWithoutReadingBeforeRequiredRestore() {
+ var reads = 0
+ let unavailable = ConnectionRecoveryService(owner: { self.currentOwner }, load: {
+ reads += 1
+ throw CocoaError(.fileReadNoPermission)
+ }, store: { _ in }, clear: {}, defaults: defaults)
+ XCTAssertTrue(unavailable.requiresRestrictedStartup(hasPendingRestore: true))
+ XCTAssertEqual(reads, 0)
+ XCTAssertTrue(unavailable.requiresRestrictedStartup(hasPendingRestore: false))
+ XCTAssertEqual(reads, 1)
+ data = Data("unreadable correction".utf8)
+ XCTAssertTrue(makeService().requiresRestrictedStartup(hasPendingRestore: false))
+ data = nil
+ XCTAssertFalse(makeService().requiresRestrictedStartup(hasPendingRestore: false))
+ }
+
+ func testQueuedInitializationCannotFinishAfterWipeFailureUntilCurrentStartupIsAcknowledged() async throws {
+ try await service.save(editor: service.editor(), electrum: server)
+ let lifecycle = service.lifecycleID
+ var dismissed = false
+ var callbackAfterRemoval = false
+ let appeared = expectation(description: "Initialization appears before wipe")
+ let callback = expectation(description: "Old callback executes after failed wipe")
+ let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)
+ let previousWindow = scene.windows.first(where: \.isKeyWindow)
+ let window = UIWindow(windowScene: scene)
+ window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
+ defer {
+ window.isHidden = true
+ window.rootViewController = nil
+ previousWindow?.makeKey()
+ }
+ let startup = Task {
+ try await service.perform {
+ _ = try self.service.replay()
+ window.rootViewController = UIHostingController(rootView: InitializingWalletView(
+ nodeLifecycleState: .constant(.running), initialPercentage: 98.75
+ ) {
+ callbackAfterRemoval = window.rootViewController == nil
+ if self.service.canFinishInitialization(lifecycle: lifecycle, isRunning: true,
+ hasPendingRestore: false, didFail: false)
+ {
+ dismissed = true
+ }
+ callback.fulfill()
+ }.onAppear { appeared.fulfill() })
+ window.makeKeyAndVisible()
+ try await Task.sleep(for: .seconds(10))
+ XCTFail("Wipe must cancel and drain the old startup")
+ }
+ }
+ await fulfillment(of: [appeared], timeout: 2)
+ try await Task.sleep(for: .milliseconds(200))
+ var lifecycleDuringWipe: UUID?
+ do {
+ try await AppReset.withConnectionRecoveryPaused(recovery: service) {
+ lifecycleDuringWipe = self.service.lifecycleID
+ window.rootViewController = nil
+ throw AppError(message: "Controlled node stop failure", debugMessage: nil)
+ }
+ XCTFail("Controlled wipe must fail")
+ } catch {}
+ do {
+ try await startup.value
+ XCTFail("Old startup must be cancelled")
+ } catch is CancellationError {} catch { XCTFail("Unexpected startup error: \(error)") }
+ await fulfillment(of: [callback], timeout: 3)
+ XCTAssertTrue(callbackAfterRemoval)
+ XCTAssertFalse(dismissed)
+ XCTAssertNotNil(data)
+ let currentLifecycle = try XCTUnwrap(lifecycleDuringWipe)
+ XCTAssertFalse(service.canFinishInitialization(lifecycle: currentLifecycle, isRunning: true,
+ hasPendingRestore: false, didFail: false))
+ try await service.perform {
+ let revision = try self.service.replay()
+ try self.service.complete(revision: revision, hasPendingRestore: false, isRunning: true)
+ }
+ XCTAssertTrue(service.canFinishInitialization(lifecycle: currentLifecycle, isRunning: true,
+ hasPendingRestore: false, didFail: false))
+ XCTAssertFalse(service.canFinishInitialization(lifecycle: lifecycle, isRunning: true,
+ hasPendingRestore: false, didFail: false))
+ }
+
+ func testQueuedInitializationCallbackCannotDismissFailedCorrectionCleanup() async throws {
+ let recovery = ConnectionRecoveryService(owner: { self.currentOwner }, load: { self.data },
+ store: { self.data = $0 }, clear: { throw CocoaError(.fileWriteNoPermission) },
+ defaults: defaults)
+ try await recovery.save(editor: recovery.editor(), electrum: server)
+ var didFail = false
+ var dismissed = false
+ var callbackAfterRemoval = false
+ let appeared = expectation(description: "Initialization view appears")
+ let callback = expectation(description: "Queued initialization callback executes after removal")
+ let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)
+ let previousWindow = scene.windows.first(where: \.isKeyWindow)
+ let window = UIWindow(windowScene: scene)
+ window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
+ defer {
+ window.isHidden = true
+ window.rootViewController = nil
+ previousWindow?.makeKey()
+ }
+ do {
+ try await recovery.perform {
+ let revision = try recovery.replay()
+ window.rootViewController = UIHostingController(rootView: InitializingWalletView(
+ nodeLifecycleState: .constant(.running), initialPercentage: 98.75
+ ) {
+ callbackAfterRemoval = window.rootViewController == nil
+ if recovery
+ .canFinishInitialization(lifecycle: recovery.lifecycleID, isRunning: true, hasPendingRestore: false, didFail: didFail)
+ {
+ dismissed = true
+ }
+ callback.fulfill()
+ }.onAppear { appeared.fulfill() })
+ window.makeKeyAndVisible()
+ await self.fulfillment(of: [appeared], timeout: 2)
+ // Let the real view enqueue its delayed completion before finalization fails.
+ try await Task.sleep(for: .milliseconds(200))
+ try recovery.complete(revision: revision, hasPendingRestore: false, isRunning: true)
+ }
+ XCTFail("Injected correction cleanup must fail")
+ } catch {
+ didFail = true
+ }
+ window.rootViewController = nil
+ XCTAssertFalse(recovery.isBusy)
+ await fulfillment(of: [callback], timeout: 3)
+ XCTAssertTrue(callbackAfterRemoval)
+ XCTAssertFalse(dismissed)
+ XCTAssertNotNil(data)
+
+ let wipe = try await recovery.beginWipe()
+ XCTAssertFalse(recovery.canFinishInitialization(lifecycle: recovery.lifecycleID, isRunning: true, hasPendingRestore: false, didFail: false))
+ recovery.endWipe(wipe)
+ }
+
+ func testActivitySyncFailureAfterAcknowledgedStartDoesNotReopenRecovery() async throws {
+ try await service.save(editor: service.editor(), electrum: server)
+ let lifecycle = service.lifecycleID
+ var showingError = true
+ var didSync = false
+ try await service.perform {
+ do {
+ let revision = try self.service.replay()
+ try self.service.complete(revision: revision, hasPendingRestore: false, isRunning: true) {
+ showingError = false
+ }
+ let sync: () async throws -> Void = {
+ didSync = true
+ throw CocoaError(.fileReadCorruptFile)
+ }
+ try await sync()
+ } catch {
+ XCTAssertTrue(self.service.canReportOperationFailure(), "The sync error still belongs to this operation")
+ if self.service.canReportStartupFailure() {
+ showingError = true
+ }
+ }
+ }
+ XCTAssertTrue(didSync)
+ XCTAssertFalse(showingError)
+ XCTAssertNil(data)
+ XCTAssertTrue(service.canFinishInitialization(lifecycle: lifecycle, isRunning: true,
+ hasPendingRestore: false, didFail: showingError))
+ }
+
+ func testStartupFailureRemainsReportableUntilRecoveryIsAcknowledged() async throws {
+ try await service.save(editor: service.editor(), electrum: server)
+ try await service.perform {
+ let revision = try self.service.replay()
+ XCTAssertTrue(self.service.canReportStartupFailure())
+ try self.service.complete(revision: revision, hasPendingRestore: true, isRunning: true)
+ XCTAssertTrue(self.service.canReportStartupFailure())
+ try self.service.complete(revision: revision, hasPendingRestore: false, isRunning: false)
+ XCTAssertTrue(self.service.canReportStartupFailure())
+ }
+ XCTAssertNotNil(data)
+ XCTAssertFalse(service.canReportStartupFailure(), "A completed operation cannot report a late error")
+ }
+
+ func testAnotherStartDoesNotInheritEarlierSuccessfulRecovery() async throws {
+ try await service.perform {
+ try self.service.complete(revision: nil, hasPendingRestore: false, isRunning: true)
+ }
+ try await service.perform {
+ XCTAssertTrue(self.service.canReportStartupFailure())
+ }
+ }
+
+ func testAutomaticResumeClearsPriorErrorOnlyAfterAcknowledgedStartup() async throws {
+ var showingError = true
+ try await service.save(editor: service.editor(), electrum: server)
+ try await service.perform {
+ let revision = try self.service.replay()
+ try self.service.complete(revision: revision, hasPendingRestore: false, isRunning: false) { showingError = false }
+ XCTAssertTrue(showingError)
+ try self.service.complete(revision: revision, hasPendingRestore: true, isRunning: true) { showingError = false }
+ XCTAssertTrue(showingError)
+ }
+ let restarted = makeService()
+ try await restarted.perform {
+ let revision = try restarted.replay()
+ try restarted.complete(revision: revision, hasPendingRestore: false, isRunning: true) { showingError = false }
+ }
+ XCTAssertFalse(showingError)
+ XCTAssertNil(data)
+
+ // A later automatic resume has no correction left, but must still retire its old error host.
+ showingError = true
+ try await restarted.perform {
+ XCTAssertNil(try restarted.replay())
+ try restarted.complete(revision: nil, hasPendingRestore: false, isRunning: true) { showingError = false }
+ }
+ XCTAssertFalse(showingError)
+
+ showingError = true
+ let failedCleanup = ConnectionRecoveryService(owner: { self.currentOwner }, load: { self.data },
+ store: { self.data = $0 }, clear: { throw CocoaError(.fileWriteNoPermission) },
+ defaults: defaults)
+ try await failedCleanup.save(editor: failedCleanup.editor(), electrum: server)
+ do {
+ try await failedCleanup.perform {
+ let revision = try failedCleanup.replay()
+ try failedCleanup.complete(revision: revision, hasPendingRestore: false, isRunning: true) { showingError = false }
+ }
+ XCTFail("Failed correction cleanup must retain the error host")
+ } catch {}
+ XCTAssertTrue(showingError)
+ XCTAssertNotNil(data)
+ }
+
+ func testWipeDrainsNonCancellableProbeAndRejectsSameSeedOldEditor() async throws {
+ let editor = try service.editor()
+ let entered = expectation(description: "Probe entered")
+ var release: CheckedContinuation?
+ let save = Task {
+ try await service.save(editor: editor, electrum: server) {
+ await withCheckedContinuation { release = $0; entered.fulfill() }
+ }
+ }
+ await fulfillment(of: [entered], timeout: 2)
+ var wipeReturned = false
+ let wipe = Task { let id = try await service.beginWipe(); wipeReturned = true; return id }
+ await Task.yield()
+ XCTAssertFalse(wipeReturned)
+ release?.resume()
+ _ = await save.result
+ let wipeID = try await wipe.value
+ XCTAssertNil(data)
+ XCTAssertNil(defaults.data(forKey: "electrumServer"))
+ service.endWipe(wipeID)
+ do {
+ try await service.save(editor: editor, electrum: server)
+ XCTFail("Same seed replacement must not revive an old editor")
+ } catch {}
+ XCTAssertFalse(service.isBusy)
+ try await service.save(editor: service.editor(), electrum: server)
+ XCTAssertNotNil(data)
+ }
+
+ func testAppResetTimesOutAndRetriesWhileOriginalStartupStillOwnsAdmission() async throws {
+ let entered = expectation(description: "Noncancellable native startup entered")
+ let gate = DispatchSemaphore(value: 0)
+ defer { gate.signal() }
+ let oldLifecycle = service.lifecycleID
+ var startupCommitted = false
+ let startup = Task {
+ try await service.perform {
+ try await ServiceQueue.background(.ldk) {
+ entered.fulfill()
+ XCTAssertEqual(gate.wait(timeout: .now() + 10), .success)
+ }
+ try self.service.checkCurrentOperation()
+ startupCommitted = true
+ }
+ }
+ await fulfillment(of: [entered], timeout: 2)
+ for _ in 0 ..< 2 {
+ do {
+ try await AppReset.withConnectionRecoveryPaused(recovery: service, timeout: .milliseconds(50)) {
+ XCTFail("No wipe step may run before the original startup drains")
+ }
+ XCTFail("The blocked prerequisite must return a bounded failure")
+ } catch let error as WipeWaitTimeoutError {
+ XCTAssertEqual(error.wait, "connection recovery")
+ }
+ XCTAssertTrue(service.isBusy)
+ XCTAssertFalse(service.isCurrentLifecycle(oldLifecycle))
+ do {
+ try await service.perform { XCTFail("Timed-out work still owns admission") }
+ XCTFail("New work must remain refused")
+ } catch ConnectionRecoveryService.AdmissionError.busy {}
+ }
+ gate.signal()
+ _ = await startup.result
+ XCTAssertFalse(startupCommitted)
+ var wipeEntered = false
+ try await AppReset.withConnectionRecoveryPaused(recovery: service) { wipeEntered = true }
+ XCTAssertTrue(wipeEntered)
+ XCTAssertFalse(service.isBusy)
+ }
+
+ func testIdentityReplacementDuringValidationCannotWrite() async throws {
+ let editor = try service.editor()
+ do {
+ try await service.save(editor: editor, electrum: server) {
+ self.currentOwner = .init(walletIndex: 0, network: "regtest", binding: "replacement")
+ }
+ XCTFail("Replacement must reject old work")
+ } catch {}
+ XCTAssertNil(data)
+ XCTAssertNil(defaults.data(forKey: "electrumServer"))
+ }
+
+ func testCancelledCallerCannotCommitAfterSuspendedProbe() async throws {
+ let editor = try service.editor()
+ let entered = expectation(description: "Probe entered")
+ var release: CheckedContinuation?
+ let save = Task {
+ try await service.save(editor: editor, electrum: server) {
+ await withCheckedContinuation { release = $0; entered.fulfill() }
+ }
+ }
+ await fulfillment(of: [entered], timeout: 2)
+ save.cancel()
+ release?.resume()
+ _ = await save.result
+ XCTAssertNil(data)
+ XCTAssertFalse(service.isBusy)
+ }
+
+ func testEscapedOperationCannotReplayAfterItsScopeEnds() async throws {
+ var escaped: Task?
+ var release: CheckedContinuation?
+ let entered = expectation(description: "Escaped task waiting")
+ try await service.perform {
+ escaped = Task {
+ await withCheckedContinuation { release = $0; entered.fulfill() }
+ return try self.service.replay()
+ }
+ await self.fulfillment(of: [entered], timeout: 2)
+ }
+ release?.resume()
+ do {
+ _ = try await escaped?.value
+ XCTFail("Inherited scope must be revoked after return")
+ } catch {}
+ }
+
+ func testSecondWipeCannotReleaseOriginalAdmission() async throws {
+ let original = try await service.beginWipe()
+ do {
+ _ = try await service.beginWipe()
+ XCTFail("Duplicate wipe must be rejected before registering cleanup")
+ } catch ConnectionRecoveryService.AdmissionError.busy {} catch { XCTFail("Unexpected error: \(error)") }
+ service.endWipe(UUID())
+ do {
+ try await service.perform {}
+ XCTFail("Foreign cleanup must not reopen admission")
+ } catch ConnectionRecoveryService.AdmissionError.busy {} catch { XCTFail("Unexpected error: \(error)") }
+ service.endWipe(original)
+ try await service.perform {}
+ }
+
+ func testAdmittedRetryFinishesAfterEditorDismissal() async throws {
+ let entered = expectation(description: "Native stop is suspended")
+ var release: CheckedContinuation?
+ var events: [String] = []
+ let retry = Task {
+ try await service.perform(cancelsWithCaller: false) {
+ events.append("stop")
+ await withCheckedContinuation { release = $0; entered.fulfill() }
+ try self.service.checkCurrentOperation()
+ events.append("restore")
+ events.append("start")
+ }
+ }
+ await fulfillment(of: [entered], timeout: 2)
+ retry.cancel()
+ release?.resume()
+ try await retry.value
+ XCTAssertEqual(events, ["stop", "restore", "start"])
+ XCTAssertFalse(service.isBusy)
+ }
+
+ func testDismissedRetryCanReportOwnerReadFailureWithoutReauthorizingWork() async {
+ var ownerUnavailable = false
+ let recovery = ConnectionRecoveryService(owner: {
+ if ownerUnavailable {
+ throw CocoaError(.fileReadNoPermission)
+ }
+ return self.currentOwner
+ }, load: { nil }, store: { _ in }, clear: {}, defaults: defaults)
+ let entered = expectation(description: "Restore is suspended")
+ var release: CheckedContinuation?
+ var reportedFailure = false
+ var started = false
+ let retry = Task {
+ try await recovery.perform(cancelsWithCaller: false) {
+ _ = try recovery.replay()
+ await withCheckedContinuation { release = $0; entered.fulfill() }
+ do {
+ try recovery.checkCurrentOperation()
+ started = true
+ } catch {
+ reportedFailure = recovery.canReportOperationFailure()
+ }
+ }
+ }
+ await fulfillment(of: [entered], timeout: 2)
+ retry.cancel()
+ ownerUnavailable = true
+ release?.resume()
+ _ = await retry.result
+ XCTAssertTrue(reportedFailure)
+ XCTAssertFalse(started)
+ XCTAssertFalse(recovery.canReportOperationFailure())
+ }
+
+ func testAppResetDrainPrecedesSdkWipeAndDuplicateCannotReopenSettings() async throws {
+ let lock = PaykitSdkOperationLock()
+ let recoveryEntered = expectation(description: "Recovery owns SDK")
+ let wipeEntered = expectation(description: "Wipe owns SDK after drain")
+ var releaseRecovery: CheckedContinuation?
+ var releaseWipe: CheckedContinuation?
+ var events: [String] = []
+ let recovery = Task {
+ try await service.perform(cancelsWithCaller: false) {
+ defer { events.append("recovery drained") }
+ try await lock.withLock {
+ events.append("recovery SDK")
+ await withCheckedContinuation { releaseRecovery = $0; recoveryEntered.fulfill() }
+ }
+ }
+ }
+ await fulfillment(of: [recoveryEntered], timeout: 2)
+ let originalGeneration = service.lifecycleID
+ let wipe = Task {
+ try await AppReset.withConnectionRecoveryPaused(recovery: service) {
+ try await lock.withWalletWipe {
+ events.append("wipe SDK")
+ await withCheckedContinuation { releaseWipe = $0; wipeEntered.fulfill() }
+ }
+ }
+ }
+ for _ in 0 ..< 100 where service.isCurrentLifecycle(originalGeneration) {
+ await Task.yield()
+ }
+ XCTAssertFalse(service.isCurrentLifecycle(originalGeneration))
+ XCTAssertEqual(events, ["recovery SDK"])
+ releaseRecovery?.resume()
+ await fulfillment(of: [wipeEntered], timeout: 2)
+ do {
+ try await AppReset.withConnectionRecoveryPaused(recovery: service) {
+ XCTFail("A second wipe must not enter")
+ }
+ XCTFail("A second wipe must be rejected")
+ } catch ConnectionRecoveryService.AdmissionError.busy {} catch { XCTFail("Unexpected error: \(error)") }
+ let settings = SettingsViewModel.shared
+ XCTAssertFalse(settings.isCurrentServerConnection(settings.serverConnectionGeneration))
+ XCTAssertFalse(service.isCurrentLifecycle(service.lifecycleID))
+ releaseWipe?.resume()
+ _ = await recovery.result
+ try await wipe.value
+ XCTAssertEqual(events, ["recovery SDK", "recovery drained", "wipe SDK"])
+ XCTAssertTrue(settings.isCurrentServerConnection(settings.serverConnectionGeneration))
+ XCTAssertTrue(service.isCurrentLifecycle(service.lifecycleID))
+ }
+}
+
+private final class FailingConnectionPreferences: UserDefaults {
+ var rejectWrites = false
+ override func set(_ value: Any?, forKey defaultName: String) {
+ if !rejectWrites {
+ super.set(value, forKey: defaultName)
+ }
+ }
+}
diff --git a/BitkitTests/NodeEventListenerTests.swift b/BitkitTests/NodeEventListenerTests.swift
new file mode 100644
index 0000000000..12bf5f731f
--- /dev/null
+++ b/BitkitTests/NodeEventListenerTests.swift
@@ -0,0 +1,320 @@
+@testable import Bitkit
+import LDKNode
+import XCTest
+
+@MainActor
+final class NodeEventListenerTests: XCTestCase {
+ func testFailedStartsDoNotLeaveEventWaitersOrRetainNodes() async throws {
+ let listener = NodeEventListener()
+ for _ in 0 ..< 3 {
+ var node: EventNode? = EventNode(noPointer: .init())
+ let releasedNode = { [weak node] in node }
+ node?.startError = TestError.failed
+ do {
+ try await listener.start(node: XCTUnwrap(node)) { _ in XCTFail("A failed node must not deliver events") }
+ XCTFail("Expected native startup failure")
+ } catch {}
+ try await listener.stop(node: XCTUnwrap(node)) { _ in XCTFail("A failed node must not resume events") }
+ XCTAssertEqual(node?.pollCount, 0)
+ XCTAssertEqual(node?.asyncWaitCount, 0)
+ node = nil
+ XCTAssertNil(releasedNode())
+ }
+ }
+
+ func testStartupEventIsDeliveredOnceAndEmptyQueueReleasesBeforeReplacement() async throws {
+ let listener = NodeEventListener()
+ for _ in 0 ..< 2 {
+ var node: EventNode? = EventNode(noPointer: .init())
+ let releasedNode = { [weak node] in node }
+ node?.enqueue()
+ let delivered = expectation(description: "Startup event delivered")
+ let empty = expectation(description: "Empty queue reached")
+ node?.onEmpty = { empty.fulfill() }
+ try await listener.start(node: XCTUnwrap(node)) { _ in delivered.fulfill() }
+ await fulfillment(of: [delivered, empty], timeout: 2)
+ try await listener.stop(node: XCTUnwrap(node)) { _ in XCTFail("Unexpected resumed event") }
+ XCTAssertEqual(node?.handledCount, 1)
+ XCTAssertEqual(node?.asyncWaitCount, 0)
+ node = nil
+ XCTAssertNil(releasedNode(), "A correction cleanup failure followed by Retry must release the previous node")
+ }
+ }
+
+ func testStopDrainsAcknowledgedDeliveryBeforeStoppingNode() async throws {
+ let listener = NodeEventListener()
+ let node = EventNode(noPointer: .init())
+ node.enqueue()
+ let entered = expectation(description: "Acknowledged delivery entered")
+ var release: CheckedContinuation?
+ var delivered = false
+ try await listener.start(node: node) { _ in
+ await withCheckedContinuation { continuation in
+ release = continuation
+ entered.fulfill()
+ }
+ delivered = true
+ }
+ await fulfillment(of: [entered], timeout: 2)
+ let stopping = expectation(description: "Stop requested")
+ node.onStop = { XCTAssertTrue(delivered, "Native stop must follow acknowledged callback completion") }
+ let stop = Task {
+ stopping.fulfill()
+ try await listener.stop(node: node) { _ in XCTFail("Unexpected resumption") }
+ }
+ await fulfillment(of: [stopping], timeout: 2)
+ XCTAssertEqual(node.stopCount, 0)
+ XCTAssertFalse(delivered)
+ let concurrentStopRejected = expectation(description: "Concurrent stop remains rejected")
+ let concurrentStop = Task {
+ do {
+ try await listener.stop(node: node) { _ in XCTFail("Unexpected concurrent delivery") }
+ XCTFail("A concurrent stop must not replace the draining operation")
+ } catch { concurrentStopRejected.fulfill() }
+ }
+ await fulfillment(of: [concurrentStopRejected], timeout: 2)
+ release?.resume()
+ try await stop.value
+ await concurrentStop.value
+ XCTAssertTrue(delivered)
+ XCTAssertEqual(node.stopCount, 1)
+ XCTAssertEqual(node.handledCount, 1)
+ }
+
+ func testAcknowledgementDoesNotBlockIndependentNodeReadsAndStopStillDrainsIt() async throws {
+ let listener = NodeEventListener()
+ let node = EventNode(noPointer: .init())
+ node.enqueue()
+ let entered = expectation(description: "Acknowledgement is held")
+ let gate = DispatchSemaphore(value: 0)
+ defer { gate.signal() }
+ node.onHandled = {
+ entered.fulfill()
+ XCTAssertEqual(gate.wait(timeout: .now() + 10), .success)
+ }
+ var delivered = false
+ try await listener.start(node: node) { _ in delivered = true }
+ await fulfillment(of: [entered], timeout: 2)
+ let readFinished = expectation(description: "Independent LDK read completes while acknowledgement is held")
+ let read = Task {
+ let event = try await ServiceQueue.background(.ldk) { node.nextEvent() }
+ XCTAssertNotNil(event)
+ readFinished.fulfill()
+ }
+ await fulfillment(of: [readFinished], timeout: 2)
+ let stopRequested = expectation(description: "Stop requested during acknowledgement")
+ node.onStop = { XCTAssertTrue(delivered) }
+ let stopping = Task {
+ stopRequested.fulfill()
+ try await listener.stop(node: node) { _ in XCTFail("Unexpected resumed delivery") }
+ }
+ await fulfillment(of: [stopRequested], timeout: 2)
+ XCTAssertEqual(node.stopCount, 0)
+ XCTAssertFalse(delivered)
+ gate.signal()
+ try await read.value
+ try await stopping.value
+ XCTAssertTrue(delivered)
+ XCTAssertEqual(node.handledCount, 1)
+ XCTAssertEqual(node.stopCount, 1)
+ }
+
+ func testStopFailureResumesOnlyTheRetainedNodeConsumer() async throws {
+ let listener = NodeEventListener()
+ let node = EventNode(noPointer: .init())
+ node.stopError = TestError.failed
+ let empty = expectation(description: "Initial empty queue")
+ node.onEmpty = { empty.fulfill() }
+ try await listener.start(node: node) { _ in XCTFail("No initial event") }
+ await fulfillment(of: [empty], timeout: 2)
+ let resumed = expectation(description: "Retained node resumes delivery")
+ do {
+ try await listener.stop(node: node) { _ in resumed.fulfill() }
+ XCTFail("Expected native stop failure")
+ } catch {}
+ node.enqueue()
+ await fulfillment(of: [resumed], timeout: 2)
+ node.stopError = nil
+ try await listener.stop(node: node) { _ in XCTFail("Unexpected further resumption") }
+ XCTAssertEqual(node.startCount, 1)
+ XCTAssertEqual(node.handledCount, 1)
+ }
+
+ func testStopDuringNativeStartDrainsStartupEvenWhenCancelled() async throws {
+ for cancelStop in [false, true] {
+ let listener = NodeEventListener()
+ let node = EventNode(noPointer: .init())
+ let gate = DispatchSemaphore(value: 0)
+ defer { gate.signal() }
+ let entered = expectation(description: "Native startup entered")
+ node.onStart = {
+ entered.fulfill()
+ XCTAssertEqual(gate.wait(timeout: .now() + 10), .success)
+ }
+ let starting = Task { try await listener.start(node: node) { _ in XCTFail("No event queued") } }
+ await fulfillment(of: [entered], timeout: 2)
+
+ let requested = expectation(description: "Stop requested during startup")
+ let stopping = Task {
+ requested.fulfill()
+ do {
+ try await listener.stop(node: node) { _ in XCTFail("No event queued") }
+ return true
+ } catch { return false }
+ }
+ await fulfillment(of: [requested], timeout: 2)
+ if cancelStop {
+ stopping.cancel()
+ }
+ XCTAssertEqual(node.stopCount, 0)
+ gate.signal()
+ try await starting.value
+ let stopped = await stopping.value
+ XCTAssertTrue(stopped, "Stop must drain the original start, including cancellation")
+ XCTAssertEqual(node.startCount, 1)
+ XCTAssertEqual(node.stopCount, 1)
+ if !stopped {
+ try await listener.stop(node: node) { _ in XCTFail("Unexpected cleanup event") }
+ }
+ }
+ }
+
+ func testStopWaitingForFailedStartCompletesWithoutAnEventConsumer() async {
+ let listener = NodeEventListener()
+ let node = EventNode(noPointer: .init())
+ node.startError = TestError.failed
+ let gate = DispatchSemaphore(value: 0)
+ defer { gate.signal() }
+ let entered = expectation(description: "Failing startup entered")
+ node.onStart = {
+ entered.fulfill()
+ XCTAssertEqual(gate.wait(timeout: .now() + 10), .success)
+ }
+ let starting = Task {
+ do {
+ try await listener.start(node: node) { _ in XCTFail("Failed startup cannot deliver events") }
+ XCTFail("Expected startup failure")
+ } catch {}
+ }
+ await fulfillment(of: [entered], timeout: 2)
+ let requested = expectation(description: "Stop requested before startup failure")
+ let stopping = Task {
+ requested.fulfill()
+ do {
+ try await listener.stop(node: node) { _ in XCTFail("Failed startup cannot resume events") }
+ return true
+ } catch { return false }
+ }
+ await fulfillment(of: [requested], timeout: 2)
+ gate.signal()
+ await starting.value
+ let stopped = await stopping.value
+ XCTAssertTrue(stopped, "An unsuccessful start must release its waiting stop")
+ XCTAssertEqual(node.startCount, 0)
+ XCTAssertEqual(node.pollCount, 0)
+ }
+
+ func testStopAlreadyWaitingForStartupRejectsAnotherStop() async throws {
+ let listener = NodeEventListener()
+ let node = EventNode(noPointer: .init())
+ let gate = DispatchSemaphore(value: 0)
+ defer { gate.signal() }
+ let entered = expectation(description: "Startup held before completion")
+ node.onStart = {
+ entered.fulfill()
+ XCTAssertEqual(gate.wait(timeout: .now() + 10), .success)
+ }
+ let starting = Task { try await listener.start(node: node) { _ in XCTFail("No event queued") } }
+ await fulfillment(of: [entered], timeout: 2)
+ let requested = expectation(description: "First stop owns pending cleanup")
+ let firstStop = Task {
+ requested.fulfill()
+ do {
+ try await listener.stop(node: node) { _ in XCTFail("No event queued") }
+ return true
+ } catch { return false }
+ }
+ await fulfillment(of: [requested], timeout: 2)
+ let rejected = expectation(description: "Second stop rejected before startup completes")
+ let secondStop = Task {
+ do {
+ try await listener.stop(node: node) { _ in XCTFail("Unexpected replacement delivery") }
+ XCTFail("The first waiting stop must retain lifecycle ownership")
+ } catch { rejected.fulfill() }
+ }
+ await fulfillment(of: [rejected], timeout: 2)
+ gate.signal()
+ try await starting.value
+ let firstStopped = await firstStop.value
+ await secondStop.value
+ XCTAssertTrue(firstStopped)
+ XCTAssertEqual(node.stopCount, 1)
+ }
+}
+
+private enum TestError: Error { case failed }
+
+private final class EventNode: Node {
+ var startError: Error?
+ var stopError: Error?
+ var onStart: (() -> Void)?
+ var onEmpty: (() -> Void)?
+ var onStop: (() -> Void)?
+ var onHandled: (() -> Void)?
+ private let lock = NSLock()
+ private var running = false
+ private var event: Event?
+ private(set) var startCount = 0
+ private(set) var stopCount = 0
+ private(set) var pollCount = 0
+ private(set) var handledCount = 0
+ private(set) var asyncWaitCount = 0
+
+ func enqueue() {
+ lock.withLock { event = .syncCompleted(syncType: .onchainWallet, syncedBlockHeight: 1) }
+ }
+
+ override func start() throws {
+ onStart?()
+ if let startError {
+ throw startError
+ }
+ running = true
+ startCount += 1
+ }
+
+ override func stop() throws {
+ if let stopError {
+ throw stopError
+ }
+ guard running else { throw NodeError.NotRunning(message: "not running") }
+ onStop?()
+ running = false
+ stopCount += 1
+ }
+
+ override func nextEvent() -> Event? {
+ lock.withLock {
+ pollCount += 1
+ if event == nil {
+ onEmpty?()
+ onEmpty = nil
+ }
+ return event
+ }
+ }
+
+ override func nextEventAsync() async -> Event {
+ asyncWaitCount += 1
+ XCTFail("The native asynchronous wait cannot be cancelled")
+ return .syncCompleted(syncType: .onchainWallet, syncedBlockHeight: 1)
+ }
+
+ override func eventHandled() throws {
+ onHandled?()
+ lock.withLock {
+ handledCount += 1
+ event = nil
+ }
+ }
+}
diff --git a/BitkitTests/UsdtRecoveryBackupTests.swift b/BitkitTests/UsdtRecoveryBackupTests.swift
index 39ba316374..f2d76ff108 100644
--- a/BitkitTests/UsdtRecoveryBackupTests.swift
+++ b/BitkitTests/UsdtRecoveryBackupTests.swift
@@ -157,7 +157,12 @@ final class UsdtRecoveryBackupTests: XCTestCase {
}
)
for _ in 0 ..< 2 {
- let service = BackupService(defaults: defaults, backupData: { _ in
+ let connection = ConnectionRecoveryService(
+ owner: { .init(walletIndex: 0, network: "regtest", binding: "legacy-test-wallet") },
+ load: { nil }, store: { _ in XCTFail("No connection correction is being saved") },
+ clear: { XCTFail("No connection correction is being completed") }, defaults: defaults
+ )
+ let service = BackupService(defaults: defaults, connectionRecovery: connection, backupData: { _ in
XCTFail("A partial wallet must not replace the retained backup")
return Data()
}, usdtRecoveryBackup: recovery, uploadBackup: { _, _ in
diff --git a/BitkitTests/WalletViewModelWipeTests.swift b/BitkitTests/WalletViewModelWipeTests.swift
index 738087e719..b526e4d093 100644
--- a/BitkitTests/WalletViewModelWipeTests.swift
+++ b/BitkitTests/WalletViewModelWipeTests.swift
@@ -29,7 +29,7 @@ private final class FakeNodeLifecycle: Bitkit.NodeLifecycleService {
hasNode = true
}
- func start(onEvent _: ((Event) -> Void)?) async throws {
+ func start(onEvent _: (@MainActor (Event) -> Void)?) async throws {
record("start")
if let startError {
throw startError
diff --git a/changelog.d/next/1139.fixed.md b/changelog.d/next/1139.fixed.md
new file mode 100644
index 0000000000..c40d82a4a6
--- /dev/null
+++ b/changelog.d/next/1139.fixed.md
@@ -0,0 +1 @@
+Allow connection settings to be corrected during wallet recovery while preserving required backup restoration, safely replacing failed nodes on retry, and keeping offline wallet creation waiting for connectivity without reporting a restoration failure, while retaining recovery controls if an existing startup-error retry remains offline.
diff --git a/journeys/backup-restore/README.md b/journeys/backup-restore/README.md
new file mode 100644
index 0000000000..b916c7f1cf
--- /dev/null
+++ b/journeys/backup-restore/README.md
@@ -0,0 +1,3 @@
+# Backup and restore
+
+- `connection-recovery.xml`: restricted Electrum/RGS repair retains required restore gates. iOS restores before node startup; Electrum Save validates syntax and startup checks connectivity. Full authenticated journey not yet executed.
diff --git a/journeys/backup-restore/connection-recovery.xml b/journeys/backup-restore/connection-recovery.xml
new file mode 100644
index 0000000000..bac713b583
--- /dev/null
+++ b/journeys/backup-restore/connection-recovery.xml
@@ -0,0 +1,27 @@
+
+
+ Use a disposable dev wallet and a controlled recovery fixture with an acknowledged complete wallet
+ backup. Prepare a failing Electrum endpoint and a reachable replacement, plus a backup SETTINGS
+ record containing the old endpoint. Required WALLET and USDT recovery must remain pending until
+ their imports succeed. Never reset an existing wallet or use live funds. iOS restores required backup state before starting a rebuilt node; Android can need a running node
+ during restoration. The iOS editor validates Electrum syntax on Save; permitted startup proves
+ connectivity. RGS uses an independent endpoint probe. Installed simulator checks cover authenticated
+ restoration, correction persistence, retry and restart, required-marker/local-storage failures, and
+ optional profile failure/recovery. The fixture's successful empty USDT record listing is not a
+ nonempty USDT import or proof of full chain synchronization or spending. Actual wallet wipe remains
+ unrun and outside the no-reset authorization. Component tests are separate from these app checks.
+
+
+ Restore the fixture wallet and verify failed node startup offers Connection Settings without access to ordinary wallet actions
+ Open Connection Settings and verify the screen tagged WalletConnectionRecovery is visible without Proceed Without Backup
+ Enter the reachable Electrum endpoint in RecoveryElectrumInput and tap RecoveryElectrumSave; verify RecoverySaved appears without automatically retrying restoration
+ Change and save RGS independently; verify a failed probe shows RecoveryError and retains the last acknowledged correction
+ Return to the restore error and tap Try Again; verify required wallet restoration resumes with the saved correction before a rebuilt node starts
+ Keep required recovery unavailable and restart the app; verify the correction is retained and spending remains gated
+ While required recovery remains unavailable, background and foreground three times and tap Try Again; verify the correction and gates remain and no already-running node is rebuilt solely because the unchanged correction is retained
+ Allow restoration of the old SETTINGS backup; verify only the explicitly corrected endpoints override that backup and unrelated preferences restore normally
+ Complete required WALLET and USDT recovery; verify ordinary wallet actions become available only after both acknowledgements
+ Repeat with only optional profile caching unavailable after required recovery; verify that error retains its optional recovery controls and is not classified as failed node startup
+ On a separate empty test installation, go offline before tapping New Wallet; verify creation stays in initialization without Spending balance error or Connection Settings. Restore connectivity and verify startup resumes through the ordinary coordinator without bypassing any required recovery marker
+
+