From e823cf89abe30a4469c220595ee0317c44b10db4 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 00:55:16 +0200 Subject: [PATCH 01/45] fix: decouple wallet restore from profile refresh --- Bitkit/AppScene.swift | 2 +- Bitkit/Managers/PubkyProfileManager.swift | 57 +++++++++- .../PrivatePaykitService+Backup.swift | 12 +- BitkitTests/PrivatePaykitServiceTests.swift | 104 +++++++++++++++++ BitkitTests/PubkyProfileManagerTests.swift | 106 ++++++++++++++++++ changelog.d/next/restore-identity.fixed.md | 1 + .../wallet/restore-during-identity-outage.xml | 18 +++ 7 files changed, 290 insertions(+), 10 deletions(-) create mode 100644 changelog.d/next/restore-identity.fixed.md create mode 100644 journeys/wallet/restore-during-identity-outage.xml diff --git a/Bitkit/AppScene.swift b/Bitkit/AppScene.swift index 47c9c2995e..c39b57cfb7 100644 --- a/Bitkit/AppScene.swift +++ b/Bitkit/AppScene.swift @@ -1169,7 +1169,7 @@ struct AppScene: View { widgets.loadSavedWidgets() widgets.objectWillChange.send() - await pubkyProfile.initialize() + pubkyProfile.scheduleInitializationAfterRestore() await startWallet(completingBackupRestore: true) } diff --git a/Bitkit/Managers/PubkyProfileManager.swift b/Bitkit/Managers/PubkyProfileManager.swift index 52b60f8cfe..d29dd6b1e0 100644 --- a/Bitkit/Managers/PubkyProfileManager.swift +++ b/Bitkit/Managers/PubkyProfileManager.swift @@ -108,6 +108,8 @@ class PubkyProfileManager: ObservableObject { private var isSignupInFlight = false private var initializationTask: Task? + private var initializationRevision: UUID? + private var restoreInitialization: (id: UUID, revision: UUID, task: Task)? private var completedRecoveryVersion = 0 private var sessionRestorationDeferred = false private var readOnlySignOutRevision: UUID? @@ -209,30 +211,65 @@ class PubkyProfileManager: ObservableObject { await initialize(mode: .userVisible, initializeSession: initializeSession) } + func scheduleInitializationAfterRestore( + initializeSession: @escaping @Sendable () async throws -> SessionInitializationResult = { + try await PubkyProfileManager.initializePersistedSession() + } + ) { + let revision = Self.sessionRevision + guard restoreInitialization?.revision != revision, Self.sessionMutationCount == 0, !Self.isProfileDeletionInFlight else { return } + clearAuthenticatedState(clearCachedProfile: false) + let previousRevision = initializationRevision + let initialization = beginInitialization(mode: .userVisible, initializeSession: initializeSession) + let id = UUID() + let task = Task { + defer { + if restoreInitialization?.id == id { + restoreInitialization = nil + } + } + guard revision == Self.sessionRevision else { return } + await initialization?.value + guard revision == Self.sessionRevision else { return } + if let previousRevision, previousRevision != revision { + await initialize(mode: .userVisible, initializeSession: initializeSession) + } + } + restoreInitialization = (id, revision, task) + } + private func initialize( mode: SessionInitializationMode, initializeSession: @escaping @Sendable () async throws -> SessionInitializationResult ) async { + await beginInitialization(mode: mode, initializeSession: initializeSession)?.value + } + + private func beginInitialization( + mode: SessionInitializationMode, + initializeSession: @escaping @Sendable () async throws -> SessionInitializationResult + ) -> Task? { if let initializationTask { - await initializationTask.value - return + return initializationTask } - guard Self.sessionMutationCount == 0, !Self.isProfileDeletionInFlight else { return } + guard Self.sessionMutationCount == 0, !Self.isProfileDeletionInFlight else { return nil } isRestoringSession = true let revision = Self.sessionRevision let task = Task { defer { initializationTask = nil + initializationRevision = nil isRestoringSession = false } - guard Self.sessionMutationCount == 0, !Self.isProfileDeletionInFlight else { return } + guard revision == Self.sessionRevision, Self.sessionMutationCount == 0, !Self.isProfileDeletionInFlight else { return } await initializeSessionState(mode: mode, initializeSession: initializeSession) if case .automaticRecovery = mode, revision == Self.sessionRevision { completedRecoveryVersion += 1 } } initializationTask = task - await task.value + initializationRevision = revision + return task } /// Retry saved credentials after startup or connectivity failures without replacing active identity work. @@ -1740,6 +1777,16 @@ class PubkyProfileManager: ObservableObject { return PubkyPublicKeyFormat.matches(adopted.pubky, publicKey) } + nonisolated static func hasStoredIdentityForBackup() throws -> Bool { + if AdoptedPubkyReference.current != nil { + return true + } + // Malformed credential bytes must not permit an identity-free replacement backup. + return try [KeychainEntryType.paykitSession, .pubkySecretKey].contains { + try Keychain.load(key: $0)?.isEmpty == false + } + } + nonisolated static func hasStoredIdentity( adopted: (sourceApp: String, pubky: String)? = AdoptedPubkyReference.current ) throws -> Bool { diff --git a/Bitkit/Services/PrivatePaykitService+Backup.swift b/Bitkit/Services/PrivatePaykitService+Backup.swift index 589b4c5cf5..9c2a92cb6f 100644 --- a/Bitkit/Services/PrivatePaykitService+Backup.swift +++ b/Bitkit/Services/PrivatePaykitService+Backup.swift @@ -3,13 +3,17 @@ import Foundation // MARK: - Backup extension PrivatePaykitService { - func backupSnapshot() async throws -> (state: String?, sdkVersion: UInt64) { - let initialSdkVersion = await PaykitSdkService.shared.backupStateVersion - guard try await PaykitSdkService.shared.currentPublicKey() != nil else { + func backupSnapshot( + sdkService: PaykitSdkService = .shared, + hasStoredIdentity: @Sendable () throws -> Bool = { try PubkyProfileManager.hasStoredIdentityForBackup() } + ) async throws -> (state: String?, sdkVersion: UInt64) { + let initialSdkVersion = await sdkService.backupStateVersion + guard try await sdkService.currentPublicKey() != nil else { + guard try !hasStoredIdentity() else { throw PubkyServiceError.sessionNotActive } return (nil, initialSdkVersion) } // Wallet backups may be required before broadcast; they cannot wait for payment to finish. - let exported = try await PaykitSdkService.shared.exportBackupSnapshot(priority: .interactive) + let exported = try await sdkService.exportBackupSnapshot(priority: .interactive) let backup = Backup( sdkState: exported.state, consumedPrivatePaymentListVersions: state.contacts.compactMapValues { contactState in diff --git a/BitkitTests/PrivatePaykitServiceTests.swift b/BitkitTests/PrivatePaykitServiceTests.swift index 3740ad349a..c0bfa70bbf 100644 --- a/BitkitTests/PrivatePaykitServiceTests.swift +++ b/BitkitTests/PrivatePaykitServiceTests.swift @@ -3,6 +3,88 @@ import Paykit import XCTest final class PrivatePaykitServiceTests: XCTestCase { + @MainActor + func testUnresolvedStoredIdentityCannotReplaceCompleteWalletBackup() async throws { + let sdk = BackupIdentitySdk(noPointer: .init()) + let sdkService = PaykitSdkService(sdkFactory: { sdk }) + let privateService = PrivatePaykitService() + let suite = "PendingIdentityBackup.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + var remote = Data("complete-wallet".utf8) + var uploads = 0 + let backup = BackupService(defaults: defaults, backupData: { _ in + let snapshot = try await privateService.backupSnapshot(sdkService: sdkService, hasStoredIdentity: { true }) + return Data((snapshot.state ?? "null").utf8) + }, uploadBackup: { _, data in + uploads += 1 + remote = data + }) + await backup.triggerBackup(category: .wallet) + XCTAssertEqual(remote, Data("complete-wallet".utf8)) + XCTAssertEqual(uploads, 0) + XCTAssertTrue(backup.getBackupStatus(category: .wallet).isRequired) + XCTAssertEqual(sdk.exportCount, 0) + + sdk.publicKey = "restored-identity" + await backup.triggerBackup(category: .wallet) + XCTAssertEqual(uploads, 1) + XCTAssertTrue(String(decoding: remote, as: UTF8.self).contains("fresh-sdk-backup")) + XCTAssertFalse(backup.getBackupStatus(category: .wallet).isRequired) + backup.setWiping(true) + await backup.stopObservingBackups() + } + + func testNoIdentityCanProduceEmptyPrivateBackupButUnreadableIdentityCannot() async throws { + let sdk = BackupIdentitySdk(noPointer: .init()) + let sdkService = PaykitSdkService(sdkFactory: { sdk }) + let service = PrivatePaykitService() + let empty = try await service.backupSnapshot(sdkService: sdkService, hasStoredIdentity: { false }) + XCTAssertNil(empty.state) + do { + _ = try await service.backupSnapshot(sdkService: sdkService, hasStoredIdentity: { + throw PubkyServiceError.sessionNotActive + }) + XCTFail("Unreadable identity must not become an empty backup") + } catch PubkyServiceError.sessionNotActive {} + XCTAssertEqual(sdk.exportCount, 0) + } + + @MainActor + func testMalformedStoredCredentialsCannotProduceIdentityFreeBackup() async throws { + let keys: [KeychainEntryType] = [.paykitSession, .pubkySecretKey] + let savedValues = try keys.map { try Keychain.load(key: $0) } + let savedReference = AdoptedPubkyReference.current + addTeardownBlock { + AdoptedPubkyReference.current = savedReference + for (key, data) in zip(keys, savedValues) { + if let data { + try Keychain.upsert(key: key, data: data) + } else { + try Keychain.delete(key: key) + } + } + } + AdoptedPubkyReference.current = nil + for key in keys { + try Keychain.delete(key: key) + } + let sdk = BackupIdentitySdk(noPointer: .init()) + let sdkService = PaykitSdkService(sdkFactory: { sdk }) + let service = PrivatePaykitService() + for key in keys { + try Keychain.upsert(key: key, data: Data([0xFF])) + do { + _ = try await service.backupSnapshot(sdkService: sdkService) + XCTFail("Malformed stored credential must prevent an identity-free backup: \(key)") + } catch PubkyServiceError.sessionNotActive {} + try Keychain.delete(key: key) + } + XCTAssertEqual(sdk.exportCount, 0) + let empty = try await service.backupSnapshot(sdkService: sdkService) + XCTAssertNil(empty.state) + } + override func setUp() { super.setUp() // Constructing `PrivatePaykitService` and mutating it writes the real cache state, injecting @@ -3167,3 +3249,25 @@ private extension PrivatePaykitService { invalidateContactPreparation() } } + +private final class BackupIdentitySdk: PaykitSdk, @unchecked Sendable { + var publicKey: String? + var exportCount = 0 + + override func identityStatus() async throws -> IdentityStatus? { + IdentityStatus(publicKey: publicKey, capability: .privateLinkCapable) + } + + override func initialize() async throws -> IdentityStatus { + IdentityStatus(publicKey: publicKey, capability: .privateLinkCapable) + } + + override func exportBackupString() async throws -> String { + exportCount += 1 + return "fresh-sdk-backup" + } + + override func observedBackupStateRevision() throws -> ObservedBackupStateRevision? { + nil + } +} diff --git a/BitkitTests/PubkyProfileManagerTests.swift b/BitkitTests/PubkyProfileManagerTests.swift index 91465c8950..8a021497b5 100644 --- a/BitkitTests/PubkyProfileManagerTests.swift +++ b/BitkitTests/PubkyProfileManagerTests.swift @@ -1009,6 +1009,112 @@ final class PubkyProfileManagerTests: XCTestCase { XCTAssertTrue(manager.isProfileSetupPending) } + @MainActor + func testScheduledInitializationReturnsWhilePendingAndSharesAwaitedRecovery() async { + let manager = RecoveryProfileManager() + manager.publicKey = "previous-identity" + manager.authState = .authenticated + let started = expectation(description: "retained initialization started") + let (stream, release) = AsyncStream.makeStream() + defer { release.finish() } + manager.scheduleInitializationAfterRestore { + started.fulfill() + for await _ in stream {} + return .restored(publicKey: "restored-identity") + } + XCTAssertTrue(manager.isRestoringSession) + XCTAssertNil(manager.currentSession) + XCTAssertNil(manager.automaticPaykitSession) + XCTAssertEqual(manager.authState, .idle) + await fulfillment(of: [started], timeout: 2) + manager.scheduleInitializationAfterRestore { + XCTFail("Overlapping scheduling must share the retained operation") + return .noSession + } + let waiting = Task { + await manager.initialize { + XCTFail("Awaited initialization must share the retained operation") + return .noSession + } + } + await Task.yield() + release.finish() + await waiting.value + XCTAssertEqual(manager.publicKey, "restored-identity") + XCTAssertFalse(manager.isRestoringSession) + } + + @MainActor + func testScheduledInitializationCannotApplyAfterIdentityReplacement() async throws { + let manager = RecoveryProfileManager() + let started = expectation(description: "scheduled initialization started") + let (stream, release) = AsyncStream.makeStream() + defer { release.finish() } + manager.scheduleInitializationAfterRestore { + started.fulfill() + for await _ in stream {} + return .restored(publicKey: "old-identity") + } + await fulfillment(of: [started], timeout: 2) + let completion = Task { await manager.initialize { .noSession } } + try await PubkyProfileManager.restoreSessionBackupState( + nil, + deleteKeychainValue: { _ in }, + removeOwnSharedRecords: {}, + forgetSessionAccess: { + release.finish() + await completion.value + } + ) + XCTAssertNil(manager.currentSession) + XCTAssertEqual(manager.authState, .idle) + XCTAssertFalse(manager.isRestoringSession) + } + + @MainActor + func testRestoreSchedulingWaitsForStaleInitializationThenActivatesCurrentCredentialsOnce() async throws { + let manager = RecoveryProfileManager() + let oldStarted = expectation(description: "old initialization started") + let newStarted = expectation(description: "current credentials activated") + let (oldStream, releaseOld) = AsyncStream.makeStream() + defer { releaseOld.finish() } + let old = Task { + await manager.initialize { + oldStarted.fulfill() + for await _ in oldStream {} + return .restored(publicKey: "old-identity") + } + } + await fulfillment(of: [oldStarted], timeout: 2) + try await PubkyProfileManager.restoreSessionBackupState( + nil, + deleteKeychainValue: { _ in }, + removeOwnSharedRecords: {}, + forgetSessionAccess: {} + ) + let (newStream, releaseNew) = AsyncStream.makeStream() + defer { releaseNew.finish() } + manager.scheduleInitializationAfterRestore { + newStarted.fulfill() + for await _ in newStream {} + return .restored(publicKey: "new-identity") + } + XCTAssertNil(manager.currentSession) + releaseOld.finish() + await old.value + await fulfillment(of: [newStarted], timeout: 2) + let waiting = Task { + await manager.initialize { + XCTFail("Current activation must be shared") + return .noSession + } + } + await Task.yield() + releaseNew.finish() + await waiting.value + XCTAssertEqual(manager.publicKey, "new-identity") + } + @MainActor func testRecoveryWaitsForStartupAndCoalescesConnectivityEvents() async { let manager = RecoveryProfileManager() diff --git a/changelog.d/next/restore-identity.fixed.md b/changelog.d/next/restore-identity.fixed.md new file mode 100644 index 0000000000..7d934b9487 --- /dev/null +++ b/changelog.d/next/restore-identity.fixed.md @@ -0,0 +1 @@ +Wallet restore finishes without waiting for optional profile refresh, while incomplete identity data cannot replace complete backups. diff --git a/journeys/wallet/restore-during-identity-outage.xml b/journeys/wallet/restore-during-identity-outage.xml new file mode 100644 index 0000000000..fcaad5e534 --- /dev/null +++ b/journeys/wallet/restore-during-identity-outage.xml @@ -0,0 +1,18 @@ + + + Use a disposable test-network wallet with a complete VSS backup and a saved Pubky identity. + Required wallet, private reservation and USDT recovery imports must succeed before the injected + delay starts. Delay only final identity activation or subsequent profile/contact reads. + Keep metadata credential replacement and required restore imports available. These complete-app + fault controls are not currently provisioned; component test results are separate evidence. + Never use live funds or reset an existing wallet. + + + Restore the complete backup and hold final identity activation; verify ordinary wallet access resumes after required recovery completes, without reporting Paykit authenticated or payment-ready + Trigger a full backup while the saved identity cannot be exported; verify failure retains the previous complete WALLET record and required pending backup work + Close the restore screen, release the identity fault and verify retained work completes and a fresh complete backup succeeds once + Repeat with delayed profile/contact enrichment, then replace or remove the identity; verify late results cannot republish the old identity or overwrite current profile data + Restart during the outage; verify saved credentials resume recovery without duplicating a payment or contact mutation + Fail a required wallet or USDT restore instead; verify spending and address allocation remain gated and retry resumes the same required recovery + + From ec20b26434979c10b5805222a2e8adcc88fe1978 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 00:55:57 +0200 Subject: [PATCH 02/45] docs: associate restore note with PR 1121 --- changelog.d/next/{restore-identity.fixed.md => 1121.fixed.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changelog.d/next/{restore-identity.fixed.md => 1121.fixed.md} (100%) diff --git a/changelog.d/next/restore-identity.fixed.md b/changelog.d/next/1121.fixed.md similarity index 100% rename from changelog.d/next/restore-identity.fixed.md rename to changelog.d/next/1121.fixed.md From 0dc56a0735fc597c967d69a435d2997f2ce9b03e Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 01:16:26 +0200 Subject: [PATCH 03/45] fix: stop automatic profile deletion replay --- Bitkit/Managers/PubkyProfileManager.swift | 52 ---------------- Bitkit/Views/Profile/EditProfileView.swift | 29 +++------ BitkitTests/PubkyProfileManagerTests.swift | 59 ------------------- .../next/profile-delete-retry.fixed.md | 1 + .../delete-profile-uncertain-response.xml | 17 ++++++ 5 files changed, 25 insertions(+), 133 deletions(-) create mode 100644 changelog.d/next/profile-delete-retry.fixed.md create mode 100644 journeys/profile/delete-profile-uncertain-response.xml diff --git a/Bitkit/Managers/PubkyProfileManager.swift b/Bitkit/Managers/PubkyProfileManager.swift index d29dd6b1e0..5591d441a0 100644 --- a/Bitkit/Managers/PubkyProfileManager.swift +++ b/Bitkit/Managers/PubkyProfileManager.swift @@ -1597,14 +1597,6 @@ class PubkyProfileManager: ObservableObject { } } - func refreshSessionIfPossible(after error: Error) async -> Bool { - await Self.refreshSessionIfPossible( - after: error, - loadKeychainString: { try Keychain.loadString(key: $0) }, - signInWithSecretKey: { try await PubkyService.signIn(secretKeyHex: $0) } - ) - } - // MARK: - Cached Profile Metadata private static let cachedNameKey = "pubky_profile_name" @@ -1982,50 +1974,6 @@ class PubkyProfileManager: ObservableObject { return false } - nonisolated static func isSessionRefreshableError(_ error: Error) -> Bool { - let errorText = [ - (error as? AppError)?.debugMessage, - error.localizedDescription, - String(describing: error), - ] - .compactMap { $0?.lowercased() } - - return errorText.contains { - ($0.contains("authfailed") || $0.contains("authentication failed") || $0.contains("sessionnotactive")) - || ($0.contains("transport error") && $0.contains("/session")) - } - } - - nonisolated static func refreshSessionIfPossible( - after error: Error, - loadKeychainString: (KeychainEntryType) throws -> String? = { - try Keychain.loadString(key: $0) - }, - signInWithSecretKey: (String) async throws -> String, - publicKeyFromSecretKey: (String) throws -> String = { - try PubkyProfileManager.publicKeyFromSecretKey($0) - } - ) async -> Bool { - guard isSessionRefreshableError(error) else { - return false - } - - guard let secretKeyHex = activeSecretKeyHex(loadKeychainString: loadKeychainString) else { - Logger.warn("Cannot refresh pubky session without a secret key", context: "PubkyProfileManager") - return false - } - - do { - _ = try await signInWithSecretKey(secretKeyHex) - _ = try publicKeyFromSecretKey(secretKeyHex) - Logger.info("Refreshed pubky session from local secret key", context: "PubkyProfileManager") - return true - } catch { - Logger.warn("Failed to refresh pubky session: \(error)", context: "PubkyProfileManager") - return false - } - } - nonisolated static func resolveSessionInitialization( savedSessionSecret: String?, storedSecretKeyHex: String?, diff --git a/Bitkit/Views/Profile/EditProfileView.swift b/Bitkit/Views/Profile/EditProfileView.swift index 183393e119..e9dbe433eb 100644 --- a/Bitkit/Views/Profile/EditProfileView.swift +++ b/Bitkit/Views/Profile/EditProfileView.swift @@ -158,33 +158,18 @@ struct EditProfileView: View { defer { isDeleting = false } do { try await pubkyProfile.performProfileDeletion { - await deleteProfileWithSessionRetry(session: session) - } - } catch { - guard !Task.isCancelled, pubkyProfile.currentSession == session else { return } - showDeleteFailureOptions = true - } - } - - private func deleteProfileWithSessionRetry(session: PubkyProfileManager.SignedInSession) async { - do { - try await performDeleteProfile(session: session) - } catch { - guard !Task.isCancelled, pubkyProfile.publicKey == session.publicKey else { return } - if pubkyProfile.currentSession == session, await pubkyProfile.refreshSessionIfPossible(after: error) { do { try await performDeleteProfile(session: session) - return } catch { - Logger.error("Failed to delete profile after session refresh: \(error)", context: "EditProfileView") + guard !Task.isCancelled, pubkyProfile.publicKey == session.publicKey else { return } + Logger.error("Failed to delete profile: \(error)", context: "EditProfileView") + showDeleteFailureOptions = true } - } else { - Logger.error("Failed to delete profile: \(error)", context: "EditProfileView") - } - - if !Task.isCancelled, pubkyProfile.publicKey == session.publicKey { - showDeleteFailureOptions = true } + } catch { + guard !Task.isCancelled, pubkyProfile.currentSession == session else { return } + Logger.error("Failed to delete profile: \(error)", context: "EditProfileView") + showDeleteFailureOptions = true } } diff --git a/BitkitTests/PubkyProfileManagerTests.swift b/BitkitTests/PubkyProfileManagerTests.swift index 8a021497b5..14f4dfe654 100644 --- a/BitkitTests/PubkyProfileManagerTests.swift +++ b/BitkitTests/PubkyProfileManagerTests.swift @@ -3459,65 +3459,6 @@ final class PubkyProfileManagerTests: XCTestCase { XCTAssertFalse(PubkyProfileManager.isMissingBitkitProfileStorageError(error)) } - func testIsSessionRefreshableErrorRecognizesSessionTransportFailure() { - let error = AppError( - message: "App Error", - debugMessage: #"BitkitCore.PubkyError.AuthFailed(reason: "Request failed: HTTP transport error: error sending request for url (https://example.com/session)")"# - ) - - XCTAssertTrue(PubkyProfileManager.isSessionRefreshableError(error)) - } - - func testRefreshSessionIfPossibleRefreshesSessionFromLocalSecret() async { - let error = AppError( - message: "App Error", - debugMessage: #"BitkitCore.PubkyError.AuthFailed(reason: "Request failed: HTTP transport error: error sending request for url (https://example.com/session)")"# - ) - let refreshed = await PubkyProfileManager.refreshSessionIfPossible( - after: error, - loadKeychainString: { key in - switch key { - case .pubkySecretKey: - return "local-secret" - default: - return nil - } - }, - signInWithSecretKey: { secretKey in - XCTAssertEqual(secretKey, "local-secret") - return "fresh-session" - }, - publicKeyFromSecretKey: { secretKey in - XCTAssertEqual(secretKey, "local-secret") - return "pubky_fresh" - } - ) - - XCTAssertTrue(refreshed) - } - - func testRefreshSessionIfPossibleReturnsFalseWithoutLocalSecret() async { - let error = AppError( - message: "App Error", - debugMessage: #"BitkitCore.PubkyError.AuthFailed(reason: "Request failed: HTTP transport error: error sending request for url (https://example.com/session)")"# - ) - - let refreshed = await PubkyProfileManager.refreshSessionIfPossible( - after: error, - loadKeychainString: { _ in nil }, - signInWithSecretKey: { _ in - XCTFail("Expected refresh to stop when no local secret key exists") - return "fresh-session" - }, - publicKeyFromSecretKey: { _ in - XCTFail("No public key should be derived without a local secret") - return "pubky_unused" - } - ) - - XCTAssertFalse(refreshed) - } - // MARK: - Session backup state func testSnapshotSessionBackupStatePrefersLocalSeedOverSessionSecret() throws { diff --git a/changelog.d/next/profile-delete-retry.fixed.md b/changelog.d/next/profile-delete-retry.fixed.md new file mode 100644 index 0000000000..fb97b9ecd4 --- /dev/null +++ b/changelog.d/next/profile-delete-retry.fixed.md @@ -0,0 +1 @@ +Prevent uncertain profile deletion failures from automatically repeating contact cleanup and deletion. diff --git a/journeys/profile/delete-profile-uncertain-response.xml b/journeys/profile/delete-profile-uncertain-response.xml new file mode 100644 index 0000000000..fe825c36ff --- /dev/null +++ b/journeys/profile/delete-profile-uncertain-response.xml @@ -0,0 +1,17 @@ + + + Requires a disposable test identity and a controlled homeserver proxy; never use a personal profile. + Configure the proxy to accept one profile deletion but lose its acknowledgement, retaining a redacted + request counter. This is a fault-injection fixture requirement, not evidence that this journey has run. + Normal SDK recovery may retry an individual request only after a confirmed authentication rejection; + the app must not restart contact cleanup and profile deletion because a request has an uncertain outcome. + + + Open Edit Profile and confirm deletion + Drop the acknowledgement after the server accepts the profile deletion + Verify failure options are shown and no success notification or onboarding navigation occurs + Wait through the network timeout and verify the app starts no second contact cleanup, profile deletion or sign-in + Cancel the failure dialog and verify no mutation is retried + Restart the app without choosing Retry and verify it does not automatically repeat the deletion + + From 1b8a6db827d0967cac744dc6f41d38283ee755db Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 01:17:16 +0200 Subject: [PATCH 04/45] docs: associate deletion fix with PR 1122 --- changelog.d/next/{profile-delete-retry.fixed.md => 1122.fixed.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changelog.d/next/{profile-delete-retry.fixed.md => 1122.fixed.md} (100%) diff --git a/changelog.d/next/profile-delete-retry.fixed.md b/changelog.d/next/1122.fixed.md similarity index 100% rename from changelog.d/next/profile-delete-retry.fixed.md rename to changelog.d/next/1122.fixed.md From f204e05eb41ed4f34e4e08f7138cc600b296d45e Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 02:33:24 +0100 Subject: [PATCH 05/45] fix: serialize backup observation lifecycle --- Bitkit/Services/BackupService.swift | 236 ++++++++++-------- BitkitTests/BackupServiceTests.swift | 167 +++++++++++++ changelog.d/next/1123.fixed.md | 1 + .../wallet-snapshot-consistency.md | 22 ++ 4 files changed, 320 insertions(+), 106 deletions(-) create mode 100644 changelog.d/next/1123.fixed.md diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 94fe0d95a4..982b003a65 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -113,9 +113,12 @@ class BackupService { @MainActor weak var usdtWallet: UsdtWalletManager? private var backupJobs: [BackupCategory: Task] = [:] private var runningBackupTasks: [BackupCategory: Task] = [:] - private var cancellables = Set() - private var periodicCheckTask: Task? - private var isObserving = false + @MainActor private var cancellables = Set() + @MainActor private var periodicCheckTask: Task? + @MainActor private var observationTask: Task? + @MainActor private var isObserving = false + private var schedulingGeneration: UInt64 = 0 + private var isStoppingBackups = false private var isRestoring = false private var isWiping = false private var lastNotificationTime: UInt64 = 0 @@ -200,18 +203,13 @@ class BackupService { } } + @MainActor func startObservingBackups() { - guard !shouldSkipBackup() else { return } - - Task { - let shouldStart = try? await ServiceQueue.background(.backup) { - guard !self.isObserving else { return false } - self.isObserving = true - return true - } - - guard shouldStart == true else { return } - + let previous = observationTask + observationTask = Task { + await previous?.value + guard !shouldSkipBackup(), !isObserving else { return } + isObserving = true Logger.debug("Start observing backup statuses and data store changes", context: "BackupService") startBackupStatusObservers() startDataStoreListeners() @@ -219,25 +217,43 @@ class BackupService { } } + @MainActor func stopObservingBackups() async { - let shouldStop = try? await ServiceQueue.background(.backup) { - let wasObserving = self.isObserving - self.isObserving = false - - self.backupJobs.values.forEach { $0.cancel() } - self.backupJobs.removeAll() - self.runningBackupTasks.values.forEach { $0.cancel() } - self.runningBackupTasks.removeAll() - self.periodicCheckTask?.cancel() - self.periodicCheckTask = nil - return wasObserving + let previous = observationTask + let stopping = Task { + await previous?.value + isObserving = false + cancellables.removeAll() + periodicCheckTask?.cancel() + periodicCheckTask = nil + + let tasks = try? await ServiceQueue.background(.backup) { + self.stateQueue.sync { self.schedulingGeneration &+= 1 } + self.isStoppingBackups = true + let scheduled = Array(self.backupJobs.values) + let running = Array(self.runningBackupTasks.values) + scheduled.forEach { $0.cancel() } + running.forEach { $0.cancel() } + return (scheduled, running) + } + // Cleanup uses the backup queue too, so drain outside it before a replacement starts. + if let (scheduled, running) = tasks { + for task in scheduled { + await task.value + } + for task in running { + _ = await task.value + } + } + await walletBackupWriter.waitUntilIdle() + await usdtBackupWriter.waitUntilIdle() + try? await ServiceQueue.background(.backup) { + self.isStoppingBackups = false + } + Logger.debug("Stopped observing backup statuses and data store changes", context: "BackupService") } - - await walletBackupWriter.waitUntilIdle() - await usdtBackupWriter.waitUntilIdle() - guard shouldStop == true else { return } - cancellables.removeAll() - Logger.debug("Stopped observing backup statuses and data store changes", context: "BackupService") + observationTask = stopping + await stopping.value } @discardableResult @@ -246,19 +262,32 @@ class BackupService { } private func triggerBackup(category: BackupCategory, isScheduled: Bool) async -> BackupOutcome { - let backupTask = try? await ServiceQueue.background(.backup) { [self] () -> Task? in - guard runningBackupTasks[category] == nil else { return nil } - let backupTask = Task { await self.runBackup(category: category, isScheduled: isScheduled) } - runningBackupTasks[category] = backupTask - return backupTask + while !Task.isCancelled { + let admission = try? await ServiceQueue.background(.backup) { [self] () -> (Task?, Bool) in + guard !isStoppingBackups else { return (nil, true) } + guard runningBackupTasks[category] == nil else { return (nil, false) } + let task = Task { await self.runBackup(category: category, isScheduled: isScheduled) } + runningBackupTasks[category] = task + return (task, false) + } + guard let (backupTask, isStopping) = admission else { return .failed } + if isStopping, !isScheduled { + await waitForObservationTransition() + continue + } + guard let backupTask else { return .busy } + return await withTaskCancellationHandler { + await backupTask.value + } onCancel: { + backupTask.cancel() + } } + return .failed + } - guard let backupTask else { return .busy } - return await withTaskCancellationHandler { - await backupTask.value - } onCancel: { - backupTask.cancel() - } + @MainActor + private func waitForObservationTransition() async { + await observationTask?.value } private func runBackup(category: BackupCategory, isScheduled: Bool) async -> BackupOutcome { @@ -618,6 +647,7 @@ class BackupService { // MARK: - Private Methods + @MainActor private func startBackupStatusObservers() { for category in BackupCategory.allCases { let categoryPublisher = backupStatusesPublisher @@ -635,8 +665,9 @@ class BackupService { .sink { [weak self] status in guard let self, !self.shouldSkipBackup(category: category) else { return } if status.isRequired && !status.running { + let generation = currentSchedulingGeneration Task { - await self.scheduleBackup(category: category) + await self.scheduleBackup(category: category, generation: generation) } } } @@ -646,27 +677,25 @@ class BackupService { Logger.debug("Started \(BackupCategory.allCases.count) backup status observers", context: "BackupService") } + @MainActor private func startDataStoreListeners() { - Task { @MainActor [weak self] in - guard let self else { return } - // SETTINGS - SettingsViewModel.shared.settingsPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) - .sink { [weak self] _ in - guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .settings) - } - .store(in: &cancellables) + // SETTINGS + SettingsViewModel.shared.settingsPublisher + .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) + .sink { [weak self] _ in + guard let self, !self.shouldSkipBackup() else { return } + markBackupRequired(category: .settings) + } + .store(in: &cancellables) - // WIDGETS - SettingsViewModel.shared.widgetsPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) - .sink { [weak self] _ in - guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .widgets) - } - .store(in: &cancellables) - } + // WIDGETS + SettingsViewModel.shared.widgetsPublisher + .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) + .sink { [weak self] _ in + guard let self, !self.shouldSkipBackup() else { return } + markBackupRequired(category: .widgets) + } + .store(in: &cancellables) // Record requirements synchronously; the scheduled upload already has a debounce. WalletBackupChangeTracker.localChanges @@ -714,16 +743,13 @@ class BackupService { .store(in: &cancellables) // APP STATE (UserDefaults changes, etc.) - Task { @MainActor [weak self] in - guard let self else { return } - SettingsViewModel.shared.appStatePublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) - .sink { [weak self] _ in - guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .metadata) - } - .store(in: &cancellables) - } + SettingsViewModel.shared.appStatePublisher + .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) + .sink { [weak self] _ in + guard let self, !self.shouldSkipBackup() else { return } + markBackupRequired(category: .metadata) + } + .store(in: &cancellables) // BLOCKTANK CoreService.shared.blocktank.stateChangedPublisher @@ -752,16 +778,13 @@ class BackupService { Logger.debug("Started data store listeners", context: "BackupService") } + @MainActor private func startPeriodicBackupFailureCheck() { - Task { - try? await ServiceQueue.background(.backup) { - self.periodicCheckTask = Task { - while !Task.isCancelled { - try? await Task.sleep(nanoseconds: UInt64(Self.backupFailureCheckInterval * 1_000_000_000)) - guard !Task.isCancelled else { break } - self.checkForFailedBackups() - } - } + periodicCheckTask = Task { + while !Task.isCancelled { + try? await Task.sleep(nanoseconds: UInt64(Self.backupFailureCheckInterval * 1_000_000_000)) + guard !Task.isCancelled else { break } + checkForFailedBackups() } } } @@ -788,42 +811,42 @@ class BackupService { return BackupItemStatus( synced: status.synced, required: max(status.required, status.synced + 1, UInt64(Date().timeIntervalSince1970)), - running: schedule || status.running + running: status.running ) } guard schedule else { return } - Task { - let status = getBackupStatus(category: category) - if status.isRequired && !shouldSkipBackup(category: category) { - await scheduleBackup(category: category) - } else if !status.isRequired { + let generation = currentSchedulingGeneration + Task { await scheduleBackup(category: category, generation: generation) } + } + + private var currentSchedulingGeneration: UInt64 { + stateQueue.sync { schedulingGeneration } + } + + private func scheduleBackup(category: BackupCategory, generation: UInt64) async { + while !Task.isCancelled { + let waitingForStop = try? await ServiceQueue.background(.backup) { [self] in + guard generation == currentSchedulingGeneration else { return false } + guard !isStoppingBackups else { return true } + guard backupJobs[category] == nil, getBackupStatus(category: category).isRequired, + !shouldSkipBackup(category: category) else { return false } updateBackupStatus(category: category) { status in BackupItemStatus( synced: status.synced, required: status.required, - running: false + running: true ) } + backupJobs[category] = Task { await self.runScheduledBackup(category: category, generation: generation) } + return false } + guard waitingForStop == true else { return } + await waitForObservationTransition() } } - private func scheduleBackup(category: BackupCategory) async { - try? await ServiceQueue.background(.backup) { [self] in - guard backupJobs[category] == nil else { return } - updateBackupStatus(category: category) { status in - BackupItemStatus( - synced: status.synced, - required: status.required, - running: true - ) - } - backupJobs[category] = Task { await self.runScheduledBackup(category: category) } - } - } - - private func runScheduledBackup(category: BackupCategory) async { + private func runScheduledBackup(category: BackupCategory, generation: UInt64) async { var outcome = BackupOutcome.failed var retryDelay: UInt64 = 10_000_000_000 while !Task.isCancelled { @@ -845,14 +868,14 @@ class BackupService { break } } - _ = try? await ServiceQueue.background(.backup) { self.backupJobs.removeValue(forKey: category) } updateBackupStatus(category: category) { status in BackupItemStatus(synced: status.synced, required: status.required, running: false) } + _ = try? await ServiceQueue.background(.backup) { self.backupJobs.removeValue(forKey: category) } if outcome.canRetryPendingBackup, !Task.isCancelled, getBackupStatus(category: category).isRequired, !shouldSkipBackup(category: category) { - await scheduleBackup(category: category) + await scheduleBackup(category: category, generation: generation) } } @@ -936,6 +959,7 @@ class BackupService { } func scheduleFullBackup() async { + let generation = currentSchedulingGeneration let currentTime = UInt64(Date().timeIntervalSince1970) for category in BackupCategory.allCases { updateBackupStatus(category: category) { status in @@ -951,7 +975,7 @@ class BackupService { for category in BackupCategory.allCases { let status = getBackupStatus(category: category) if status.isRequired && !status.running { - await scheduleBackup(category: category) + await scheduleBackup(category: category, generation: generation) } } } diff --git a/BitkitTests/BackupServiceTests.swift b/BitkitTests/BackupServiceTests.swift index a0cc74b0fc..efb5c25fe5 100644 --- a/BitkitTests/BackupServiceTests.swift +++ b/BitkitTests/BackupServiceTests.swift @@ -169,6 +169,149 @@ final class BackupServiceTests: XCTestCase { } } + func testStopDrainsCancelledWorkBeforeManualBackupAndRestart() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let started = expectation(description: "Scheduled delay started") + let cancelled = expectation(description: "Scheduled delay cancelled") + let uploadedEarly = expectation(description: "Manual upload must wait for cleanup") + uploadedEarly.isInverted = true + let gate = BackupDelayGate() + let recorder = BackupRecorder() + let service = BackupService(defaults: defaults, backupData: { _ in Data("complete".utf8) }, uploadBackup: { key, data in + await recorder.recordUpload(key: key, data: data) + if await gate.isHeld { + uploadedEarly.fulfill() + } + }, waitForBackupDelay: { + try await withTaskCancellationHandler { + await gate.wait(started: started) + try Task.checkCancellation() + } onCancel: { cancelled.fulfill() } + }) + service.markBackupRequired(category: .wallet) + await fulfillment(of: [started], timeout: 2) + let stop = Task { + await service.stopObservingBackups() + await gate.recordStop() + } + await fulfillment(of: [cancelled], timeout: 2) + let deferred = expectation(description: "New USDT request survives the drain") + let deferredSubscription = service.backupStatusesPublisher + .filter { $0[.usdt].map { !$0.isRequired && !$0.running } == true } + .first().sink { _ in deferred.fulfill() } + service.markBackupRequired(category: .usdt) + let manual = Task { await service.triggerBackup(category: .metadata) } + await fulfillment(of: [uploadedEarly], timeout: 0.1) + let stoppedBeforeDrain = await gate.didStop + XCTAssertFalse(stoppedBeforeDrain) + await gate.release() + await stop.value + let outcome = await manual.value + await fulfillment(of: [deferred], timeout: 2) + deferredSubscription.cancel() + XCTAssertEqual(outcome, .completed) + XCTAssertTrue(service.getBackupStatus(category: .wallet).isRequired) + XCTAssertFalse(service.getBackupStatus(category: .wallet).running) + let uploads = await recorder.uploads + XCTAssertEqual(Set(uploads.map(\.key)), [BackupCategory.metadata.rawValue, BackupCategory.usdt.rawValue]) + XCTAssertEqual(uploads.count, 2) + await service.stopObservingBackups() + + let restarted = BackupService(defaults: defaults, backupData: { _ in Data("latest".utf8) }, + uploadBackup: { _, _ in }, waitForBackupDelay: {}) + let completed = expectation(description: "Restart uploads retained work") + let subscription = restarted.backupStatusesPublisher + .filter { $0[.wallet].map { !$0.isRequired && !$0.running } == true } + .first().sink { _ in completed.fulfill() } + restarted.startObservingBackups() + await fulfillment(of: [completed], timeout: 2) + subscription.cancel() + await restarted.stopObservingBackups() + XCTAssertFalse(restarted.getBackupStatus(category: .wallet).isRequired) + } + + func testStopWaitsForFinalScheduledStatusWrite() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let delayStarted = expectation(description: "Scheduled backup entered delay") + let cleanupStarted = expectation(description: "Final status write entered") + let stoppedEarly = expectation(description: "Stop must wait for final status write") + stoppedEarly.isInverted = true + let delayGate = BackupDelayGate() + let cleanupGate = DispatchSemaphore(value: 0) + let stopGate = BackupDelayGate() + let service = BackupService(defaults: defaults, backupData: { _ in Data() }, + uploadBackup: { _, _ in XCTFail("Wiping must prevent upload") }, + waitForBackupDelay: { await delayGate.wait(started: delayStarted) }) + service.markBackupRequired(category: .wallet) + await fulfillment(of: [delayStarted], timeout: 2) + let subscription = service.backupStatusesPublisher + .filter { $0[.wallet]?.running == false } + .first().sink { _ in + cleanupStarted.fulfill() + cleanupGate.wait() + } + service.setWiping(true) + await delayGate.release() + await fulfillment(of: [cleanupStarted], timeout: 2) + let stop = Task { + await service.stopObservingBackups() + if await stopGate.isHeld { + stoppedEarly.fulfill() + } + } + await fulfillment(of: [stoppedEarly], timeout: 0.1) + await stopGate.release() + cleanupGate.signal() + await stop.value + subscription.cancel() + XCTAssertTrue(service.getBackupStatus(category: .wallet).isRequired) + XCTAssertFalse(service.getBackupStatus(category: .wallet).running) + } + + func testImmediateStartStopDoesNotObserveLaterWalletChanges() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let service = BackupService(defaults: defaults, backupData: { _ in Data("complete".utf8) }, + uploadBackup: { _, _ in }, waitForBackupDelay: {}) + for _ in 0 ..< 25 { + service.startObservingBackups() + await service.stopObservingBackups() + let stoppedStatus = service.getBackupStatus(category: .wallet) + try Bitkit.WatchOnlyAccountStore.save([], defaults: defaults) + XCTAssertEqual(service.getBackupStatus(category: .wallet), stoppedStatus) + } + } + + func testExplicitUsdtBackupRetriesWhileObserversRemainStopped() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let completed = expectation(description: "USDT retry acknowledged without node observation") + var captures = 0 + let service = BackupService(defaults: defaults, backupData: { _ in + captures += 1 + if captures == 1 { + throw PaykitError.SharedStateBusy(code: "shared_state_busy", context: "temporarily unavailable") + } + return Data("signed-recovery".utf8) + }, uploadBackup: { _, _ in }, waitForBackupDelay: {}, waitForTemporaryFailureDelay: { _ in }) + await service.stopObservingBackups() + let subscription = service.backupStatusesPublisher + .filter { $0[.usdt].map { !$0.isRequired && !$0.running } == true } + .first().sink { _ in completed.fulfill() } + service.markBackupRequired(category: .usdt) + await fulfillment(of: [completed], timeout: 2) + subscription.cancel() + await service.stopObservingBackups() + XCTAssertEqual(captures, 2) + XCTAssertFalse(service.getBackupStatus(category: .usdt).isRequired) + } + func testTemporaryFailureRemainsPendingAcrossServiceRestart() async throws { let suite = "BackupServiceTests.\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) @@ -453,3 +596,27 @@ private final class WalletBackupSdk: PaykitSdk, @unchecked Sendable { return "wallet-backup" } } + +private actor BackupDelayGate { + private(set) var isHeld = true + private(set) var didStop = false + private var continuation: CheckedContinuation? + + func wait(started: XCTestExpectation) async { + guard isHeld else { return } + await withCheckedContinuation { continuation in + self.continuation = continuation + started.fulfill() + } + } + + func recordStop() { + didStop = true + } + + func release() { + isHeld = false + continuation?.resume() + continuation = nil + } +} diff --git a/changelog.d/next/1123.fixed.md b/changelog.d/next/1123.fixed.md new file mode 100644 index 0000000000..3cba6c7e79 --- /dev/null +++ b/changelog.d/next/1123.fixed.md @@ -0,0 +1 @@ +Fixed a crash when backup observation stops and ensured pending backups resume safely after restart. diff --git a/journeys/backup-restore/wallet-snapshot-consistency.md b/journeys/backup-restore/wallet-snapshot-consistency.md index 0c5e7acfb5..e79d4e3233 100644 --- a/journeys/backup-restore/wallet-snapshot-consistency.md +++ b/journeys/backup-restore/wallet-snapshot-consistency.md @@ -34,3 +34,25 @@ mutation. A genuine capture/upload failure must not enter an automatic retry loo Record the tested commit, gate locations, attempts and upload counts, and the restored state. Unit coverage does not establish a device pass or a maximum backup delay during sustained activity. + +## Backup observation shutdown + +The following controls require the same dedicated lifecycle/capture fixture; +these are not ordinary UI journey capabilities. No wallet reset is needed. + +1. Hold a scheduled backup in its cancellable debounce, stop observation, and + request a manual metadata backup while cancellation cleanup remains held. + Verify shutdown and the manual upload both wait for cleanup, including a final + status write held after the delay finishes. Release cleanup; + verify pending wallet work remains required and resumes on observation restart. +2. Request a new USDT recovery backup during cleanup and again after observation + is stopped. Verify both requests can finish without restarting Lightning, and + transient backup failures retain bounded automatic retry. +3. Repeatedly start and immediately stop observation. Change a wallet record only + after stop returns; verify the stopped observer does not schedule an upload or + mutate its saved backup status. Restart observation and verify a single set of + listeners resumes pending work. + +The iOS lifecycle unit tests exercise these component boundaries with injected +capture/upload and delay controls. They do not prove a full device fault journey. +Android's related job-ownership and reset paths require separate validation. From 538f45c7551dddfb96193e0107f9f2a3a01e7166 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 04:28:06 +0100 Subject: [PATCH 06/45] fix: retain backup changes during observation restart --- Bitkit/Services/BackupService.swift | 65 +++++------ BitkitTests/BackupServiceTests.swift | 102 ++++++++++++++++++ .../wallet-snapshot-consistency.md | 7 +- 3 files changed, 143 insertions(+), 31 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 982b003a65..7903e1c8e7 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -206,13 +206,14 @@ class BackupService { @MainActor func startObservingBackups() { let previous = observationTask + let listeners = makeDataStoreListeners() observationTask = Task { await previous?.value guard !shouldSkipBackup(), !isObserving else { return } isObserving = true Logger.debug("Start observing backup statuses and data store changes", context: "BackupService") + cancellables.formUnion(listeners) startBackupStatusObservers() - startDataStoreListeners() startPeriodicBackupFailureCheck() } } @@ -329,7 +330,7 @@ class BackupService { updateBackupStatus(category: category) { status in BackupItemStatus( synced: status.synced, - required: category == .wallet || category == .usdt ? status.required : status.synced, + required: status.required, running: false ) } @@ -678,87 +679,81 @@ class BackupService { } @MainActor - private func startDataStoreListeners() { + private func makeDataStoreListeners() -> Set { + var listeners = Set() // SETTINGS SettingsViewModel.shared.settingsPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) .sink { [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .settings) + markObservedBackupRequired(category: .settings) } - .store(in: &cancellables) + .store(in: &listeners) // WIDGETS SettingsViewModel.shared.widgetsPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) .sink { [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .widgets) + markObservedBackupRequired(category: .widgets) } - .store(in: &cancellables) + .store(in: &listeners) // Record requirements synchronously; the scheduled upload already has a debounce. WalletBackupChangeTracker.localChanges .merge(with: PaykitSdkService.walletBackupDataChangedPublisher) .sink { [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .wallet) + markObservedBackupRequired(category: .wallet) } - .store(in: &cancellables) + .store(in: &listeners) UsdtWalletManager.walletBackupDataChangedPublisher .merge(with: PaykitUsdtPaymentService.walletBackupDataChangedPublisher) .sink { [weak self] _ in guard let self, !self.isWipingOrRestoringUsdt() else { return } - markBackupRequired(category: .usdt) + markObservedBackupRequired(category: .usdt) } - .store(in: &cancellables) + .store(in: &listeners) // ACTIVITIES CoreService.shared.activity.activitiesChangedPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) .sink { [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .activity) + markObservedBackupRequired(category: .activity) } - .store(in: &cancellables) + .store(in: &listeners) // METADATA (from ActivityService) CoreService.shared.activity.metadataChangedPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) .sink { [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .metadata) + markObservedBackupRequired(category: .metadata) } - .store(in: &cancellables) + .store(in: &listeners) // METADATA (hardware wallet names). Scoped to the names alone: the known-device store is also // rewritten by every connect, and reconnect traffic must not re-upload the whole envelope. HwKnownDeviceStorage.namesChangedPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) .sink { [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .metadata) + markObservedBackupRequired(category: .metadata) } - .store(in: &cancellables) + .store(in: &listeners) // APP STATE (UserDefaults changes, etc.) SettingsViewModel.shared.appStatePublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) .sink { [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .metadata) + markObservedBackupRequired(category: .metadata) } - .store(in: &cancellables) + .store(in: &listeners) // BLOCKTANK CoreService.shared.blocktank.stateChangedPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) .sink { [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .blocktank) + markObservedBackupRequired(category: .blocktank) } - .store(in: &cancellables) + .store(in: &listeners) // LIGHTNING SYNC STATUS LightningService.shared.syncStatusChangedPublisher @@ -773,9 +768,19 @@ class BackupService { ) } } - .store(in: &cancellables) + .store(in: &listeners) + + return listeners + } - Logger.debug("Started data store listeners", context: "BackupService") + private func markObservedBackupRequired(category: BackupCategory) { + // Persist notifications during restart without admitting uploads before cleanup finishes. + markBackupRequired(category: category, schedule: false) + Task { @MainActor in + await waitForObservationTransition() + guard isObserving else { return } + await scheduleBackup(category: category, generation: currentSchedulingGeneration) + } } @MainActor diff --git a/BitkitTests/BackupServiceTests.swift b/BitkitTests/BackupServiceTests.swift index efb5c25fe5..76ae93fabb 100644 --- a/BitkitTests/BackupServiceTests.swift +++ b/BitkitTests/BackupServiceTests.swift @@ -232,6 +232,108 @@ final class BackupServiceTests: XCTestCase { XCTAssertFalse(restarted.getBackupStatus(category: .wallet).isRequired) } + func testRestartRecordsWalletChangesWhilePreviousCleanupDrains() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let started = expectation(description: "Old scheduled work started") + let cancelled = expectation(description: "Old work entered cancellation cleanup") + let completed = expectation(description: "Restart uploads the change made during cleanup") + let early = expectation(description: "New upload must wait for old cleanup") + early.isInverted = true + let gate = BackupDelayGate() + let recorder = BackupRecorder() + var state = Data("initial".utf8) + var delays = 0 + let service = BackupService(defaults: defaults, backupData: { _ in state }, uploadBackup: { key, data in + await recorder.recordUpload(key: key, data: data) + if data == Data("updated".utf8), await gate.isHeld { + early.fulfill() + } + }, waitForBackupDelay: { + delays += 1 + guard delays == 1 else { return } + try await withTaskCancellationHandler { + await gate.wait(started: started) + try Task.checkCancellation() + } onCancel: { cancelled.fulfill() } + }) + await service.triggerBackup(category: .wallet) + service.markBackupRequired(category: .settings) + await fulfillment(of: [started], timeout: 2) + let stop = Task { await service.stopObservingBackups() } + await fulfillment(of: [cancelled], timeout: 2) + + service.startObservingBackups() + state = Data("updated".utf8) + try Bitkit.WatchOnlyAccountStore.save([], defaults: defaults) + XCTAssertTrue(service.getBackupStatus(category: .wallet).isRequired) + let beforeDrain = await recorder.uploads + XCTAssertEqual(beforeDrain.map(\.data), [Data("initial".utf8)]) + let subscription = service.backupStatusesPublisher + .filter { $0[.wallet].map { !$0.isRequired && !$0.running } == true } + .first().sink { _ in completed.fulfill() } + await fulfillment(of: [early], timeout: 0.1) + await gate.release() + await stop.value + await fulfillment(of: [completed], timeout: 2) + subscription.cancel() + await service.stopObservingBackups() + let uploads = await recorder.uploads.filter { $0.key == BackupCategory.wallet.rawValue } + XCTAssertEqual(uploads.map(\.data), [Data("initial".utf8), Data("updated".utf8)]) + } + + func testCancelledUploadRetainsNewerSettingsAfterRestart() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let entered = expectation(description: "Settings upload entered") + let gate = BackupDelayGate() + let service = BackupService(defaults: defaults, backupData: { _ in Data("old".utf8) }, uploadBackup: { _, _ in + await gate.wait(started: entered) + try Task.checkCancellation() + }) + let upload = Task { await service.triggerBackup(category: .settings) } + await fulfillment(of: [entered], timeout: 2) + upload.cancel() + service.markBackupRequired(category: .settings, schedule: false) + await gate.release() + let outcome = await upload.value + XCTAssertEqual(outcome, .failed) + XCTAssertTrue(service.getBackupStatus(category: .settings).isRequired) + await service.stopObservingBackups() + + let uploaded = expectation(description: "Restart uploads latest settings") + let restarted = BackupService(defaults: defaults, backupData: { _ in Data("latest".utf8) }, uploadBackup: { key, data in + XCTAssertEqual(key, BackupCategory.settings.rawValue) + XCTAssertEqual(data, Data("latest".utf8)) + uploaded.fulfill() + }, waitForBackupDelay: {}) + restarted.startObservingBackups() + await fulfillment(of: [uploaded], timeout: 2) + await restarted.stopObservingBackups() + } + + func testImmediateStopRetainsReceivedSettingsChange() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let original = SettingsViewModel.shared.swipeBalanceToHide + defer { SettingsViewModel.shared.swipeBalanceToHide = original } + let service = BackupService(defaults: defaults, backupData: { _ in Data() }, uploadBackup: { _, _ in + XCTFail("Immediate stop must prevent upload") + }) + service.startObservingBackups() + let received = expectation(description: "Settings notification received") + let subscription = SettingsViewModel.shared.settingsPublisher.first().sink { _ in received.fulfill() } + SettingsViewModel.shared.swipeBalanceToHide = !original + await fulfillment(of: [received], timeout: 2) + subscription.cancel() + await service.stopObservingBackups() + XCTAssertTrue(service.getBackupStatus(category: .settings).isRequired) + XCTAssertFalse(service.getBackupStatus(category: .settings).running) + } + func testStopWaitsForFinalScheduledStatusWrite() async throws { let suite = "BackupServiceTests.\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) diff --git a/journeys/backup-restore/wallet-snapshot-consistency.md b/journeys/backup-restore/wallet-snapshot-consistency.md index e79d4e3233..767d93452d 100644 --- a/journeys/backup-restore/wallet-snapshot-consistency.md +++ b/journeys/backup-restore/wallet-snapshot-consistency.md @@ -45,13 +45,18 @@ these are not ordinary UI journey capabilities. No wallet reset is needed. Verify shutdown and the manual upload both wait for cleanup, including a final status write held after the delay finishes. Release cleanup; verify pending wallet work remains required and resumes on observation restart. + Change wallet/settings state after requesting restart while cleanup is held; + verify no new upload starts before the drain and the latest state uploads + afterward without another edit. Repeat with a canceled settings upload; its + cleanup must not clear a newer required marker. 2. Request a new USDT recovery backup during cleanup and again after observation is stopped. Verify both requests can finish without restarting Lightning, and transient backup failures retain bounded automatic retry. 3. Repeatedly start and immediately stop observation. Change a wallet record only after stop returns; verify the stopped observer does not schedule an upload or mutate its saved backup status. Restart observation and verify a single set of - listeners resumes pending work. + listeners resumes pending work. Also receive a settings-change notification + immediately before stop: its pending marker must survive the stopped listener. The iOS lifecycle unit tests exercise these component boundaries with injected capture/upload and delay controls. They do not prove a full device fault journey. From 1ad665f81364c08f52329767478cd29e75dd8a2f Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 05:29:53 +0100 Subject: [PATCH 07/45] test: wait for unobstructed USDT back navigation --- BitkitUITests/UsdtWalletUITests.swift | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/BitkitUITests/UsdtWalletUITests.swift b/BitkitUITests/UsdtWalletUITests.swift index 6dccbc5662..fd8cb46e6a 100644 --- a/BitkitUITests/UsdtWalletUITests.swift +++ b/BitkitUITests/UsdtWalletUITests.swift @@ -35,7 +35,7 @@ final class UsdtWalletUITests: XCTestCase { XCTAssertFalse(app.staticTexts["Could not update USDT. Check your connection and try again."].exists) XCTAssertFalse(app.staticTexts["Older activity is still syncing. Your balance is up to date when the connection is available."].exists) capture(app, "USDT unknown wallet in German region") - try XCTUnwrap(app.buttons.matching(identifier: "NavigationBack").allElementsBoundByIndex.first(where: \.isHittable)).tap() + try tapBack(in: app) app.buttons["Send"].tap() XCTAssertTrue(app.buttons["RecipientManual"].waitForExistence(timeout: 5)) app.buttons["RecipientManual"].tap() @@ -65,9 +65,9 @@ final class UsdtWalletUITests: XCTestCase { XCTAssertTrue(network.isEnabled) network.tap() XCTAssertTrue(app.buttons["UsdtNetwork-Polygon"].waitForExistence(timeout: 5)) - try XCTUnwrap(app.buttons.matching(identifier: "NavigationBack").allElementsBoundByIndex.first(where: \.isHittable)).tap() + try tapBack(in: app) XCTAssertTrue(app.buttons["UsdtReview"].waitForExistence(timeout: 5)) - try XCTUnwrap(app.buttons.matching(identifier: "NavigationBack").allElementsBoundByIndex.first(where: \.isHittable)).tap() + try tapBack(in: app) let restoredRecipient = app.textViews["RecipientInput"] XCTAssertTrue(restoredRecipient.waitForExistence(timeout: 5)) XCTAssertEqual(restoredRecipient.value as? String, recipient) @@ -174,6 +174,16 @@ final class UsdtWalletUITests: XCTestCase { capture(app, "USDT saved activity offline after restart") } + @MainActor + private func tapBack(in app: XCUIApplication) throws { + let buttons = app.buttons.matching(identifier: "NavigationBack") + let available = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + buttons.allElementsBoundByIndex.contains(where: \.isHittable) + }, object: app) + XCTAssertEqual(XCTWaiter.wait(for: [available], timeout: 10), .completed, app.debugDescription) + try XCTUnwrap(buttons.allElementsBoundByIndex.first(where: \.isHittable)).tap() + } + @MainActor private func capture(_ app: XCUIApplication, _ name: String) { let attachment = XCTAttachment(screenshot: app.screenshot()) @@ -223,7 +233,7 @@ final class UsdtWalletUITests: XCTestCase { XCTAssertFalse(amountlessUri.contains("uint256=")) app.buttons["SpecifyInvoiceButton"].tap() app.buttons["N5"].tap() - try XCTUnwrap(app.buttons.matching(identifier: "NavigationBack").allElementsBoundByIndex.first(where: \.isHittable)).tap() + try tapBack(in: app) XCTAssertTrue(qr.waitForExistence(timeout: 5)) XCTAssertEqual(qr.label, amountlessUri) app.buttons["SpecifyInvoiceButton"].tap() @@ -234,7 +244,7 @@ final class UsdtWalletUITests: XCTestCase { XCTAssertTrue(committedUri.contains("uint256=3000000")) app.buttons["SpecifyInvoiceButton"].tap() app.buttons["N5"].tap() - try XCTUnwrap(app.buttons.matching(identifier: "NavigationBack").allElementsBoundByIndex.first(where: \.isHittable)).tap() + try tapBack(in: app) XCTAssertTrue(qr.waitForExistence(timeout: 5)) XCTAssertEqual(qr.label, committedUri) app.buttons["UsdtReceiveDetails"].tap() From 8d4ed2b4a23d8e4753e4e439a6e4a686546d57a8 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 05:36:28 +0100 Subject: [PATCH 08/45] fix: stop profile deletion after incomplete cleanup --- Bitkit/Managers/ContactsManager.swift | 28 +------------ Bitkit/Managers/PubkyProfileManager.swift | 2 +- Bitkit/Views/Profile/EditProfileView.swift | 23 ++++++++--- BitkitTests/ContactsManagerTests.swift | 22 ++++++++++ BitkitTests/PubkyProfileManagerTests.swift | 43 ++++++++++++++++++++ changelog.d/next/profile-cleanup.fixed.md | 1 + journeys/profile/profile-cleanup-failure.xml | 18 ++++++++ 7 files changed, 103 insertions(+), 34 deletions(-) create mode 100644 changelog.d/next/profile-cleanup.fixed.md create mode 100644 journeys/profile/profile-cleanup-failure.xml diff --git a/Bitkit/Managers/ContactsManager.swift b/Bitkit/Managers/ContactsManager.swift index 4d3e7a5ad3..3c2a5b595d 100644 --- a/Bitkit/Managers/ContactsManager.swift +++ b/Bitkit/Managers/ContactsManager.swift @@ -969,22 +969,7 @@ class ContactsManager: ObservableObject { stopPendingProfileLookups() let contactRecords = contactRecords let removeContactRecords = removeContactRecords - let records: [ContactRecord] - do { - records = try await Task.detached { - try await contactRecords() - }.value - } catch { - guard Self.isMissingContactsDataError(error) else { - throw error - } - - Self.clearContactProfileOverrides() - await PrivatePaykitService.shared.pruneUnsavedContactState(savedPublicKeys: []) - contacts.removeAll() - Logger.info("Contacts storage missing, treating delete-all as empty", context: "ContactsManager") - return - } + let records = try await Task.detached { try await contactRecords() }.value let keys = records.compactMap { PubkyPublicKeyFormat.normalized($0.publicKey) } let removed = try await Task.detached { try await removeContactRecords(keys) }.value @@ -1003,17 +988,6 @@ class ContactsManager: ObservableObject { Logger.info("Deleted all contacts", context: "ContactsManager") } - func deleteAllContactsBestEffort() async { - do { - try await deleteAllContacts() - } catch { - Logger.warn("Continuing after contact cleanup failed: \(error)", context: "ContactsManager") - Self.clearContactProfileOverrides() - await PrivatePaykitService.shared.pruneUnsavedContactState(savedPublicKeys: []) - contacts.removeAll() - } - } - // MARK: - Remote Contact Discovery /// Looks every follow's profile up on the interactive read lane: the user waits on the choice screen until the import diff --git a/Bitkit/Managers/PubkyProfileManager.swift b/Bitkit/Managers/PubkyProfileManager.swift index 5591d441a0..458ef6f6e5 100644 --- a/Bitkit/Managers/PubkyProfileManager.swift +++ b/Bitkit/Managers/PubkyProfileManager.swift @@ -1062,7 +1062,7 @@ class PubkyProfileManager: ObservableObject { private func deleteProfile(for session: SignedInSession, cleanPrivatePaykitEndpoints: Bool) async throws { try requireCurrentSession(session) if cleanPrivatePaykitEndpoints { - await Self.removePrivatePaykitEndpointsBestEffort( + try await Self.removePrivatePaykitEndpoints( context: "PubkyProfileManager.deleteProfile", deferAppSync: true, isSessionCurrent: { self.currentSession == session } ) diff --git a/Bitkit/Views/Profile/EditProfileView.swift b/Bitkit/Views/Profile/EditProfileView.swift index e9dbe433eb..092006c0f4 100644 --- a/Bitkit/Views/Profile/EditProfileView.swift +++ b/Bitkit/Views/Profile/EditProfileView.swift @@ -174,16 +174,27 @@ struct EditProfileView: View { } private func performDeleteProfile(session: PubkyProfileManager.SignedInSession) async throws { + try await Self.performDeleteProfile(session: session, pubkyProfile: pubkyProfile, contactsManager: contactsManager) { + try await PubkyProfileManager.removePrivatePaykitEndpoints( + context: "EditProfileView.deleteProfile", deferAppSync: true, + isSessionCurrent: { pubkyProfile.currentSession == session } + ) + } + navigation.path = [app.hasSeenProfileIntro ? .pubkyChoice : .profileIntro] + } + + static func performDeleteProfile( + session: PubkyProfileManager.SignedInSession, + pubkyProfile: PubkyProfileManager, + contactsManager: ContactsManager, + removePrivateEndpoints: () async throws -> Void + ) async throws { try pubkyProfile.requireCurrentSession(session) - await PubkyProfileManager.removePrivatePaykitEndpointsBestEffort( - context: "EditProfileView.deleteProfile", deferAppSync: true, - isSessionCurrent: { pubkyProfile.currentSession == session } - ) + try await removePrivateEndpoints() try pubkyProfile.requireCurrentSession(session) - await contactsManager.deleteAllContactsBestEffort() + try await contactsManager.deleteAllContacts() try pubkyProfile.requireCurrentSession(session) try await pubkyProfile.deleteProfile(cleanPrivatePaykitEndpoints: false, expectedSession: session) - navigation.path = [app.hasSeenProfileIntro ? .pubkyChoice : .profileIntro] } private func disconnectAfterFailedDelete() async { diff --git a/BitkitTests/ContactsManagerTests.swift b/BitkitTests/ContactsManagerTests.swift index b53ddaf16d..0323836fa4 100644 --- a/BitkitTests/ContactsManagerTests.swift +++ b/BitkitTests/ContactsManagerTests.swift @@ -2243,6 +2243,28 @@ final class ContactsManagerTests: XCTestCase { XCTAssertTrue(manager.contacts.isEmpty) } + func testDeleteAllContactsPreservesEvidenceWhenTheContactReadFails() async throws { + snapshotAppDefaults("pubkyContactProfileOverrides") + let contact = makeContact(publicKey: contactProfileKey) + ContactsManager.restoreContactProfileOverrides([contact.publicKey: PubkyProfileData.from(profile: contact.profile)]) + let unavailable = AppError(message: "App Error", debugMessage: "Fetch failed: 404 missing session") + let manager = ContactsManager(contactRecords: { throw unavailable }, removeContactRecords: { _ in + XCTFail("An unavailable read must not authorize a removal") + return [] + }) + manager.contacts = [contact] + + do { + try await manager.deleteAllContacts() + XCTFail("An unavailable read is not an empty contact list") + } catch { + XCTAssertEqual(error.localizedDescription, unavailable.localizedDescription) + } + + XCTAssertEqual(manager.contacts, [contact]) + XCTAssertNotNil(ContactsManager.backupContactProfileOverrides()?[contact.publicKey]) + } + func testDeleteAllContactsPreservesContactsNotRemovedByTheBulkOperation() async throws { snapshotAppDefaults("pubkyContactProfileOverrides") let removed = contactRecord(key: contactProfileKey, name: "Removed") diff --git a/BitkitTests/PubkyProfileManagerTests.swift b/BitkitTests/PubkyProfileManagerTests.swift index 14f4dfe654..bfadce3de3 100644 --- a/BitkitTests/PubkyProfileManagerTests.swift +++ b/BitkitTests/PubkyProfileManagerTests.swift @@ -11,6 +11,49 @@ final class PubkyProfileManagerTests: XCTestCase { case signOut } + @MainActor + func testProfileRemovalStopsBeforeDeletingWhenCleanupIsIncomplete() async throws { + snapshotAppDefaultsDomain() + for failure in ["private endpoints", "contacts"] { + let key = "pubky" + String(repeating: "y", count: 52) + let originalError = KeychainError.failedToDelete + let manager = PubkyProfileManager(profileDeleter: { _ in + XCTFail("Incomplete cleanup must not delete the profile") + throw PublicPaykitError.publicationFailed + }) + manager.publicKey = key + manager.authState = .authenticated + let session = try XCTUnwrap(manager.currentSession) + let contact = Bitkit.PubkyProfile.placeholder(publicKey: key) + ContactsManager.restoreContactProfileOverrides([key: PubkyProfileData.from(profile: contact)]) + let contacts = ContactsManager(contactRecords: { + XCTAssertEqual(failure, "contacts", "Private withdrawal failure must stop before contact removal") + throw originalError + }) + contacts.contacts = [PubkyContact(publicKey: key, profile: contact)] + + do { + try await manager.performProfileDeletion { + try await EditProfileView.performDeleteProfile( + session: session, pubkyProfile: manager, contactsManager: contacts + ) { + if failure == "private endpoints" { + throw originalError + } + } + } + XCTFail("Incomplete cleanup must fail") + } catch { + XCTAssertTrue(error is KeychainError, "Preserve the cleanup failure, got \(error)") + } + + XCTAssertEqual(contacts.contacts.map(\.publicKey), [key]) + XCTAssertEqual(Set(ContactsManager.backupContactProfileOverrides()?.keys ?? [:].keys), [key]) + XCTAssertEqual(manager.currentSession, session) + XCTAssertFalse(manager.isDeletingProfile) + } + } + @MainActor func testProfileDeletionPausesAutomaticWorkWithoutEndingTheSession() async throws { for outcome in ["success", "failure", "cancellation"] { diff --git a/changelog.d/next/profile-cleanup.fixed.md b/changelog.d/next/profile-cleanup.fixed.md new file mode 100644 index 0000000000..e4eaf87e34 --- /dev/null +++ b/changelog.d/next/profile-cleanup.fixed.md @@ -0,0 +1 @@ +Preserve contact data and stop profile deletion when payment-link or contact cleanup is incomplete. diff --git a/journeys/profile/profile-cleanup-failure.xml b/journeys/profile/profile-cleanup-failure.xml new file mode 100644 index 0000000000..ab494d5d10 --- /dev/null +++ b/journeys/profile/profile-cleanup-failure.xml @@ -0,0 +1,18 @@ + + + Requires a disposable test identity with saved contacts and a controlled homeserver proxy. + Never use a personal profile. Inject a private-endpoint withdrawal failure, then in a fresh + fixture inject an unknown contact-removal response or a partial removal retaining an active peer. + These controls are not available in standard staging. This journey covers stopping on incomplete + cleanup, not cross-device conditional deletion or safe manual replay of an uncertain operation. + + + Open Edit Profile and confirm deletion with the cleanup fault enabled + Verify failure options appear without a success notification or onboarding navigation + Verify a failed private withdrawal is followed by no contact or profile deletion + Verify unknown contact removal keeps local contact data and prevents profile deletion + Verify partial contact removal preserves contacts and overrides not acknowledged as removed + Cancel the failure dialog and verify the app starts no second deletion + Restart the app and verify no profile deletion is automatically replayed + + From 76e0f8034705cae973b57665a90f324a3629f736 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 05:37:07 +0100 Subject: [PATCH 09/45] chore: rename changelog fragment --- changelog.d/next/{profile-cleanup.fixed.md => 1124.fixed.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changelog.d/next/{profile-cleanup.fixed.md => 1124.fixed.md} (100%) diff --git a/changelog.d/next/profile-cleanup.fixed.md b/changelog.d/next/1124.fixed.md similarity index 100% rename from changelog.d/next/profile-cleanup.fixed.md rename to changelog.d/next/1124.fixed.md From a0626189c02388c9c7725893aecb263ebb829fce Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 06:33:07 +0100 Subject: [PATCH 10/45] fix: preserve sessions after uncertain profile deletion --- Bitkit/Managers/PubkyProfileManager.swift | 39 ++------------ BitkitTests/PubkyProfileManagerTests.swift | 55 +++++++++++++------- changelog.d/next/1124.fixed.md | 2 +- journeys/profile/profile-cleanup-failure.xml | 2 + 4 files changed, 43 insertions(+), 55 deletions(-) diff --git a/Bitkit/Managers/PubkyProfileManager.swift b/Bitkit/Managers/PubkyProfileManager.swift index 458ef6f6e5..54fb3f7113 100644 --- a/Bitkit/Managers/PubkyProfileManager.swift +++ b/Bitkit/Managers/PubkyProfileManager.swift @@ -1069,17 +1069,9 @@ class PubkyProfileManager: ObservableObject { } try requireCurrentSession(session) let delete = profileDeleter - do { - try await Task.detached { - try await delete(session.publicKey) - }.value - } catch { - guard Self.isMissingBitkitProfileStorageError(error) else { - throw error - } - - Logger.info("Bitkit profile storage already missing, continuing sign out", context: "PubkyProfileManager") - } + try await Task.detached { + try await delete(session.publicKey) + }.value try requireCurrentSession(session) invalidateProfileLoads() @@ -1949,31 +1941,6 @@ class PubkyProfileManager: ObservableObject { return normalized } - nonisolated static func isMissingBitkitProfileStorageError(_ error: Error) -> Bool { - if case .profileNotFound = error as? PubkyServiceError { - return true - } - - let errorText = [ - (error as? AppError)?.debugMessage, - error.localizedDescription, - String(describing: error), - ] - .compactMap { $0?.lowercased() } - - if errorText.contains(where: { $0.contains("404 not found") || $0.contains("directory not found") }) { - return true - } - - let nsError = error as NSError - if nsError.domain == NSCocoaErrorDomain { - let cocoaCode = CocoaError.Code(rawValue: nsError.code) - return cocoaCode == .fileNoSuchFile || cocoaCode == .fileReadNoSuchFile - } - - return false - } - nonisolated static func resolveSessionInitialization( savedSessionSecret: String?, storedSecretKeyHex: String?, diff --git a/BitkitTests/PubkyProfileManagerTests.swift b/BitkitTests/PubkyProfileManagerTests.swift index bfadce3de3..c15f25c334 100644 --- a/BitkitTests/PubkyProfileManagerTests.swift +++ b/BitkitTests/PubkyProfileManagerTests.swift @@ -322,6 +322,43 @@ final class PubkyProfileManagerTests: XCTestCase { } } + @MainActor + func testProfileDeletionRequiresAcknowledgedCompletionBeforeSignOut() async throws { + try await withEmptyIdentityStorage { + let errors: [NSError?] = [ + nil, + NSError(domain: "ProfileDeleteFixture", code: 404, + userInfo: [NSLocalizedDescriptionKey: "Delete failed: HTTP 404 Not Found at session endpoint"]), + NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadNoSuchFile.rawValue), + ] + for failure in errors { + let manager = PubkyProfileManager(profileDeleter: { _ in + if let failure { + throw failure + } + }) + manager.publicKey = "pubky" + String(repeating: "y", count: 52) + manager.authState = .authenticated + let session = try XCTUnwrap(manager.currentSession) + UserDefaults.standard.set(true, forKey: PublicPaykitService.publishingEnabledKey) + UserDefaults.standard.set(true, forKey: PrivatePaykitService.publishingEnabledKey) + + do { + try await manager.deleteProfile(cleanPrivatePaykitEndpoints: false) + XCTAssertNil(failure, "An unavailable profile does not confirm its deletion") + } catch { + XCTAssertEqual((error as NSError).domain, failure?.domain) + XCTAssertEqual((error as NSError).code, failure?.code) + } + + XCTAssertEqual(manager.currentSession, failure == nil ? nil : session) + XCTAssertEqual(UserDefaults.standard.bool(forKey: PublicPaykitService.publishingEnabledKey), failure != nil) + XCTAssertEqual(UserDefaults.standard.bool(forKey: PrivatePaykitService.publishingEnabledKey), failure != nil) + XCTAssertFalse(manager.isDeletingProfile) + } + } + } + @MainActor func testDeletionSessionRejectsAReplacementAndANewSessionForTheSameKey() async throws { try await withEmptyIdentityStorage { @@ -3484,24 +3521,6 @@ final class PubkyProfileManagerTests: XCTestCase { XCTAssertNil(resolved) } - func testIsMissingBitkitProfileStorageErrorRecognizes404DeleteFailure() { - let error = AppError( - message: "App Error", - debugMessage: #"BitkitCore.PubkyError.WriteFailed(reason: "delete failed: Request failed: Server responded with an error: 404 Not Found - Not Found")"# - ) - - XCTAssertTrue(PubkyProfileManager.isMissingBitkitProfileStorageError(error)) - } - - func testIsMissingBitkitProfileStorageErrorRejectsNonMissingErrors() { - let error = AppError( - message: "App Error", - debugMessage: #"BitkitCore.PubkyError.AuthFailed(reason: "Request failed: HTTP transport error")"# - ) - - XCTAssertFalse(PubkyProfileManager.isMissingBitkitProfileStorageError(error)) - } - // MARK: - Session backup state func testSnapshotSessionBackupStatePrefersLocalSeedOverSessionSecret() throws { diff --git a/changelog.d/next/1124.fixed.md b/changelog.d/next/1124.fixed.md index e4eaf87e34..f05f0a6f84 100644 --- a/changelog.d/next/1124.fixed.md +++ b/changelog.d/next/1124.fixed.md @@ -1 +1 @@ -Preserve contact data and stop profile deletion when payment-link or contact cleanup is incomplete. +Preserve session and contact data after failed profile deletion or incomplete payment-link cleanup. diff --git a/journeys/profile/profile-cleanup-failure.xml b/journeys/profile/profile-cleanup-failure.xml index ab494d5d10..f9fd8c2e29 100644 --- a/journeys/profile/profile-cleanup-failure.xml +++ b/journeys/profile/profile-cleanup-failure.xml @@ -3,6 +3,7 @@ Requires a disposable test identity with saved contacts and a controlled homeserver proxy. Never use a personal profile. Inject a private-endpoint withdrawal failure, then in a fresh fixture inject an unknown contact-removal response or a partial removal retaining an active peer. + Also inject a profile-deletion error whose message contains 404 Not Found, without confirming deletion. These controls are not available in standard staging. This journey covers stopping on incomplete cleanup, not cross-device conditional deletion or safe manual replay of an uncertain operation. @@ -12,6 +13,7 @@ Verify a failed private withdrawal is followed by no contact or profile deletion Verify unknown contact removal keeps local contact data and prevents profile deletion Verify partial contact removal preserves contacts and overrides not acknowledged as removed + Verify an uncertain profile-deletion error preserves the session and sharing settings without success feedback Cancel the failure dialog and verify the app starts no second deletion Restart the app and verify no profile deletion is automatically replayed From ca10ace721cf718331a66e594607b226034e2370 Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 26 Oct 2026 01:04:59 +0200 Subject: [PATCH 11/45] test: retain navigation timeout evidence --- .../SendConfirmationLifecycleTests.swift | 37 ++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/BitkitTests/SendConfirmationLifecycleTests.swift b/BitkitTests/SendConfirmationLifecycleTests.swift index d36bb0f220..d033e469ad 100644 --- a/BitkitTests/SendConfirmationLifecycleTests.swift +++ b/BitkitTests/SendConfirmationLifecycleTests.swift @@ -581,7 +581,42 @@ private final class SendConfirmationTestNavigation { while visibleRoutes != [route], ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) } - XCTAssertEqual(visibleRoutes, [route], file: file, line: line) + let observedRoutes = visibleRoutes + XCTAssertEqual(observedRoutes, [route], file: file, line: line) + guard observedRoutes != [route] else { return } + + XCTContext.runActivity(named: "Navigation appearance deadline") { activity in + let state = XCTAttachment(string: "expected=\(route) visible=\(observedRoutes) path=\(path)") + state.name = "navigation-state" + state.lifetime = .keepAlways + activity.add(state) + + func describe(_ view: UIView, depth: Int = 0) -> String { + let row = "\(String(repeating: " ", count: depth))\(type(of: view)) frame=\(view.frame) hidden=\(view.isHidden) firstResponder=\(view.isFirstResponder)\n" + return row + view.subviews.map { describe($0, depth: depth + 1) }.joined() + } + func describe(_ controller: UIViewController, depth: Int = 0) -> String { + let row = "\(String(repeating: " ", count: depth))\(type(of: controller)) appearing=\(controller.isBeingPresented) disappearing=\(controller.isBeingDismissed) transitioning=\(controller.transitionCoordinator != nil)\n" + let children = controller.children.map { describe($0, depth: depth + 1) }.joined() + let presented = controller.presentedViewController.map { describe($0, depth: depth + 1) } ?? "" + return row + children + presented + } + let windows = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.flatMap(\.windows) + for (index, window) in windows.enumerated() { + let controllers = window.rootViewController.map { describe($0) } ?? "No root view controller\n" + let hierarchy = XCTAttachment(string: "key=\(window.isKeyWindow)\n" + controllers + describe(window)) + hierarchy.name = "deadline-window-\(index)-hierarchy" + hierarchy.lifetime = .keepAlways + activity.add(hierarchy) + guard !window.isHidden, !window.bounds.isEmpty else { continue } + let screenshot = XCTAttachment(image: UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: false) + }) + screenshot.name = "deadline-window-\(index)" + screenshot.lifetime = .keepAlways + activity.add(screenshot) + } + } } } From 2fee5322c80547dd9312445edbd2dd7c979ae801 Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 26 Oct 2026 09:13:15 +0200 Subject: [PATCH 12/45] fix: reject stale SDK waiters before wipe enqueue --- Bitkit/Services/PubkyService.swift | 39 +++++++++++++---- BitkitTests/PaykitSdkOperationLockTests.swift | 43 +++++++++++++++++++ changelog.d/next/1687.fixed.md | 1 + 3 files changed, 74 insertions(+), 9 deletions(-) create mode 100644 changelog.d/next/1687.fixed.md diff --git a/Bitkit/Services/PubkyService.swift b/Bitkit/Services/PubkyService.swift index 7be9cb33ea..ba09e591a3 100644 --- a/Bitkit/Services/PubkyService.swift +++ b/Bitkit/Services/PubkyService.swift @@ -1866,7 +1866,7 @@ final class PaykitSdkOperationLock: @unchecked Sendable { } private enum Waiter { - case uncancellable(Priority, CheckedContinuation) + case uncancellable(Priority, CheckedContinuation) case cancellable(UUID, Priority, CheckedContinuation) var priority: Priority { @@ -1886,6 +1886,14 @@ final class PaykitSdkOperationLock: @unchecked Sendable { private var activeWipeID: UUID? @TaskLocal private static var walletWipeOwner: UUID? + #if DEBUG + private let beforeAcquireForTesting: (@Sendable () async -> Void)? + + init(beforeAcquireForTesting: (@Sendable () async -> Void)? = nil) { + self.beforeAcquireForTesting = beforeAcquireForTesting + } + #endif + func withLock( priority: Priority = .ordered, generation expectedGeneration: Int? = nil, @@ -1895,7 +1903,10 @@ final class PaykitSdkOperationLock: @unchecked Sendable { return try await operation() } let admittedGeneration = try admit() - await acquire(priority: priority) + #if DEBUG + await beforeAcquireForTesting?() + #endif + guard await acquire(priority: priority, generation: admittedGeneration) else { throw wipeError() } defer { release() } try validate(expectedGeneration ?? admittedGeneration) try Task.checkCancellation() @@ -1924,7 +1935,7 @@ final class PaykitSdkOperationLock: @unchecked Sendable { func withWalletWipe(_ operation: () async throws -> T) async throws -> T { let wipeID = try beginWipe() defer { endWipe() } - await acquire(priority: .ordered) + _ = await acquire(priority: .ordered) defer { release() } try Task.checkCancellation() return try await Self.$walletWipeOwner.withValue(wipeID) { @@ -1980,28 +1991,35 @@ final class PaykitSdkOperationLock: @unchecked Sendable { return try await operation() } let admittedGeneration = try admit() - try await acquireCancellable() + #if DEBUG + await beforeAcquireForTesting?() + #endif + try await acquireCancellable(generation: admittedGeneration) defer { release() } try validate(admittedGeneration) try Task.checkCancellation() return try await operation() } - private func acquire(priority: Priority) async { + private func acquire(priority: Priority, generation expectedGeneration: Int? = nil) async -> Bool { await withCheckedContinuation { continuation in lock.lock() - if isLocked { + // Recheck while inserting: an old outer owner must not queue behind a wipe draining it. + if let expectedGeneration, isWiping || generation != expectedGeneration { + lock.unlock() + continuation.resume(returning: false) + } else if isLocked { waiters.append(.uncancellable(priority, continuation)) lock.unlock() } else { isLocked = true lock.unlock() - continuation.resume() + continuation.resume(returning: true) } } } - private func acquireCancellable() async throws { + private func acquireCancellable(generation admittedGeneration: Int) async throws { let id = UUID() try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in @@ -2009,6 +2027,9 @@ final class PaykitSdkOperationLock: @unchecked Sendable { if Task.isCancelled { lock.unlock() continuation.resume(throwing: CancellationError()) + } else if isWiping || generation != admittedGeneration { + lock.unlock() + continuation.resume(throwing: wipeError()) } else if isLocked { waiters.append(.cancellable(id, .ordered, continuation)) lock.unlock() @@ -2054,7 +2075,7 @@ final class PaykitSdkOperationLock: @unchecked Sendable { lock.unlock() switch nextWaiter { case let .uncancellable(_, continuation): - continuation.resume() + continuation.resume(returning: true) case let .cancellable(_, _, continuation): continuation.resume() case nil: diff --git a/BitkitTests/PaykitSdkOperationLockTests.swift b/BitkitTests/PaykitSdkOperationLockTests.swift index f703a36ab9..6e624d6983 100644 --- a/BitkitTests/PaykitSdkOperationLockTests.swift +++ b/BitkitTests/PaykitSdkOperationLockTests.swift @@ -513,6 +513,49 @@ final class PaykitSdkOperationLockTests: XCTestCase { } catch is CancellationError {} } + func testWipeRejectsPreviouslyAdmittedOuterOwnerBeforeQueueInsertion() async throws { + for cancellable in [false, true] { + let outer = PaykitSdkOperationLock() + let admitted = expectation(description: "Ordinary operation admitted before SDK enqueue") + let finished = expectation(description: "Old outer owner rejected without waiting behind wipe") + let wipeEntered = expectation(description: "Wipe waits on original outer owner") + let (gate, release) = AsyncStream.makeStream() + let sdk = PaykitSdkOperationLock(beforeAcquireForTesting: { + admitted.fulfill() + for await _ in gate {} + }) + let ordinary = Task { + defer { finished.fulfill() } + do { + try await outer.withLock { + if cancellable { + try await sdk.withCancellableLock { XCTFail("Stale SDK operation executed") } + } else { + try await sdk.withLock { XCTFail("Stale SDK operation executed") } + } + } + XCTFail("Expected wipe rejection") + } catch let PaykitError.Storage(code, _) { + XCTAssertEqual(code, "wallet_wipe_in_progress") + } + } + await fulfillment(of: [admitted], timeout: 2) + let wipe = Task { + try await sdk.withWalletWipe { + wipeEntered.fulfill() + // Allow cleanup after a failed assertion without leaving either task suspended. + try await outer.withCancellableLock {} + } + } + await fulfillment(of: [wipeEntered], timeout: 2) + release.finish() + await fulfillment(of: [finished], timeout: 1) + wipe.cancel() + do { try await wipe.value } catch is CancellationError {} + try await ordinary.value + } + } + func testWipeDrainsActiveWorkRejectsQueuedWorkAndAllowsCleanupAndFreshWork() async throws { let lock = PaykitSdkOperationLock() let recorder = Recorder() diff --git a/changelog.d/next/1687.fixed.md b/changelog.d/next/1687.fixed.md new file mode 100644 index 0000000000..67503a93b4 --- /dev/null +++ b/changelog.d/next/1687.fixed.md @@ -0,0 +1 @@ +Prevent wallet reset from waiting indefinitely for an older Paykit operation queued during teardown. From 3a7210b0bbb129a3e0f4007aeeaef7727c5fc10a Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 26 Oct 2026 09:15:29 +0200 Subject: [PATCH 13/45] chore: rename changelog fragment --- changelog.d/next/{1687.fixed.md => 1125.fixed.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changelog.d/next/{1687.fixed.md => 1125.fixed.md} (100%) diff --git a/changelog.d/next/1687.fixed.md b/changelog.d/next/1125.fixed.md similarity index 100% rename from changelog.d/next/1687.fixed.md rename to changelog.d/next/1125.fixed.md From 494c9492596100e198b0bdb91c712ebe5888d929 Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 26 Oct 2026 21:51:49 +0200 Subject: [PATCH 14/45] fix: retry backup transport failures and coalesce status writes --- Bitkit/Services/BackupService.swift | 17 +++++- BitkitTests/BackupServiceTests.swift | 85 ++++++++++++++++++++++++++++ changelog.d/next/1123.fixed.md | 2 +- 3 files changed, 102 insertions(+), 2 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 7903e1c8e7..03f1257119 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -357,11 +357,24 @@ class BackupService { case PaykitError.ConcurrentUpdate, PaykitError.SharedStateBusy, PaykitError.Transport, VssError.ConnectionError, VssError.NetworkError, VssError.StoreError, VssError.PutError: true + case let VssError.UnknownError(details): + isVssRequestSendFailure(details) default: false } } + private static func isVssRequestSendFailure(_ details: String) -> Bool { + let prefix = "error sending request for url (" + guard details.hasPrefix(prefix), details.hasSuffix(")"), + let url = URLComponents(string: String(details.dropFirst(prefix.count).dropLast())), + url.scheme == "http" || url.scheme == "https", + let host = url.host, !host.isEmpty, + url.path.hasSuffix("/putObjects") + else { return false } + return true + } + func persistWalletBackup() async throws { do { try await writeWalletBackup() @@ -989,7 +1002,9 @@ class BackupService { statusUpdateQueue.sync { var statuses = getAllBackupStatuses() let currentStatus = statuses[category] ?? BackupItemStatus() - statuses[category] = update(currentStatus) + let nextStatus = update(currentStatus) + guard statuses[category] != nextStatus else { return } + statuses[category] = nextStatus saveBackupStatuses(statuses) } } diff --git a/BitkitTests/BackupServiceTests.swift b/BitkitTests/BackupServiceTests.swift index 76ae93fabb..a8b78a243c 100644 --- a/BitkitTests/BackupServiceTests.swift +++ b/BitkitTests/BackupServiceTests.swift @@ -1,10 +1,79 @@ @testable import Bitkit import Combine import Paykit +import VssRustClientFfi import XCTest @MainActor final class BackupServiceTests: XCTestCase { + func testReleasedVssConnectionErrorIsTemporaryWithoutBroadUnknownRetry() { + XCTAssertTrue(BackupService.isTemporaryBackupFailure( + VssError.UnknownError(errorDetails: "error sending request for url (http://127.0.0.1:1/putObjects)") + )) + XCTAssertTrue(BackupService.isTemporaryBackupFailure( + VssError.UnknownError(errorDetails: "error sending request for url (https://backup.example/vss/putObjects)") + )) + for details in ["invalid ciphertext", "permission denied", "HTTP status client error (401 Unauthorized)", + "error sending request for url (not a URL)", "prefix error sending request for url (https://example.com)", + "error sending request for url (https://example.com/getObject)", + "error sending request for url (file://example.com/putObjects)", + "error sending request for url (https:///putObjects)", + "error sending request for url (https://example.com/putObjects) suffix"] + { + XCTAssertFalse(BackupService.isTemporaryBackupFailure(VssError.UnknownError(errorDetails: details))) + } + XCTAssertFalse(BackupService.isTemporaryBackupFailure(URLError(.notConnectedToInternet))) + XCTAssertFalse(BackupService.isTemporaryBackupFailure(CancellationError())) + } + + func testReleasedVssConnectionFailureRetriesStoppedUsdtWithBoundedBackoff() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let completed = expectation(description: "Recovery upload acknowledged after connection resumes") + var attempts = 0 + var delays: [UInt64] = [] + let payload = Data("same-signed-recovery".utf8) + let service = BackupService(defaults: defaults, backupData: { _ in payload }, uploadBackup: { key, data in + XCTAssertEqual(key, BackupCategory.usdt.rawValue) + XCTAssertEqual(data, payload) + attempts += 1 + if attempts <= 8 { + throw VssError.UnknownError(errorDetails: "error sending request for url (http://127.0.0.1:1/putObjects)") + } + }, waitForBackupDelay: {}, waitForTemporaryFailureDelay: { delays.append($0) }) + await service.stopObservingBackups() + let subscription = service.backupStatusesPublisher + .filter { $0[.usdt].map { !$0.isRequired && !$0.running } == true } + .first().sink { _ in completed.fulfill() } + service.markBackupRequired(category: .usdt) + await fulfillment(of: [completed], timeout: 3) + subscription.cancel() + service.setWiping(true) + await service.stopObservingBackups() + XCTAssertEqual(attempts, 9) + XCTAssertEqual(delays, [10, 20, 40, 80, 160, 300, 300, 300].map { UInt64($0) * 1_000_000_000 }) + XCTAssertFalse(service.getBackupStatus(category: .usdt).isRequired) + } + + func testRepeatedPendingNotificationsDoNotRewriteUnchangedDurableStatus() throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(CountingBackupDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let required = UInt64(Date().timeIntervalSince1970) + 3600 + let pending = BackupItemStatus(synced: 0, required: required, running: false) + try defaults.set(JSONEncoder().encode([BackupCategory.wallet.rawValue: pending]), forKey: "backupStatuses") + let service = BackupService(defaults: defaults) + let writes = defaults.backupStatusWrites + for _ in 0 ..< 200 { + service.markBackupRequired(category: .wallet, schedule: false) + } + XCTAssertEqual(defaults.backupStatusWrites, writes) + XCTAssertEqual(service.getBackupStatus(category: .wallet), pending) + let restarted = BackupService(defaults: defaults) + XCTAssertEqual(restarted.getBackupStatus(category: .wallet), pending) + } + func testChangesDuringCaptureAndUploadRemainRequired() async throws { for changeDuringCapture in [true, false] { let suite = "BackupServiceTests.\(UUID().uuidString)" @@ -699,6 +768,22 @@ private final class WalletBackupSdk: PaykitSdk, @unchecked Sendable { } } +private final class CountingBackupDefaults: UserDefaults { + private let writeLock = NSLock() + private var writes = 0 + + var backupStatusWrites: Int { + writeLock.withLock { writes } + } + + override func set(_ value: Any?, forKey defaultName: String) { + if defaultName == "backupStatuses" { + writeLock.withLock { writes += 1 } + } + super.set(value, forKey: defaultName) + } +} + private actor BackupDelayGate { private(set) var isHeld = true private(set) var didStop = false diff --git a/changelog.d/next/1123.fixed.md b/changelog.d/next/1123.fixed.md index 3cba6c7e79..94995fe117 100644 --- a/changelog.d/next/1123.fixed.md +++ b/changelog.d/next/1123.fixed.md @@ -1 +1 @@ -Fixed a crash when backup observation stops and ensured pending backups resume safely after restart. +Prevent crashes when backup observation stops and resume pending backups after restart or temporary connection failures without redundant status writes. From ff999a50e24326ad45fb033c61155b95c041d1be Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 26 Oct 2026 23:11:18 +0200 Subject: [PATCH 15/45] fix: complete wallet initialization once --- .../Onboarding/InitializingWalletView.swift | 11 +++++++++ BitkitTests/InitializingWalletViewTests.swift | 23 +++++++++++++++++++ changelog.d/next/1123.fixed.md | 2 +- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/Bitkit/Views/Onboarding/InitializingWalletView.swift b/Bitkit/Views/Onboarding/InitializingWalletView.swift index 63f1a22ea7..e56638cc01 100644 --- a/Bitkit/Views/Onboarding/InitializingWalletView.swift +++ b/Bitkit/Views/Onboarding/InitializingWalletView.swift @@ -10,11 +10,22 @@ struct InitializingWalletView: View { @Binding var nodeLifecycleState: NodeLifecycleState let onComplete: () -> Void + init( + nodeLifecycleState: Binding, + initialPercentage: Double = 0, + onComplete: @escaping () -> Void + ) { + _nodeLifecycleState = nodeLifecycleState + _percentage = State(initialValue: initialPercentage) + self.onComplete = onComplete + } + private var shouldFinish: Bool { nodeLifecycleState == .running } private func handleCompletion() { + guard shouldFinish, !shouldStopAnimation else { return } timer?.invalidate() shouldStopAnimation = true Haptics.stopHaptics() diff --git a/BitkitTests/InitializingWalletViewTests.swift b/BitkitTests/InitializingWalletViewTests.swift index 7e23a21190..a8eb9b0780 100644 --- a/BitkitTests/InitializingWalletViewTests.swift +++ b/BitkitTests/InitializingWalletViewTests.swift @@ -4,6 +4,29 @@ import XCTest @MainActor final class InitializingWalletViewTests: XCTestCase { + func testNormalizingCompletedProgressInvokesCompletionOnce() async { + var completionCount = 0 + let completion = expectation(description: "Wallet initialization completes once") + let window = UIWindow(frame: UIScreen.main.bounds) + window.rootViewController = UIHostingController(rootView: InitializingWalletView( + nodeLifecycleState: .constant(.running), initialPercentage: 98.75 + ) { + completionCount += 1 + if completionCount == 1 { + completion.fulfill() + } + }) + window.makeKeyAndVisible() + defer { + window.isHidden = true + window.rootViewController = nil + } + + await fulfillment(of: [completion], timeout: 3) + try? await Task.sleep(for: .milliseconds(200)) + XCTAssertEqual(completionCount, 1) + } + func testSlowRetryWaitsForRunningNodeBeforeCompleting() async { let state = InitializationTestState() var completionCount = 0 diff --git a/changelog.d/next/1123.fixed.md b/changelog.d/next/1123.fixed.md index 94995fe117..0136537fdc 100644 --- a/changelog.d/next/1123.fixed.md +++ b/changelog.d/next/1123.fixed.md @@ -1 +1 @@ -Prevent crashes when backup observation stops and resume pending backups after restart or temporary connection failures without redundant status writes. +Preserve pending backups through observation changes and temporary connection failures, and complete wallet initialization only once after node startup. From 61e74dc0cf542d1d1152aada26c111dc76fb3839 Mon Sep 17 00:00:00 2001 From: benk10 Date: Tue, 27 Oct 2026 00:58:57 +0200 Subject: [PATCH 16/45] fix: recover connections during wallet restore --- Bitkit/AppScene.swift | 122 +++- .../Localization/ar.lproj/Localizable.strings | 3 + .../Localization/ca.lproj/Localizable.strings | 3 + .../Localization/cs.lproj/Localizable.strings | 3 + .../Localization/de.lproj/Localizable.strings | 3 + .../Localization/el.lproj/Localizable.strings | 3 + .../Localization/en.lproj/Localizable.strings | 3 + .../es-419.lproj/Localizable.strings | 3 + .../Localization/es.lproj/Localizable.strings | 3 + .../Localization/fr.lproj/Localizable.strings | 3 + .../Localization/it.lproj/Localizable.strings | 3 + .../Localization/nl.lproj/Localizable.strings | 3 + .../Localization/pl.lproj/Localizable.strings | 3 + .../pt-BR.lproj/Localizable.strings | 3 + .../Localization/pt.lproj/Localizable.strings | 3 + .../Localization/ru.lproj/Localizable.strings | 3 + Bitkit/Services/BackupService.swift | 28 +- .../Services/ConnectionRecoveryService.swift | 325 +++++++++ Bitkit/Utilities/AppReset.swift | 22 +- Bitkit/Utilities/Keychain.swift | 2 + .../WalletConnectionRecoveryView.swift | 133 ++++ .../Views/Onboarding/WalletRestoreError.swift | 7 + .../ConnectionRecoveryServiceTests.swift | 645 ++++++++++++++++++ BitkitTests/UsdtRecoveryBackupTests.swift | 7 +- changelog.d/next/connection-recovery.fixed.md | 1 + journeys/backup-restore/README.md | 3 + .../backup-restore/connection-recovery.xml | 22 + 27 files changed, 1343 insertions(+), 19 deletions(-) create mode 100644 Bitkit/Services/ConnectionRecoveryService.swift create mode 100644 Bitkit/Views/Onboarding/WalletConnectionRecoveryView.swift create mode 100644 BitkitTests/ConnectionRecoveryServiceTests.swift create mode 100644 changelog.d/next/connection-recovery.fixed.md create mode 100644 journeys/backup-restore/README.md create mode 100644 journeys/backup-restore/connection-recovery.xml diff --git a/Bitkit/AppScene.swift b/Bitkit/AppScene.swift index c39b57cfb7..9b06e9fd17 100644 --- a/Bitkit/AppScene.swift +++ b/Bitkit/AppScene.swift @@ -371,6 +371,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 showConnectionRecovery = false @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. @@ -888,7 +890,9 @@ struct AppScene: View { @ViewBuilder private var existingWalletContent: some View { - if walletIsInitializing == true { + if showConnectionRecovery { + WalletConnectionRecoveryView(onBack: { showConnectionRecovery = false }, onRetry: retryWalletStart) + } else if walletIsInitializing == true { // New wallet is being created or restored initializingContent } else if wallet.isRestoringWallet { @@ -911,20 +915,24 @@ struct AppScene: View { @ViewBuilder private var initializingContent: some View { if didWalletBackupRestoreFail { - WalletRestoreError { - didWalletBackupRestoreFail = false - await restoreWalletBackupAndStart() - } + WalletRestoreError(onRetry: retryWalletStart, onConnectionSettings: { showConnectionRecovery = true }) } else if case .errorStarting = wallet.nodeLifecycleState { - WalletRestoreError(onRetry: retryWalletStart) + WalletRestoreError(onRetry: retryWalletStart, onConnectionSettings: { showConnectionRecovery = true }) } 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) } } @@ -978,7 +986,7 @@ struct AppScene: View { } let shouldRestoreWalletBackup = wallet.isRestoringWallet || BackupService.shared.hasPendingWalletRestore() - if shouldRestoreWalletBackup { + if connectionRecovery.requiresRestrictedStartup(hasPendingRestore: shouldRestoreWalletBackup) { walletIsInitializing = true } @@ -998,7 +1006,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, @@ -1011,6 +1038,9 @@ struct AppScene: View { // Check network before attempting to start - LDK hangs when VSS is unreachable guard network.isConnected else { Logger.warn("Network offline, skipping wallet start", context: "AppScene") + if walletIsInitializing == true { + didWalletBackupRestoreFail = true + } if MigrationsService.shared.isShowingMigrationLoading { await MainActor.run { MigrationsService.shared.isShowingMigrationLoading = false @@ -1021,7 +1051,18 @@ 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() + try connectionRecovery.checkCurrentOperation() + try connectionRecovery.complete(revision: revision, hasPendingRestore: BackupService.shared.hasPendingWalletRestore(), + isRunning: wallet.nodeLifecycleState == .running) + { + didWalletBackupRestoreFail = false + } try await activity.syncLdkNodePayments() // Start watching pending orders after wallet is ready await blocktank.startWatchingPendingOrders(transferViewModel: transfer) @@ -1033,7 +1074,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 { + didWalletBackupRestoreFail = true + } if playsErrorHaptic { Haptics.notify(.error) } @@ -1151,6 +1196,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 else { return } isWalletBackupRestoreRunning = true walletIsInitializing = true @@ -1162,6 +1223,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 @@ -1174,12 +1243,42 @@ 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 wallet.nodeLifecycleState == .running, !BackupService.shared.hasPendingWalletRestore(), !didWalletBackupRestoreFail { + showConnectionRecovery = false + } + } 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) } } @@ -1247,6 +1346,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/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index bd85944aba..d67b04d15c 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -1638,3 +1638,6 @@ "subscriptions__allowance_limit_title" = "تم بلوغ الحد"; "subscriptions__allowance_limit_description" = "طلب بقيمة {amount} من {name} يتجاوز مخصصك. راجعه للدفع."; "subscriptions__allowance_auto_paid" = "مدفوع تلقائيًا"; + +"onboarding__connection_settings" = "إعدادات الاتصال"; +"onboarding__connection_saved" = "تم الحفظ. أعد المحاولة لمتابعة الاستعادة."; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index 194a214be1..ed005cc45b 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -1822,3 +1822,6 @@ "subscriptions__allowance_limit_title" = "Límit assolit"; "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."; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index 1a1cf5c825..04de6b9902 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -1961,3 +1961,6 @@ "subscriptions__allowance_limit_title" = "Limit dosažen"; "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ě."; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index a3af19f31a..b8dfc17891 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -1958,3 +1958,6 @@ "subscriptions__allowance_limit_title" = "Limit erreicht"; "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."; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index 03a6e79c7a..b2565ea6da 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -1693,3 +1693,6 @@ "subscriptions__allowance_limit_title" = "Το όριο εξαντλήθηκε"; "subscriptions__allowance_limit_description" = "Ένα αίτημα {amount} από {name} υπερβαίνει την προέγκρισή σου. Έλεγξέ το για να πληρώσεις."; "subscriptions__allowance_auto_paid" = "Πληρώθηκε αυτόματα"; + +"onboarding__connection_settings" = "Ρυθμίσεις σύνδεσης"; +"onboarding__connection_saved" = "Αποθηκεύτηκε. Δοκιμάστε ξανά για να συνεχίσετε την επαναφορά."; diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings index 9ee3615760..d07498ed2f 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -2050,3 +2050,6 @@ "usdt__error_bridge_maximum" = "Amount is above this route’s maximum. Try a smaller amount."; "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."; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index 456943a31c..db24329c0f 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -1964,3 +1964,6 @@ "subscriptions__allowance_limit_title" = "Límite alcanzado"; "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."; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index a0d36bae34..5414b5b6af 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -1842,3 +1842,6 @@ "subscriptions__allowance_limit_title" = "Límite alcanzado"; "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."; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index 26d35f483e..a43dc5f8df 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -1972,3 +1972,6 @@ "subscriptions__allowance_limit_title" = "Limite atteinte"; "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."; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index 792e01c101..84819cd128 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -1931,3 +1931,6 @@ "subscriptions__allowance_limit_title" = "Limite Raggiunto"; "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."; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index 0cc8b04816..6556c5d481 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -1966,3 +1966,6 @@ "subscriptions__allowance_limit_title" = "Limiet bereikt"; "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."; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index 7fd3cf0988..6f319b56fd 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -1971,3 +1971,6 @@ "subscriptions__allowance_limit_title" = "Osiągnięto limit"; "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."; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index 7f5b0015f1..f900a41980 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -1972,3 +1972,6 @@ "subscriptions__allowance_limit_title" = "Limite Atingido"; "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."; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index 1090ee9ed4..c26c0f867f 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -1618,3 +1618,6 @@ "subscriptions__allowance_limit_title" = "Limite atingido"; "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."; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index 507d733adb..58eb7a9291 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -1952,3 +1952,6 @@ "subscriptions__allowance_limit_title" = "Лимит Достигнут"; "subscriptions__allowance_limit_description" = "Запрос на {amount} от {name} превышает ваш лимит автооплаты. Проверьте его, чтобы оплатить."; "subscriptions__allowance_auto_paid" = "Оплачено автоматически"; + +"onboarding__connection_settings" = "Настройки подключения"; +"onboarding__connection_saved" = "Сохранено. Повторите попытку, чтобы продолжить восстановление."; diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 03f1257119..add0ff5ff4 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -124,6 +124,11 @@ class BackupService { private var lastNotificationTime: UInt64 = 0 private let defaults: UserDefaults + private let connectionRecovery: ConnectionRecoveryService? + @MainActor private var connectionRecoveryService: ConnectionRecoveryService { + connectionRecovery ?? .shared + } + private let backupData: ((BackupCategory) async throws -> Data)? private let uploadBackup: (String, Data) async throws -> Void private let waitForBackupDelay: () async throws -> Void @@ -152,6 +157,7 @@ class BackupService { init( defaults: UserDefaults = .standard, + connectionRecovery: ConnectionRecoveryService? = nil, backupData: ((BackupCategory) async throws -> Data)? = nil, usdtRecoveryBackup: UsdtRecoveryBackupStore = UsdtRecoveryBackupStore(), uploadBackup: @escaping (String, Data) async throws -> Void = { key, data in @@ -165,6 +171,7 @@ class BackupService { } ) { self.defaults = defaults + self.connectionRecovery = connectionRecovery self.backupData = backupData self.usdtRecoveryBackup = usdtRecoveryBackup self.uploadBackup = uploadBackup @@ -450,6 +457,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 @@ -467,7 +480,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() @@ -494,7 +507,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() @@ -523,6 +543,7 @@ class BackupService { try await PaykitUsdtPaymentService.shared.restoreBackup($0) } ) + _ = try await connectionRecoveryService.replay() try UsdtRecoveryRestoreGate.complete() await usdtWallet?.resumeAfterRecoveryRestore() markRestoreComplete(category: .usdt) @@ -532,9 +553,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..b6c8961ad6 --- /dev/null +++ b/Bitkit/Services/ConnectionRecoveryService.swift @@ -0,0 +1,325 @@ +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() async throws -> UUID { + guard wipeID == nil else { throw AdmissionError.busy } + let id = UUID() + wipeID = id + readyGeneration = nil + generation = UUID() + cancelActive?() + await drainActive?() + 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 + } + + 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") + 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") + guard defaults.string(forKey: "rapidGossipSyncUrl") == rgs else { throw failure("RGS settings could not be saved") } + } + 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/Utilities/AppReset.swift b/Bitkit/Utilities/AppReset.swift index f309a6f018..c097f4ab33 100644 --- a/Bitkit/Utilities/AppReset.swift +++ b/Bitkit/Utilities/AppReset.swift @@ -14,15 +14,27 @@ enum AppReset { session: SessionManager, toastType: Toast.ToastType = .success ) async throws { - try await PaykitSdkService.shared.withWalletWipe { - try await app.withMigrationSyncPausedForWipe { - await SettingsViewModel.shared.beginServerSettingsWipe() - defer { SettingsViewModel.shared.endServerSettingsWipe() } - try await wipeLocal(app: app, wallet: wallet, session: session, toastType: toastType) + try await withConnectionRecoveryPaused(recovery: .shared) { + try await PaykitSdkService.shared.withWalletWipe { + try await app.withMigrationSyncPausedForWipe { + try await wipeLocal(app: app, wallet: wallet, session: session, toastType: toastType) + } } } } + @MainActor + static func withConnectionRecoveryPaused( + recovery: ConnectionRecoveryService, + operation: () async throws -> Void + ) async throws { + let connectionWipe = try await recovery.beginWipe() + defer { recovery.endWipe(connectionWipe) } + await SettingsViewModel.shared.beginServerSettingsWipe() + defer { SettingsViewModel.shared.endServerSettingsWipe() } + try await operation() + } + @MainActor private static func wipeLocal( app: AppViewModel, diff --git a/Bitkit/Utilities/Keychain.swift b/Bitkit/Utilities/Keychain.swift index d1b717a353..745c4cf5c7 100644 --- a/Bitkit/Utilities/Keychain.swift +++ b/Bitkit/Utilities/Keychain.swift @@ -19,6 +19,7 @@ enum KeychainEntryType { case usdtPendingBackupRestore case paykitAllowanceState case pubkySecretKey + case connectionRecovery var storageKey: String { switch self { @@ -39,6 +40,7 @@ enum KeychainEntryType { case .usdtPendingBackupRestore: "usdt_pending_backup_restore" case .paykitAllowanceState: "paykit_allowance_state" case .pubkySecretKey: "pubky_secret_key" + case .connectionRecovery: "connection_recovery" } } } diff --git a/Bitkit/Views/Onboarding/WalletConnectionRecoveryView.swift b/Bitkit/Views/Onboarding/WalletConnectionRecoveryView.swift new file mode 100644 index 0000000000..53e341f377 --- /dev/null +++ b/Bitkit/Views/Onboarding/WalletConnectionRecoveryView.swift @@ -0,0 +1,133 @@ +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? + + 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(recovery.isBusy || editor == nil) + CustomButton(title: t("settings__es__button_reset"), variant: .secondary, + isDisabled: recovery.isBusy || editor == nil) + { + electrum = ElectrumConfigService().getDefaultServer().fullUrl + }.accessibilityIdentifier("RecoveryElectrumReset") + CustomButton(title: t("common__save"), isDisabled: recovery.isBusy || editor == nil) { + saveElectrum() + }.accessibilityIdentifier("RecoveryElectrumSave") + + BodyMText(t("settings__rgs__server_url")) + TextField("https://host", text: $rgs) + .textInputAutocapitalization(.never).autocorrectionDisabled() + .accessibilityIdentifier("RecoveryRgsInput") + .disabled(recovery.isBusy || editor == nil) + CustomButton(title: t("settings__es__button_reset"), variant: .secondary, + isDisabled: recovery.isBusy || editor == nil) + { + rgs = RgsConfigService().getDefaultServerUrl() + }.accessibilityIdentifier("RecoveryRgsReset") + CustomButton(title: t("common__save"), isDisabled: recovery.isBusy || editor == nil) { + 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: recovery.isBusy, isLoading: recovery.isBusy) { + work = Task { await onRetry() } + }.accessibilityIdentifier("RecoveryRetry") + } + } + } + .padding(16) + .bottomSafeAreaPadding() + .accessibilityElement(children: .contain) + .accessibilityIdentifier("WalletConnectionRecovery") + .onAppear(perform: load) + .onDisappear { work?.cancel() } + .onChange(of: electrum) { saved = false } + .onChange(of: rgs) { saved = false } + } + + private func load() { + do { + let value = try recovery.editor() + editor = value + electrum = value.electrum.fullUrl + rgs = value.rgs + } catch { + self.error = error.localizedDescription + } + } + + 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 let editor else { return } + 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 d08b171615..1219de0914 100644 --- a/Bitkit/Views/Onboarding/WalletRestoreError.swift +++ b/Bitkit/Views/Onboarding/WalletRestoreError.swift @@ -2,6 +2,7 @@ import SwiftUI struct WalletRestoreError: View { let onRetry: () async -> Void + var onConnectionSettings: (() -> Void)? var body: some View { VStack(spacing: 0) { @@ -23,6 +24,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..3c9b47fb3a --- /dev/null +++ b/BitkitTests/ConnectionRecoveryServiceTests.swift @@ -0,0 +1,645 @@ +@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 + } + + 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 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(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 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 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 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/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/changelog.d/next/connection-recovery.fixed.md b/changelog.d/next/connection-recovery.fixed.md new file mode 100644 index 0000000000..cdf42bf917 --- /dev/null +++ b/changelog.d/next/connection-recovery.fixed.md @@ -0,0 +1 @@ +Allow connection settings to be corrected during wallet recovery while preserving required backup restoration. 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..8a74cc28cb --- /dev/null +++ b/journeys/backup-restore/connection-recovery.xml @@ -0,0 +1,22 @@ + + + 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. Component tests do not execute this complete + authenticated journey, which remains unrun for this revision. + + + 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 + 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 + + From 9481b503d84ee9d9d30343e917ffd8d661eac188 Mon Sep 17 00:00:00 2001 From: benk10 Date: Tue, 27 Oct 2026 01:09:56 +0200 Subject: [PATCH 17/45] docs: number connection recovery changelog --- changelog.d/next/{connection-recovery.fixed.md => 1139.fixed.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changelog.d/next/{connection-recovery.fixed.md => 1139.fixed.md} (100%) diff --git a/changelog.d/next/connection-recovery.fixed.md b/changelog.d/next/1139.fixed.md similarity index 100% rename from changelog.d/next/connection-recovery.fixed.md rename to changelog.d/next/1139.fixed.md From 754a899182bb39869b37d1f3e9601afecad8c593 Mon Sep 17 00:00:00 2001 From: benk10 Date: Tue, 27 Oct 2026 15:18:53 +0200 Subject: [PATCH 18/45] fix: serialize backup observer cancellable mutations --- Bitkit/Services/BackupService.swift | 66 ++++++++++++++--------------- 1 file changed, 31 insertions(+), 35 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 94fe0d95a4..0c4a33ea8f 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -113,7 +113,7 @@ class BackupService { @MainActor weak var usdtWallet: UsdtWalletManager? private var backupJobs: [BackupCategory: Task] = [:] private var runningBackupTasks: [BackupCategory: Task] = [:] - private var cancellables = Set() + @MainActor private var cancellables = Set() private var periodicCheckTask: Task? private var isObserving = false private var isRestoring = false @@ -213,8 +213,10 @@ class BackupService { guard shouldStart == true else { return } Logger.debug("Start observing backup statuses and data store changes", context: "BackupService") - startBackupStatusObservers() - startDataStoreListeners() + await MainActor.run { + startBackupStatusObservers() + startDataStoreListeners() + } startPeriodicBackupFailureCheck() } } @@ -236,7 +238,7 @@ class BackupService { await walletBackupWriter.waitUntilIdle() await usdtBackupWriter.waitUntilIdle() guard shouldStop == true else { return } - cancellables.removeAll() + await MainActor.run { cancellables.removeAll() } Logger.debug("Stopped observing backup statuses and data store changes", context: "BackupService") } @@ -618,7 +620,7 @@ class BackupService { // MARK: - Private Methods - private func startBackupStatusObservers() { + @MainActor private func startBackupStatusObservers() { for category in BackupCategory.allCases { let categoryPublisher = backupStatusesPublisher .prepend(getAllBackupStatuses()) @@ -646,27 +648,24 @@ class BackupService { Logger.debug("Started \(BackupCategory.allCases.count) backup status observers", context: "BackupService") } - private func startDataStoreListeners() { - Task { @MainActor [weak self] in - guard let self else { return } - // SETTINGS - SettingsViewModel.shared.settingsPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) - .sink { [weak self] _ in - guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .settings) - } - .store(in: &cancellables) + @MainActor private func startDataStoreListeners() { + // SETTINGS + SettingsViewModel.shared.settingsPublisher + .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) + .sink { [weak self] _ in + guard let self, !self.shouldSkipBackup() else { return } + markBackupRequired(category: .settings) + } + .store(in: &cancellables) - // WIDGETS - SettingsViewModel.shared.widgetsPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) - .sink { [weak self] _ in - guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .widgets) - } - .store(in: &cancellables) - } + // WIDGETS + SettingsViewModel.shared.widgetsPublisher + .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) + .sink { [weak self] _ in + guard let self, !self.shouldSkipBackup() else { return } + markBackupRequired(category: .widgets) + } + .store(in: &cancellables) // Record requirements synchronously; the scheduled upload already has a debounce. WalletBackupChangeTracker.localChanges @@ -714,16 +713,13 @@ class BackupService { .store(in: &cancellables) // APP STATE (UserDefaults changes, etc.) - Task { @MainActor [weak self] in - guard let self else { return } - SettingsViewModel.shared.appStatePublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) - .sink { [weak self] _ in - guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .metadata) - } - .store(in: &cancellables) - } + SettingsViewModel.shared.appStatePublisher + .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) + .sink { [weak self] _ in + guard let self, !self.shouldSkipBackup() else { return } + markBackupRequired(category: .metadata) + } + .store(in: &cancellables) // BLOCKTANK CoreService.shared.blocktank.stateChangedPublisher From bfc4a5e87b2694cf4906d1c6aa784e2fa1c3e78b Mon Sep 17 00:00:00 2001 From: benk10 Date: Tue, 27 Oct 2026 19:52:39 +0200 Subject: [PATCH 19/45] fix: retain backup changes while stopped uploads drain --- Bitkit/Services/BackupService.swift | 10 ++-- BitkitTests/BackupServiceTests.swift | 69 ++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 4 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 03f1257119..873bb1a37f 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -113,7 +113,8 @@ class BackupService { @MainActor weak var usdtWallet: UsdtWalletManager? private var backupJobs: [BackupCategory: Task] = [:] private var runningBackupTasks: [BackupCategory: Task] = [:] - @MainActor private var cancellables = Set() + @MainActor private var dataStoreListeners = Set() + @MainActor private var statusListeners = Set() @MainActor private var periodicCheckTask: Task? @MainActor private var observationTask: Task? @MainActor private var isObserving = false @@ -212,7 +213,7 @@ class BackupService { guard !shouldSkipBackup(), !isObserving else { return } isObserving = true Logger.debug("Start observing backup statuses and data store changes", context: "BackupService") - cancellables.formUnion(listeners) + dataStoreListeners.formUnion(listeners) startBackupStatusObservers() startPeriodicBackupFailureCheck() } @@ -224,7 +225,7 @@ class BackupService { let stopping = Task { await previous?.value isObserving = false - cancellables.removeAll() + statusListeners.removeAll() periodicCheckTask?.cancel() periodicCheckTask = nil @@ -248,6 +249,7 @@ class BackupService { } await walletBackupWriter.waitUntilIdle() await usdtBackupWriter.waitUntilIdle() + dataStoreListeners.removeAll() try? await ServiceQueue.background(.backup) { self.isStoppingBackups = false } @@ -685,7 +687,7 @@ class BackupService { } } } - .store(in: &cancellables) + .store(in: &statusListeners) } Logger.debug("Started \(BackupCategory.allCases.count) backup status observers", context: "BackupService") diff --git a/BitkitTests/BackupServiceTests.swift b/BitkitTests/BackupServiceTests.swift index a8b78a243c..ec9ba4f2fd 100644 --- a/BitkitTests/BackupServiceTests.swift +++ b/BitkitTests/BackupServiceTests.swift @@ -352,6 +352,75 @@ final class BackupServiceTests: XCTestCase { XCTAssertEqual(uploads.map(\.data), [Data("initial".utf8), Data("updated".utf8)]) } + func testStopRetainsEditsUntilAcknowledgedUploadDrains() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let original = SettingsViewModel.shared.swipeBalanceToHide + defer { SettingsViewModel.shared.swipeBalanceToHide = original } + let entered = expectation(description: "Captured settings upload entered") + let cancelled = expectation(description: "Stop cancelled the held upload") + let unexpectedUpload = expectation(description: "Stopped observers cannot upload new data") + unexpectedUpload.isInverted = true + let gate = BackupDelayGate() + let recorder = BackupRecorder() + var data = Data("initial".utf8) + var holdUpload = false + var mayUploadLatest = false + let service = BackupService(defaults: defaults, backupData: { _ in data }, uploadBackup: { key, bytes in + await recorder.recordUpload(key: key, data: bytes) + if bytes == Data("latest".utf8), !mayUploadLatest { + unexpectedUpload.fulfill() + } + if holdUpload, key == BackupCategory.settings.rawValue { + holdUpload = false + await withTaskCancellationHandler { + await gate.wait(started: entered) + } onCancel: { cancelled.fulfill() } + } + }, waitForBackupDelay: {}) + await service.triggerBackup(category: .settings) + await service.triggerBackup(category: .wallet) + service.startObservingBackups() + holdUpload = true + data = Data("captured".utf8) + SettingsViewModel.shared.swipeBalanceToHide = !original + await fulfillment(of: [entered], timeout: 2) + let stop = Task { await service.stopObservingBackups() } + await fulfillment(of: [cancelled], timeout: 2) + + data = Data("latest".utf8) + SettingsViewModel.shared.swipeBalanceToHide = original + try Bitkit.WatchOnlyAccountStore.save([], defaults: defaults) + XCTAssertTrue(service.getBackupStatus(category: .settings).isRequired) + XCTAssertTrue(service.getBackupStatus(category: .wallet).isRequired) + await gate.release() + await stop.value + for category in [BackupCategory.settings, .wallet] { + XCTAssertTrue(service.getBackupStatus(category: category).isRequired) + XCTAssertFalse(service.getBackupStatus(category: category).running) + } + await fulfillment(of: [unexpectedUpload], timeout: 0.1) + let stoppedUploads = await recorder.uploads + XCTAssertEqual(stoppedUploads.map(\.data), [Data("initial".utf8), Data("initial".utf8), Data("captured".utf8)]) + + mayUploadLatest = true + let completed = expectation(description: "Restart uploads both latest sources") + let subscription = service.backupStatusesPublisher + .filter { statuses in + [BackupCategory.settings, .wallet].allSatisfy { category in + statuses[category].map { !$0.isRequired && !$0.running } == true + } + }.first().sink { _ in completed.fulfill() } + service.startObservingBackups() + await fulfillment(of: [completed], timeout: 2) + subscription.cancel() + await service.stopObservingBackups() + let latest = await recorder.uploads.filter { $0.data == Data("latest".utf8) } + XCTAssertEqual(Set(latest.map(\.key)), [BackupCategory.settings.rawValue, BackupCategory.wallet.rawValue]) + XCTAssertEqual(latest.count, 2) + } + func testCancelledUploadRetainsNewerSettingsAfterRestart() async throws { let suite = "BackupServiceTests.\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) From 911f24cdd7d25b0c218903493e868c70a9cd6c28 Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 28 Oct 2026 01:07:43 +0200 Subject: [PATCH 20/45] fix: preserve readiness after activity sync errors --- Bitkit/AppScene.swift | 2 +- .../Services/ConnectionRecoveryService.swift | 4 ++ .../ConnectionRecoveryServiceTests.swift | 53 +++++++++++++++++++ 3 files changed, 58 insertions(+), 1 deletion(-) diff --git a/Bitkit/AppScene.swift b/Bitkit/AppScene.swift index 0dc8e78012..dfbb4503e3 100644 --- a/Bitkit/AppScene.swift +++ b/Bitkit/AppScene.swift @@ -1095,7 +1095,7 @@ struct AppScene: View { } catch { guard connectionRecovery.canReportOperationFailure() else { return } Logger.error(error, context: "Failed to start wallet") - if walletIsInitializing == true { + if walletIsInitializing == true, connectionRecovery.canReportStartupFailure() { didWalletBackupRestoreFail = true } if playsErrorHaptic { diff --git a/Bitkit/Services/ConnectionRecoveryService.swift b/Bitkit/Services/ConnectionRecoveryService.swift index 0f5f818eb2..6ce06a856f 100644 --- a/Bitkit/Services/ConnectionRecoveryService.swift +++ b/Bitkit/Services/ConnectionRecoveryService.swift @@ -261,6 +261,10 @@ final class ConnectionRecoveryService: ObservableObject { 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) diff --git a/BitkitTests/ConnectionRecoveryServiceTests.swift b/BitkitTests/ConnectionRecoveryServiceTests.swift index f25c275266..90ac51c843 100644 --- a/BitkitTests/ConnectionRecoveryServiceTests.swift +++ b/BitkitTests/ConnectionRecoveryServiceTests.swift @@ -451,6 +451,59 @@ final class ConnectionRecoveryServiceTests: XCTestCase { 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) From e7d5595bf9419f628d5f1941e79d2b25824139d4 Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 28 Oct 2026 12:44:36 +0200 Subject: [PATCH 21/45] fix: defer wallet creation while offline --- Bitkit/AppScene.swift | 3 --- changelog.d/next/1139.fixed.md | 2 +- journeys/backup-restore/connection-recovery.xml | 1 + 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Bitkit/AppScene.swift b/Bitkit/AppScene.swift index dfbb4503e3..46d35651fa 100644 --- a/Bitkit/AppScene.swift +++ b/Bitkit/AppScene.swift @@ -1057,9 +1057,6 @@ struct AppScene: View { // Check network before attempting to start - LDK hangs when VSS is unreachable guard network.isConnected else { Logger.warn("Network offline, skipping wallet start", context: "AppScene") - if walletIsInitializing == true { - didWalletBackupRestoreFail = true - } if MigrationsService.shared.isShowingMigrationLoading { await MainActor.run { MigrationsService.shared.isShowingMigrationLoading = false diff --git a/changelog.d/next/1139.fixed.md b/changelog.d/next/1139.fixed.md index cdf42bf917..a8f04effe3 100644 --- a/changelog.d/next/1139.fixed.md +++ b/changelog.d/next/1139.fixed.md @@ -1 +1 @@ -Allow connection settings to be corrected during wallet recovery while preserving required backup restoration. +Allow connection settings to be corrected during wallet recovery while preserving required backup restoration. Offline wallet creation waits for connectivity instead of reporting a backup restoration failure. diff --git a/journeys/backup-restore/connection-recovery.xml b/journeys/backup-restore/connection-recovery.xml index 3402c59bb2..bac713b583 100644 --- a/journeys/backup-restore/connection-recovery.xml +++ b/journeys/backup-restore/connection-recovery.xml @@ -22,5 +22,6 @@ 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 From 753d6d1f3dfa1b6ba2f39f608ab657251972897a Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 28 Oct 2026 12:49:23 +0200 Subject: [PATCH 22/45] docs: condense recovery changelog entry --- changelog.d/next/1139.fixed.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog.d/next/1139.fixed.md b/changelog.d/next/1139.fixed.md index a8f04effe3..cf772ec9b4 100644 --- a/changelog.d/next/1139.fixed.md +++ b/changelog.d/next/1139.fixed.md @@ -1 +1 @@ -Allow connection settings to be corrected during wallet recovery while preserving required backup restoration. Offline wallet creation waits for connectivity instead of reporting a backup restoration failure. +Allow connection settings to be corrected during wallet recovery while preserving required backup restoration, and keep offline wallet creation waiting for connectivity without reporting a restoration failure. From 0b77f099edcb76daf06f13421e4f2291d22e81c6 Mon Sep 17 00:00:00 2001 From: benk10 Date: Thu, 29 Oct 2026 00:36:09 +0200 Subject: [PATCH 23/45] fix: retry missing profiles after reconnect --- Bitkit/Managers/PubkyProfileManager.swift | 12 ++- BitkitTests/PubkyProfileManagerTests.swift | 75 +++++++++++++++++++ changelog.d/next/1121.fixed.md | 2 +- .../wallet/restore-during-identity-outage.xml | 1 + 4 files changed, 88 insertions(+), 2 deletions(-) diff --git a/Bitkit/Managers/PubkyProfileManager.swift b/Bitkit/Managers/PubkyProfileManager.swift index d29dd6b1e0..0e4e3ac650 100644 --- a/Bitkit/Managers/PubkyProfileManager.swift +++ b/Bitkit/Managers/PubkyProfileManager.swift @@ -287,7 +287,17 @@ class PubkyProfileManager: ObservableObject { if completedRecoveryVersion != recoveryVersion, revision == Self.sessionRevision { return } - guard !Task.isCancelled, publicKey == nil, authState == .idle, Self.sessionMutationCount == 0 else { return } + guard !Task.isCancelled else { return } + if let session = automaticPaykitSession { + if isInitialized, profile == nil { + Task { + guard automaticPaykitSession == session, isInitialized, profile == nil else { return } + await loadProfile() + } + } + return + } + guard publicKey == nil, authState == .idle, Self.sessionMutationCount == 0 else { return } do { guard try hasStoredIdentity() else { return } await initialize(mode: .automaticRecovery, initializeSession: initializeSession) diff --git a/BitkitTests/PubkyProfileManagerTests.swift b/BitkitTests/PubkyProfileManagerTests.swift index d8357df8de..c80845e665 100644 --- a/BitkitTests/PubkyProfileManagerTests.swift +++ b/BitkitTests/PubkyProfileManagerTests.swift @@ -1802,6 +1802,67 @@ final class PubkyProfileManagerTests: XCTestCase { } } + @MainActor + func testSessionRecoveryReloadsMissingProfileWithoutReauthenticationOrWaiting() async { + await withRestoredProfileDefaults { + let stub = RemoteProfileStub(profiles: [ringKeyA: makeProfile(publicKey: ringKeyA, name: "Recovered")]) + await stub.makeUnreachable(ringKeyA) + let manager = PubkyProfileManager(remoteProfileResolver: { try await stub.resolve($0) }) + manager.publicKey = ringKeyA + manager.authState = .authenticated + manager.isInitialized = true + let session = manager.currentSession + await manager.loadProfile() + XCTAssertNil(manager.profile) + + await stub.makeReachable(ringKeyA) + await stub.setHoldsRequests(true) + for _ in 0 ..< 3 { + await manager.restoreSessionIfNeeded(hasStoredIdentity: { + XCTFail("An active identity must not inspect or import saved credentials") + return false + }) + } + await stub.waitForRequests(2) + XCTAssertTrue(manager.isLoadingProfile) + XCTAssertEqual(manager.currentSession, session) + let heldRequests = await stub.requests + XCTAssertEqual(heldRequests, [ringKeyA, ringKeyA]) + + await stub.release(request: 1) + await waitUntil("the missing profile recovers") { manager.profile?.name == "Recovered" } + await manager.restoreSessionIfNeeded() + await Task.yield() + let completedRequests = await stub.requests + XCTAssertEqual(completedRequests, [ringKeyA, ringKeyA]) + XCTAssertEqual(manager.cachedName, "Recovered") + } + } + + @MainActor + func testSessionRecoveryDropsMissingProfileResultFromClearedStateWithSameKey() async { + await withRestoredProfileDefaults { + let stub = RemoteProfileStub( + profiles: [ringKeyA: makeProfile(publicKey: ringKeyA, name: "Stale")], + holdsRequests: true + ) + let manager = ObservedProfileReadManager(remoteProfileResolver: { try await stub.resolve($0) }) + manager.publicKey = ringKeyA + manager.authState = .authenticated + manager.isInitialized = true + + await manager.restoreSessionIfNeeded() + await stub.waitForRequests(1) + manager.clearAuthenticatedStateForTesting() + manager.publicKey = ringKeyA + manager.authState = .authenticated + await stub.release(request: 0) + await waitUntil("the old profile read finishes") { manager.completedReads == 1 } + XCTAssertNil(manager.profile) + XCTAssertNil(manager.cachedName) + } + } + // MARK: - Profile saves /// The review regression: a remembered Ring profile with tags was removed remotely. Adoption reuses its cached row and @@ -4250,6 +4311,10 @@ private actor RemoteProfileStub { unreachableKeys.insert(key) } + func makeReachable(_ key: String) { + unreachableKeys.remove(key) + } + func waitForRequests(_ count: Int, file: StaticString = #filePath, line: UInt = #line) async { guard requests.count < count else { return } let id = UUID() @@ -4440,3 +4505,13 @@ private actor SessionRecoveryAttempts { return count } } + +@MainActor +private final class ObservedProfileReadManager: PubkyProfileManager { + private(set) var completedReads = 0 + + override func loadProfile() async { + await super.loadProfile() + completedReads += 1 + } +} diff --git a/changelog.d/next/1121.fixed.md b/changelog.d/next/1121.fixed.md index 7d934b9487..5afda00c45 100644 --- a/changelog.d/next/1121.fixed.md +++ b/changelog.d/next/1121.fixed.md @@ -1 +1 @@ -Wallet restore finishes without waiting for optional profile refresh, while incomplete identity data cannot replace complete backups. +Wallet restore finishes without waiting for optional profile refresh, retries missing profile data after reconnecting, and preserves complete backups when identity data is unavailable. diff --git a/journeys/wallet/restore-during-identity-outage.xml b/journeys/wallet/restore-during-identity-outage.xml index fcaad5e534..e549f8d36a 100644 --- a/journeys/wallet/restore-during-identity-outage.xml +++ b/journeys/wallet/restore-during-identity-outage.xml @@ -11,6 +11,7 @@ Restore the complete backup and hold final identity activation; verify ordinary wallet access resumes after required recovery completes, without reporting Paykit authenticated or payment-ready Trigger a full backup while the saved identity cannot be exported; verify failure retains the previous complete WALLET record and required pending backup work Close the restore screen, release the identity fault and verify retained work completes and a fresh complete backup succeeds once + Fail the restored identity's own public profile read, then reconnect or resume while staying on Home; verify wallet maintenance continues while the read is held, and the saved profile replaces the placeholder after release without opening Profile or re-importing the active session Repeat with delayed profile/contact enrichment, then replace or remove the identity; verify late results cannot republish the old identity or overwrite current profile data Restart during the outage; verify saved credentials resume recovery without duplicating a payment or contact mutation Fail a required wallet or USDT restore instead; verify spending and address allocation remain gated and retry resumes the same required recovery From a2b218613ecdeb0a45cd9364d723204147b27044 Mon Sep 17 00:00:00 2001 From: benk10 Date: Thu, 29 Oct 2026 03:48:46 +0200 Subject: [PATCH 24/45] fix: refuse profile removal with active subscriptions --- Bitkit/Managers/ContactsManager.swift | 2 +- Bitkit/Managers/PubkyProfileManager.swift | 13 ++- .../Localization/ar.lproj/Localizable.strings | 1 + .../Localization/ca.lproj/Localizable.strings | 1 + .../Localization/cs.lproj/Localizable.strings | 1 + .../Localization/de.lproj/Localizable.strings | 1 + .../Localization/el.lproj/Localizable.strings | 1 + .../Localization/en.lproj/Localizable.strings | 1 + .../es-419.lproj/Localizable.strings | 1 + .../Localization/es.lproj/Localizable.strings | 1 + .../Localization/fr.lproj/Localizable.strings | 1 + .../Localization/it.lproj/Localizable.strings | 1 + .../Localization/nl.lproj/Localizable.strings | 1 + .../Localization/pl.lproj/Localizable.strings | 1 + .../pt-BR.lproj/Localizable.strings | 1 + .../Localization/pt.lproj/Localizable.strings | 1 + .../Localization/ru.lproj/Localizable.strings | 1 + Bitkit/Services/PubkyService.swift | 34 ++++++++ Bitkit/Views/Profile/EditProfileView.swift | 5 +- BitkitTests/PaykitSdkIdentityCheckTests.swift | 85 +++++++++++++++++++ BitkitTests/PubkyProfileManagerTests.swift | 48 ++++++++++- changelog.d/next/1124.fixed.md | 2 +- journeys/profile/profile-cleanup-failure.xml | 9 +- 23 files changed, 204 insertions(+), 9 deletions(-) diff --git a/Bitkit/Managers/ContactsManager.swift b/Bitkit/Managers/ContactsManager.swift index a87e33f265..fde215be33 100644 --- a/Bitkit/Managers/ContactsManager.swift +++ b/Bitkit/Managers/ContactsManager.swift @@ -193,7 +193,7 @@ class ContactsManager: ObservableObject { _ = try await PubkyService.removeContact(publicKey: $0) }, removeContactRecords: @escaping @Sendable (_ publicKeys: [String]) async throws -> [ContactRecord] = { - try await PubkyService.removeContacts(publicKeys: $0) + try await PubkyService.removeContactsForProfile(publicKeys: $0) }, forgetRemovedContacts: @escaping @Sendable (_ publicKeys: [String]) async -> Void = { await PrivatePaykitService.shared.removeSavedContacts(publicKeys: $0) diff --git a/Bitkit/Managers/PubkyProfileManager.swift b/Bitkit/Managers/PubkyProfileManager.swift index 54fb3f7113..5573bc9008 100644 --- a/Bitkit/Managers/PubkyProfileManager.swift +++ b/Bitkit/Managers/PubkyProfileManager.swift @@ -121,6 +121,7 @@ class PubkyProfileManager: ObservableObject { private let remoteProfileResolver: RemoteProfileResolver private let profilePublisher: ProfilePublisher private let avatarUploader: AvatarUploader + private let profileDeletionValidator: ProfileDeleter private let profileDeleter: ProfileDeleter /// Bumped whenever a profile save starts, `profile` is written or the identity changes, so a remote read that started /// earlier is dropped. @@ -157,6 +158,9 @@ class PubkyProfileManager: ObservableObject { avatarUploader: @escaping AvatarUploader = { try await PubkyService.uploadProfileAvatar(bytes: $0, contentType: "image/jpeg", expectedIdentity: $1) }, + profileDeletionValidator: @escaping ProfileDeleter = { + try await PubkyService.requireNoActiveSubscriptions(expectedIdentity: $0) + }, profileDeleter: @escaping ProfileDeleter = { try await PubkyService.deletePaykitProfile(expectedIdentity: $0) } @@ -164,6 +168,7 @@ class PubkyProfileManager: ObservableObject { self.remoteProfileResolver = remoteProfileResolver self.profilePublisher = profilePublisher self.avatarUploader = avatarUploader + self.profileDeletionValidator = profileDeletionValidator self.profileDeleter = profileDeleter cachedName = UserDefaults.standard.string(forKey: Self.cachedNameKey) cachedImageUri = UserDefaults.standard.string(forKey: Self.cachedImageUriKey) @@ -1045,6 +1050,12 @@ class PubkyProfileManager: ObservableObject { await PrivatePaykitService.shared.endProfileDeletion() } + func validateProfileDeletion(for session: SignedInSession) async throws { + try requireCurrentSession(session) + try await profileDeletionValidator(session.publicKey) + try requireCurrentSession(session) + } + func deleteProfile(cleanPrivatePaykitEndpoints: Bool = true, expectedSession: SignedInSession? = nil) async throws { guard let session = expectedSession ?? currentSession else { throw PubkyServiceError.sessionNotActive } try requireCurrentSession(session) @@ -1060,7 +1071,7 @@ class PubkyProfileManager: ObservableObject { } private func deleteProfile(for session: SignedInSession, cleanPrivatePaykitEndpoints: Bool) async throws { - try requireCurrentSession(session) + try await validateProfileDeletion(for: session) if cleanPrivatePaykitEndpoints { try await Self.removePrivatePaykitEndpoints( context: "PubkyProfileManager.deleteProfile", deferAppSync: true, diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index 6961ba37d2..ce6d0097b6 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -946,6 +946,7 @@ "profile__edit_delete_section" = "حذف"; "profile__edit_unlink_section" = "إلغاء الربط"; "profile__edit_public_note" = "يرجى ملاحظة أن معلومات الملف الشخصي مخزنة في ملفات عامة."; +"profile__delete_active_subscription" = "أنه الاشتراكات النشطة قبل إزالة هذا الملف الشخصي."; "profile__delete_title" = "حذف الملف الشخصي؟"; "profile__delete_description" = "يؤدي حذف ملفك الشخصي إلى إزالته من Pubky. قد تحتفظ جهات الاتصال بمعلومات الملف الشخصي والدفع التي شاركتها معهم سابقًا."; "profile__delete_confirm" = "نعم، احذف"; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index 651052fb4b..d068ddbe8c 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -1062,6 +1062,7 @@ "profile__edit_delete_section" = "ELIMINAR"; "profile__edit_unlink_section" = "DESVINCULAR"; "profile__edit_public_note" = "Tingues en compte que la informació del perfil es desa en fitxers públics."; +"profile__delete_active_subscription" = "Finalitza les subscripcions actives abans d’eliminar aquest perfil."; "profile__delete_title" = "Eliminar el perfil?"; "profile__delete_description" = "Eliminar el teu perfil l'esborra de Pubky. És possible que els contactes conservin la informació de perfil i de pagament que s'hi hagi compartit abans."; "profile__delete_confirm" = "Sí, elimina"; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index 274ca916d4..b200d53045 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -1167,6 +1167,7 @@ "profile__edit_delete_section" = "SMAZAT"; "profile__edit_unlink_section" = "ZRUŠIT PROPOJENÍ"; "profile__edit_public_note" = "Upozorňujeme, že informace o profilu jsou uloženy ve veřejných souborech."; +"profile__delete_active_subscription" = "Před odstraněním tohoto profilu ukončete aktivní předplatná."; "profile__delete_title" = "Smazat profil?"; "profile__delete_description" = "Smazáním profilu ho odstraníte z Pubky. Kontakty si mohou ponechat informace o profilu a platbách, které jste s nimi dříve sdíleli."; "profile__delete_confirm" = "Ano, smazat"; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index 01009c4ce7..79514b702f 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -1165,6 +1165,7 @@ "profile__edit_delete_section" = "LÖSCHEN"; "profile__edit_unlink_section" = "VERKNÜPFUNG AUFHEBEN"; "profile__edit_public_note" = "Bitte beachte, dass Profilinformationen in öffentlichen Dateien gespeichert werden."; +"profile__delete_active_subscription" = "Beende aktive Abonnements, bevor du dieses Profil entfernst."; "profile__delete_title" = "Profil löschen?"; "profile__delete_description" = "Durch das Löschen deines Profils wird es von Pubky entfernt. Kontakte können zuvor mit ihnen geteilte Profil- und Zahlungsinformationen weiterhin behalten."; "profile__delete_confirm" = "Ja, löschen"; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index 5a70bbd052..eb4e336741 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -963,6 +963,7 @@ "profile__edit_delete_section" = "ΔΙΑΓΡΑΦΗ"; "profile__edit_unlink_section" = "ΑΠΟΣΥΝΔΕΣΗ"; "profile__edit_public_note" = "Τα στοιχεία του προφίλ αποθηκεύονται σε δημόσια αρχεία."; +"profile__delete_active_subscription" = "Τερμάτισε τις ενεργές συνδρομές πριν αφαιρέσεις αυτό το προφίλ."; "profile__delete_title" = "Διαγραφή Προφίλ;"; "profile__delete_description" = "Η διαγραφή του προφίλ σας το αφαιρεί από το Pubky. Οι επαφές μπορεί να διατηρούν ακόμα πληροφορίες προφίλ και πληρωμών που τους κοινοποιήθηκαν παλαιότερα."; "profile__delete_confirm" = "Ναι, Διαγραφή"; diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings index cec4fe8cf1..2c3388dc1d 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -1180,6 +1180,7 @@ "profile__edit_delete_section" = "DELETE"; "profile__edit_unlink_section" = "UNLINK"; "profile__edit_public_note" = "Please note profile information is stored in public files."; +"profile__delete_active_subscription" = "End active subscriptions before removing this profile."; "profile__delete_title" = "Delete Profile?"; "profile__delete_description" = "Deleting your profile removes it from Pubky. Contacts may still retain profile and payment information previously shared with them."; "profile__delete_confirm" = "Yes, Delete"; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index 97b79caa8b..09d802a6eb 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -1170,6 +1170,7 @@ "profile__edit_delete_section" = "ELIMINAR"; "profile__edit_unlink_section" = "DESVINCULAR"; "profile__edit_public_note" = "Tenga en cuenta que la información del perfil se guarda en archivos públicos."; +"profile__delete_active_subscription" = "Finaliza las suscripciones activas antes de eliminar este perfil."; "profile__delete_title" = "¿Eliminar perfil?"; "profile__delete_description" = "Al eliminar su perfil, se borra de Pubky. Es posible que sus contactos conserven la información de perfil y de pago que compartió con ellos anteriormente."; "profile__delete_confirm" = "Sí, eliminar"; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index fe2d64fa17..1d2ee2fdc9 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -1079,6 +1079,7 @@ "profile__edit_delete_section" = "ELIMINAR"; "profile__edit_unlink_section" = "DESVINCULAR"; "profile__edit_public_note" = "Tenga en cuenta que la información del perfil se guarda en archivos públicos."; +"profile__delete_active_subscription" = "Finaliza las suscripciones activas antes de eliminar este perfil."; "profile__delete_title" = "¿Eliminar el perfil?"; "profile__delete_description" = "Al eliminar su perfil, se elimina de Pubky. Es posible que sus contactos conserven la información de perfil y de pago que compartió con ellos anteriormente."; "profile__delete_confirm" = "Sí, eliminar"; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index 1d45f068a8..ab085fc068 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -1178,6 +1178,7 @@ "profile__edit_delete_section" = "SUPPRIMER"; "profile__edit_unlink_section" = "DISSOCIER"; "profile__edit_public_note" = "Veuillez noter que les informations de profil sont stockées dans des fichiers publics."; +"profile__delete_active_subscription" = "Mettez fin aux abonnements actifs avant de supprimer ce profil."; "profile__delete_title" = "Supprimer le profil ?"; "profile__delete_description" = "La suppression de votre profil le retire de Pubky. Vos contacts peuvent encore conserver les informations de profil et de paiement que vous leur avez partagées."; "profile__delete_confirm" = "Oui, supprimer"; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index 24dc9c6aa2..d47a4a60f7 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -1144,6 +1144,7 @@ "profile__edit_delete_section" = "ELIMINA"; "profile__edit_unlink_section" = "SCOLLEGA"; "profile__edit_public_note" = "Tieni presente che le informazioni del profilo sono salvate in file pubblici."; +"profile__delete_active_subscription" = "Termina gli abbonamenti attivi prima di rimuovere questo profilo."; "profile__delete_title" = "Eliminare il Profilo?"; "profile__delete_description" = "Eliminando il profilo lo rimuovi da Pubky. I contatti potrebbero conservare le informazioni di profilo e di pagamento condivise in precedenza con loro."; "profile__delete_confirm" = "Sì, Elimina"; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index e37f02521a..65c63cc45a 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -1173,6 +1173,7 @@ "profile__edit_delete_section" = "VERWIJDEREN"; "profile__edit_unlink_section" = "ONTKOPPELEN"; "profile__edit_public_note" = "Let op: profielgegevens worden opgeslagen in openbare bestanden."; +"profile__delete_active_subscription" = "Beëindig actieve abonnementen voordat je dit profiel verwijdert."; "profile__delete_title" = "Profiel verwijderen?"; "profile__delete_description" = "Als u uw profiel verwijdert, wordt het van Pubky verwijderd. Contacten kunnen eerder gedeelde profiel- en betaalgegevens nog bewaren."; "profile__delete_confirm" = "Ja, verwijderen"; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index e5e7d923f0..2320c034da 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -1177,6 +1177,7 @@ "profile__edit_delete_section" = "USUWANIE"; "profile__edit_unlink_section" = "ODŁĄCZANIE"; "profile__edit_public_note" = "Pamiętaj, że dane profilu są przechowywane w publicznych plikach."; +"profile__delete_active_subscription" = "Zakończ aktywne subskrypcje przed usunięciem tego profilu."; "profile__delete_title" = "Usunąć profil?"; "profile__delete_description" = "Usunięcie profilu usuwa go z Pubky. Kontakty mogą nadal przechowywać udostępnione im wcześniej dane profilu i płatności."; "profile__delete_confirm" = "Tak, usuń"; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index 3fa83ecf1a..c7a060fe17 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -1178,6 +1178,7 @@ "profile__edit_delete_section" = "EXCLUIR"; "profile__edit_unlink_section" = "DESVINCULAR"; "profile__edit_public_note" = "Observe que as informações do perfil são armazenadas em arquivos públicos."; +"profile__delete_active_subscription" = "Encerre as assinaturas ativas antes de remover este perfil."; "profile__delete_title" = "Excluir Perfil?"; "profile__delete_description" = "Excluir seu perfil o remove do Pubky. Os contatos ainda podem manter informações de perfil e de pagamento compartilhadas anteriormente com eles."; "profile__delete_confirm" = "Sim, Excluir"; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index 3d4393d859..951c738639 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -938,6 +938,7 @@ "profile__edit_delete_section" = "ELIMINAR"; "profile__edit_unlink_section" = "DESASSOCIAR"; "profile__edit_public_note" = "Tenha em atenção que as informações do perfil são guardadas em ficheiros públicos."; +"profile__delete_active_subscription" = "Termina as subscrições ativas antes de remover este perfil."; "profile__delete_title" = "Eliminar perfil?"; "profile__delete_description" = "Eliminar o seu perfil remove-o do Pubky. Os contactos podem manter as informações de perfil e pagamento partilhadas anteriormente com eles."; "profile__delete_confirm" = "Sim, Excluir"; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index c35cebdc4b..9d9a10028e 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -1163,6 +1163,7 @@ "profile__edit_delete_section" = "УДАЛЕНИЕ"; "profile__edit_unlink_section" = "ОТВЯЗКА"; "profile__edit_public_note" = "Обратите внимание: данные профиля хранятся в публичных файлах."; +"profile__delete_active_subscription" = "Завершите активные подписки перед удалением этого профиля."; "profile__delete_title" = "Удалить Профиль?"; "profile__delete_description" = "Удаление профиля удалит его из Pubky. У контактов могут остаться данные профиля и платёжные данные, которыми вы делились ранее."; "profile__delete_confirm" = "Да, Удалить"; diff --git a/Bitkit/Services/PubkyService.swift b/Bitkit/Services/PubkyService.swift index 3813f6b704..5e3ee269b2 100644 --- a/Bitkit/Services/PubkyService.swift +++ b/Bitkit/Services/PubkyService.swift @@ -346,6 +346,10 @@ enum PubkyService { try await PaykitSdkService.shared.uploadAvatar(bytes: bytes, contentType: contentType, expectedIdentity: expectedIdentity) } + static func requireNoActiveSubscriptions(expectedIdentity: String) async throws { + try await PaykitSdkService.shared.requireNoActiveSubscriptions(expectedIdentity: expectedIdentity) + } + static func deletePaykitProfile(expectedIdentity: String? = nil) async throws { try await PaykitSdkService.shared.deletePaykitProfile(expectedIdentity: expectedIdentity) } @@ -383,6 +387,10 @@ enum PubkyService { try await PaykitSdkService.shared.removeContact(publicKey: publicKey) } + static func removeContactsForProfile(publicKeys: [String]) async throws -> [Paykit.ContactRecord] { + try await PaykitSdkService.shared.removeContactsForProfile(publicKeys: publicKeys) + } + static func removeContacts(publicKeys: [String]) async throws -> [Paykit.ContactRecord] { try await PaykitSdkService.shared.removeContacts(publicKeys: publicKeys) } @@ -804,11 +812,29 @@ actor PaykitSdkService { return record.uri } + func requireNoActiveSubscriptions(expectedIdentity: String) async throws { + try await withStateRevisionTracking { sdk in + try await Self.requireSignedInIdentity(expectedIdentity, in: sdk) + try await Self.requireNoActiveSubscriptions(in: sdk) + } + } + + private static func requireNoActiveSubscriptions(in sdk: PaykitSdk) async throws { + let requests = try await sdk.paymentRequests() + try Task.checkCancellation() + let now = Date() + guard !requests.contains(where: { + $0.state == .activeRecurring && + ($0.terms?.recurrence?.endsAt.flatMap(PaykitPaymentRequest.parseDate).map { $0 > now } ?? true) + }) else { throw PubkyServiceError.activeSubscription(endsAt: nil) } + } + func deletePaykitProfile(expectedIdentity: String? = nil) async throws { try await withStateRevisionTracking { sdk in if let expectedIdentity { try await Self.requireSignedInIdentity(expectedIdentity, in: sdk) } + try await Self.requireNoActiveSubscriptions(in: sdk) guard let publicKey = try await sdk.identityStatus()?.publicKey else { throw PubkyServiceError.sessionNotActive } guard let current = try await sdk.fetchPaykitProfile(publicKey: publicKey) else { return } try await sdk.deletePaykitProfile(expectedRevision: current.revision) @@ -929,6 +955,14 @@ actor PaykitSdkService { } } + func removeContactsForProfile(publicKeys: [String]) async throws -> [Paykit.ContactRecord] { + try await withStateRevisionTracking { sdk in + try await Self.requireNoActiveSubscriptions(in: sdk) + guard !publicKeys.isEmpty else { return [] } + return try await sdk.removeContactsAndBlockPeers(publicKeys: publicKeys) + } + } + func removeContacts(publicKeys: [String]) async throws -> [Paykit.ContactRecord] { guard !publicKeys.isEmpty else { return [] } return try await withStateRevisionTracking { sdk in diff --git a/Bitkit/Views/Profile/EditProfileView.swift b/Bitkit/Views/Profile/EditProfileView.swift index 092006c0f4..0db9252a92 100644 --- a/Bitkit/Views/Profile/EditProfileView.swift +++ b/Bitkit/Views/Profile/EditProfileView.swift @@ -160,6 +160,9 @@ struct EditProfileView: View { try await pubkyProfile.performProfileDeletion { do { try await performDeleteProfile(session: session) + } catch PubkyServiceError.activeSubscription { + guard !Task.isCancelled, pubkyProfile.currentSession == session else { return } + app.toast(type: .error, title: t("profile__delete_active_subscription")) } catch { guard !Task.isCancelled, pubkyProfile.publicKey == session.publicKey else { return } Logger.error("Failed to delete profile: \(error)", context: "EditProfileView") @@ -189,7 +192,7 @@ struct EditProfileView: View { contactsManager: ContactsManager, removePrivateEndpoints: () async throws -> Void ) async throws { - try pubkyProfile.requireCurrentSession(session) + try await pubkyProfile.validateProfileDeletion(for: session) try await removePrivateEndpoints() try pubkyProfile.requireCurrentSession(session) try await contactsManager.deleteAllContacts() diff --git a/BitkitTests/PaykitSdkIdentityCheckTests.swift b/BitkitTests/PaykitSdkIdentityCheckTests.swift index fcd7620275..670794574f 100644 --- a/BitkitTests/PaykitSdkIdentityCheckTests.swift +++ b/BitkitTests/PaykitSdkIdentityCheckTests.swift @@ -440,6 +440,80 @@ final class PaykitSdkIdentityCheckTests: XCTestCase { XCTAssertEqual(sdk.writes, ["upload"]) } + func testProfileDeletionRefusesActiveSubscriptionsInEitherRoleWithoutContacts() async throws { + for role in [PaymentRequestLocalRole.payer, .payee] { + let sdk = IdentitySwitchingSdk(noPointer: .init()) + sdk.identity = identityA + sdk.profileExists = true + var request = try paymentRequestRecord(appId: "another-app") + request.localRole = role + request.state = .activeRecurring + sdk.rawPaymentRequests = { [request] } + let service = PaykitSdkService(sdkFactory: { sdk }) + + do { + try await service.deletePaykitProfile(expectedIdentity: identityA) + XCTFail("An active subscription must prevent profile deletion even without a contact") + } catch PubkyServiceError.activeSubscription {} + XCTAssertTrue(sdk.writes.isEmpty) + } + } + + func testProfileCleanupChecksAllSubscriptionsBeforeRemovingAnyContact() async throws { + for endsAt in [nil, "invalid", "9999-01-01T00:00:00Z", "2000-01-01T00:00:00Z"] as [String?] { + let sdk = IdentitySwitchingSdk(noPointer: .init()) + sdk.identity = identityA + sdk.profileExists = true + var request = try paymentRequestRecord(appId: "another-app") + request.state = .activeRecurring + request.terms?.recurrence = PaymentRequestRecurrence( + every: 1, unit: "month", startsAt: "1999-01-01T00:00:00Z", anchor: "1999-01-01T00:00:00Z", endsAt: endsAt + ) + sdk.rawPaymentRequests = { [request] } + let service = PaykitSdkService(sdkFactory: { sdk }) + let blocked = endsAt != "2000-01-01T00:00:00Z" + let operations: [() async throws -> Void] = [ + { try await service.requireNoActiveSubscriptions(expectedIdentity: identityA) }, + { _ = try await service.removeContactsForProfile(publicKeys: [identityB]) }, + { _ = try await service.removeContactsForProfile(publicKeys: []) }, + { try await service.deletePaykitProfile(expectedIdentity: identityA) }, + ] + for operation in operations { + do { + try await operation() + XCTAssertFalse(blocked) + } catch PubkyServiceError.activeSubscription { + XCTAssertTrue(blocked) + } + } + XCTAssertEqual(sdk.writes, blocked ? [] : ["remove-contacts:1", "delete-profile:test"]) + } + } + + func testSubscriptionReadFailureAndCancellationNeverAuthorizeProfileCleanup() async throws { + for failure: Error in [sharedStateBusy, CancellationError()] { + let sdk = IdentitySwitchingSdk(noPointer: .init()) + sdk.identity = identityA + sdk.profileExists = true + sdk.rawPaymentRequests = { throw failure } + let service = PaykitSdkService(sdkFactory: { sdk }) + let operations: [() async throws -> Void] = [ + { try await service.requireNoActiveSubscriptions(expectedIdentity: identityA) }, + { _ = try await service.removeContactsForProfile(publicKeys: [contactKey]) }, + { try await service.deletePaykitProfile(expectedIdentity: identityA) }, + ] + for operation in operations { + do { + try await operation() + XCTFail("An unavailable subscription read must stop cleanup") + } catch { + XCTAssertEqual(error.localizedDescription, failure.localizedDescription) + } + } + XCTAssertTrue(sdk.writes.isEmpty) + } + } + func testProfileDeletionChecksItsOwnerBeforeReadingOrRemovingTheProfile() async throws { for signedIn in [identityA, identityB, nil] { let sdk = IdentitySwitchingSdk(noPointer: .init()) @@ -766,6 +840,8 @@ private final class IdentitySwitchingSdk: PaykitSdk, @unchecked Sendable { PaymentRequestRead(identityStatus: nil, paymentRequests: []) } + var rawPaymentRequests: () async throws -> [PaymentRequestRecord] = { [] } + var schedulingRead: () async throws -> Paykit.PrivateMessageSchedulingSnapshot = { Paykit.PrivateMessageSchedulingSnapshot(linkedPeers: [], pendingOutboundCounterparties: []) } @@ -826,6 +902,10 @@ private final class IdentitySwitchingSdk: PaykitSdk, @unchecked Sendable { } } + override func paymentRequests() async throws -> [PaymentRequestRecord] { + try await rawPaymentRequests() + } + override func readPaymentRequests(counterparty: String, expectedIdentity: String?) async throws -> PaymentRequestRead { try await paymentRequestRead(counterparty, expectedIdentity) } @@ -890,6 +970,11 @@ private final class IdentitySwitchingSdk: PaykitSdk, @unchecked Sendable { return [] } + override func removeContactsAndBlockPeers(publicKeys: [String]) async throws -> [ContactRecord] { + recordWrite("remove-contacts:\(publicKeys.count)") + return publicKeys.map { Self.record(publicKey: $0, label: nil) } + } + override func contactRecord(publicKey: String) async throws -> ContactRecord? { lock.withLock { recordedContactReads += 1 } return Self.record(publicKey: publicKey, label: "Contact") diff --git a/BitkitTests/PubkyProfileManagerTests.swift b/BitkitTests/PubkyProfileManagerTests.swift index 48157df7f9..2dba17bcb1 100644 --- a/BitkitTests/PubkyProfileManagerTests.swift +++ b/BitkitTests/PubkyProfileManagerTests.swift @@ -11,13 +11,53 @@ final class PubkyProfileManagerTests: XCTestCase { case signOut } + @MainActor + func testActiveSubscriptionStopsProfileRemovalBeforePrivateOrContactCleanup() async throws { + try await withEmptyIdentityStorage { + for entry in ["screen", "manager"] { + let key = "pubky" + String(repeating: "y", count: 52) + let manager = PubkyProfileManager(profileDeletionValidator: { expectedIdentity in + XCTAssertEqual(expectedIdentity, key) + throw PubkyServiceError.activeSubscription(endsAt: nil) + }, profileDeleter: { _ in + XCTFail("An active subscription must preserve the profile") + }) + manager.publicKey = key + manager.authState = .authenticated + let session = try XCTUnwrap(manager.currentSession) + let contacts = ContactsManager(contactRecords: { + XCTFail("An active subscription must stop before contact cleanup") + return [] + }) + UserDefaults.standard.set(true, forKey: PublicPaykitService.publishingEnabledKey) + UserDefaults.standard.set(true, forKey: PrivatePaykitService.publishingEnabledKey) + do { + if entry == "screen" { + try await manager.performProfileDeletion { + try await EditProfileView.performDeleteProfile( + session: session, pubkyProfile: manager, contactsManager: contacts + ) { XCTFail("An active subscription must preserve private endpoints") } + } + } else { + try await manager.deleteProfile() + } + XCTFail("Expected subscription refusal") + } catch PubkyServiceError.activeSubscription {} + XCTAssertEqual(manager.currentSession, session) + XCTAssertFalse(manager.isDeletingProfile) + XCTAssertTrue(UserDefaults.standard.bool(forKey: PublicPaykitService.publishingEnabledKey)) + XCTAssertTrue(UserDefaults.standard.bool(forKey: PrivatePaykitService.publishingEnabledKey)) + } + } + } + @MainActor func testProfileRemovalStopsBeforeDeletingWhenCleanupIsIncomplete() async throws { snapshotAppDefaultsDomain() for failure in ["private endpoints", "contacts"] { let key = "pubky" + String(repeating: "y", count: 52) let originalError = KeychainError.failedToDelete - let manager = PubkyProfileManager(profileDeleter: { _ in + let manager = PubkyProfileManager(profileDeletionValidator: { _ in }, profileDeleter: { _ in XCTFail("Incomplete cleanup must not delete the profile") throw PublicPaykitError.publicationFailed }) @@ -243,7 +283,7 @@ final class PubkyProfileManagerTests: XCTestCase { let started = expectation(description: "Profile delete admitted") let (resume, continuation) = AsyncStream.makeStream() defer { continuation.finish() } - let manager = PubkyProfileManager(profileDeleter: { expectedIdentity in + let manager = PubkyProfileManager(profileDeletionValidator: { _ in }, profileDeleter: { expectedIdentity in XCTAssertEqual(expectedIdentity, original) started.fulfill() for await _ in resume {} @@ -332,7 +372,7 @@ final class PubkyProfileManagerTests: XCTestCase { NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadNoSuchFile.rawValue), ] for failure in errors { - let manager = PubkyProfileManager(profileDeleter: { _ in + let manager = PubkyProfileManager(profileDeletionValidator: { _ in }, profileDeleter: { _ in if let failure { throw failure } @@ -364,7 +404,7 @@ final class PubkyProfileManagerTests: XCTestCase { try await withEmptyIdentityStorage { let secret = String(repeating: "01", count: 32) let original = try PubkyProfileManager.publicKeyFromSecretKey(secret) - let manager = PubkyProfileManager(profileDeleter: { _ in + let manager = PubkyProfileManager(profileDeletionValidator: { _ in }, profileDeleter: { _ in XCTFail("A stale deletion must not reach profile storage") }) manager.publicKey = original diff --git a/changelog.d/next/1124.fixed.md b/changelog.d/next/1124.fixed.md index f05f0a6f84..4998652b65 100644 --- a/changelog.d/next/1124.fixed.md +++ b/changelog.d/next/1124.fixed.md @@ -1 +1 @@ -Preserve session and contact data after failed profile deletion or incomplete payment-link cleanup. +Preserve session and contact data after incomplete profile cleanup, and require ending active subscriptions before removing a profile. diff --git a/journeys/profile/profile-cleanup-failure.xml b/journeys/profile/profile-cleanup-failure.xml index f9fd8c2e29..5b1f66be99 100644 --- a/journeys/profile/profile-cleanup-failure.xml +++ b/journeys/profile/profile-cleanup-failure.xml @@ -2,12 +2,19 @@ Requires a disposable test identity with saved contacts and a controlled homeserver proxy. Never use a personal profile. Inject a private-endpoint withdrawal failure, then in a fresh - fixture inject an unknown contact-removal response or a partial removal retaining an active peer. + fixture inject an unknown contact-removal response or a partial removal acknowledging only some contacts. + Separately prepare an active recurring subscription in each role (payer and payee), with an + unrelated saved contact, and record endpoint/contact state before confirming removal. Verify + the subscription warning appears before cleanup; cancel or expire the subscription in the + disposable fixture and confirm removal again to verify it can proceed. Also inject a profile-deletion error whose message contains 404 Not Found, without confirming deletion. These controls are not available in standard staging. This journey covers stopping on incomplete cleanup, not cross-device conditional deletion or safe manual replay of an uncertain operation. + With an active subscription, confirm profile deletion or unlink and verify the localized instruction to end active subscriptions + Verify there is no generic Retry dialog, endpoint withdrawal, contact removal or profile deletion, including for the unrelated contact + After ending the subscription, explicitly confirm removal again and verify acknowledged cleanup succeeds Open Edit Profile and confirm deletion with the cleanup fault enabled Verify failure options appear without a success notification or onboarding navigation Verify a failed private withdrawal is followed by no contact or profile deletion From 6665a4431d04eb00f286a81e90b38d3e3f9e6d7f Mon Sep 17 00:00:00 2001 From: benk10 Date: Thu, 29 Oct 2026 16:07:55 +0200 Subject: [PATCH 25/45] Explain finite subscription expiration before profile removal --- .../Localization/ar.lproj/Localizable.strings | 2 +- .../Localization/ca.lproj/Localizable.strings | 2 +- .../Localization/cs.lproj/Localizable.strings | 2 +- .../Localization/de.lproj/Localizable.strings | 2 +- .../Localization/el.lproj/Localizable.strings | 2 +- .../Localization/en.lproj/Localizable.strings | 2 +- .../es-419.lproj/Localizable.strings | 2 +- .../Localization/es.lproj/Localizable.strings | 2 +- .../Localization/fr.lproj/Localizable.strings | 2 +- .../Localization/it.lproj/Localizable.strings | 2 +- .../Localization/nl.lproj/Localizable.strings | 2 +- .../Localization/pl.lproj/Localizable.strings | 2 +- .../pt-BR.lproj/Localizable.strings | 2 +- .../Localization/pt.lproj/Localizable.strings | 2 +- .../Localization/ru.lproj/Localizable.strings | 2 +- Bitkit/Services/PubkyService.swift | 10 ++++-- Bitkit/Views/Profile/EditProfileView.swift | 7 ++-- BitkitTests/PaykitSdkIdentityCheckTests.swift | 36 ++++++++++++++++++- changelog.d/next/1124.fixed.md | 2 +- journeys/profile/profile-cleanup-failure.xml | 2 +- 20 files changed, 65 insertions(+), 22 deletions(-) diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index ce6d0097b6..f186485efb 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -946,7 +946,7 @@ "profile__edit_delete_section" = "حذف"; "profile__edit_unlink_section" = "إلغاء الربط"; "profile__edit_public_note" = "يرجى ملاحظة أن معلومات الملف الشخصي مخزنة في ملفات عامة."; -"profile__delete_active_subscription" = "أنه الاشتراكات النشطة قبل إزالة هذا الملف الشخصي."; +"profile__delete_active_subscription" = "تمنع الاشتراكات النشطة إزالة هذا الملف الشخصي."; "profile__delete_title" = "حذف الملف الشخصي؟"; "profile__delete_description" = "يؤدي حذف ملفك الشخصي إلى إزالته من Pubky. قد تحتفظ جهات الاتصال بمعلومات الملف الشخصي والدفع التي شاركتها معهم سابقًا."; "profile__delete_confirm" = "نعم، احذف"; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index d068ddbe8c..72adfbb414 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -1062,7 +1062,7 @@ "profile__edit_delete_section" = "ELIMINAR"; "profile__edit_unlink_section" = "DESVINCULAR"; "profile__edit_public_note" = "Tingues en compte que la informació del perfil es desa en fitxers públics."; -"profile__delete_active_subscription" = "Finalitza les subscripcions actives abans d’eliminar aquest perfil."; +"profile__delete_active_subscription" = "Les subscripcions actives impedeixen eliminar aquest perfil."; "profile__delete_title" = "Eliminar el perfil?"; "profile__delete_description" = "Eliminar el teu perfil l'esborra de Pubky. És possible que els contactes conservin la informació de perfil i de pagament que s'hi hagi compartit abans."; "profile__delete_confirm" = "Sí, elimina"; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index b200d53045..78fe68c6a7 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -1167,7 +1167,7 @@ "profile__edit_delete_section" = "SMAZAT"; "profile__edit_unlink_section" = "ZRUŠIT PROPOJENÍ"; "profile__edit_public_note" = "Upozorňujeme, že informace o profilu jsou uloženy ve veřejných souborech."; -"profile__delete_active_subscription" = "Před odstraněním tohoto profilu ukončete aktivní předplatná."; +"profile__delete_active_subscription" = "Aktivní předplatná brání odstranění tohoto profilu."; "profile__delete_title" = "Smazat profil?"; "profile__delete_description" = "Smazáním profilu ho odstraníte z Pubky. Kontakty si mohou ponechat informace o profilu a platbách, které jste s nimi dříve sdíleli."; "profile__delete_confirm" = "Ano, smazat"; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index 79514b702f..6c1a7e8368 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -1165,7 +1165,7 @@ "profile__edit_delete_section" = "LÖSCHEN"; "profile__edit_unlink_section" = "VERKNÜPFUNG AUFHEBEN"; "profile__edit_public_note" = "Bitte beachte, dass Profilinformationen in öffentlichen Dateien gespeichert werden."; -"profile__delete_active_subscription" = "Beende aktive Abonnements, bevor du dieses Profil entfernst."; +"profile__delete_active_subscription" = "Aktive Abonnements verhindern das Entfernen dieses Profils."; "profile__delete_title" = "Profil löschen?"; "profile__delete_description" = "Durch das Löschen deines Profils wird es von Pubky entfernt. Kontakte können zuvor mit ihnen geteilte Profil- und Zahlungsinformationen weiterhin behalten."; "profile__delete_confirm" = "Ja, löschen"; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index eb4e336741..7740f95c28 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -963,7 +963,7 @@ "profile__edit_delete_section" = "ΔΙΑΓΡΑΦΗ"; "profile__edit_unlink_section" = "ΑΠΟΣΥΝΔΕΣΗ"; "profile__edit_public_note" = "Τα στοιχεία του προφίλ αποθηκεύονται σε δημόσια αρχεία."; -"profile__delete_active_subscription" = "Τερμάτισε τις ενεργές συνδρομές πριν αφαιρέσεις αυτό το προφίλ."; +"profile__delete_active_subscription" = "Οι ενεργές συνδρομές εμποδίζουν την αφαίρεση αυτού του προφίλ."; "profile__delete_title" = "Διαγραφή Προφίλ;"; "profile__delete_description" = "Η διαγραφή του προφίλ σας το αφαιρεί από το Pubky. Οι επαφές μπορεί να διατηρούν ακόμα πληροφορίες προφίλ και πληρωμών που τους κοινοποιήθηκαν παλαιότερα."; "profile__delete_confirm" = "Ναι, Διαγραφή"; diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings index 2c3388dc1d..6cba87f8a4 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -1180,7 +1180,7 @@ "profile__edit_delete_section" = "DELETE"; "profile__edit_unlink_section" = "UNLINK"; "profile__edit_public_note" = "Please note profile information is stored in public files."; -"profile__delete_active_subscription" = "End active subscriptions before removing this profile."; +"profile__delete_active_subscription" = "Active subscriptions prevent removing this profile."; "profile__delete_title" = "Delete Profile?"; "profile__delete_description" = "Deleting your profile removes it from Pubky. Contacts may still retain profile and payment information previously shared with them."; "profile__delete_confirm" = "Yes, Delete"; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index 09d802a6eb..d3136f913c 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -1170,7 +1170,7 @@ "profile__edit_delete_section" = "ELIMINAR"; "profile__edit_unlink_section" = "DESVINCULAR"; "profile__edit_public_note" = "Tenga en cuenta que la información del perfil se guarda en archivos públicos."; -"profile__delete_active_subscription" = "Finaliza las suscripciones activas antes de eliminar este perfil."; +"profile__delete_active_subscription" = "Las suscripciones activas impiden eliminar este perfil."; "profile__delete_title" = "¿Eliminar perfil?"; "profile__delete_description" = "Al eliminar su perfil, se borra de Pubky. Es posible que sus contactos conserven la información de perfil y de pago que compartió con ellos anteriormente."; "profile__delete_confirm" = "Sí, eliminar"; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index 1d2ee2fdc9..56f20db88e 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -1079,7 +1079,7 @@ "profile__edit_delete_section" = "ELIMINAR"; "profile__edit_unlink_section" = "DESVINCULAR"; "profile__edit_public_note" = "Tenga en cuenta que la información del perfil se guarda en archivos públicos."; -"profile__delete_active_subscription" = "Finaliza las suscripciones activas antes de eliminar este perfil."; +"profile__delete_active_subscription" = "Las suscripciones activas impiden eliminar este perfil."; "profile__delete_title" = "¿Eliminar el perfil?"; "profile__delete_description" = "Al eliminar su perfil, se elimina de Pubky. Es posible que sus contactos conserven la información de perfil y de pago que compartió con ellos anteriormente."; "profile__delete_confirm" = "Sí, eliminar"; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index ab085fc068..0ddcc5f3b5 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -1178,7 +1178,7 @@ "profile__edit_delete_section" = "SUPPRIMER"; "profile__edit_unlink_section" = "DISSOCIER"; "profile__edit_public_note" = "Veuillez noter que les informations de profil sont stockées dans des fichiers publics."; -"profile__delete_active_subscription" = "Mettez fin aux abonnements actifs avant de supprimer ce profil."; +"profile__delete_active_subscription" = "Les abonnements actifs empêchent la suppression de ce profil."; "profile__delete_title" = "Supprimer le profil ?"; "profile__delete_description" = "La suppression de votre profil le retire de Pubky. Vos contacts peuvent encore conserver les informations de profil et de paiement que vous leur avez partagées."; "profile__delete_confirm" = "Oui, supprimer"; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index d47a4a60f7..d497b9752a 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -1144,7 +1144,7 @@ "profile__edit_delete_section" = "ELIMINA"; "profile__edit_unlink_section" = "SCOLLEGA"; "profile__edit_public_note" = "Tieni presente che le informazioni del profilo sono salvate in file pubblici."; -"profile__delete_active_subscription" = "Termina gli abbonamenti attivi prima di rimuovere questo profilo."; +"profile__delete_active_subscription" = "Gli abbonamenti attivi impediscono la rimozione di questo profilo."; "profile__delete_title" = "Eliminare il Profilo?"; "profile__delete_description" = "Eliminando il profilo lo rimuovi da Pubky. I contatti potrebbero conservare le informazioni di profilo e di pagamento condivise in precedenza con loro."; "profile__delete_confirm" = "Sì, Elimina"; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index 65c63cc45a..6e1a387e66 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -1173,7 +1173,7 @@ "profile__edit_delete_section" = "VERWIJDEREN"; "profile__edit_unlink_section" = "ONTKOPPELEN"; "profile__edit_public_note" = "Let op: profielgegevens worden opgeslagen in openbare bestanden."; -"profile__delete_active_subscription" = "Beëindig actieve abonnementen voordat je dit profiel verwijdert."; +"profile__delete_active_subscription" = "Actieve abonnementen verhinderen het verwijderen van dit profiel."; "profile__delete_title" = "Profiel verwijderen?"; "profile__delete_description" = "Als u uw profiel verwijdert, wordt het van Pubky verwijderd. Contacten kunnen eerder gedeelde profiel- en betaalgegevens nog bewaren."; "profile__delete_confirm" = "Ja, verwijderen"; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index 2320c034da..6fb626ca8d 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -1177,7 +1177,7 @@ "profile__edit_delete_section" = "USUWANIE"; "profile__edit_unlink_section" = "ODŁĄCZANIE"; "profile__edit_public_note" = "Pamiętaj, że dane profilu są przechowywane w publicznych plikach."; -"profile__delete_active_subscription" = "Zakończ aktywne subskrypcje przed usunięciem tego profilu."; +"profile__delete_active_subscription" = "Aktywne subskrypcje uniemożliwiają usunięcie tego profilu."; "profile__delete_title" = "Usunąć profil?"; "profile__delete_description" = "Usunięcie profilu usuwa go z Pubky. Kontakty mogą nadal przechowywać udostępnione im wcześniej dane profilu i płatności."; "profile__delete_confirm" = "Tak, usuń"; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index c7a060fe17..028091cbf8 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -1178,7 +1178,7 @@ "profile__edit_delete_section" = "EXCLUIR"; "profile__edit_unlink_section" = "DESVINCULAR"; "profile__edit_public_note" = "Observe que as informações do perfil são armazenadas em arquivos públicos."; -"profile__delete_active_subscription" = "Encerre as assinaturas ativas antes de remover este perfil."; +"profile__delete_active_subscription" = "As assinaturas ativas impedem a remoção deste perfil."; "profile__delete_title" = "Excluir Perfil?"; "profile__delete_description" = "Excluir seu perfil o remove do Pubky. Os contatos ainda podem manter informações de perfil e de pagamento compartilhadas anteriormente com eles."; "profile__delete_confirm" = "Sim, Excluir"; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index 951c738639..da0cf21be1 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -938,7 +938,7 @@ "profile__edit_delete_section" = "ELIMINAR"; "profile__edit_unlink_section" = "DESASSOCIAR"; "profile__edit_public_note" = "Tenha em atenção que as informações do perfil são guardadas em ficheiros públicos."; -"profile__delete_active_subscription" = "Termina as subscrições ativas antes de remover este perfil."; +"profile__delete_active_subscription" = "As subscrições ativas impedem a remoção deste perfil."; "profile__delete_title" = "Eliminar perfil?"; "profile__delete_description" = "Eliminar o seu perfil remove-o do Pubky. Os contactos podem manter as informações de perfil e pagamento partilhadas anteriormente com eles."; "profile__delete_confirm" = "Sim, Excluir"; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index 9d9a10028e..ce06e85ae4 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -1163,7 +1163,7 @@ "profile__edit_delete_section" = "УДАЛЕНИЕ"; "profile__edit_unlink_section" = "ОТВЯЗКА"; "profile__edit_public_note" = "Обратите внимание: данные профиля хранятся в публичных файлах."; -"profile__delete_active_subscription" = "Завершите активные подписки перед удалением этого профиля."; +"profile__delete_active_subscription" = "Активные подписки не позволяют удалить этот профиль."; "profile__delete_title" = "Удалить Профиль?"; "profile__delete_description" = "Удаление профиля удалит его из Pubky. У контактов могут остаться данные профиля и платёжные данные, которыми вы делились ранее."; "profile__delete_confirm" = "Да, Удалить"; diff --git a/Bitkit/Services/PubkyService.swift b/Bitkit/Services/PubkyService.swift index 5e3ee269b2..8017448799 100644 --- a/Bitkit/Services/PubkyService.swift +++ b/Bitkit/Services/PubkyService.swift @@ -823,10 +823,16 @@ actor PaykitSdkService { let requests = try await sdk.paymentRequests() try Task.checkCancellation() let now = Date() - guard !requests.contains(where: { + let activeSubscriptions = requests.filter { $0.state == .activeRecurring && ($0.terms?.recurrence?.endsAt.flatMap(PaykitPaymentRequest.parseDate).map { $0 > now } ?? true) - }) else { throw PubkyServiceError.activeSubscription(endsAt: nil) } + } + guard !activeSubscriptions.isEmpty else { return } + let endDates = activeSubscriptions.compactMap { + $0.terms?.recurrence?.endsAt.flatMap(PaykitPaymentRequest.parseDate) + } + let latestEndDate = endDates.count == activeSubscriptions.count ? endDates.max() : nil + throw PubkyServiceError.activeSubscription(endsAt: latestEndDate) } func deletePaykitProfile(expectedIdentity: String? = nil) async throws { diff --git a/Bitkit/Views/Profile/EditProfileView.swift b/Bitkit/Views/Profile/EditProfileView.swift index 0db9252a92..d85df61f5a 100644 --- a/Bitkit/Views/Profile/EditProfileView.swift +++ b/Bitkit/Views/Profile/EditProfileView.swift @@ -160,9 +160,12 @@ struct EditProfileView: View { try await pubkyProfile.performProfileDeletion { do { try await performDeleteProfile(session: session) - } catch PubkyServiceError.activeSubscription { + } catch let PubkyServiceError.activeSubscription(endsAt) { guard !Task.isCancelled, pubkyProfile.currentSession == session else { return } - app.toast(type: .error, title: t("profile__delete_active_subscription")) + let description = endsAt.map { + t("subscriptions__expires_date", variables: ["date": $0.formatted(date: .long, time: .omitted)]) + } + app.toast(type: .error, title: t("profile__delete_active_subscription"), description: description) } catch { guard !Task.isCancelled, pubkyProfile.publicKey == session.publicKey else { return } Logger.error("Failed to delete profile: \(error)", context: "EditProfileView") diff --git a/BitkitTests/PaykitSdkIdentityCheckTests.swift b/BitkitTests/PaykitSdkIdentityCheckTests.swift index 670794574f..ca2720e916 100644 --- a/BitkitTests/PaykitSdkIdentityCheckTests.swift +++ b/BitkitTests/PaykitSdkIdentityCheckTests.swift @@ -482,14 +482,48 @@ final class PaykitSdkIdentityCheckTests: XCTestCase { do { try await operation() XCTAssertFalse(blocked) - } catch PubkyServiceError.activeSubscription { + } catch let PubkyServiceError.activeSubscription(actualEnd) { XCTAssertTrue(blocked) + XCTAssertEqual(actualEnd, endsAt.flatMap(PaykitPaymentRequest.parseDate)) } } XCTAssertEqual(sdk.writes, blocked ? [] : ["remove-contacts:1", "delete-profile:test"]) } } + func testProfileRemovalOnlyReportsAnEndWhenEveryBlockingSubscriptionHasOne() async throws { + let earlier = "2999-01-01T00:00:00Z" + let later = "3000-01-01T00:00:00Z" + let cases: [(ends: [String?], expected: String?)] = [ + ([earlier, later], later), + ([later, earlier], later), + ([earlier, nil], nil), + (["invalid", later], nil), + (["2000-01-01T00:00:00Z", later], later), + ] + for testCase in cases { + let sdk = IdentitySwitchingSdk(noPointer: .init()) + sdk.identity = identityA + let requests = try testCase.ends.map { endsAt in + var request = try paymentRequestRecord(appId: "another-app") + request.state = .activeRecurring + request.terms?.recurrence = PaymentRequestRecurrence( + every: 1, unit: "month", startsAt: "1999-01-01T00:00:00Z", anchor: "1999-01-01T00:00:00Z", endsAt: endsAt + ) + return request + } + sdk.rawPaymentRequests = { requests } + let service = PaykitSdkService(sdkFactory: { sdk }) + do { + try await service.requireNoActiveSubscriptions(expectedIdentity: identityA) + XCTFail("Every case contains a blocking subscription") + } catch let PubkyServiceError.activeSubscription(endsAt) { + XCTAssertEqual(endsAt, testCase.expected.flatMap(PaykitPaymentRequest.parseDate)) + } + XCTAssertTrue(sdk.writes.isEmpty) + } + } + func testSubscriptionReadFailureAndCancellationNeverAuthorizeProfileCleanup() async throws { for failure: Error in [sharedStateBusy, CancellationError()] { let sdk = IdentitySwitchingSdk(noPointer: .init()) diff --git a/changelog.d/next/1124.fixed.md b/changelog.d/next/1124.fixed.md index 4998652b65..64a4e10014 100644 --- a/changelog.d/next/1124.fixed.md +++ b/changelog.d/next/1124.fixed.md @@ -1 +1 @@ -Preserve session and contact data after incomplete profile cleanup, and require ending active subscriptions before removing a profile. +Preserve session and contact data after incomplete profile cleanup, and explain when active subscriptions prevent profile removal. diff --git a/journeys/profile/profile-cleanup-failure.xml b/journeys/profile/profile-cleanup-failure.xml index 5b1f66be99..9b7a6747e5 100644 --- a/journeys/profile/profile-cleanup-failure.xml +++ b/journeys/profile/profile-cleanup-failure.xml @@ -12,7 +12,7 @@ cleanup, not cross-device conditional deletion or safe manual replay of an uncertain operation. - With an active subscription, confirm profile deletion or unlink and verify the localized instruction to end active subscriptions + With an active subscription, confirm profile deletion or unlink and verify the localized refusal; show the latest expiry only when all blocking subscriptions have known finite ends, and no date for open-ended or unknown terms Verify there is no generic Retry dialog, endpoint withdrawal, contact removal or profile deletion, including for the unrelated contact After ending the subscription, explicitly confirm removal again and verify acknowledged cleanup succeeds Open Edit Profile and confirm deletion with the cleanup fault enabled From a4f5ca6034f1025baa857a538d5e250c1529194a Mon Sep 17 00:00:00 2001 From: benk10 Date: Thu, 29 Oct 2026 18:21:34 +0200 Subject: [PATCH 26/45] fix: drain node event listeners before retry --- Bitkit.xcodeproj/project.pbxproj | 2 + Bitkit/Services/LightningService.swift | 374 ++++++++++------------- Bitkit/Services/NodeEventListener.swift | 71 +++++ Bitkit/ViewModels/WalletViewModel.swift | 202 ++++++------ BitkitTests/NodeEventListenerTests.swift | 158 ++++++++++ changelog.d/next/1139.fixed.md | 2 +- 6 files changed, 501 insertions(+), 308 deletions(-) create mode 100644 Bitkit/Services/NodeEventListener.swift create mode 100644 BitkitTests/NodeEventListenerTests.swift diff --git a/Bitkit.xcodeproj/project.pbxproj b/Bitkit.xcodeproj/project.pbxproj index f83b181fa9..c9512c6857 100644 --- a/Bitkit.xcodeproj/project.pbxproj +++ b/Bitkit.xcodeproj/project.pbxproj @@ -173,6 +173,7 @@ Services/HwActivityTagBackup.swift, Services/HwSnapshotMerge.swift, Services/LightningService.swift, + Services/NodeEventListener.swift, Services/MigrationsService.swift, Services/RNBackupClient.swift, Services/ServiceQueue.swift, @@ -205,6 +206,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/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 8174f9ef67..6cb67a5eb2 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -36,7 +36,8 @@ class LightningService { @MainActor private var cachedPeers: [PeerDetails]? @MainActor private var cachedChannels: [ChannelDetails]? - private var storedEventCallback: ((Event) -> Void)? + private var storedEventCallback: (@MainActor (Event) -> Void)? + @MainActor private var eventListener = NodeEventListener() var onchainTransactionConfirmed: (@Sendable (String) async -> Void)? var onchainTransactionReceived: (@Sendable (String) async -> Void)? @@ -188,14 +189,7 @@ class LightningService { // 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 @@ -224,13 +218,7 @@ class LightningService { // 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") @@ -248,7 +236,7 @@ class LightningService { /// 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) } @@ -257,11 +245,9 @@ class LightningService { storedEventCallback = onEvent } - listenForEvents(onEvent: 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 @@ -305,13 +291,8 @@ class LightningService { } Logger.debug("Stopping node...") - try await ServiceQueue.background(.ldk) { - do { - try node.stop() - } catch NodeError.NotRunning { - // A failed start can leave an allocated node that never became running. - Logger.debug("Node already stopped") - } + try await eventListener.stop(node: node) { [weak self] event in + await self?.handleEvent(event) } self.node = nil @@ -1353,199 +1334,182 @@ extension LightningService { // MARK: Events extension LightningService { - 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() + } - let event = await node.nextEventAsync() + await storedEventCallback?(event) + 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()") - } - - if case .channelReady = event { - await refreshChannelCache() + Logger.error("Failed to handle payment success for \(hash): \(error)", context: "LightningService") } - - onEvent?(event) - - 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 .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") } - 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)" - ) + } 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 CoreService.shared.activity.handleOnchainTransactionReceived(txid: txid, details: details) - } 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 CoreService.shared.activity.handleOnchainTransactionConfirmed( - txid: txid, - details: details - ) - } 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 CoreService.shared.activity.handleOnchainTransactionReplaced(txid: txid, conflicts: conflicts) - } 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 CoreService.shared.activity.handleOnchainTransactionReorged(txid: txid) - } 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 CoreService.shared.activity.handleOnchainTransactionEvicted(txid: txid) - } catch { - Logger.error("Failed to handle transaction evicted 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 CoreService.shared.activity.handleOnchainTransactionReceived(txid: txid, details: details) + } 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 CoreService.shared.activity.handleOnchainTransactionConfirmed( + txid: txid, + details: details + ) + } 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 CoreService.shared.activity.handleOnchainTransactionReplaced(txid: txid, conflicts: conflicts) + } 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 CoreService.shared.activity.handleOnchainTransactionReorged(txid: txid) + } 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 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..73d0f4dedd --- /dev/null +++ b/Bitkit/Services/NodeEventListener.swift @@ -0,0 +1,71 @@ +import Foundation +import LDKNode + +@MainActor +final class NodeEventListener { + private var task: Task? + private var isTransitioning = false + + private enum LifecycleError: Error { + case transitionInProgress + } + + func start(node: Node, onEvent: @escaping (Event) async -> Void) async throws { + guard !isTransitioning, task == nil else { throw LifecycleError.transitionInProgress } + isTransitioning = true + defer { isTransitioning = false } + 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 !isTransitioning else { throw LifecycleError.transitionInProgress } + isTransitioning = true + defer { isTransitioning = false } + let previous = task + previous?.cancel() + await previous?.value + task = nil + + do { + try await ServiceQueue.background(.ldk) { + do { + try node.stop() + } catch NodeError.NotRunning { + // An unsuccessful start leaves a node without a running event consumer. + } + } + } 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(.ldk) { () -> 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/ViewModels/WalletViewModel.swift b/Bitkit/ViewModels/WalletViewModel.swift index b40aeedce7..fd68b5ec16 100644 --- a/Bitkit/ViewModels/WalletViewModel.swift +++ b/Bitkit/ViewModels/WalletViewModel.swift @@ -220,124 +220,122 @@ class WalletViewModel: ObservableObject { ) } try await lightningService.start(onEvent: { event in - Task { @MainActor in - // Notify all event handlers - for handler in self.eventHandlers.values { - handler(event) - } + // Notify all event handlers + for handler in self.eventHandlers.values { + handler(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.refreshAndSyncState() - await self.handleChannelClosed(channelId: channelId, reason: reason) - try? await self.refreshBip21(reportsError: false) - if self.isPaykitUIActive { - await PrivatePaykitService.shared.refreshKnownSavedContactEndpoints(wallet: self, reason: "channel-closed refresh") - } + case let .channelClosed(channelId, _, _, reason): + self.invalidateReceiveInvoice() + Task { + await self.refreshAndSyncState() + await self.handleChannelClosed(channelId: channelId, reason: reason) + try? await self.refreshBip21(reportsError: false) + if self.isPaykitUIActive { + await PrivatePaykitService.shared.refreshKnownSavedContactEndpoints(wallet: self, reason: "channel-closed refresh") } + } - // 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 - ) - } + // 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 .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)") - Task { - await self.refreshAndSyncState() - } + 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)") + Task { + await self.refreshAndSyncState() + } - // 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/BitkitTests/NodeEventListenerTests.swift b/BitkitTests/NodeEventListenerTests.swift new file mode 100644 index 0000000000..05f278974b --- /dev/null +++ b/BitkitTests/NodeEventListenerTests.swift @@ -0,0 +1,158 @@ +@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()) + weak var releasedNode = 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()) + weak var releasedNode = 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) + release?.resume() + try await stop.value + XCTAssertTrue(delivered) + XCTAssertEqual(node.stopCount, 1) + XCTAssertEqual(node.handledCount, 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) + } +} + +private enum TestError: Error { case failed } + +private final class EventNode: Node { + var startError: Error? + var stopError: Error? + var onEmpty: (() -> Void)? + var onStop: (() -> 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 { + 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 { + lock.withLock { + handledCount += 1 + event = nil + } + } +} diff --git a/changelog.d/next/1139.fixed.md b/changelog.d/next/1139.fixed.md index cf772ec9b4..a705f8ab25 100644 --- a/changelog.d/next/1139.fixed.md +++ b/changelog.d/next/1139.fixed.md @@ -1 +1 @@ -Allow connection settings to be corrected during wallet recovery while preserving required backup restoration, and keep offline wallet creation waiting for connectivity without reporting a restoration failure. +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. From 1dd6d2fb8974cffc674802180d5f8ef620a60959 Mon Sep 17 00:00:00 2001 From: benk10 Date: Fri, 30 Oct 2026 00:59:49 +0200 Subject: [PATCH 27/45] test: isolate identity publication return deadline --- BitkitTests/PaykitSdkClientConfigTests.swift | 31 ++++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/BitkitTests/PaykitSdkClientConfigTests.swift b/BitkitTests/PaykitSdkClientConfigTests.swift index 6c919cff3b..88d2858a95 100644 --- a/BitkitTests/PaykitSdkClientConfigTests.swift +++ b/BitkitTests/PaykitSdkClientConfigTests.swift @@ -586,14 +586,22 @@ final class PaykitSdkClientConfigTests: XCTestCase { try Keychain.delete(key: .paykitKeyGeneration(publicKey: publicKey)) let republishStarted = expectation(description: "Republish started") let republishFinished = expectation(description: "Republish finished") + let republishFinishedBeforeGateOpened = expectation(description: "Republish finished before gate opened") + republishFinishedBeforeGateOpened.isInverted = true let activationReturned = expectation(description: "Activation returned") let gate = AsyncStream.makeStream() + defer { gate.continuation.finish() } let bootstrap = CacheActivationBootstrap(noPointer: .init()) bootstrap.republishOperation = { republishStarted.fulfill() + var gateOpened = false for await _ in gate.stream { + gateOpened = true break } + if !gateOpened { + republishFinishedBeforeGateOpened.fulfill() + } republishFinished.fulfill() return true } @@ -608,13 +616,24 @@ final class PaykitSdkClientConfigTests: XCTestCase { try await service.activateRegisteredIdentity(.init(result: result, walletGeneration: 0)) activationReturned.fulfill() } - // Shorter than the republish timeout, so an activation that awaited the publication would miss it. - await fulfillment(of: [activationReturned, republishStarted], timeout: 2) - XCTAssertEqual(bootstrap.republishedKeys, [result.publicKey]) + defer { activation.cancel() } + try await withTaskCancellationHandler { + let setup = await XCTWaiter.fulfillment(of: [republishStarted], timeout: 10) + XCTAssertEqual(setup, .completed, "Identity activation must reach the gated publication") + if setup == .completed { + // Measure the return after credential preparation, below the unchanged five-second publication cap. + await fulfillment(of: [activationReturned, republishFinishedBeforeGateOpened], timeout: 2) + XCTAssertEqual(bootstrap.republishedKeys, [result.publicKey]) + } - gate.continuation.yield() - await fulfillment(of: [republishFinished], timeout: 1) - try await activation.value + gate.continuation.yield() + gate.continuation.finish() + await fulfillment(of: [republishFinished], timeout: 1) + try await activation.value + } onCancel: { + gate.continuation.finish() + activation.cancel() + } } func testSessionImportDoesNotCreateRuntimeBeforeBootstrapSucceeds() async throws { From e5143b1304e9c29f503e9082f75e857555ccf47f Mon Sep 17 00:00:00 2001 From: benk10 Date: Sat, 31 Oct 2026 18:55:32 +0200 Subject: [PATCH 28/45] fix: skip profile recovery while setup is pending --- Bitkit/Managers/PubkyProfileManager.swift | 4 +-- BitkitTests/PubkyProfileManagerTests.swift | 34 ++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/Bitkit/Managers/PubkyProfileManager.swift b/Bitkit/Managers/PubkyProfileManager.swift index 55874f22c7..e4a9cd2665 100644 --- a/Bitkit/Managers/PubkyProfileManager.swift +++ b/Bitkit/Managers/PubkyProfileManager.swift @@ -301,9 +301,9 @@ class PubkyProfileManager: ObservableObject { } guard !Task.isCancelled else { return } if let session = automaticPaykitSession { - if isInitialized, profile == nil { + if isInitialized, profile == nil, !isProfileSetupPending { Task { - guard automaticPaykitSession == session, isInitialized, profile == nil else { return } + guard automaticPaykitSession == session, isInitialized, profile == nil, !isProfileSetupPending else { return } await loadProfile() } } diff --git a/BitkitTests/PubkyProfileManagerTests.swift b/BitkitTests/PubkyProfileManagerTests.swift index c920424ef4..687cf5f3df 100644 --- a/BitkitTests/PubkyProfileManagerTests.swift +++ b/BitkitTests/PubkyProfileManagerTests.swift @@ -1829,6 +1829,7 @@ final class PubkyProfileManagerTests: XCTestCase { @MainActor func testSessionRecoveryReloadsMissingProfileWithoutReauthenticationOrWaiting() async { await withRestoredProfileDefaults { + UserDefaults.standard.set(false, forKey: "pubky_profile_setup_pending") let stub = RemoteProfileStub(profiles: [ringKeyA: makeProfile(publicKey: ringKeyA, name: "Recovered")]) await stub.makeUnreachable(ringKeyA) let manager = PubkyProfileManager(remoteProfileResolver: { try await stub.resolve($0) }) @@ -1863,9 +1864,42 @@ final class PubkyProfileManagerTests: XCTestCase { } } + @MainActor + func testSessionRecoveryDoesNotRefetchProfileWhileSetupIsPending() async { + await withRestoredProfileDefaults { + UserDefaults.standard.set(true, forKey: "pubky_profile_setup_pending") + let unexpectedRead = expectation(description: "An unfinished profile does not need a remote read") + unexpectedRead.isInverted = true + let stub = RemoteProfileStub() + let manager = PubkyProfileManager(remoteProfileResolver: { + unexpectedRead.fulfill() + return try await stub.resolve($0) + }) + manager.publicKey = ringKeyA + manager.authState = .authenticated + manager.isInitialized = true + let session = manager.currentSession + XCTAssertTrue(manager.isProfileSetupPending) + XCTAssertNotNil(manager.automaticPaykitSession) + + for _ in 0 ..< 3 { + await manager.restoreSessionIfNeeded(hasStoredIdentity: { + XCTFail("An active identity must not reload saved credentials") + return false + }) + } + await fulfillment(of: [unexpectedRead], timeout: 0.2) + let requests = await stub.requests + XCTAssertTrue(requests.isEmpty) + XCTAssertEqual(manager.currentSession, session) + XCTAssertTrue(manager.isProfileSetupPending) + } + } + @MainActor func testSessionRecoveryDropsMissingProfileResultFromClearedStateWithSameKey() async { await withRestoredProfileDefaults { + UserDefaults.standard.set(false, forKey: "pubky_profile_setup_pending") let stub = RemoteProfileStub( profiles: [ringKeyA: makeProfile(publicKey: ringKeyA, name: "Stale")], holdsRequests: true From 13b91199d523b5b3f2af665ac8d247715ceebd93 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sat, 31 Oct 2026 20:24:45 +0200 Subject: [PATCH 29/45] fix: wait for node startup before stopping --- Bitkit/Services/NodeEventListener.swift | 24 +++-- BitkitTests/NodeEventListenerTests.swift | 122 +++++++++++++++++++++++ 2 files changed, 139 insertions(+), 7 deletions(-) diff --git a/Bitkit/Services/NodeEventListener.swift b/Bitkit/Services/NodeEventListener.swift index 73d0f4dedd..e4dda21087 100644 --- a/Bitkit/Services/NodeEventListener.swift +++ b/Bitkit/Services/NodeEventListener.swift @@ -4,24 +4,34 @@ import LDKNode @MainActor final class NodeEventListener { private var task: Task? - private var isTransitioning = false + 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 !isTransitioning, task == nil else { throw LifecycleError.transitionInProgress } - isTransitioning = true - defer { isTransitioning = false } + 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 !isTransitioning else { throw LifecycleError.transitionInProgress } - isTransitioning = true - defer { isTransitioning = false } + 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 diff --git a/BitkitTests/NodeEventListenerTests.swift b/BitkitTests/NodeEventListenerTests.swift index 1461de0b82..077edbdb01 100644 --- a/BitkitTests/NodeEventListenerTests.swift +++ b/BitkitTests/NodeEventListenerTests.swift @@ -65,8 +65,17 @@ final class NodeEventListenerTests: XCTestCase { 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) @@ -92,6 +101,117 @@ final class NodeEventListenerTests: XCTestCase { 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 } @@ -99,6 +219,7 @@ 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)? private let lock = NSLock() @@ -115,6 +236,7 @@ private final class EventNode: Node { } override func start() throws { + onStart?() if let startError { throw startError } From b9f3bbda22cf8010e79c2c6bd24b69002f543be7 Mon Sep 17 00:00:00 2001 From: benk10 Date: Tue, 3 Nov 2026 10:47:56 -0500 Subject: [PATCH 30/45] fix: preserve backups when cached channel reads fail --- Bitkit/Services/BackupService.swift | 6 +- BitkitTests/BlocktankBackupTests.swift | 92 ++++++++++++++++++++++++++ changelog.d/next/1121.fixed.md | 2 +- 3 files changed, 96 insertions(+), 4 deletions(-) create mode 100644 BitkitTests/BlocktankBackupTests.swift diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index e1c2226f4e..ac0d64c47a 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -1294,9 +1294,9 @@ class BackupService { return try JSONEncoder().encode(payload) case .blocktank: - let orders = try await CoreService.shared.blocktank.orders() - let cjitEntries = try await CoreService.shared.blocktank.cjitOrders() - let info = try? await CoreService.shared.blocktank.info(refresh: false) + let orders = try await CoreService.shared.blocktank.orders(refresh: false) + let cjitEntries = try await CoreService.shared.blocktank.cjitOrders(refresh: false) + let info = try await CoreService.shared.blocktank.info(refresh: false) let payload = BlocktankBackupV1( version: 1, diff --git a/BitkitTests/BlocktankBackupTests.swift b/BitkitTests/BlocktankBackupTests.swift new file mode 100644 index 0000000000..a5af516432 --- /dev/null +++ b/BitkitTests/BlocktankBackupTests.swift @@ -0,0 +1,92 @@ +@testable import Bitkit +import BitkitCore +import SQLite3 +import XCTest + +@MainActor +final class BlocktankBackupTests: XCTestCase { + private var databaseDirectory: URL! + + override func setUp() async throws { + try await super.setUp() + _ = Bitkit.CoreService.shared.blocktank + await drainCoreServiceQueue() + databaseDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("BlocktankBackupTests-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: databaseDirectory, withIntermediateDirectories: true) + _ = try initDb(basePath: databaseDirectory.path) + try await Bitkit.CoreService.shared.blocktank.upsertOrdersList([.mock(id: "cached-order")]) + } + + override func tearDown() async throws { + await drainCoreServiceQueue() + await repointCoreToAppStorage() + if let databaseDirectory { + try FileManager.default.removeItem(at: databaseDirectory) + } + try await super.tearDown() + } + + func testAbsentCachedInfoDoesNotPreventCompleteCachedBackup() async throws { + let defaults = try makeIsolatedDefaults() + var uploads: [Data] = [] + let service = BackupService(defaults: defaults, uploadBackup: { key, data in + XCTAssertEqual(key, BackupCategory.blocktank.rawValue) + uploads.append(data) + }) + + let outcome = await service.triggerBackup(category: .blocktank) + XCTAssertTrue(outcome == .completed) + XCTAssertEqual(uploads.count, 1) + let payload = try JSONDecoder().decode(BlocktankBackupV1.self, from: XCTUnwrap(uploads.first)) + XCTAssertEqual(payload.orders.map(\.id), ["cached-order"]) + XCTAssertTrue(payload.cjitEntries.isEmpty) + XCTAssertNil(payload.info) + XCTAssertFalse(service.getBackupStatus(category: .blocktank).isRequired) + await service.stopObservingBackups() + } + + func testUnreadableCachedDataPreservesAcknowledgedBackupAndPendingRevision() async throws { + for table in ["orders", "cjit_entries", "info"] { + let defaults = try makeIsolatedDefaults(table) + var uploads: [Data] = [] + let service = BackupService(defaults: defaults, uploadBackup: { _, data in + uploads.append(data) + }) + let initial = await service.triggerBackup(category: .blocktank) + XCTAssertTrue(initial == .completed, table) + let acknowledged = try XCTUnwrap(uploads.last) + let synced = service.getBackupStatus(category: .blocktank).synced + service.markBackupRequired(category: .blocktank, schedule: false) + let pending = service.getBackupStatus(category: .blocktank) + XCTAssertTrue(pending.isRequired, table) + + try execute("ALTER TABLE \(table) RENAME TO unreadable_\(table)") + let failed = await service.triggerBackup(category: .blocktank) + XCTAssertTrue(failed == .failed, table) + XCTAssertEqual(uploads, [acknowledged], table) + let afterFailure = service.getBackupStatus(category: .blocktank) + XCTAssertEqual(afterFailure.synced, synced, table) + XCTAssertEqual(afterFailure.required, pending.required, table) + XCTAssertTrue(afterFailure.isRequired, table) + XCTAssertFalse(afterFailure.running, table) + + try execute("ALTER TABLE unreadable_\(table) RENAME TO \(table)") + let recovered = await service.triggerBackup(category: .blocktank) + XCTAssertTrue(recovered == .completed, table) + XCTAssertEqual(uploads.count, 2, table) + XCTAssertFalse(service.getBackupStatus(category: .blocktank).isRequired, table) + await service.stopObservingBackups() + } + } + + private func execute(_ sql: String) throws { + var connection: OpaquePointer? + let opened = sqlite3_open_v2(databaseDirectory.appendingPathComponent("blocktank.db").path, + &connection, SQLITE_OPEN_READWRITE, nil) + defer { sqlite3_close(connection) } + guard opened == SQLITE_OK, sqlite3_exec(connection, sql, nil, nil, nil) == SQLITE_OK else { + throw NSError(domain: "BlocktankBackupTests", code: Int(sqlite3_errcode(connection))) + } + } +} diff --git a/changelog.d/next/1121.fixed.md b/changelog.d/next/1121.fixed.md index 5afda00c45..7a81bf8089 100644 --- a/changelog.d/next/1121.fixed.md +++ b/changelog.d/next/1121.fixed.md @@ -1 +1 @@ -Wallet restore finishes without waiting for optional profile refresh, retries missing profile data after reconnecting, and preserves complete backups when identity data is unavailable. +Wallet restore finishes without waiting for optional profile refresh, retries missing profile data after reconnecting, and preserves complete backups when identity or cached channel data is unavailable. From 4e6c06ed79d0b916529b293fc83cd98d8acb0d33 Mon Sep 17 00:00:00 2001 From: benk10 Date: Tue, 3 Nov 2026 14:31:19 -0500 Subject: [PATCH 31/45] fix: publish backup idle after scheduled admission cleanup --- Bitkit/Services/BackupService.swift | 8 +-- .../BackupForegroundRecoveryTests.swift | 50 +++++++++++++++++++ changelog.d/next/1123.fixed.md | 2 +- 3 files changed, 56 insertions(+), 4 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 6949a8ca54..d810c600ac 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -1054,10 +1054,12 @@ class BackupService { break } } - updateBackupStatus(category: category) { status in - BackupItemStatus(synced: status.synced, required: status.required, running: false) + _ = try? await ServiceQueue.background(.backup) { + self.backupJobs.removeValue(forKey: category) + self.updateBackupStatus(category: category) { status in + BackupItemStatus(synced: status.synced, required: status.required, running: false) + } } - _ = try? await ServiceQueue.background(.backup) { self.backupJobs.removeValue(forKey: category) } if outcome.canRetryPendingBackup, !Task.isCancelled, getBackupStatus(category: category).isRequired, !shouldSkipBackup(category: category) { diff --git a/BitkitTests/BackupForegroundRecoveryTests.swift b/BitkitTests/BackupForegroundRecoveryTests.swift index 6d3b8b8341..4989593d69 100644 --- a/BitkitTests/BackupForegroundRecoveryTests.swift +++ b/BitkitTests/BackupForegroundRecoveryTests.swift @@ -308,6 +308,56 @@ final class BackupForegroundRecoveryTests: XCTestCase { await service.stopObservingBackups() } + func testScheduledIdlePublicationWaitsForForegroundAdmissionCleanup() async throws { + let fixture = try Fixture(categories: [.settings]) + defer { fixture.removeDefaults() } + let uploads = UploadRecorder() + let delayStarted = expectation(description: "Initial scheduled backup is held") + let queueHeld = expectation(description: "Backup admission queue is held") + let prematureIdle = expectation(description: "Idle must not precede admission cleanup") + prematureIdle.isInverted = true + let settled = expectation(description: "Scheduled backup becomes available for foreground retry") + let (delay, releaseDelay) = AsyncStream.makeStream() + let releaseQueue = DispatchSemaphore(value: 0) + defer { + releaseDelay.finish() + releaseQueue.signal() + } + let service = fixture.service(uploadBackup: { key, _ in + await uploads.record(key) + }, waitForBackupDelay: { + delayStarted.fulfill() + for await _ in delay {} + throw CancellationError() + }) + await service.startObservingBackups()?.value + await fulfillment(of: [delayStarted], timeout: 2) + Bitkit.ServiceQueue.ServiceTypes.backup.queue.async { + queueHeld.fulfill() + XCTAssertEqual(releaseQueue.wait(timeout: .now() + 2), .success) + } + await fulfillment(of: [queueHeld], timeout: 2) + let earlySubscription = service.backupStatusesPublisher + .filter { $0[.settings]?.running == false } + .first().sink { _ in prematureIdle.fulfill() } + releaseDelay.finish() + await fulfillment(of: [prematureIdle], timeout: 0.2) + earlySubscription.cancel() + let settledSubscription = service.backupStatusesPublisher + .filter { $0[.settings]?.running == false } + .first().sink { _ in settled.fulfill() } + defer { settledSubscription.cancel() } + releaseQueue.signal() + await fulfillment(of: [settled], timeout: 2) + + await service.setAppActive(true)?.value + let recorded = await uploads.counts + XCTAssertEqual(recorded, [BackupCategory.settings.rawValue: 1]) + XCTAssertFalse(service.getBackupStatus(category: .settings).isRequired) + service.setAppActive(false) + await service.stopObservingBackups() + } + private func startAfterPendingJobsSettle(_ service: BackupService, categories: [BackupCategory]) async { let settled = categories.map { expectation(description: "Initial \($0.rawValue) scheduling settled") } let subscriptions = zip(categories, settled).map { category, completed in diff --git a/changelog.d/next/1123.fixed.md b/changelog.d/next/1123.fixed.md index 0136537fdc..ad9fb38d18 100644 --- a/changelog.d/next/1123.fixed.md +++ b/changelog.d/next/1123.fixed.md @@ -1 +1 @@ -Preserve pending backups through observation changes and temporary connection failures, and complete wallet initialization only once after node startup. +Preserve pending backups through observation changes and temporary connection failures, keep foreground retries available as scheduled backups finish, and complete wallet initialization only once after node startup. From 11fb65d780055a10081bd9d7e12fee61949d140d Mon Sep 17 00:00:00 2001 From: benk10 Date: Tue, 3 Nov 2026 17:38:38 -0500 Subject: [PATCH 32/45] fix: retry temporary backup authentication failures --- Bitkit/Services/BackupService.swift | 29 ++++++--- BitkitTests/BackupServiceTests.swift | 90 ++++++++++++++++++++++++++++ 2 files changed, 111 insertions(+), 8 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index d810c600ac..f6fc217b19 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -1,6 +1,7 @@ import BitkitCore import Combine import Foundation +import Network import Paykit import VssRustClientFfi @@ -499,23 +500,35 @@ class BackupService { case MetadataBackupError.walletTemporarilyUnavailable, PaykitError.ConcurrentUpdate, PaykitError.SharedStateBusy, PaykitError.Transport, VssError.ConnectionError, VssError.NetworkError, VssError.StoreError, VssError.PutError: - true + return true case let VssError.UnknownError(details): - isVssRequestSendFailure(details) + return isVssRequestSendFailure(details, pathSuffix: "/putObjects") + case let VssError.AuthError(details): + let prefix = "error performing external request: " + let requestFailure = details.hasPrefix(prefix) ? String(details.dropFirst(prefix.count)) : details + return isVssRequestSendFailure(requestFailure) default: - false + return false } } - private static func isVssRequestSendFailure(_ details: String) -> Bool { + private static func isVssRequestSendFailure(_ details: String, pathSuffix: String? = nil) -> Bool { let prefix = "error sending request for url (" + let invalidHostCharacters = CharacterSet.whitespacesAndNewlines.union(.controlCharacters) + .union(CharacterSet(charactersIn: "/%@?#\\")) guard details.hasPrefix(prefix), details.hasSuffix(")"), - let url = URLComponents(string: String(details.dropFirst(prefix.count).dropLast())), + let url = URLComponents(string: String(details.dropFirst(prefix.count).dropLast()), encodingInvalidCharacters: false), url.scheme == "http" || url.scheme == "https", - let host = url.host, !host.isEmpty, - url.path.hasSuffix("/putObjects") + let host = url.host, !host.isEmpty, host.rangeOfCharacter(from: invalidHostCharacters) == nil, + (0 ... 65535).contains(url.port ?? 0), + url.url != nil else { return false } - return true + if host.hasPrefix("[") { + guard host.hasSuffix("]"), IPv6Address(String(host.dropFirst().dropLast())) != nil else { return false } + } else if host.contains(":") || host.contains("[") || host.contains("]") { + return false + } + return pathSuffix.map { url.path.hasSuffix($0) } ?? true } func persistWalletBackup() async throws { diff --git a/BitkitTests/BackupServiceTests.swift b/BitkitTests/BackupServiceTests.swift index 58f1511ba9..fe70679a86 100644 --- a/BitkitTests/BackupServiceTests.swift +++ b/BitkitTests/BackupServiceTests.swift @@ -6,6 +6,96 @@ import XCTest @MainActor final class BackupServiceTests: XCTestCase { + func testReleasedVssAuthTransportIsTemporaryWithoutRetryingAuthorizationFailures() { + let requestFailure = "error sending request for url (https://backup.example/lnurl_auth/auth)" + for details in [requestFailure, "error performing external request: \(requestFailure)", + "error sending request for url (http://127.0.0.1:1/custom/callback)", + "error sending request for url (http://[::1]:8080/auth?value=a%20b)", + "error sending request for url (https://xn--bcher-kva.example/auth)"] + { + XCTAssertTrue(BackupService.isTemporaryBackupFailure(VssError.AuthError(errorDetails: details)), details) + } + for details in ["permission denied", "invalid JWT", "HTTP status client error (401 Unauthorized)", + "error decoding response body", "error performing external request: permission denied", + "error performing external request: error performing external request: \(requestFailure)", + "prefix \(requestFailure)", "\(requestFailure) suffix", + "error sending request for url (not a URL)", + "error sending request for url (file://example.com/auth)", + "error sending request for url (https:///auth)", + "error sending request for url (https://backup.example/auth) trailing)", + "error sending request for url (https://backup.example/auth path)", + "error sending request for url (https://%20/auth)", + "error sending request for url (https://auth%20example.com/auth)", + "error sending request for url (https://%2F/auth)", + "error sending request for url (https://%3A/auth)", + "error sending request for url (https://%40/auth)", + "error sending request for url (https://[abc]/auth)", + "error sending request for url (https://[:::]/auth)", + "error sending request for url (https://host:99999/auth)"] + { + XCTAssertFalse(BackupService.isTemporaryBackupFailure(VssError.AuthError(errorDetails: details)), details) + } + XCTAssertFalse(BackupService.isTemporaryBackupFailure(VssError.UnknownError(errorDetails: requestFailure))) + } + + func testReleasedVssAuthTransportRetriesScheduledSettingsWithoutObservation() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let completed = expectation(description: "Settings acknowledged after auth transport recovers") + var attempts = 0 + var delays: [UInt64] = [] + let payload = Data("settings-snapshot".utf8) + let service = BackupService(defaults: defaults, backupData: { _ in payload }, uploadBackup: { key, data in + XCTAssertEqual(key, BackupCategory.settings.rawValue) + XCTAssertEqual(data, payload) + attempts += 1 + if attempts == 1 { + throw VssError.AuthError(errorDetails: "error performing external request: error sending request for url (http://127.0.0.1:1/auth)") + } + }, waitForBackupDelay: {}, waitForTemporaryFailureDelay: { delays.append($0) }) + await service.stopObservingBackups() + let subscription = service.backupStatusesPublisher + .filter { $0[.settings].map { !$0.isRequired && !$0.running } == true } + .first().sink { _ in completed.fulfill() } + service.markBackupRequired(category: .settings) + await fulfillment(of: [completed], timeout: 3) + subscription.cancel() + service.setWiping(true) + await service.stopObservingBackups() + XCTAssertEqual(attempts, 2) + XCTAssertEqual(delays, [10_000_000_000]) + XCTAssertFalse(service.getBackupStatus(category: .settings).isRequired) + } + + func testReleasedVssAuthorizationDenialStaysPendingWithoutAutomaticRetry() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let attempted = expectation(description: "Authorization refused") + let retried = expectation(description: "Authorization refusal automatically retried") + retried.isInverted = true + var attempts = 0 + let service = BackupService(defaults: defaults, backupData: { _ in Data("settings-snapshot".utf8) }, uploadBackup: { _, _ in + attempts += 1 + if attempts == 1 { + attempted.fulfill() + } else { + retried.fulfill() + } + throw VssError.AuthError(errorDetails: "permission denied") + }, waitForBackupDelay: {}, waitForTemporaryFailureDelay: { _ in retried.fulfill() }) + await service.stopObservingBackups() + service.markBackupRequired(category: .settings) + await fulfillment(of: [attempted], timeout: 3) + await fulfillment(of: [retried], timeout: 0.2) + service.setWiping(true) + await service.stopObservingBackups() + XCTAssertEqual(attempts, 1) + XCTAssertTrue(service.getBackupStatus(category: .settings).isRequired) + XCTAssertFalse(service.getBackupStatus(category: .settings).running) + } + func testReleasedVssConnectionErrorIsTemporaryWithoutBroadUnknownRetry() { XCTAssertTrue(BackupService.isTemporaryBackupFailure( VssError.UnknownError(errorDetails: "error sending request for url (http://127.0.0.1:1/putObjects)") From 25f25eaed54e0c0cb7f39d863c96412cd3a3f94c Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 04:46:29 -0500 Subject: [PATCH 33/45] fix: drain VSS calls before replacing wallet clients --- Bitkit/Services/VssBackupClient.swift | 334 ++++++++++++-------- Bitkit/Utilities/AppReset.swift | 14 +- BitkitTests/VssClientCoordinatorTests.swift | 234 ++++++++++++++ changelog.d/next/1121.fixed.md | 2 +- 4 files changed, 453 insertions(+), 131 deletions(-) create mode 100644 BitkitTests/VssClientCoordinatorTests.swift diff --git a/Bitkit/Services/VssBackupClient.swift b/Bitkit/Services/VssBackupClient.swift index 3c7995d2fb..67183fac56 100644 --- a/Bitkit/Services/VssBackupClient.swift +++ b/Bitkit/Services/VssBackupClient.swift @@ -1,68 +1,146 @@ import Foundation import VssRustClientFfi -/// Actor to coordinate VSS client setup (ensures only one setup runs at a time) -private actor VssSetupCoordinator { - private enum SetupState { - case idle - case inProgress(Task) - case completed +/// Owns setup and calls until both native slots can be retired together. +/// Calls remain concurrent; reset closes admission and waits without holding a network lock. +actor VssClientCoordinator { + enum Domain { case app, ldk } + + private struct Setup { + let id = UUID() + let task: Task } - private var state: SetupState = .idle + private var generation = UUID() + private var setups: [Domain: Setup] = [:] + private var ready: Set = [] + private var activeCalls = 0 + private var resetting = false + private var idleWaiters: [CheckedContinuation] = [] + private var resetWaiters: [CheckedContinuation] = [] + + func withClient( + domain: Domain, + setup: @escaping () async throws -> Void, + operation: () async throws -> T + ) async throws -> T { + try Task.checkCancellation() + guard !resetting else { throw CancellationError() } + let owner = generation + activeCalls += 1 + defer { finishCall() } + + let result: Result + do { + try await awaitSetup(domain: domain, owner: owner, action: setup) + try validate(owner) + result = try await .success(operation()) + } catch { + result = .failure(error) + } + try validate(owner) + return try result.get() + } - func awaitSetup(setupAction: @escaping () async throws -> Void) async throws { - switch state { - case .completed: - Logger.debug("VssSetupCoordinator: already completed, returning", context: "VssBackupClient") + /// Cancellation of the caller cannot abandon retirement. Native calls already + /// admitted may finish, but their results cannot escape into the next owner. + func reset(shutdown: () -> Void) async { + if resetting { + await withCheckedContinuation { resetWaiters.append($0) } return + } + await closeAdmission() + shutdown() + reopenAdmission() + } - case let .inProgress(existingTask): - Logger.debug("VssSetupCoordinator: setup in progress, waiting for existing task", context: "VssBackupClient") - try await existingTask.value - Logger.debug("VssSetupCoordinator: existing task completed", context: "VssBackupClient") - return + /// Keep admission closed while the caller replaces or removes wallet credentials. + func withSuspendedClients(shutdown: () -> Void, operation: () async throws -> T) async throws -> T { + guard !resetting else { throw CancellationError() } + await closeAdmission() + shutdown() + defer { reopenAdmission() } + return try await operation() + } - case .idle: - Logger.debug("VssSetupCoordinator: idle, starting new setup", context: "VssBackupClient") - let task = Task { - try await setupAction() - } - state = .inProgress(task) + private func closeAdmission() async { + resetting = true + generation = UUID() + setups.values.forEach { $0.task.cancel() } + if activeCalls > 0 { + await withCheckedContinuation { idleWaiters.append($0) } + } + } - do { - try await task.value - state = .completed - Logger.debug("VssSetupCoordinator: setup completed successfully", context: "VssBackupClient") - } catch { - // Reset on any error to allow retry attempts - state = .idle - Logger.debug("VssSetupCoordinator: setup failed, resetting to idle", context: "VssBackupClient") - throw error + private func reopenAdmission() { + setups.removeAll() + ready.removeAll() + resetting = false + let waiters = resetWaiters + resetWaiters.removeAll() + waiters.forEach { $0.resume() } + } + + private func awaitSetup(domain: Domain, owner: UUID, action: @escaping () async throws -> Void) async throws { + if ready.contains(domain) { + return + } + let setup: Setup + if let existing = setups[domain] { + setup = existing + } else { + setup = Setup(task: Task { try await action() }) + setups[domain] = setup + } + do { + try await setup.task.value + guard !resetting, generation == owner else { throw CancellationError() } + if setups[domain]?.id == setup.id { + ready.insert(domain) + setups[domain] = nil + } + } catch { + if generation == owner, setups[domain]?.id == setup.id { + setups[domain] = nil } + throw error } } - func reset() { - Logger.debug("VssSetupCoordinator: reset called", context: "VssBackupClient") - if case let .inProgress(task) = state { - task.cancel() + private func validate(_ owner: UUID) throws { + try Task.checkCancellation() + guard !resetting, generation == owner else { throw CancellationError() } + } + + private func finishCall() { + activeCalls -= 1 + if activeCalls == 0 { + let waiters = idleWaiters + idleWaiters.removeAll() + waiters.forEach { $0.resume() } } - state = .idle } } class VssBackupClient { static let shared = VssBackupClient() - private let setupCoordinator = VssSetupCoordinator() - private let ldkSetupCoordinator = VssSetupCoordinator() + private let coordinator = VssClientCoordinator() private init() {} func reset() async { - await setupCoordinator.reset() - await ldkSetupCoordinator.reset() + await coordinator.reset { + vssShutdownClient() + vssShutdownLdkClient() + } + } + + func withSuspendedClients(_ operation: () async throws -> T) async throws -> T { + try await coordinator.withSuspendedClients(shutdown: { + vssShutdownClient() + vssShutdownLdkClient() + }, operation: operation) } /// Returns LNURL-auth params when configured. Callers fail closed if this returns nil. @@ -76,7 +154,11 @@ class VssBackupClient { } let passphraseRaw = try Keychain.loadString(key: .bip39Passphrase(index: walletIndex)) let passphrase = passphraseRaw?.isEmpty == true ? nil : passphraseRaw - let storeId = try await VssStoreIdProvider.shared.getVssStoreId(walletIndex: walletIndex) + let storeId = try vssDeriveStoreId( + prefix: Env.vssStoreIdPrefix, + mnemonic: mnemonic, + passphrase: passphrase + ) return (Env.vssServerUrl, storeId, mnemonic, passphrase, lnurlAuthServerUrl) } @@ -129,36 +211,36 @@ class VssBackupClient { } func putObject(key: String, data: Data) async throws -> VssItem { - try await awaitSetup() + try await coordinator.withClient(domain: .app, setup: { [self] in try await setup() }) { + Logger.debug("VSS 'putObject' call for '\(key)'", context: "VssBackupClient") - Logger.debug("VSS 'putObject' call for '\(key)'", context: "VssBackupClient") - - do { - let item = try await vssStore(key: key, value: data) - Logger.debug("VSS 'putObject' success for '\(key)' at version: \(item.version)", context: "VssBackupClient") - return item - } catch { - Logger.debug("VSS 'putObject' error for '\(key)': \(error)", context: "VssBackupClient") - throw error + do { + let item = try await vssStore(key: key, value: data) + Logger.debug("VSS 'putObject' success for '\(key)' at version: \(item.version)", context: "VssBackupClient") + return item + } catch { + Logger.debug("VSS 'putObject' error for '\(key)': \(error)", context: "VssBackupClient") + throw error + } } } func getObject(key: String) async throws -> VssItem? { - try await awaitSetup() - - Logger.debug("VSS 'getObject' call for '\(key)'", context: "VssBackupClient") + try await coordinator.withClient(domain: .app, setup: { [self] in try await setup() }) { + Logger.debug("VSS 'getObject' call for '\(key)'", context: "VssBackupClient") - do { - if let item = try await vssGet(key: key) { - Logger.debug("VSS 'getObject' success for '\(key)' at version \(item.version)", context: "VssBackupClient") - return item - } else { - Logger.debug("VSS 'getObject' success null for '\(key)'", context: "VssBackupClient") - return nil + do { + if let item = try await vssGet(key: key) { + Logger.debug("VSS 'getObject' success for '\(key)' at version \(item.version)", context: "VssBackupClient") + return item + } else { + Logger.debug("VSS 'getObject' success null for '\(key)'", context: "VssBackupClient") + return nil + } + } catch { + Logger.warn("VSS 'getObject' error for '\(key)': \(error)", context: "VssBackupClient") + throw error } - } catch { - Logger.warn("VSS 'getObject' error for '\(key)': \(error)", context: "VssBackupClient") - throw error } } @@ -169,37 +251,41 @@ class VssBackupClient { /// Returns app-level keys with version info (for debug UI). func listKeyVersions() async throws -> [KeyVersion] { - try await awaitSetup() - Logger.debug("VSS 'listKeyVersions' call", context: "VssBackupClient") - do { - let versions = try await vssListKeys(prefix: nil) - Logger.debug("VSS 'listKeyVersions' success: \(versions.count) key(s)", context: "VssBackupClient") - return versions - } catch { - Logger.debug("VSS 'listKeyVersions' error: \(error)", context: "VssBackupClient") - throw error + try await coordinator.withClient(domain: .app, setup: { [self] in try await setup() }) { + Logger.debug("VSS 'listKeyVersions' call", context: "VssBackupClient") + do { + let versions = try await vssListKeys(prefix: nil) + Logger.debug("VSS 'listKeyVersions' success: \(versions.count) key(s)", context: "VssBackupClient") + return versions + } catch { + Logger.debug("VSS 'listKeyVersions' error: \(error)", context: "VssBackupClient") + throw error + } } } /// Deletes a single app-level key. func deleteKey(_ key: String) async throws -> Bool { - try await awaitSetup() - Logger.debug("VSS 'deleteKey' call for '\(key)'", context: "VssBackupClient") - do { - let wasDeleted = try await vssDelete(key: key) - Logger.debug("VSS 'deleteKey' success for '\(key)': \(wasDeleted)", context: "VssBackupClient") - return wasDeleted - } catch { - Logger.debug("VSS 'deleteKey' error for '\(key)': \(error)", context: "VssBackupClient") - throw error + try await coordinator.withClient(domain: .app, setup: { [self] in try await setup() }) { + Logger.debug("VSS 'deleteKey' call for '\(key)'", context: "VssBackupClient") + do { + let wasDeleted = try await vssDelete(key: key) + Logger.debug("VSS 'deleteKey' success for '\(key)': \(wasDeleted)", context: "VssBackupClient") + return wasDeleted + } catch { + Logger.debug("VSS 'deleteKey' error for '\(key)': \(error)", context: "VssBackupClient") + throw error + } } } /// Deletes all app-level keys (lists then deletes each). func deleteAllKeys() async throws { - let versions = try await listKeyVersions() - for kv in versions { - _ = try await deleteKey(kv.key) + try await coordinator.withClient(domain: .app, setup: { [self] in try await setup() }) { + let versions = try await vssListKeys(prefix: nil) + for version in versions { + _ = try await vssDelete(key: version.key) + } } } @@ -213,64 +299,56 @@ class VssBackupClient { /// Returns all LDK keys across default, monitors, and archivedMonitors namespaces. func listAllKeysTaggedLdk() async throws -> [(LdkNamespace, KeyVersion)] { - try await awaitLdkSetup() - Logger.debug("VSS 'listAllKeysTaggedLdk' call", context: "VssBackupClient") - var result: [(LdkNamespace, KeyVersion)] = [] - for ns in Self.ldkNamespacesForList { - do { - let keys = try await vssLdkListKeys(namespace: ns) - result.append(contentsOf: keys.map { (ns, $0) }) - } catch { - Logger.debug("VSS 'listAllKeysTaggedLdk' error for namespace \(ns): \(error)", context: "VssBackupClient") - throw error + try await coordinator.withClient(domain: .ldk, setup: { [self] in try await setupLdk() }) { + Logger.debug("VSS 'listAllKeysTaggedLdk' call", context: "VssBackupClient") + var result: [(LdkNamespace, KeyVersion)] = [] + for ns in Self.ldkNamespacesForList { + do { + let keys = try await vssLdkListKeys(namespace: ns) + result.append(contentsOf: keys.map { (ns, $0) }) + } catch { + Logger.debug("VSS 'listAllKeysTaggedLdk' error for namespace \(ns): \(error)", context: "VssBackupClient") + throw error + } } + Logger.debug("VSS 'listAllKeysTaggedLdk' success: \(result.count) key(s)", context: "VssBackupClient") + return result } - Logger.debug("VSS 'listAllKeysTaggedLdk' success: \(result.count) key(s)", context: "VssBackupClient") - return result } /// Gets a single LDK key value by key and namespace. func getObjectLdk(key: String, namespace: LdkNamespace) async throws -> VssItem? { - try await awaitLdkSetup() - Logger.debug("VSS 'getObjectLdk' call for '\(key)'", context: "VssBackupClient") - do { - return try await vssLdkGet(key: key, namespace: namespace) - } catch { - Logger.debug("VSS 'getObjectLdk' error for '\(key)': \(error)", context: "VssBackupClient") - throw error + try await coordinator.withClient(domain: .ldk, setup: { [self] in try await setupLdk() }) { + Logger.debug("VSS 'getObjectLdk' call for '\(key)'", context: "VssBackupClient") + do { + return try await vssLdkGet(key: key, namespace: namespace) + } catch { + Logger.debug("VSS 'getObjectLdk' error for '\(key)': \(error)", context: "VssBackupClient") + throw error + } } } /// Deletes a single LDK key by key and namespace. func deleteObjectLdk(key: String, namespace: LdkNamespace) async throws -> Bool { - try await awaitLdkSetup() - Logger.debug("VSS 'deleteObjectLdk' call for '\(key)'", context: "VssBackupClient") - do { - let wasDeleted = try await vssLdkDelete(key: key, namespace: namespace) - Logger.debug("VSS 'deleteObjectLdk' success for '\(key)': \(wasDeleted)", context: "VssBackupClient") - return wasDeleted - } catch { - Logger.debug("VSS 'deleteObjectLdk' error for '\(key)': \(error)", context: "VssBackupClient") - throw error + try await coordinator.withClient(domain: .ldk, setup: { [self] in try await setupLdk() }) { + Logger.debug("VSS 'deleteObjectLdk' call for '\(key)'", context: "VssBackupClient") + do { + let wasDeleted = try await vssLdkDelete(key: key, namespace: namespace) + Logger.debug("VSS 'deleteObjectLdk' success for '\(key)': \(wasDeleted)", context: "VssBackupClient") + return wasDeleted + } catch { + Logger.debug("VSS 'deleteObjectLdk' error for '\(key)': \(error)", context: "VssBackupClient") + throw error + } } } func deleteLdkScorerCache() async throws { - _ = try await deleteObjectLdk(key: "scorer", namespace: .default) - _ = try await deleteObjectLdk(key: "external_pathfinding_scores_cache", namespace: .default) - Logger.info("Cleared LDK scorer cache from VSS", context: "VssBackupClient") - } - - private func awaitSetup() async throws { - try await setupCoordinator.awaitSetup { [self] in - try await setup() - } - } - - /// Lazily sets up the LDK client when first needed (debug screen). Independent of the app client. - private func awaitLdkSetup() async throws { - try await ldkSetupCoordinator.awaitSetup { [self] in - try await setupLdk() + try await coordinator.withClient(domain: .ldk, setup: { [self] in try await setupLdk() }) { + _ = try await vssLdkDelete(key: "scorer", namespace: .default) + _ = try await vssLdkDelete(key: "external_pathfinding_scores_cache", namespace: .default) + Logger.info("Cleared LDK scorer cache from VSS", context: "VssBackupClient") } } diff --git a/Bitkit/Utilities/AppReset.swift b/Bitkit/Utilities/AppReset.swift index f309a6f018..8bf5cdffa2 100644 --- a/Bitkit/Utilities/AppReset.swift +++ b/Bitkit/Utilities/AppReset.swift @@ -39,9 +39,19 @@ enum AppReset { BackupService.shared.setWiping(false) } - // Stop backup observers and reset VSS client await BackupService.shared.stopObservingBackups() - await VssBackupClient.shared.reset() + try await VssBackupClient.shared.withSuspendedClients { + try await wipeWithClientsSuspended(app: app, wallet: wallet, session: session, toastType: toastType) + } + } + + @MainActor + private static func wipeWithClientsSuspended( + app: AppViewModel, + wallet: WalletViewModel, + session: SessionManager, + toastType: Toast.ToastType + ) async throws { VssStoreIdProvider.shared.clearCache() OnChainHwService.shared.stopAllWatchers() diff --git a/BitkitTests/VssClientCoordinatorTests.swift b/BitkitTests/VssClientCoordinatorTests.swift new file mode 100644 index 0000000000..503848776d --- /dev/null +++ b/BitkitTests/VssClientCoordinatorTests.swift @@ -0,0 +1,234 @@ +@testable import Bitkit +import XCTest + +final class VssClientCoordinatorTests: XCTestCase { + func testResetDrainsOldSetupAndRejectsLateCompletion() async throws { + let coordinator = VssClientCoordinator() + let gate = Gate() + let started = expectation(description: "Original setup started") + let cancelled = expectation(description: "Reset cancelled original setup") + let retired = expectation(description: "Retirement must await old setup") + let shutdowns = Counter() + let old = Task { + try await coordinator.withClient(domain: .app, setup: { + await withTaskCancellationHandler { + started.fulfill() + await gate.wait() + } onCancel: { cancelled.fulfill() } + }, operation: { XCTFail("Retired setup must not dispatch a call") }) + } + await fulfillment(of: [started], timeout: 2) + let reset = Task { await coordinator.reset { shutdowns.increment(); retired.fulfill() } } + await fulfillment(of: [cancelled], timeout: 2) + try await Task.sleep(nanoseconds: 100_000_000) + XCTAssertEqual(shutdowns.value, 0) + do { + try await coordinator.withClient(domain: .ldk, setup: { XCTFail("Admission during drain") }, operation: {}) + XCTFail("Admission during reset must fail") + } catch is CancellationError {} catch { XCTFail("Unexpected error: \(error)") } + await gate.release() + await assertCancelled(old) + await reset.value + await fulfillment(of: [retired], timeout: 2) + let replacement = expectation(description: "Replacement setup runs") + try await coordinator.withClient(domain: .app, setup: { replacement.fulfill() }, operation: {}) + await fulfillment(of: [replacement], timeout: 2) + } + + func testResetDrainsBothDomainsAndRejectsTheirResults() async throws { + let coordinator = VssClientCoordinator() + let appGate = Gate() + let ldkGate = Gate() + let started = expectation(description: "Both calls admitted") + started.expectedFulfillmentCount = 2 + let retired = expectation(description: "Both calls must drain before shutdown") + let shutdowns = Counter() + let app = Task { + try await coordinator.withClient(domain: .app, setup: {}, operation: { + started.fulfill() + await appGate.wait() + }) + } + let ldk = Task { + try await coordinator.withClient(domain: .ldk, setup: {}, operation: { + started.fulfill() + await ldkGate.wait() + }) + } + await fulfillment(of: [started], timeout: 2) + let reset = Task { await coordinator.reset { shutdowns.increment(); retired.fulfill() } } + await waitForClosedAdmission(coordinator) + try await Task.sleep(nanoseconds: 100_000_000) + XCTAssertEqual(shutdowns.value, 0) + await appGate.release() + await assertCancelled(app) + try await Task.sleep(nanoseconds: 100_000_000) + XCTAssertEqual(shutdowns.value, 0) + await ldkGate.release() + await assertCancelled(ldk) + await reset.value + await fulfillment(of: [retired], timeout: 2) + } + + func testCancelledResetStillWaitsForNativeCall() async throws { + let coordinator = VssClientCoordinator() + let gate = Gate() + let started = expectation(description: "Call admitted") + let retired = expectation(description: "Native retirement") + let shutdowns = Counter() + let old = Task { + try await coordinator.withClient(domain: .app, setup: {}, operation: { + started.fulfill() + await gate.wait() + }) + } + await fulfillment(of: [started], timeout: 2) + let reset = Task { await coordinator.reset { shutdowns.increment(); retired.fulfill() } } + await waitForClosedAdmission(coordinator) + reset.cancel() + try await Task.sleep(nanoseconds: 100_000_000) + XCTAssertEqual(shutdowns.value, 0) + await gate.release() + await assertCancelled(old) + await reset.value + await fulfillment(of: [retired], timeout: 2) + XCTAssertEqual(shutdowns.value, 1) + try await coordinator.withClient(domain: .app, setup: {}, operation: {}) + } + + func testAdmissionStaysClosedThroughoutCredentialRemovalAndReopensAfterFailure() async throws { + let coordinator = VssClientCoordinator() + try await coordinator.withClient(domain: .app, setup: {}, operation: {}) + do { + try await coordinator.withSuspendedClients(shutdown: {}, operation: { + for domain in [VssClientCoordinator.Domain.app, .ldk] { + do { + try await coordinator.withClient(domain: domain, setup: { + XCTFail("Old credentials must not be read") + }, operation: {}) + XCTFail("Wallet transition must keep admission closed") + } catch is CancellationError {} catch { XCTFail("Unexpected error: \(error)") } + } + throw URLError(.cannotWriteToFile) + }) + XCTFail("Transition failure must propagate") + } catch let error as URLError { XCTAssertEqual(error.code, .cannotWriteToFile) } + let setup = expectation(description: "Failure still retires cached setup") + try await coordinator.withClient(domain: .app, setup: { setup.fulfill() }, operation: {}) + await fulfillment(of: [setup], timeout: 2) + } + + func testRetiredNativeFailureIsCancellationRatherThanNewOwnerAuthFailure() async { + let coordinator = VssClientCoordinator() + let gate = Gate() + let started = expectation(description: "Old call admitted") + let old = Task { + try await coordinator.withClient(domain: .app, setup: {}, operation: { + started.fulfill() + await gate.wait() + throw URLError(.userAuthenticationRequired) + }) + } + await fulfillment(of: [started], timeout: 2) + let reset = Task { await coordinator.reset {} } + await waitForClosedAdmission(coordinator) + await gate.release() + await assertCancelled(old) + await reset.value + } + + func testConcurrentCallsShareSetupAndRemainConcurrent() async throws { + let coordinator = VssClientCoordinator() + let setupGate = Gate() + let callGate = Gate() + let setupStarted = expectation(description: "One setup") + setupStarted.assertForOverFulfill = true + let callsStarted = expectation(description: "Both calls run concurrently") + callsStarted.expectedFulfillmentCount = 2 + let setup = { setupStarted.fulfill(); await setupGate.wait() } + let operation = { callsStarted.fulfill(); await callGate.wait() } + let first = Task { try await coordinator.withClient(domain: .app, setup: setup, operation: operation) } + await fulfillment(of: [setupStarted], timeout: 2) + let second = Task { try await coordinator.withClient(domain: .app, setup: setup, operation: operation) } + await setupGate.release() + await fulfillment(of: [callsStarted], timeout: 2) + await callGate.release() + try await first.value + try await second.value + } + + func testFailedSetupCanRetryWithoutAdmittingItsOperation() async throws { + let coordinator = VssClientCoordinator() + do { + try await coordinator.withClient(domain: .app, setup: { throw URLError(.notConnectedToInternet) }, operation: { + XCTFail("Failed setup must not dispatch") + }) + XCTFail("Setup must fail") + } catch let error as URLError { XCTAssertEqual(error.code, .notConnectedToInternet) } + let value = try await coordinator.withClient(domain: .app, setup: {}, operation: { 42 }) + XCTAssertEqual(value, 42) + } + + func testCancelledWaiterDoesNotInvalidateSuccessfulSharedSetup() async throws { + let coordinator = VssClientCoordinator() + let gate = Gate() + let started = expectation(description: "Setup started") + let first = Task { + try await coordinator.withClient(domain: .app, setup: { + started.fulfill() + await gate.wait() + }, operation: { XCTFail("Cancelled caller must not dispatch") }) + } + await fulfillment(of: [started], timeout: 2) + first.cancel() + await gate.release() + await assertCancelled(first) + try await coordinator.withClient(domain: .app, setup: { XCTFail("Setup already succeeded") }, operation: {}) + } + + private func assertCancelled(_ task: Task, file: StaticString = #filePath, line: UInt = #line) async { + do { + try await task.value + XCTFail("Retired call must fail", file: file, line: line) + } catch is CancellationError {} catch { XCTFail("Unexpected error: \(error)", file: file, line: line) } + } + + private func waitForClosedAdmission(_ coordinator: VssClientCoordinator) async { + for _ in 0 ..< 100 { + do { try await coordinator.withClient(domain: .app, setup: {}, operation: {}) } + catch is CancellationError { return } + catch { XCTFail("Unexpected error: \(error)"); return } + await Task.yield() + } + XCTFail("Reset did not close admission") + } + + private final class Counter: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + var value: Int { + lock.withLock { count } + } + + func increment() { + lock.withLock { count += 1 } + } + } + + /// Deliberately ignores cancellation, like a native FFI call already in progress. + private actor Gate { + private var released = false + private var waiters: [CheckedContinuation] = [] + func wait() async { + guard !released else { return } + await withCheckedContinuation { waiters.append($0) } + } + + func release() { + released = true + let pending = waiters + waiters.removeAll() + pending.forEach { $0.resume() } + } + } +} diff --git a/changelog.d/next/1121.fixed.md b/changelog.d/next/1121.fixed.md index 7a81bf8089..02bcfbd43b 100644 --- a/changelog.d/next/1121.fixed.md +++ b/changelog.d/next/1121.fixed.md @@ -1 +1 @@ -Wallet restore finishes without waiting for optional profile refresh, retries missing profile data after reconnecting, and preserves complete backups when identity or cached channel data is unavailable. +Wallet restore finishes without waiting for optional profile refresh, retries missing profile data after reconnecting, preserves complete backups when identity or cached channel data is unavailable, and keeps retired backup calls from crossing wallet resets. From 154326affef9a14f5c235b93aedab85d9bff253b Mon Sep 17 00:00:00 2001 From: benk10 Date: Thu, 5 Nov 2026 06:33:41 -0500 Subject: [PATCH 34/45] fix: bound wipe drain waits and isolate event acknowledgements --- .../Services/ConnectionRecoveryService.swift | 9 +++- Bitkit/Services/NodeEventListener.swift | 2 +- Bitkit/Services/ServiceQueue.swift | 4 ++ Bitkit/Utilities/AppReset.swift | 3 +- .../ConnectionRecoveryServiceTests.swift | 42 +++++++++++++++++++ BitkitTests/NodeEventListenerTests.swift | 40 ++++++++++++++++++ 6 files changed, 96 insertions(+), 4 deletions(-) diff --git a/Bitkit/Services/ConnectionRecoveryService.swift b/Bitkit/Services/ConnectionRecoveryService.swift index 6ce06a856f..9189de7fcc 100644 --- a/Bitkit/Services/ConnectionRecoveryService.swift +++ b/Bitkit/Services/ConnectionRecoveryService.swift @@ -136,14 +136,19 @@ final class ConnectionRecoveryService: ObservableObject { } } - func beginWipe() async throws -> UUID { + 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?() - await drainActive?() + 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 } diff --git a/Bitkit/Services/NodeEventListener.swift b/Bitkit/Services/NodeEventListener.swift index 0ab152040f..42ddbc36a1 100644 --- a/Bitkit/Services/NodeEventListener.swift +++ b/Bitkit/Services/NodeEventListener.swift @@ -54,7 +54,7 @@ final class NodeEventListener { 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(.ldk) { () -> Event? in + let event = try? await ServiceQueue.background(.ldkEvents) { () -> Event? in guard let event = node.nextEvent() else { return nil } do { try node.eventHandled() 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 bd74e8d7a5..838ad33745 100644 --- a/Bitkit/Utilities/AppReset.swift +++ b/Bitkit/Utilities/AppReset.swift @@ -63,9 +63,10 @@ final class AppReset: WipeStepExecutor { static func withConnectionRecoveryPaused( recovery: ConnectionRecoveryService, + timeout: Duration = waitTimeout, operation: () async throws -> Void ) async throws { - let connectionWipe = try await recovery.beginWipe() + 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() } diff --git a/BitkitTests/ConnectionRecoveryServiceTests.swift b/BitkitTests/ConnectionRecoveryServiceTests.swift index 90ac51c843..48bb6f5219 100644 --- a/BitkitTests/ConnectionRecoveryServiceTests.swift +++ b/BitkitTests/ConnectionRecoveryServiceTests.swift @@ -575,6 +575,48 @@ final class ConnectionRecoveryServiceTests: XCTestCase { 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 { diff --git a/BitkitTests/NodeEventListenerTests.swift b/BitkitTests/NodeEventListenerTests.swift index 077edbdb01..12bf5f731f 100644 --- a/BitkitTests/NodeEventListenerTests.swift +++ b/BitkitTests/NodeEventListenerTests.swift @@ -81,6 +81,44 @@ final class NodeEventListenerTests: XCTestCase { 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()) @@ -222,6 +260,7 @@ private final class EventNode: Node { var onStart: (() -> Void)? var onEmpty: (() -> Void)? var onStop: (() -> Void)? + var onHandled: (() -> Void)? private let lock = NSLock() private var running = false private var event: Event? @@ -272,6 +311,7 @@ private final class EventNode: Node { } override func eventHandled() throws { + onHandled?() lock.withLock { handledCount += 1 event = nil From fb8cddb2953f25ecfc4f6ba03c32046f9aede289 Mon Sep 17 00:00:00 2001 From: benk10 Date: Thu, 5 Nov 2026 10:59:27 -0500 Subject: [PATCH 35/45] test: await both Jade connection teardown effects --- BitkitTests/HwConnectViewModelTests.swift | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/BitkitTests/HwConnectViewModelTests.swift b/BitkitTests/HwConnectViewModelTests.swift index 78eadbbc3e..11ed47c25b 100644 --- a/BitkitTests/HwConnectViewModelTests.swift +++ b/BitkitTests/HwConnectViewModelTests.swift @@ -702,7 +702,10 @@ final class HwConnectViewModelTests: XCTestCase { connectService.cancelPendingConnection(to: jadeDevice) - await waitUntil { self.jadeLog.contains("service.disconnect.done") } + await waitUntil { + self.jadeLog.contains("service.disconnect.done") && + self.jadeLog.contains("transport.disconnect:\(JadeFixtures.blePath)") + } XCTAssertTrue(jadeLog.contains("service.cancel")) XCTAssertTrue(jadeLog.contains("transport.disconnect:\(JadeFixtures.blePath)")) } From 1c3cde650bd42e1189e50c1f0d256f6b930905ec Mon Sep 17 00:00:00 2001 From: benk10 Date: Thu, 5 Nov 2026 17:13:12 -0500 Subject: [PATCH 36/45] fix: resume metadata backup after wallet recovery --- Bitkit/Services/BackupService.swift | 31 ++++++++++++- BitkitTests/BackupServiceTests.swift | 68 +++++++++++++++++++++++++++- changelog.d/next/1121.fixed.md | 2 +- 3 files changed, 97 insertions(+), 4 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 242c5dc7f5..83a8c20e58 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -104,6 +104,7 @@ class BackupService { case snapshotChanged case busy case temporarilyUnavailable + case walletDependencyFailed case failed var canRetryPendingBackup: Bool { @@ -134,6 +135,7 @@ class BackupService { private let uploadBackup: (String, Data) async throws -> Void private let waitForBackupDelay: () async throws -> Void private let waitForTemporaryFailureDelay: (UInt64) async throws -> Void + private let waitForScheduledBackupCompletion: (BackupCategory, BackupOutcome) async -> Void private let waitForForegroundRecoveryTimeout: () async throws -> Void private static let backupStatusesKey = "backupStatuses" private var backupVersions: [BackupCategory: UInt64] = [:] @@ -170,6 +172,7 @@ class BackupService { waitForTemporaryFailureDelay: @escaping (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }, + waitForScheduledBackupCompletion: @escaping (BackupCategory, BackupOutcome) async -> Void = { _, _ in }, waitForForegroundRecoveryTimeout: @escaping () async throws -> Void = { try await Task.sleep(for: .seconds(BackupService.backupFailureCheckInterval)) } @@ -180,6 +183,7 @@ class BackupService { self.uploadBackup = uploadBackup self.waitForBackupDelay = waitForBackupDelay self.waitForTemporaryFailureDelay = waitForTemporaryFailureDelay + self.waitForScheduledBackupCompletion = waitForScheduledBackupCompletion self.waitForForegroundRecoveryTimeout = waitForForegroundRecoveryTimeout let statuses = getAllBackupStatuses() var clearedStatuses = statuses @@ -383,6 +387,7 @@ class BackupService { } private func runBackup(category: BackupCategory, isScheduled: Bool) async -> BackupOutcome { + let generation = stateQueue.sync { foregroundObservationGeneration } Logger.debug("Backup starting for: '\(category.rawValue)'", context: "BackupService") var outcome = BackupOutcome.failed var requiredAtStart: UInt64 = 0 @@ -455,11 +460,19 @@ class BackupService { outcome = .temporarilyUnavailable Logger.warn("Backup temporarily unavailable for: '\(category.rawValue)'", context: "BackupService") } else { + if case MetadataBackupError.walletBackupFailed = error { + outcome = .walletDependencyFailed + } Logger.error("Backup failed for: '\(category.rawValue)': \(error)", context: "BackupService") checkForFailedBackups() } } _ = try? await ServiceQueue.background(.backup) { self.runningBackupTasks.removeValue(forKey: category) } + if category == .wallet, outcome == .completed { + await resumeMetadataAfterWalletBackup(generation: generation) + } else if category == .metadata, outcome == .walletDependencyFailed { + await resumeMetadataAfterWalletBackup(generation: generation) + } return outcome } @@ -1025,11 +1038,14 @@ class BackupService { running: true ) } - backupJobs[category] = Task { await self.runScheduledBackup(category: category, initialOutcome: initialOutcome) } + let generation = stateQueue.sync { self.foregroundObservationGeneration } + backupJobs[category] = Task { + await self.runScheduledBackup(category: category, initialOutcome: initialOutcome, generation: generation) + } } } - private func runScheduledBackup(category: BackupCategory, initialOutcome: BackupOutcome) async { + private func runScheduledBackup(category: BackupCategory, initialOutcome: BackupOutcome, generation: UInt64) async { var outcome = initialOutcome var retryDelay: UInt64 = 10_000_000_000 while !Task.isCancelled { @@ -1051,10 +1067,15 @@ class BackupService { break } } + await waitForScheduledBackupCompletion(category, outcome) _ = try? await ServiceQueue.background(.backup) { self.backupJobs.removeValue(forKey: category) } updateBackupStatus(category: category) { status in BackupItemStatus(synced: status.synced, required: status.required, running: false) } + // A wallet recovery may have arrived while this metadata job still occupied its slot. + if category == .metadata, outcome == .walletDependencyFailed { + await resumeMetadataAfterWalletBackup(generation: generation) + } if outcome.canRetryPendingBackup, !Task.isCancelled, getBackupStatus(category: category).isRequired, !shouldSkipBackup(category: category) { @@ -1062,6 +1083,12 @@ class BackupService { } } + private func resumeMetadataAfterWalletBackup(generation: UInt64) async { + guard !Task.isCancelled, !getBackupStatus(category: .wallet).isRequired, + getBackupStatus(category: .metadata).isRequired else { return } + await scheduleBackup(category: .metadata, foregroundGeneration: generation) + } + private func checkForFailedBackups() { let currentTime = UInt64(Date().timeIntervalSince1970) if hasFailedBackups(at: currentTime) { diff --git a/BitkitTests/BackupServiceTests.swift b/BitkitTests/BackupServiceTests.swift index 5a2a7a36c8..2eab8dbf85 100644 --- a/BitkitTests/BackupServiceTests.swift +++ b/BitkitTests/BackupServiceTests.swift @@ -515,7 +515,8 @@ final class BackupServiceTests: XCTestCase { let failedAttempts = await remote.attemptedKeys let metadata = await remote.metadata let wallet = await remote.wallet - XCTAssertTrue(outcome == .failed) + XCTAssertTrue(outcome == .walletDependencyFailed) + XCTAssertFalse(outcome.canRetryPendingBackup) XCTAssertEqual(failedAttempts, [BackupCategory.wallet.rawValue]) XCTAssertEqual(metadata, LegacyMetadataBackupServer.legacyMetadata) XCTAssertEqual(wallet, LegacyMetadataBackupServer.legacyWallet) @@ -534,6 +535,71 @@ final class BackupServiceTests: XCTestCase { await restarted.stopObservingBackups() } + func testWalletRecoveryResumesMetadataAfterFailedJobRetires() async throws { + for stopBeforeRetirement in [false, true] { + let remote = LegacyMetadataBackupServer(failWalletUpload: true) + let defaults = try makeLegacyMetadataBackupDefaults() + let pending = BackupItemStatus(synced: 1, required: 2, running: false) + try defaults.set(JSONEncoder().encode([ + BackupCategory.wallet.rawValue: pending, + BackupCategory.metadata.rawValue: pending, + ]), forKey: "backupStatuses") + let held = expectation(description: "Failed metadata job still occupies its slot") + let completed = expectation(description: "Pending metadata resumes only in its active generation") + completed.isInverted = stopBeforeRetirement + let (retirement, releaseRetirement) = AsyncStream.makeStream() + defer { releaseRetirement.finish() } + let service = BackupService( + defaults: defaults, + backupData: { try await remote.backupData(for: $0) }, + uploadBackup: { try await remote.upload(key: $0, data: $1) }, + waitForBackupDelay: { await Task.yield() }, + waitForScheduledBackupCompletion: { category, outcome in + if category == .metadata, outcome == .walletDependencyFailed { + held.fulfill() + for await _ in retirement {} + } + } + ) + let subscription = service.backupStatusesPublisher + .filter { $0[.metadata].map { !$0.running && !$0.isRequired } == true } + .first().sink { _ in completed.fulfill() } + defer { subscription.cancel() } + + await service.startObservingBackups()?.value + await fulfillment(of: [held], timeout: 2) + XCTAssertEqual(service.getBackupStatus(category: .metadata).required, pending.required) + let retainedMetadata = await remote.metadata + XCTAssertEqual(retainedMetadata, LegacyMetadataBackupServer.legacyMetadata) + + await remote.setWalletUploadFailure(false) + let recovered = await service.triggerBackup(category: .wallet) + XCTAssertTrue(recovered == .completed) + let heldUploads = await remote.successfulKeys + XCTAssertEqual(heldUploads, [BackupCategory.wallet.rawValue]) + if stopBeforeRetirement { + service.setWiping(true) + let stopping = service.requestStopObservingBackups() + releaseRetirement.finish() + await stopping.value + } else { + releaseRetirement.finish() + } + await fulfillment(of: [completed], timeout: stopBeforeRetirement ? 0.2 : 2) + service.setWiping(true) + await service.stopObservingBackups() + + if stopBeforeRetirement { + let uploads = await remote.successfulKeys + XCTAssertEqual(uploads, [BackupCategory.wallet.rawValue]) + } else { + await assertWalletExclusionsPrecedeMetadataReplacement(remote) + } + XCTAssertEqual(service.getBackupStatus(category: .metadata).required, pending.required) + XCTAssertEqual(service.getBackupStatus(category: .metadata).isRequired, stopBeforeRetirement) + } + } + func testTemporaryWalletFailureKeepsMetadataRetryable() async throws { let remote = LegacyMetadataBackupServer() let defaults = try makeLegacyMetadataBackupDefaults() diff --git a/changelog.d/next/1121.fixed.md b/changelog.d/next/1121.fixed.md index 02bcfbd43b..44fec70bfa 100644 --- a/changelog.d/next/1121.fixed.md +++ b/changelog.d/next/1121.fixed.md @@ -1 +1 @@ -Wallet restore finishes without waiting for optional profile refresh, retries missing profile data after reconnecting, preserves complete backups when identity or cached channel data is unavailable, and keeps retired backup calls from crossing wallet resets. +Wallet restore finishes without waiting for optional profile refresh, retries missing profile data after reconnecting, resumes pending metadata after wallet backup recovers, preserves complete backups when identity or cached channel data is unavailable, and keeps retired backup calls from crossing wallet resets. From eff0dadf1f391335ad327cb56e9534aec1c47250 Mon Sep 17 00:00:00 2001 From: benk10 Date: Fri, 6 Nov 2026 11:05:34 -0500 Subject: [PATCH 37/45] fix: preserve backup work across observation restarts --- Bitkit/Services/BackupService.swift | 120 ++++++++++++-------- BitkitTests/BackupServiceTests.swift | 159 +++++++++++++++++++++++++++ 2 files changed, 234 insertions(+), 45 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 83a8c20e58..5f815c2c32 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -325,31 +325,44 @@ class BackupService { func requestStopObservingBackups() -> Task { let request = nextObservationRequest() return Task { - let stopped = try? await ServiceQueue.background(.backup) { () -> (wasObserving: Bool, generation: UInt64)? in - guard self.stateQueue.sync(execute: { self.observationRequestGeneration == request }) else { return nil } - let wasObserving = self.isObserving - self.isObserving = false - let generation = self.stateQueue.sync { + typealias Observation = (wasObserving: Bool, observers: UInt64, foreground: UInt64) + let stopped = try? await ServiceQueue.background(.backup) { [self] () -> ( + metadata: Task?, + observation: Observation? + ) in + let metadata = runningBackupTasks[.metadata] + guard stateQueue.sync(execute: { observationRequestGeneration == request }) else { + return (metadata, nil) + } + let wasObserving = isObserving + isObserving = false + let generation = stateQueue.sync { self.foregroundObservationGeneration &+= 1 self.observationGeneration &+= 1 - return self.observationGeneration + return (wasObserving, self.observationGeneration, self.foregroundObservationGeneration) } - self.backupJobs.values.forEach { $0.cancel() } - self.backupJobs.removeAll() - self.runningBackupTasks.values.forEach { $0.cancel() } - self.periodicCheckTask?.cancel() - self.periodicCheckTask = nil - return (wasObserving: wasObserving, generation: generation) + for (category, job) in backupJobs { + job.cancel() + clearScheduledBackupStatus(category: category) + } + backupJobs.removeAll() + runningBackupTasks.values.forEach { $0.cancel() } + periodicCheckTask?.cancel() + periodicCheckTask = nil + return (metadata, generation) } - let metadataTask = try? await ServiceQueue.background(.backup) { self.runningBackupTasks[.metadata] } - _ = await metadataTask?.value + _ = await stopped?.metadata?.value + if stopped?.metadata != nil, let observation = stopped?.observation { + // A new observer may have seen only the running status of the cancelled upload. + await resumeMetadataAfterWalletBackup(generation: observation.foreground) + } await walletBackupWriter.waitUntilIdle() await usdtBackupWriter.waitUntilIdle() - guard let stopped else { return } - await removeBackupObservers(generation: stopped.generation) - guard stopped.wasObserving else { return } + guard let observation = stopped?.observation else { return } + await removeBackupObservers(generation: observation.observers) + guard observation.wasObserving else { return } Logger.debug("Stopped observing backup statuses and data store changes", context: "BackupService") } } @@ -366,8 +379,13 @@ class BackupService { await triggerBackup(category: category, isScheduled: false) } - private func triggerBackup(category: BackupCategory, isScheduled: Bool, waitForExisting: Bool = false) async -> BackupOutcome { + private func triggerBackup(category: BackupCategory, isScheduled: Bool, waitForExisting: Bool = false, + generation: UInt64? = nil) async -> BackupOutcome + { let work = try? await ServiceQueue.background(.backup) { [self] () -> (task: Task, owned: Bool)? in + if let generation, stateQueue.sync(execute: { foregroundObservationGeneration != generation }) { + return nil + } if let existing = runningBackupTasks[category] { return waitForExisting ? (existing, false) : nil } @@ -416,7 +434,7 @@ class BackupService { } } else { if category == .metadata { - try await prepareMetadataBackup() + try await prepareMetadataBackup(generation: generation) } let data = try await getBackupDataBytes(category: category) if category == .metadata { @@ -476,11 +494,11 @@ class BackupService { return outcome } - private func prepareMetadataBackup() async throws { + private func prepareMetadataBackup(generation: UInt64) async throws { try Task.checkCancellation() guard !shouldSkipBackup(), !hasPendingWalletRestore() else { throw MetadataBackupError.deferred } if getBackupStatus(category: .wallet).isRequired { - let outcome = await triggerBackup(category: .wallet, isScheduled: true, waitForExisting: true) + let outcome = await triggerBackup(category: .wallet, isScheduled: true, waitForExisting: true, generation: generation) try Task.checkCancellation() if outcome == .temporarilyUnavailable { throw MetadataBackupError.walletTemporarilyUnavailable @@ -1025,23 +1043,35 @@ class BackupService { private func scheduleBackup(category: BackupCategory, initialOutcome: BackupOutcome = .failed, foregroundGeneration: UInt64? = nil) async { try? await ServiceQueue.background(.backup) { [self] in - if let foregroundGeneration { - guard isObserving, !shouldSkipBackup(category: category), - stateQueue.sync(execute: { foregroundObservationGeneration == foregroundGeneration }) - else { return } - } - guard backupJobs[category] == nil else { return } - updateBackupStatus(category: category) { status in - BackupItemStatus( - synced: status.synced, - required: status.required, - running: true - ) - } let generation = stateQueue.sync { self.foregroundObservationGeneration } - backupJobs[category] = Task { - await self.runScheduledBackup(category: category, initialOutcome: initialOutcome, generation: generation) + if let foregroundGeneration { + guard isObserving, !shouldSkipBackup(category: category), generation == foregroundGeneration else { return } } + enqueueBackup(category: category, initialOutcome: initialOutcome, generation: generation) + } + } + + #if DEBUG + func scheduledBackupTask(for category: BackupCategory) async -> Task? { + try? await ServiceQueue.background(.backup) { self.backupJobs[category] } + } + #endif + + /// Must run on the backup queue so slot registration and retirement are serialized. + private func enqueueBackup(category: BackupCategory, initialOutcome: BackupOutcome, generation: UInt64) { + guard backupJobs[category] == nil else { return } + updateBackupStatus(category: category) { status in + BackupItemStatus(synced: status.synced, required: status.required, running: true) + } + backupJobs[category] = Task { + await self.runScheduledBackup(category: category, initialOutcome: initialOutcome, generation: generation) + } + } + + private func clearScheduledBackupStatus(category: BackupCategory) { + guard runningBackupTasks[category] == nil else { return } + updateBackupStatus(category: category) { status in + BackupItemStatus(synced: status.synced, required: status.required, running: false) } } @@ -1062,25 +1092,25 @@ class BackupService { break } guard getBackupStatus(category: category).isRequired && !shouldSkipBackup(category: category) else { break } - outcome = await triggerBackup(category: category, isScheduled: true) + outcome = await triggerBackup(category: category, isScheduled: true, generation: generation) if !outcome.canRetryPendingBackup || !getBackupStatus(category: category).isRequired { break } } await waitForScheduledBackupCompletion(category, outcome) - _ = try? await ServiceQueue.background(.backup) { self.backupJobs.removeValue(forKey: category) } - updateBackupStatus(category: category) { status in - BackupItemStatus(synced: status.synced, required: status.required, running: false) + let shouldRetry = outcome.canRetryPendingBackup && !Task.isCancelled + try? await ServiceQueue.background(.backup) { [self] in + guard stateQueue.sync(execute: { foregroundObservationGeneration == generation }) else { return } + backupJobs.removeValue(forKey: category) + clearScheduledBackupStatus(category: category) + if shouldRetry, getBackupStatus(category: category).isRequired, !shouldSkipBackup(category: category) { + enqueueBackup(category: category, initialOutcome: .failed, generation: generation) + } } // A wallet recovery may have arrived while this metadata job still occupied its slot. if category == .metadata, outcome == .walletDependencyFailed { await resumeMetadataAfterWalletBackup(generation: generation) } - if outcome.canRetryPendingBackup, !Task.isCancelled, - getBackupStatus(category: category).isRequired, !shouldSkipBackup(category: category) - { - await scheduleBackup(category: category) - } } private func resumeMetadataAfterWalletBackup(generation: UInt64) async { diff --git a/BitkitTests/BackupServiceTests.swift b/BitkitTests/BackupServiceTests.swift index 2eab8dbf85..b20529d413 100644 --- a/BitkitTests/BackupServiceTests.swift +++ b/BitkitTests/BackupServiceTests.swift @@ -600,6 +600,165 @@ final class BackupServiceTests: XCTestCase { } } + func testRestartKeepsNewMetadataJobWhenOldWalletDependencyFailureRetires() async throws { + let remote = LegacyMetadataBackupServer(failWalletUpload: true) + let defaults = try makeLegacyMetadataBackupDefaults() + let pending = BackupItemStatus(synced: 1, required: 2, running: false) + try defaults.set(JSONEncoder().encode([ + BackupCategory.wallet.rawValue: pending, + BackupCategory.metadata.rawValue: pending, + ]), forKey: "backupStatuses") + let held = expectation(description: "Failed metadata job is retiring") + let walletFailed = expectation(description: "Scheduled wallet attempt failed") + let uploading = expectation(description: "Restarted metadata upload is in flight") + let completed = expectation(description: "Restarted metadata is synced") + let (retirement, release) = AsyncStream.makeStream() + // Keep the old job at retirement even when observation cancels it. + let permissionToRetire = Task { for await _ in retirement {} } + let (upload, releaseUpload) = AsyncStream.makeStream() + defer { + release.finish() + releaseUpload.finish() + } + let service = BackupService( + defaults: defaults, + backupData: { try await remote.backupData(for: $0) }, + uploadBackup: { key, data in + if key == BackupCategory.metadata.rawValue { + uploading.fulfill() + for await _ in upload {} + } + try Task.checkCancellation() + try await remote.upload(key: key, data: data) + }, + waitForBackupDelay: { await Task.yield() }, + waitForScheduledBackupCompletion: { category, outcome in + if category == .wallet, outcome == .failed { + walletFailed.fulfill() + } + if category == .metadata, outcome == .walletDependencyFailed { + held.fulfill() + await permissionToRetire.value + } + } + ) + let synced = service.backupStatusesPublisher + .filter { $0[.metadata].map { !$0.running && !$0.isRequired } == true } + .first().sink { _ in completed.fulfill() } + defer { synced.cancel() } + + await service.startObservingBackups()?.value + await fulfillment(of: [held, walletFailed], timeout: 2) + let old = await service.scheduledBackupTask(for: .metadata) + XCTAssertNotNil(old) + await remote.setWalletUploadFailure(false) + let recovered = await service.triggerBackup(category: .wallet) + XCTAssertEqual(recovered, .completed) + await service.stopObservingBackups() + await service.startObservingBackups()?.value + await fulfillment(of: [uploading], timeout: 2) + + let replacement = await service.scheduledBackupTask(for: .metadata) + XCTAssertNotNil(replacement) + release.finish() + await old?.value + let registered = await service.scheduledBackupTask(for: .metadata) + XCTAssertEqual(registered, replacement) + XCTAssertEqual( + service.getBackupStatus(category: .metadata), + BackupItemStatus(synced: pending.synced, required: pending.required, running: true) + ) + releaseUpload.finish() + await fulfillment(of: [completed], timeout: 2) + await assertWalletExclusionsPrecedeMetadataReplacement(remote) + await service.stopObservingBackups() + } + + func testStoppingDelayedBackupLeavesPendingWorkAvailableOnRestart() async throws { + let defaults = try makeIsolatedDefaults() + let waiting = expectation(description: "Scheduled backup is in its delay") + let uploaded = expectation(description: "Restart uploads the pending backup") + let (delay, release) = AsyncStream.makeStream() + let firstDelay = Task { for await _ in delay {} } + defer { release.finish() } + let service = BackupService( + defaults: defaults, + backupData: { _ in Data("settings".utf8) }, + uploadBackup: { key, _ in + XCTAssertEqual(key, BackupCategory.settings.rawValue) + uploaded.fulfill() + }, + waitForBackupDelay: { + waiting.fulfill() + await firstDelay.value + } + ) + // Both observation generations enter the delay. Only the first entry gates the stop. + waiting.assertForOverFulfill = false + await service.startObservingBackups()?.value + service.markBackupRequired(category: .settings) + await fulfillment(of: [waiting], timeout: 2) + let scheduled = service.getBackupStatus(category: .settings) + await service.stopObservingBackups() + XCTAssertTrue(scheduled.isRequired) + XCTAssertEqual( + service.getBackupStatus(category: .settings), + BackupItemStatus(synced: scheduled.synced, required: scheduled.required, running: false) + ) + await service.startObservingBackups()?.value + release.finish() + await fulfillment(of: [uploaded], timeout: 2) + await service.stopObservingBackups() + } + + func testRestartWhileCancelledMetadataReadDrainsResumesPendingBackup() async throws { + let remote = LegacyMetadataBackupServer() + let defaults = try makeLegacyMetadataBackupDefaults() + let reading = expectation(description: "Metadata export is held") + let cancelled = expectation(description: "Stop cancelled the active export") + let completed = expectation(description: "Restarted export is synced") + let (gate, release) = AsyncStream.makeStream() + let held = Task { for await _ in gate {} } + defer { release.finish() } + var firstMetadata = true + let service = BackupService( + defaults: defaults, + backupData: { category in + if category == .metadata, firstMetadata { + firstMetadata = false + await withTaskCancellationHandler { + reading.fulfill() + await held.value + } onCancel: { + cancelled.fulfill() + } + try Task.checkCancellation() + } + return try await remote.backupData(for: category) + }, + uploadBackup: { try await remote.upload(key: $0, data: $1) }, + waitForBackupDelay: { await Task.yield() } + ) + let wallet = await service.triggerBackup(category: .wallet) + XCTAssertEqual(wallet, .completed) + service.markBackupRequired(category: .metadata, schedule: false) + let subscription = service.backupStatusesPublisher + .filter { $0[.metadata].map { !$0.running && !$0.isRequired } == true } + .first().sink { _ in completed.fulfill() } + defer { subscription.cancel() } + + await service.startObservingBackups()?.value + await fulfillment(of: [reading], timeout: 2) + let stopping = service.requestStopObservingBackups() + await fulfillment(of: [cancelled], timeout: 2) + await service.startObservingBackups()?.value + release.finish() + await stopping.value + await fulfillment(of: [completed], timeout: 2) + await assertWalletExclusionsPrecedeMetadataReplacement(remote) + await service.stopObservingBackups() + } + func testTemporaryWalletFailureKeepsMetadataRetryable() async throws { let remote = LegacyMetadataBackupServer() let defaults = try makeLegacyMetadataBackupDefaults() From 0ad55417a1f43de50e71f52e645d5eeeff866353 Mon Sep 17 00:00:00 2001 From: benk10 Date: Fri, 6 Nov 2026 14:58:16 -0500 Subject: [PATCH 38/45] test: wait for the USDT quote before navigating back --- BitkitUITests/UsdtWalletUITests.swift | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/BitkitUITests/UsdtWalletUITests.swift b/BitkitUITests/UsdtWalletUITests.swift index 067eda4cf2..3d7a948956 100644 --- a/BitkitUITests/UsdtWalletUITests.swift +++ b/BitkitUITests/UsdtWalletUITests.swift @@ -300,12 +300,30 @@ final class UsdtWalletUITests: XCTestCase { "ethereum:0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9@42161/transfer?address=0x0000000000000000000000000000000000000001&uint256=1.23e6" ) app.buttons["UsdtRecipientContinue"].tap() - // A URI with an amount fixes it: the review opens instead of the editable Amount step. - XCTAssertTrue(app.descendants(matching: .any)["UsdtConfirmLoading"].waitForExistence(timeout: 5)) + // A fixed URI opens review. Back is disabled while the quote is being prepared. + let retryQuote = app.buttons.matching(NSPredicate( + format: "identifier == %@ OR (identifier == %@ AND label == %@)", + "UsdtRetryQuote", "UsdtConfirmLoading", "Try Again" + )).firstMatch + let reviewDetails = app.buttons["UsdtReviewDetails"] + let settled = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + reviewDetails.exists || (retryQuote.exists && retryQuote.isEnabled) + }, object: nil) + XCTAssertEqual(XCTWaiter.wait(for: [settled], timeout: 30), .completed, app.debugDescription) XCTAssertTrue(app.staticTexts["$ 1.23"].exists) XCTAssertFalse(app.buttons["N1"].exists) - // Back, then a different recipient: Amount opens editable with the earlier amount. - try XCTUnwrap(app.buttons.matching(identifier: "NavigationBack").allElementsBoundByIndex.first(where: \.isHittable)).tap() + + // The wallet behind the sheet also has a Back button. Use the one in the Confirm header. + let title = app.staticTexts["Confirm"] + XCTAssertTrue(title.exists, app.debugDescription) + let titleY = title.frame.midY + let headerButtons = app.buttons.matching(identifier: "NavigationBack").allElementsBoundByIndex.filter { + $0.isHittable && $0.frame.minY <= titleY && titleY <= $0.frame.maxY + } + XCTAssertEqual(headerButtons.count, 1, app.debugDescription) + let back = try XCTUnwrap(headerButtons.first) + XCTAssertTrue(back.isEnabled, app.debugDescription) + back.tap() XCTAssertTrue(recipient.waitForExistence(timeout: 5)) recipient.tap() recipient.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: 60)) From 6c40b8d5f3897cb648de34d7d4f422b48370288a Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 9 Nov 2026 13:02:38 -0500 Subject: [PATCH 39/45] test: defer optional update prompts in wallet UI fixtures --- BitkitUITests/HomeHeaderUITests.swift | 1 + BitkitUITests/UsdtWalletUITests.swift | 2 ++ 2 files changed, 3 insertions(+) diff --git a/BitkitUITests/HomeHeaderUITests.swift b/BitkitUITests/HomeHeaderUITests.swift index 9967c6006a..2c4a96c21d 100644 --- a/BitkitUITests/HomeHeaderUITests.swift +++ b/BitkitUITests/HomeHeaderUITests.swift @@ -8,6 +8,7 @@ final class HomeHeaderUITests: XCTestCase { func testHeaderRowTapsOpenHeaderButtonsAndBalanceStillToggles() throws { continueAfterFailure = false let app = XCUIApplication() + app.launchArguments += ["-appUpdateIgnoreTimestamp", String(Date().timeIntervalSince1970)] app.launchArguments += ["-AppleLanguages", "(en)", "-AppleLocale", "en_US"] app.launch() if app.buttons["Continue"].waitForExistence(timeout: 3) { diff --git a/BitkitUITests/UsdtWalletUITests.swift b/BitkitUITests/UsdtWalletUITests.swift index 586855d0c3..b12774a45c 100644 --- a/BitkitUITests/UsdtWalletUITests.swift +++ b/BitkitUITests/UsdtWalletUITests.swift @@ -17,6 +17,7 @@ final class UsdtWalletUITests: XCTestCase { func testUnknownBalanceAndManualEntryUseConsistentAmountsInCommaRegion() throws { continueAfterFailure = false let app = XCUIApplication() + app.launchArguments += ["-appUpdateIgnoreTimestamp", String(Date().timeIntervalSince1970)] app.launchArguments += ["-AppleLanguages", "(en)", "-AppleLocale", "de_DE"] app.launchEnvironment["USDT_RPC_URL"] = "http://127.0.0.1:1" app.launchEnvironment["USDT_BUNDLER_URL"] = "http://127.0.0.1:1" @@ -219,6 +220,7 @@ final class UsdtWalletUITests: XCTestCase { func testReceiveAndInvalidPaymentStaySeparateFromBitcoin() throws { continueAfterFailure = false let app = XCUIApplication() + app.launchArguments += ["-appUpdateIgnoreTimestamp", String(Date().timeIntervalSince1970)] app.resetAuthorizationStatus(for: .camera) app.launchEnvironment["USDT_RPC_URL"] = rpcURL app.launchEnvironment["USDT_BUNDLER_URL"] = bundlerURL From 038f1153171fffd41ae907083a188f16e6235070 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 04:09:17 +0100 Subject: [PATCH 40/45] fix: store the move-to-spark backup listener with the other listeners Verified: build passes; unit tests running --- Bitkit/Services/BackupService.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index fe888b5dc5..df66a3c069 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -1121,7 +1121,7 @@ class BackupService { guard let self, !self.shouldSkipBackup() else { return } markBackupRequired(category: .metadata) } - .store(in: cancellables) + .store(in: &listeners) // APP STATE (UserDefaults changes, etc.) SettingsViewModel.shared.appStatePublisher From 809f1852085f16e899f4a5b1927cb2bcece56b22 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 04:11:49 +0100 Subject: [PATCH 41/45] fix: keep the spark exit backup required during an active exit An exit that is already active made the export return nothing, so the run skipped the upload and still recorded success. Defer it instead. Verified: SparkExitBackupTests and BackupServiceTests (73 pass), swiftformat lint --- Bitkit/Services/BackupService.swift | 2 ++ BitkitTests/SparkExitBackupTests.swift | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index df66a3c069..94127745d8 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -541,6 +541,8 @@ class BackupService { case .nothingStaged, .imported: break } + // An active exit defers the upload and keeps this category required; it never counts as backed up. + guard await !isSparkExitActive() else { throw CancellationError() } // Nothing to back up until Spark connects, which marks this category required again. if let data = try await sparkExitBackupData() { guard await !isSparkExitActive() else { throw CancellationError() } diff --git a/BitkitTests/SparkExitBackupTests.swift b/BitkitTests/SparkExitBackupTests.swift index a0ba98cc06..cd44891826 100644 --- a/BitkitTests/SparkExitBackupTests.swift +++ b/BitkitTests/SparkExitBackupTests.swift @@ -55,10 +55,12 @@ final class SparkExitBackupTests: XCTestCase { uploadBackup: { key, _ in uploads.append(key) } ) - await service.triggerBackup(category: .sparkExit) + let outcome = await service.triggerBackup(category: .sparkExit) XCTAssertTrue(uploads.isEmpty) XCTAssertEqual(exports, 0) + XCTAssertEqual(outcome, .failed) + XCTAssertTrue(service.getBackupStatus(category: .sparkExit).isRequired, "an active exit counted as backed up") } func testAFailedExitRestoreBlocksReplacingTheRemoteBackupUntilItRecovers() async throws { From 697566708c6c06404be854fb2f42c6f02b038444 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 05:11:17 +0100 Subject: [PATCH 42/45] fix: cancel a backup run when its caller is cancelled before it resumes The run starts on the backup queue before the caller resumes, and the caller's cancellation only reached it once the caller awaited it. A cancel in that gap was lost, so a cancelled Spark export could upload. Verified: BackupServiceTests and SparkExitBackupTests (73 pass), two cancel tests x200, swiftformat lint --- Bitkit/Services/BackupService.swift | 62 ++++++++++++++++++++++------- 1 file changed, 47 insertions(+), 15 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 94127745d8..554d17e658 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -439,22 +439,29 @@ class BackupService { { guard let wipeGeneration = try? captureWipeGeneration() else { return .failed } while !Task.isCancelled { - let admission = try? await ServiceQueue.background(.backup) { [self] () -> ( - task: Task?, - owned: Bool, - stopping: Bool - ) in - try requireWipeGeneration(wipeGeneration) - if let generation, generation != currentSchedulingGeneration { - return (nil, false, false) - } - guard !isStoppingBackups else { return (nil, false, true) } - if let existing = runningBackupTasks[category] { - return (waitForExisting ? existing : nil, false, false) + // The run starts on the backup queue before this caller resumes; a cancel in between must still reach it. + let cancellation = BackupRunCancellation() + let admission = try? await withTaskCancellationHandler { + try await ServiceQueue.background(.backup) { [self] () -> ( + task: Task?, + owned: Bool, + stopping: Bool + ) in + try requireWipeGeneration(wipeGeneration) + if let generation, generation != currentSchedulingGeneration { + return (nil, false, false) + } + guard !isStoppingBackups else { return (nil, false, true) } + if let existing = runningBackupTasks[category] { + return (waitForExisting ? existing : nil, false, false) + } + let task = Task { await self.runBackup(category: category, isScheduled: isScheduled, wipeGeneration: wipeGeneration) } + runningBackupTasks[category] = task + cancellation.attach(task) + return (task, true, false) } - let task = Task { await self.runBackup(category: category, isScheduled: isScheduled, wipeGeneration: wipeGeneration) } - runningBackupTasks[category] = task - return (task, true, false) + } onCancel: { + cancellation.cancel() } guard let admission else { return .failed } if admission.stopping, !isScheduled { @@ -1976,3 +1983,28 @@ struct SparkExitBackupMark { return true } } + +/// Cancels a backup run its caller owns, even when the cancel arrives before the caller has resumed with that run. +private final class BackupRunCancellation: @unchecked Sendable { + private let lock = NSLock() + private var task: Task? + private var isCancelled = false + + func attach(_ task: Task) { + let cancelled = lock.withLock { + self.task = task + return isCancelled + } + if cancelled { + task.cancel() + } + } + + func cancel() { + let task = lock.withLock { + isCancelled = true + return self.task + } + task?.cancel() + } +} From 4c9d57d3c7abf23c2164bfaee8a4d8f7523a3c08 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 10:42:31 +0100 Subject: [PATCH 43/45] fix: close review gaps in recovery, backups and wipe - Moves to Spark mark metadata like the other backup listeners, so no upload starts while observation is stopped. - A successful automatic wallet start closes the connection settings screen. - Retry in connection settings shows an error when the wallet still cannot start. - Wallet wipe bounds its wait for backup uploads at quiesce and offers Retry instead of hanging. - Remove NodeEventListener and the ldkEvents queue, unused since master's event loop. - One changelog fragment for the PR. Verified: BitkitTests unit suite (iPhone 17 simulator), swiftformat --lint on changed files --- Bitkit.xcodeproj/project.pbxproj | 2 - Bitkit/AppScene.swift | 1 + Bitkit/Services/BackupService.swift | 2 +- Bitkit/Services/NodeEventListener.swift | 77 ----- Bitkit/Services/ServiceQueue.swift | 4 - Bitkit/Utilities/AppReset.swift | 2 +- .../WalletConnectionRecoveryView.swift | 5 + BitkitTests/NodeEventListenerTests.swift | 320 ------------------ changelog.d/next/1121.fixed.md | 2 +- changelog.d/next/1122.fixed.md | 1 - changelog.d/next/1123.fixed.md | 1 - changelog.d/next/1124.fixed.md | 1 - changelog.d/next/1125.fixed.md | 1 - changelog.d/next/1139.fixed.md | 1 - 14 files changed, 9 insertions(+), 411 deletions(-) delete mode 100644 Bitkit/Services/NodeEventListener.swift delete mode 100644 BitkitTests/NodeEventListenerTests.swift delete mode 100644 changelog.d/next/1122.fixed.md delete mode 100644 changelog.d/next/1123.fixed.md delete mode 100644 changelog.d/next/1124.fixed.md delete mode 100644 changelog.d/next/1125.fixed.md delete mode 100644 changelog.d/next/1139.fixed.md diff --git a/Bitkit.xcodeproj/project.pbxproj b/Bitkit.xcodeproj/project.pbxproj index 2a3610f665..df9571d4ae 100644 --- a/Bitkit.xcodeproj/project.pbxproj +++ b/Bitkit.xcodeproj/project.pbxproj @@ -178,7 +178,6 @@ Services/HwActivityTagBackup.swift, Services/HwSnapshotMerge.swift, Services/LightningService.swift, - Services/NodeEventListener.swift, Services/MigrationsService.swift, Services/RNBackupClient.swift, Services/ServiceQueue.swift, @@ -211,7 +210,6 @@ Services/HwActivityTagBackup.swift, Services/HwSnapshotMerge.swift, Services/LightningService.swift, - Services/NodeEventListener.swift, Services/ServiceQueue.swift, Services/VssStoreIdProvider.swift, Services/Wake/WakeReceiver.swift, diff --git a/Bitkit/AppScene.swift b/Bitkit/AppScene.swift index 1f91cdfbdc..516b8fcfc4 100644 --- a/Bitkit/AppScene.swift +++ b/Bitkit/AppScene.swift @@ -1245,6 +1245,7 @@ struct AppScene: View { isRunning: wallet.nodeLifecycleState == .running) { didWalletBackupRestoreFail = false + connectionEditor = nil } try await activity.syncLdkNodePayments() diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 554d17e658..3c77bb96b4 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -1128,7 +1128,7 @@ class BackupService { MoveToSparkPayments.savedPublisher .sink { @Sendable [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .metadata) + markObservedBackupRequired(category: .metadata) } .store(in: &listeners) diff --git a/Bitkit/Services/NodeEventListener.swift b/Bitkit/Services/NodeEventListener.swift deleted file mode 100644 index 42ddbc36a1..0000000000 --- a/Bitkit/Services/NodeEventListener.swift +++ /dev/null @@ -1,77 +0,0 @@ -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 52d4a1cf5f..a607f8a1f2 100644 --- a/Bitkit/Services/ServiceQueue.swift +++ b/Bitkit/Services/ServiceQueue.swift @@ -4,7 +4,6 @@ import UIKit /// 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) @@ -14,7 +13,6 @@ class ServiceQueue { enum ServiceTypes { case ldk - case ldkEvents case core case migration case forex @@ -24,8 +22,6 @@ 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 eab4f0b92c..4b07320cad 100644 --- a/Bitkit/Utilities/AppReset.swift +++ b/Bitkit/Utilities/AppReset.swift @@ -81,7 +81,7 @@ final class AppReset: WipeStepExecutor { func run(_ step: WipeStep) async throws { switch step { case .quiesce: - await BackupService.shared.stopObservingBackups() + try await Self.bounded("backup uploads") { await BackupService.shared.stopObservingBackups() } try await Self.bounded("migration sync") { [app] in await app.cancelMigrationSyncForWipe() } case .stopNode: try await wallet.stopForWipe() diff --git a/Bitkit/Views/Onboarding/WalletConnectionRecoveryView.swift b/Bitkit/Views/Onboarding/WalletConnectionRecoveryView.swift index 2ae8995821..a37986c0d8 100644 --- a/Bitkit/Views/Onboarding/WalletConnectionRecoveryView.swift +++ b/Bitkit/Views/Onboarding/WalletConnectionRecoveryView.swift @@ -72,7 +72,12 @@ struct WalletConnectionRecoveryView: View { CustomButton(title: t("common__try_again"), isDisabled: !canEdit, isLoading: recovery.isBusy) { work = Task { guard canEdit else { return } + let editor = editor + saved = false + error = nil await onRetry() + guard !Task.isCancelled, recovery.isCurrent(editor) else { return } + error = t("other__lnurl_ln_error_msg") } }.accessibilityIdentifier("RecoveryRetry") } diff --git a/BitkitTests/NodeEventListenerTests.swift b/BitkitTests/NodeEventListenerTests.swift deleted file mode 100644 index 12bf5f731f..0000000000 --- a/BitkitTests/NodeEventListenerTests.swift +++ /dev/null @@ -1,320 +0,0 @@ -@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/changelog.d/next/1121.fixed.md b/changelog.d/next/1121.fixed.md index 44fec70bfa..dda30997dc 100644 --- a/changelog.d/next/1121.fixed.md +++ b/changelog.d/next/1121.fixed.md @@ -1 +1 @@ -Wallet restore finishes without waiting for optional profile refresh, retries missing profile data after reconnecting, resumes pending metadata after wallet backup recovers, preserves complete backups when identity or cached channel data is unavailable, and keeps retired backup calls from crossing wallet resets. +Wallet restore no longer waits for optional profile data, pending backups survive connection failures and wallet resets, connection settings can be corrected during wallet recovery, wallet reset no longer waits indefinitely on older operations, and incomplete profile deletion keeps session and contact data without repeating cleanup. diff --git a/changelog.d/next/1122.fixed.md b/changelog.d/next/1122.fixed.md deleted file mode 100644 index fb97b9ecd4..0000000000 --- a/changelog.d/next/1122.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Prevent uncertain profile deletion failures from automatically repeating contact cleanup and deletion. diff --git a/changelog.d/next/1123.fixed.md b/changelog.d/next/1123.fixed.md deleted file mode 100644 index 892f8fd43b..0000000000 --- a/changelog.d/next/1123.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Preserve pending backups through observation changes and temporary connection failures, keep foreground retries available as scheduled backups finish, complete wallet initialization only once after node startup, and refuse old backup requests across wallet removal. diff --git a/changelog.d/next/1124.fixed.md b/changelog.d/next/1124.fixed.md deleted file mode 100644 index 64a4e10014..0000000000 --- a/changelog.d/next/1124.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Preserve session and contact data after incomplete profile cleanup, and explain when active subscriptions prevent profile removal. diff --git a/changelog.d/next/1125.fixed.md b/changelog.d/next/1125.fixed.md deleted file mode 100644 index 67503a93b4..0000000000 --- a/changelog.d/next/1125.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Prevent wallet reset from waiting indefinitely for an older Paykit operation queued during teardown. diff --git a/changelog.d/next/1139.fixed.md b/changelog.d/next/1139.fixed.md deleted file mode 100644 index c40d82a4a6..0000000000 --- a/changelog.d/next/1139.fixed.md +++ /dev/null @@ -1 +0,0 @@ -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. From 8c400aa205866f8ddd54317f400d0dac2ef03c2d Mon Sep 17 00:00:00 2001 From: ovitrif Date: Fri, 27 Nov 2026 18:16:54 +0100 Subject: [PATCH 44/45] fix: stop the backup failure alert during an active spark exit An active exit defers the SPARK_EXIT upload and keeps it required, which the failure check counted as a failed backup after 30 minutes. The guard now records the deferral and the failure check skips SPARK_EXIT while it holds; the category stays required and uploads once the exit ends. Verified: BitkitTests unit suite (incl. new BackupForegroundRecoveryTests case) and swiftformat --lint on this tree --- Bitkit/Services/BackupService.swift | 20 +++++++++++--- .../BackupForegroundRecoveryTests.swift | 27 +++++++++++++++++++ 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 3c77bb96b4..fd4f72149a 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -164,6 +164,9 @@ class BackupService { private let statusUpdateQueue = DispatchQueue(label: "backup-service-status-update", qos: .userInitiated) private let stateQueue = DispatchQueue(label: "backup-service-state", qos: .userInitiated) private var sparkExitMark = SparkExitBackupMark() + /// Set while an active exit defers the SPARK_EXIT upload, so the failure check doesn't count the deferral as a failure. + private let sparkExitDeferralLock = NSLock() + private var isSparkExitDeferredByExit = false private let backupStatusesSubject = PassthroughSubject<[BackupCategory: BackupItemStatus], Never>() private let backupFailureSubject = PassthroughSubject() @@ -549,10 +552,10 @@ class BackupService { break } // An active exit defers the upload and keeps this category required; it never counts as backed up. - guard await !isSparkExitActive() else { throw CancellationError() } + guard await !isSparkExitDeferred() else { throw CancellationError() } // Nothing to back up until Spark connects, which marks this category required again. if let data = try await sparkExitBackupData() { - guard await !isSparkExitActive() else { throw CancellationError() } + guard await !isSparkExitDeferred() else { throw CancellationError() } try Task.checkCancellation() try requireWipeGeneration(wipeGeneration) if isScheduled, shouldSkipBackup(category: category) { @@ -1334,7 +1337,11 @@ class BackupService { } private func hasFailedBackups(at currentTime: UInt64) -> Bool { - BackupCategory.allCases.contains { category in + let isSparkExitDeferred = sparkExitDeferralLock.withLock { isSparkExitDeferredByExit } + return BackupCategory.allCases.contains { category in + if category == .sparkExit, isSparkExitDeferred { + return false + } let status = getBackupStatus(category: category) return BackupFailureNotificationGate.hasFailedBackup( status, @@ -1722,6 +1729,13 @@ class BackupService { return sparkExitRejectedKey + "_" + digest.prefix(16) } + /// Whether an active exit defers the SPARK_EXIT upload, recorded for the failure check. + private func isSparkExitDeferred() async -> Bool { + let isActive = await isSparkExitActive() + sparkExitDeferralLock.withLock { isSparkExitDeferredByExit = isActive } + return isActive + } + /// Nothing while an exit runs: the operators may stop reporting a leaf once it is being exited, so a fresh export /// could drop the very leaf a restored wallet needs. The backup from before the exit stays. private func sparkExitBackupData() async throws -> Data? { diff --git a/BitkitTests/BackupForegroundRecoveryTests.swift b/BitkitTests/BackupForegroundRecoveryTests.swift index 7c3a925ff5..0219bd40d1 100644 --- a/BitkitTests/BackupForegroundRecoveryTests.swift +++ b/BitkitTests/BackupForegroundRecoveryTests.swift @@ -32,6 +32,33 @@ final class BackupForegroundRecoveryTests: XCTestCase { await service.stopObservingBackups() } + func testAnExitDeferredSparkExitBackupDoesNotRaiseTheFailureAlert() async throws { + let fixture = try Fixture(categories: [.sparkExit]) + defer { fixture.removeDefaults() } + let uploads = UploadRecorder() + let service = BackupService( + defaults: fixture.defaults, + backupData: { _ in Data("{}".utf8) }, + isSparkExitActive: { true }, + uploadBackup: { key, _ in await uploads.record(key) }, + waitForBackupDelay: { throw CancellationError() } + ) + await startAfterPendingJobsSettle(service, categories: fixture.categories) + let falseAlert = expectation(description: "An active exit's deferred SPARK_EXIT must not raise 'Data Backup Failure'") + falseAlert.isInverted = true + let subscription = service.backupFailurePublisher.sink { _ in falseAlert.fulfill() } + defer { subscription.cancel() } + + await service.setAppActive(true)?.value + await fulfillment(of: [falseAlert], timeout: 0.5) + + let recorded = await uploads.counts + XCTAssertNil(recorded[BackupCategory.sparkExit.rawValue], "an active exit must not upload") + XCTAssertTrue(service.getBackupStatus(category: .sparkExit).isRequired, "the deferred backup must stay required") + service.setAppActive(false) + await service.stopObservingBackups() + } + func testFailedRecoveryWaitsForOtherRetriesAndPreservesAgeAndCooldown() async throws { let fixture = try Fixture(categories: [.usdt, .widgets]) defer { fixture.removeDefaults() } From 75da1b2424c2f7f0875ea0df2c188ec92a40688d Mon Sep 17 00:00:00 2001 From: ovitrif Date: Sat, 28 Nov 2026 08:58:16 +0100 Subject: [PATCH 45/45] fix: raise the backup failure alert once the spark exit ends The failure check skipped SPARK_EXIT on a flag that only a backup run reaching the exit check updated, so after an exit ended with no further run the flag stayed set and an overdue backup never raised the alert. The alert now asks whether an exit is active when it fires. Verified: BitkitTests unit suite (new latch test fails on the previous BackupService, passes here) and swiftformat --lint --- Bitkit/Services/BackupService.swift | 28 +++++------ .../BackupForegroundRecoveryTests.swift | 46 +++++++++++++++++++ 2 files changed, 57 insertions(+), 17 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 5947e10de4..ae485ff551 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -164,9 +164,6 @@ class BackupService { private let statusUpdateQueue = DispatchQueue(label: "backup-service-status-update", qos: .userInitiated) private let stateQueue = DispatchQueue(label: "backup-service-state", qos: .userInitiated) private var sparkExitMark = SparkExitBackupMark() - /// Set while an active exit defers the SPARK_EXIT upload, so the failure check doesn't count the deferral as a failure. - private let sparkExitDeferralLock = NSLock() - private var isSparkExitDeferredByExit = false private let backupStatusesSubject = PassthroughSubject<[BackupCategory: BackupItemStatus], Never>() private let backupFailureSubject = PassthroughSubject() @@ -552,10 +549,10 @@ class BackupService { break } // An active exit defers the upload and keeps this category required; it never counts as backed up. - guard await !isSparkExitDeferred() else { throw CancellationError() } + guard await !isSparkExitActive() else { throw CancellationError() } // Nothing to back up until Spark connects, which marks this category required again. if let data = try await sparkExitBackupData() { - guard await !isSparkExitDeferred() else { throw CancellationError() } + guard await !isSparkExitActive() else { throw CancellationError() } try Task.checkCancellation() try requireWipeGeneration(wipeGeneration) if isScheduled, shouldSkipBackup(category: category) { @@ -1342,10 +1339,10 @@ class BackupService { } } - private func hasFailedBackups(at currentTime: UInt64) -> Bool { - let isSparkExitDeferred = sparkExitDeferralLock.withLock { isSparkExitDeferredByExit } - return BackupCategory.allCases.contains { category in - if category == .sparkExit, isSparkExitDeferred { + /// An active exit defers the SPARK_EXIT upload and keeps it required, so while one runs that category is no failure. + private func hasFailedBackups(at currentTime: UInt64, isSparkExitActive: Bool = false) -> Bool { + BackupCategory.allCases.contains { category in + if category == .sparkExit, isSparkExitActive { return false } let status = getBackupStatus(category: category) @@ -1361,8 +1358,12 @@ class BackupService { let generation = currentSchedulingGeneration Task { @MainActor in guard self.isObserving, generation == self.currentSchedulingGeneration, !self.shouldSkipBackup() else { return } + let isSparkExitActive = await self.isSparkExitActive() + guard self.isObserving, generation == self.currentSchedulingGeneration else { return } let currentTime = UInt64(Date().timeIntervalSince1970) - guard self.statusUpdateQueue.sync(execute: { self.hasFailedBackups(at: currentTime) }) else { return } + guard self.statusUpdateQueue.sync(execute: { + self.hasFailedBackups(at: currentTime, isSparkExitActive: isSparkExitActive) + }) else { return } let shouldNotify = self.stateQueue.sync { self.backupFailureNotificationGate.shouldNotify( @@ -1737,13 +1738,6 @@ class BackupService { return sparkExitRejectedKey + "_" + digest.prefix(16) } - /// Whether an active exit defers the SPARK_EXIT upload, recorded for the failure check. - private func isSparkExitDeferred() async -> Bool { - let isActive = await isSparkExitActive() - sparkExitDeferralLock.withLock { isSparkExitDeferredByExit = isActive } - return isActive - } - /// Nothing while an exit runs: the operators may stop reporting a leaf once it is being exited, so a fresh export /// could drop the very leaf a restored wallet needs. The backup from before the exit stays. private func sparkExitBackupData() async throws -> Data? { diff --git a/BitkitTests/BackupForegroundRecoveryTests.swift b/BitkitTests/BackupForegroundRecoveryTests.swift index 0219bd40d1..4f4a4a1d18 100644 --- a/BitkitTests/BackupForegroundRecoveryTests.swift +++ b/BitkitTests/BackupForegroundRecoveryTests.swift @@ -59,6 +59,42 @@ final class BackupForegroundRecoveryTests: XCTestCase { await service.stopObservingBackups() } + func testAnOverdueSparkExitBackupRaisesTheFailureAlertOnceTheExitEnds() async throws { + let fixture = try Fixture(categories: [.sparkExit]) + defer { fixture.removeDefaults() } + let exit = SparkExitState() + let service = BackupService( + defaults: fixture.defaults, + backupData: { _ in Data("{}".utf8) }, + isSparkExitActive: { exit.isActive }, + uploadBackup: { _, _ in }, + waitForBackupDelay: { throw CancellationError() }, + importStagedSparkExit: { exit.isActive ? .nothingStaged : .rejected }, + stagedSparkExitState: { throw URLError(.cannotOpenFile) } + ) + await startAfterPendingJobsSettle(service, categories: fixture.categories) + let deferredAlert = expectation(description: "No alert while the exit defers the upload") + deferredAlert.isInverted = true + var subscription = service.backupFailurePublisher.sink { _ in deferredAlert.fulfill() } + await service.setAppActive(true)?.value + await fulfillment(of: [deferredAlert], timeout: 0.5) + subscription.cancel() + service.setAppActive(false) + + // The exit ends, and the next attempt fails before it reaches the exit check, with no retry scheduled. + exit.isActive = false + let alert = expectation(description: "An overdue SPARK_EXIT backup raises 'Data Backup Failure' once the exit ends") + subscription = service.backupFailurePublisher.sink { _ in alert.fulfill() } + defer { subscription.cancel() } + + await service.setAppActive(true)?.value + await fulfillment(of: [alert], timeout: 2) + + XCTAssertTrue(service.getBackupStatus(category: .sparkExit).isRequired) + service.setAppActive(false) + await service.stopObservingBackups() + } + func testFailedRecoveryWaitsForOtherRetriesAndPreservesAgeAndCooldown() async throws { let fixture = try Fixture(categories: [.usdt, .widgets]) defer { fixture.removeDefaults() } @@ -773,6 +809,16 @@ private final class CancellationRecorder: @unchecked Sendable { } } +private final class SparkExitState: @unchecked Sendable { + private let lock = NSLock() + private var active = true + + var isActive: Bool { + get { lock.withLock { active } } + set { lock.withLock { active = newValue } } + } +} + private struct Fixture { let suite = "BackupForegroundRecoveryTests.\(UUID().uuidString)" let defaults: UserDefaults