From 4d86489c360e60167fbc9cf5f25291268975f372 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 00:49:48 +0200 Subject: [PATCH 01/61] fix: decouple wallet restore from profile refresh --- .../java/to/bitkit/repositories/BackupRepo.kt | 7 +- .../java/to/bitkit/repositories/PubkyRepo.kt | 43 +++++++++- .../to/bitkit/viewmodels/WalletViewModel.kt | 4 +- .../to/bitkit/repositories/BackupRepoTest.kt | 52 ++++++++++++ .../to/bitkit/repositories/PubkyRepoTest.kt | 81 +++++++++++++++++++ .../java/to/bitkit/ui/WalletViewModelTest.kt | 28 ++++++- changelog.d/next/restore-identity.fixed.md | 1 + .../wallet/restore-during-identity-outage.xml | 18 +++++ 8 files changed, 224 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/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index dabef786d4..f9ea2491d3 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -743,8 +743,8 @@ class BackupRepo @Inject constructor( // propagate and fail the backup rather than upload an empty set over the stored ones. val hwWalletNames = hwWalletStore.backupSnapshot().takeIf { it.isNotEmpty() } val cacheData = cacheStore.data.first() - val pubkySession = pubkyRepo.snapshotSessionBackupState().getOrDefault(null) - val pubkyContactProfileOverrides = pubkyRepo.snapshotContactProfileOverrides().getOrDefault(null) + val pubkySession = pubkyRepo.snapshotSessionBackupState().getOrThrow() + val pubkyContactProfileOverrides = pubkyRepo.snapshotContactProfileOverrides().getOrThrow() val payload = MetadataBackupV1( createdAt = currentTimeMillis(), @@ -782,6 +782,9 @@ class BackupRepo @Inject constructor( val privateRepo = privatePaykitRepo.get() val privateVersion = privateRepo.backupStateVersion.value val paykitSdkBackupState = privateRepo.backupSnapshot().getOrThrow() + check(paykitSdkBackupState.state != null || !pubkyRepo.hasIdentityForBackup()) { + "Paykit identity is unavailable for backup" + } val reservationRepo = privatePaykitAddressReservationRepo.get() val reservationVersion = reservationRepo.backupStateVersion.value val privateReservations = reservationRepo.backupSnapshot().getOrThrow() diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 39a03aefb4..8340349b42 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -333,6 +333,8 @@ class PubkyRepo @Inject constructor( } private val initializationReady = CompletableDeferred() + private val restoreInitializationLock = Any() + private var restoreInitialization: Pair? = null init { scope.launch { initialize() }.invokeOnCompletion { @@ -350,9 +352,38 @@ class PubkyRepo @Inject constructor( runSuspendCatching { pubkyService.republishIdentityIfNeeded(publicKey.value) } } - suspend fun initialize() = withContext(ioDispatcher) { - val restored = initializeMutex.withLock { initializeSession() } + suspend fun initialize() = initializeForRevision() + + fun scheduleInitializationAfterRestore() { + val job = synchronized(restoreInitializationLock) { + val revision = storedIdentityRevision.get() + restoreInitialization?.takeIf { it.first == revision && !it.second.isCompleted }?.second + ?: scope.launch(start = CoroutineStart.LAZY) { + initializeForRevision(revision) + }.also { pending -> + restoreInitialization = revision to pending + pending.invokeOnCompletion { + synchronized(restoreInitializationLock) { + if (restoreInitialization?.second === pending) restoreInitialization = null + } + } + } + } + job.start() + } + + private suspend fun initializeForRevision( + expectedRevision: Long? = null, + ): Result = withContext(ioDispatcher) { + val (restored, revision) = initializeMutex.withLock { + if (expectedRevision != null && expectedRevision != storedIdentityRevision.get()) { + return@withContext Result.success(Unit) + } + initializeSession() to storedIdentityRevision.get() + } + if (revision != storedIdentityRevision.get()) return@withContext Result.success(Unit) if (restored) loadIdentityData() + if (revision != storedIdentityRevision.get()) return@withContext Result.success(Unit) checkAdoptedSource() } @@ -1576,6 +1607,14 @@ class PubkyRepo @Inject constructor( !keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name).isNullOrEmpty() } + internal suspend fun hasIdentityForBackup(): Boolean = withContext(ioDispatcher) { + _publicKey.value != null || listOf( + Keychain.Key.PAYKIT_SESSION, + Keychain.Key.PUBKY_SECRET_KEY, + Keychain.Key.SHARED_PUBKY_SOURCE, + ).any { !keychain.loadString(it.name).isNullOrEmpty() } + } + suspend fun parseAuthUrl(authUrl: String): Result = runSuspendCatching { withContext(ioDispatcher) { if (PubkyAuthRequest.isSignupUrl(authUrl) && !PubkyAuthRequest.isGrantSignupUrl(authUrl)) { diff --git a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index 114798b9d0..1d74917e2e 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -235,7 +235,7 @@ class WalletViewModel @Inject constructor( if (resumePendingWalletBackup) { backupRepo.performFullRestoreFromLatestBackup(onCacheRestored = walletRepo::loadFromCache) .getOrThrow() - pubkyRepo.initialize() + pubkyRepo.scheduleInitializationAfterRestore() } else { restoreFromMostRecentBackup() } @@ -273,7 +273,7 @@ class WalletViewModel @Inject constructor( .getOrThrow() } - pubkyRepo.initialize() + pubkyRepo.scheduleInitializationAfterRestore() } private suspend fun restoreFromRNRemoteBackup() { diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index cd7289587f..1eee30e7dd 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -189,9 +189,61 @@ class BackupRepoTest : BaseUnitTest() { }.thenReturn(Result.success(Unit)) whenever { vssBackupClient.listKeys() }.thenReturn(Result.success(emptyList())) + whenever(pubkyRepo.hasIdentityForBackup()).thenReturn(false) sut = createSut() } + @Test + fun `metadata backup preserves complete data when identity records cannot be read`() = test { + stubMetadataBackupReads() + val error = AppError("keychain unavailable") + whenever(pubkyRepo.snapshotSessionBackupState()).thenReturn(Result.failure(error)) + assertEquals(error, sut.triggerBackup(BackupCategory.METADATA).exceptionOrNull()) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) + + stubMetadataBackupReads() + sut.triggerBackup(BackupCategory.METADATA).getOrThrow() + verify(vssBackupClient).putObject(eq(BackupCategory.METADATA.name), any()) + } + + @Test + fun `metadata backup preserves complete data when contact overrides cannot be read`() = test { + stubMetadataBackupReads() + val error = AppError("store unavailable") + whenever(pubkyRepo.snapshotContactProfileOverrides()).thenReturn(Result.failure(error)) + assertEquals(error, sut.triggerBackup(BackupCategory.METADATA).exceptionOrNull()) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) + + stubMetadataBackupReads() + sut.triggerBackup(BackupCategory.METADATA).getOrThrow() + verify(vssBackupClient).putObject(eq(BackupCategory.METADATA.name), any()) + } + + @Test + fun `wallet backup preserves complete data while stored identity is unresolved`() = test { + whenever(pubkyRepo.hasIdentityForBackup()).thenReturn(true) + assertTrue(sut.triggerBackup(BackupCategory.WALLET).isFailure) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) + + whenever(privatePaykitRepo.backupSnapshot()).thenReturn( + Result.success(PrivatePaykitBackupSnapshot("fresh-sdk-state", 0)), + ) + sut.triggerBackup(BackupCategory.WALLET).getOrThrow() + val payload = argumentCaptor() + verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), payload.capture()) + val backup = json.decodeFromString(payload.firstValue.decodeToString()) + assertEquals("fresh-sdk-state", backup.paykitSdkBackupState) + } + + @Test + fun `wallet backup cannot treat unreadable identity as absent`() = test { + whenever(pubkyRepo.hasIdentityForBackup()).doSuspendableAnswer { + throw IllegalStateException("keychain unavailable") + } + assertTrue(sut.triggerBackup(BackupCategory.WALLET).isFailure) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) + } + @Test fun `wallet backup waits for submission and includes the latest pending state`() = test { val statuses = MutableStateFlow( diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 1a5b05c58f..a6d429a882 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -2412,6 +2412,87 @@ class PubkyRepoTest : BaseUnitTest() { assertNull(result.getOrNull()) } + @Test + fun `scheduled restore activation returns while authentication is held and coalesces duplicates`() = test { + sut.awaitInitialization() + whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn("restored_session") + val release = CompletableDeferred() + whenever(pubkyService.importSession("restored_session")).doSuspendableAnswer { release.await() } + clearInvocations(pubkyService) + try { + repeat(3) { sut.scheduleInitializationAfterRestore() } + runCurrent() + assertNull(sut.publicKey.value) + assertFalse(sut.isAuthenticated.value) + verify(pubkyService).importSession("restored_session") + } finally { + release.complete(VALID_SELF_KEY) + } + advanceUntilIdle() + assertEquals(VALID_SELF_KEY, sut.publicKey.value) + verify(pubkyService).importSession("restored_session") + } + + @Test + fun `new restored identity proceeds while old scheduled profile loading is held`() = test { + sut.awaitInitialization() + var session: String? = "first_session" + whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenAnswer { session } + whenever(keychain.delete(Keychain.Key.PAYKIT_SESSION.name)).thenAnswer { session = null } + whenever(pubkyService.importSession("first_session")).thenReturn(VALID_SELF_KEY) + whenever(pubkyService.importSession("second_session")).thenReturn(VALID_CONTACT_KEY_B) + val releaseFirst = CompletableDeferred() + val releaseSecond = CompletableDeferred() + whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + releaseFirst.await() + createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile(name = "Obsolete")) + } + whenever(pubkyService.resolveContactProfile(VALID_CONTACT_KEY_B, true)).doSuspendableAnswer { + releaseSecond.await() + createResolution(VALID_CONTACT_KEY_B, pubkyProfile = createPubkyProfile(name = "Current")) + } + try { + sut.scheduleInitializationAfterRestore() + runCurrent() + assertEquals(VALID_SELF_KEY, sut.publicKey.value) + sut.restoreSessionBackupState(null).getOrThrow() + assertNull(sut.publicKey.value) + session = "second_session" + sut.scheduleInitializationAfterRestore() + runCurrent() + assertEquals(VALID_CONTACT_KEY_B, sut.publicKey.value) + releaseFirst.complete(Unit) + runCurrent() + sut.scheduleInitializationAfterRestore() + runCurrent() + verify(pubkyService).importSession("second_session") + } finally { + releaseFirst.complete(Unit) + releaseSecond.complete(Unit) + } + advanceUntilIdle() + assertEquals(VALID_CONTACT_KEY_B, sut.publicKey.value) + assertEquals("Current", sut.profile.value?.name) + } + + @Test + fun `backup identity includes persisted and adopted credentials and fails on unreadable storage`() = test { + sut.awaitInitialization() + assertFalse(sut.hasIdentityForBackup()) + val identityKeys = listOf( + Keychain.Key.PAYKIT_SESSION, + Keychain.Key.PUBKY_SECRET_KEY, + Keychain.Key.SHARED_PUBKY_SOURCE, + ) + for (key in identityKeys) { + whenever(keychain.loadString(key.name)).thenReturn("stored") + assertTrue(sut.hasIdentityForBackup()) + whenever(keychain.loadString(key.name)).thenReturn(null) + } + whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenAnswer { throw TestAppError("unreadable") } + assertTrue(runSuspendCatching { sut.hasIdentityForBackup() }.isFailure) + } + @Test fun `awaitInitialization shares startup and preserves it when a waiter is cancelled`() = test { val imported = CompletableDeferred() diff --git a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt index 91cdfe0477..2dbdff6abe 100644 --- a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt @@ -23,7 +23,6 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify -import org.mockito.kotlin.verifyBlocking import org.mockito.kotlin.whenever import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore @@ -411,12 +410,33 @@ class WalletViewModelTest : BaseUnitTest() { } @Test - fun `post restore profile failure allows proceeding only while safety markers stay clear`() = test { + fun `completed wallet restore does not wait for optional identity activation`() = test { + val release = CompletableDeferred() whenever(backupRepo.performFullRestoreFromLatestBackup(any())).thenReturn(Result.success(Unit)) - whenever(pubkyRepo.initialize()).doSuspendableAnswer { throw AppError("profile cache unavailable") } + whenever(pubkyRepo.initialize()).doSuspendableAnswer { + release.await() + Result.success(Unit) + } + try { + sut.onBackupRestoreRetry() + runCurrent() + assertEquals(RestoreState.Completed, sut.restoreState.value) + verify(pubkyRepo).scheduleInitializationAfterRestore() + verify(pubkyRepo, never()).initialize() + verify(backupRepo).setRestorePending(false) + } finally { + release.complete(Unit) + } + } + + @Test + fun `proceed rechecks safety markers after an optional restore failure`() = test { + whenever(backupRepo.performFullRestoreFromLatestBackup(any())) + .thenReturn(Result.failure(AppError("metadata cache unavailable"))) sut.onBackupRestoreRetry() advanceUntilIdle() assertEquals(RestoreState.BackupFailed(1, hasPendingWalletRestore = false), sut.restoreState.value) + verify(pubkyRepo, never()).scheduleInitializationAfterRestore() whenever(backupRepo.hasPendingWalletRestore()).thenReturn(true) var dismissed = false @@ -589,7 +609,7 @@ class WalletViewModelTest : BaseUnitTest() { walletState.value = walletState.value.copy(walletExists = true) advanceUntilIdle() - verifyBlocking(pubkyRepo) { initialize() } + verify(pubkyRepo).scheduleInitializationAfterRestore() } @Test 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 ac2a7c6680589bd80e75de1ffb097b44f1cf2f28 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 00:50:23 +0200 Subject: [PATCH 02/61] docs: associate restore note with PR 1686 --- changelog.d/next/{restore-identity.fixed.md => 1686.fixed.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changelog.d/next/{restore-identity.fixed.md => 1686.fixed.md} (100%) diff --git a/changelog.d/next/restore-identity.fixed.md b/changelog.d/next/1686.fixed.md similarity index 100% rename from changelog.d/next/restore-identity.fixed.md rename to changelog.d/next/1686.fixed.md From ab59838adcc9346270e93590ad0165c2e334eaf3 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 01:15:20 +0200 Subject: [PATCH 03/61] fix: stop automatic profile deletion replay --- .../java/to/bitkit/repositories/PubkyRepo.kt | 24 ------ .../screens/profile/EditProfileViewModel.kt | 2 +- .../to/bitkit/repositories/PubkyRepoTest.kt | 81 ++++++++----------- .../profile/EditProfileViewModelTest.kt | 32 ++++---- .../next/profile-delete-retry.fixed.md | 1 + .../delete-profile-uncertain-response.xml | 17 ++++ 6 files changed, 68 insertions(+), 89 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/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 8340349b42..e92362b4a5 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -1086,16 +1086,6 @@ class PubkyRepo @Inject constructor( } } - suspend fun deleteProfileWithSessionRetry(): Result = withContext(ioDispatcher) { - val initialResult = deleteProfile() - if (initialResult.isSuccess) return@withContext initialResult - - val refreshedSession = refreshSessionIfPossible().getOrDefault(false) - if (!refreshedSession) return@withContext initialResult - - deleteProfile() - } - suspend fun deleteProfile(): Result = runSuspendCatching { withContext(ioDispatcher) { requireNotNull(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)) { @@ -1812,20 +1802,6 @@ class PubkyRepo @Inject constructor( } } - suspend fun refreshSessionIfPossible(): Result = runSuspendCatching { - withContext(ioDispatcher) { - val storedSecretKeyHex = activeSecretKeyHex() ?: return@withContext false - - pubkyService.signIn(storedSecretKeyHex) - val publicKey = pubkyService.publicKeyFromSecret(storedSecretKeyHex).ensurePubkyPrefix() - - notifyBackupStateChanged() - continueSignIn(publicKey) - - true - } - } - // endregion // region Sign out diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt index e2628806cf..06bb4bd4c5 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt @@ -273,7 +273,7 @@ class EditProfileViewModel @Inject constructor( try { privatePaykitRepo.beginProfileDeletion() privatePaykitRepo.removePublishedEndpointsForCleanup(TAG, deferAppSync = true) - val result = pubkyRepo.deleteProfileWithSessionRetry() + val result = pubkyRepo.deleteProfile() if (result.isSuccess) { privatePaykitRepo.closeAndClear() ToastEventBus.send( diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index a6d429a882..28ad1a79a0 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -1375,36 +1375,46 @@ class PubkyRepoTest : BaseUnitTest() { } @Test - fun `deleteProfileWithSessionRetry should refresh session and retry delete`() = test { - val expiredSession = "expired_session" - val newSession = "new_session" + fun `profile deletion does not replay after an uncertain response`() = test { val secretKey = "local_secret" - authenticateForTesting(publicKey = VALID_SELF_KEY, secret = expiredSession) - whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn(expiredSession, newSession) + authenticateForTesting(publicKey = VALID_SELF_KEY, secret = "test_session") whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(secretKey) - whenever(pubkyService.deletePaykitProfile()).thenAnswer { throw TestAppError("Expired") }.thenReturn(Unit) - whenever(pubkyService.signIn(secretKey)).thenReturn(Unit) whenever(pubkyService.publicKeyFromSecret(secretKey)).thenReturn(VALID_SELF_KEY.removePrefix("pubky")) + val uncertainResponse = TestAppError("Connection closed after profile deletion") + whenever(pubkyService.deletePaykitProfile()).thenAnswer { throw uncertainResponse }.thenReturn(Unit) - val result = sut.deleteProfileWithSessionRetry() + val result = sut.deleteProfile() - assertTrue(result.isSuccess) - verifyBlocking(pubkyService, times(2)) { deletePaykitProfile() } + assertSame(uncertainResponse, result.exceptionOrNull()) + verify(pubkyService).deletePaykitProfile() + verify(pubkyService, never()).signIn(any()) + verify(pubkyService, never()).signOut() } @Test - fun `deleteProfileWithSessionRetry should return failure when session cannot refresh`() = test { - val expiredSession = "expired_session" - authenticateForTesting(publicKey = VALID_SELF_KEY, secret = expiredSession) - whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn(expiredSession) - whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(null) - whenever(pubkyService.deletePaykitProfile()).thenAnswer { throw TestAppError("Expired") } - - val result = sut.deleteProfileWithSessionRetry() + fun `failed profile deletion does not restore an identity after sign out`() = test { + val secretKey = "local_secret" + authenticateForTesting(publicKey = VALID_SELF_KEY, secret = "test_session") + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(secretKey) + whenever(pubkyService.publicKeyFromSecret(secretKey)).thenReturn(VALID_SELF_KEY.removePrefix("pubky")) + val deletionStarted = CompletableDeferred() + val finishDeletion = CompletableDeferred() + val uncertainResponse = TestAppError("Connection closed after profile deletion") + whenever(pubkyService.deletePaykitProfile()).doSuspendableAnswer { + deletionStarted.complete(Unit) + withContext(NonCancellable) { finishDeletion.await() } + throw uncertainResponse + } + val deletion = async { sut.deleteProfile() } + deletionStarted.await() + sut.signOut().getOrThrow() + finishDeletion.complete(Unit) - assertTrue(result.isFailure) - verifyBlocking(pubkyService) { deletePaykitProfile() } - verifyBlocking(pubkyService, never()) { signIn(any()) } + assertSame(uncertainResponse, deletion.await().exceptionOrNull()) + assertNull(sut.publicKey.value) + assertFalse(sut.isAuthenticated.value) + verify(pubkyService, never()).signIn(any()) + verify(pubkyService).deletePaykitProfile() } @Test @@ -3466,31 +3476,6 @@ class PubkyRepoTest : BaseUnitTest() { verify(pubkyStore).reset() } - @Test - fun `refreshSessionIfPossible should refresh session when local secret key exists`() = test { - val secretKey = "local_secret" - whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(secretKey) - whenever(pubkyService.signIn(secretKey)).thenReturn(Unit) - whenever(pubkyService.publicKeyFromSecret(secretKey)).thenReturn(VALID_SELF_KEY.removePrefix("pubky")) - - val result = sut.refreshSessionIfPossible() - - assertEquals(true, result.getOrNull()) - assertEquals(VALID_SELF_KEY, sut.publicKey.value) - assertTrue(sut.isAuthenticated.value) - } - - @Test - fun `refreshSessionIfPossible should return false when local secret key is missing`() = test { - whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(null) - - val result = sut.refreshSessionIfPossible() - - assertEquals(false, result.getOrNull()) - assertNull(sut.publicKey.value) - assertFalse(sut.isAuthenticated.value) - } - @Test fun `restoreSessionBackupState should derive local secret key for local seed backups`() = test { whenever(keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn("test mnemonic") @@ -4394,7 +4379,7 @@ class PubkyRepoTest : BaseUnitTest() { } @Test - fun `a contact edit started before the session of its identity is refreshed still saves`() = test { + fun `a contact edit started before the session of its identity is restored still saves`() = test { val store = stubGatedPubkyStore() authenticateForTesting(publicKey = VALID_SELF_KEY) whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("local_secret") @@ -4402,7 +4387,7 @@ class PubkyRepoTest : BaseUnitTest() { whenever(pubkyService.publicKeyFromSecret("local_secret")).thenReturn(VALID_SELF_KEY.removePrefix("pubky")) val signIn = checkNotNull(sut.currentSignIn()) - assertEquals(true, sut.refreshSessionIfPossible().getOrNull()) + sut.initialize().getOrThrow() val result = sut.updateContact(signIn, VALID_CONTACT_KEY_A, "Alice", "", null, emptyList(), listOf("Friend")) assertTrue(result.isSuccess) diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt index f9c005d101..381c03e5e4 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt @@ -60,7 +60,7 @@ class EditProfileViewModelTest : BaseUnitTest() { sut.showDeleteConfirmation() advanceUntilIdle() verify(pubkyRepo, times(1)).forgetUnrestoredIdentity() - verify(pubkyRepo, never()).deleteProfileWithSessionRetry() + verify(pubkyRepo, never()).deleteProfile() verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any()) assertFalse(sut.uiState.value.showDeleteDialog) @@ -113,7 +113,7 @@ class EditProfileViewModelTest : BaseUnitTest() { val sut = createSut() advanceUntilIdle() val result = CompletableDeferred>() - whenever(pubkyRepo.deleteProfileWithSessionRetry()).doSuspendableAnswer { result.await() } + whenever(pubkyRepo.deleteProfile()).doSuspendableAnswer { result.await() } sut.showDeleteConfirmation() sut.deleteProfile() @@ -129,7 +129,7 @@ class EditProfileViewModelTest : BaseUnitTest() { sut.disconnectProfile() sut.showDeleteConfirmation() advanceUntilIdle() - verify(pubkyRepo, times(1)).deleteProfileWithSessionRetry() + verify(pubkyRepo, times(1)).deleteProfile() verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any()) verify(pubkyRepo, never()).signOut() assertFalse(sut.uiState.value.showDeleteDialog) @@ -161,7 +161,7 @@ class EditProfileViewModelTest : BaseUnitTest() { sut.showDeleteConfirmation() advanceUntilIdle() verify(pubkyRepo, times(1)).saveProfile(any(), any(), any(), any(), any()) - verify(pubkyRepo, never()).deleteProfileWithSessionRetry() + verify(pubkyRepo, never()).deleteProfile() verify(pubkyRepo, never()).forgetUnrestoredIdentity() assertFalse(sut.uiState.value.showDeleteDialog) @@ -183,7 +183,7 @@ class EditProfileViewModelTest : BaseUnitTest() { @Test fun `deleteProfile should emit success when repository delete succeeds`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn(Result.success(Unit)) + whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) val sut = createSut() advanceUntilIdle() @@ -197,14 +197,14 @@ class EditProfileViewModelTest : BaseUnitTest() { assertFalse(sut.uiState.value.showDeleteFailureDialog) inOrder(privatePaykitRepo, pubkyRepo).apply { verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) - verify(pubkyRepo).deleteProfileWithSessionRetry() + verify(pubkyRepo).deleteProfile() verify(privatePaykitRepo).closeAndClear() } } @Test fun `profile created in Bitkit keeps delete copy`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn(Result.success(Unit)) + whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) val sut = createSut() advanceUntilIdle() @@ -218,7 +218,7 @@ class EditProfileViewModelTest : BaseUnitTest() { @Test fun `ring identity is unlinked with the same cleanup`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn(Result.success(Unit)) + whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) val sut = createSut(isRingIdentity = true) advanceUntilIdle() @@ -234,7 +234,7 @@ class EditProfileViewModelTest : BaseUnitTest() { verify(context, never()).getString(R.string.profile__delete_success) inOrder(privatePaykitRepo, pubkyRepo).apply { verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) - verify(pubkyRepo).deleteProfileWithSessionRetry() + verify(pubkyRepo).deleteProfile() verify(privatePaykitRepo).closeAndClear() } } @@ -256,7 +256,7 @@ class EditProfileViewModelTest : BaseUnitTest() { @Test fun `retryDeleteProfile should emit success when repository delete succeeds`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn(Result.success(Unit)) + whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) val sut = createSut() advanceUntilIdle() @@ -270,14 +270,14 @@ class EditProfileViewModelTest : BaseUnitTest() { assertFalse(sut.uiState.value.showDeleteFailureDialog) inOrder(privatePaykitRepo, pubkyRepo).apply { verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) - verify(pubkyRepo).deleteProfileWithSessionRetry() + verify(pubkyRepo).deleteProfile() verify(privatePaykitRepo).closeAndClear() } } @Test fun `deleteProfile should show retry dialog when delete still fails`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn( + whenever(pubkyRepo.deleteProfile()).thenReturn( Result.failure(TestAppError("expired session")), ) @@ -295,7 +295,7 @@ class EditProfileViewModelTest : BaseUnitTest() { @Test fun `disconnectProfile should emit disconnect success`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn( + whenever(pubkyRepo.deleteProfile()).thenReturn( Result.failure(TestAppError("expired session")), ) whenever(pubkyRepo.signOut()).thenReturn(Result.success(Unit)) @@ -354,7 +354,7 @@ class EditProfileViewModelTest : BaseUnitTest() { val sut = createSut() whenever { privatePaykitRepo.removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) } .thenReturn(Result.failure(TestAppError("cleanup failed"))) - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn(Result.success(Unit)) + whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) advanceUntilIdle() sut.effects.test { @@ -367,14 +367,14 @@ class EditProfileViewModelTest : BaseUnitTest() { assertFalse(sut.uiState.value.isDeleting) inOrder(privatePaykitRepo, pubkyRepo).apply { verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) - verify(pubkyRepo).deleteProfileWithSessionRetry() + verify(pubkyRepo).deleteProfile() verify(privatePaykitRepo).closeAndClear() } } @Test fun `dismissDeleteFailureDialog should hide retry dialog`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn( + whenever(pubkyRepo.deleteProfile()).thenReturn( Result.failure(TestAppError("expired session")), ) 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 99b446a59634e66ab8cf196ff0c109aa5bc9e070 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 01:16:43 +0200 Subject: [PATCH 04/61] docs: associate deletion fix with PR 1688 --- changelog.d/next/{profile-delete-retry.fixed.md => 1688.fixed.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changelog.d/next/{profile-delete-retry.fixed.md => 1688.fixed.md} (100%) diff --git a/changelog.d/next/profile-delete-retry.fixed.md b/changelog.d/next/1688.fixed.md similarity index 100% rename from changelog.d/next/profile-delete-retry.fixed.md rename to changelog.d/next/1688.fixed.md From a8f0810769b5c29c01c6f7c1f02e3988b048c7db Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 03:31:47 +0100 Subject: [PATCH 05/61] fix: preserve pending backups across restart --- .../java/to/bitkit/repositories/BackupRepo.kt | 516 ++++++++------- .../to/bitkit/repositories/BackupRepoTest.kt | 591 +++++++++++++++++- changelog.d/next/1689.fixed.md | 1 + .../wallet-snapshot-consistency.md | 36 ++ 4 files changed, 912 insertions(+), 232 deletions(-) create mode 100644 changelog.d/next/1689.fixed.md diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index f9ea2491d3..78ea754524 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -5,13 +5,18 @@ import com.synonym.bitkitcore.UsdtException import com.synonym.vssclient.VssException import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async +import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -23,6 +28,7 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive +import kotlinx.coroutines.joinAll import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock @@ -82,6 +88,7 @@ import java.util.concurrent.ConcurrentHashMap import javax.inject.Inject import javax.inject.Provider import javax.inject.Singleton +import kotlin.coroutines.cancellation.CancellationException import kotlin.time.Clock import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds @@ -142,19 +149,30 @@ class BackupRepo @Inject constructor( private val usdtRecoveryBackup = UsdtRecoveryBackupStore(vssBackupClient) private val scope = appScope(ioDispatcher, TAG) + private val lifecycleLock = Any() + private val resetMutex = Mutex() + private var generation = 0L + private var resetting = false + + // Reset owns all pending work; stopping observation only cancels its child scope. + // Retiring observation parents remain attached until their cancellation cleanup finishes. + private var pendingScope = newBackupScope(scope) + private var observation: Observation? = null + private val retiringObservations = mutableSetOf() private val backupJobs = mutableMapOf() - private val statusObserverJobs = mutableListOf() - private val dataListenerJobs = mutableListOf() - private var periodicCheckJob: Job? = null + private val categoryMutexes = BackupCategory.entries.associateWith { Mutex() } private val runningBackups = ConcurrentHashMap.newKeySet() // Tracks active jobs since app start private val failedBackupRequired = ConcurrentHashMap() private val temporaryFailureRetries = ConcurrentHashMap() private val temporaryFailureSince = ConcurrentHashMap() - - private var isObserving = false private var lastNotificationTime = 0L + private class Observation(val scope: CoroutineScope, val generation: Long) + + private fun newBackupScope(parent: CoroutineScope) = + CoroutineScope(parent.coroutineContext + SupervisorJob(parent.coroutineContext[Job])) + private val _isRestoring = MutableStateFlow(false) val isRestoring: StateFlow = _isRestoring.asStateFlow() @@ -163,10 +181,34 @@ class BackupRepo @Inject constructor( private val restorePendingUntil = MutableStateFlow(0L) - fun reset() { - stopObservingBackups() - vssBackupClient.reset() - vssBackupClientLdk.reset() + suspend fun reset() = withContext(ioDispatcher) { + resetMutex.withLock { + val pending = synchronized(lifecycleLock) { + resetting = true + observation = null + pendingScope.coroutineContext[Job] + } + withContext(NonCancellable) { + try { + pending?.cancel() + pending?.join() + synchronized(lifecycleLock) { generation += 1 } + vssBackupClient.reset() + vssBackupClientLdk.reset() + synchronized(lifecycleLock) { + backupJobs.clear() + failedBackupRequired.clear() + temporaryFailureRetries.clear() + temporaryFailureSince.clear() + } + } finally { + synchronized(lifecycleLock) { + pendingScope = newBackupScope(scope) + resetting = false + } + } + } + } } fun setWiping(isWiping: Boolean) = _isWiping.update { isWiping } @@ -208,16 +250,26 @@ class BackupRepo @Inject constructor( failedBackupRequired[category] != this.required fun startObservingBackups() { - if (isObserving) return - if (_isWiping.value) { - Logger.debug("Skipped observing backups while wiping", context = TAG) - return + val startup = synchronized(lifecycleLock) { + if (observation != null || resetting || _isWiping.value) return + val previous = retiringObservations.toList() + val owner = Observation(newBackupScope(pendingScope), generation) + observation = owner + val parent = checkNotNull(owner.scope.coroutineContext[Job]) + retiringObservations.add(parent) + parent.invokeOnCompletion { synchronized(lifecycleLock) { retiringObservations.remove(parent) } } + owner.scope.launch(start = CoroutineStart.LAZY) { + previous.joinAll() + currentCoroutineContext().ensureActive() + startObservation(owner) + } } + startup.start() + } - isObserving = true + private fun startObservation(owner: Observation) { Logger.debug("Start observing backup statuses and data store changes", context = TAG) - - scope.launch { + owner.scope.launch { vssBackupClient.setupWithRetry { onSuccess = { attempt -> Logger.debug("VSS client setup succeeded on attempt $attempt", context = TAG) @@ -232,15 +284,16 @@ class BackupRepo @Inject constructor( Logger.warn("VSS client setup failed after $maxAttempts attempts", context = TAG) } }.onSuccess { - scope.launch { vssBackupClientLdk.setup() } + currentCoroutineContext().ensureActive() + vssBackupClientLdk.setup() } } - scope.launch { + owner.scope.launch { BackupCategory.entries.forEach { category -> if (category !in runningBackups) { - cacheStore.updateBackupStatus(category) { status -> - if (status.running) { + updateBackupStatus(category, owner.generation) { status -> + if (status.running && category !in runningBackups) { Logger.debug("Clearing stale running flag for: '$category'", context = TAG) status.copy(running = false) } else { @@ -251,39 +304,23 @@ class BackupRepo @Inject constructor( } } - startBackupStatusObservers() - startDataStoreListeners() - startPeriodicBackupFailureCheck() + startBackupStatusObservers(owner) + startDataStoreListeners(owner) + startPeriodicBackupFailureCheck(owner) } fun stopObservingBackups() { - if (!isObserving) return - - isObserving = false - - // Cancel all backup jobs - backupJobs.values.forEach { it.cancel() } - backupJobs.clear() - - // Cancel backup status observer jobs - statusObserverJobs.forEach { it.cancel() } - statusObserverJobs.clear() - - // Cancel data store listener jobs - dataListenerJobs.forEach { it.cancel() } - dataListenerJobs.clear() - - // Cancel periodic check job - periodicCheckJob?.cancel() - periodicCheckJob = null - + val parent = synchronized(lifecycleLock) { + observation?.scope?.coroutineContext?.get(Job).also { observation = null } + } + parent?.cancel() Logger.debug("Stopped observing backup statuses and data store changes", context = TAG) } - private fun startBackupStatusObservers() { + private fun startBackupStatusObservers(owner: Observation) { // Observe backup status changes for each category BackupCategory.entries.forEach { category -> - val job = scope.launch { + owner.scope.launch { cacheStore.backupStatuses .map { statuses -> statuses[category] ?: BackupItemStatus() } .distinctUntilChanged { old, new -> @@ -293,143 +330,126 @@ class BackupRepo @Inject constructor( } .collect { status -> if (status.shouldBackup(category)) { - scheduleBackup(category) + scheduleBackup(category, owner) } } } - statusObserverJobs.add(job) } - - Logger.debug("Started ${statusObserverJobs.size} backup status observers", context = TAG) } - private fun startDataStoreListeners() { - val settingsJob = scope.launch { + private fun startDataStoreListeners(owner: Observation) { + owner.scope.launch { settingsStore.data .distinctUntilChanged() .drop(1) .collect { if (shouldSkipBackup()) return@collect - markBackupRequired(BackupCategory.SETTINGS) + markBackupRequired(owner, BackupCategory.SETTINGS) } } - dataListenerJobs.add(settingsJob) - val widgetsJob = scope.launch { + owner.scope.launch { widgetsStore.data .distinctUntilChanged() .drop(1) .collect { if (shouldSkipBackup()) return@collect - markBackupRequired(BackupCategory.WIDGETS) + markBackupRequired(owner, BackupCategory.WIDGETS) } } - dataListenerJobs.add(widgetsJob) // WALLET - Observe transfers - val transfersJob = scope.launch { + owner.scope.launch { db.transferDao().observeAll() .distinctUntilChanged() .drop(1) .collect { if (shouldSkipBackup()) return@collect - markBackupRequired(BackupCategory.WALLET) + markBackupRequired(owner, BackupCategory.WALLET) } } - dataListenerJobs.add(transfersJob) - val watchOnlyAccountsJob = scope.launch { + owner.scope.launch { watchOnlyAccountStore.data .distinctUntilChanged() .drop(1) .collect { if (shouldSkipBackup()) return@collect - markBackupRequired(BackupCategory.WALLET) + markBackupRequired(owner, BackupCategory.WALLET) } } - dataListenerJobs.add(watchOnlyAccountsJob) // METADATA - Observe entire CacheStore excluding backup statuses - val cacheMetadataJob = scope.launch { + owner.scope.launch { cacheStore.data .map { it.copy(backupStatuses = mapOf()) } .distinctUntilChanged() .drop(1) .collect { if (shouldSkipBackup()) return@collect - markBackupRequired(BackupCategory.METADATA) + markBackupRequired(owner, BackupCategory.METADATA) } } - dataListenerJobs.add(cacheMetadataJob) // METADATA - Observe pre-activity metadata changes - val preActivityMetadataJob = scope.launch { + owner.scope.launch { preActivityMetadataRepo.preActivityMetadataChanged .drop(1) .collect { if (shouldSkipBackup()) return@collect - markBackupRequired(BackupCategory.METADATA) + markBackupRequired(owner, BackupCategory.METADATA) } } - dataListenerJobs.add(preActivityMetadataJob) // METADATA - Observe hardware wallet names only: the store is also rewritten by every connect, // and reconnect traffic must not re-upload the whole metadata envelope. - val hwWalletNamesJob = scope.launch { + owner.scope.launch { hwWalletStore.data .map { it.hwWalletNames() } .distinctUntilChanged() .drop(1) .collect { if (shouldSkipBackup()) return@collect - markBackupRequired(BackupCategory.METADATA) + markBackupRequired(owner, BackupCategory.METADATA) } } - dataListenerJobs.add(hwWalletNamesJob) - - dataListenerJobs.add(observeBackupChanges(pubkyRepo.backupStateVersion, BackupCategory.METADATA)) - dataListenerJobs.add(observeBackupChanges(privatePaykitRepo.get().backupStateVersion, BackupCategory.WALLET)) - dataListenerJobs.add(observeBackupChanges(paykitSdkService.backupStateVersion, BackupCategory.WALLET)) - dataListenerJobs.add(observeBackupChanges(paykitPaymentProofStore.backupStateVersion, BackupCategory.WALLET)) - dataListenerJobs.add(observeBackupChanges(onchainSendAttemptStore.backupStateVersion, BackupCategory.WALLET)) - dataListenerJobs.add( - observeBackupChanges(paykitUsdtPaymentRepo.get().backupStateVersion, BackupCategory.WALLET) - ) - dataListenerJobs.add( - observeBackupChanges(paykitUsdtPaymentRepo.get().backupStateVersion, BackupCategory.USDT_RECOVERY) - ) - dataListenerJobs.add( - observeBackupChanges( - usdtRepo.get().state.map { it.transfers }.distinctUntilChanged(), - BackupCategory.USDT_RECOVERY, - ) + + observeBackupChanges(owner, pubkyRepo.backupStateVersion, BackupCategory.METADATA) + observeBackupChanges(owner, privatePaykitRepo.get().backupStateVersion, BackupCategory.WALLET) + observeBackupChanges(owner, paykitSdkService.backupStateVersion, BackupCategory.WALLET) + observeBackupChanges(owner, paykitPaymentProofStore.backupStateVersion, BackupCategory.WALLET) + observeBackupChanges(owner, onchainSendAttemptStore.backupStateVersion, BackupCategory.WALLET) + observeBackupChanges(owner, paykitUsdtPaymentRepo.get().backupStateVersion, BackupCategory.WALLET) + observeBackupChanges(owner, paykitUsdtPaymentRepo.get().backupStateVersion, BackupCategory.USDT_RECOVERY) + observeBackupChanges( + owner, + usdtRepo.get().state.map { it.transfers }.distinctUntilChanged(), + BackupCategory.USDT_RECOVERY, ) - dataListenerJobs.add( - observeBackupChanges( - usdtRepo.get().state.map { it.transfers }.distinctUntilChanged(), - BackupCategory.WALLET, - ) + observeBackupChanges( + owner, + usdtRepo.get().state.map { it.transfers }.distinctUntilChanged(), + BackupCategory.WALLET, ) - dataListenerJobs.add(observeBackupChanges(paykitPresentationStore.backupStateVersion, BackupCategory.WALLET)) - dataListenerJobs.add( - observeBackupChanges( - privatePaykitAddressReservationRepo.get().backupStateVersion, - BackupCategory.WALLET, - ) + observeBackupChanges(owner, paykitPresentationStore.backupStateVersion, BackupCategory.WALLET) + observeBackupChanges( + owner, + privatePaykitAddressReservationRepo.get().backupStateVersion, + BackupCategory.WALLET, ) // BLOCKTANK - Observe blocktank state changes (orders, cjitEntries, info) - dataListenerJobs.add(observeBackupChanges(blocktankRepo.blocktankState, BackupCategory.BLOCKTANK)) + observeBackupChanges(owner, blocktankRepo.blocktankState, BackupCategory.BLOCKTANK) // ACTIVITY - Observe activity changes - dataListenerJobs.add(observeBackupChanges(activityRepo.activitiesChanged, BackupCategory.ACTIVITY)) + observeBackupChanges(owner, activityRepo.activitiesChanged, BackupCategory.ACTIVITY) // Hardware tags are carried by the metadata backup. Observe the narrower tag signal so ordinary // payment and sync traffic does not re-upload the whole metadata envelope. - dataListenerJobs.add(observeBackupChanges(activityRepo.activityTagsChanged, BackupCategory.METADATA)) + observeBackupChanges(owner, activityRepo.activityTagsChanged, BackupCategory.METADATA) // LIGHTNING_CONNECTIONS - Only display sync timestamp, ldk-node manages its own backups @OptIn(FlowPreview::class) - val lightningConnectionsJob = scope.launch { + owner.scope.launch { lightningService.syncStatusChanged .debounce(SYNC_STATUS_DEBOUNCE) .collect { @@ -437,87 +457,119 @@ class BackupRepo @Inject constructor( ?.let { it * 1000 } // Convert seconds to millis ?: return@collect if (shouldSkipBackup()) return@collect - cacheStore.updateBackupStatus(BackupCategory.LIGHTNING_CONNECTIONS) { + updateBackupStatus(BackupCategory.LIGHTNING_CONNECTIONS, owner.generation) { it.copy(required = lastSync, synced = lastSync, running = false) } } } - dataListenerJobs.add(lightningConnectionsJob) - - Logger.debug("Started ${dataListenerJobs.size} data store listeners", context = TAG) } - private fun observeBackupChanges(flow: Flow<*>, category: BackupCategory): Job = - scope.launch { + private fun observeBackupChanges(owner: Observation, flow: Flow<*>, category: BackupCategory): Job = + owner.scope.launch { flow.drop(1).collect { if (shouldSkipBackup(category)) return@collect - markBackupRequired(category) + markBackupRequired(owner, category) } } - private fun startPeriodicBackupFailureCheck() { - periodicCheckJob = scope.launch { + private fun startPeriodicBackupFailureCheck(owner: Observation) { + owner.scope.launch { while (currentCoroutineContext().isActive) { delay(BACKUP_CHECK_INTERVAL) - checkForFailedBackups() + checkForFailedBackups(owner) } } } - private fun markBackupRequired(category: BackupCategory) { - scope.launch { - failedBackupRequired -= category - cacheStore.updateBackupStatus(category) { + private suspend fun markBackupRequired(owner: Observation, category: BackupCategory) = + markBackupRequired(category, owner.generation) + + private suspend fun markBackupRequired(category: BackupCategory, expectedGeneration: Long) = + withContext(NonCancellable) { + // A consumed change must remain pending even if observation stops before the cache write. + updateBackupStatus(category, expectedGeneration) { + failedBackupRequired -= category it.copy(required = maxOf(currentTimeMillis(), it.required + 1, it.synced + 1)) } - Logger.verbose("Marked backup required for: '$category'", context = TAG) } - } - private fun scheduleBackup(category: BackupCategory) { - backupJobs[category]?.cancel() - - Logger.verbose("Scheduling backup for: '$category'", context = TAG) - - backupJobs[category] = scope.launch { - runningBackups += category - cacheStore.updateBackupStatus(category) { - it.copy(running = true) + private suspend fun updateBackupStatus( + category: BackupCategory, + expectedGeneration: Long, + transform: (BackupItemStatus) -> BackupItemStatus, + ) { + cacheStore.update { data -> + synchronized(lifecycleLock) { + // Reset drains admitted writers before advancing the generation or clearing clients. + if (generation != expectedGeneration) return@update data + val status = data.backupStatuses[category] ?: BackupItemStatus() + data.copy(backupStatuses = data.backupStatuses + (category to transform(status))) } + } + } - delay(BACKUP_DEBOUNCE) - if (category == BackupCategory.WALLET) paykitSdkService.isPaymentSubmissionActive.first { !it } - - val status = cacheStore.backupStatuses.first()[category] ?: BackupItemStatus() - if (status.isRequired && !shouldSkipBackup(category)) { - triggerBackup(category) - } else { - Logger.debug("Backup no longer needed for: '$category'", context = TAG) - runningBackups -= category - cacheStore.updateBackupStatus(category) { - it.copy(running = false) - } + private fun scheduleBackup( + category: BackupCategory, + owner: Observation? = null, + requestedGeneration: Long? = null, + ) { + val job = synchronized(lifecycleLock) { + if (resetting || _isWiping.value || (owner != null && observation !== owner) || + (requestedGeneration != null && requestedGeneration != generation) + ) { + return } - }.also { job -> - job.invokeOnCompletion { exception -> - if (exception != null) { - Logger.debug("Backup job cancelled for: '$category'", context = TAG) - scope.launch { - runningBackups -= category - cacheStore.updateBackupStatus(category) { - it.copy(running = false) + val existing = backupJobs[category] + if (existing != null && !existing.isCompleted && !existing.isCancelled) return + val expectedGeneration = generation + val jobScope = owner?.scope ?: pendingScope + jobScope.launch(start = CoroutineStart.LAZY) { + try { + categoryMutexes.getValue(category).withLock { + runningBackups += category + try { + updateBackupStatus(category, expectedGeneration) { it.copy(running = true) } + delay(BACKUP_DEBOUNCE) + if (category == BackupCategory.WALLET) { + paykitSdkService.isPaymentSubmissionActive.first { !it } + } + val status = cacheStore.backupStatuses.first()[category] ?: BackupItemStatus() + if (status.isRequired && !shouldSkipBackup(category)) { + performBackup(category, expectedGeneration) + } + } finally { + finishBackup(category, expectedGeneration) } } + } finally { + val currentJob = currentCoroutineContext()[Job] + synchronized(lifecycleLock) { backupJobs.remove(category, currentJob) } + val nextOwner = synchronized(lifecycleLock) { + observation?.takeIf { generation == expectedGeneration && (owner == null || owner === it) } + } + if (nextOwner != null && nextOwner.scope.isActive) { + val status = cacheStore.backupStatuses.first()[category] ?: BackupItemStatus() + if (status.shouldBackup(category)) scheduleBackup(category, nextOwner) + } } - } + }.also { backupJobs[category] = it } } + job.start() } - private fun checkForFailedBackups() { + private suspend fun finishBackup(category: BackupCategory, expectedGeneration: Long) = withContext(NonCancellable) { + try { + updateBackupStatus(category, expectedGeneration) { it.copy(running = false) } + } finally { + runningBackups -= category + } + } + + private fun checkForFailedBackups(owner: Observation) { val currentTime = currentTimeMillis() // find if there are any backup categories that have been failing for more than 30 minutes - scope.launch { + owner.scope.launch { val backupStatuses = cacheStore.backupStatuses.first() val hasFailedBackups = BackupCategory.entries.any { category -> val status = backupStatuses[category] ?: BackupItemStatus() @@ -529,18 +581,18 @@ class BackupRepo @Inject constructor( } if (hasFailedBackups) { - showBackupFailureNotification(currentTime) + showBackupFailureNotification(owner, currentTime) } } } - private fun showBackupFailureNotification(currentTime: Long) { + private fun showBackupFailureNotification(owner: Observation, currentTime: Long) { // Throttle notifications to avoid spam if (currentTime - lastNotificationTime < FAILED_BACKUP_NOTIFICATION_INTERVAL) return lastNotificationTime = currentTime - scope.launch { + owner.scope.launch { ToastEventBus.send( type = Toast.ToastType.ERROR, title = context.getString(R.string.settings__backup__failed_title), @@ -551,58 +603,85 @@ class BackupRepo @Inject constructor( } } - suspend fun triggerBackup(category: BackupCategory): Result = withContext(ioDispatcher) { - Logger.debug("Backup starting for: '$category'", context = TAG) - - var backupRequired = currentTimeMillis() - runningBackups += category - failedBackupRequired -= category - try { - cacheStore.updateBackupStatus(category) { - backupRequired = maxOf(backupRequired, it.required, it.synced + 1) - it.copy(running = true, required = backupRequired) + suspend fun triggerBackup(category: BackupCategory): Result = withBackupOperation { expectedGeneration -> + categoryMutexes.getValue(category).withLock { + if (synchronized(lifecycleLock) { resetting || generation != expectedGeneration }) { + return@withLock Result.failure(UsdtException.BackupUnavailable()) } + runningBackups += category + try { + performBackup(category, expectedGeneration) + } finally { + finishBackup(category, expectedGeneration) + } + } + } - val upload = when (category) { - BackupCategory.WALLET -> uploadWalletBackup() - BackupCategory.USDT_RECOVERY -> uploadUsdtRecoveryBackup() - else -> runSuspendCatching { - vssBackupClient.putObject(key = category.name, data = getBackupDataBytes(category)).getOrThrow() - } + private suspend fun performBackup(category: BackupCategory, expectedGeneration: Long): Result { + Logger.debug("Backup starting for: '$category'", context = TAG) + var backupRequired = currentTimeMillis() + updateBackupStatus(category, expectedGeneration) { + failedBackupRequired -= category + backupRequired = maxOf(backupRequired, it.required, it.synced + 1) + it.copy(running = true, required = backupRequired) + } + if (synchronized(lifecycleLock) { resetting || generation != expectedGeneration }) { + return Result.failure(UsdtException.BackupUnavailable()) + } + val upload = when (category) { + BackupCategory.WALLET -> uploadWalletBackup() + BackupCategory.USDT_RECOVERY -> uploadUsdtRecoveryBackup() + else -> runSuspendCatching { + vssBackupClient.putObject(key = category.name, data = getBackupDataBytes(category)).getOrThrow() } - upload - .onSuccess { - withContext(NonCancellable) { - cacheStore.updateBackupStatus(category) { - it.copy(running = false, synced = backupRequired) - } - runningBackups -= category + } + return upload + .onSuccess { + withContext(NonCancellable) { + updateBackupStatus(category, expectedGeneration) { failedBackupRequired -= category temporaryFailureRetries -= category temporaryFailureSince -= category + it.copy(running = false, synced = backupRequired) } - Logger.info("Backup succeeded for: '$category'", context = TAG) - } - .onFailure { markBackupFailed(category, backupRequired, it) } - .map {} - } finally { - if (runningBackups.remove(category)) { - withContext(NonCancellable) { - cacheStore.updateBackupStatus(category) { it.copy(running = false) } } + Logger.info("Backup succeeded for: '$category'", context = TAG) } - } + .onFailure { markBackupFailed(category, backupRequired, expectedGeneration, it) } + .map { } } - suspend fun persistWalletBackup(): Result = - uploadWalletBackup().onFailure { markBackupRequired(BackupCategory.WALLET) } + suspend fun persistWalletBackup(): Result = withBackupOperation { expectedGeneration -> + uploadWalletBackup().onFailure { markBackupRequired(BackupCategory.WALLET, expectedGeneration) } + } - suspend fun persistUsdtRecoveryBackup(snapshot: String): Result = runSuspendCatching { - cacheStore.updateBackupStatus(BackupCategory.USDT_RECOVERY) { - it.copy(required = maxOf(currentTimeMillis(), it.required + 1, it.synced + 1)) + suspend fun persistUsdtRecoveryBackup(snapshot: String): Result = withBackupOperation { expectedGeneration -> + runSuspendCatching { + updateBackupStatus(BackupCategory.USDT_RECOVERY, expectedGeneration) { + it.copy(required = maxOf(currentTimeMillis(), it.required + 1, it.synced + 1)) + } + uploadUsdtRecoveryBackup(snapshot).getOrThrow() + }.onFailure { markBackupRequired(BackupCategory.USDT_RECOVERY, expectedGeneration) } + } + + private suspend fun withBackupOperation( + operation: suspend (Long) -> Result, + ): Result = withContext(ioDispatcher) { + val callerContext = currentCoroutineContext().minusKey(Job) + val task = synchronized(lifecycleLock) { + if (resetting || _isWiping.value) return@withContext Result.failure(UsdtException.BackupUnavailable()) + val expectedGeneration = generation + pendingScope.async(context = callerContext, start = CoroutineStart.LAZY) { operation(expectedGeneration) } } - uploadUsdtRecoveryBackup(snapshot).getOrThrow() - }.onFailure { markBackupRequired(BackupCategory.USDT_RECOVERY) } + try { + task.await() + } catch (e: CancellationException) { + currentCoroutineContext().ensureActive() + Result.failure(UsdtException.BackupUnavailable().apply { initCause(e) }) + } finally { + withContext(NonCancellable) { task.cancelAndJoin() } + } + } private suspend fun uploadUsdtRecoveryBackup(snapshot: String? = null): Result = withContext(ioDispatcher) { runSuspendCatching { @@ -640,9 +719,14 @@ class BackupRepo @Inject constructor( }.map { } } - private suspend fun markBackupFailed(category: BackupCategory, backupRequired: Long, e: Throwable) { + private suspend fun markBackupFailed( + category: BackupCategory, + backupRequired: Long, + expectedGeneration: Long, + e: Throwable, + ) { withContext(NonCancellable) { - cacheStore.updateBackupStatus(category) { + updateBackupStatus(category, expectedGeneration) { if (it.required == backupRequired && e !is WalletBackupSnapshotChanged) { failedBackupRequired[category] = backupRequired } else { @@ -650,28 +734,41 @@ class BackupRepo @Inject constructor( } it.copy(running = false) } - runningBackups -= category } when { e is WalletBackupSnapshotChanged -> Logger.debug("Deferred changing backup snapshot for: '$category'", context = TAG) - e.isTemporaryBackupFailure() -> retryAfterTemporaryFailure(category, backupRequired, e) + e.isTemporaryBackupFailure() -> retryAfterTemporaryFailure(category, backupRequired, expectedGeneration, e) else -> Logger.error("Backup failed for: '$category'", e, context = TAG) } } - private fun retryAfterTemporaryFailure(category: BackupCategory, backupRequired: Long, e: Throwable) { - val attempt = temporaryFailureRetries.merge(category, 1, Int::plus) ?: 1 - temporaryFailureSince.putIfAbsent(category, backupRequired) - val retryDelay = (TEMPORARY_FAILURE_RETRY_DELAY * (1 shl (attempt - 1).coerceAtMost(MAX_RETRY_SHIFT))) - .coerceAtMost(TEMPORARY_FAILURE_RETRY_MAX_DELAY) - Logger.warn("Retrying backup for: '$category' in '$retryDelay'", e, context = TAG) - scope.launch { - delay(retryDelay) - if (!failedBackupRequired.remove(category, backupRequired) || !isObserving) return@launch - val status = cacheStore.backupStatuses.first()[category] ?: return@launch - if (status.shouldBackup(category)) scheduleBackup(category) + private fun retryAfterTemporaryFailure( + category: BackupCategory, + backupRequired: Long, + expectedGeneration: Long, + e: Throwable, + ) { + val job = synchronized(lifecycleLock) { + if (resetting || generation != expectedGeneration) return + val attempt = temporaryFailureRetries.merge(category, 1, Int::plus) ?: 1 + temporaryFailureSince.putIfAbsent(category, backupRequired) + val retryDelay = (TEMPORARY_FAILURE_RETRY_DELAY * (1 shl (attempt - 1).coerceAtMost(MAX_RETRY_SHIFT))) + .coerceAtMost(TEMPORARY_FAILURE_RETRY_MAX_DELAY) + Logger.warn("Retrying backup for: '$category' in '$retryDelay'", e, context = TAG) + pendingScope.launch(start = CoroutineStart.LAZY) { + delay(retryDelay) + val owner = synchronized(lifecycleLock) { + if (generation != expectedGeneration || !failedBackupRequired.remove(category, backupRequired)) { + return@launch + } + observation + } ?: return@launch + val status = cacheStore.backupStatuses.first()[category] ?: return@launch + if (status.shouldBackup(category)) scheduleBackup(category, owner) + } } + job.start() } private suspend fun getBackupDataBytes(category: BackupCategory): ByteArray = when (category) { @@ -1131,10 +1228,11 @@ class BackupRepo @Inject constructor( fun scheduleFullBackup() { Logger.debug("Scheduling backups for all categories", context = TAG) + val requestedGeneration = synchronized(lifecycleLock) { generation } BackupCategory.entries .filter { it != BackupCategory.LIGHTNING_CONNECTIONS } .forEach { - scheduleBackup(it) + scheduleBackup(it, requestedGeneration = requestedGeneration) } } diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 1eee30e7dd..c3c6328f85 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -1,22 +1,35 @@ package to.bitkit.repositories import android.content.Context +import androidx.datastore.core.DataStore +import androidx.datastore.core.DataStoreFactory import com.synonym.bitkitcore.ActivityTags import com.synonym.bitkitcore.PreActivityMetadata import com.synonym.paykit.PaykitException import com.synonym.vssclient.VssItem import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.currentTime import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.yield import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonObject import org.junit.Before @@ -56,6 +69,7 @@ import to.bitkit.data.backup.VssBackupClientLdk import to.bitkit.data.dao.TransferDao import to.bitkit.data.entities.TransferEntity import to.bitkit.data.keychain.Keychain +import to.bitkit.data.serializers.AppCacheSerializer import to.bitkit.di.json import to.bitkit.models.ActivityBackupV1 import to.bitkit.models.BackupCategory @@ -70,9 +84,14 @@ import to.bitkit.models.WalletScope import to.bitkit.models.WatchOnlyAccountRecord import to.bitkit.models.WatchOnlyAccountSetupState import to.bitkit.services.LightningService +import to.bitkit.services.PaykitSdkOperationLock import to.bitkit.services.PaykitSdkService +import to.bitkit.services.UsdtService import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError +import java.nio.file.Files +import java.util.concurrent.Executors +import java.util.concurrent.atomic.AtomicInteger import javax.inject.Provider import kotlin.coroutines.cancellation.CancellationException import kotlin.test.assertEquals @@ -82,6 +101,7 @@ import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds import kotlin.time.ExperimentalTime import kotlin.time.Instant @@ -150,7 +170,10 @@ class BackupRepoTest : BaseUnitTest() { } whenever { transferDao.upsert(any>()) }.thenReturn(Unit) whenever { cacheStore.updateBackupStatus(any(), any()) }.thenReturn(Unit) - whenever { cacheStore.update(any()) }.thenReturn(Unit) + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + cacheData.update(transform) + } whenever(cacheStore.data).thenReturn(cacheData) whenever(settingsStore.data).thenReturn(settingsData) whenever { settingsStore.update(any()) }.thenReturn(Unit) @@ -296,14 +319,14 @@ class BackupRepoTest : BaseUnitTest() { val statusWriteStarted = CompletableDeferred() val finishStatusWrite = CompletableDeferred() whenever(cacheStore.backupStatuses).thenReturn(statuses) - whenever(cacheStore.updateBackupStatus(eq(category), any())).doSuspendableAnswer { - val transform = it.getArgument<(BackupItemStatus) -> BackupItemStatus>(1) - val updated = transform(statuses.value.getValue(category)) - if (!updated.running) { + whenever(cacheStore.update(any())).doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + val updated = transform(AppCacheData(backupStatuses = statuses.value)).backupStatuses + if (!updated.getValue(category).running) { statusWriteStarted.complete(Unit) finishStatusWrite.await() } - statuses.update { current -> current + (category to updated) } + statuses.value = updated } val uploadResult = if (uploadSucceeds) { Result.success(VssItem(key = category.name, value = byteArrayOf(), version = 1)) @@ -1265,6 +1288,476 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `reset prevents an interrupted observer setup from initializing the old LDK client`() = test { + val setupStarted = CompletableDeferred() + val allowSetup = CompletableDeferred() + val backupStatuses = MutableStateFlow(emptyMap()) + val allowWalletClear = CompletableDeferred().apply { complete(Unit) } + stubBackupStatuses(backupStatuses, allowWalletClear) {} + stubBackupObservers() + whenever { vssBackupClient.setupWithRetry(any(), any(), any()) }.doSuspendableAnswer { + setupStarted.complete(Unit) + allowSetup.await() + Result.success(Unit) + } + + sut.startObservingBackups() + setupStarted.await() + sut.setWiping(true) + val reset = async { sut.reset() } + runCurrent() + allowSetup.complete(Unit) + reset.await() + runCurrent() + + verify(vssBackupClient).reset() + verify(vssBackupClientLdk).reset() + verify(vssBackupClientLdk, never()).setup() + } + + @Test + fun `consumed settings change survives observation stop`() = test { + assertConsumedSettingsChangeSurvivesStop(reset = false) + } + + @Test + fun `consumed settings change survives reset when wipe does not clear data`() = test { + assertConsumedSettingsChangeSurvivesStop(reset = true) + } + + private suspend fun TestScope.assertConsumedSettingsChangeSurvivesStop(reset: Boolean) { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000, synced = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + sut.startObservingBackups() + runCurrent() + + val entered = CompletableDeferred() + val release = CompletableDeferred() + var holdNextWrite = true + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + if (holdNextWrite) { + holdNextWrite = false + entered.complete(Unit) + release.await() + } + statuses.update { current -> transform(AppCacheData(backupStatuses = current)).backupStatuses } + } + settingsData.update { it.copy(selectedCurrency = "EUR") } + entered.await() + val resetJob = if (reset) async { sut.reset() } else null + if (!reset) sut.stopObservingBackups() + try { + runCurrent() + release.complete(Unit) + resetJob?.await() + runCurrent() + assertTrue(statuses.value.getValue(category).isRequired) + sut.startObservingBackups() + advanceTimeBy(5_000) + runCurrent() + val payload = argumentCaptor() + verify(vssBackupClient).putObject(eq(category.name), payload.capture()) + assertTrue(payload.firstValue.decodeToString().contains("EUR")) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + release.complete(Unit) + resetJob?.join() + sut.reset() + } + } + + @Test + fun `reset drains cancelled setup even after stop and restart`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + val statuses = MutableStateFlow(emptyMap()) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + whenever { vssBackupClient.setupWithRetry(any(), any(), any()) }.doSuspendableAnswer { + entered.complete(Unit) + withContext(NonCancellable) { release.await() } + Result.success(Unit) + } + + sut.startObservingBackups() + entered.await() + sut.stopObservingBackups() + sut.startObservingBackups() + sut.setWiping(true) + val reset = async { sut.reset() } + try { + runCurrent() + assertFalse(reset.isCompleted) + verify(vssBackupClient, never()).reset() + verify(vssBackupClientLdk, never()).reset() + verify(vssBackupClient, times(1)).setupWithRetry(any(), any(), any()) + reset.cancel() + runCurrent() + assertFalse(reset.isCompleted) + } finally { + release.complete(Unit) + reset.join() + } + verify(vssBackupClient).reset() + verify(vssBackupClientLdk).reset() + verify(vssBackupClientLdk, never()).setup() + } + + @Test + fun `restart waits for prior upload cleanup before scheduling replacement`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + var attempts = 0 + whenever { vssBackupClient.putObject(eq(category.name), any()) }.doSuspendableAnswer { + attempts += 1 + if (attempts == 1) { + entered.complete(Unit) + try { + awaitCancellation() + } finally { + withContext(NonCancellable) { release.await() } + } + } + Result.success(VssItem(key = category.name, value = byteArrayOf(), version = 1)) + } + + sut.startObservingBackups() + advanceTimeBy(5_000) + runCurrent() + entered.await() + sut.stopObservingBackups() + sut.startObservingBackups() + try { + runCurrent() + assertTrue(statuses.value.getValue(category).running) + verify(vssBackupClient, times(1)).setupWithRetry(any(), any(), any()) + assertEquals(1, attempts) + release.complete(Unit) + runCurrent() + verify(vssBackupClient, times(2)).setupWithRetry(any(), any(), any()) + advanceTimeBy(5_000) + runCurrent() + assertEquals(2, attempts) + assertFalse(statuses.value.getValue(category).running) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + release.complete(Unit) + sut.reset() + } + } + + @Test + fun `full backup requested during observer cleanup resumes without restart`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + var attempts = 0 + whenever { vssBackupClient.putObject(eq(category.name), any()) }.doSuspendableAnswer { + attempts += 1 + if (attempts == 1) { + entered.complete(Unit) + try { + awaitCancellation() + } finally { + withContext(NonCancellable) { release.await() } + } + } + Result.success(VssItem(key = category.name, value = byteArrayOf(), version = 1)) + } + + sut.startObservingBackups() + advanceTimeBy(5_000) + runCurrent() + entered.await() + sut.stopObservingBackups() + sut.scheduleFullBackup() + try { + runCurrent() + assertTrue(statuses.value.getValue(category).running) + verify(vssBackupClient, times(1)).setupWithRetry(any(), any(), any()) + assertEquals(1, attempts) + release.complete(Unit) + runCurrent() + verify(vssBackupClient, times(1)).setupWithRetry(any(), any(), any()) + advanceTimeBy(5_000) + runCurrent() + assertEquals(2, attempts) + assertFalse(statuses.value.getValue(category).running) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + release.complete(Unit) + sut.reset() + } + } + + @Test + fun `manual finalization cannot recreate status entries after reset`() = test { + val data = MutableStateFlow(AppCacheData()) + val store = mock>() + whenever(store.data).thenReturn(data) + val entered = CompletableDeferred() + val release = CompletableDeferred() + var holdNextWrite = false + whenever { store.updateData(any()) }.doSuspendableAnswer { + val transform = it.getArgument AppCacheData>(0) + if (holdNextWrite) { + holdNextWrite = false + entered.complete(Unit) + withContext(NonCancellable) { release.await() } + } + transform(data.value).also { value -> data.value = value } + } + whenever { vssBackupClient.putObject(eq(BackupCategory.SETTINGS.name), any()) }.doSuspendableAnswer { + holdNextWrite = true + Result.success(VssItem(key = BackupCategory.SETTINGS.name, value = byteArrayOf(), version = 1)) + } + val repo = createSut(backupCache = CacheStore(store)) + val manual = async { repo.triggerBackup(BackupCategory.SETTINGS) } + entered.await() + val reset = async { repo.reset() } + try { + runCurrent() + assertFalse(reset.isCompleted) + } finally { + release.complete(Unit) + reset.await() + } + data.value = AppCacheData() + assertTrue(manual.await().isFailure) + assertTrue(data.value.backupStatuses.isEmpty()) + } + + @Test + fun `reset drains manual upload so failed wipe can resume pending backups`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + var attempts = 0 + whenever { vssBackupClient.putObject(eq(category.name), any()) }.doSuspendableAnswer { + attempts += 1 + if (attempts == 1) { + entered.complete(Unit) + withContext(NonCancellable) { release.await() } + return@doSuspendableAnswer Result.failure(AppError("upload interrupted")) + } + Result.success(VssItem(key = category.name, value = byteArrayOf(), version = 1)) + } + val manual = async { sut.triggerBackup(category) } + entered.await() + val reset = async { sut.reset() } + try { + runCurrent() + assertFalse(reset.isCompleted) + verify(vssBackupClient, never()).reset() + } finally { + release.complete(Unit) + reset.await() + manual.await() + } + try { + sut.startObservingBackups() + advanceTimeBy(5_000) + runCurrent() + assertEquals(2, attempts) + assertFalse(statuses.value.getValue(category).running) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + sut.reset() + } + } + + @Test + fun `USDT callback does not acknowledge reset cancellation and retries the same recovery record`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + val service = UsdtService(keychain, Provider { sut }) + var attempts = 0 + whenever { vssBackupClient.putObject(argThat { startsWith(UsdtRecoveryBackupStore.PREFIX) }, any()) } + .doSuspendableAnswer { + attempts += 1 + if (attempts == 1) { + entered.complete(Unit) + withContext(NonCancellable) { release.await() } + } + Result.success(VssItem(key = "recovery", value = byteArrayOf(), version = 1)) + } + val pending = async { runCatching { service.recoveryBackup.persist("same-signed-operation") } } + entered.await() + val reset = async { sut.reset() } + try { + runCurrent() + assertFalse(reset.isCompleted) + } finally { + release.complete(Unit) + reset.await() + } + assertTrue(pending.await().isFailure) + assertEquals(0L, service.recoveryGeneration) + service.recoveryBackup.persist("same-signed-operation") + assertEquals(1L, service.recoveryGeneration) + val keys = argumentCaptor() + val payloads = argumentCaptor() + verify(vssBackupClient, times(2)).putObject(keys.capture(), payloads.capture()) + assertEquals(keys.firstValue, keys.secondValue) + assertTrue(payloads.firstValue.contentEquals(payloads.secondValue)) + sut.reset() + } + + @Test + fun `explicit backups are rejected throughout wallet wipe`() = test { + sut.setWiping(true) + sut.reset() + assertTrue(sut.triggerBackup(BackupCategory.SETTINGS).isFailure) + assertTrue(sut.persistWalletBackup().isFailure) + assertTrue(sut.persistUsdtRecoveryBackup("signed").isFailure) + sut.scheduleFullBackup() + verify(vssBackupClient, never()).setup(any()) + verify(vssBackupClient, never()).putObject(any(), any()) + verify(cacheStore, never()).update(any()) + sut.setWiping(false) + sut.triggerBackup(BackupCategory.SETTINGS).getOrThrow() + verify(vssBackupClient).putObject(eq(BackupCategory.SETTINGS.name), any()) + } + + @Test + fun `explicit USDT recovery backup works after observers stop`() = test { + stubBackupObservers() + stubBackupStatuses(MutableStateFlow(emptyMap()), CompletableDeferred(Unit)) {} + sut.startObservingBackups() + sut.stopObservingBackups() + whenever(privatePaykitRepo.backupSnapshot()).thenReturn( + Result.failure(PaykitException.SharedStateBusy("shared_state_busy", "lock unavailable")), + ) + sut.persistUsdtRecoveryBackup("same-signed-operation").getOrThrow() + verify(vssBackupClient).putObject(argThat { startsWith(UsdtRecoveryBackupStore.PREFIX) }, any()) + verify(privatePaykitRepo, never()).backupSnapshot() + sut.reset() + } + + @Test + fun `wipe admission drains a backup queued at the real SDK operation barrier`() = test { + val sdkLock = PaykitSdkOperationLock() + val held = CompletableDeferred() + val release = CompletableDeferred() + val exportQueued = CompletableDeferred() + val blocker = async { + sdkLock.withLock { + held.complete(Unit) + release.await() + } + } + held.await() + val statuses = MutableStateFlow(mapOf(BackupCategory.WALLET to BackupItemStatus(required = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + var exported = false + whenever { privatePaykitRepo.backupSnapshot() }.doSuspendableAnswer { + exportQueued.complete(Unit) + sdkLock.withLock(PaykitSdkOperationLock.Priority.Background) { + exported = true + Result.success(PrivatePaykitBackupSnapshot(null, 0)) + } + } + sut.startObservingBackups() + advanceTimeBy(5_000) + runCurrent() + exportQueued.await() + val wipe = async { + sdkLock.withWalletWipe { + sut.setWiping(true) + sut.reset() + } + } + runCurrent() + try { + release.complete(Unit) + withTimeout(5.seconds) { wipe.await() } + blocker.await() + assertFalse(exported) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) + verify(vssBackupClient).reset() + } finally { + release.complete(Unit) + sut.reset() + } + } + + @Test + fun `concurrent lifecycle and scheduling drains with a real cache store`() = test { + stubBackupObservers() + val directory = Files.createTempDirectory("backup-lifecycle-test").toFile() + val dispatcher = Executors.newFixedThreadPool(2).asCoroutineDispatcher() + val dataJob = SupervisorJob() + val store = DataStoreFactory.create( + serializer = AppCacheSerializer, + scope = CoroutineScope(dispatcher + dataJob), + produceFile = { directory.resolve("cache.json") }, + ) + val repo = createSut(backupCache = CacheStore(store), dispatcher = dispatcher) + val setupCalls = AtomicInteger() + whenever { vssBackupClient.setupWithRetry(any(), any(), any()) }.doSuspendableAnswer { + setupCalls.incrementAndGet() + Result.success(Unit) + } + try { + withContext(dispatcher) { + withTimeout(10.seconds) { + val start = CompletableDeferred() + val tasks = listOf( + async { + start.await() + repeat(25) { + repo.startObservingBackups() + repo.scheduleFullBackup() + yield() + } + }, + async { + start.await() + repeat(25) { + repo.stopObservingBackups() + yield() + } + }, + ) + start.complete(Unit) + tasks.awaitAll() + repo.reset() + val beforeRestart = setupCalls.get() + val restarted = CompletableDeferred() + whenever { vssBackupClient.setupWithRetry(any(), any(), any()) }.doSuspendableAnswer { + setupCalls.incrementAndGet() + restarted.complete(Unit) + Result.success(Unit) + } + repeat(25) { repo.startObservingBackups() } + restarted.await() + repo.reset() + assertEquals(beforeRestart + 1, setupCalls.get()) + } + } + } finally { + repo.reset() + dataJob.cancelAndJoin() + dispatcher.close() + directory.deleteRecursively() + } + } + @Test fun `busy wallet backup retries after observation pauses and resumes`() = test { whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(3_000)) @@ -1442,6 +1935,57 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `full backup follows newer required data after observers coalesce`() = test { + whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(3_000)) + val backupStatuses = MutableStateFlow( + mapOf( + BackupCategory.SETTINGS to BackupItemStatus( + synced = 1_000, + required = 2_000, + ), + ) + ) + var uploadAttempts = 0 + whenever { vssBackupClient.putObject(eq(BackupCategory.SETTINGS.name), any()) } + .doSuspendableAnswer { + uploadAttempts += 1 + if (uploadAttempts == 1) { + backupStatuses.update { statuses -> + val status = statuses.getValue(BackupCategory.SETTINGS) + statuses + (BackupCategory.SETTINGS to status.copy(required = 4_000)) + } + whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(5_000)) + Result.success(VssItem(key = BackupCategory.SETTINGS.name, value = byteArrayOf(), version = 1)) + } else { + Result.success( + VssItem( + key = BackupCategory.SETTINGS.name, + value = byteArrayOf(), + version = 1, + ) + ) + } + } + val allowWalletClear = CompletableDeferred().apply { complete(Unit) } + stubBackupStatuses(backupStatuses, allowWalletClear) {} + stubBackupObservers() + + try { + sut.scheduleFullBackup() + sut.startObservingBackups() + runCurrent() + advanceTimeBy(5_000) + runCurrent() + advanceTimeBy(5_000) + runCurrent() + + verify(vssBackupClient, times(2)).putObject(eq(BackupCategory.SETTINGS.name), any()) + } finally { + sut.stopObservingBackups() + } + } + @Test fun `failed automatic backup retries newer required timestamp`() = test { whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(3_000)) @@ -1668,12 +2212,9 @@ class BackupRepoTest : BaseUnitTest() { fun `metadata restore preserves the Blocktank refund address pointer`() = test { val refundAddress = BlocktankRefundAddress(address = "bcrt1qrefund", index = 7) stubMetadataRestore(envelope = metadataEnvelope(cache = AppCacheData(blocktankRefundAddress = refundAddress))) - val cacheTransform = argumentCaptor<(AppCacheData) -> AppCacheData>() - sut.performFullRestoreFromLatestBackup() - verifyBlocking(cacheStore) { update(cacheTransform.capture()) } - assertEquals(refundAddress, cacheTransform.firstValue(AppCacheData()).blocktankRefundAddress) + assertEquals(refundAddress, cacheData.value.blocktankRefundAddress) } @Test @@ -2180,17 +2721,18 @@ class BackupRepoTest : BaseUnitTest() { onWalletClearDelayed: () -> Unit, ) { whenever(cacheStore.backupStatuses).thenReturn(backupStatuses) - whenever { cacheStore.updateBackupStatus(any(), any()) }.doSuspendableAnswer { - val category = it.getArgument(0) - val transform = it.getArgument<(BackupItemStatus) -> BackupItemStatus>(1) - if (category == BackupCategory.WALLET && !allowWalletClear.isCompleted) { - onWalletClearDelayed() - allowWalletClear.await() - } - backupStatuses.update { statuses -> - val currentStatus = statuses[category] ?: BackupItemStatus() - statuses + (category to transform(currentStatus)) + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + if (!allowWalletClear.isCompleted) { + val current = AppCacheData(backupStatuses = backupStatuses.value) + if (transform(current).backupStatuses[BackupCategory.WALLET] != + current.backupStatuses[BackupCategory.WALLET] + ) { + onWalletClearDelayed() + allowWalletClear.await() + } } + backupStatuses.update { statuses -> transform(AppCacheData(backupStatuses = statuses)).backupStatuses } } } @@ -2209,10 +2751,13 @@ class BackupRepoTest : BaseUnitTest() { whenever(lightningService.syncStatusChanged).thenReturn(MutableSharedFlow()) } - private fun createSut() = BackupRepo( + private fun createSut( + backupCache: CacheStore = cacheStore, + dispatcher: CoroutineDispatcher = testDispatcher, + ) = BackupRepo( context = context, - ioDispatcher = testDispatcher, - cacheStore = cacheStore, + ioDispatcher = dispatcher, + cacheStore = backupCache, vssBackupClient = vssBackupClient, vssBackupClientLdk = vssBackupClientLdk, settingsStore = settingsStore, diff --git a/changelog.d/next/1689.fixed.md b/changelog.d/next/1689.fixed.md new file mode 100644 index 0000000000..3af930d512 --- /dev/null +++ b/changelog.d/next/1689.fixed.md @@ -0,0 +1 @@ +Prevent interrupted backup work from leaking across wallet reset or leaving pending backups stuck after observation restarts. diff --git a/journeys/backup-restore/wallet-snapshot-consistency.md b/journeys/backup-restore/wallet-snapshot-consistency.md index 6b58ef5e31..4bc98a0a3c 100644 --- a/journeys/backup-restore/wallet-snapshot-consistency.md +++ b/journeys/backup-restore/wallet-snapshot-consistency.md @@ -25,3 +25,39 @@ funded personal wallet or shorten payment safety waits. 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. Use isolated fixture accounts; +do not reset a funded wallet. + +1. Hold a scheduled backup in its cancellable debounce, stop observation, and + request a manual metadata backup while cancellation cleanup remains held. + Verify a same-category manual upload and observation restart wait for cleanup. + Release cleanup; verify pending wallet work remains required and resumes. +2. Request a new USDT recovery backup during cleanup and again after observation + is stopped. Verify both can finish without restarting Lightning, and transient + backup failures retain bounded retry without repeating the payment. +3. Repeatedly start and immediately stop observation. Change a wallet record only + after the stopped listeners finish; verify no new automatic upload starts. + Restart observation and verify a single set of listeners resumes pending work. +4. Hold setup, upload or final status persistence, then request fixture wallet + reset. Verify both VSS clients remain unchanged until old work finishes, even + if the reset caller is canceled. Once reset returns, simulate failed node stop + and resume observation without clearing the cache; pending work must recover. +5. Keep wallet wipe admission closed after reset returns. Request manual retry, + full backup and USDT persistence; all must avoid new uploads/status changes. + After wipe finishes, new explicit backups work with observation stopped. +6. Change required data during an explicit full backup while observation runs. + Verify the new revision uploads after the first job completes without another + mutation. + +Android stop invalidates observation immediately; reset awaits all retained work, +and restart awaits prior observer cleanup. iOS awaits its asynchronous shutdown +boundary. These platform differences do not make observation a prerequisite for +explicit USDT persistence. Component tests cover controlled cancellation, the real +SDK operation barrier, and concurrent calls with a real DataStore. They do not +establish a complete device fault journey or a deployed Paykit/VSS outage pass. + +For the consumption-to-status interval, begin with synchronized settings, change the currency, and hold the required-status cache write. Stop observation or request a fixture reset that leaves the data intact, then release the write and restart without another edit. The changed settings must upload once and become synchronized. Reset must drain the write before a later cache clear; an acknowledged upload need not repeat. From e585fccf56f0cc914ba33087eb1d1b3f46c74b28 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 04:23:15 +0100 Subject: [PATCH 06/61] fix: retain backup changes while restart drains --- .../java/to/bitkit/repositories/BackupRepo.kt | 10 +- .../to/bitkit/repositories/BackupRepoTest.kt | 102 ++++++++++++++++++ .../wallet-snapshot-consistency.md | 6 +- 3 files changed, 115 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 78ea754524..009228a790 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -4,6 +4,7 @@ import android.content.Context import com.synonym.bitkitcore.UsdtException import com.synonym.vssclient.VssException import dagger.hilt.android.qualifiers.ApplicationContext +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart @@ -168,7 +169,9 @@ class BackupRepo @Inject constructor( private val temporaryFailureSince = ConcurrentHashMap() private var lastNotificationTime = 0L - private class Observation(val scope: CoroutineScope, val generation: Long) + private class Observation(val scope: CoroutineScope, val generation: Long) { + val ready = CompletableDeferred() + } private fun newBackupScope(parent: CoroutineScope) = CoroutineScope(parent.coroutineContext + SupervisorJob(parent.coroutineContext[Job])) @@ -259,8 +262,11 @@ class BackupRepo @Inject constructor( retiringObservations.add(parent) parent.invokeOnCompletion { synchronized(lifecycleLock) { retiringObservations.remove(parent) } } owner.scope.launch(start = CoroutineStart.LAZY) { + // Record new changes during the drain; only uploads and client setup must wait. + startDataStoreListeners(owner) previous.joinAll() currentCoroutineContext().ensureActive() + owner.ready.complete(Unit) startObservation(owner) } } @@ -305,7 +311,6 @@ class BackupRepo @Inject constructor( } startBackupStatusObservers(owner) - startDataStoreListeners(owner) startPeriodicBackupFailureCheck(owner) } @@ -525,6 +530,7 @@ class BackupRepo @Inject constructor( val jobScope = owner?.scope ?: pendingScope jobScope.launch(start = CoroutineStart.LAZY) { try { + owner?.ready?.await() categoryMutexes.getValue(category).withLock { runningBackups += category try { diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index c3c6328f85..5e7aa43071 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -1454,6 +1454,108 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `settings changed during restart cleanup remain pending without another edit`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + val statuses = MutableStateFlow( + mapOf( + BackupCategory.WIDGETS to BackupItemStatus(required = 1_000), + BackupCategory.SETTINGS to BackupItemStatus(required = 1_000, synced = 1_000), + ) + ) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + var widgetAttempts = 0 + whenever { vssBackupClient.putObject(eq(BackupCategory.WIDGETS.name), any()) }.doSuspendableAnswer { + widgetAttempts += 1 + if (widgetAttempts == 1) { + entered.complete(Unit) + try { + awaitCancellation() + } finally { + withContext(NonCancellable) { release.await() } + } + } + Result.success(VssItem(key = BackupCategory.WIDGETS.name, value = byteArrayOf(), version = 1)) + } + sut.startObservingBackups() + advanceTimeBy(5_000) + runCurrent() + entered.await() + sut.stopObservingBackups() + sut.startObservingBackups() + try { + runCurrent() + settingsData.update { it.copy(selectedCurrency = "EUR") } + runCurrent() + verify(vssBackupClient, never()).putObject(eq(BackupCategory.SETTINGS.name), any()) + release.complete(Unit) + runCurrent() + advanceTimeBy(5_000) + runCurrent() + val payload = argumentCaptor() + verify(vssBackupClient).putObject(eq(BackupCategory.SETTINGS.name), payload.capture()) + assertTrue(payload.firstValue.decodeToString().contains("EUR")) + assertFalse(statuses.value.getValue(BackupCategory.SETTINGS).isRequired) + } finally { + release.complete(Unit) + sut.reset() + } + } + + @Test + fun `temporary retry waits for other category cleanup during restart`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + val statuses = MutableStateFlow( + mapOf( + BackupCategory.WIDGETS to BackupItemStatus(required = 1_000), + BackupCategory.WALLET to BackupItemStatus(required = 1_000), + ) + ) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + whenever { privatePaykitRepo.backupSnapshot() } + .thenReturn(Result.failure(PaykitException.SharedStateBusy("shared_state_busy", "locked"))) + .thenReturn(Result.success(PrivatePaykitBackupSnapshot(null, 0))) + var widgetAttempts = 0 + whenever { vssBackupClient.putObject(eq(BackupCategory.WIDGETS.name), any()) }.doSuspendableAnswer { + widgetAttempts += 1 + if (widgetAttempts == 1) { + entered.complete(Unit) + try { + awaitCancellation() + } finally { + withContext(NonCancellable) { release.await() } + } + } + Result.success(VssItem(key = BackupCategory.WIDGETS.name, value = byteArrayOf(), version = 1)) + } + sut.startObservingBackups() + advanceTimeBy(5_000) + runCurrent() + entered.await() + verify(privatePaykitRepo).backupSnapshot() + sut.stopObservingBackups() + sut.startObservingBackups() + try { + advanceTimeBy(20_000) + runCurrent() + verify(privatePaykitRepo, times(1)).backupSnapshot() + verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) + release.complete(Unit) + runCurrent() + advanceTimeBy(5_000) + runCurrent() + verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), any()) + assertFalse(statuses.value.getValue(BackupCategory.WALLET).isRequired) + } finally { + release.complete(Unit) + sut.reset() + } + } + @Test fun `full backup requested during observer cleanup resumes without restart`() = test { val entered = CompletableDeferred() diff --git a/journeys/backup-restore/wallet-snapshot-consistency.md b/journeys/backup-restore/wallet-snapshot-consistency.md index 4bc98a0a3c..4dccf9d071 100644 --- a/journeys/backup-restore/wallet-snapshot-consistency.md +++ b/journeys/backup-restore/wallet-snapshot-consistency.md @@ -35,7 +35,11 @@ do not reset a funded wallet. 1. Hold a scheduled backup in its cancellable debounce, stop observation, and request a manual metadata backup while cancellation cleanup remains held. Verify a same-category manual upload and observation restart wait for cleanup. - Release cleanup; verify pending wallet work remains required and resumes. + Change synchronized settings after requesting restart while cleanup is still + held. Release cleanup; verify those settings and pending wallet work upload + without another edit, and no upload or client setup ran before the drain. + Repeat with a retained temporary-failure retry for another category becoming + due during the wait; that automatic retry must wait too. 2. Request a new USDT recovery backup during cleanup and again after observation is stopped. Verify both can finish without restarting Lightning, and transient backup failures retain bounded retry without repeating the payment. From 618087aa45e70e8a7b7d7298419b3e74bdc325f8 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 05:36:27 +0100 Subject: [PATCH 07/61] fix: stop profile deletion after incomplete cleanup --- .../java/to/bitkit/repositories/PubkyRepo.kt | 24 +++---- .../screens/profile/EditProfileViewModel.kt | 18 +++-- .../to/bitkit/repositories/PubkyRepoTest.kt | 65 ++++++++++++++++++ .../profile/EditProfileViewModelTest.kt | 66 ++++++++++++------- changelog.d/next/profile-cleanup.fixed.md | 1 + journeys/profile/profile-cleanup-failure.xml | 18 +++++ 6 files changed, 149 insertions(+), 43 deletions(-) create mode 100644 changelog.d/next/profile-cleanup.fixed.md create mode 100644 journeys/profile/profile-cleanup-failure.xml diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index e92362b4a5..ae7765e8b1 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -1108,27 +1108,19 @@ class PubkyRepo @Inject constructor( } private suspend fun deleteAllContacts() { - val records = runSuspendCatching { - pubkyService.contactRecords() - }.getOrElse { - if (!it.isMissingPubkyData()) throw it - emptyList() - } - runSuspendCatching { - val removed = pubkyService.removeContacts(records.map { it.publicKey }) - if (removed.size != records.size) { - Logger.warn("Retained contacts that could not be removed during profile deletion", context = TAG) - } - }.onFailure { - Logger.warn("Failed to delete contacts", it, context = TAG) - } - pubkyStore.update { it.copy(contactProfileOverrides = emptyMap()) } + val records = pubkyService.contactRecords() + if (records.isEmpty()) return + val keys = records.map { it.publicKey.ensurePubkyPrefix() }.toSet() + val removedKeys = pubkyService.removeContacts(records.map { it.publicKey }) + .map { it.publicKey.ensurePubkyPrefix() }.toSet().intersect(keys) + pubkyStore.update { it.copy(contactProfileOverrides = it.contactProfileOverrides - removedKeys) } notifyBackupStateChanged() synchronized(contactsLock) { cancelContactScreenLookups() - updateContacts { emptyList() } + updateContacts { current -> current.filterNot { it.publicKey in removedKeys } } } markContactsLoaded() + if (removedKeys != keys) throw PrivatePaykitError.PrivateUnavailable Logger.info("Deleted all contacts", context = TAG) } diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt index 06bb4bd4c5..f72026cafe 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt @@ -243,7 +243,7 @@ class EditProfileViewModel @Inject constructor( privatePaykitRepo.removePublishedEndpointsForCleanup(TAG).getOrThrow() pubkyRepo.signOut().getOrThrow() } - privatePaykitRepo.closeAndClear() + privatePaykitRepo.closeAndClear().getOrThrow() } } if (result.isSuccess) { @@ -272,10 +272,20 @@ class EditProfileViewModel @Inject constructor( } try { privatePaykitRepo.beginProfileDeletion() - privatePaykitRepo.removePublishedEndpointsForCleanup(TAG, deferAppSync = true) - val result = pubkyRepo.deleteProfile() + val result = runSuspendCatching { + privatePaykitRepo.removePublishedEndpointsForCleanup(TAG, deferAppSync = true).getOrThrow() + pubkyRepo.deleteProfile().getOrThrow() + } if (result.isSuccess) { - privatePaykitRepo.closeAndClear() + privatePaykitRepo.closeAndClear().onFailure { + Logger.error("Failed to clear local state after profile deletion", it, context = TAG) + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.common__error), + description = it.message, + ) + return + } ToastEventBus.send( type = Toast.ToastType.SUCCESS, title = context.getString(_uiState.value.removal.successToast), diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 28ad1a79a0..412fcb5dac 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -1356,6 +1356,71 @@ class PubkyRepoTest : BaseUnitTest() { verify(pubkyService, never()).removeContact(any()) } + @Test + fun `partial contact cleanup preserves retained contacts and stops profile deletion`() = test { + authenticateForTesting() + val records = listOf( + createContactRecord(VALID_CONTACT_KEY_A, label = "Removed"), + createContactRecord(VALID_CONTACT_KEY_B, label = "Retained"), + ) + val overrides = records.associate { + it.publicKey to PubkyProfile.placeholder(it.publicKey).toProfileData() + } + var stored = PubkyStoreData(contactProfileOverrides = overrides) + whenever(pubkyStore.data).thenReturn(flowOf(stored)) + whenever(pubkyStore.update(any())).thenAnswer { + stored = it.getArgument<(PubkyStoreData) -> PubkyStoreData>(0)(stored) + Unit + } + whenever(pubkyService.contactRecords()).thenReturn(records) + whenever(pubkyService.removeContacts(records.map { it.publicKey })).thenReturn(listOf(records.first())) + sut.loadContacts() + + val result = sut.deleteProfile() + + assertTrue(result.isFailure) + assertEquals(listOf(VALID_CONTACT_KEY_B), sut.contacts.value.map { it.publicKey }) + assertEquals(setOf(VALID_CONTACT_KEY_B), stored.contactProfileOverrides.keys) + verify(pubkyService, never()).deletePaykitProfile() + verify(pubkyService, never()).signOut() + } + + @Test + fun `unavailable contact read does not authorize profile deletion`() = test { + authenticateForTesting() + val error = TestAppError("Fetch failed: 404 missing session") + whenever(pubkyService.contactRecords()).thenAnswer { throw error } + clearInvocations(pubkyStore) + + val result = sut.deleteProfile() + + assertSame(error, result.exceptionOrNull()) + verify(pubkyStore, never()).update(any()) + verify(pubkyService, never()).removeContacts(any()) + verify(pubkyService, never()).deletePaykitProfile() + verify(pubkyService, never()).signOut() + } + + @Test + fun `uncertain contact cleanup preserves local evidence and stops profile deletion`() = test { + authenticateForTesting() + val record = createContactRecord(VALID_CONTACT_KEY_A, label = "Retained") + val records = listOf(record) + val error = TestAppError("Contact removal acknowledgement lost") + whenever(pubkyService.contactRecords()).thenReturn(records) + whenever(pubkyService.removeContacts(listOf(record.publicKey))).thenAnswer { throw error } + sut.loadContacts() + clearInvocations(pubkyStore) + + val result = sut.deleteProfile() + + assertSame(error, result.exceptionOrNull()) + assertEquals(listOf(VALID_CONTACT_KEY_A), sut.contacts.value.map { it.publicKey }) + verify(pubkyStore, never()).update(any()) + verify(pubkyService, never()).deletePaykitProfile() + verify(pubkyService, never()).signOut() + } + @Test fun `deleteProfile should fail when signOut fails`() = test { authenticateForTesting() diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt index 381c03e5e4..30f48762ae 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt @@ -181,6 +181,49 @@ class EditProfileViewModelTest : BaseUnitTest() { assertEquals("https://updated.example.com", sut.uiState.value.links.first().url) } + @Test + fun `failed private cleanup stops deletion and preserves pending state`() = test { + val sut = createSut() + advanceUntilIdle() + whenever(privatePaykitRepo.removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true))) + .thenReturn(Result.failure(TestAppError("Withdrawal pending"))) + whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) + + sut.effects.test { + sut.deleteProfile() + advanceUntilIdle() + expectNoEvents() + } + + assertTrue(sut.uiState.value.showDeleteFailureDialog) + assertFalse(sut.uiState.value.isDeleting) + verify(pubkyRepo, never()).deleteProfile() + verify(privatePaykitRepo, never()).closeAndClear() + verify(privatePaykitRepo).endProfileDeletion() + } + + @Test + fun `failed local finalization does not report deletion success`() = test { + val sut = createSut() + advanceUntilIdle() + whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) + whenever( + privatePaykitRepo.closeAndClear() + ).thenReturn(Result.failure(TestAppError("Local storage unavailable"))) + + sut.effects.test { + sut.deleteProfile() + advanceUntilIdle() + expectNoEvents() + } + + assertFalse(sut.uiState.value.showDeleteFailureDialog) + assertFalse(sut.uiState.value.isDeleting) + verify(pubkyRepo).deleteProfile() + verify(privatePaykitRepo).closeAndClear() + verify(privatePaykitRepo).endProfileDeletion() + } + @Test fun `deleteProfile should emit success when repository delete succeeds`() = test { whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) @@ -349,29 +392,6 @@ class EditProfileViewModelTest : BaseUnitTest() { verify(privatePaykitRepo, never()).closeAndClear() } - @Test - fun `deleteProfile should continue when private cleanup fails`() = test { - val sut = createSut() - whenever { privatePaykitRepo.removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) } - .thenReturn(Result.failure(TestAppError("cleanup failed"))) - whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) - advanceUntilIdle() - - sut.effects.test { - sut.deleteProfile() - advanceUntilIdle() - - assertEquals(EditProfileEffect.DeleteSuccess, awaitItem()) - } - assertFalse(sut.uiState.value.showDeleteFailureDialog) - assertFalse(sut.uiState.value.isDeleting) - inOrder(privatePaykitRepo, pubkyRepo).apply { - verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) - verify(pubkyRepo).deleteProfile() - verify(privatePaykitRepo).closeAndClear() - } - } - @Test fun `dismissDeleteFailureDialog should hide retry dialog`() = test { whenever(pubkyRepo.deleteProfile()).thenReturn( 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 479c53065167ed85b99393f79d1b0b83827ca134 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 05:37:07 +0100 Subject: [PATCH 08/61] chore: rename changelog fragment --- changelog.d/next/{profile-cleanup.fixed.md => 1690.fixed.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changelog.d/next/{profile-cleanup.fixed.md => 1690.fixed.md} (100%) diff --git a/changelog.d/next/profile-cleanup.fixed.md b/changelog.d/next/1690.fixed.md similarity index 100% rename from changelog.d/next/profile-cleanup.fixed.md rename to changelog.d/next/1690.fixed.md From 2daec90e2651f6ed94a72fe5b5ccd5847cb5aa4b Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 06:33:07 +0100 Subject: [PATCH 09/61] fix: preserve sessions after uncertain profile deletion --- .../java/to/bitkit/repositories/PubkyRepo.kt | 25 +------------------ .../to/bitkit/repositories/PubkyRepoTest.kt | 19 ++++++++++++++ changelog.d/next/1690.fixed.md | 2 +- journeys/profile/profile-cleanup-failure.xml | 2 ++ 4 files changed, 23 insertions(+), 25 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index ae7765e8b1..0ddfd7e599 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -1093,14 +1093,7 @@ class PubkyRepo @Inject constructor( } clearSessionContactProfiles() deleteAllContacts() - runSuspendCatching { - pubkyService.deletePaykitProfile() - }.getOrElse { - if (!it.isMissingPubkyData()) { - throw it - } - Logger.info("Continuing sign out, bitkit profile storage already missing", context = TAG) - } + pubkyService.deletePaykitProfile() profileWriteGeneration.incrementAndGet() } settingsStore.update { it.paykitDisabled(markPublicCleanupPending = it.hasPaykitState()) } @@ -2254,21 +2247,5 @@ class PubkyRepo @Inject constructor( private fun redacted(publicKey: String): String = PubkyPublicKeyFormat.redacted(publicKey) - private fun Throwable.isMissingPubkyData(): Boolean { - val fullMessage = buildErrorMessage() - return fullMessage.contains("404") || - fullMessage.contains("not found", ignoreCase = true) || - fullMessage.contains("missing", ignoreCase = true) - } - - private fun Throwable.buildErrorMessage(): String = - buildString { - append(message.orEmpty()) - cause?.message?.takeIf { it.isNotBlank() }?.let { - append(" ") - append(it) - } - } - // endregion } diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 412fcb5dac..a4d18e2836 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -1421,6 +1421,25 @@ class PubkyRepoTest : BaseUnitTest() { verify(pubkyService, never()).signOut() } + @Test + fun `profile deletion errors mentioning missing data do not authorize sign out`() = test { + authenticateForTesting() + settingsFlow.value = SettingsData( + sharesPublicPaykitEndpoints = true, + sharesPrivatePaykitEndpoints = true, + ) + val error = TestAppError("Delete failed: HTTP 404 Not Found at session endpoint") + whenever(pubkyService.deletePaykitProfile()).thenAnswer { throw error } + + val result = sut.deleteProfile() + + assertSame(error, result.exceptionOrNull()) + assertTrue(sut.isAuthenticated.value) + assertTrue(settingsFlow.value.sharesPublicPaykitEndpoints) + assertTrue(settingsFlow.value.sharesPrivatePaykitEndpoints) + verify(pubkyService, never()).signOut() + } + @Test fun `deleteProfile should fail when signOut fails`() = test { authenticateForTesting() diff --git a/changelog.d/next/1690.fixed.md b/changelog.d/next/1690.fixed.md index e4eaf87e34..f05f0a6f84 100644 --- a/changelog.d/next/1690.fixed.md +++ b/changelog.d/next/1690.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 edd647611a1bd695f12a6f7eff69acdd19f03019 Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 26 Oct 2026 08:36:08 +0200 Subject: [PATCH 10/61] fix: bind profile removal to its original owner --- .../profile/ProfileRecoveryContentTest.kt | 126 +++++ .../to/bitkit/data/ProfileRemovalStore.kt | 200 ++++++++ .../java/to/bitkit/repositories/BackupRepo.kt | 21 +- .../ContactPaymentSettingsRepo.kt | 53 +- .../PrivatePaykitContactResolver.kt | 33 +- .../bitkit/repositories/PrivatePaykitRepo.kt | 151 ++++-- .../repositories/PubkyIdentityOperations.kt | 126 +++++ .../java/to/bitkit/repositories/PubkyRepo.kt | 323 +++++++++--- .../java/to/bitkit/services/CoreService.kt | 15 +- .../bitkit/services/PaykitSdkOperationLock.kt | 156 +++++- .../to/bitkit/services/PaykitSdkService.kt | 235 +++++++-- .../java/to/bitkit/services/PubkyService.kt | 30 ++ .../ui/screens/profile/EditProfileScreen.kt | 46 +- .../screens/profile/EditProfileViewModel.kt | 176 ++++--- .../ui/screens/profile/ProfileScreen.kt | 32 +- .../ui/screens/profile/ProfileViewModel.kt | 152 ++++-- .../usecases/ProfileRemovalCoordinator.kt | 169 +++++++ .../to/bitkit/usecases/WipeWalletUseCase.kt | 50 +- .../java/to/bitkit/viewmodels/AppViewModel.kt | 45 +- app/src/main/res/values-ar/strings.xml | 4 + app/src/main/res/values-b+es+419/strings.xml | 4 + app/src/main/res/values-ca/strings.xml | 4 + app/src/main/res/values-cs/strings.xml | 4 + app/src/main/res/values-de/strings.xml | 4 + app/src/main/res/values-el/strings.xml | 4 + app/src/main/res/values-es-rES/strings.xml | 4 + app/src/main/res/values-es/strings.xml | 4 + app/src/main/res/values-fr/strings.xml | 4 + app/src/main/res/values-it/strings.xml | 4 + app/src/main/res/values-nl/strings.xml | 4 + app/src/main/res/values-pl/strings.xml | 4 + app/src/main/res/values-pt-rBR/strings.xml | 4 + app/src/main/res/values-pt/strings.xml | 4 + app/src/main/res/values-ru/strings.xml | 4 + app/src/main/res/values/strings.xml | 4 + .../to/bitkit/data/ProfileRemovalStoreTest.kt | 203 ++++++++ .../to/bitkit/repositories/BackupRepoTest.kt | 46 ++ .../ContactPaymentSettingsRepoTest.kt | 89 ++++ .../PrivatePaykitAllowancePaymentTest.kt | 3 + .../PrivatePaykitContactResolverTest.kt | 72 +++ .../repositories/PrivatePaykitRepoTest.kt | 211 +++++++- .../PubkyIdentityOperationsTest.kt | 142 ++++++ .../to/bitkit/repositories/PubkyRepoTest.kt | 469 +++++++++++++++-- .../ActivityServicePaykitContactsTest.kt | 27 + .../services/PaykitSdkOperationLockTest.kt | 181 +++++++ .../bitkit/services/PaykitSdkServiceTest.kt | 443 ++++++++++++++++ .../contacts/ContactSaveSessionChangeTest.kt | 29 ++ .../profile/EditProfileViewModelTest.kt | 478 ++++++++---------- .../profile/ProfileRemovalUiFixture.kt | 60 +++ .../screens/profile/ProfileViewModelTest.kt | 306 +++++++---- .../usecases/ProfileRemovalCoordinatorTest.kt | 416 +++++++++++++++ .../bitkit/usecases/WipeWalletUseCaseTest.kt | 302 +++++++++-- .../viewmodels/AppViewModelSendFlowTest.kt | 72 ++- changelog.d/next/1687.fixed.md | 1 + journeys/profile/README.md | 36 +- .../delete-profile-uncertain-response.xml | 2 +- journeys/profile/delete-profile.xml | 3 +- journeys/profile/profile-cleanup-failure.xml | 7 +- journeys/profile/profile-removal-recovery.xml | 25 + 59 files changed, 5005 insertions(+), 821 deletions(-) create mode 100644 app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt create mode 100644 app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt create mode 100644 app/src/main/java/to/bitkit/repositories/PubkyIdentityOperations.kt create mode 100644 app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt create mode 100644 app/src/test/java/to/bitkit/data/ProfileRemovalStoreTest.kt create mode 100644 app/src/test/java/to/bitkit/repositories/PubkyIdentityOperationsTest.kt create mode 100644 app/src/test/java/to/bitkit/ui/screens/profile/ProfileRemovalUiFixture.kt create mode 100644 app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt create mode 100644 changelog.d/next/1687.fixed.md create mode 100644 journeys/profile/profile-removal-recovery.xml diff --git a/app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt b/app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt new file mode 100644 index 0000000000..7c67be5946 --- /dev/null +++ b/app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt @@ -0,0 +1,126 @@ +package to.bitkit.ui.screens.profile + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.platform.LocalInspectionMode +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Rule +import org.junit.Test +import to.bitkit.R +import to.bitkit.test.annotations.ComposeUi +import to.bitkit.ui.theme.AppThemeSurface +import kotlin.test.assertEquals + +@ComposeUi +class ProfileRecoveryContentTest { + @get:Rule + val compose = createComposeRule() + + private val context get() = InstrumentationRegistry.getInstrumentation().targetContext + + @Test + fun restartRecoveryWithoutCredentialsRequiresLocalConfirmation() { + var state by mutableStateOf(ProfileUiState(recoveryPending = true, localDisconnect = true)) + var confirmations = 0 + compose.setContent { + AppThemeSurface { + CompositionLocalProvider(LocalInspectionMode provides true) { + ProfileContent( + uiState = state, + onBackClick = {}, + onClickEdit = { error("Pending recovery must not offer editing") }, + onClickCopy = {}, + onClickShare = {}, + onClickSignOut = { state = state.copy(showSignOutDialog = true) }, + onDismissSignOutDialog = { state = state.copy(showSignOutDialog = false) }, + onConfirmSignOut = { + confirmations++ + state = state.copy(showSignOutDialog = false, isSigningOut = true) + }, + onClickRetry = { error("Pending recovery must not restore credentials") }, + onClickAddTag = {}, + onRemoveTag = {}, + onDismissAddTagSheet = {}, + onSaveTag = {}, + onDismissCopiedPopup = {}, + ) + } + } + } + compose.onNodeWithText(context.getString(R.string.profile__cleanup_pending)).assertIsDisplayed() + compose.onNodeWithTag("ProfileRecoveryDisconnect").assertIsDisplayed().performClick() + compose.onNodeWithText(context.getString(R.string.profile__disconnect_local_description)).assertIsDisplayed() + compose.runOnIdle { assertEquals(0, confirmations) } + compose.onNodeWithTag("DialogCancel").performClick() + val dismissedAt = System.currentTimeMillis() + compose.runOnIdle { assertEquals(0, confirmations) } + compose.waitUntil(1_000) { System.currentTimeMillis() - dismissedAt > 600 } + compose.onNodeWithTag("ProfileRecoveryDisconnect").performClick() + compose.onNodeWithTag("DialogConfirm").performClick() + compose.runOnIdle { assertEquals(1, confirmations) } + compose.onNodeWithTag("ProfileRecoveryDisconnect").assertIsNotEnabled() + } + + @Test + fun uncertainDeletionOffersReviewThenSeparateConfirmation() { + var state by mutableStateOf(EditProfileUiState(showDeleteFailureDialog = true, canReviewRemoval = true)) + var reviews = 0 + var deletes = 0 + editContent({ state }, onReview = { + reviews++ + state = state.copy(showDeleteFailureDialog = false, showDeleteDialog = true) + }, onConfirm = { deletes++ }) + compose.onNodeWithText(context.getString(R.string.profile__review_removal)).assertIsDisplayed() + compose.onNodeWithTag("DialogConfirm").performClick() + compose.runOnIdle { + assertEquals(1, reviews) + assertEquals(0, deletes) + } + compose.onNodeWithTag("DialogConfirm").performClick() + compose.runOnIdle { assertEquals(1, deletes) } + } + + @Test + fun localCompletionFailureOnlyOffersDisconnectAndClose() { + var disconnects = 0 + editContent( + state = { EditProfileUiState(showDeleteFailureDialog = true, canReviewRemoval = false) }, + onReview = { error("Local completion cannot repeat remote deletion") }, + onDisconnect = { disconnects++ }, + ) + compose.onNodeWithText(context.getString(R.string.profile__review_removal)).assertDoesNotExist() + compose.onNodeWithText(context.getString(R.string.common__close)).assertIsDisplayed() + compose.onNodeWithTag("DialogConfirm").performClick() + compose.runOnIdle { assertEquals(1, disconnects) } + } + + private fun editContent( + state: () -> EditProfileUiState, + onReview: () -> Unit, + onDisconnect: () -> Unit = {}, + onConfirm: () -> Unit = {}, + ) { + compose.setContent { + AppThemeSurface { + CompositionLocalProvider(LocalInspectionMode provides true) { + EditProfileContent( + uiState = state(), + onBackClick = {}, onNameChange = {}, onBioChange = {}, onLinkUrlChange = { _, _ -> }, + onAvatarSelected = {}, onAddLink = {}, onRemoveLink = {}, onAddTag = {}, onRemoveTag = {}, + onSave = {}, onDelete = {}, onDismissDeleteDialog = {}, onConfirmDelete = onConfirm, + onRetryDelete = onReview, onDismissDeleteFailureDialog = {}, onDisconnectProfile = onDisconnect, + onDismissAddLinkSheet = {}, onSaveLink = { _, _ -> }, onDismissAddTagSheet = {}, onSaveTag = {}, + ) + } + } + } + } +} diff --git a/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt b/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt new file mode 100644 index 0000000000..b0cc7033a7 --- /dev/null +++ b/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt @@ -0,0 +1,200 @@ +package to.bitkit.data + +import android.content.Context +import androidx.datastore.core.CorruptionException +import androidx.datastore.core.DataStore +import androidx.datastore.core.Serializer +import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler +import androidx.datastore.dataStore +import dagger.hilt.android.qualifiers.ApplicationContext +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.catch +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.retryWhen +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.decodeFromJsonElement +import kotlinx.serialization.json.intOrNull +import to.bitkit.di.json +import to.bitkit.utils.AppError +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.nio.charset.CharacterCodingException +import java.util.UUID +import java.util.concurrent.atomic.AtomicBoolean +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.coroutines.AbstractCoroutineContextElement +import kotlin.coroutines.CoroutineContext +import kotlin.time.Duration.Companion.milliseconds + +private val Context.profileRemovalDataStore: DataStore by dataStore( + fileName = "profile_removal.json", + serializer = ProfileRemovalSerializer, + corruptionHandler = profileRemovalCorruptionHandler(), +) + +/** Local recovery admission only. A pending attempt is never evidence that a remote mutation succeeded. */ +@Singleton +class ProfileRemovalStore internal constructor(private val store: DataStore) { + internal companion object { + /** Used only by the existing service's injected-handle unit-test constructor. */ + fun inMemoryForTesting() = ProfileRemovalStore(object : DataStore { + private val state = MutableStateFlow(ProfileRemovalState()) + private val mutex = Mutex() + override val data: Flow = state + override suspend fun updateData(transform: suspend (ProfileRemovalState) -> ProfileRemovalState) = + mutex.withLock { transform(state.value).also { state.value = it } } + }) + } + + @Inject + constructor(@ApplicationContext context: Context) : this(context.profileRemovalDataStore) + + private val observationRevision = MutableStateFlow(0L) + internal val generation: Long get() = observationRevision.value + + @OptIn(ExperimentalCoroutinesApi::class) + internal val pending: Flow = observationRevision.flatMapLatest { + store.data.map { it.attemptId != null } + .retryWhen { _, attempt -> + emit(true) + if (attempt < 3) { + delay((250L shl attempt.toInt()).milliseconds) + true + } else { + false + } + } + .catch { emit(true) } + } + + internal suspend fun pendingAttempt(): String? = store.data.first().attemptId + + internal suspend fun requireNoPending() { + if (pendingAttempt() != null) throw ProfileRemovalPending() + } + + internal suspend fun requireAccess() { + val pending = pendingAttempt() ?: return + val access = currentCoroutineContext()[Access] + if (access?.store !== this || access.attemptId != pending || !access.active.get()) { + throw ProfileRemovalPending() + } + access.job.ensureActive() + } + + /** Only for local completion after acknowledged credential teardown, while outer removal ownership is retained. */ + internal suspend fun requireCompletionAccess() { + val pending = pendingAttempt() ?: return + val access = currentCoroutineContext()[Access] + if (access?.store !== this || access.attemptId != pending || !access.active.get()) { + throw ProfileRemovalPending() + } + } + + internal suspend fun withAccess(attemptId: String, operation: suspend () -> T): T { + require(UUID.fromString(attemptId).toString() == attemptId) { "Invalid profile removal attempt" } + val pending = pendingAttempt() + check(pending == null || pending == attemptId) { "Another profile removal needs local recovery" } + val access = Access(this, attemptId, requireNotNull(currentCoroutineContext()[Job])) + try { + return withContext(access) { operation() } + } finally { + access.active.set(false) + } + } + + internal suspend fun begin(attemptId: String) { + val access = currentCoroutineContext()[Access] + check(access?.store === this && access.attemptId == attemptId && access.active.get()) { + "Profile removal admission is required" + } + access.job.ensureActive() + store.updateData { + check(it.attemptId == null || it.attemptId == attemptId) { "Profile removal attempt changed" } + it.copy(attemptId = attemptId) + } + observationRevision.update { it + 1 } + } + + /** Caller must retain removal ownership until all acknowledged teardown's local persistence has completed. */ + internal suspend fun complete(attemptId: String) { + val access = currentCoroutineContext()[Access] + check(access?.store === this && access.attemptId == attemptId && access.active.get()) { + "Profile removal admission is required" + } + store.updateData { + check(it.attemptId == attemptId) { "Profile removal attempt changed" } + ProfileRemovalState() + } + observationRevision.update { it + 1 } + } + + private class Access( + val store: ProfileRemovalStore, + val attemptId: String, + val job: Job, + ) : AbstractCoroutineContextElement(Key) { + companion object Key : CoroutineContext.Key + val active = AtomicBoolean(true) + } +} + +@Serializable +internal data class ProfileRemovalState(val version: Int = 1, val attemptId: String? = null) + +/** Malformed local admission data is replaced only with a new, still-blocking recovery obligation. */ +internal fun profileRemovalCorruptionHandler() = ReplaceFileCorruptionHandler { + ProfileRemovalState(attemptId = UUID.randomUUID().toString()) +} + +internal class UnsupportedProfileRemovalFormat : IOException("Update Bitkit to recover this profile cleanup state") + +internal object ProfileRemovalSerializer : Serializer { + override val defaultValue = ProfileRemovalState() + + override suspend fun readFrom(input: InputStream): ProfileRemovalState { + val bytes = input.readBytes() + return try { + val envelope = json.parseToJsonElement(bytes.decodeToString(throwOnInvalidSequence = true)) as? JsonObject + ?: throw CorruptionException("Profile recovery state is not an object") + envelope["version"]?.let { version -> + if (version !is JsonPrimitive || version.isString || version.intOrNull != 1) { + throw UnsupportedProfileRemovalFormat() + } + } + json.decodeFromJsonElement(envelope).also { + require(it.attemptId == null || UUID.fromString(it.attemptId).toString() == it.attemptId) { + "Invalid profile removal attempt" + } + } + } catch (error: CharacterCodingException) { + throw CorruptionException("Profile recovery state has invalid text encoding", error) + } catch (error: IllegalArgumentException) { + throw CorruptionException("Profile recovery state could not be read", error) + } + } + + override suspend fun writeTo(t: ProfileRemovalState, output: OutputStream) { + output.write(json.encodeToString(t).encodeToByteArray()) + } +} + +internal class ProfileRemovalPending : AppError( + "Profile cleanup is pending. Disconnect the profile to finish local recovery." +) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index f9ea2491d3..c3471463fd 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -2,6 +2,7 @@ package to.bitkit.repositories import android.content.Context import com.synonym.bitkitcore.UsdtException +import com.synonym.paykit.PaykitException import com.synonym.vssclient.VssException import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CoroutineDispatcher @@ -1275,11 +1276,15 @@ private data class RestoredCoreBackup( val needsRewrite: Boolean, ) -internal fun Throwable.isTemporaryBackupFailure(): Boolean = isPaykitTemporarilyUnavailable() || when (this) { - is VssException.ConnectionException, - is VssException.NetworkException, - is VssException.StoreException, - is VssException.PutException, - -> true - else -> false -} +internal fun Throwable.isTemporaryBackupFailure(): Boolean = isPaykitTemporarilyUnavailable() || + // Only backup capture may retry this admission rejection; profile mutations must reconcile separately. + generateSequence(this) { it.cause }.any { + it is PaykitException.Storage && it.code == "profile_removal_in_progress" + } || when (this) { + is VssException.ConnectionException, + is VssException.NetworkException, + is VssException.StoreException, + is VssException.PutException, + -> true + else -> false + } diff --git a/app/src/main/java/to/bitkit/repositories/ContactPaymentSettingsRepo.kt b/app/src/main/java/to/bitkit/repositories/ContactPaymentSettingsRepo.kt index 1145ebfad9..9b76c49eb0 100644 --- a/app/src/main/java/to/bitkit/repositories/ContactPaymentSettingsRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/ContactPaymentSettingsRepo.kt @@ -15,6 +15,8 @@ import to.bitkit.data.paykitDisabled import to.bitkit.di.IoDispatcher import to.bitkit.ext.runSuspendCatching import to.bitkit.services.PaykitSdkOperationLock.Priority +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicLong import javax.inject.Inject import javax.inject.Singleton @@ -27,27 +29,70 @@ class ContactPaymentSettingsRepo @Inject constructor( @IoDispatcher private val ioDispatcher: CoroutineDispatcher, ) { private val sharingMutex = Mutex() + private val removalPending = AtomicBoolean(false) + private val wipePending = AtomicBoolean(false) + private val sharingEpoch = AtomicLong(0) + + internal suspend fun withProfileRemoval(operation: suspend () -> T): T { + check(!wipePending.get()) { "Wallet wipe is in progress" } + val epoch = sharingEpoch.get() + check(removalPending.compareAndSet(false, true)) { "Profile removal is already in progress" } + sharingEpoch.incrementAndGet() + try { + return sharingMutex.withLock { + check(!wipePending.get() && sharingEpoch.get() == epoch + 1) { "Profile sharing state changed" } + operation() + } + } finally { + removalPending.set(false) + } + } + + /** Close sharing admission first, revoke repository removal, then drain sharing before taking the SDK barrier. */ + internal suspend fun withWalletWipe( + admitRepository: suspend (suspend () -> T) -> T, + operation: suspend () -> T, + ): T { + check(wipePending.compareAndSet(false, true)) { "Wallet wipe is already in progress" } + sharingEpoch.incrementAndGet() + try { + return admitRepository { sharingMutex.withLock { operation() } } + } finally { + wipePending.set(false) + } + } + + private suspend fun changeSharing(operation: suspend () -> Result): Result = runSuspendCatching { + val epoch = sharingEpoch.get() + check(!removalPending.get() && !wipePending.get()) { "Profile removal is in progress" } + sharingMutex.withLock { + check( + !removalPending.get() && !wipePending.get() && epoch == sharingEpoch.get() + ) { "Profile sharing state changed" } + operation().getOrThrow() + } + } val isEnabled: Flow = settingsStore.data.map { it.areContactPaymentsEnabled() } suspend fun setEnabled(isEnabled: Boolean): Result = withContext(ioDispatcher) { - sharingMutex.withLock { + changeSharing { val contacts = pubkyRepo.contacts.value.map { it.publicKey } if (isEnabled) enable(contacts) else disable(contacts) } } suspend fun reconcilePendingEndpoints(reconcile: suspend () -> Unit) = withContext(ioDispatcher) { - if (!sharingMutex.tryLock()) return@withContext + if (removalPending.get() || wipePending.get() || !sharingMutex.tryLock()) return@withContext try { - reconcile() + if (!removalPending.get() && !wipePending.get()) reconcile() } finally { sharingMutex.unlock() } } suspend fun disablePaykit(): Result = withContext(ioDispatcher) { - sharingMutex.withLock { + changeSharing { runSuspendCatching { val previous = settingsStore.data.first() val hadPublicState = previous.hasPublicPaykitPublicationState() diff --git a/app/src/main/java/to/bitkit/repositories/PrivatePaykitContactResolver.kt b/app/src/main/java/to/bitkit/repositories/PrivatePaykitContactResolver.kt index 47c01cdf88..70aa242485 100644 --- a/app/src/main/java/to/bitkit/repositories/PrivatePaykitContactResolver.kt +++ b/app/src/main/java/to/bitkit/repositories/PrivatePaykitContactResolver.kt @@ -4,7 +4,9 @@ import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.first import kotlinx.coroutines.withContext import to.bitkit.data.PrivatePaykitCacheStore +import to.bitkit.data.ProfileRemovalStore import to.bitkit.di.IoDispatcher +import to.bitkit.ext.runSuspendCatching import to.bitkit.models.PubkyPublicKeyFormat import javax.inject.Inject import javax.inject.Provider @@ -16,7 +18,21 @@ class PrivatePaykitContactResolver @Inject constructor( private val cacheStore: PrivatePaykitCacheStore, private val addressReservationRepo: Provider, private val paymentRequestRepo: Provider, + private val profileRemovalStore: ProfileRemovalStore, ) { + internal val recoveryGeneration: Long get() = profileRemovalStore.generation + + private suspend fun isRecoveryCurrent(generation: Long): Boolean = + hasProfileAccess() && generation == recoveryGeneration + + internal suspend fun hasProfileAccess(): Boolean = + runSuspendCatching { profileRemovalStore.requireNoPending() }.isSuccess + + /** Wallet address accounting is independent of whether its old profile may be attributed. */ + internal suspend fun isReservedReceiveAddress(address: String): Boolean = withContext(ioDispatcher) { + addressReservationRepo.get().contactPublicKeyForReservedAddress(address) != null + } + internal val receivedPaymentContacts: PaykitReceivedPaymentContacts get() = paymentRequestRepo.get().receivedPaymentContacts @@ -28,7 +44,8 @@ class PrivatePaykitContactResolver @Inject constructor( suspend fun contactPublicKeyForPrivateInvoicePaymentHash(paymentHash: String): String? = withContext(ioDispatcher) { - if (paymentHash.isBlank()) return@withContext null + val generation = recoveryGeneration + if (paymentHash.isBlank() || !hasProfileAccess()) return@withContext null val shared = receivedPaymentContacts val contacts = cacheStore.data.first().contacts.mapNotNull { (publicKey, contactState) -> publicKey.takeIf { @@ -36,13 +53,16 @@ class PrivatePaykitContactResolver @Inject constructor( paymentHash in contactState.receivedInvoicePaymentHashes } } - if (receivedPaymentContacts !== shared) return@withContext null + if (receivedPaymentContacts !== shared || !isRecoveryCurrent(generation)) return@withContext null (contacts + shared.contactsForPaymentHash(paymentHash)) .mapNotNull(PubkyPublicKeyFormat::normalized).distinct().singleOrNull() } suspend fun contactPublicKeyForReservedAddress(address: String): String? = withContext(ioDispatcher) { - addressReservationRepo.get().contactPublicKeyForReservedAddress(address) + val generation = recoveryGeneration + if (!hasProfileAccess()) return@withContext null + val contact = addressReservationRepo.get().contactPublicKeyForReservedAddress(address) + contact.takeIf { isRecoveryCurrent(generation) } } suspend fun contactPublicKeyForPrivateOnchainAddresses( @@ -50,7 +70,10 @@ class PrivatePaykitContactResolver @Inject constructor( addresses: Collection, ): String? = withContext(ioDispatcher) { - if (receivingAddress.isNullOrBlank() || receivingAddress !in addresses) return@withContext null + val generation = recoveryGeneration + if (receivingAddress.isNullOrBlank() || receivingAddress !in addresses || !hasProfileAccess()) { + return@withContext null + } val shared = receivedPaymentContacts val reservedContacts = addresses.distinct().associateWith { contactPublicKeyForReservedAddress(it) @@ -59,7 +82,7 @@ class PrivatePaykitContactResolver @Inject constructor( shared.contactsForAddresses(listOf(receivingAddress)) val contact = receivingContacts.mapNotNull(PubkyPublicKeyFormat::normalized).distinct().singleOrNull() ?: return@withContext null - if (receivedPaymentContacts !== shared) return@withContext null + if (receivedPaymentContacts !== shared || !isRecoveryCurrent(generation)) return@withContext null contact.takeIf { (reservedContacts.values.filterNotNull() + shared.contactsForAddresses(addresses)) .mapNotNull(PubkyPublicKeyFormat::normalized).distinct().singleOrNull() == contact diff --git a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt index 02dc4fbb55..6ab085472a 100644 --- a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt @@ -17,6 +17,7 @@ import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.currentCoroutineContext @@ -41,6 +42,7 @@ import org.lightningdevkit.ldknode.PaymentStatus import to.bitkit.App import to.bitkit.async.appScope import to.bitkit.data.PrivatePaykitCacheStore +import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.SettingsStore import to.bitkit.di.IoDispatcher import to.bitkit.di.json @@ -87,6 +89,7 @@ class PrivatePaykitRepo @Inject constructor( private val usdtRepo: UsdtRepo, private val coreService: CoreService, private val clock: Clock, + private val profileRemovalStore: ProfileRemovalStore, ) { companion object { private const val TAG = "PrivatePaykitRepo" @@ -126,10 +129,12 @@ class PrivatePaykitRepo @Inject constructor( private val activeLinkPreparations = mutableMapOf>() private var preparationJob: Job? = null private var preparationGeneration = 0 - private val _isProfileDeletionInProgress = MutableStateFlow(false) + private val profileDeletionPauses = mutableSetOf() + private var recoveryPending = true + private val _isProfileDeletionInProgress = MutableStateFlow(true) val isProfileDeletionInProgress = _isProfileDeletionInProgress.asStateFlow() - private val isDeletingProfile: Boolean - get() = _isProfileDeletionInProgress.value + private val profileRecoveryReady = CompletableDeferred() + private var pendingLightningRefresh: LightningRefresh? = null private val unavailableLinkRetryAt = mutableMapOf() private var state: PrivatePaykitState? = null @@ -220,6 +225,16 @@ class PrivatePaykitRepo @Inject constructor( private val _backupStateVersion = MutableStateFlow(0L) val backupStateVersion: StateFlow = _backupStateVersion.asStateFlow() + init { + retryScope.launch { + profileRemovalStore.pending.collect { pending -> + recoveryPending = pending + _isProfileDeletionInProgress.value = pending || profileDeletionPauses.isNotEmpty() + profileRecoveryReady.complete(Unit) + } + } + } + suspend fun reconcileReservedReceiveIndexes(): Result = addressReservationRepo.reconcileReservedIndexesWithLdk() @@ -302,12 +317,12 @@ class PrivatePaykitRepo @Inject constructor( } } - private fun scheduleContactPreparation( + private suspend fun scheduleContactPreparation( publicKeys: Collection, forceRefreshLightning: Boolean = false, requeueActive: Boolean = false, ) { - if (isDeletingProfile) return + if (isDeletingProfile()) return pendingPreparationKeys.addAll( publicKeys.filter { requeueActive || forceRefreshLightning || it !in activePreparationKeys } ) @@ -359,13 +374,38 @@ class PrivatePaykitRepo @Inject constructor( clearPendingMessageDrainRetries() } - suspend fun beginProfileDeletion() = withContext(serializedDispatcher) { - _isProfileDeletionInProgress.update { true } - invalidateContactPreparation() + internal class ProfileDeletionPause internal constructor() + + internal suspend fun beginProfileDeletion(): ProfileDeletionPause { + val pause = ProfileDeletionPause() + try { + withContext(serializedDispatcher) { + profileDeletionPauses.add(pause) + _isProfileDeletionInProgress.value = true + invalidateContactPreparation() + } + return pause + } catch (error: Throwable) { + // Cancellation can discard the return dispatch after the pause was already installed. + withContext(NonCancellable) { endProfileDeletion(pause) } + throw error + } } - suspend fun endProfileDeletion() = withContext(serializedDispatcher) { - _isProfileDeletionInProgress.update { false } + internal suspend fun endProfileDeletion(pause: ProfileDeletionPause) = withContext(serializedDispatcher) { + profileDeletionPauses.remove(pause) + _isProfileDeletionInProgress.value = recoveryPending || profileDeletionPauses.isNotEmpty() + } + + internal suspend fun withProfileDeletionPaused( + operation: suspend (ProfileDeletionPause) -> T, + ): T { + val pause = beginProfileDeletion() + try { + return operation(pause) + } finally { + withContext(NonCancellable) { endProfileDeletion(pause) } + } } suspend fun refreshSavedContactEndpoints( @@ -377,7 +417,7 @@ class PrivatePaykitRepo @Inject constructor( withContext(serializedDispatcher) { runContactSync { val normalizedKey = normalizedPublicKey(publicKey) ?: return@runContactSync - if (isDeletingProfile || isContactSharingCleanupPending()) return@runContactSync + if (isDeletingProfile() || isContactSharingCleanupPending()) return@runContactSync checkPaykitContactSync(isStillCurrent) rememberSavedContacts(savedPublicKeys + normalizedKey, replacing = false) schedulePendingPrivateMessageDrainRetries( @@ -412,7 +452,8 @@ class PrivatePaykitRepo @Inject constructor( savedPublicKeys: Collection, ): Result = withContext(serializedDispatcher) { runSuspendCatching { - if (isDeletingProfile) return@runSuspendCatching + if (isDeletingProfile()) return@runSuspendCatching + profileRemovalStore.requireNoPending() val settings = settingsStore.data.first() val hasDisabledPublications = !settings.sharesPrivatePaykitEndpoints && hasPublishedPrivateEndpoints() val cleanupPending = isContactSharingCleanupPending() @@ -459,7 +500,7 @@ class PrivatePaykitRepo @Inject constructor( pendingPreparationKeys.removeAll(keys) keys.forEach { pendingMessageDrainRetries.remove(it)?.job?.cancel() } keys.forEach(unavailableLinkRetryAt::remove) - if (!isDeletingProfile) { + if (!isDeletingProfile()) { removePublishedEndpoints(keys, isStillCurrent).onFailure { checkPaykitContactSync(isStillCurrent) updateDeletedContactCleanupPending(keys, true, isStillCurrent) @@ -469,7 +510,7 @@ class PrivatePaykitRepo @Inject constructor( clearContactStates(keys, isStillCurrent) checkPaykitContactSync(isStillCurrent) addressReservationRepo.removeContactAssignments(keys, isStillCurrent) - if (!isDeletingProfile) updateDeletedContactCleanupPending(keys, false, isStillCurrent) + if (!isDeletingProfile()) updateDeletedContactCleanupPending(keys, false, isStillCurrent) } } @@ -519,21 +560,42 @@ class PrivatePaykitRepo @Inject constructor( suspend fun closeAndClear(): Result = withContext(serializedDispatcher) { runSuspendCatching { + profileRemovalStore.requireAccess() pendingLightningRefresh = null invalidateContactPreparation() publicationMutex.withLock { - clearPendingMessageDrainRetries() - knownSavedContactKeys.clear() - unavailableLinkRetryAt.clear() - state = PrivatePaykitState() - cacheStore.reset() - addressReservationRepo.clearContactAssignments(excludingPublicKeys = emptySet()) + clearLocalPaymentState() paykitSdkService.clearState() notifyBackupStateChanged() } } } + /** Native sign-out already reset the SDK; complete only the local state owned by this removal. */ + internal suspend fun finishProfileRemoval(pause: ProfileDeletionPause): Result = + withContext(serializedDispatcher) { + runSuspendCatching { + profileRemovalStore.requireCompletionAccess() + check(pause in profileDeletionPauses) { "Profile removal has already finished" } + pendingLightningRefresh = null + invalidateContactPreparation() + publicationMutex.withLock { + check(pause in profileDeletionPauses) { "Profile removal has already finished" } + clearLocalPaymentState() + notifyBackupStateChanged() + } + } + } + + private suspend fun clearLocalPaymentState() { + clearPendingMessageDrainRetries() + knownSavedContactKeys.clear() + unavailableLinkRetryAt.clear() + state = PrivatePaykitState() + cacheStore.reset() + addressReservationRepo.clearContactAssignments(excludingPublicKeys = emptySet()) + } + suspend fun beginSavedContactPayment(publicKey: String): Result = withContext(serializedDispatcher) { runSuspendCatching { @@ -800,18 +862,22 @@ class PrivatePaykitRepo @Inject constructor( suspend fun contactPublicKeyForPrivateInvoicePaymentHash(paymentHash: String): String? = withContext(serializedDispatcher) { - if (paymentHash.isBlank()) return@withContext null - ensureState().contacts.firstNotNullOfOrNull { (publicKey, contactState) -> - publicKey.takeIf { - contactState.localInvoice?.paymentHash == paymentHash || - paymentHash in contactState.receivedInvoicePaymentHashes + runSuspendCatching { + profileRemovalStore.requireNoPending() + if (paymentHash.isBlank()) return@runSuspendCatching null + ensureState().contacts.firstNotNullOfOrNull { (publicKey, contactState) -> + publicKey.takeIf { + contactState.localInvoice?.paymentHash == paymentHash || + paymentHash in contactState.receivedInvoicePaymentHashes + } } - } + }.getOrNull() } internal suspend fun backupSnapshot(): Result = withContext(serializedDispatcher) { runSuspendCatching { + profileRemovalStore.requireNoPending() val sdkVersion = paykitSdkService.backupStateVersion.value pubkyService.currentPublicKey() ?: return@runSuspendCatching PrivatePaykitBackupSnapshot(null, sdkVersion) @@ -833,6 +899,7 @@ class PrivatePaykitRepo @Inject constructor( suspend fun restoreBackup(backup: String?): Result = withContext(serializedDispatcher) { runSuspendCatching { + profileRemovalStore.requireNoPending() val decoded = backup?.let { json.decodeFromString(it) } decoded?.let { paykitSdkService.retainRecoveryBackup(it.sdkState) } pendingLightningRefresh = null @@ -1199,7 +1266,7 @@ class PrivatePaykitRepo @Inject constructor( status: IdentityStatus? = null, ): Boolean { val currentIdentity = status?.publicKey ?: pubkyService.currentPublicKey() - val isCurrent = !isDeletingProfile && generation == preparationGeneration && currentIdentity == identity + val isCurrent = !isDeletingProfile() && generation == preparationGeneration && currentIdentity == identity if (!isCurrent && requireImmediatePublication) throw PrivatePaykitError.PrivateUnavailable return isCurrent } @@ -1329,9 +1396,9 @@ class PrivatePaykitRepo @Inject constructor( generation: Int, priority: Priority = Priority.Ordered, ) { - if (isDeletingProfile || generation != preparationGeneration) return + if (isDeletingProfile() || generation != preparationGeneration) return if (isContactSharingCleanupPending() || !hasPrivatePaymentAccessForCurrentProfile()) return - if (isDeletingProfile || generation != preparationGeneration) return + if (isDeletingProfile() || generation != preparationGeneration) return drainAndSchedulePrivateLinkRetries(reason, publicKeys.distinct(), generation, priority) } @@ -1343,12 +1410,12 @@ class PrivatePaykitRepo @Inject constructor( ) { val newKeys = retryKeys.toSet() - pendingMessageDrainRetries.keys val pendingKeys = pendingPrivateMessageDrainKeys(newKeys, retryMissingPeers = true, priority = priority) - if (pendingKeys.isEmpty() || isDeletingProfile || generation != preparationGeneration) return + if (pendingKeys.isEmpty() || isDeletingProfile() || generation != preparationGeneration) return drainPendingPrivateMessages(reason, retryKeys = pendingKeys, priority = priority) - if (isDeletingProfile || generation != preparationGeneration) return + if (isDeletingProfile() || generation != preparationGeneration) return val pendingRetryKeys = pendingPrivateMessageDrainKeys(pendingKeys, priority = priority) - if (pendingRetryKeys.isNotEmpty() && !isDeletingProfile && generation == preparationGeneration) { + if (pendingRetryKeys.isNotEmpty() && !isDeletingProfile() && generation == preparationGeneration) { schedulePendingPrivateMessageDrainRetries(reason, retryKeys = pendingRetryKeys) } } @@ -1534,7 +1601,7 @@ class PrivatePaykitRepo @Inject constructor( explicit: Boolean = false, identity: String? = null, ) { - if (retryKeys.isEmpty() || isDeletingProfile) return + if (retryKeys.isEmpty() || isDeletingProfile()) return if (!explicit && retryKeys.all { it in pendingMessageDrainRetries }) return val generation = preparationGeneration val identity = identity ?: pubkyService.currentPublicKey() ?: return @@ -2216,21 +2283,26 @@ class PrivatePaykitRepo @Inject constructor( return paymentHash in paymentHashes } + private suspend fun isDeletingProfile(): Boolean { + profileRecoveryReady.await() + return _isProfileDeletionInProgress.value + } + private suspend fun canPublishPrivateEndpoints(status: IdentityStatus? = null): Boolean { - if (isDeletingProfile) return false + if (isDeletingProfile()) return false val settings = settingsStore.data.first() val locallyEligible = settings.sharesPrivatePaykitEndpoints && !isContactSharingCleanupPending() && App.currentActivity?.value != null && walletRepo.walletExists() && lightningRepo.lightningState.value.nodeLifecycleState.isRunning() - if (!locallyEligible || isDeletingProfile) return false + if (!locallyEligible || isDeletingProfile()) return false val hasAccess = if (status?.publicKey != null) { status.capability == PubkyIdentityCapability.PRIVATE_LINK_CAPABLE } else { hasPrivatePaymentAccessForCurrentProfile() } - return hasAccess && !isDeletingProfile + return hasAccess && !isDeletingProfile() } private suspend fun hasPrivatePaymentAccessForCurrentProfile(): Boolean = runSuspendCatching { @@ -2382,8 +2454,12 @@ class PrivatePaykitRepo @Inject constructor( private fun redacted(publicKey: String): String = PubkyPublicKeyFormat.redacted(publicKey) private suspend fun ensureState(): PrivatePaykitState { + profileRemovalStore.requireAccess() state?.let { return it } - return PrivatePaykitState(cacheStore.data.first()).also { state = it } + val loaded = PrivatePaykitState(cacheStore.data.first()) + profileRemovalStore.requireAccess() + // A teardown or restore may have installed a newer state while this cold read was suspended. + return state ?: loaded.also { state = it } } private suspend fun persistState( @@ -2391,6 +2467,7 @@ class PrivatePaykitRepo @Inject constructor( preserveCleanupMarkers: Boolean = true, isStillCurrent: (() -> Boolean)? = null, ) { + profileRemovalStore.requireAccess() val currentState = state ?: PrivatePaykitState() cacheStore.update { if (isStillCurrent?.invoke() == false) return@update it diff --git a/app/src/main/java/to/bitkit/repositories/PubkyIdentityOperations.kt b/app/src/main/java/to/bitkit/repositories/PubkyIdentityOperations.kt new file mode 100644 index 0000000000..755d86162f --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/PubkyIdentityOperations.kt @@ -0,0 +1,126 @@ +package to.bitkit.repositories + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Job +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.withContext +import to.bitkit.utils.AppError +import kotlin.coroutines.AbstractCoroutineContextElement +import kotlin.coroutines.CoroutineContext + +/** Admission covers local completion and rollback as well as the native session change. */ +internal class PubkyIdentityOperations(private val beforeTransition: suspend () -> Unit = {}) { + private val lock = Any() + private val active = mutableSetOf() + private var removal: Operation? = null + private var wiping = false + private var wipeOperation: Operation? = null + + suspend fun transition(block: suspend () -> T): T { + currentCoroutineContext()[Operation]?.takeIf { it.owner === this }?.let { + check(synchronized(lock) { it in active }) { "Pubky operation has already finished" } + return block() + } + val operation = synchronized(lock) { + if (wiping || removal != null) throw PubkyIdentityBusy + Operation(this).also(active::add) + } + return run(operation) { + beforeTransition() + block() + } + } + + suspend fun remove(block: suspend () -> T): T { + val operation = synchronized(lock) { + if (wiping || active.isNotEmpty()) throw PubkyIdentityBusy + Operation(this).also { + removal = it + active.add(it) + } + } + return run(operation, block) + } + + suspend fun requireRemoval() { + val operation = currentCoroutineContext()[Operation] + check(synchronized(lock) { operation != null && operation === removal && operation in active }) { + "Profile removal admission is required" + } + } + + suspend fun requireWipe() { + val operation = currentCoroutineContext()[Operation] + check(synchronized(lock) { operation != null && operation === wipeOperation && operation in active }) { + "Wallet wipe admission is required" + } + } + + suspend fun wipe(block: suspend () -> T): T { + check(currentCoroutineContext()[Operation]?.owner !== this) { "Pubky operation cannot start a wallet wipe" } + val (draining, cancelled) = synchronized(lock) { + if (wiping) throw PubkyIdentityBusy + wiping = true + active.toList() to removal + } + // Revoke and drain before the SDK barrier; no monitor or session mutex is held while awaiting cleanup. + cancelled?.cancel() + try { + draining.forEach { it.drained.await() } + val operation = synchronized(lock) { + Operation(this).also { + active.add(it) + wipeOperation = it + } + } + return run(operation, block) + } finally { + synchronized(lock) { + wiping = false + wipeOperation = null + } + } + } + + private suspend fun run(operation: Operation, block: suspend () -> T): T { + try { + return withContext(operation) { + operation.bind(requireNotNull(currentCoroutineContext()[Job])) + block() + } + } finally { + synchronized(lock) { + active.remove(operation) + if (removal === operation) removal = null + } + operation.drained.complete(Unit) + } + } + + private class Operation(val owner: PubkyIdentityOperations) : AbstractCoroutineContextElement(Key) { + companion object Key : CoroutineContext.Key + + private val lock = Any() + private var job: Job? = null + private var cancelled = false + val drained = CompletableDeferred() + + fun bind(job: Job) { + val cancelNow = synchronized(lock) { + this.job = job + cancelled + } + if (cancelNow) job.cancel() + } + + fun cancel() { + val current = synchronized(lock) { + cancelled = true + job + } + current?.cancel() + } + } +} + +internal data object PubkyIdentityBusy : AppError("Pubky identity work is already in progress") diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 0ddfd7e599..784f1e0c6e 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -43,13 +43,13 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import to.bitkit.async.appScope +import to.bitkit.data.ProfileRemovalPending +import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.PubkyCachedProfile import to.bitkit.data.PubkyImageCacheEpoch import to.bitkit.data.PubkyStore import to.bitkit.data.SettingsStore -import to.bitkit.data.hasPaykitState import to.bitkit.data.keychain.Keychain -import to.bitkit.data.paykitDisabled import to.bitkit.data.sharedpubky.SharedPubkyClient import to.bitkit.data.sharedpubky.SharedPubkyContract import to.bitkit.di.IoDispatcher @@ -68,6 +68,7 @@ import to.bitkit.models.PubkyProfileLink import to.bitkit.models.PubkyPublicKeyFormat import to.bitkit.models.PubkySessionBackupKind import to.bitkit.models.PubkySessionBackupV1 +import to.bitkit.services.PaykitProfileDeletionSnapshot import to.bitkit.services.PaykitReadLane import to.bitkit.services.PaykitReadTimeoutError import to.bitkit.services.PubkyService @@ -101,6 +102,18 @@ sealed class PubkyContactError(message: String) : AppError(message) { */ class PubkySignIn internal constructor(val publicKey: String, internal val generation: Long) +/** One displayed identity, including a saved identity whose session could not be restored. */ +class PubkyProfileOwner internal constructor( + internal val signIn: PubkySignIn?, + internal val storedRevision: Long, +) + +internal class PubkyProfileDeletion( + val owner: PubkyProfileOwner, + val profileWriteRevision: Long, + val snapshot: PaykitProfileDeletionSnapshot, +) + private fun Throwable.hasCause(error: AppError): Boolean = generateSequence(this) { it.cause }.any { it == error } @@ -119,6 +132,9 @@ enum class PubkyIdentityReadiness { /** An identity is saved, or could not be checked, but its session could not be restored yet. */ Unavailable, + + /** An interrupted local removal must be completed without activating saved credentials. */ + RecoveryRequired, } @OptIn(ExperimentalTime::class) @@ -134,6 +150,7 @@ class PubkyRepo @Inject constructor( private val settingsStore: SettingsStore, private val httpClient: HttpClient, private val clock: Clock, + private val profileRemovalStore: ProfileRemovalStore, ) { companion object { private const val TAG = "PubkyRepo" @@ -164,6 +181,7 @@ class PubkyRepo @Inject constructor( private val scope = appScope(ioDispatcher, TAG) private val serviceInitializeMutex = Mutex() private val initializeMutex = Mutex() + private val identityOperations = PubkyIdentityOperations(::requireNoPendingRemoval) private val deferredRestoreMutex = Mutex() private var deferredRestoreGeneration: Long? = null private val completedRestoreVersion = AtomicLong() @@ -250,12 +268,21 @@ class PubkyRepo @Inject constructor( val isAuthenticated: StateFlow = _publicKey.map { it != null } .stateIn(scope, SharingStarted.Eagerly, false) + val profileRecoveryPending: StateFlow = profileRemovalStore.pending + .map { it } + .stateIn(scope, SharingStarted.Eagerly, null) + + suspend fun requiresProfileRecovery(): Boolean = withContext(ioDispatcher) { + runSuspendCatching { profileRemovalStore.requireNoPending() }.isFailure + } + val identityExists: StateFlow = combine( _publicKey, _backupStateVersion, _identityRefreshVersion, - ) { _, _, _ -> - runSuspendCatching { hasIdentity() } + profileRemovalStore.pending, + ) { _, _, _, pending -> + pending || runSuspendCatching { hasIdentity() } .onFailure { Logger.warn("Failed to check saved identity", it, context = TAG) } .getOrDefault(true) }.stateIn(scope, SharingStarted.Eagerly, null) @@ -342,6 +369,61 @@ class PubkyRepo @Inject constructor( } } + private suspend fun requireNoPendingRemoval() { + runSuspendCatching { profileRemovalStore.requireNoPending() }.exceptionOrNull()?.let { failure -> + // Retained credentials must not activate while local teardown is unresolved or unreadable. + _isRestoringSession.value = false + _sessionRestorationFailed.value = true + runSuspendCatching { pubkyService.preparePublicProfileRecovery() } + .onFailure { Logger.warn("Failed to prepare public profile access", it, context = TAG) } + throw failure + } + } + + private suspend fun identityTransition(operation: suspend () -> Result): Result = + runSuspendCatching { identityOperations.transition { operation().getOrThrow() } } + + fun profileOwner(): PubkyProfileOwner { + val revision = storedIdentityRevision.get() + return PubkyProfileOwner(currentSignIn(), revision) + } + + fun isProfileOwnerCurrent(owner: PubkyProfileOwner): Boolean = + owner.storedRevision == storedIdentityRevision.get() && + (owner.signIn?.let(::isCurrent) ?: (currentSignIn() == null)) + + /** Reserve the original identity through native work, local completion and cancellation cleanup. */ + internal suspend fun performProfileRemoval( + owner: PubkyProfileOwner, + operation: suspend () -> Unit, + ): Result = runSuspendCatching { + identityOperations.remove { + check(isProfileOwnerCurrent(owner)) { "The profile identity changed" } + pubkyService.withProfileRemoval({ isProfileOwnerCurrent(owner) }, operation) + profileOwner() + } + } + + /** UUID access is granted only after the repository has admitted the captured owner. */ + internal suspend fun performProfileRemoval( + owner: PubkyProfileOwner, + attemptId: String, + operation: suspend () -> Unit, + ): Result = runSuspendCatching { + identityOperations.remove { + check(isProfileOwnerCurrent(owner)) { "The profile identity changed" } + profileRemovalStore.withAccess(attemptId) { + pubkyService.preparePublicProfileRecovery() + pubkyService.withProfileRemoval({ isProfileOwnerCurrent(owner) }, operation) + } + profileOwner() + } + } + + /** Close session admission before the native wipe barrier, retaining admitted rollback/local tails. */ + internal suspend fun withWalletWipeAdmission(operation: suspend () -> T): T = + identityOperations.wipe(operation) + // region Initialization suspend fun awaitInitialization() = withContext(ioDispatcher) { @@ -349,7 +431,10 @@ class PubkyRepo @Inject constructor( } suspend fun republishIdentityIfNeeded(): Result = withContext(ioDispatcher) { - runSuspendCatching { pubkyService.republishIdentityIfNeeded(publicKey.value) } + runSuspendCatching { + profileRemovalStore.requireNoPending() + pubkyService.republishIdentityIfNeeded(publicKey.value) + } } suspend fun initialize() = initializeForRevision() @@ -372,7 +457,10 @@ class PubkyRepo @Inject constructor( job.start() } - private suspend fun initializeForRevision( + private suspend fun initializeForRevision(expectedRevision: Long? = null): Result = + identityTransition { initializeForRevisionAdmitted(expectedRevision) } + + private suspend fun initializeForRevisionAdmitted( expectedRevision: Long? = null, ): Result = withContext(ioDispatcher) { val (restored, revision) = initializeMutex.withLock { @@ -387,7 +475,15 @@ class PubkyRepo @Inject constructor( checkAdoptedSource() } - suspend fun restoreSessionIfNeeded() = withContext(ioDispatcher) { + suspend fun restoreSessionIfNeeded(): Boolean = try { + identityOperations.transition { restoreSessionIfNeededAdmitted() } + } catch (_: PubkyIdentityBusy) { + false + } catch (_: ProfileRemovalPending) { + false + } + + private suspend fun restoreSessionIfNeededAdmitted() = withContext(ioDispatcher) { awaitInitialization() val restored = restoreSession() if (restored) loadIdentityData() @@ -418,6 +514,7 @@ class PubkyRepo @Inject constructor( */ suspend fun awaitIdentityReady(): PubkyIdentityReadiness = withContext(ioDispatcher) { awaitInitialization() + if (requiresProfileRecovery()) return@withContext PubkyIdentityReadiness.RecoveryRequired if (_publicKey.value != null) return@withContext PubkyIdentityReadiness.Ready scope.async { val restored = restoreSession() @@ -439,7 +536,15 @@ class PubkyRepo @Inject constructor( } } - private suspend fun restoreSession(expectedGeneration: Long? = null): Boolean { + private suspend fun restoreSession(expectedGeneration: Long? = null): Boolean = try { + identityOperations.transition { restoreSessionAdmitted(expectedGeneration) } + } catch (_: PubkyIdentityBusy) { + false + } catch (_: ProfileRemovalPending) { + false + } + + private suspend fun restoreSessionAdmitted(expectedGeneration: Long?): Boolean { val version = completedRestoreVersion.get() return initializeMutex.withLock { if (expectedGeneration != null && @@ -618,7 +723,10 @@ class PubkyRepo @Inject constructor( _adoptedSourceLost.update { false } } - suspend fun checkAdoptedSource(): Result = withContext(ioDispatcher) { + suspend fun checkAdoptedSource(): Result = + identityTransition { checkAdoptedSourceAdmitted() } + + private suspend fun checkAdoptedSourceAdmitted(): Result = withContext(ioDispatcher) { runSuspendCatching { if (initializationReady.isCompleted) checkAdoptedSourcePresent() }.onFailure { Logger.warn("Failed to check adopted ring identity", it, context = TAG) } @@ -658,6 +766,12 @@ class PubkyRepo @Inject constructor( suspend fun adoptRingIdentity( pubky: String, knownProfile: () -> PubkyProfile? = { null }, + ): Result = + identityTransition { adoptRingIdentityAdmitted(pubky, knownProfile) } + + private suspend fun adoptRingIdentityAdmitted( + pubky: String, + knownProfile: () -> PubkyProfile? = { null }, ): Result = withContext(ioDispatcher) { val reference = "${SharedPubkyContract.RING_SOURCE_PREFIX}$pubky" adoptionMutex.withLock { @@ -919,6 +1033,15 @@ class PubkyRepo @Inject constructor( links: List, tags: List, avatarBytes: ByteArray?, + ): Result = + identityTransition { createIdentityAdmitted(name, bio, links, tags, avatarBytes) } + + private suspend fun createIdentityAdmitted( + name: String, + bio: String, + links: List, + tags: List, + avatarBytes: ByteArray?, ): Result { val result = initializeMutex.withLock { if (settingsStore.isPubkyProfileSetupPending.first() && _publicKey.value != null) { @@ -1064,6 +1187,15 @@ class PubkyRepo @Inject constructor( links: List, tags: List, imageUrl: String?, + ): Result = + identityTransition { saveProfileAdmitted(name, bio, links, tags, imageUrl) } + + private suspend fun saveProfileAdmitted( + name: String, + bio: String, + links: List, + tags: List, + imageUrl: String?, ): Result = runSuspendCatching { withContext(ioDispatcher) { requireNotNull(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)) { @@ -1086,22 +1218,36 @@ class PubkyRepo @Inject constructor( } } - suspend fun deleteProfile(): Result = runSuspendCatching { - withContext(ioDispatcher) { - requireNotNull(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)) { - "No session available" + internal suspend fun prepareProfileDeletion(owner: PubkyProfileOwner): Result = + runSuspendCatching { + check(isProfileOwnerCurrent(owner)) { "Profile removal identity changed" } + val signIn = requireNotNull(owner.signIn) { "Profile identity is not available" } + val revision = profileWriteGeneration.get() + val snapshot = pubkyService.captureProfileDeletion(signIn.publicKey) { isProfileOwnerCurrent(owner) } + check(isProfileOwnerCurrent(owner) && revision == profileWriteGeneration.get()) { + "Profile changed; review it before removing it" } - clearSessionContactProfiles() - deleteAllContacts() - pubkyService.deletePaykitProfile() - profileWriteGeneration.incrementAndGet() + PubkyProfileDeletion(owner, revision, snapshot) + } + + internal suspend fun validateProfileDeletion(deletion: PubkyProfileDeletion) { + identityOperations.requireRemoval() + check(isProfileOwnerCurrent(deletion.owner) && deletion.profileWriteRevision == profileWriteGeneration.get()) { + "Profile changed; review it before removing it" } - settingsStore.update { it.paykitDisabled(markPublicCleanupPending = it.hasPaykitState()) } - signOut().getOrThrow() + pubkyService.validateProfileDeletion(deletion.snapshot) } - private suspend fun deleteAllContacts() { - val records = pubkyService.contactRecords() + internal suspend fun deleteProfile(deletion: PubkyProfileDeletion): Result = runSuspendCatching { + identityOperations.requireRemoval() + check(isProfileOwnerCurrent(deletion.owner)) { "Profile removal identity changed" } + clearSessionContactProfiles() + deleteContacts(deletion.snapshot.contacts) + pubkyService.deletePaykitProfile(deletion.snapshot) + profileWriteGeneration.incrementAndGet() + } + + private suspend fun deleteContacts(records: List) { if (records.isEmpty()) return val keys = records.map { it.publicKey.ensurePubkyPrefix() }.toSet() val removedKeys = pubkyService.removeContacts(records.map { it.publicKey }) @@ -1542,8 +1688,9 @@ class PubkyRepo @Inject constructor( // region Auth approval suspend fun hasSecretKey(): Boolean = runSuspendCatching { - val publicKey = _publicKey.value ?: return@runSuspendCatching false - managedSecretKeyFor(publicKey) != null + val owner = profileOwner() + if (owner.signIn == null) return@runSuspendCatching false + activeSecretKeyHex(owner, clearInvalidKey = false) != null }.getOrDefault(false) suspend fun hasStoredSecretKey(): Boolean = withContext(ioDispatcher) { @@ -1620,7 +1767,10 @@ class PubkyRepo @Inject constructor( } } - suspend fun approveSignupAuth(request: PubkyAuthRequest): Result = initializeMutex.withLock { + suspend fun approveSignupAuth(request: PubkyAuthRequest): Result = + identityTransition { approveSignupAuthAdmitted(request) } + + private suspend fun approveSignupAuthAdmitted(request: PubkyAuthRequest): Result = initializeMutex.withLock { runSuspendCatching { withContext(ioDispatcher) { require(request.isSignup) { "Not a Pubky signup request" } @@ -1681,6 +1831,13 @@ class PubkyRepo @Inject constructor( authUrl: String, expectedCapabilities: String, approvedClientId: String, + ): Result = + identityTransition { approveAuthAdmitted(authUrl, expectedCapabilities, approvedClientId) } + + private suspend fun approveAuthAdmitted( + authUrl: String, + expectedCapabilities: String, + approvedClientId: String, ): Result = runSuspendCatching { withContext(ioDispatcher) { val secretKeyHex = requireNotNull(activeSecretKeyHex()) { @@ -1694,6 +1851,13 @@ class PubkyRepo @Inject constructor( authUrl: String, approvedClientId: String, unsignedPayload: ByteArray, + ): Result = + identityTransition { approveAuthWithCompanionClaimAdmitted(authUrl, approvedClientId, unsignedPayload) } + + private suspend fun approveAuthWithCompanionClaimAdmitted( + authUrl: String, + approvedClientId: String, + unsignedPayload: ByteArray, ): Result = runSuspendCatching { withContext(ioDispatcher) { val claim = PubkyAuthRequest.parseBitkitClaim( @@ -1736,7 +1900,12 @@ class PubkyRepo @Inject constructor( } } - suspend fun restoreSessionBackupState(backup: PubkySessionBackupV1?): Result = runSuspendCatching { + suspend fun restoreSessionBackupState(backup: PubkySessionBackupV1?): Result = + identityTransition { restoreSessionBackupStateAdmitted(backup) } + + private suspend fun restoreSessionBackupStateAdmitted( + backup: PubkySessionBackupV1?, + ): Result = runSuspendCatching { withContext(ioDispatcher) { ensureServiceInitialized() @@ -1791,44 +1960,45 @@ class PubkyRepo @Inject constructor( // region Sign out - suspend fun signOut(): Result = withContext(NonCancellable + ioDispatcher) { - initializeMutex.withLock { - val hadPaykitState = settingsStore.data.first().hasPaykitState() - val endpointCleanupResult = removeBitkitPaymentEndpoints() - .onFailure { Logger.warn("Failed to remove Bitkit payment endpoints", it, context = TAG) } + /** Remote acknowledgement only. Local safety state is retained until strict credential teardown. */ + internal suspend fun signOutForProfileRemoval() { + identityOperations.requireRemoval() + pubkyService.signOut() + } - val result = runSuspendCatching { - pubkyService.signOut() - }.onFailure { Logger.error("Failed to revoke Pubky session during sign out", it, context = TAG) } - - if (result.isFailure) { - if (hadPaykitState) { - runSuspendCatching { - settingsStore.update { it.copy(publicPaykitCleanupPending = true) } - }.onFailure { - Logger.warn("Failed to mark Paykit state for reconciliation", it, context = TAG) - } - } - return@withLock result - } + /** No native initialization or remote mutation; callers retain admission through private completion. */ + internal suspend fun finishProfileRemovalLocally() { + identityOperations.requireRemoval() + pubkyService.forgetLocalProfileAccess() + clearProfileMetadataAfterCredentialTeardown() + } - clearLocalState(publicPaykitCleanupPending = endpointCleanupResult.isFailure && hadPaykitState) - result - } + /** The wallet wipe has acknowledged keychain deletion and still owns both teardown barriers. */ + internal suspend fun finishProfileWipeLocally() { + identityOperations.requireWipe() + pubkyService.requireWalletWipe() + clearProfileMetadataAfterCredentialTeardown() } - suspend fun forgetUnrestoredIdentity(): Result = withContext(NonCancellable + ioDispatcher) { - initializeMutex.withLock { - if (_publicKey.value != null) return@withLock Result.success(false) - runSuspendCatching { - pubkyService.forgetSessionAccess() - clearLocalState() - true - }.onFailure { Logger.error("Failed to forget unrestored Pubky identity", it, context = TAG) } + private suspend fun clearProfileMetadataAfterCredentialTeardown() { + withContext(NonCancellable + ioDispatcher) { + try { + // End asynchronous profile/contact writers before resetting their durable cache. + clearAuthenticatedState(clearCachedProfile = false) + invalidateReadOnlyProfile() + evictPubkyImages() + profileWriteGeneration.incrementAndGet() + clearPublicPaykitSharingState(publicPaykitCleanupPending = false) + pubkyStore.reset() + } finally { + notifyBackupStateChanged() + } } } - suspend fun wipeLocalState() = initializeMutex.withLock { + suspend fun wipeLocalState() = identityOperations.transition { wipeLocalStateAdmitted() } + + private suspend fun wipeLocalStateAdmitted() = initializeMutex.withLock { runSuspendCatching { withContext(ioDispatcher) { pubkyService.forgetSessionAccess() } }.onFailure { @@ -2078,34 +2248,38 @@ class PubkyRepo @Inject constructor( } } - private suspend fun managedSecretKeyFor(publicKey: String): String? = withContext(ioDispatcher) { + private suspend fun managedSecretKeyFor(publicKey: String, clearInvalidKey: Boolean): String? { val bareKey = publicKey.removePrefix(PUBKY_PREFIX) val secretKeyHex = keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name) - ?: return@withContext bareKey - .takeIf { - keychain.loadString(Keychain.Key.SHARED_PUBKY_SOURCE.name) == - "${SharedPubkyContract.RING_SOURCE_PREFIX}$bareKey" - } - ?.let { sharedPubkyClient.ringCredential(it).getOrNull() } + ?: return matchingRingSecretKey(bareKey) - val derivedPublicKey = runCatching { + val derivedPublicKey = runSuspendCatching { pubkyService.publicKeyFromSecret(secretKeyHex).ensurePubkyPrefix() }.onFailure { Logger.warn("Ignoring invalid managed secret key for '${redacted(publicKey)}'", it, context = TAG) }.getOrNull() if (derivedPublicKey == publicKey) { - return@withContext secretKeyHex + return secretKeyHex } if (derivedPublicKey != null) { Logger.warn("Ignoring stale managed secret key for '${redacted(publicKey)}'", context = TAG) } + if (!clearInvalidKey) return matchingRingSecretKey(bareKey) + storedIdentityRevision.incrementAndGet() runCatching { keychain.delete(Keychain.Key.PUBKY_SECRET_KEY.name) } .onSuccess { notifyBackupStateChanged() } - null + return matchingRingSecretKey(bareKey) } + private suspend fun matchingRingSecretKey(bareKey: String): String? = bareKey + .takeIf { + keychain.loadString(Keychain.Key.SHARED_PUBKY_SOURCE.name) == + "${SharedPubkyContract.RING_SOURCE_PREFIX}$bareKey" + } + ?.let { sharedPubkyClient.ringCredential(it).getOrNull() } + private suspend fun adoptedRingPubky(): String? = runCatching { keychain.loadString(Keychain.Key.SHARED_PUBKY_SOURCE.name) }.getOrNull() ?.substringAfter(SharedPubkyContract.RING_SOURCE_PREFIX, "") @@ -2118,10 +2292,19 @@ class PubkyRepo @Inject constructor( .getOrNull() } - private suspend fun activeSecretKeyHex(): String? { - val publicKey = _publicKey.value ?: return keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name) - return managedSecretKeyFor(publicKey) - } + private suspend fun activeSecretKeyHex( + owner: PubkyProfileOwner = profileOwner(), + clearInvalidKey: Boolean = true, + ): String? = + withContext(ioDispatcher) { + // Keep the read/derive/delete decision with the identity that supplied its public key. + initializeMutex.withLock { + if (!isProfileOwnerCurrent(owner)) return@withLock null + val publicKey = owner.signIn?.publicKey + ?: return@withLock keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name) + managedSecretKeyFor(publicKey, clearInvalidKey) + } + } private suspend fun deriveLocalSecretKeyFromWalletSeed(): String = withContext(ioDispatcher) { val mnemonic = requireNotNull(keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)) { diff --git a/app/src/main/java/to/bitkit/services/CoreService.kt b/app/src/main/java/to/bitkit/services/CoreService.kt index b59c70edd1..eae5a97f4f 100644 --- a/app/src/main/java/to/bitkit/services/CoreService.kt +++ b/app/src/main/java/to/bitkit/services/CoreService.kt @@ -395,6 +395,7 @@ class ActivityService( val generation: Long, val activityRevision: Long, val reservationVersion: Long, + val recoveryGeneration: Long, ) internal suspend fun invalidatePaykitContactBackfill() = ServiceQueue.CORE.background { @@ -604,6 +605,10 @@ class ActivityService( suspend fun backfillPaykitContacts(): Boolean = ServiceQueue.CORE.background { val resolver = privatePaykitContactResolver.get() + if (!resolver.hasProfileAccess()) { + lastPaykitContactBackfill = null + return@background false + } val contacts = resolver.receivedPaymentContacts if (contacts === PaykitReceivedPaymentContacts.Empty) { lastPaykitContactBackfill = null @@ -614,6 +619,7 @@ class ActivityService( generation = resolver.receivedPaymentContactsGeneration, activityRevision = paykitActivityRevision, reservationVersion = resolver.reservationVersion, + recoveryGeneration = resolver.recoveryGeneration, ) if (snapshot == lastPaykitContactBackfill) return@background false val activities = getActivities( @@ -647,13 +653,14 @@ class ActivityService( changed } - private fun isCurrentPaykitContactBackfill( + private suspend fun isCurrentPaykitContactBackfill( resolver: PrivatePaykitContactResolver, snapshot: PaykitContactBackfillState, - ): Boolean = resolver.receivedPaymentContacts === snapshot.contacts && + ): Boolean = resolver.hasProfileAccess() && resolver.receivedPaymentContacts === snapshot.contacts && resolver.receivedPaymentContactsGeneration == snapshot.generation && paykitActivityRevision == snapshot.activityRevision && - resolver.reservationVersion == snapshot.reservationVersion + resolver.reservationVersion == snapshot.reservationVersion && + resolver.recoveryGeneration == snapshot.recoveryGeneration private suspend fun attributedPaykitActivity( activity: Activity, @@ -1022,7 +1029,7 @@ class ActivityService( private suspend fun findPrivateReservedAddress(details: BitkitCoreTransactionDetails): String? { for (output in details.outputs) { val address = output.scriptpubkeyAddress ?: continue - if (privatePaykitContactResolver.get().contactPublicKeyForReservedAddress(address) != null) return address + if (privatePaykitContactResolver.get().isReservedReceiveAddress(address)) return address } return null } diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkOperationLock.kt b/app/src/main/java/to/bitkit/services/PaykitSdkOperationLock.kt index ea3483bc12..7db69e37b8 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkOperationLock.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkOperationLock.kt @@ -2,6 +2,7 @@ package to.bitkit.services import com.synonym.paykit.PaykitException import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Job import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.withContext @@ -9,7 +10,9 @@ import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.CoroutineContext import kotlin.coroutines.cancellation.CancellationException -internal class PaykitSdkOperationLock { +internal class PaykitSdkOperationLock( + private val checkRecoveryAccess: suspend () -> Unit = {}, +) { companion object { /** Maximum interactive overtakes before the oldest background operation gets a turn. */ private const val MAX_INTERACTIVE_BYPASSES = 3 @@ -28,20 +31,110 @@ internal class PaykitSdkOperationLock { private var interactiveBypasses = 0 private var generation = 0L private var isWiping = false + private var profileRemoval: ProfileRemoval? = null + private var profileRemovalGeneration = 0L suspend fun withLock(priority: Priority = Priority.Ordered, operation: suspend () -> T): T { + return withLock(priority, allowPublicReadInitialization = false, operation) + } + + /** Only for constructing the unauthenticated handle used by publicRead. */ + suspend fun withPublicReadInitialization(operation: suspend () -> T): T = + withLock(Priority.Ordered, allowPublicReadInitialization = true, operation) + + private suspend fun withLock( + priority: Priority, + allowPublicReadInitialization: Boolean, + operation: suspend () -> T, + ): T { if (ownsWipe()) return operation() + val removal = currentCoroutineContext()[ProfileRemoval] + val removalGeneration = synchronized(stateLock) { profileRemovalGeneration } val admittedGeneration = admit() - acquire(priority) + if (!allowPublicReadInitialization) { + checkRecoveryAccess() + checkProfileRemoval(removal) + } + acquire(priority, admittedGeneration) return try { currentCoroutineContext().ensureActive() checkAdmitted(admittedGeneration) + if (!allowPublicReadInitialization) { + checkRecoveryAccess() + checkProfileRemoval(removal) + if (synchronized(stateLock) { removalGeneration != profileRemovalGeneration }) { + throw removalError() + } + } operation() } finally { release() } } + /** Reserves admission, without holding the SDK lock across caller-owned cleanup. */ + suspend fun withProfileRemoval( + isOwnerCurrent: () -> Boolean, + operation: suspend (ProfileRemoval) -> T, + ): T { + val removal = ProfileRemoval(isOwnerCurrent) + withLock { + removal.requireCurrent() + synchronized(stateLock) { + checkAvailable() + check(profileRemoval == null) { "Profile removal is already in progress" } + profileRemoval = removal + profileRemovalGeneration++ + } + } + try { + return withContext(removal) { + removal.bind(requireNotNull(currentCoroutineContext()[Job])) + removal.requireCurrent() + operation(removal) + } + } finally { + synchronized(stateLock) { + if (profileRemoval === removal) { + profileRemoval = null + profileRemovalGeneration++ + } + } + removal.drained.complete(Unit) + } + } + + /** Independent publication must never run inside teardown, including its owning context. */ + fun requireNoProfileRemoval() = synchronized(stateLock) { + checkAvailable() + if (profileRemoval != null) throw removalError() + } + + suspend fun requireWalletWipe() { + check(ownsWipe()) { "Wallet wipe admission is required" } + } + + suspend fun requireProfileRemoval() { + val removal = currentCoroutineContext()[ProfileRemoval] + check(removal != null) { "Profile removal admission is required" } + checkRecoveryAccess() + checkProfileRemoval(removal) + } + + suspend fun checkProfileRemoval() { + if (!ownsWipe()) { + checkRecoveryAccess() + checkProfileRemoval(currentCoroutineContext()[ProfileRemoval]) + } + } + + private fun checkProfileRemoval(removal: ProfileRemoval?) { + if (synchronized(stateLock) { profileRemoval !== removal }) { + throw removalError() + } + removal?.requireCurrent() + } + /** * Runs [operation] without the lock but under the wallet wipe admission of [withLock]: it is rejected while a wipe * is in progress. A wipe cannot drain work that does not hold the lock, so a result that a wipe overtakes is @@ -58,12 +151,17 @@ internal class PaykitSdkOperationLock { } suspend fun withWalletWipe(operation: suspend () -> T): T { - synchronized(stateLock) { + check(currentCoroutineContext()[ProfileRemoval] == null) { "Profile removal cannot start a wallet wipe" } + val removal = synchronized(stateLock) { checkAvailable() isWiping = true generation++ + profileRemoval } + removal?.revoke() return try { + // No SDK lock is held while draining the caller's private/local cleanup. + removal?.drained?.await() acquire(Priority.Ordered) try { withContext(WipeContext(this, generation)) { operation() } @@ -75,8 +173,14 @@ internal class PaykitSdkOperationLock { } } - private suspend fun acquire(priority: Priority) { + private suspend fun acquire(priority: Priority, admittedGeneration: Long? = null) { val waiter = synchronized(stateLock) { + // An ordinary caller may have suspended after admission while holding an outer repository mutex. + // Never enqueue it behind the wipe that could now be draining that mutex. + admittedGeneration?.let { + checkAvailable() + if (it != generation) throw wipeError() + } if (!isLocked) { isLocked = true return @@ -137,8 +241,52 @@ internal class PaykitSdkOperationLock { context = "Paykit operation interrupted by wallet wipe", ) + private fun removalError() = PaykitException.Storage( + code = "profile_removal_in_progress", + context = "Paykit operation was interrupted by profile removal", + ) + private class Waiter(val priority: Priority, val ready: CompletableDeferred) + class ProfileRemoval internal constructor( + private val isOwnerCurrent: () -> Boolean, + ) : AbstractCoroutineContextElement(Key) { + companion object Key : CoroutineContext.Key + + private val lock = Any() + private var revoked = false + private var job: Job? = null + internal val drained = CompletableDeferred() + + internal fun bind(job: Job) { + val shouldCancel = synchronized(lock) { + check(this.job == null) + this.job = job + revoked + } + if (shouldCancel) job.cancel() + } + + internal fun revoke() { + val activeJob = synchronized(lock) { + revoked = true + job + } + activeJob?.cancel() + } + + fun requireCurrent() { + val (activeJob, isRevoked) = synchronized(lock) { job to revoked } + activeJob?.ensureActive() + if (isRevoked || !isOwnerCurrent()) { + throw PaykitException.Storage( + code = "profile_removal_obsolete", + context = "The profile removal no longer owns this session", + ) + } + } + } + private class WipeContext( val owner: PaykitSdkOperationLock, val generation: Long, diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt index 87c452f640..713f3c5111 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt @@ -110,6 +110,7 @@ import kotlinx.coroutines.withTimeoutOrNull import org.lightningdevkit.ldknode.Network import to.bitkit.BuildConfig import to.bitkit.async.BaseCoroutineScope +import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.PubkyStore import to.bitkit.data.SettingsStore import to.bitkit.data.keychain.Keychain @@ -257,6 +258,7 @@ class PaykitSdkService @Inject constructor( sharedPubky: SharedPubkyClient, @IoDispatcher ioDispatcher: CoroutineDispatcher, private val settingsStore: SettingsStore, + private val profileRemovalStore: ProfileRemovalStore, ) : BaseCoroutineScope(ioDispatcher, TAG) { private val sessionProvider = PaykitSdkSessionProvider(keychain, sharedPubky) private val paymentAdapter = PaykitSdkPaymentAdapter() @@ -276,12 +278,13 @@ class PaykitSdkService @Inject constructor( private var nextIdentityRepublishAt = 0L private var lastIdentityRepublishAt = 0L private val handleMutex = Mutex() - private val operationLock = PaykitSdkOperationLock() + private val operationLock = PaykitSdkOperationLock { profileRemovalStore.requireAccess() } private val publicReadSlots = PaykitPublicReadSlots(PUBLIC_READ_PERMITS) private val bulkReadPermits = Semaphore(BULK_READ_PERMITS) private val setupMutex = Mutex() private var isSetup = CompletableDeferred() private var setupFailed = false + private var publicRecoverySetup = false private var platformInitializer: () -> Unit = { PaykitAndroid.initializeOrThrow(context) } @Volatile @@ -317,8 +320,9 @@ class PaykitSdkService @Inject constructor( sharedPubky: SharedPubkyClient = SharedPubkyClient(context, ioDispatcher), platformInitializer: (() -> Unit)? = null, settingsStore: SettingsStore, + profileRemovalStore: ProfileRemovalStore = ProfileRemovalStore.inMemoryForTesting(), sdkFactory: () -> PaykitSdk, - ) : this(context, keychain, pubkyStore, sharedPubky, ioDispatcher, settingsStore) { + ) : this(context, keychain, pubkyStore, sharedPubky, ioDispatcher, settingsStore, profileRemovalStore) { this.sdkFactory = sdkFactory if (bootstrapFactory != null) this.bootstrapFactory = bootstrapFactory if (platformInitializer == null) { @@ -332,6 +336,39 @@ class PaykitSdkService @Inject constructor( initialize { initializeRuntime() } } + /** Makes public reads and explicit local recovery available without restoring or publishing saved access. */ + internal suspend fun preparePublicProfileRecovery() { + setupMutex.withLock { + if (isSetup.isCompleted && !setupFailed) return + if (setupFailed) isSetup = CompletableDeferred() + try { + platformInitializer() + setupFailed = false + publicRecoverySetup = true + // Preserve the barrier that callers may already be awaiting on a cold start. + isSetup.complete(Unit) + } catch (error: Throwable) { + setupFailed = true + isSetup.completeExceptionally(error) + throw error + } + } + } + + /** Local credential removal only; it must not initialize a retained session or swallow storage failures. */ + internal suspend fun forgetLocalProfileAccess() { + operationLock.requireProfileRemoval() + operationLock.withLock { + operationLock.requireProfileRemoval() + try { + sessionProvider.clearSessionAccess() + } finally { + resetRuntime() + notifyBackupStateChanged() + } + } + } + fun setPaymentSubmissionActive(active: Boolean) { _isPaymentSubmissionActive.update { active } } @@ -352,17 +389,23 @@ class PaykitSdkService @Inject constructor( private suspend fun initialize(activate: suspend () -> Unit) { setupMutex.withLock { - if (isSetup.isCompleted && !setupFailed) return - if (setupFailed) { + // A cleanup permit authorizes the original operation, never restoration/publication of saved access. + profileRemovalStore.requireNoPending() + if (isSetup.isCompleted && !setupFailed && !publicRecoverySetup) return + val promotingPublicSetup = publicRecoverySetup + if (setupFailed || promotingPublicSetup) { isSetup = CompletableDeferred() setupFailed = false } - try { - platformInitializer() - launch { republishIdentityIfNeeded() } - operationLock.withLock { activate() } + if (!promotingPublicSetup) platformInitializer() + operationLock.withLock { + if (promotingPublicSetup) resetRuntime() + publicRecoverySetup = false + activate() + } isSetup.complete(Unit) + launch { republishIdentityIfNeeded() } } catch (t: Throwable) { setupFailed = true isSetup.completeExceptionally(t) @@ -398,6 +441,8 @@ class PaykitSdkService @Inject constructor( } suspend fun republishIdentityIfNeeded(publicKey: String? = null, now: Long = nowMillis()) { + profileRemovalStore.requireNoPending() + operationLock.requireNoProfileRemoval() val publication = launchIdentityRepublish(publicKey, now) withTimeoutOrNull(IDENTITY_REPUBLISH_WAIT_TIMEOUT) { publication.join() @@ -408,12 +453,16 @@ class PaykitSdkService @Inject constructor( private suspend fun launchIdentityRepublish(publicKey: String?, now: Long = nowMillis()): Job { currentCoroutineContext().ensureActive() + val generation = runtimeGeneration return launch { if (!identityRepublishMutex.tryLock()) return@launch identityRepublishJob = currentCoroutineContext().job try { withTimeoutOrNull(IDENTITY_REPUBLISH_TIMEOUT) { runSuspendCatching { + profileRemovalStore.requireNoPending() + operationLock.requireNoProfileRemoval() + if (generation != runtimeGeneration) return@runSuspendCatching if (!isSetup.isCompleted) PaykitAndroid.initializeOrThrow(context) val key = publicKey ?: sessionProvider.loadLocalSecretKey()?.let(::pubkyPublicKeyFromSecret) val identity = key?.let(PubkyPublicKeyFormat::normalized) ?: return@runSuspendCatching @@ -425,6 +474,9 @@ class PaykitSdkService @Inject constructor( return@runSuspendCatching } + profileRemovalStore.requireNoPending() + operationLock.requireNoProfileRemoval() + if (generation != runtimeGeneration) return@runSuspendCatching republishPublicKey = identity lastIdentityRepublishAt = now nextIdentityRepublishAt = now + IDENTITY_REPUBLISH_RETRY_INTERVAL.inWholeMilliseconds @@ -444,8 +496,16 @@ class PaykitSdkService @Inject constructor( /** Rebroadcasts the identity record when one exists. Returns false only when the network reports none. */ suspend fun hasIdentityRecord(publicKey: String): Boolean { + profileRemovalStore.requireNoPending() + operationLock.requireNoProfileRemoval() + val generation = runtimeGeneration isSetup.await() - return bootstrap().republishIdentity(publicKey) + return identityRepublishMutex.withLock { + profileRemovalStore.requireNoPending() + operationLock.requireNoProfileRemoval() + check(generation == runtimeGeneration) { "Pubky runtime changed before identity publication" } + bootstrap().republishIdentity(publicKey) + } } suspend fun currentPublicKey(): String? { @@ -622,7 +682,7 @@ class PaykitSdkService @Inject constructor( return operationLock.withLock { withPaykitKey { handle -> val publicKey = requireNotNull(completeSdkCall { handle.identityStatus() }?.publicKey) - val current = handle.fetchPaykitProfile(publicKey) + val current = completeSdkCall { handle.fetchPaykitProfile(publicKey) } completeSdkCall { handle.publishPaykitProfile(profile, current?.revision).also { notifyBackupStateChanged() } } @@ -646,12 +706,66 @@ class PaykitSdkService @Inject constructor( } } + internal suspend fun captureProfileDeletion( + expectedIdentity: String, + isStillCurrent: () -> Boolean, + ): PaykitProfileDeletionSnapshot { + isSetup.await() + return operationLock.withLock { + withPaykitKey { handle -> + check(isStillCurrent()) { "Profile removal identity changed" } + val identity = requireNotNull(completeSdkCall { handle.identityStatus() }?.publicKey) + check(PubkyPublicKeyFormat.matches(identity, expectedIdentity)) { "Profile removal identity changed" } + val profile = completeSdkCall { handle.fetchPaykitProfile(identity) } + val contacts = completeSdkCall { handle.contactRecords() } + check(isStillCurrent()) { "Profile removal identity changed" } + PaykitProfileDeletionSnapshot(identity, profile?.revision, contacts.toList()) + } + } + } + + internal suspend fun validateProfileDeletion(snapshot: PaykitProfileDeletionSnapshot) { + isSetup.await() + operationLock.withLock { + withPaykitKey { handle -> + val identity = completeSdkCall { handle.identityStatus() }?.publicKey + check(PubkyPublicKeyFormat.matches(identity, snapshot.publicKey)) { "Profile removal identity changed" } + val profile = completeSdkCall { handle.fetchPaykitProfile(snapshot.publicKey) } + check(profile?.revision == snapshot.profileRevision) { "Profile changed; review it before removing it" } + val contacts = completeSdkCall { handle.contactRecords() } + check( + contacts.toSet() == snapshot.contacts.toSet() + ) { "Contacts changed; review them before removing the profile" } + } + } + } + + internal suspend fun deletePaykitProfile(snapshot: PaykitProfileDeletionSnapshot) { + isSetup.await() + operationLock.withLock { + withPaykitKey { handle -> + val identity = completeSdkCall { handle.identityStatus() }?.publicKey + check(PubkyPublicKeyFormat.matches(identity, snapshot.publicKey)) { "Profile removal identity changed" } + if (snapshot.profileRevision == null) { + check(completeSdkCall { handle.fetchPaykitProfile(snapshot.publicKey) } == null) { + "Profile changed; review it before removing it" + } + } else { + completeSdkCall { + handle.deletePaykitProfile(snapshot.profileRevision) + notifyBackupStateChanged() + } + } + } + } + } + suspend fun deletePaykitProfile() { isSetup.await() operationLock.withLock { withPaykitKey { handle -> val publicKey = requireNotNull(completeSdkCall { handle.identityStatus() }?.publicKey) - val current = handle.fetchPaykitProfile(publicKey) + val current = completeSdkCall { handle.fetchPaykitProfile(publicKey) } completeSdkCall { current?.let { handle.deletePaykitProfile(it.revision) } notifyBackupStateChanged() @@ -924,7 +1038,8 @@ class PaykitSdkService @Inject constructor( if (updates.isEmpty()) return@withStateRevisionTracking null val publicKey = completeSdkCall { handle.identityStatus() }?.publicKey if (publicKey != null) { - val app = handle.paykitAppRegistry(publicKey)?.apps?.find { it.appId == "bitkit" } + val app = completeSdkCall { handle.paykitAppRegistry(publicKey) } + ?.apps?.find { it.appId == "bitkit" } if (app?.capabilities?.privatePayments == false) return@withStateRevisionTracking null } for (update in updates) { @@ -1542,6 +1657,20 @@ class PaykitSdkService @Inject constructor( } } + /** The caller retains this admission through its private and local teardown, not only native calls. */ + internal suspend fun withProfileRemoval( + isOwnerCurrent: () -> Boolean, + operation: suspend () -> T, + ): T { + isSetup.await() + // Reserve SDK admission first, so wipe can revoke a removal waiting for publication to drain. + return operationLock.withProfileRemoval(isOwnerCurrent) { + identityRepublishMutex.withLock { operation() } + } + } + + internal suspend fun requireWalletWipe() = operationLock.requireWalletWipe() + suspend fun clearSessionAccess() = operationLock.withLock { clearRegisteredIdentityActivationLocked() } suspend fun forgetSessionAccess() { @@ -1561,14 +1690,20 @@ class PaykitSdkService @Inject constructor( suspend fun withWalletWipe(operation: suspend () -> T): T { // Drain setup before closing admission, so cleanup cannot await setup queued behind its own barrier. runSuspendCatching { initialize() } - .onFailure { Logger.warn("Failed to initialize Paykit before wallet wipe", it, context = TAG) } + .onFailure { + Logger.warn("Failed to initialize Paykit before wallet wipe", it, context = TAG) + preparePublicProfileRecovery() + } return operationLock.withWalletWipe { - resetRuntime() - try { - operation() - } finally { - sessionProvider.clearLiveSessionAccess() + // Removal has drained. Bootstrap publication never waits for the SDK lock. + identityRepublishMutex.withLock { resetRuntime() + try { + operation() + } finally { + sessionProvider.clearLiveSessionAccess() + resetRuntime() + } } } } @@ -1581,22 +1716,27 @@ class PaykitSdkService @Inject constructor( } private suspend fun refreshPaykitKey(force: Boolean = false) { + operationLock.checkProfileRemoval() if (force) { cachedPaykitKey = null cachedBackupState = null } - val root = sessionProvider.loadLocalSecretKey() ?: run { + val root = sessionProvider.loadLocalSecretKey() + operationLock.checkProfileRemoval() + if (root == null) { if (cachedPaykitKey != null) cachedBackupState = null cachedPaykitKey = null return } val publicKey = pubkyPublicKeyFromSecret(root) val savedGeneration = keychain.loadString("${Keychain.Key.PAYKIT_KEY_GENERATION.name}:$publicKey")?.toULong() + operationLock.checkProfileRemoval() val cached = cachedPaykitKey if (cached != null && cached.publicKey == publicKey && cached.generation == savedGeneration) return cachedPaykitKey = null cachedBackupState = null val key = paykitKey(root) + operationLock.checkProfileRemoval() sessionProvider.setPaykitIdentitySecretKey(key) cachedPaykitKey = PaykitKeyGeneration(publicKey, key.keyGeneration()) } @@ -1609,9 +1749,10 @@ class PaykitSdkService @Inject constructor( private suspend fun paykitKey(root: PubkyLocalSecretKey): PaykitIdentitySecretKey { val publicKey = pubkyPublicKeyFromSecret(root) - val generation = handle().paykitAppRegistry(publicKey)?.keyGeneration ?: 1uL + val generation = completeSdkCall { handle().paykitAppRegistry(publicKey) }?.keyGeneration ?: 1uL val storageKey = "${Keychain.Key.PAYKIT_KEY_GENERATION.name}:$publicKey" val saved = keychain.loadString(storageKey)?.toULong() + operationLock.checkProfileRemoval() check(generation >= (saved ?: 1uL)) { "The Paykit App Registry has an older key generation" } if (saved != generation) keychain.upsertString(storageKey, generation.toString()) return root.derivePaykitIdentitySecretKey(generation) @@ -1638,6 +1779,7 @@ class PaykitSdkService @Inject constructor( } resetRuntime() refreshPaykitKey() + operationLock.checkProfileRemoval() val handle = handle() val identityStatus = completeSdkCall { handle.initialize() } if (result.sessionAccess.exportLocalSecretKey() != null) { @@ -1711,6 +1853,7 @@ class PaykitSdkService @Inject constructor( private suspend fun withPaykitKey(block: suspend (PaykitSdk) -> T): T { val started = TimeSource.Monotonic.markNow() refreshPaykitKey() + operationLock.checkProfileRemoval() if (BuildConfig.DEBUG) Logger.debug("Prepared Paykit key duration='${started.elapsedNow()}'", context = TAG) return runSuspendCatching { block(handle()) } .onFailure(::invalidatePaykitKeyIfNeeded) @@ -1769,6 +1912,7 @@ class PaykitSdkService @Inject constructor( private suspend fun completeSdkCall(operation: suspend () -> T): T { currentCoroutineContext().ensureActive() + operationLock.checkProfileRemoval() val result = withContext(NonCancellable) { runSuspendCatching { operation() } } .onFailure(::invalidatePaykitKeyIfNeeded) currentCoroutineContext().ensureActive() @@ -1802,7 +1946,7 @@ class PaykitSdkService @Inject constructor( ): T { isSetup.await() return operationLock.withoutLock { - val existing = sdk ?: operationLock.withLock { handle() } + val existing = sdk ?: operationLock.withPublicReadInitialization { handle() } val read: suspend () -> T = { withReadTimeout(timeout) { block(existing) } } when (lane) { PaykitReadLane.Interactive -> publicReadSlots.withSlot(lane, read) @@ -1924,22 +2068,32 @@ internal suspend fun withPaykitBackupStateTracking( onChange() return@withContext } - val nextStateRevision = runSuspendCatching { readStateRevision() }.getOrNull() - val observedSnapshot = runSuspendCatching { readObservedSnapshot() }.getOrNull() - ?.takeIf { it.stateRevision == nextStateRevision } - val nextRevision = observedSnapshot?.backupRevision - ?: runSuspendCatching { readRevision() }.getOrNull() - val stateRevision = observedSnapshot?.stateRevision - ?: runSuspendCatching { readStateRevision() }.getOrNull() - onSnapshot( - if (stateRevision != null && nextRevision != null) { - PaykitBackupStateSnapshot(stateRevision, nextRevision) - } else { - null - }, - ) - if (previousRevision == null || nextRevision == null || previousRevision != nextRevision) { - onChange() + var recordedRevision = false + try { + val nextStateRevision = runSuspendCatching { readStateRevision() }.getOrNull() + val observedSnapshot = runSuspendCatching { readObservedSnapshot() }.getOrNull() + ?.takeIf { it.stateRevision == nextStateRevision } + val nextRevision = observedSnapshot?.backupRevision + ?: runSuspendCatching { readRevision() }.getOrNull() + val stateRevision = observedSnapshot?.stateRevision + ?: runSuspendCatching { readStateRevision() }.getOrNull() + onSnapshot( + if (stateRevision != null && nextRevision != null) { + PaykitBackupStateSnapshot(stateRevision, nextRevision) + } else { + null + }, + ) + if (previousRevision == null || nextRevision == null || previousRevision != nextRevision) { + onChange() + } + recordedRevision = true + } finally { + // The mutation completed even when its original caller no longer admits a revision read. + if (!recordedRevision) { + onSnapshot(null) + onChange() + } } } } @@ -2136,3 +2290,10 @@ internal fun paykitStorageCallback(code: String, operation: () -> T): T = if (it is PaykitException) throw it throw PaykitException.Storage(code = code, context = "Platform Paykit storage operation failed") } + +/** The exact remote records presented for one confirmed profile removal. */ +internal data class PaykitProfileDeletionSnapshot( + val publicKey: String, + val profileRevision: String?, + val contacts: List, +) diff --git a/app/src/main/java/to/bitkit/services/PubkyService.kt b/app/src/main/java/to/bitkit/services/PubkyService.kt index e9105a40c9..a9a57d8405 100644 --- a/app/src/main/java/to/bitkit/services/PubkyService.kt +++ b/app/src/main/java/to/bitkit/services/PubkyService.kt @@ -29,6 +29,10 @@ class PubkyService @Inject constructor( internal val AUTHORIZATION_TIMEOUT = 30.seconds } + internal suspend fun preparePublicProfileRecovery() = ServiceQueue.CORE.background { + paykitSdkService.preparePublicProfileRecovery() + } + suspend fun initialize() = ServiceQueue.CORE.background { paykitSdkService.initialize() } @@ -54,10 +58,20 @@ class PubkyService @Inject constructor( paykitSdkService.signOut() } + // Keep the initiating Job here, before ServiceQueue replaces it for individual native calls. + internal suspend fun withProfileRemoval(isOwnerCurrent: () -> Boolean, operation: suspend () -> T): T = + paykitSdkService.withProfileRemoval(isOwnerCurrent, operation) + suspend fun forgetSessionAccess() = ServiceQueue.CORE.background { paykitSdkService.forgetSessionAccess() } + internal suspend fun forgetLocalProfileAccess() = ServiceQueue.CORE.background { + paykitSdkService.forgetLocalProfileAccess() + } + + internal suspend fun requireWalletWipe() = paykitSdkService.requireWalletWipe() + suspend fun clearSessionAccess() = ServiceQueue.CORE.background { paykitSdkService.clearSessionAccess() } @@ -207,6 +221,22 @@ class PubkyService @Inject constructor( paykitSdkService.uploadProfileAvatar(bytes, contentType) } + internal suspend fun captureProfileDeletion( + publicKey: String, + isStillCurrent: () -> Boolean, + ): PaykitProfileDeletionSnapshot = ServiceQueue.CORE.background { + paykitSdkService.captureProfileDeletion(publicKey, isStillCurrent) + } + + internal suspend fun validateProfileDeletion(snapshot: PaykitProfileDeletionSnapshot) = + ServiceQueue.CORE.background { + paykitSdkService.validateProfileDeletion(snapshot) + } + + internal suspend fun deletePaykitProfile(snapshot: PaykitProfileDeletionSnapshot) = ServiceQueue.CORE.background { + paykitSdkService.deletePaykitProfile(snapshot) + } + suspend fun deletePaykitProfile() = ServiceQueue.CORE.background { paykitSdkService.deletePaykitProfile() } diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt index 45563016c3..bb5728a27e 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt @@ -55,14 +55,12 @@ fun EditProfileScreen( viewModel.effects.collect { when (it) { EditProfileEffect.SaveSuccess -> onBackClick() - EditProfileEffect.DeleteSuccess, - EditProfileEffect.DisconnectSuccess, - -> onExitProfile() + is EditProfileEffect.RemovalCompleted -> if (viewModel.isRemovalCurrent(it)) onExitProfile() } } } - Content( + EditProfileContent( uiState = uiState, onBackClick = onBackClick, onNameChange = viewModel::onNameChange, @@ -88,7 +86,7 @@ fun EditProfileScreen( } @Composable -private fun Content( +internal fun EditProfileContent( uiState: EditProfileUiState, onBackClick: () -> Unit, onNameChange: (String) -> Unit, @@ -188,9 +186,19 @@ private fun Content( if (uiState.showDeleteDialog) { AppAlertDialog( - title = stringResource(removal.confirmTitle), - text = stringResource(removal.confirmDescription), - confirmText = stringResource(removal.confirmText), + title = stringResource( + if (uiState.isLocalDisconnect) R.string.profile__sign_out_title else removal.confirmTitle + ), + text = stringResource( + if (uiState.isLocalDisconnect) { + R.string.profile__disconnect_local_description + } else { + removal.confirmDescription + } + ), + confirmText = stringResource( + if (uiState.isLocalDisconnect) R.string.profile__sign_out else removal.confirmText + ), onConfirm = onConfirmDelete, onDismiss = onDismissDeleteDialog, ) @@ -199,11 +207,21 @@ private fun Content( if (uiState.showDeleteFailureDialog) { AppAlertDialog( title = stringResource(removal.errorTitle), - text = stringResource(removal.errorDescription), - confirmText = stringResource(R.string.common__retry), - dismissText = stringResource(R.string.profile__sign_out), - onConfirm = onRetryDelete, - onDismiss = onDisconnectProfile, + text = stringResource( + if (uiState.canReviewRemoval) { + R.string.profile__delete_review_description + } else { + R.string.profile__cleanup_pending + } + ), + confirmText = stringResource( + if (uiState.canReviewRemoval) R.string.profile__review_removal else R.string.profile__sign_out + ), + dismissText = stringResource( + if (uiState.canReviewRemoval) R.string.profile__sign_out else R.string.common__close + ), + onConfirm = if (uiState.canReviewRemoval) onRetryDelete else onDisconnectProfile, + onDismiss = if (uiState.canReviewRemoval) onDisconnectProfile else onDismissDeleteFailureDialog, onDismissRequest = onDismissDeleteFailureDialog, properties = DialogProperties( dismissOnClickOutside = true, @@ -265,7 +283,7 @@ private fun AvatarSection( @Composable private fun Preview() { AppThemeSurface { - Content( + EditProfileContent( uiState = EditProfileUiState( name = "Satoshi", bio = "Authored the Bitcoin white paper", diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt index f72026cafe..c99f3aa71f 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt @@ -12,22 +12,22 @@ import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList -import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext import to.bitkit.R -import to.bitkit.ext.runSuspendCatching import to.bitkit.models.PubkyProfileLink import to.bitkit.models.Toast -import to.bitkit.repositories.PrivatePaykitRepo +import to.bitkit.repositories.PubkyProfileOwner import to.bitkit.repositories.PubkyRepo import to.bitkit.ui.components.ProfileEditLink import to.bitkit.ui.shared.toast.ToastEventBus +import to.bitkit.usecases.ProfileRemovalConfirmation +import to.bitkit.usecases.ProfileRemovalCoordinator +import to.bitkit.usecases.ProfileRemovalFailure import to.bitkit.utils.Logger import javax.inject.Inject @@ -35,12 +35,17 @@ import javax.inject.Inject class EditProfileViewModel @Inject constructor( @ApplicationContext private val context: Context, private val pubkyRepo: PubkyRepo, - private val privatePaykitRepo: PrivatePaykitRepo, + private val removalCoordinator: ProfileRemovalCoordinator, ) : ViewModel() { companion object { private const val TAG = "EditProfileViewModel" } + private val screenOwner = pubkyRepo.profileOwner() + private var preparationRevision = 0L + private var removalConfirmation: ProfileRemovalConfirmation? = null + private var removalFailure: ProfileRemovalFailure? = null + private val _uiState = MutableStateFlow(EditProfileUiState()) val uiState = _uiState.asStateFlow() @@ -57,6 +62,10 @@ class EditProfileViewModel @Inject constructor( val profile = pubkyRepo.profile.value val publicKey = pubkyRepo.publicKey.value.orEmpty() val removal = if (pubkyRepo.isRingAdoptedIdentity()) ProfileRemoval.UNLINK else ProfileRemoval.DELETE + if (!removalCoordinator.isCurrent(screenOwner)) { + _uiState.update { it.copy(isLoading = false) } + return@launch + } if (profile != null) { _uiState.update { it.copy( @@ -161,12 +170,51 @@ class EditProfileViewModel @Inject constructor( } fun showDeleteConfirmation() { - if (_uiState.value.isBusy) return - _uiState.update { it.copy(showDeleteDialog = true) } + if (_uiState.value.isBusy || _uiState.value.isLoading) return + viewModelScope.launch { + prepareConfirmation { removalCoordinator.prepareDeletion(screenOwner) } + } } fun dismissDeleteDialog() { - _uiState.update { it.copy(showDeleteDialog = false) } + preparationRevision++ + removalConfirmation = null + _uiState.update { + it.copy( + showDeleteDialog = false, + showDeleteFailureDialog = removalFailure != null, + canReviewRemoval = removalFailure?.canReview == true, + ) + } + } + + private suspend fun prepareConfirmation(prepare: suspend () -> Result) { + if (_uiState.value.isBusy) return + val revision = ++preparationRevision + _uiState.update { it.copy(isPreparingRemoval = true) } + try { + prepare().onSuccess { confirmation -> + if (revision != preparationRevision || !removalCoordinator.isCurrent(confirmation.owner)) { + return@onSuccess + } + removalConfirmation = confirmation + _uiState.update { + it.copy( + showDeleteDialog = true, + showDeleteFailureDialog = false, + isLocalDisconnect = confirmation.localOnly + ) + } + }.onFailure { error -> + ToastEventBus.send( + Toast.ToastType.ERROR, + context.getString(R.string.profile__disconnect_error), + error.message + ) + } + } finally { + _uiState.update { it.copy(isPreparingRemoval = false) } + } } fun save() { @@ -217,90 +265,72 @@ class EditProfileViewModel @Inject constructor( } fun deleteProfile() { - viewModelScope.launch { - attemptDeleteProfile() - } + if (_uiState.value.isBusy) return + val confirmation = removalConfirmation ?: return + removalConfirmation = null + viewModelScope.launch { performRemoval(confirmation) } } fun retryDeleteProfile() { - viewModelScope.launch { - attemptDeleteProfile() - } + if (_uiState.value.isBusy) return + val failure = removalFailure ?: return + viewModelScope.launch { prepareConfirmation { removalCoordinator.reviewAgain(failure) } } } fun dismissDeleteFailureDialog() { + preparationRevision++ + removalConfirmation = null _uiState.update { it.copy(showDeleteFailureDialog = false) } } fun disconnectProfile() { + if (_uiState.value.isBusy) return + val failure = removalFailure ?: return viewModelScope.launch { - if (_uiState.value.isBusy) return@launch - _uiState.update { it.copy(showDeleteFailureDialog = false, isDeleting = true) } - try { - val result = runSuspendCatching { - withContext(NonCancellable) { - if (!pubkyRepo.forgetUnrestoredIdentity().getOrThrow()) { - privatePaykitRepo.removePublishedEndpointsForCleanup(TAG).getOrThrow() - pubkyRepo.signOut().getOrThrow() - } - privatePaykitRepo.closeAndClear().getOrThrow() - } - } - if (result.isSuccess) { - _effects.emit(EditProfileEffect.DisconnectSuccess) - } else { - ToastEventBus.send( - type = Toast.ToastType.ERROR, - title = context.getString(R.string.profile__disconnect_error), - description = result.exceptionOrNull()?.message, - ) - } - } finally { - _uiState.update { it.copy(isDeleting = false) } - } + prepareConfirmation { removalCoordinator.prepareLocalDisconnect(failure) } } } - private suspend fun attemptDeleteProfile() { + private suspend fun performRemoval(confirmation: ProfileRemovalConfirmation) { if (_uiState.value.isBusy) return - _uiState.update { - it.copy( - showDeleteDialog = false, - showDeleteFailureDialog = false, - isDeleting = true, - ) - } + _uiState.update { it.copy(showDeleteDialog = false, showDeleteFailureDialog = false, isDeleting = true) } try { - privatePaykitRepo.beginProfileDeletion() - val result = runSuspendCatching { - privatePaykitRepo.removePublishedEndpointsForCleanup(TAG, deferAppSync = true).getOrThrow() - pubkyRepo.deleteProfile().getOrThrow() - } - if (result.isSuccess) { - privatePaykitRepo.closeAndClear().onFailure { - Logger.error("Failed to clear local state after profile deletion", it, context = TAG) + removalCoordinator.remove(confirmation).onSuccess { endedOwner -> + removalFailure = null + if (removalCoordinator.isCurrent(endedOwner)) { + _effects.emit(EditProfileEffect.RemovalCompleted(endedOwner)) + } + }.onFailure { error -> + removalFailure = (error as? ProfileRemovalFailure) ?: removalFailure + if (removalFailure != null) { + _uiState.update { + it.copy( + showDeleteFailureDialog = true, + canReviewRemoval = requireNotNull(removalFailure).canReview, + ) + } + } else { ToastEventBus.send( - type = Toast.ToastType.ERROR, - title = context.getString(R.string.common__error), - description = it.message, + Toast.ToastType.ERROR, + context.getString(R.string.profile__disconnect_error), + error.message, ) - return } - ToastEventBus.send( - type = Toast.ToastType.SUCCESS, - title = context.getString(_uiState.value.removal.successToast), - ) - _effects.emit(EditProfileEffect.DeleteSuccess) - } else { - val error = requireNotNull(result.exceptionOrNull()) { "Profile delete failed without an error" } - Logger.error("Failed to delete profile", error, context = TAG) - _uiState.update { it.copy(showDeleteFailureDialog = true) } } } finally { - withContext(NonCancellable) { privatePaykitRepo.endProfileDeletion() } - _uiState.update { it.copy(isDeleting = false) } + removalFailure = removalCoordinator.failureFor(confirmation) ?: removalFailure + _uiState.update { + it.copy( + isDeleting = false, + showDeleteFailureDialog = removalFailure != null, + canReviewRemoval = removalFailure?.canReview == true, + ) + } } } + + fun isRemovalCurrent(effect: EditProfileEffect.RemovalCompleted): Boolean = + removalCoordinator.isCurrent(effect.owner) } @Stable @@ -317,12 +347,15 @@ data class EditProfileUiState( val isLoading: Boolean = false, val isSaving: Boolean = false, val isDeleting: Boolean = false, + val isPreparingRemoval: Boolean = false, + val isLocalDisconnect: Boolean = false, + val canReviewRemoval: Boolean = true, val showDeleteDialog: Boolean = false, val showDeleteFailureDialog: Boolean = false, val showAddLinkSheet: Boolean = false, val showAddTagSheet: Boolean = false, ) { - val isBusy: Boolean get() = isSaving || isDeleting + val isBusy: Boolean get() = isSaving || isDeleting || isPreparingRemoval } enum class ProfileRemoval( @@ -362,6 +395,5 @@ enum class ProfileRemoval( sealed interface EditProfileEffect { data object SaveSuccess : EditProfileEffect - data object DeleteSuccess : EditProfileEffect - data object DisconnectSuccess : EditProfileEffect + data class RemovalCompleted(val owner: PubkyProfileOwner) : EditProfileEffect } diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt index 5958a0adab..f46736a047 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt @@ -87,12 +87,12 @@ fun ProfileScreen( LaunchedEffect(Unit) { viewModel.effects.collect { when (it) { - ProfileEffect.SignedOut -> onBackClick() + is ProfileEffect.SignedOut -> if (viewModel.isRemovalCurrent(it)) onBackClick() } } } - Content( + ProfileContent( uiState = uiState, onBackClick = onBackClick, onClickEdit = onEditProfile, @@ -111,7 +111,7 @@ fun ProfileScreen( } @Composable -private fun Content( +internal fun ProfileContent( uiState: ProfileUiState, onBackClick: () -> Unit, onClickEdit: () -> Unit, @@ -139,6 +139,20 @@ private fun Content( } when { + uiState.recoveryPending -> ScreenColumn { + topBar(Modifier) + VerticalSpacer(32.dp) + BodyM(text = stringResource(R.string.profile__cleanup_pending)) + VerticalSpacer(24.dp) + PrimaryButton( + text = stringResource(R.string.profile__sign_out), + onClick = onClickSignOut, + enabled = !uiState.isSigningOut, + modifier = Modifier.testTag("ProfileRecoveryDisconnect"), + ) + if (uiState.isSigningOut) GradientCircularProgressIndicator(Modifier.size(32.dp)) + } + currentProfile != null -> Box(modifier = Modifier.screen()) { ProfileBody( profile = currentProfile, @@ -178,7 +192,13 @@ private fun Content( if (uiState.showSignOutDialog) { AppAlertDialog( title = stringResource(R.string.profile__sign_out_title), - text = stringResource(R.string.profile__sign_out_description), + text = stringResource( + if (uiState.localDisconnect) { + R.string.profile__disconnect_local_description + } else { + R.string.profile__sign_out_description + } + ), confirmText = stringResource(R.string.profile__sign_out), onConfirm = onConfirmSignOut, onDismiss = onDismissSignOutDialog, @@ -461,7 +481,7 @@ private fun EmptyState( @Composable private fun PreviewCached() { AppThemeSurface { - Content( + ProfileContent( uiState = ProfileUiState( cachedProfile = PubkyCachedProfile( publicKey = "pk8e3qm5...gxag", @@ -491,7 +511,7 @@ private fun PreviewCached() { @Composable private fun Preview() { AppThemeSurface { - Content( + ProfileContent( uiState = ProfileUiState( profile = PubkyProfile( publicKey = "pk8e3qm5...gxag", diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt index 4880ed4375..abb6c6af76 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt @@ -7,7 +7,6 @@ import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.Job -import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow @@ -22,16 +21,17 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock -import kotlinx.coroutines.withContext import to.bitkit.R import to.bitkit.data.PubkyCachedProfile -import to.bitkit.ext.runSuspendCatching import to.bitkit.ext.setClipboardText import to.bitkit.models.PubkyProfile import to.bitkit.models.Toast -import to.bitkit.repositories.PrivatePaykitRepo +import to.bitkit.repositories.PubkyProfileOwner import to.bitkit.repositories.PubkyRepo import to.bitkit.ui.shared.toast.ToastEventBus +import to.bitkit.usecases.ProfileRemovalConfirmation +import to.bitkit.usecases.ProfileRemovalCoordinator +import to.bitkit.usecases.ProfileRemovalFailure import to.bitkit.utils.Logger import javax.inject.Inject import kotlin.time.Duration.Companion.seconds @@ -40,13 +40,19 @@ import kotlin.time.Duration.Companion.seconds class ProfileViewModel @Inject constructor( @ApplicationContext private val context: Context, private val pubkyRepo: PubkyRepo, - private val privatePaykitRepo: PrivatePaykitRepo, + private val removalCoordinator: ProfileRemovalCoordinator, ) : ViewModel() { companion object { private const val TAG = "ProfileViewModel" private val COPIED_POPUP_DURATION = 3.seconds } + private var displayedOwner = pubkyRepo.profileOwner() + private var ownerBoundToSession = displayedOwner.signIn != null + private var removalConfirmation: ProfileRemovalConfirmation? = null + private var removalFailure: ProfileRemovalFailure? = null + private var preparationRevision = 0L + private val _localDisconnect = MutableStateFlow(false) private val _showSignOutDialog = MutableStateFlow(false) private val _isSigningOut = MutableStateFlow(false) private val _showAddTagSheet = MutableStateFlow(false) @@ -63,13 +69,23 @@ class ProfileViewModel @Inject constructor( pubkyRepo.isRestoringSession, _isRefreshing, ) { loading, restoring, refreshing -> loading || restoring || refreshing } - private val controls = combine( + private val dialogControls = combine( _showSignOutDialog, _isSigningOut, _showAddTagSheet, _copiedPublicKey, ) { showSignOutDialog, isSigningOut, showAddTagSheet, copiedPublicKey -> - ProfileControls(showSignOutDialog, isSigningOut, showAddTagSheet, copiedPublicKey) + ProfileControls( + showSignOutDialog = showSignOutDialog, + isSigningOut = isSigningOut, + showAddTagSheet = showAddTagSheet, + copiedPublicKey = copiedPublicKey + ) + } + + private val controls = combine(dialogControls, pubkyRepo.profileRecoveryPending, _localDisconnect) { + controls, pending, localOnly -> + controls.copy(recoveryPending = pending, localDisconnect = localOnly) } init { @@ -92,7 +108,7 @@ class ProfileViewModel @Inject constructor( publicKey = pubkyRepo.publicKey.value, isLoading = pubkyRepo.isLoadingProfile.value || pubkyRepo.isRestoringSession.value || _isRefreshing.value, cachedProfile = pubkyRepo.cachedProfile.value, - controls = ProfileControls(), + controls = ProfileControls(recoveryPending = pubkyRepo.profileRecoveryPending.value), ), ) @@ -122,7 +138,7 @@ class ProfileViewModel @Inject constructor( profileLoadJob = viewModelScope.launch { _isRefreshing.update { true } try { - load() + if (pubkyRepo.profileRecoveryPending.first { it != null } == false) load() } finally { _isRefreshing.update { false } } @@ -130,11 +146,36 @@ class ProfileViewModel @Inject constructor( } fun showSignOutConfirmation() { - _showSignOutDialog.update { true } + if (_isSigningOut.value) return + val owner = uiState.value.owner ?: return + val revision = ++preparationRevision + _isSigningOut.value = true + viewModelScope.launch { + try { + val failure = removalFailure + val result = if (failure != null) { + removalCoordinator.prepareLocalDisconnect(failure) + } else { + removalCoordinator.prepareSignOut(owner) + } + result.onSuccess { confirmation -> + if (revision != preparationRevision || !removalCoordinator.isCurrent(confirmation.owner)) { + return@onSuccess + } + removalConfirmation = confirmation + _localDisconnect.value = confirmation.localOnly + _showSignOutDialog.value = true + }.onFailure { showRemovalError(it) } + } finally { + _isSigningOut.value = false + } + } } fun dismissSignOutDialog() { - _showSignOutDialog.update { false } + preparationRevision++ + removalConfirmation = null + _showSignOutDialog.value = false } fun showAddTagSheet() { @@ -157,35 +198,37 @@ class ProfileViewModel @Inject constructor( } fun signOut() { + if (_isSigningOut.value) return + val confirmation = removalConfirmation ?: return + removalConfirmation = null + _isSigningOut.value = true + _showSignOutDialog.value = false viewModelScope.launch { - if (_isSigningOut.value) return@launch - _isSigningOut.update { true } - _showSignOutDialog.update { false } try { - val result = runSuspendCatching { - withContext(NonCancellable) { - if (!pubkyRepo.forgetUnrestoredIdentity().getOrThrow()) { - privatePaykitRepo.removePublishedEndpointsForCleanup(TAG).getOrThrow() - pubkyRepo.signOut().getOrThrow() - } - privatePaykitRepo.closeAndClear() - } - } - if (result.isSuccess) { - _effects.emit(ProfileEffect.SignedOut) - } else { - ToastEventBus.send( - type = Toast.ToastType.ERROR, - title = context.getString(R.string.profile__sign_out_title), - description = result.exceptionOrNull()?.message, - ) + removalCoordinator.remove(confirmation).onSuccess { endedOwner -> + removalFailure = null + if (removalCoordinator.isCurrent(endedOwner)) _effects.emit(ProfileEffect.SignedOut(endedOwner)) + }.onFailure { + removalFailure = (it as? ProfileRemovalFailure) ?: removalFailure + showRemovalError(it) } } finally { - _isSigningOut.update { false } + removalFailure = removalCoordinator.failureFor(confirmation) ?: removalFailure + _isSigningOut.value = false } } } + fun isRemovalCurrent(effect: ProfileEffect.SignedOut): Boolean = removalCoordinator.isCurrent(effect.owner) + + private suspend fun showRemovalError(error: Throwable) { + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.profile__sign_out_title), + description = error.message, + ) + } + fun copyPublicKey() { val pk = pubkyRepo.publicKey.value ?: pubkyRepo.readOnlyProfile.value?.publicKey ?: return context.setClipboardText(pk, context.getString(R.string.profile__public_key)) @@ -208,17 +251,32 @@ class ProfileViewModel @Inject constructor( isLoading: Boolean, cachedProfile: PubkyCachedProfile?, controls: ProfileControls, - ) = ProfileUiState( - profile = profile, - cachedProfile = cachedProfile?.takeIf { isLoading && it.publicKey == publicKey }, - publicKey = publicKey ?: profile?.publicKey, - canEdit = publicKey != null && publicKey == pubkyRepo.profile.value?.publicKey, - isLoading = isLoading, - showSignOutDialog = controls.showSignOutDialog, - isSigningOut = controls.isSigningOut, - showAddTagSheet = controls.showAddTagSheet, - copiedPublicKey = controls.copiedPublicKey, - ) + ): ProfileUiState { + if (!ownerBoundToSession) { + val restoredOwner = pubkyRepo.profileOwner() + if (restoredOwner.storedRevision == displayedOwner.storedRevision && restoredOwner.signIn != null) { + displayedOwner = restoredOwner + ownerBoundToSession = true + } + } + return ProfileUiState( + profile = profile?.takeIf { controls.recoveryPending == false }, + cachedProfile = cachedProfile?.takeIf { + controls.recoveryPending == false && isLoading && it.publicKey == publicKey + }, + publicKey = publicKey ?: profile?.publicKey, + canEdit = controls.recoveryPending == false && publicKey != null && + publicKey == pubkyRepo.profile.value?.publicKey, + isLoading = controls.recoveryPending == null || (controls.recoveryPending == false && isLoading), + recoveryPending = controls.recoveryPending == true, + localDisconnect = controls.localDisconnect, + owner = displayedOwner, + showSignOutDialog = controls.showSignOutDialog, + isSigningOut = controls.isSigningOut, + showAddTagSheet = controls.showAddTagSheet, + copiedPublicKey = controls.copiedPublicKey, + ) + } private fun updateTags( transform: (List) -> List, @@ -226,6 +284,7 @@ class ProfileViewModel @Inject constructor( ) { viewModelScope.launch { tagUpdateMutex.withLock { + if (pubkyRepo.profileRecoveryPending.value != false) return@withLock val profile = pubkyRepo.profile.value ?: return@withLock val tags = transform(profile.tags) if (tags == profile.tags) { @@ -260,6 +319,9 @@ data class ProfileUiState( val cachedProfile: PubkyCachedProfile? = null, val publicKey: String? = null, val canEdit: Boolean = false, + val recoveryPending: Boolean = false, + val localDisconnect: Boolean = false, + val owner: PubkyProfileOwner? = null, val isLoading: Boolean = true, val showSignOutDialog: Boolean = false, val isSigningOut: Boolean = false, @@ -268,6 +330,8 @@ data class ProfileUiState( ) private data class ProfileControls( + val recoveryPending: Boolean? = null, + val localDisconnect: Boolean = false, val showSignOutDialog: Boolean = false, val isSigningOut: Boolean = false, val showAddTagSheet: Boolean = false, @@ -275,5 +339,5 @@ private data class ProfileControls( ) sealed interface ProfileEffect { - data object SignedOut : ProfileEffect + data class SignedOut(val owner: PubkyProfileOwner) : ProfileEffect } diff --git a/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt b/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt new file mode 100644 index 0000000000..a6c1757934 --- /dev/null +++ b/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt @@ -0,0 +1,169 @@ +package to.bitkit.usecases + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.withContext +import to.bitkit.data.ProfileRemovalStore +import to.bitkit.ext.runSuspendCatching +import to.bitkit.repositories.ContactPaymentSettingsRepo +import to.bitkit.repositories.PrivatePaykitRepo +import to.bitkit.repositories.PubkyProfileDeletion +import to.bitkit.repositories.PubkyProfileOwner +import to.bitkit.repositories.PubkyRepo +import to.bitkit.utils.AppError +import java.util.UUID +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference +import javax.inject.Inject +import javax.inject.Singleton + +/** One confirmation belongs to one identity and may start destructive work at most once. */ +class ProfileRemovalConfirmation internal constructor( + internal val owner: PubkyProfileOwner, + internal val attemptId: String, + internal val deletion: PubkyProfileDeletion?, + internal val localOnly: Boolean, + internal val reviewCeiling: AtomicReference = AtomicReference(deletion), +) { + internal val used = AtomicBoolean(false) + internal val failure = AtomicReference(null) +} + +class ProfileRemovalFailure internal constructor( + cause: Throwable, + internal val confirmation: ProfileRemovalConfirmation, + internal val recoveryOwner: PubkyProfileOwner, + internal val localCompletionStarted: Boolean, +) : AppError("Profile removal did not finish. Review its state or disconnect locally.", cause) { + internal val canReview: Boolean get() = confirmation.deletion != null && !localCompletionStarted +} + +/** Remote work never resumes automatically from the durable local cleanup obligation. */ +@Singleton +class ProfileRemovalCoordinator @Inject constructor( + private val pubkyRepo: PubkyRepo, + private val privatePaykitRepo: PrivatePaykitRepo, + private val sharingRepo: ContactPaymentSettingsRepo, + private val removalStore: ProfileRemovalStore, +) { + suspend fun prepareDeletion(owner: PubkyProfileOwner): Result = runSuspendCatching { + removalStore.requireNoPending() + check(pubkyRepo.isProfileOwnerCurrent(owner)) { "The profile identity changed" } + val deletion = pubkyRepo.prepareProfileDeletion(owner).getOrThrow() + removalStore.requireNoPending() + check(pubkyRepo.isProfileOwnerCurrent(owner)) { "The profile identity changed" } + ProfileRemovalConfirmation(owner, UUID.randomUUID().toString(), deletion, localOnly = false) + } + + suspend fun prepareSignOut(owner: PubkyProfileOwner): Result = runSuspendCatching { + check(pubkyRepo.isProfileOwnerCurrent(owner)) { "The profile identity changed" } + val pending = removalStore.pendingAttempt() + check(pubkyRepo.isProfileOwnerCurrent(owner)) { "The profile identity changed" } + ProfileRemovalConfirmation( + owner, + pending ?: UUID.randomUUID().toString(), + deletion = null, + localOnly = pending != null || owner.signIn == null, + ) + } + + /** Re-read the original identity's remote state, then require a new user confirmation. */ + suspend fun reviewAgain(failure: ProfileRemovalFailure): Result = runSuspendCatching { + check(!failure.localCompletionStarted) { "Finish disconnecting this profile locally" } + val previous = failure.confirmation + check(previous.deletion != null) { "Disconnect this profile locally to finish cleanup" } + var deletion: PubkyProfileDeletion? = null + pubkyRepo.performProfileRemoval(previous.owner, previous.attemptId) { + val fresh = pubkyRepo.prepareProfileDeletion(previous.owner).getOrThrow() + val confirmed = checkNotNull(previous.reviewCeiling.get()).snapshot + val remaining = fresh.snapshot + check(remaining.publicKey == confirmed.publicKey) { "The profile identity changed" } + check(remaining.profileRevision == null || remaining.profileRevision == confirmed.profileRevision) { + "The profile changed after confirmation. Disconnect locally to finish cleanup." + } + check(confirmed.contacts.containsAll(remaining.contacts)) { + "Contacts changed after confirmation. Disconnect locally to finish cleanup." + } + // Missing records leave this attempt's scope; later reviews cannot add them back. + previous.reviewCeiling.set(fresh) + deletion = fresh + }.getOrThrow() + ProfileRemovalConfirmation( + previous.owner, + previous.attemptId, + deletion, + previous.localOnly, + previous.reviewCeiling + ) + } + + suspend fun prepareLocalDisconnect(failure: ProfileRemovalFailure): Result = + runSuspendCatching { + val pending = removalStore.pendingAttempt() + check(pending == null || pending == failure.confirmation.attemptId) { + "The pending profile cleanup changed" + } + check(pubkyRepo.isProfileOwnerCurrent(failure.recoveryOwner)) { "The profile identity changed" } + ProfileRemovalConfirmation( + failure.recoveryOwner, + failure.confirmation.attemptId, + deletion = null, + localOnly = true, + reviewCeiling = failure.confirmation.reviewCeiling, + ) + } + + suspend fun remove(confirmation: ProfileRemovalConfirmation): Result = runSuspendCatching { + check(confirmation.used.compareAndSet(false, true)) { "Review this profile removal before trying again" } + sharingRepo.withProfileRemoval { + pubkyRepo.performProfileRemoval(confirmation.owner, confirmation.attemptId) { + var localCompletionStarted = false + try { + check(confirmation.deletion == null || confirmation.reviewCeiling.get() === confirmation.deletion) { + "This confirmation was replaced by a later review" + } + privatePaykitRepo.withProfileDeletionPaused { pause -> + confirmation.deletion?.let { pubkyRepo.validateProfileDeletion(it) } + removalStore.begin(confirmation.attemptId) + if (!confirmation.localOnly) { + privatePaykitRepo.removePublishedEndpointsForCleanup(TAG, deferAppSync = true).getOrThrow() + pubkyRepo.removeBitkitPaymentEndpoints().getOrThrow() + confirmation.deletion?.let { pubkyRepo.deleteProfile(it).getOrThrow() } + pubkyRepo.signOutForProfileRemoval() + } + localCompletionStarted = true + pubkyRepo.finishProfileRemovalLocally() + withContext(NonCancellable) { + privatePaykitRepo.finishProfileRemoval(pause).getOrThrow() + removalStore.complete(confirmation.attemptId) + } + } + } catch (error: CancellationException) { + captureFailure(error, confirmation, localCompletionStarted) + throw error + } catch (error: Throwable) { + throw captureFailure(error, confirmation, localCompletionStarted) + } + }.getOrThrow() + } + } + + private fun captureFailure( + error: Throwable, + confirmation: ProfileRemovalConfirmation, + localCompletionStarted: Boolean, + ): ProfileRemovalFailure { + // Admission still excludes replacements, even when our own cleanup has ended the sign-in. + val failure = ProfileRemovalFailure(error, confirmation, pubkyRepo.profileOwner(), localCompletionStarted) + confirmation.failure.set(failure) + return failure + } + + fun failureFor(confirmation: ProfileRemovalConfirmation): ProfileRemovalFailure? = confirmation.failure.get() + + fun isCurrent(owner: PubkyProfileOwner): Boolean = pubkyRepo.isProfileOwnerCurrent(owner) + + private companion object { + const val TAG = "ProfileRemovalCoordinator" + } +} diff --git a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt index 96307eaaf4..4262c8933c 100644 --- a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt @@ -4,6 +4,7 @@ import com.google.firebase.messaging.FirebaseMessaging import kotlinx.coroutines.sync.Mutex import to.bitkit.data.AppDb import to.bitkit.data.CacheStore +import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.SettingsStore import to.bitkit.data.WidgetsStore import to.bitkit.data.keychain.Keychain @@ -11,6 +12,7 @@ import to.bitkit.ext.runSuspendCatching import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.BackupRepo import to.bitkit.repositories.BlocktankRepo +import to.bitkit.repositories.ContactPaymentSettingsRepo import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.PaykitUsdtPaymentRepo @@ -24,6 +26,7 @@ import to.bitkit.services.MigrationService import to.bitkit.services.PaykitSdkService import to.bitkit.utils.AppError import to.bitkit.utils.Logger +import java.util.UUID import javax.inject.Inject import javax.inject.Provider import javax.inject.Singleton @@ -50,6 +53,8 @@ class WipeWalletUseCase @Inject constructor( private val paykitSdkService: PaykitSdkService, private val usdtRepo: UsdtRepo, private val paykitUsdtPaymentRepo: PaykitUsdtPaymentRepo, + private val profileRemovalStore: ProfileRemovalStore, + private val contactPaymentSettingsRepo: Provider, ) { private val wipeMutex = Mutex() @@ -63,11 +68,22 @@ class WipeWalletUseCase @Inject constructor( lightningRepo.setWiping(true) val result = try { runSuspendCatching { - paykitSdkService.withWalletWipe { - stopNode().getOrThrow() - cleanupRemote() - wipeLocal(walletIndex, resetWalletState).getOrThrow() - onSuccess() + contactPaymentSettingsRepo.get().withWalletWipe(pubkyRepo::withWalletWipeAdmission) { + paykitSdkService.withWalletWipe { + val pending = profileRemovalStore.pendingAttempt() + val attemptId = pending ?: UUID.randomUUID().toString() + profileRemovalStore.withAccess(attemptId) { + privatePaykitRepo.get().withProfileDeletionPaused { pause -> + stopNode().getOrThrow() + profileRemovalStore.begin(attemptId) + if (pending == null) cleanupRemote() + wipeLocal(walletIndex, pause).getOrThrow() + profileRemovalStore.complete(attemptId) + resetWalletState() + onSuccess() + } + } + } } } } finally { @@ -91,30 +107,34 @@ class WipeWalletUseCase @Inject constructor( private suspend fun cleanupRemote() { step("remove Paykit published endpoints") { privatePaykitRepo.get().removePublishedEndpointsForCleanup(TAG) } step("remove Bitkit payment endpoints") { pubkyRepo.removeBitkitPaymentEndpoints() } - step("close Paykit SDK") { privatePaykitRepo.get().closeAndClear() } } - private suspend fun wipeLocal(walletIndex: Int, resetWalletState: () -> Unit): Result { + private suspend fun wipeLocal( + walletIndex: Int, + pause: PrivatePaykitRepo.ProfileDeletionPause, + ): Result { lightningRepo.wipeStorage(walletIndex).onFailure { return Result.failure(it) } step("clear post-migration sync flag") { migrationService.setNeedsPostMigrationSync(false) } step("clear migration data") { migrationService.cleanupAfterMigration() } - step("clear Paykit address reservations") { privatePaykitAddressReservationRepo.clear() } - step("wipe Pubky local state") { pubkyRepo.wipeLocalState() } - val keychainWiped = step("wipe USDT and keychain") { usdtRepo.wipe { keychain.wipe() } } - if (keychainWiped) paykitUsdtPaymentRepo.resetForWipe() + runSuspendCatching { usdtRepo.wipe { keychain.wipe() }.getOrThrow() } + .getOrElse { return Result.failure(WipeIncomplete(it)) } + paykitUsdtPaymentRepo.resetForWipe() + // Consumption watermarks survive until the keychain wipe is acknowledged. Pending remains on any failure. + privatePaykitRepo.get().finishProfileRemoval(pause).getOrElse { return Result.failure(it) } + pubkyRepo.finishProfileWipeLocally() + privatePaykitAddressReservationRepo.clear() step("delete FCM token") { firebaseMessaging.deleteToken() } step("wipe core data") { coreService.wipeData() } step("clear database") { db.clearAllTables() } - step("reset settings") { settingsStore.reset() } + settingsStore.reset() step("reset cache") { cacheStore.reset() } step("clear watch-only accounts") { watchOnlyAccountRepo.clear() } step("reset widgets") { widgetsStore.reset() } blocktankRepo.resetState() activityRepo.resetState() hwWalletRepo.resetState() - resetWalletState() step("mark migration checked") { migrationService.markMigrationChecked() } - return if (keychainWiped) Result.success(Unit) else Result.failure(WipeIncomplete()) + return Result.success(Unit) } private suspend fun step(name: String, block: suspend () -> Any?): Boolean = @@ -130,4 +150,4 @@ class WipeWalletUseCase @Inject constructor( class WipeAlreadyInProgress : AppError("Wallet wipe already in progress") -class WipeIncomplete : AppError("Wallet wipe did not complete, please reset again") +class WipeIncomplete(cause: Throwable? = null) : AppError("Wallet wipe did not complete, please reset again", cause) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index ef470a7fd4..6230654695 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -3415,7 +3415,7 @@ class AppViewModel @Inject constructor( val timeout = if (isContactLink) PubkyService.AUTHORIZATION_TIMEOUT else PUBKY_AUTH_DEEPLINK_TIMEOUT val isInitializationReady = withTimeoutOrNull(timeout) { pubkyRepo.awaitInitialization() - if (!isContactLink) awaitPubkyAuthIdentity() + if (!isContactLink && !awaitPubkyAuthIdentity()) return@withTimeoutOrNull false awaitContactDataForDeeplink(isContactLink) } ?: false if (!isInitializationReady) { @@ -3444,19 +3444,28 @@ class AppViewModel @Inject constructor( return isPaykitUiEnabledFromSettings() && walletRepo.walletExists() } - private suspend fun awaitPubkyAuthIdentity() { - while (pubkyRepo.awaitIdentityReady() == PubkyIdentityReadiness.Unavailable) { - if (isOnline.value == ConnectivityState.CONNECTED && pubkyRepo.localIdentityPublicKey() != null) { - Logger.debug("Continuing sign-in link with the stored Pubky key", context = TAG) - return + private suspend fun awaitPubkyAuthIdentity(): Boolean { + while (true) { + when (pubkyRepo.awaitIdentityReady()) { + PubkyIdentityReadiness.RecoveryRequired -> return false + PubkyIdentityReadiness.Ready, PubkyIdentityReadiness.Missing -> return true + PubkyIdentityReadiness.Unavailable -> { + if (pubkyRepo.requiresProfileRecovery()) return false + if (isOnline.value == ConnectivityState.CONNECTED && pubkyRepo.localIdentityPublicKey() != null) { + return !pubkyRepo.requiresProfileRecovery() + } + delay(PUBKY_AUTH_DEEPLINK_RETRY_INTERVAL) + // A pending local cleanup must end this wait even while connectivity stays offline. + combine(isOnline, pubkyRepo.profileRecoveryPending) { online, pending -> + online == ConnectivityState.CONNECTED || pending == true + }.first { it } + } } - delay(PUBKY_AUTH_DEEPLINK_RETRY_INTERVAL) - isOnline.first { it == ConnectivityState.CONNECTED } - Logger.debug("Retrying Pubky session restore for a sign-in link", context = TAG) } } private suspend fun showPubkyAuthWaitToastIfRestoring() { + if (pubkyRepo.requiresProfileRecovery()) return if (pubkyRepo.publicKey.value != null) return if (!isPaykitUiEnabledFromSettings() || !walletRepo.walletExists()) return if (!runSuspendCatching { pubkyRepo.hasIdentity() }.getOrDefault(false)) return @@ -7060,6 +7069,11 @@ class AppViewModel @Inject constructor( } // A stale amount above inbound liquidity would hide the Auto tab until the receive state refreshes if (sheetType is Sheet.Receive) walletRepo.setBip21AmountSats(null) + if (sheetType is Sheet.PubkyAuth && pubkyRepo.requiresProfileRecovery()) { + hidePubkyAuthWaitToast() + showPubkyIdentityUnavailableToast() + return@launch + } _currentSheet.update { sheetType } } sheetTransitionJob = nextJob @@ -8101,6 +8115,7 @@ class AppViewModel @Inject constructor( } private suspend fun handlePubkyAuth(authUrl: String) { + if (pubkyRepo.requiresProfileRecovery()) return showPubkyIdentityUnavailableToast() val isSignup = PubkyAuthRequest.isSignupUrl(authUrl) val createsIdentity = isSignup && ( @@ -8109,12 +8124,14 @@ class AppViewModel @Inject constructor( ) if (createsIdentity) { if (rejectPubkySignupForExistingIdentity()) return + if (pubkyRepo.requiresProfileRecovery()) return showPubkyIdentityUnavailableToast() showSheet(Sheet.PubkyAuth(authUrl)) return } if (pubkyRepo.publicKey.value == null) { if (pubkyRepo.localIdentityPublicKey() == null) return showPubkyIdentityUnavailableToast() + if (pubkyRepo.requiresProfileRecovery()) return showPubkyIdentityUnavailableToast() showSheet(Sheet.PubkyAuth(authUrl)) return } @@ -8127,10 +8144,20 @@ class AppViewModel @Inject constructor( ) return } + if (pubkyRepo.requiresProfileRecovery()) return showPubkyIdentityUnavailableToast() showSheet(Sheet.PubkyAuth(authUrl)) } private suspend fun showPubkyIdentityUnavailableToast() { + if (pubkyRepo.requiresProfileRecovery()) { + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.profile__nav_title), + description = context.getString(R.string.profile__cleanup_pending), + visibilityTime = Toast.VISIBILITY_TIME_LONG, + ) + return + } val hasIdentity = runSuspendCatching { pubkyRepo.hasIdentity() }.getOrDefault(true) if (hasIdentity) { ToastEventBus.send( diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 23f52e9523..36ca05763b 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -435,9 +435,13 @@ إضافة علامة التفاصيل حسنًا + لم يكتمل تنظيف الملف الشخصي. افصل الاتصال محليًا لإزالة وصول هذا الجهاز دون إعادة محاولة الحذف عن بُعد. إنشاء ملف شخصي + قد تكون بعض التغييرات قد اكتملت. راجع الحالة الحالية قبل التأكيد مجددًا، أو افصل الاتصال محليًا. + أزل وصول هذا الجهاز وأكمل التنظيف المحلي. لن يؤدي هذا إلى حذف الملف الشخصي من Pubky. الملف الشخصي حاول مرة أخرى + مراجعة اقتراحات نسخ احتياطي الآن بعد أن لديك بعض الأموال في محفظتك، حان وقت عمل نسخة احتياطية! diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 854b902b00..8a7fe9ce1b 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -447,10 +447,14 @@ Autorizar Detalles Autorizar + La limpieza del perfil está incompleta. Desconéctate localmente para retirar el acceso de este dispositivo sin volver a intentar la eliminación remota. Crear perfil + Es posible que algunos cambios se hayan completado. Revisa el estado actual antes de confirmar de nuevo o desconéctate localmente. + Retira el acceso de este dispositivo y completa la limpieza local. Esto no elimina el perfil de Pubky. Editar Perfil Perfil Inténtelo de nuevo + Revisar Sugerencias Sugerencias para añadir Sí, desvincular diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index bfcc033901..c1f4679a8e 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -441,10 +441,14 @@ Nota: Qualsevol enllaç que afegiu serà visible públicament. Afegeix etiqueta Detalls + La neteja del perfil és incompleta. Desconnecta localment per eliminar l’accés d’aquest dispositiu sense tornar a intentar la supressió remota. Crear perfil + És possible que alguns canvis s’hagin completat. Revisa l’estat actual abans de tornar a confirmar, o desconnecta localment. + Elimina l’accés d’aquest dispositiu i completa la neteja local. Això no suprimeix el perfil de Pubky. Editar perfil Perfil Torna a intentar + Revisa Suggeriments Sí, desvincula Això eliminarà les teves dades de Paykit i desvincularà aquest pubky de Bitkit. Continuarà disponible a Pubky Ring. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index ec26262d2b..fac03ac310 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -446,10 +446,14 @@ Autorizovat Podrobnosti Autorizovat + Vyčištění profilu není dokončeno. Odpojte se místně a odeberte přístup tohoto zařízení bez dalšího pokusu o vzdálené smazání. Vytvořit profil + Některé změny již mohly být dokončeny. Před dalším potvrzením zkontrolujte aktuální stav nebo se odpojte místně. + Odeberte přístup tohoto zařízení a dokončete místní vyčištění. Tím se profil z Pubky nesmaže. Upravit profil Profil Zkusit znovu + Zkontrolovat Návrhy Ano, zrušit propojení Tímto smažete svá data Paykit a zrušíte propojení tohoto pubky s Bitkitem. V Pubky Ring zůstane k dispozici. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 862f4f1b0c..4a93e1f5b4 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -427,10 +427,14 @@ Tag hinzufügen Autorisieren Sie Autorisieren Sie + Die Profilbereinigung ist unvollständig. Trenne die Verbindung lokal, um den Zugriff dieses Geräts zu entfernen, ohne die entfernte Löschung erneut zu versuchen. Profil erstellen + Einige Änderungen wurden möglicherweise abgeschlossen. Prüfe den aktuellen Stand vor einer erneuten Bestätigung oder trenne die Verbindung lokal. + Entferne den Zugriff dieses Geräts und schließe die lokale Bereinigung ab. Dadurch wird das Profil nicht aus Pubky gelöscht. Profil bearbeiten Profil Erneut versuchen + Prüfen Vorschläge Ja, aufheben Dadurch werden deine Paykit-Daten gelöscht und die Verknüpfung dieses pubky mit Bitkit aufgehoben. In Pubky Ring bleibt er weiterhin verfügbar. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 273e174438..f5bc116b80 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -436,9 +436,13 @@ Προσθήκη ετικέτας Λεπτομέρειες ΟΚ + Η εκκαθάριση του προφίλ δεν ολοκληρώθηκε. Αποσυνδεθείτε τοπικά για να καταργήσετε την πρόσβαση αυτής της συσκευής χωρίς νέα προσπάθεια απομακρυσμένης διαγραφής. Δημιουργία προφίλ + Ορισμένες αλλαγές ενδέχεται να έχουν ολοκληρωθεί. Ελέγξτε την τρέχουσα κατάσταση πριν επιβεβαιώσετε ξανά ή αποσυνδεθείτε τοπικά. + Καταργήστε την πρόσβαση αυτής της συσκευής και ολοκληρώστε την τοπική εκκαθάριση. Αυτό δεν διαγράφει το προφίλ από το Pubky. Προφίλ Προσπαθήστε Ξανά + Έλεγχος Προτάσεις Αντίγραφο ασφαλείας Τώρα που έχεις κεφάλαια στο πορτοφόλι σου, ήρθε η ώρα να δημιουργήσεις αντίγραφο ασφαλείας των χρημάτων σου! diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 558a020922..610788ed11 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -444,10 +444,14 @@ Nota: Cualquier enlace que añada será públicamente visible. Añadir etiqueta Detalles + La limpieza del perfil está incompleta. Desconéctate localmente para retirar el acceso de este dispositivo sin volver a intentar la eliminación remota. Crear perfil + Es posible que algunos cambios se hayan completado. Revisa el estado actual antes de confirmar de nuevo o desconéctate localmente. + Retira el acceso de este dispositivo y completa la limpieza local. Esto no elimina el perfil de Pubky. Editar Perfil Perfil Inténtelo de nuevo + Revisar Sugerencias Sugerencias para añadir Sí, desvincular diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 5224935de6..7c24c2c224 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -441,10 +441,14 @@ Nota: Cualquier enlace que añada será públicamente visible. Añadir etiqueta Detalles + La limpieza del perfil está incompleta. Desconéctate localmente para retirar el acceso de este dispositivo sin volver a intentar la eliminación remota. Crear perfil + Es posible que algunos cambios se hayan completado. Revisa el estado actual antes de confirmar de nuevo o desconéctate localmente. + Retira el acceso de este dispositivo y completa la limpieza local. Esto no elimina el perfil de Pubky. Editar Perfil Perfil Inténtelo de nuevo + Revisar Sugerencias Sugerencias para añadir Sí, desvincular diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 06a89e56bd..be6028811c 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -420,10 +420,14 @@ Autoriser Détails Autoriser + Le nettoyage du profil est incomplet. Déconnectez-vous localement pour retirer l’accès de cet appareil sans réessayer la suppression à distance. Créer un profil + Certaines modifications ont peut-être été effectuées. Vérifiez l’état actuel avant de confirmer à nouveau, ou déconnectez-vous localement. + Retirez l’accès de cet appareil et terminez le nettoyage local. Cela ne supprime pas le profil de Pubky. Modifier le profil Profil Réessayer + Vérifier Suggestions à ajouter Oui, dissocier Cela supprimera vos données Paykit et dissociera ce pubky de Bitkit. Il restera disponible dans Pubky Ring. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index e0ebc9f571..2b0a71aa11 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -443,10 +443,14 @@ Nota: qualsiasi link aggiunto sarà visibile pubblicamente. Aggiungi Tag Dettagli + La pulizia del profilo è incompleta. Disconnettiti localmente per rimuovere l’accesso di questo dispositivo senza ritentare l’eliminazione remota. Crea Profilo + Alcune modifiche potrebbero essere state completate. Verifica lo stato attuale prima di confermare di nuovo, oppure disconnettiti localmente. + Rimuovi l’accesso di questo dispositivo e completa la pulizia locale. Il profilo non verrà eliminato da Pubky. Modifica Profilo Profilo Riprova + Verifica Consigli Suggerimenti Da Aggiungere Sì, Scollega diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index de56a9473b..6610fa0ede 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -441,10 +441,14 @@ Bijvoorbeeld \'Website\' Let op: Iedere link die u toevoegt is openbaar beschikbaar. Tag toevoegen + Het opschonen van het profiel is niet voltooid. Verbreek lokaal de verbinding om de toegang van dit apparaat te verwijderen zonder de verwijdering op afstand opnieuw te proberen. Profiel aanmaken + Sommige wijzigingen zijn mogelijk voltooid. Controleer de huidige status voordat je opnieuw bevestigt, of verbreek lokaal de verbinding. + Verwijder de toegang van dit apparaat en voltooi het lokaal opschonen. Dit verwijdert het profiel niet uit Pubky. Profiel Bewerken Profiel Probeer opnieuw + Controleren Suggesties Suggesties Om Toe Te Voegen Ja, ontkoppelen diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 64f2590831..dd5a29a305 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -420,10 +420,14 @@ Autoryzuj Szczegóły Autoryzuj + Czyszczenie profilu nie zostało ukończone. Odłącz się lokalnie, aby usunąć dostęp tego urządzenia bez ponawiania zdalnego usuwania. Utwórz profil + Niektóre zmiany mogły zostać ukończone. Sprawdź bieżący stan przed ponownym potwierdzeniem lub odłącz się lokalnie. + Usuń dostęp tego urządzenia i dokończ lokalne czyszczenie. Nie spowoduje to usunięcia profilu z Pubky. Edytuj profil Profil Spróbuj ponownie + Sprawdź Sugestie Sugestie do dodania Tak, odłącz diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index af9986b902..88fcdc1761 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -448,10 +448,14 @@ Autorizar Detalhes Autorizar + A limpeza do perfil está incompleta. Desconecte-se localmente para remover o acesso deste dispositivo sem tentar novamente a exclusão remota. Criar Perfil + Algumas alterações podem ter sido concluídas. Revise o estado atual antes de confirmar novamente ou desconecte-se localmente. + Remova o acesso deste dispositivo e conclua a limpeza local. Isso não exclui o perfil do Pubky. Editar perfil Perfil Tente novamente + Revisar Sugestões Sugestões Para Adicionar Sim, Desvincular diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index e49a4a0d16..06fd782814 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -398,9 +398,13 @@ Atualizar\n<accent>Bitkit</accent> Adicionar Tag Detalhes + A limpeza do perfil está incompleta. Desligue-se localmente para remover o acesso deste dispositivo sem voltar a tentar a eliminação remota. Criar Perfil + Algumas alterações poderão ter sido concluídas. Reveja o estado atual antes de confirmar novamente ou desligue-se localmente. + Remova o acesso deste dispositivo e conclua a limpeza local. Isto não elimina o perfil do Pubky. Perfil Tente novamente + Rever Sugestões Atualize a Bitkit para obter novos recursos e correções de bugs! Atualizar diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 7f841901c8..4b2a54d235 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -463,10 +463,14 @@ Подробности Ок Авторизовать + Очистка профиля не завершена. Отключитесь локально, чтобы убрать доступ этого устройства без повторной попытки удалённого удаления. Создать Профиль + Некоторые изменения могли быть выполнены. Проверьте текущее состояние перед повторным подтверждением или отключитесь локально. + Уберите доступ этого устройства и завершите локальную очистку. Профиль в Pubky удалён не будет. Редактировать Профиль Профиль Попробовать снова + Проверить Рекомендации Рекомендации для добавления Да, Отвязать diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ab3c0af5e3..c841328888 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -689,6 +689,7 @@ Use an existing pubky from Pubky Ring. Loading your profile… Enter the\n<accent>freedom web</accent> + Profile cleanup is incomplete. Disconnect locally to remove this device’s access without retrying remote deletion. Failed to create profile Create Profile Deleting your profile removes it from Pubky. Contacts may still retain profile and payment information previously shared with them. @@ -696,9 +697,11 @@ We couldn\'t delete your profile data. Retry, or disconnect this pubky from Bitkit. Unable to Delete Profile Delete Profile + Some changes may have completed. Review the current state before confirming again, or disconnect locally. Profile deleted Deriving your keys… Failed to disconnect profile + Remove this device’s access and finish local cleanup. This does not delete the profile from Pubky. BIO Short note. Tell a bit about yourself. DELETE @@ -725,6 +728,7 @@ Public Key Restore Profile Try Again + Review Your profile session has expired. Please reconnect to restore your profile. Disconnect This will disconnect your Pubky profile from Bitkit. You can reconnect at any time. diff --git a/app/src/test/java/to/bitkit/data/ProfileRemovalStoreTest.kt b/app/src/test/java/to/bitkit/data/ProfileRemovalStoreTest.kt new file mode 100644 index 0000000000..476cc1375d --- /dev/null +++ b/app/src/test/java/to/bitkit/data/ProfileRemovalStoreTest.kt @@ -0,0 +1,203 @@ +package to.bitkit.data + +import androidx.datastore.core.CorruptionException +import androidx.datastore.core.DataStore +import androidx.datastore.core.DataStoreFactory +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.emitAll +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withContext +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.ByteArrayInputStream +import java.io.IOException +import java.util.UUID +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +@OptIn(ExperimentalCoroutinesApi::class) +class ProfileRemovalStoreTest { + @get:Rule + val folder = TemporaryFolder() + + @Test + fun `observation fails closed with bounded retries and restarts after explicit durable completion`() = runTest { + val id = UUID.randomUUID().toString() + val state = MutableStateFlow(ProfileRemovalState(attemptId = id)) + var unavailable = true + var reads = 0 + val store = ProfileRemovalStore(object : DataStore { + override val data = flow { + reads++ + if (unavailable) throw IOException("Local storage unavailable") + emitAll(state) + } + override suspend fun updateData(transform: suspend (ProfileRemovalState) -> ProfileRemovalState) = + transform(state.value).also { state.value = it } + }) + val observed = mutableListOf() + backgroundScope.launch { store.pending.collect { observed += it } } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + assertEquals(4, reads) + assertEquals(true, observed.last()) + unavailable = false + store.withAccess(id) { store.complete(id) } + runCurrent() + assertEquals(false, observed.last()) + assertNull(store.pendingAttempt()) + } + + @Test + fun `restart retains pending without authorizing cleanup or another attempt`() = runTest { + val file = folder.newFile("removal").also { it.delete() } + val firstScope = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler)) + val first = ProfileRemovalStore(DataStoreFactory.create(ProfileRemovalSerializer, scope = firstScope) { file }) + val attempt = UUID.randomUUID().toString() + try { + first.withAccess(attempt) { + first.begin(attempt) + first.requireAccess() + } + } finally { + requireNotNull(firstScope.coroutineContext[Job]).cancelAndJoin() + } + val second = + ProfileRemovalStore(DataStoreFactory.create(ProfileRemovalSerializer, scope = backgroundScope) { file }) + assertEquals(attempt, second.pendingAttempt()) + assertFailsWith { second.requireAccess() } + assertFailsWith { second.requireNoPending() } + assertFailsWith { second.complete(attempt) } + assertFailsWith { second.withAccess(UUID.randomUUID().toString()) {} } + second.withAccess(attempt) { + second.requireAccess() + second.complete(attempt) + } + assertNull(second.pendingAttempt()) + } + + @Test + fun `an escaped access context cannot authorize work after its scope finishes`() = runTest { + val store = ProfileRemovalStore.inMemoryForTesting() + val id = UUID.randomUUID().toString() + val stale = store.withAccess(id) { + store.begin(id) + currentCoroutineContext().minusKey(Job) + } + assertFailsWith { withContext(stale) { store.requireAccess() } } + assertEquals(id, store.pendingAttempt()) + } + + @Test + fun `a foreign coroutine cannot use a pending owner's access`() = runTest { + val store = ProfileRemovalStore.inMemoryForTesting() + val id = UUID.randomUUID().toString() + store.withAccess(id) { + store.begin(id) + val foreign = backgroundScope.async { assertFailsWith { store.requireAccess() } } + foreign.await() + store.requireAccess() + assertFailsWith { store.complete(UUID.randomUUID().toString()) } + assertEquals(id, store.pendingAttempt()) + } + } + + @Test + fun `malformed persisted marker becomes stable pending recovery across restart`() = runTest { + val file = folder.newFile("malformed").also { it.writeText("{broken") } + val firstScope = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler)) + val first = ProfileRemovalStore( + DataStoreFactory.create( + ProfileRemovalSerializer, + corruptionHandler = profileRemovalCorruptionHandler(), + scope = firstScope, + ) { file } + ) + val recovered = try { + assertNotNull(first.pendingAttempt()).also { + assertFailsWith { first.requireNoPending() } + assertFailsWith { first.complete(it) } + } + } finally { + requireNotNull(firstScope.coroutineContext[Job]).cancelAndJoin() + } + val second = ProfileRemovalStore( + DataStoreFactory.create( + ProfileRemovalSerializer, + corruptionHandler = profileRemovalCorruptionHandler(), + scope = backgroundScope, + ) { file } + ) + assertEquals(recovered, second.pendingAttempt()) + second.withAccess(recovered) { second.complete(recovered) } + assertNull(second.pendingAttempt()) + } + + @Test + fun `future version with incompatible fields stays intact and cannot be mistaken for corrupt v1`() = runTest { + for (version in listOf("2", "\"1\"", "null", "1.5")) { + val bytes = "{\"version\":$version,\"attemptId\":{\"future\":true}}".toByteArray() + val file = folder.newFile().also { it.writeBytes(bytes) } + val scope = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler)) + val store = ProfileRemovalStore( + DataStoreFactory.create( + ProfileRemovalSerializer, + corruptionHandler = profileRemovalCorruptionHandler(), + scope = scope, + ) { file } + ) + try { + val failure = assertFailsWith { store.pendingAttempt() } + assertTrue( + generateSequence(failure) { it.cause } + .any { it is UnsupportedProfileRemovalFormat } + ) + assertTrue(bytes.contentEquals(file.readBytes())) + } finally { + requireNotNull(scope.coroutineContext[Job]).cancelAndJoin() + } + } + } + + @Test + fun `input read failure is not classified as replaceable corruption`() = runTest { + val failure = IOException("storage unavailable") + val stream = object : java.io.InputStream() { + override fun read(): Int = throw failure + } + assertEquals(failure, assertFailsWith { ProfileRemovalSerializer.readFrom(stream) }) + } + + @Test + fun `corrupt recovery state is never interpreted as no pending work`() = runTest { + for (bytes in listOf( + "not json".toByteArray(), + "{\"attemptId\":\"bad\"}".toByteArray() + )) { + assertFailsWith { ProfileRemovalSerializer.readFrom(ByteArrayInputStream(bytes)) } + } + assertFailsWith { + ProfileRemovalSerializer.readFrom( + ByteArrayInputStream(byteArrayOf(-1)) + ) + } + assertEquals(ProfileRemovalState(), ProfileRemovalSerializer.readFrom(ByteArrayInputStream("{}".toByteArray()))) + } +} diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 1eee30e7dd..188ae1f8c2 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -193,6 +193,13 @@ class BackupRepoTest : BaseUnitTest() { sut = createSut() } + @Test + fun `profile backup retry admission does not retry unrelated storage failures`() { + assertFalse(PaykitException.Storage("wallet_wipe_in_progress", "wipe").isTemporaryBackupFailure()) + assertFalse(AppError(PaykitException.Storage("wallet_wipe_in_progress", "wipe")).isTemporaryBackupFailure()) + assertFalse(PaykitException.Storage("unknown", "profile_removal_in_progress").isTemporaryBackupFailure()) + } + @Test fun `metadata backup preserves complete data when identity records cannot be read`() = test { stubMetadataBackupReads() @@ -1228,6 +1235,45 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `wallet backup retains pending work while profile removal owns the SDK`() = test { + whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(3_000)) + whenever { privatePaykitRepo.backupSnapshot() } + .thenReturn( + Result.failure(AppError(PaykitException.Storage("profile_removal_in_progress", "removal owns SDK"))) + ) + .thenReturn(Result.success(PrivatePaykitBackupSnapshot(null, 0))) + val backupStatuses = MutableStateFlow( + mapOf( + BackupCategory.WALLET to BackupItemStatus( + synced = 1_000, + required = 2_000, + ), + ) + ) + val allowWalletClear = CompletableDeferred().apply { complete(Unit) } + stubBackupStatuses(backupStatuses, allowWalletClear) {} + stubBackupObservers() + + try { + sut.startObservingBackups() + runCurrent() + advanceTimeBy(5_000) + runCurrent() + verify(privatePaykitRepo, times(1)).backupSnapshot() + verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) + + advanceTimeBy(20_000) + runCurrent() + + verify(privatePaykitRepo, times(2)).backupSnapshot() + verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), any()) + assertFalse(backupStatuses.value.getValue(BackupCategory.WALLET).isRequired) + } finally { + sut.stopObservingBackups() + } + } + @Test fun `wallet backup retries after a busy Paykit shared state`() = test { whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(3_000)) diff --git a/app/src/test/java/to/bitkit/repositories/ContactPaymentSettingsRepoTest.kt b/app/src/test/java/to/bitkit/repositories/ContactPaymentSettingsRepoTest.kt index 2adacf44ff..41a7055272 100644 --- a/app/src/test/java/to/bitkit/repositories/ContactPaymentSettingsRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/ContactPaymentSettingsRepoTest.kt @@ -3,6 +3,7 @@ package to.bitkit.repositories import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin @@ -10,6 +11,8 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout import org.junit.Before import org.junit.Test import org.mockito.kotlin.any @@ -70,6 +73,92 @@ class ContactPaymentSettingsRepoTest : BaseUnitTest() { .thenReturn(Result.success(Unit)) } + @Test + fun `wipe revokes repository removal before draining the sharing mutex`() = test { + val sut = createSut() + val repository = PubkyIdentityOperations() + val entered = CompletableDeferred() + val cleanup = CompletableDeferred() + val finishCleanup = CompletableDeferred() + val removing = launch { + sut.withProfileRemoval { + repository.remove { + entered.complete(Unit) + try { + awaitCancellation() + } finally { + withContext(NonCancellable) { + cleanup.complete(Unit) + finishCleanup.await() + } + } + } + } + } + entered.await() + var reachedSdk = false + val wiping = async { + sut.withWalletWipe(repository::wipe) { reachedSdk = true } + } + cleanup.await() + assertFalse(reachedSdk) + assertTrue(sut.setEnabled(true).isFailure) + finishCleanup.complete(Unit) + withTimeout(1_000) { + wiping.await() + removing.join() + } + assertTrue(reachedSdk) + assertTrue(sut.setEnabled(false).isSuccess) + } + + @Test + fun `removal drains sharing rollback and rejects queued changes`() = test { + val publication = CompletableDeferred() + val enteredRemoval = CompletableDeferred() + val finishRemoval = CompletableDeferred() + whenever(publicPaykitRepo.syncPublishedEndpoints(publish = true)).doSuspendableAnswer { + publication.await() + Result.failure(IllegalStateException("Uncertain publication")) + } + val sut = createSut() + val enabling = async { sut.setEnabled(true) } + runCurrent() + val queued = async { sut.setEnabled(false) } + runCurrent() + val removing = async { + sut.withProfileRemoval { + assertFalse(settingsFlow.value.sharesPublicPaykitEndpoints) + enteredRemoval.complete(Unit) + finishRemoval.await() + } + } + runCurrent() + assertFalse(enteredRemoval.isCompleted) + assertTrue(sut.disablePaykit().isFailure) + publication.complete(Unit) + runCurrent() + assertTrue(enabling.await().isFailure) + assertTrue(queued.await().isFailure) + assertTrue(enteredRemoval.isCompleted) + var reconciled = false + sut.reconcilePendingEndpoints { reconciled = true } + assertFalse(reconciled) + finishRemoval.complete(Unit) + removing.await() + assertTrue(sut.setEnabled(false).isSuccess) + } + + @Test + fun `cancelled removal reservation releases sharing admission`() = test { + val sut = createSut() + val removal = launch { sut.withProfileRemoval { awaitCancellation() } } + runCurrent() + assertTrue(sut.setEnabled(true).isFailure) + removal.cancelAndJoin() + assertTrue(sut.setEnabled(true).isSuccess) + } + @Test fun `enabling publishes public and private contact payments`() = test { settingsFlow.value = SettingsData( diff --git a/app/src/test/java/to/bitkit/repositories/PrivatePaykitAllowancePaymentTest.kt b/app/src/test/java/to/bitkit/repositories/PrivatePaykitAllowancePaymentTest.kt index 076c74f7c4..0381dbf584 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitAllowancePaymentTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitAllowancePaymentTest.kt @@ -20,6 +20,7 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.data.PrivatePaykitCacheData import to.bitkit.data.PrivatePaykitCacheStore +import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.ext.toHex @@ -50,6 +51,7 @@ class PrivatePaykitAllowancePaymentTest : BaseUnitTest(StandardTestDispatcher()) } private val paykitSdkService = mock() + private val profileRemovalStore = ProfileRemovalStore.inMemoryForTesting() private val cacheStore = mock() private val settingsStore = mock() private val lightningRepo = mock() @@ -84,6 +86,7 @@ class PrivatePaykitAllowancePaymentTest : BaseUnitTest(StandardTestDispatcher()) usdtRepo = mock(), coreService = coreService, clock = clock, + profileRemovalStore = profileRemovalStore, ) } diff --git a/app/src/test/java/to/bitkit/repositories/PrivatePaykitContactResolverTest.kt b/app/src/test/java/to/bitkit/repositories/PrivatePaykitContactResolverTest.kt index 500c8252a3..6054e08c34 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitContactResolverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitContactResolverTest.kt @@ -1,19 +1,26 @@ package to.bitkit.repositories +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flow import org.junit.Before import org.junit.Test +import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import to.bitkit.data.PrivatePaykitCacheData import to.bitkit.data.PrivatePaykitCacheStore import to.bitkit.data.PrivatePaykitContactCacheData import to.bitkit.data.PrivatePaykitStoredInvoiceData +import to.bitkit.data.ProfileRemovalStore import to.bitkit.models.PubkyPublicKeyFormat import to.bitkit.test.BaseUnitTest +import java.util.UUID import javax.inject.Provider import kotlin.test.assertEquals import kotlin.test.assertNull +import kotlin.test.assertTrue class PrivatePaykitContactResolverTest : BaseUnitTest() { companion object { @@ -22,6 +29,7 @@ class PrivatePaykitContactResolverTest : BaseUnitTest() { private const val PRIVATE_ADDRESS = "bcrt1qterdweva9vextackckt6pjy0mmuc54g87g6lsq" } + private val profileRemovalStore = ProfileRemovalStore.inMemoryForTesting() private val cacheStore = mock() private val addressReservationRepo = mock() private val paymentRequestRepo = mock() @@ -38,9 +46,73 @@ class PrivatePaykitContactResolverTest : BaseUnitTest() { cacheStore = cacheStore, addressReservationRepo = Provider { addressReservationRepo }, paymentRequestRepo = Provider { paymentRequestRepo }, + profileRemovalStore = profileRemovalStore, ) } + @Test + fun `recovery generation discards a cold invoice lookup across completed local cleanup`() = test { + val old = PrivatePaykitCacheData( + contacts = mapOf( + CONTACT_KEY to PrivatePaykitContactCacheData(receivedInvoicePaymentHashes = listOf(PAYMENT_HASH)) + ) + ) + val ready = CompletableDeferred() + val release = CompletableDeferred() + whenever(cacheStore.data).thenReturn( + flow { + ready.complete(Unit) + release.await() + emit(old) + } + ) + val lookup = async { sut.contactPublicKeyForPrivateInvoicePaymentHash(PAYMENT_HASH) } + ready.await() + val id = UUID.randomUUID().toString() + profileRemovalStore.withAccess(id) { + profileRemovalStore.begin(id) + cacheData.value = PrivatePaykitCacheData() + profileRemovalStore.complete(id) + } + release.complete(Unit) + assertNull(lookup.await()) + } + + @Test + fun `recovery generation discards a reserved contact lookup across completed local cleanup`() = test { + val ready = CompletableDeferred() + val release = CompletableDeferred() + whenever(addressReservationRepo.contactPublicKeyForReservedAddress(PRIVATE_ADDRESS)).doSuspendableAnswer { + ready.complete(Unit) + release.await() + CONTACT_KEY + } + val lookup = async { sut.contactPublicKeyForReservedAddress(PRIVATE_ADDRESS) } + ready.await() + val id = UUID.randomUUID().toString() + profileRemovalStore.withAccess(id) { + profileRemovalStore.begin(id) + profileRemovalStore.complete(id) + } + release.complete(Unit) + assertNull(lookup.await()) + } + + @Test + fun `pending removal hides invoice and address contacts without erasing reservation state`() = test { + val shared = mock() + whenever(shared.contactsForPaymentHash(PAYMENT_HASH)).thenReturn(setOf(CONTACT_KEY)) + whenever(shared.contactsForAddresses(listOf(PRIVATE_ADDRESS))).thenReturn(setOf(CONTACT_KEY)) + whenever(paymentRequestRepo.receivedPaymentContacts).thenReturn(shared) + whenever(addressReservationRepo.contactPublicKeyForReservedAddress(PRIVATE_ADDRESS)).thenReturn(CONTACT_KEY) + val id = UUID.randomUUID().toString() + profileRemovalStore.withAccess(id) { profileRemovalStore.begin(id) } + assertNull(sut.contactPublicKeyForPrivateInvoicePaymentHash(PAYMENT_HASH)) + assertNull(sut.contactPublicKeyForReservedAddress(PRIVATE_ADDRESS)) + assertNull(sut.contactPublicKeyForPrivateOnchainAddresses(PRIVATE_ADDRESS, listOf(PRIVATE_ADDRESS))) + assertTrue(sut.isReservedReceiveAddress(PRIVATE_ADDRESS)) + } + @Test fun `shared request invoice hash resolves without local invoice reservations`() = test { val shared = mock() diff --git a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt index 5e0aa48fea..2f3bbd7bbb 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt @@ -32,6 +32,7 @@ import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle @@ -60,6 +61,7 @@ import to.bitkit.CurrentActivity import to.bitkit.data.PrivatePaykitCacheData import to.bitkit.data.PrivatePaykitCacheStore import to.bitkit.data.PrivatePaykitContactCacheData +import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.data.UsdtPreference @@ -77,6 +79,7 @@ import to.bitkit.services.PaykitSdkService import to.bitkit.services.PubkyService import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError +import java.util.UUID import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse @@ -104,6 +107,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { private val paykitSdkService = mock() private val pubkyService = mock() + private val profileRemovalStore = ProfileRemovalStore.inMemoryForTesting() private val cacheStore = mock() private val settingsStore = mock() private val addressReservationRepo = mock() @@ -201,6 +205,170 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { App.currentActivity = null } + private var deletionPause: PrivatePaykitRepo.ProfileDeletionPause? = null + + private suspend fun beginProfileDeletion() { + deletionPause = sut.beginProfileDeletion() + } + + private suspend fun endProfileDeletion() { + deletionPause?.let { sut.endProfileDeletion(it) } + deletionPause = null + } + + @Test + fun `recovery admission rejects a cold attribution result after pending begins`() = test { + val old = PrivatePaykitCacheData( + contacts = mapOf( + CONTACT_KEY to PrivatePaykitContactCacheData(receivedInvoicePaymentHashes = listOf("old-hash")) + ) + ) + val ready = CompletableDeferred() + val release = CompletableDeferred() + whenever(cacheStore.data).thenReturn( + flow { + ready.complete(Unit) + release.await() + emit(old) + } + ) + val reading = async { sut.contactPublicKeyForPrivateInvoicePaymentHash("old-hash") } + ready.await() + val id = UUID.randomUUID().toString() + profileRemovalStore.withAccess(id) { profileRemovalStore.begin(id) } + release.complete(Unit) + assertNull(reading.await()) + assertEquals(id, profileRemovalStore.pendingAttempt()) + } + + @Test + fun `recovery admission prevents an old cold cache read overwriting completed local teardown`() = test { + val old = PrivatePaykitCacheData( + contacts = mapOf( + CONTACT_KEY to PrivatePaykitContactCacheData(receivedInvoicePaymentHashes = listOf("old-hash")) + ) + ) + val ready = CompletableDeferred() + val release = CompletableDeferred() + whenever(cacheStore.data).thenReturn( + flow { + ready.complete(Unit) + release.await() + emit(old) + } + ) + val reading = async { sut.contactPublicKeyForPrivateInvoicePaymentHash("old-hash") } + ready.await() + val id = UUID.randomUUID().toString() + profileRemovalStore.withAccess(id) { + profileRemovalStore.begin(id) + sut.withProfileDeletionPaused { pause -> sut.finishProfileRemoval(pause).getOrThrow() } + profileRemovalStore.complete(id) + } + release.complete(Unit) + assertNull(reading.await()) + assertNull(sut.contactPublicKeyForPrivateInvoicePaymentHash("old-hash")) + assertTrue(cacheData.value.contacts.isEmpty()) + } + + @Test + fun `profile removal recovery leaves ordinary incoming payment attribution optional`() = test { + assertNull(sut.contactPublicKeyForPrivateInvoicePaymentHash("ordinary-payment")) + val id = UUID.randomUUID().toString() + profileRemovalStore.withAccess(id) { profileRemovalStore.begin(id) } + assertNull(sut.contactPublicKeyForPrivateInvoicePaymentHash("ordinary-payment")) + } + + @Test + fun `pending removal prevents a complete backup before touching authenticated identity`() = test { + whenever(paykitSdkService.backupStateVersion).thenReturn(MutableStateFlow(0L)) + whenever(pubkyService.currentPublicKey()).thenReturn(null) + val id = UUID.randomUUID().toString() + profileRemovalStore.withAccess(id) { profileRemovalStore.begin(id) } + clearInvocations(pubkyService, paykitSdkService) + assertTrue(sut.backupSnapshot().isFailure) + verify(pubkyService, never()).currentPublicKey() + verify(paykitSdkService, never()).exportBackupState(any()) + } + + @Test + fun `pending removal prevents destructive cache clearing while credentials may survive`() = test { + val id = UUID.randomUUID().toString() + cacheData.value = PrivatePaykitCacheData( + contacts = mapOf( + CONTACT_KEY to PrivatePaykitContactCacheData(consumedPrivatePaymentListVersion = 7uL) + ) + ) + val original = cacheData.value + profileRemovalStore.withAccess(id) { profileRemovalStore.begin(id) } + assertTrue(sut.closeAndClear().isFailure) + assertTrue(sut.restoreBackup(null).isFailure) + assertEquals(original, cacheData.value) + verify(paykitSdkService, never()).clearState() + verify(addressReservationRepo, never()).clearContactAssignments(any(), anyOrNull()) + } + + @Test + fun `pending removal survives process recreation and ending a temporary pause`() = test { + val id = UUID.randomUUID().toString() + profileRemovalStore.withAccess(id) { profileRemovalStore.begin(id) } + val restarted = createSut() + runCurrent() + assertTrue(restarted.isProfileDeletionInProgress.value) + val pause = restarted.beginProfileDeletion() + restarted.endProfileDeletion(pause) + assertTrue(restarted.isProfileDeletionInProgress.value) + profileRemovalStore.withAccess(id) { profileRemovalStore.complete(id) } + runCurrent() + assertFalse(restarted.isProfileDeletionInProgress.value) + } + + @Test + fun `cancellation while returning a deletion pause cannot retain it`() = test { + val returns = ArrayDeque() + val caller = object : kotlinx.coroutines.CoroutineDispatcher() { + override fun dispatch(context: kotlin.coroutines.CoroutineContext, block: Runnable) { + returns.addLast(block) + } + } + var entered = false + val removal = launch(caller) { sut.withProfileDeletionPaused { entered = true } } + returns.removeFirst().run() + runCurrent() + assertTrue(sut.isProfileDeletionInProgress.value) + removal.cancel() + while (returns.isNotEmpty()) { + returns.removeFirst().run() + runCurrent() + } + assertTrue(removal.isCompleted) + assertFalse(entered) + assertFalse(sut.isProfileDeletionInProgress.value) + } + + @Test + fun `ending one removal pause cannot unpause another owner`() = test { + val first = sut.beginProfileDeletion() + val second = sut.beginProfileDeletion() + sut.endProfileDeletion(first) + assertTrue(sut.isProfileDeletionInProgress.value) + sut.endProfileDeletion(first) + assertTrue(sut.isProfileDeletionInProgress.value) + sut.endProfileDeletion(second) + assertFalse(sut.isProfileDeletionInProgress.value) + } + + @Test + fun `profile removal finalization is local and rejects an ended pause`() = test { + val pause = sut.beginProfileDeletion() + assertTrue(sut.finishProfileRemoval(pause).isSuccess) + verify(paykitSdkService, never()).clearState() + sut.endProfileDeletion(pause) + clearInvocations(cacheStore) + assertTrue(sut.finishProfileRemoval(pause).isFailure) + verify(cacheStore, never()).reset() + } + @Test fun `obsolete contact sync preserves the admitted retry and its original priority deadline`() = test { whenever(clock.now()).thenAnswer { @@ -1162,7 +1330,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { "identity" -> whenever(paykitSdkService.identityStatus()).thenReturn( IdentityStatus(OTHER_CONTACT_KEY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE), ) - "deletion" -> sut.beginProfileDeletion() + "deletion" -> beginProfileDeletion() } completion.complete(Unit) runCurrent() @@ -1179,7 +1347,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { } finally { completion.complete(Unit) sut.closeAndClear() - sut.endProfileDeletion() + endProfileDeletion() whenever(paykitSdkService.identityStatus()).thenReturn( IdentityStatus(OWN_KEY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE), ) @@ -1558,7 +1726,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { } sut.refreshSavedContactEndpoints(CONTACT_KEY, listOf(CONTACT_KEY)).getOrThrow() runCurrent() - sut.beginProfileDeletion() + beginProfileDeletion() clearInvocations(paykitSdkService) completion.complete(Unit) advanceTimeBy(120_000) @@ -1660,7 +1828,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { sut.setContactPreparationActive(false) completion.complete(Unit) runCurrent() - sut.beginProfileDeletion() + beginProfileDeletion() clearInvocations(paykitSdkService) sut.setContactPreparationActive(true) @@ -1697,7 +1865,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { sut.scheduleSavedContactPreparation(listOf(OTHER_CONTACT_KEY)).getOrThrow() advanceTimeBy(2_000) runCurrent() - sut.beginProfileDeletion() + beginProfileDeletion() clearInvocations(paykitSdkService) sut.setContactPreparationActive(true) @@ -1893,8 +2061,8 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { val old = async { sut.prepareSavedContacts(listOf(CONTACT_KEY)) } runCurrent() assertEquals(1, advances) - sut.beginProfileDeletion() - sut.endProfileDeletion() + beginProfileDeletion() + endProfileDeletion() val current = async { sut.prepareSavedContacts(listOf(CONTACT_KEY)) } try { runCurrent() @@ -2851,7 +3019,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { publicPaykitLightningEnabled = false, publicPaykitUsdtEnabled = false, ) - sut.beginProfileDeletion() + beginProfileDeletion() sut.scheduleSavedContactPreparation(listOf(CONTACT_KEY, OTHER_CONTACT_KEY)).getOrThrow() runCurrent() verify(paykitSdkService, never()).ensureLinkWithPeer(any(), any(), any()) @@ -2860,7 +3028,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { verify(paykitSdkService, never()).clearPrivatePaymentLists(any(), anyOrNull()) verify(addressReservationRepo).removeContactAssignments(setOf(CONTACT_KEY, OTHER_CONTACT_KEY)) - sut.endProfileDeletion() + endProfileDeletion() sut.scheduleSavedContactPreparation(listOf(CONTACT_KEY)).getOrThrow() runCurrent() verify(paykitSdkService).ensureLinkWithPeer(CONTACT_KEY) @@ -2870,7 +3038,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { @Test fun `deferred private Lightning refresh survives cleanup and failed publication`() = test { preparePrivateLightningContact() - sut.beginProfileDeletion() + beginProfileDeletion() clearInvocations(paykitSdkService, pubkyService) sut.refreshKnownSavedContactEndpoints("channel ready", forceRefreshLightning = true).getOrThrow() verifyNoInteractions(paykitSdkService, pubkyService) @@ -2878,7 +3046,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { whenever(paykitSdkService.clearPrivatePaymentLists(any(), anyOrNull())) .thenAnswer { throw AppError("cleanup unavailable") } assertTrue(sut.removePublishedEndpointsForCleanup("profile deletion").isFailure) - sut.endProfileDeletion() + endProfileDeletion() settingsData.update { it.copy(sharesPrivatePaykitEndpoints = false) } sut.refreshKnownSavedContactEndpoints("foreground").getOrThrow() runCurrent() @@ -3000,14 +3168,14 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { sut.scheduleSavedContactPreparation(emptyList()).getOrThrow() runCurrent() var isCurrent = true - sut.beginProfileDeletion() + beginProfileDeletion() sut.refreshKnownSavedContactEndpoints( "channel ready", forceRefreshLightning = true, isStillCurrent = { isCurrent }, ).getOrThrow() isCurrent = false - sut.endProfileDeletion() + endProfileDeletion() sut.scheduleSavedContactPreparation(listOf(CONTACT_KEY)).getOrThrow() runCurrent() @@ -3068,7 +3236,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { whenever(coreService.decode(PRIVATE_BOLT11)) .thenReturn(Scanner.Lightning(lightningInvoice(PRIVATE_BOLT11, byteArrayOf(9, 9, 9)))) sut.prepareSavedContacts(listOf(CONTACT_KEY), requireImmediatePublication = true).getOrThrow() - sut.beginProfileDeletion() + beginProfileDeletion() clearInvocations(paykitSdkService) sut.handleReceivedPayment("090909").getOrThrow() @@ -3076,7 +3244,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { assertEquals(CONTACT_KEY, sut.contactPublicKeyForPrivateInvoicePaymentHash("090909")) assertEquals(listOf("090909"), cacheData.value.contacts.getValue(CONTACT_KEY).receivedInvoicePaymentHashes) verifyNoInteractions(paykitSdkService) - sut.endProfileDeletion() + endProfileDeletion() sut.refreshKnownSavedContactEndpoints("deletion ended").getOrThrow() runCurrent() verify(paykitSdkService).syncPrivatePaymentListsWithReservations(any(), eq(false)) @@ -3094,14 +3262,14 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { whenever(addressReservationRepo.contactsWithUsedReservedAddresses()).thenReturn(listOf(CONTACT_KEY)) whenever(addressReservationRepo.currentContactPublicKeyForReservedAddress(PRIVATE_ADDRESS)) .thenReturn(CONTACT_KEY) - sut.beginProfileDeletion() + beginProfileDeletion() clearInvocations(paykitSdkService) sut.handleOnchainActivity().getOrThrow() sut.handleOnchainActivity(listOf(PRIVATE_ADDRESS)).getOrThrow() verifyNoInteractions(paykitSdkService) - sut.endProfileDeletion() + endProfileDeletion() sut.refreshKnownSavedContactEndpoints("deletion ended").getOrThrow() runCurrent() verify(paykitSdkService).syncPrivatePaymentListsWithReservations(any(), eq(false)) @@ -3135,8 +3303,8 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { val rotation = async { sut.handleOnchainActivity() } runCurrent() assertTrue(identityStarted.isCompleted) - sut.beginProfileDeletion() - sut.endProfileDeletion() + beginProfileDeletion() + endProfileDeletion() resumeIdentity.complete(Unit) rotation.await().getOrThrow() verify(paykitSdkService, never()).syncPrivatePaymentListsWithReservations(any(), any()) @@ -3164,7 +3332,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { sut.scheduleSavedContactPreparation(listOf(CONTACT_KEY)).getOrThrow() runCurrent() assertTrue(settingsStarted.isCompleted) - sut.beginProfileDeletion() + beginProfileDeletion() sut.removePublishedEndpointsForCleanup("profile deletion").getOrThrow() assertFalse(cacheData.value.cleanupPending) clearInvocations(paykitSdkService) @@ -3173,7 +3341,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { sut.awaitContactPreparation() verifyNoInteractions(paykitSdkService) - sut.endProfileDeletion() + endProfileDeletion() sut.closeAndClear() } @@ -4105,6 +4273,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { usdtRepo = usdtRepo, coreService = coreService, clock = clock, + profileRemovalStore = profileRemovalStore, ).also { it.setContactPreparationActive(true) } private fun resolution( diff --git a/app/src/test/java/to/bitkit/repositories/PubkyIdentityOperationsTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyIdentityOperationsTest.kt new file mode 100644 index 0000000000..8fd7ee3c23 --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/PubkyIdentityOperationsTest.kt @@ -0,0 +1,142 @@ +package to.bitkit.repositories + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withContext +import org.junit.Test +import kotlin.coroutines.CoroutineContext +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +@OptIn(ExperimentalCoroutinesApi::class) +class PubkyIdentityOperationsTest { + @Test + fun `removal excludes identity replacement through local completion`() = runTest { + val operations = PubkyIdentityOperations() + val local = CompletableDeferred() + var writes = 0 + val removal = launch { + operations.remove { + operations.transition { writes++ } + local.await() + } + } + runCurrent() + assertFailsWith { operations.transition { writes++ } } + assertFailsWith { operations.remove { writes++ } } + assertEquals(1, writes) + local.complete(Unit) + removal.join() + operations.transition { writes++ } + assertEquals(2, writes) + } + + @Test + fun `concurrent transition tails finish before removal can start`() = runTest { + val operations = PubkyIdentityOperations() + val first = CompletableDeferred() + val second = CompletableDeferred() + val a = launch { operations.transition { first.await() } } + val b = launch { operations.transition { second.await() } } + runCurrent() + first.complete(Unit) + a.join() + assertFailsWith { operations.remove {} } + second.complete(Unit) + b.join() + operations.remove {} + } + + @Test + fun `wipe revokes removal and drains noncancellable local cleanup before reset`() = runTest { + val operations = PubkyIdentityOperations() + val local = CompletableDeferred() + val events = mutableListOf() + val removal = launch { + operations.remove { + try { + awaitCancellation() + } finally { + withContext(NonCancellable) { + local.await() + operations.transition { events += "local" } + } + } + } + } + runCurrent() + val wipe = launch { operations.wipe { operations.transition { events += "wipe" } } } + try { + runCurrent() + assertFalse(wipe.isCompleted) + assertFailsWith { operations.transition {} } + assertFailsWith { operations.remove {} } + local.complete(Unit) + removal.join() + wipe.join() + assertEquals(listOf("local", "wipe"), events) + operations.transition {} + } finally { + local.complete(Unit) + removal.cancel() + wipe.cancel() + } + } + + @Test + fun `wipe drains an admitted transition rollback and rejects new identity work`() = runTest { + val operations = PubkyIdentityOperations() + val rollback = CompletableDeferred() + var restored = false + val transition = launch { + operations.transition { + try { + awaitCancellation() + } finally { + withContext(NonCancellable) { + rollback.await() + operations.transition { restored = true } + } + } + } + } + runCurrent() + transition.cancel() + val wipe = launch { operations.wipe { assertTrue(restored) } } + try { + runCurrent() + assertFalse(wipe.isCompleted) + assertFailsWith { operations.remove {} } + rollback.complete(Unit) + transition.join() + wipe.join() + } finally { + rollback.complete(Unit) + transition.cancel() + wipe.cancel() + } + } + + @Test + fun `ended context cannot authorize later work and nested wipe cannot self-deadlock`() = runTest { + val operations = PubkyIdentityOperations() + lateinit var ended: CoroutineContext + operations.remove { + ended = currentCoroutineContext() + assertFailsWith { operations.wipe {} } + } + // Preserve the context element but use the current active Job for this deliberately stale continuation. + withContext(ended.minusKey(kotlinx.coroutines.Job)) { + assertFailsWith { operations.transition {} } + } + operations.remove {} + } +} diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index a4d18e2836..4f753fd1eb 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -66,6 +66,7 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.verifyBlocking import org.mockito.kotlin.whenever import org.mockito.verification.VerificationMode +import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.PubkyCachedProfile import to.bitkit.data.PubkyImageCacheEpoch import to.bitkit.data.PubkyStore @@ -82,14 +83,19 @@ import to.bitkit.models.PubkyAuthRequest import to.bitkit.models.PubkyProfile import to.bitkit.models.PubkySessionBackupKind import to.bitkit.models.PubkySessionBackupV1 +import to.bitkit.services.PaykitProfileDeletionSnapshot import to.bitkit.services.PaykitReadLane import to.bitkit.services.PaykitSdkService import to.bitkit.services.PubkyRingAuthTimeoutError import to.bitkit.services.PubkyService import to.bitkit.test.BaseUnitTest import to.bitkit.test.forEachCase +import to.bitkit.usecases.ProfileRemovalCoordinator +import to.bitkit.usecases.ProfileRemovalFailure import to.bitkit.utils.AppError +import java.util.UUID import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull @@ -129,11 +135,172 @@ class PubkyRepoTest : BaseUnitTest() { private lateinit var sut: PubkyRepo + @Test + fun `removal rejects every competing identity entry before it changes credentials or settings`() = test { + advanceUntilIdle() + whenever { pubkyService.withProfileRemoval(any(), any()) }.doSuspendableAnswer { + it.getArgument Unit>(1).invoke() + } + val release = CompletableDeferred() + val removal = async { sut.performProfileRemoval(sut.profileOwner()) { release.await() } } + runCurrent() + clearInvocations(pubkyService, keychain, settingsStore) + val entries = listOf Result<*>>( + { sut.initialize() }, + { sut.checkAdoptedSource() }, + { sut.adoptRingIdentity(VALID_SELF_KEY) }, + { sut.createIdentity("Name", "", emptyList(), emptyList(), null) }, + { sut.saveProfile("Name", "", emptyList(), emptyList(), null) }, + { sut.approveSignupAuth(directSignupRequest()) }, + { sut.approveAuth("auth", "capabilities", "client") }, + { sut.approveAuthWithCompanionClaim("auth", "client", byteArrayOf()) }, + { sut.restoreSessionBackupState(null) }, + { sut.signOut() }, + { sut.forgetUnrestoredIdentity() }, + ) + try { + entries.forEach { assertSame(PubkyIdentityBusy, it().exceptionOrNull()) } + assertFalse(sut.hasSecretKey()) + assertFalse(sut.restoreSessionIfNeeded()) + assertFailsWith { sut.wipeLocalState() } + verify(keychain, never()).delete(any()) + verify(keychain, never()).upsertString(any(), any()) + verify(settingsStore, never()).update(any()) + verify(pubkyService, never()).signOut() + verify(pubkyService, never()).forgetSessionAccess() + } finally { + release.complete(Unit) + } + assertTrue(removal.await().isSuccess) + } + + @Test + fun `removal cannot start during the local tail of Ring adoption`() = test { + advanceUntilIdle() + val ringPubky = stubRingCredential() + val releaseContacts = CompletableDeferred() + whenever(pubkyService.contactRecords()).doSuspendableAnswer { + releaseContacts.await() + emptyList() + } + val adoption = async { sut.adoptRingIdentity(ringPubky) } + try { + runCurrent() + assertEquals(VALID_SELF_KEY, sut.publicKey.value) + assertFalse(adoption.isCompleted) + val removal = sut.performProfileRemoval(sut.profileOwner()) { error("removal admitted during adoption") } + assertSame(PubkyIdentityBusy, removal.exceptionOrNull()) + } finally { + releaseContacts.complete(Unit) + } + assertTrue(adoption.await().isSuccess) + } + + @Test + fun `removal preserves its original owner and returns the ended generation after signout`() = test { + authenticateForTesting() + whenever { pubkyService.withProfileRemoval(any(), any()) }.doSuspendableAnswer { + assertTrue(it.getArgument<() -> Boolean>(0).invoke()) + it.getArgument Unit>(1).invoke() + } + val original = sut.profileOwner() + val completion = sut.performProfileRemoval(original) { sut.finishProfileRemovalLocally() }.getOrThrow() + assertFalse(sut.isProfileOwnerCurrent(original)) + assertTrue(sut.isProfileOwnerCurrent(completion)) + assertNull(sut.publicKey.value) + assertTrue(sut.performProfileRemoval(original) { error("obsolete owner admitted") }.isFailure) + } + + @Test + fun `pending removal restart refuses activation and settles restoration without clearing credentials`() = test { + advanceUntilIdle() + val id = UUID.randomUUID().toString() + profileRemovalStore.withAccess(id) { profileRemovalStore.begin(id) } + whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn("saved-session") + clearInvocations(pubkyService, keychain) + val restarted = createSut() + advanceUntilIdle() + assertFalse(restarted.isRestoringSession.value) + assertTrue(restarted.sessionRestorationFailed.value) + assertFalse(restarted.restoreSessionIfNeeded()) + assertEquals(PubkyIdentityReadiness.RecoveryRequired, restarted.awaitIdentityReady()) + assertTrue(restarted.initialize().isFailure) + verify(pubkyService, never()).initialize() + verify(pubkyService, never()).initializeAndImportSession(any()) + verify(keychain, never()).delete(any()) + assertEquals(id, profileRemovalStore.pendingAttempt()) + } + + @Test + fun `pending removal rejects new identity and reports unavailable even with an old active profile`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + val id = UUID.randomUUID().toString() + profileRemovalStore.withAccess(id) { profileRemovalStore.begin(id) } + clearInvocations(pubkyService, keychain) + assertEquals(PubkyIdentityReadiness.RecoveryRequired, sut.awaitIdentityReady()) + assertTrue(sut.adoptRingIdentity(VALID_CONTACT_KEY_A).isFailure) + assertTrue(sut.restoreSessionBackupState(null).isFailure) + assertTrue(sut.republishIdentityIfNeeded().isFailure) + verify(keychain, never()).delete(any()) + assertEquals(id, profileRemovalStore.pendingAttempt()) + } + + @Test + fun `pending removal grants exact marker scope before SDK admission`() = test { + advanceUntilIdle() + val id = UUID.randomUUID().toString() + profileRemovalStore.withAccess(id) { profileRemovalStore.begin(id) } + whenever { pubkyService.withProfileRemoval(any(), any()) }.doSuspendableAnswer { + profileRemovalStore.requireAccess() + it.getArgument Unit>(1).invoke() + } + var reached = false + assertTrue(sut.performProfileRemoval(sut.profileOwner(), id) { reached = true }.isSuccess) + assertTrue(reached) + assertTrue(sut.performProfileRemoval(sut.profileOwner(), UUID.randomUUID().toString()) {}.isFailure) + assertEquals(id, profileRemovalStore.pendingAttempt()) + } + + @Test + fun `strict local completion does not clear metadata when credentials cannot be forgotten`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + val owner = sut.profileOwner() + whenever { pubkyService.withProfileRemoval(any(), any()) }.doSuspendableAnswer { + it.getArgument Unit>(1).invoke() + } + whenever { pubkyService.forgetLocalProfileAccess() }.thenAnswer { error("keychain unavailable") } + clearInvocations(pubkyStore, settingsStore) + assertTrue(sut.performProfileRemoval(owner) { sut.finishProfileRemovalLocally() }.isFailure) + assertTrue(sut.isProfileOwnerCurrent(owner)) + verify(pubkyStore, never()).reset() + verify(settingsStore, never()).update(any()) + verify(pubkyService, never()).signOut() + } + + @Test + fun `strict local completion ends old writers before reset and propagates cache failure`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + val owner = sut.profileOwner() + val version = sut.backupStateVersion.value + whenever { pubkyService.withProfileRemoval(any(), any()) }.doSuspendableAnswer { + it.getArgument Unit>(1).invoke() + } + whenever { pubkyStore.reset() }.thenAnswer { + assertFalse(sut.isProfileOwnerCurrent(owner)) + error("cache unavailable") + } + assertTrue(sut.performProfileRemoval(owner) { sut.finishProfileRemovalLocally() }.isFailure) + assertNull(sut.publicKey.value) + assertTrue(sut.backupStateVersion.value > version) + verify(pubkyService).forgetLocalProfileAccess() + } + private val pubkyService = mock() private val keychain = mock() private val sharedPubkyClient = mock() private val imageLoader = mock() private val imageCacheEpoch = PubkyImageCacheEpoch() + private val profileRemovalStore = ProfileRemovalStore.inMemoryForTesting() private val pubkyStore = mock() private val settingsStore = mock() private val settingsFlow = MutableStateFlow(SettingsData()) @@ -173,6 +340,18 @@ class PubkyRepoTest : BaseUnitTest() { adoptedSource = null Unit } + whenever { pubkyService.withProfileRemoval(any(), any()) }.doSuspendableAnswer { + check(it.getArgument<() -> Boolean>(0).invoke()) + it.getArgument Unit>(1).invoke() + } + whenever { pubkyService.captureProfileDeletion(any(), any()) }.doSuspendableAnswer { + PaykitProfileDeletionSnapshot(it.getArgument(0), "revision", pubkyService.contactRecords()) + } + whenever { pubkyService.forgetLocalProfileAccess() }.doSuspendableAnswer { + keychain.delete(Keychain.Key.PAYKIT_SESSION.name) + keychain.delete(Keychain.Key.PUBKY_SECRET_KEY.name) + keychain.delete(Keychain.Key.SHARED_PUBKY_SOURCE.name) + } sut = createSut() } @@ -187,6 +366,44 @@ class PubkyRepoTest : BaseUnitTest() { settingsStore = settingsStore, httpClient = httpClient, clock = clock, + profileRemovalStore = profileRemovalStore, + ) + + private fun PubkyRepo.removalCoordinatorForTest(): ProfileRemovalCoordinator { + val privateRepo = mock() + val sharing = mock() + whenever { sharing.withProfileRemoval(any()) }.doSuspendableAnswer { + it.getArgument PubkyProfileOwner>(0).invoke() + } + whenever { privateRepo.withProfileDeletionPaused(any()) }.doSuspendableAnswer { + it.getArgument Unit>(0) + .invoke(PrivatePaykitRepo.ProfileDeletionPause()) + } + whenever { privateRepo.removePublishedEndpointsForCleanup(any(), eq(true)) }.thenReturn(Result.success(Unit)) + whenever { privateRepo.finishProfileRemoval(any()) }.thenReturn(Result.success(Unit)) + return ProfileRemovalCoordinator(this, privateRepo, sharing, profileRemovalStore) + } + + private suspend fun PubkyRepo.signOut(): Result = runSuspendCatching { + val coordinator = removalCoordinatorForTest() + coordinator.remove(coordinator.prepareSignOut(profileOwner()).getOrThrow()).repositoryResult().getOrThrow() + } + + private suspend fun PubkyRepo.deleteProfile(): Result = runSuspendCatching { + val coordinator = removalCoordinatorForTest() + coordinator.remove(coordinator.prepareDeletion(profileOwner()).getOrThrow()).repositoryResult().getOrThrow() + } + + private suspend fun PubkyRepo.forgetUnrestoredIdentity(): Result = runSuspendCatching { + check(publicKey.value == null) + signOut().getOrThrow() + true + } + + /** These cases assert the repository failure; coordinator failure metadata has its own integration coverage. */ + private fun Result.repositoryResult(): Result = fold( + onSuccess = { Result.success(Unit) }, + onFailure = { Result.failure((it as? ProfileRemovalFailure)?.cause ?: it) }, ) private fun stubAdoptedRingSource() { @@ -1139,18 +1356,148 @@ class PubkyRepoTest : BaseUnitTest() { } @Test - fun `hasSecretKey should mark backup state changed when stale local secret is removed`() = test { + fun `credential availability remains readable while failed removal retains its identity`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("current_secret") + whenever(pubkyService.publicKeyFromSecret("current_secret")).thenReturn(VALID_SELF_KEY.removePrefix("pubky")) + whenever { pubkyService.withProfileRemoval(any(), any()) }.doSuspendableAnswer { + it.getArgument Unit>(1).invoke() + } + val release = CompletableDeferred() + val removal = async { + sut.performProfileRemoval(sut.profileOwner()) { + release.await() + throw TestAppError("unknown deletion outcome") + } + } + try { + runCurrent() + assertTrue(sut.hasSecretKey(), "temporary removal admission is not absence of the credential") + } finally { + release.complete(Unit) + } + assertTrue(removal.await().isFailure) + assertTrue(sut.hasSecretKey()) + } + + @Test + fun `cancelled credential derivation preserves the managed secret`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("current_secret") + val entered = CompletableDeferred() + whenever(pubkyService.publicKeyFromSecret("current_secret")).doSuspendableAnswer { + entered.complete(Unit) + awaitCancellation() + } + clearInvocations(keychain) + val read = launch { sut.hasSecretKey() } + entered.await() + read.cancelAndJoin() + verify(keychain, never()).delete(Keychain.Key.PUBKY_SECRET_KEY.name) + } + + @Test + fun `credential validation drains before identity replacement can install its secret`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + val ringPubky = stubRingCredential(VALID_CONTACT_KEY_A) + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("current_secret") + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever(pubkyService.publicKeyFromSecret("current_secret")).doSuspendableAnswer { + entered.complete(Unit) + release.await() + VALID_SELF_KEY.removePrefix("pubky") + } + val read = async { sut.hasSecretKey() } + entered.await() + val adoption = async { sut.adoptRingIdentity(ringPubky) } + try { + runCurrent() + assertFalse(adoption.isCompleted, "replacement must not overtake managed credential validation") + assertEquals(VALID_SELF_KEY, sut.publicKey.value) + } finally { + release.complete(Unit) + } + assertTrue(read.await()) + assertTrue(adoption.await().isSuccess) + assertEquals(VALID_CONTACT_KEY_A, sut.publicKey.value) + } + + @Test + fun `credential availability never deletes a stale local secret`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) val staleSecret = "stale_secret" whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(staleSecret) whenever(pubkyService.publicKeyFromSecret(staleSecret)).thenReturn(VALID_CONTACT_KEY_A.removePrefix("pubky")) val backupVersion = sut.backupStateVersion.value + clearInvocations(keychain) + + assertFalse(sut.hasSecretKey()) - val result = sut.hasSecretKey() + assertEquals(backupVersion, sut.backupStateVersion.value) + verify(keychain, never()).delete(any()) + } - assertFalse(result) + @Test + fun `credential availability can read the matching Ring key without removing a stale local key`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + stubAdoptedRingSource() + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("stale_secret") + whenever(pubkyService.publicKeyFromSecret("stale_secret")).thenReturn(VALID_CONTACT_KEY_A.removePrefix("pubky")) + whenever(sharedPubkyClient.ringCredential(VALID_SELF_KEY.removePrefix("pubky"))) + .thenReturn(Result.success("ring_secret")) + clearInvocations(keychain) + + assertTrue(sut.hasSecretKey()) + verify(keychain, never()).delete(any()) + } + + @Test + fun `authorization uses the matching Ring credential on its first attempt after stale key cleanup`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + stubAdoptedRingSource() + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("stale_secret") + whenever(pubkyService.publicKeyFromSecret("stale_secret")).thenReturn(VALID_CONTACT_KEY_A.removePrefix("pubky")) + whenever(sharedPubkyClient.ringCredential(VALID_SELF_KEY.removePrefix("pubky"))) + .thenReturn(Result.success("ring_secret")) + + assertTrue(sut.hasSecretKey()) + assertTrue(sut.approveAuth("auth", "capabilities", "client").isSuccess) + + verify(keychain).delete(Keychain.Key.PUBKY_SECRET_KEY.name) + verify(pubkyService).approveAuth("auth", "capabilities", "client", "ring_secret") + } + + @Test + fun `authorization invalidates its captured owner when removing a stale managed credential`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("stale_secret") + whenever(pubkyService.publicKeyFromSecret("stale_secret")).thenReturn(VALID_CONTACT_KEY_A.removePrefix("pubky")) + val owner = sut.profileOwner() + val backupVersion = sut.backupStateVersion.value + + assertTrue(sut.approveAuth("auth", "capabilities", "client").isFailure) + + assertFalse(sut.isProfileOwnerCurrent(owner)) assertEquals(backupVersion + 1, sut.backupStateVersion.value) - verifyBlocking(keychain) { delete(Keychain.Key.PUBKY_SECRET_KEY.name) } + verify(keychain).delete(Keychain.Key.PUBKY_SECRET_KEY.name) + verify(pubkyService, never()).approveAuth(any(), any(), any(), any()) + } + + @Test + fun `cancelled authorization derivation preserves the managed credential`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("current_secret") + val entered = CompletableDeferred() + whenever(pubkyService.publicKeyFromSecret("current_secret")).doSuspendableAnswer { + entered.complete(Unit) + awaitCancellation() + } + clearInvocations(keychain) + val approval = launch { sut.approveAuth("auth", "capabilities", "client") } + entered.await() + approval.cancelAndJoin() + verify(keychain, never()).delete(Keychain.Key.PUBKY_SECRET_KEY.name) } @Test @@ -1202,7 +1549,7 @@ class PubkyRepoTest : BaseUnitTest() { } @Test - fun `signOut should continue when endpoint cleanup fails`() = test { + fun `signOut retains identity and durable recovery when endpoint cleanup fails`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) settingsFlow.value = SettingsData( hasConfirmedPublicPaykitEndpoints = true, @@ -1215,34 +1562,34 @@ class PubkyRepoTest : BaseUnitTest() { val result = sut.signOut() - assertTrue(result.isSuccess) - assertNull(sut.publicKey.value) - assertFalse(sut.isAuthenticated.value) - assertTrue(settingsFlow.value.publicPaykitCleanupPending) - assertFalse(settingsFlow.value.hasConfirmedPublicPaykitEndpoints) - assertFalse(settingsFlow.value.sharesPublicPaykitEndpoints) - assertEquals("", settingsFlow.value.publicPaykitBolt11) - assertEquals("", settingsFlow.value.publicPaykitBolt11PaymentHash) - assertEquals(0, settingsFlow.value.publicPaykitBolt11ExpiresAtMillis) - verifyBlocking(pubkyService) { signOut() } - verifyBlocking(keychain, atLeastOnce()) { delete(Keychain.Key.PAYKIT_SESSION.name) } + assertTrue(result.isFailure) + assertEquals(VALID_SELF_KEY, sut.publicKey.value) + assertTrue(sut.isAuthenticated.value) + assertNotNull(profileRemovalStore.pendingAttempt()) + assertTrue(settingsFlow.value.hasConfirmedPublicPaykitEndpoints) + assertTrue(settingsFlow.value.sharesPublicPaykitEndpoints) + assertEquals("lnbc1old", settingsFlow.value.publicPaykitBolt11) + assertEquals("010203", settingsFlow.value.publicPaykitBolt11PaymentHash) + assertEquals(123L, settingsFlow.value.publicPaykitBolt11ExpiresAtMillis) + verifyBlocking(pubkyService, never()) { signOut() } + verifyBlocking(keychain, never()) { delete(Keychain.Key.PAYKIT_SESSION.name) } } @Test - fun `signOut should keep cleanup pending when private-only endpoint cleanup fails`() = test { + fun `signOut preserves private sharing and pending removal on endpoint failure`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) settingsFlow.value = SettingsData(sharesPrivatePaykitEndpoints = true) whenever(pubkyService.removeBitkitPaymentEndpoints()).thenAnswer { throw TestAppError("Cleanup failed") } val result = sut.signOut() - assertTrue(result.isSuccess) - assertNull(sut.publicKey.value) - assertFalse(sut.isAuthenticated.value) - assertTrue(settingsFlow.value.publicPaykitCleanupPending) - assertFalse(settingsFlow.value.sharesPrivatePaykitEndpoints) - verifyBlocking(pubkyService) { signOut() } - verifyBlocking(keychain, atLeastOnce()) { delete(Keychain.Key.PAYKIT_SESSION.name) } + assertTrue(result.isFailure) + assertEquals(VALID_SELF_KEY, sut.publicKey.value) + assertTrue(sut.isAuthenticated.value) + assertNotNull(profileRemovalStore.pendingAttempt()) + assertTrue(settingsFlow.value.sharesPrivatePaykitEndpoints) + verifyBlocking(pubkyService, never()) { signOut() } + verifyBlocking(keychain, never()) { delete(Keychain.Key.PAYKIT_SESSION.name) } } @Test @@ -1338,7 +1685,7 @@ class PubkyRepoTest : BaseUnitTest() { val screenLookup = async { sut.resolvePendingContactProfile(VALID_CONTACT_KEY_A) } val deletionStarted = CompletableDeferred() val finishDeletion = CompletableDeferred() - whenever(pubkyService.contactRecords()).doSuspendableAnswer { + whenever(pubkyService.removeContacts(records.map { it.publicKey })).doSuspendableAnswer { deletionStarted.complete(Unit) finishDeletion.await() records @@ -1381,7 +1728,7 @@ class PubkyRepoTest : BaseUnitTest() { assertTrue(result.isFailure) assertEquals(listOf(VALID_CONTACT_KEY_B), sut.contacts.value.map { it.publicKey }) assertEquals(setOf(VALID_CONTACT_KEY_B), stored.contactProfileOverrides.keys) - verify(pubkyService, never()).deletePaykitProfile() + verify(pubkyService, never()).deletePaykitProfile(any()) verify(pubkyService, never()).signOut() } @@ -1397,7 +1744,7 @@ class PubkyRepoTest : BaseUnitTest() { assertSame(error, result.exceptionOrNull()) verify(pubkyStore, never()).update(any()) verify(pubkyService, never()).removeContacts(any()) - verify(pubkyService, never()).deletePaykitProfile() + verify(pubkyService, never()).deletePaykitProfile(any()) verify(pubkyService, never()).signOut() } @@ -1417,7 +1764,7 @@ class PubkyRepoTest : BaseUnitTest() { assertSame(error, result.exceptionOrNull()) assertEquals(listOf(VALID_CONTACT_KEY_A), sut.contacts.value.map { it.publicKey }) verify(pubkyStore, never()).update(any()) - verify(pubkyService, never()).deletePaykitProfile() + verify(pubkyService, never()).deletePaykitProfile(any()) verify(pubkyService, never()).signOut() } @@ -1429,7 +1776,7 @@ class PubkyRepoTest : BaseUnitTest() { sharesPrivatePaykitEndpoints = true, ) val error = TestAppError("Delete failed: HTTP 404 Not Found at session endpoint") - whenever(pubkyService.deletePaykitProfile()).thenAnswer { throw error } + whenever(pubkyService.deletePaykitProfile(any())).thenAnswer { throw error } val result = sut.deleteProfile() @@ -1441,7 +1788,7 @@ class PubkyRepoTest : BaseUnitTest() { } @Test - fun `deleteProfile should fail when signOut fails`() = test { + fun `deleteProfile retains local evidence when revocation is uncertain`() = test { authenticateForTesting() settingsFlow.value = SettingsData( sharesPublicPaykitEndpoints = true, @@ -1453,9 +1800,10 @@ class PubkyRepoTest : BaseUnitTest() { val result = sut.deleteProfile() assertTrue(result.isFailure) - assertFalse(settingsFlow.value.sharesPublicPaykitEndpoints) - assertFalse(settingsFlow.value.sharesPrivatePaykitEndpoints) - assertTrue(settingsFlow.value.publicPaykitCleanupPending) + assertTrue(settingsFlow.value.sharesPublicPaykitEndpoints) + assertTrue(settingsFlow.value.sharesPrivatePaykitEndpoints) + assertNotNull(profileRemovalStore.pendingAttempt()) + verify(pubkyService, never()).forgetLocalProfileAccess() } @Test @@ -1465,12 +1813,14 @@ class PubkyRepoTest : BaseUnitTest() { whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(secretKey) whenever(pubkyService.publicKeyFromSecret(secretKey)).thenReturn(VALID_SELF_KEY.removePrefix("pubky")) val uncertainResponse = TestAppError("Connection closed after profile deletion") - whenever(pubkyService.deletePaykitProfile()).thenAnswer { throw uncertainResponse }.thenReturn(Unit) + whenever(pubkyService.deletePaykitProfile(any())).thenAnswer { + throw uncertainResponse + }.thenReturn(Unit) val result = sut.deleteProfile() assertSame(uncertainResponse, result.exceptionOrNull()) - verify(pubkyService).deletePaykitProfile() + verify(pubkyService).deletePaykitProfile(any()) verify(pubkyService, never()).signIn(any()) verify(pubkyService, never()).signOut() } @@ -1484,25 +1834,26 @@ class PubkyRepoTest : BaseUnitTest() { val deletionStarted = CompletableDeferred() val finishDeletion = CompletableDeferred() val uncertainResponse = TestAppError("Connection closed after profile deletion") - whenever(pubkyService.deletePaykitProfile()).doSuspendableAnswer { + whenever(pubkyService.deletePaykitProfile(any())).doSuspendableAnswer { deletionStarted.complete(Unit) withContext(NonCancellable) { finishDeletion.await() } throw uncertainResponse } val deletion = async { sut.deleteProfile() } deletionStarted.await() - sut.signOut().getOrThrow() + assertTrue(sut.signOut().isFailure) finishDeletion.complete(Unit) assertSame(uncertainResponse, deletion.await().exceptionOrNull()) + sut.signOut().getOrThrow() assertNull(sut.publicKey.value) assertFalse(sut.isAuthenticated.value) verify(pubkyService, never()).signIn(any()) - verify(pubkyService).deletePaykitProfile() + verify(pubkyService).deletePaykitProfile(any()) } @Test - fun `forgetUnrestoredIdentity clears an expired imported grant without remote calls`() = test { + fun `local disconnect clears an expired imported grant without remote calls`() = test { sut.awaitInitialization() var session: String? = "expired_session" whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenAnswer { session } @@ -1518,15 +1869,15 @@ class PubkyRepoTest : BaseUnitTest() { assertFalse(sut.hasIdentity()) assertNull(sut.profile.value) assertTrue(sut.contacts.value.isEmpty()) - verify(pubkyService).forgetSessionAccess() + verify(pubkyService).forgetLocalProfileAccess() verify(pubkyService, never()).signOut() verify(pubkyService, never()).removeBitkitPaymentEndpoints() - verify(pubkyService, never()).deletePaykitProfile() + verify(pubkyService, never()).deletePaykitProfile(any()) verify(pubkyStore).reset() } @Test - fun `forgetUnrestoredIdentity preserves identity restored while waiting for auth lock`() = test { + fun `local disconnect rejects an identity whose restoration is still admitted`() = test { sut.awaitInitialization() val importStarted = CompletableDeferred() val finishImport = CompletableDeferred() @@ -1539,13 +1890,13 @@ class PubkyRepoTest : BaseUnitTest() { val initialize = async { sut.initialize() } importStarted.await() val disconnect = async(start = CoroutineStart.UNDISPATCHED) { sut.forgetUnrestoredIdentity() } - assertFalse(disconnect.isCompleted) + assertTrue(disconnect.isCompleted) finishImport.complete(VALID_SELF_KEY) initialize.await() - assertEquals(false, disconnect.await().getOrThrow()) + assertSame(PubkyIdentityBusy, disconnect.await().exceptionOrNull()) assertEquals(VALID_SELF_KEY, sut.publicKey.value) - verify(pubkyService, never()).forgetSessionAccess() + verify(pubkyService, never()).forgetLocalProfileAccess() verify(keychain, never()).delete(Keychain.Key.PAYKIT_SESSION.name) } @@ -1561,16 +1912,16 @@ class PubkyRepoTest : BaseUnitTest() { val result = sut.signOut() assertTrue(result.isFailure) - verifyBlocking(pubkyService, never()) { forgetSessionAccess() } + verifyBlocking(pubkyService, never()) { forgetLocalProfileAccess() } verifyBlocking(keychain, never()) { delete(Keychain.Key.PAYKIT_SESSION.name) } assertTrue(sut.isAuthenticated.value) assertTrue(settingsFlow.value.sharesPublicPaykitEndpoints) assertTrue(settingsFlow.value.sharesPrivatePaykitEndpoints) - assertTrue(settingsFlow.value.publicPaykitCleanupPending) + assertNotNull(profileRemovalStore.pendingAttempt()) } @Test - fun `signOut should finish clearing state after caller cancellation`() = test { + fun `cancelled unacknowledged signOut retains credentials and durable recovery`() = test { val revocationStarted = CompletableDeferred() val finishRevocation = CompletableDeferred() authenticateForTesting() @@ -1585,9 +1936,10 @@ class PubkyRepoTest : BaseUnitTest() { finishRevocation.complete(Unit) result.join() - assertFalse(sut.isAuthenticated.value) - assertNull(sut.publicKey.value) - verifyBlocking(keychain, atLeastOnce()) { delete(Keychain.Key.PAYKIT_SESSION.name) } + assertTrue(sut.isAuthenticated.value) + assertNotNull(sut.publicKey.value) + assertNotNull(profileRemovalStore.pendingAttempt()) + verifyBlocking(keychain, never()) { delete(Keychain.Key.PAYKIT_SESSION.name) } } @Test @@ -4487,17 +4839,20 @@ class PubkyRepoTest : BaseUnitTest() { } @Test - fun `a sign-in taken while a sign-out resets the store ends once the identity is restored`() = test { + fun `signOut ends old sign-in before durable reset and later restoration cannot revive it`() = test { val store = stubGatedPubkyStore() authenticateForTesting(publicKey = VALID_SELF_KEY) - var signInDuringSignOut: PubkySignIn? = null + val signIn = checkNotNull(sut.currentSignIn()) + var resetObserved = false whenever(pubkyStore.reset()).thenAnswer { - signInDuringSignOut = sut.currentSignIn() + assertNull(sut.currentSignIn()) + assertFalse(sut.isCurrent(signIn)) + resetObserved = true store.data = PubkyStoreData() Unit } assertTrue(sut.signOut().isSuccess) - val signIn = checkNotNull(signInDuringSignOut) + assertTrue(resetObserved) authenticateForTesting(publicKey = VALID_SELF_KEY) val result = sut.updateContact(signIn, VALID_CONTACT_KEY_A, "Alice", "", null, emptyList(), listOf("Friend")) @@ -4749,7 +5104,9 @@ class PubkyRepoTest : BaseUnitTest() { whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn("test_secret") val records = listOf(createContactRecord(VALID_CONTACT_KEY_A, "Saved")) whenever(pubkyService.removeContacts(records.map { it.publicKey })).thenReturn(records) - whenever(pubkyService.deletePaykitProfile()).thenAnswer { throw TestAppError("Offline") } + whenever(pubkyService.deletePaykitProfile(any())).thenAnswer { + throw TestAppError("Offline") + } val newRead = createResolution(VALID_CONTACT_KEY_A, paykitProfile = createPaykitProfile("Alice", "New")) val oldRead = holdScreenLookup(VALID_CONTACT_KEY_A, laterRead = newRead) val deletionStarted = CompletableDeferred() diff --git a/app/src/test/java/to/bitkit/services/ActivityServicePaykitContactsTest.kt b/app/src/test/java/to/bitkit/services/ActivityServicePaykitContactsTest.kt index 2874cd3c9d..f0fcdc9bcc 100644 --- a/app/src/test/java/to/bitkit/services/ActivityServicePaykitContactsTest.kt +++ b/app/src/test/java/to/bitkit/services/ActivityServicePaykitContactsTest.kt @@ -27,6 +27,7 @@ import org.lightningdevkit.ldknode.PaymentStatus import org.mockito.Mockito.mockStatic import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify @@ -36,6 +37,7 @@ import to.bitkit.data.AppCacheData import to.bitkit.data.CacheStore import to.bitkit.data.PrivatePaykitCacheData import to.bitkit.data.PrivatePaykitCacheStore +import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.ext.create @@ -48,6 +50,7 @@ import to.bitkit.repositories.PrivatePaykitAddressReservationRepo import to.bitkit.repositories.PrivatePaykitContactResolver import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError +import java.util.UUID import javax.inject.Provider import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -63,6 +66,7 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { private val requestRepo = mock() private val reservations = mock() private val privateCacheStore = mock() + private val profileRemovalStore = ProfileRemovalStore.inMemoryForTesting() private val cacheStore = mock() private val cacheData = MutableStateFlow(AppCacheData(onchainAddress = "wallet-address")) private val settingsStore = mock() @@ -74,6 +78,7 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { cacheStore = privateCacheStore, addressReservationRepo = Provider { reservations }, paymentRequestRepo = Provider { requestRepo }, + profileRemovalStore = profileRemovalStore, ) } private val sut by lazy { @@ -86,6 +91,28 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { private var activityReads = 0 private var detailReads = 0 + @Test + fun `backfill drops a completed recovery generation and retries the current snapshot`() = coreTest { + rows = listOf(Activity.Onchain(onchain("request-address"))) + val outputs = listOf(output("request-address")) + details = mock { on { this.outputs }.thenReturn(outputs) } + sharedAddresses("request-address" to BUYER) + val id = UUID.randomUUID().toString() + whenever(reservations.contactPublicKeyForReservedAddress(any())).doSuspendableAnswer { + profileRemovalStore.withAccess(id) { + profileRemovalStore.begin(id) + profileRemovalStore.complete(id) + } + null + } + + assertFalse(sut.backfillPaykitContacts()) + assertTrue(updates.isEmpty()) + whenever(reservations.contactPublicKeyForReservedAddress(any())).thenReturn(null) + assertTrue(sut.backfillPaykitContacts()) + assertEquals(2, activityReads) + } + @Test fun `backfill matches receiving address in outputs and preserves all other onchain metadata`() = coreTest { val original = onchain(address = "request-address") diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkOperationLockTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkOperationLockTest.kt index d5c96eab32..258c9f8092 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkOperationLockTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkOperationLockTest.kt @@ -3,11 +3,16 @@ package to.bitkit.services import com.synonym.paykit.PaykitException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout import org.junit.Test import to.bitkit.services.PaykitSdkOperationLock.Priority import kotlin.coroutines.cancellation.CancellationException @@ -18,6 +23,182 @@ import kotlin.test.assertTrue @OptIn(ExperimentalCoroutinesApi::class) class PaykitSdkOperationLockTest { + @Test + fun `admitted outer mutex holder cannot enqueue behind a wipe draining that mutex`() = runTest { + val admitted = CompletableDeferred() + val continueAcquire = CompletableDeferred() + val outerMutex = Mutex() + var firstCheck = true + val lock = PaykitSdkOperationLock { + if (firstCheck) { + firstCheck = false + admitted.complete(Unit) + continueAcquire.await() + } + } + val oldOperation = async { + outerMutex.withLock { + assertFailsWith { lock.withLock { error("stale operation executed") } } + } + } + admitted.await() + val wipe = async { + lock.withWalletWipe { + continueAcquire.complete(Unit) + outerMutex.withLock { } + } + } + withTimeout(1_000) { + oldOperation.await() + wipe.await() + } + } + + @Test + fun `queued foreign work cannot resume after a complete removal`() = runTest { + val lock = PaykitSdkOperationLock() + val release = CompletableDeferred() + val active = launch { lock.withLock { release.await() } } + runCurrent() + val removal = launch { lock.withProfileRemoval({ true }) {} } + runCurrent() + var mutations = 0 + val queued = async { + assertFailsWith { lock.withLock { mutations++ } } + } + runCurrent() + release.complete(Unit) + active.join() + removal.join() + queued.await() + assertEquals(0, mutations) + lock.withLock { mutations++ } + assertEquals(1, mutations) + } + + @Test + fun `profile removal drains preceding work and excludes foreign mutations until finalization`() = runTest { + val lock = PaykitSdkOperationLock() + val release = CompletableDeferred() + val finishRemoval = CompletableDeferred() + val events = mutableListOf() + lateinit var oldRemoval: PaykitSdkOperationLock.ProfileRemoval + val preceding = launch { + lock.withLock { + release.await() + events += "preceding" + } + } + runCurrent() + val removal = launch { + lock.withProfileRemoval({ true }) { owner -> + oldRemoval = owner + lock.withLock { events += "owned" } + assertFailsWith { lock.withProfileRemoval({ true }) {} } + assertFailsWith { lock.withWalletWipe {} } + finishRemoval.await() + events += "finalized" + } + } + runCurrent() + assertTrue(events.isEmpty()) + release.complete(Unit) + preceding.join() + runCurrent() + assertEquals(listOf("preceding", "owned"), events) + assertFailsWith { lock.withLock { events += "foreign" } } + assertFailsWith { lock.withProfileRemoval({ true }) {} } + assertEquals("public", lock.withoutLock { "public" }) + assertEquals("handle", lock.withPublicReadInitialization { "handle" }) + finishRemoval.complete(Unit) + removal.join() + assertFailsWith { withContext(oldRemoval) { lock.withLock {} } } + lock.withLock { events += "fresh" } + assertEquals(listOf("preceding", "owned", "finalized", "fresh"), events) + } + + @Test + fun `wipe revokes profile removal and drains local finalization before taking SDK barrier`() = runTest { + val lock = PaykitSdkOperationLock() + val releaseCleanup = CompletableDeferred() + val events = mutableListOf() + val removal = launch { + lock.withProfileRemoval({ true }) { + try { + lock.withLock { events += "native" } + CompletableDeferred().await() + } finally { + withContext(NonCancellable) { + events += "cleanup started" + releaseCleanup.await() + assertFailsWith { lock.checkProfileRemoval() } + events += "cleanup drained" + } + } + } + } + runCurrent() + val wipe = launch { lock.withWalletWipe { lock.withLock { events += "wipe" } } } + runCurrent() + assertEquals(listOf("native", "cleanup started"), events) + assertFalse(wipe.isCompleted) + assertFailsWith { lock.withLock {} } + releaseCleanup.complete(Unit) + removal.join() + wipe.join() + assertEquals(listOf("native", "cleanup started", "cleanup drained", "wipe"), events) + lock.withLock {} + } + + @Test + fun `changed owner rejects the next mutation after a suspended read`() = runTest { + val lock = PaykitSdkOperationLock() + val read = CompletableDeferred() + var current = true + var mutations = 0 + val removal = async { + assertFailsWith { + lock.withProfileRemoval({ current }) { + lock.withLock { + read.await() + lock.checkProfileRemoval() + mutations++ + } + } + } + } + runCurrent() + current = false + read.complete(Unit) + assertEquals("profile_removal_obsolete", removal.await().code) + assertEquals(0, mutations) + lock.withLock {} + } + + @Test + fun `replacing coroutine Job cannot admit a cancelled removal mutation`() = runTest { + val lock = PaykitSdkOperationLock() + val release = CompletableDeferred() + var rejected = false + val removal = launch { + lock.withProfileRemoval({ true }) { + withContext(NonCancellable) { + release.await() + assertFailsWith { lock.withLock { error("cancelled mutation ran") } } + rejected = true + } + } + } + runCurrent() + removal.cancel() + assertFalse(removal.isCompleted) + assertFailsWith { lock.withLock {} } + release.complete(Unit) + removal.join() + assertTrue(rejected) + lock.withLock {} + } + @Test fun `interactive work overtakes only queued publication with bounded fairness`() = runTest { val lock = PaykitSdkOperationLock() diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt index f4056f8672..85123ce5d2 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt @@ -15,6 +15,7 @@ import com.synonym.paykit.PaykitAppCapabilities import com.synonym.paykit.PaykitAppRegistry import com.synonym.paykit.PaykitException import com.synonym.paykit.PaykitIdentitySecretKey +import com.synonym.paykit.PaykitProfileRecord import com.synonym.paykit.PaykitSdk import com.synonym.paykit.PaykitStateObservation import com.synonym.paykit.PaymentPayload @@ -47,6 +48,7 @@ import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.awaitCancellation @@ -59,6 +61,8 @@ import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.currentTime import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout import org.junit.Test import org.mockito.Mockito.mockConstruction import org.mockito.Mockito.mockStatic @@ -76,6 +80,8 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever import to.bitkit.async.ServiceQueue +import to.bitkit.data.ProfileRemovalPending +import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.PubkyStore import to.bitkit.data.PubkyStoreData import to.bitkit.data.SettingsData @@ -96,6 +102,7 @@ import to.bitkit.repositories.PubkyContactError import to.bitkit.services.PaykitSdkOperationLock.Priority import to.bitkit.test.forEachCase import to.bitkit.utils.AppError +import java.util.UUID import kotlin.coroutines.cancellation.CancellationException import kotlin.test.assertContentEquals import kotlin.test.assertEquals @@ -110,6 +117,442 @@ import kotlin.time.Duration.Companion.seconds @OptIn(ExperimentalCoroutinesApi::class) class PaykitSdkServiceTest { + @Test + fun `recovery admission lets a direct SDK wipe revoke an idle removal before waiting on publication`() = runTest { + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { mock() } + val removal = launch { service.withProfileRemoval({ true }) { awaitCancellation() } } + runCurrent() + var entered = false + try { + withTimeout(1_000) { service.withWalletWipe { entered = true } } + assertTrue(entered) + assertTrue(removal.isCompleted) + } finally { + removal.cancel() + removal.join() + } + } + + @Test + fun `profile removal recovery rejects bootstrap publication before loading retained keys`() = runTest { + val pending = ProfileRemovalStore.inMemoryForTesting() + val id = UUID.randomUUID().toString() + pending.withAccess(id) { pending.begin(id) } + val sdk = mock() + val bootstrap = mock() + val service = PaykitSdkService( + mock(), + mock(), + mock(), + { bootstrap }, + settingsStore = mock(), + profileRemovalStore = pending, + ) { sdk } + assertFailsWith { service.republishIdentityIfNeeded(RING_PUBKY) } + assertFailsWith { service.hasIdentityRecord(RING_PUBKY) } + verifyNoInteractions(bootstrap) + verify(sdk, never()).initialize() + } + + @Test + fun `profile removal recovery drains admitted publication while ordinary public reads continue`() = runTest { + val sdk = mock() + val bootstrap = mock() + val published = CompletableDeferred() + whenever(bootstrap.republishIdentity(any())).doSuspendableAnswer { published.await() } + val service = PaykitSdkService( + mock(), + mock(), + mock(), + { bootstrap }, + ioDispatcher = StandardTestDispatcher(testScheduler), + settingsStore = mock(), + ) { sdk } + val publishing = async { service.republishIdentityIfNeeded(RING_PUBKY) } + runCurrent() + var removalEntered = false + val removal = async { service.withProfileRemoval({ true }) { removalEntered = true } } + try { + runCurrent() + assertFalse(removalEntered) + assertNull(service.fetchPubkyProfile(RING_PUBKY)) + } finally { + published.complete(true) + publishing.await() + removal.await() + } + assertTrue(removalEntered) + } + + @Test + fun `profile recovery releases public reads already awaiting cold setup`() = runTest { + val sdk = mock() + val service = PaykitSdkService(mock(), mock(), mock(), platformInitializer = {}, settingsStore = mock()) { sdk } + val reading = async { withTimeout(1_000) { service.fetchPubkyProfile(RING_PUBKY) } } + runCurrent() + service.preparePublicProfileRecovery() + assertNull(reading.await()) + verify(sdk, never()).initialize() + } + + @Test + fun `profile recovery exposes platform failure to waiters and permits explicit setup retry`() = runTest { + val sdk = mock() + var failed = true + val failure = IllegalStateException("Platform unavailable") + val service = PaykitSdkService( + mock(), + mock(), + mock(), + platformInitializer = { if (failed) throw failure }, + settingsStore = mock(), + ) { sdk } + assertSame(failure, assertFailsWith { service.preparePublicProfileRecovery() }) + val waiterFailure = assertFailsWith { + withTimeout(1_000) { service.fetchPubkyProfile(RING_PUBKY) } + } + assertEquals(failure.javaClass, waiterFailure.javaClass) + assertTrue(generateSequence(waiterFailure) { it.cause }.any { it === failure }) + failed = false + service.preparePublicProfileRecovery() + assertNull(service.fetchPubkyProfile(RING_PUBKY)) + verify(sdk, never()).initialize() + } + + @Test + fun `profile recovery promotion drains admitted native work before resetting runtime`() = runTest { + val sdk = mock() + val release = CompletableDeferred() + whenever(sdk.contactRecords()).doSuspendableAnswer { + release.await() + emptyList() + } + val service = PaykitSdkService(mock(), mock(), mock(), platformInitializer = {}, settingsStore = mock()) { sdk } + service.preparePublicProfileRecovery() + val read = async { service.contactRecords() } + runCurrent() + val before = service.runtimeGeneration + val initialize = async { service.initialize() } + try { + runCurrent() + assertEquals(before, service.runtimeGeneration) + verify(sdk, never()).initialize() + } finally { + release.complete(Unit) + read.await() + initialize.await() + } + } + + @Test + fun `profile recovery permits wipe drainage without activating retained credentials`() = runTest { + val pending = ProfileRemovalStore.inMemoryForTesting() + val id = UUID.randomUUID().toString() + pending.withAccess(id) { pending.begin(id) } + val sdk = mock() + val service = PaykitSdkService( + mock(), + mock(), + mock(), + platformInitializer = {}, + settingsStore = mock(), + profileRemovalStore = pending, + ) { sdk } + withTimeout(1_000) { + service.withWalletWipe { assertNull(service.fetchPubkyProfile(RING_PUBKY)) } + } + verify(sdk, never()).initialize() + assertEquals(id, pending.pendingAttempt()) + } + + @Test + fun `pending restart permits public reads and strict local disconnect without activation`() = runTest { + val pending = ProfileRemovalStore.inMemoryForTesting() + val id = UUID.randomUUID().toString() + pending.withAccess(id) { pending.begin(id) } + val sdk = mock() + val keychain = mock() + val blocking = mock() + whenever(keychain.accessBlocking(any())).doAnswer { + it.getArgument Any?>(0).invoke(blocking) + } + var platformSetups = 0 + val service = PaykitSdkService( + mock(), + keychain, + mock(), + platformInitializer = { platformSetups++ }, + settingsStore = mock(), + profileRemovalStore = pending, + ) { sdk } + assertFailsWith { service.initialize() } + assertEquals(0, platformSetups) + service.preparePublicProfileRecovery() + assertEquals(1, platformSetups) + assertNull(service.fetchPubkyProfile(RING_PUBKY)) + assertFailsWith { service.contactRecords() } + assertFailsWith { service.forgetLocalProfileAccess() } + val failure = IllegalStateException("Credential storage unavailable") + org.mockito.kotlin.doThrow(failure).whenever(blocking).delete(Keychain.Key.SHARED_PUBKY_SOURCE.name) + pending.withAccess(id) { + service.withProfileRemoval({ true }) { + assertFailsWith { service.forgetLocalProfileAccess() } + } + } + assertEquals(id, pending.pendingAttempt()) + pending.withAccess(id) { assertFailsWith { service.initialize() } } + verify(sdk, never()).initialize() + verify(sdk, never()).signOut() + verify(sdk, never()).forgetSessionAccess() + org.mockito.kotlin.doNothing().whenever(blocking).delete(Keychain.Key.SHARED_PUBKY_SOURCE.name) + pending.withAccess(id) { + service.withProfileRemoval({ true }) { service.forgetLocalProfileAccess() } + pending.complete(id) + } + verify(blocking).delete(Keychain.Key.PAYKIT_SESSION.name) + verify(blocking).delete(Keychain.Key.PUBKY_SECRET_KEY.name) + service.initialize() + verify(sdk).initialize() + assertEquals(1, platformSetups) + } + + @Test + fun `cancellation after confirmed profile deletion retains backup dirtiness`() = runTest { + val sdk = mock() + whenever( + sdk.identityStatus() + ).thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + val profile = mock() + whenever(profile.revision).thenReturn("confirmed") + whenever(sdk.fetchPaykitProfile(RING_PUBKY)).thenReturn(profile) + whenever(sdk.contactRecords()).thenReturn(emptyList()) + val release = CompletableDeferred() + whenever(sdk.deletePaykitProfile("confirmed")).doSuspendableAnswer { release.await() } + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + val snapshot = service.captureProfileDeletion(RING_PUBKY) { true } + val before = service.backupStateVersion.value + val removal = launch { service.withProfileRemoval({ true }) { service.deletePaykitProfile(snapshot) } } + runCurrent() + removal.cancel() + assertFalse(removal.isCompleted) + release.complete(Unit) + removal.join() + verify(sdk).deletePaykitProfile("confirmed") + assertTrue(service.backupStateVersion.value > before) + } + + @Test + fun `profile deletion uses the confirmed revision without fetching a newer profile`() = runTest { + val sdk = mock() + whenever( + sdk.identityStatus() + ).thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + val profile = mock() + whenever(profile.revision).thenReturn("confirmed") + whenever(sdk.fetchPaykitProfile(RING_PUBKY)).thenReturn(profile) + whenever(sdk.contactRecords()).thenReturn(emptyList()) + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + val snapshot = service.captureProfileDeletion("pubky$RING_PUBKY") { true } + whenever(profile.revision).thenReturn("later-edit") + val uncertain = IllegalStateException("Response lost") + whenever(sdk.deletePaykitProfile("confirmed")).thenThrow(uncertain) + + val result = runSuspendCatching { service.deletePaykitProfile(snapshot) } + + assertSame(uncertain, result.exceptionOrNull()) + verify(sdk).deletePaykitProfile("confirmed") + verify(sdk, times(1)).fetchPaykitProfile(RING_PUBKY) + verify(sdk, never()).deletePaykitProfile("later-edit") + } + + @Test + fun `profile reconciliation rejects later profile and contact changes without mutations`() = runTest { + val sdk = mock() + whenever( + sdk.identityStatus() + ).thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + val profile = mock() + whenever(profile.revision).thenReturn("original") + whenever(sdk.fetchPaykitProfile(RING_PUBKY)).thenReturn(profile) + val contact = mock() + whenever(sdk.contactRecords()).thenReturn(listOf(contact)) + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + val snapshot = service.captureProfileDeletion(RING_PUBKY) { true } + whenever(profile.revision).thenReturn("changed") + assertFailsWith { service.validateProfileDeletion(snapshot) } + whenever(profile.revision).thenReturn("original") + whenever(sdk.contactRecords()).thenReturn(emptyList()) + assertFailsWith { service.validateProfileDeletion(snapshot) } + verify(sdk, never()).deletePaykitProfile(any()) + verify(sdk, never()).removeContactsAndBlockPeers(any()) + } + + @Test + fun `profile capture rejects identity replacement during its read`() = runTest { + val sdk = mock() + whenever( + sdk.identityStatus() + ).thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + var current = true + whenever(sdk.contactRecords()).thenAnswer { + current = false + emptyList() + } + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + assertFailsWith { service.captureProfileDeletion(RING_PUBKY) { current } } + verify(sdk, never()).deletePaykitProfile(any()) + } + + @Test + fun `confirmed missing profile does not authorize deleting a subsequently created profile`() = runTest { + val sdk = mock() + whenever( + sdk.identityStatus() + ).thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + whenever(sdk.contactRecords()).thenReturn(emptyList()) + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + val snapshot = service.captureProfileDeletion(RING_PUBKY) { true } + whenever(sdk.fetchPaykitProfile(RING_PUBKY)).thenReturn(mock()) + assertFailsWith { service.deletePaykitProfile(snapshot) } + verify(sdk, never()).deletePaykitProfile(any()) + } + + @Test + fun `profile removal rejects foreign reset but permits cold public lookup`() = runTest { + val sdk = mock() + whenever(sdk.contactRecords()).thenReturn(emptyList()) + val release = CompletableDeferred() + var handles = 0 + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { + handles++ + sdk + } + val removal = launch { service.withProfileRemoval({ true }) { release.await() } } + runCurrent() + assertEquals(0, handles) + assertNull(service.fetchPubkyProfile(RING_PUBKY)) + assertEquals(1, handles) + assertFailsWith { service.signOut() } + assertFailsWith { service.forgetSessionAccess() } + assertFailsWith { service.clearState() } + verify(sdk, never()).signOut() + verify(sdk, never()).forgetSessionAccess() + release.complete(Unit) + removal.join() + assertEquals(emptyList(), service.contactRecords()) + assertEquals(1, handles) + } + + @Test + fun `cancelled removal does not delete after an awaited profile read with replaced Job`() = runTest { + val sdk = mock() + whenever( + sdk.identityStatus() + ).thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + val release = CompletableDeferred() + val profile = mock() + whenever(profile.revision).thenReturn("confirmed-profile-revision") + whenever(sdk.fetchPaykitProfile(RING_PUBKY)).doSuspendableAnswer { + release.await() + profile + } + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + var rejected = false + val removal = launch { + service.withProfileRemoval({ true }) { + withContext(NonCancellable) { + assertFailsWith { service.deletePaykitProfile() } + rejected = true + } + } + } + runCurrent() + removal.cancel() + assertFalse(removal.isCompleted) + assertFailsWith { service.clearState() } + release.complete(Unit) + removal.join() + assertTrue(rejected) + verify(sdk, never()).deletePaykitProfile(any()) + } + + @Test + fun `wipe waits for admitted removal mutation and local finalization before resetting SDK`() = runTest { + val sdk = mock() + whenever( + sdk.identityStatus() + ).thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + val profile = mock() + whenever(profile.revision).thenReturn("confirmed-profile-revision") + whenever(sdk.fetchPaykitProfile(RING_PUBKY)).thenReturn(profile) + val releaseNative = CompletableDeferred() + val releaseLocal = CompletableDeferred() + val events = mutableListOf() + whenever(sdk.deletePaykitProfile(any())).doSuspendableAnswer { + events += "native admitted" + releaseNative.await() + events += "native drained" + } + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + val removal = launch { + service.withProfileRemoval({ true }) { + try { + service.deletePaykitProfile() + } finally { + withContext(NonCancellable) { + releaseLocal.await() + events += "local drained" + } + } + } + } + try { + runCurrent() + assertEquals(listOf("native admitted"), events) + val wipe = launch { service.withWalletWipe { events += "wipe" } } + runCurrent() + assertFalse(wipe.isCompleted) + releaseNative.complete(Unit) + runCurrent() + assertEquals(listOf("native admitted", "native drained"), events) + assertFalse(wipe.isCompleted) + releaseLocal.complete(Unit) + removal.join() + wipe.join() + assertEquals(listOf("native admitted", "native drained", "local drained", "wipe"), events) + verify(sdk).deletePaykitProfile("confirmed-profile-revision") + } finally { + releaseNative.complete(Unit) + releaseLocal.complete(Unit) + removal.cancel() + } + } + + @Test + fun `completed removal mutation keeps backup invalidation when original Job cancels bookkeeping`() = runTest { + val sdk = mock() + whenever(sdk.backupStateRevision()).thenReturn("before") + val release = CompletableDeferred() + whenever(sdk.processPendingPrivateMessages()).doSuspendableAnswer { + release.await() + emptyList() + } + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + val removal = launch { + service.withProfileRemoval({ true }) { + withContext(NonCancellable) { + assertFailsWith { service.processPendingPrivateMessages() } + } + } + } + runCurrent() + removal.cancel() + release.complete(Unit) + removal.join() + verify(sdk).processPendingPrivateMessages() + assertEquals(1L, service.backupStateVersion.value) + } + companion object { private const val RING_PUBKY = "3rsduhcxpw74snwyct86m38c63j3pq8x4ycqikxg64roik8yw5xg" private const val FILE_URI = "pubky://$RING_PUBKY/pub/pubky.app/files/avatar" diff --git a/app/src/test/java/to/bitkit/ui/screens/contacts/ContactSaveSessionChangeTest.kt b/app/src/test/java/to/bitkit/ui/screens/contacts/ContactSaveSessionChangeTest.kt index 9645c467ea..ba8842ceba 100644 --- a/app/src/test/java/to/bitkit/ui/screens/contacts/ContactSaveSessionChangeTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/contacts/ContactSaveSessionChangeTest.kt @@ -22,10 +22,12 @@ import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.PubkyImageCacheEpoch import to.bitkit.data.PubkyStore import to.bitkit.data.PubkyStoreData @@ -33,16 +35,21 @@ import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.data.keychain.Keychain import to.bitkit.data.sharedpubky.SharedPubkyClient +import to.bitkit.ext.runSuspendCatching import to.bitkit.models.PubkyProfile import to.bitkit.models.Toast +import to.bitkit.repositories.ContactPaymentSettingsRepo import to.bitkit.repositories.PaykitPaymentRequestRepo import to.bitkit.repositories.PaykitPaymentRequestTargetCheck +import to.bitkit.repositories.PrivatePaykitRepo import to.bitkit.repositories.PubkyContactError +import to.bitkit.repositories.PubkyProfileOwner import to.bitkit.repositories.PubkyRepo import to.bitkit.services.PaykitReadLane import to.bitkit.services.PubkyService import to.bitkit.test.BaseUnitTest import to.bitkit.ui.shared.toast.ToastEventBus +import to.bitkit.usecases.ProfileRemovalCoordinator import kotlin.test.assertEquals import kotlin.test.assertTrue import kotlin.time.Clock @@ -83,6 +90,7 @@ class ContactSaveSessionChangeTest : BaseUnitTest() { private var heldSave: CompletableDeferred? = null private var heldSaveSucceeds = true + private val removalStore = ProfileRemovalStore.inMemoryForTesting() private lateinit var repo: PubkyRepo @Before @@ -105,6 +113,10 @@ class ContactSaveSessionChangeTest : BaseUnitTest() { } whenever { pubkyService.contactRecords() }.thenReturn(emptyList()) whenever { pubkyService.observedContactRecords(any()) }.doSuspendableAnswer { pubkyService.contactRecords() } + whenever { pubkyService.withProfileRemoval(any(), any()) }.doSuspendableAnswer { + check(it.getArgument<() -> Boolean>(0).invoke()) + it.getArgument Unit>(1).invoke() + } whenever { pubkyService.signOut() }.thenAnswer { sdkIdentity = null Unit @@ -127,6 +139,7 @@ class ContactSaveSessionChangeTest : BaseUnitTest() { settingsStore = settingsStore, httpClient = mock(), clock = clock, + profileRemovalStore = removalStore, ) } @@ -272,6 +285,22 @@ class ContactSaveSessionChangeTest : BaseUnitTest() { assertTrue(repo.signOut().isSuccess) } + private suspend fun PubkyRepo.signOut(): Result = runSuspendCatching { + val privateRepo = mock() + val sharing = mock() + whenever { sharing.withProfileRemoval(any()) }.doSuspendableAnswer { + it.getArgument PubkyProfileOwner>(0).invoke() + } + whenever { privateRepo.withProfileDeletionPaused(any()) }.doSuspendableAnswer { + it.getArgument Unit>(0) + .invoke(PrivatePaykitRepo.ProfileDeletionPause()) + } + whenever { privateRepo.removePublishedEndpointsForCleanup(any(), eq(true)) }.thenReturn(Result.success(Unit)) + whenever { privateRepo.finishProfileRemoval(any()) }.thenReturn(Result.success(Unit)) + val coordinator = ProfileRemovalCoordinator(this, privateRepo, sharing, removalStore) + coordinator.remove(coordinator.prepareSignOut(profileOwner()).getOrThrow()).getOrThrow() + } + private suspend fun fakeSdkSave( publicKey: String, expectedIdentity: String?, diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt index 30f48762ae..627e4ffd85 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt @@ -4,141 +4,234 @@ import android.content.Context import androidx.lifecycle.viewModelScope import app.cash.turbine.test import kotlinx.collections.immutable.toImmutableList +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.test.advanceUntilIdle import org.junit.Test -import org.mockito.Mockito.clearInvocations import org.mockito.kotlin.any import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq -import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever -import to.bitkit.R import to.bitkit.models.PubkyProfile import to.bitkit.models.PubkyProfileLink -import to.bitkit.repositories.PrivatePaykitRepo +import to.bitkit.repositories.PubkyProfileOwner import to.bitkit.repositories.PubkyRepo +import to.bitkit.repositories.PubkySignIn import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError import kotlin.test.assertEquals import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull import kotlin.test.assertTrue @OptIn(ExperimentalCoroutinesApi::class) class EditProfileViewModelTest : BaseUnitTest() { - companion object { - private const val TEST_PUBLIC_KEY = "pubkyalice" - } - + companion object { private const val TEST_PUBLIC_KEY = "pubkyalice" } private val context: Context = mock() private val pubkyRepo: PubkyRepo = mock() - private val privatePaykitRepo: PrivatePaykitRepo = mock() + private val fixture = ProfileRemovalUiFixture(pubkyRepo) @Test - fun `disconnect finishes private cleanup after the screen is closed`() = test { + fun `confirmation is required and consumed once`() = test { val sut = createSut() - val forget = CompletableDeferred>() - whenever(pubkyRepo.forgetUnrestoredIdentity()).doSuspendableAnswer { forget.await() } - advanceUntilIdle() - - sut.disconnectProfile() advanceUntilIdle() - assertTrue(sut.uiState.value.isDeleting) - assertFalse(sut.uiState.value.isSaving) - assertTrue(sut.uiState.value.isBusy) - - sut.disconnectProfile() sut.deleteProfile() - sut.save() + advanceUntilIdle() + verify(pubkyRepo, never()).deleteProfile(any()) sut.showDeleteConfirmation() advanceUntilIdle() - verify(pubkyRepo, times(1)).forgetUnrestoredIdentity() - verify(pubkyRepo, never()).deleteProfile() - verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any()) - assertFalse(sut.uiState.value.showDeleteDialog) + assertTrue(sut.uiState.value.showDeleteDialog) + sut.effects.test { + sut.deleteProfile() + sut.deleteProfile() + advanceUntilIdle() + val effect = assertIs(awaitItem()) + assertTrue(sut.isRemovalCurrent(effect)) + fixture.current = PubkyProfileOwner(PubkySignIn(TEST_PUBLIC_KEY, 3), 3) + assertFalse(sut.isRemovalCurrent(effect)) + expectNoEvents() + } + verify(pubkyRepo, times(1)).deleteProfile(fixture.deletion) + assertNull(fixture.store.pendingAttempt()) + } - sut.viewModelScope.cancel() - forget.complete(Result.success(true)) + @Test + fun `uncertain deletion review reads state and requires fresh confirmation`() = test { + val sut = createSut() + whenever(pubkyRepo.deleteProfile(fixture.deletion)).thenReturn(Result.failure(TestAppError("lost response"))) advanceUntilIdle() - - assertFalse(sut.uiState.value.isDeleting) - assertFalse(sut.uiState.value.isBusy) - verify(privatePaykitRepo).closeAndClear() - verify(pubkyRepo, never()).signOut() + sut.showDeleteConfirmation() + advanceUntilIdle() + sut.deleteProfile() + advanceUntilIdle() + assertTrue(sut.uiState.value.showDeleteFailureDialog) + assertNotNull(fixture.store.pendingAttempt()) + sut.retryDeleteProfile() + advanceUntilIdle() + assertTrue(sut.uiState.value.showDeleteDialog) + verify(pubkyRepo, times(2)).prepareProfileDeletion(fixture.original) + verify(pubkyRepo, times(1)).deleteProfile(fixture.deletion) + sut.dismissDeleteDialog() + assertTrue(sut.uiState.value.showDeleteFailureDialog) + sut.deleteProfile() + advanceUntilIdle() + verify(pubkyRepo, times(1)).deleteProfile(fixture.deletion) } @Test - fun `disconnect forgets unrestored identity without remote cleanup`() = test { + fun `failure disconnect asks again and never replays remote cleanup`() = test { val sut = createSut() - whenever(pubkyRepo.forgetUnrestoredIdentity()).thenReturn(Result.success(true)) - whenever(privatePaykitRepo.removePublishedEndpointsForCleanup(any())) - .thenReturn(Result.failure(AppError("No session"))) + whenever(pubkyRepo.deleteProfile(fixture.deletion)).thenReturn(Result.failure(TestAppError("lost response"))) advanceUntilIdle() - + sut.showDeleteConfirmation() + advanceUntilIdle() + sut.deleteProfile() + advanceUntilIdle() + sut.disconnectProfile() + advanceUntilIdle() + assertTrue(sut.uiState.value.showDeleteDialog) + assertTrue(sut.uiState.value.isLocalDisconnect) + verify(pubkyRepo, never()).finishProfileRemovalLocally() sut.effects.test { - sut.disconnectProfile() + sut.deleteProfile() advanceUntilIdle() - assertEquals(EditProfileEffect.DisconnectSuccess, awaitItem()) + assertIs(awaitItem()) } - - assertFalse(sut.uiState.value.isDeleting) - verify(privatePaykitRepo, never()).removePublishedEndpointsForCleanup(any()) - verify(pubkyRepo, never()).signOut() - verify(privatePaykitRepo).closeAndClear() + verify(pubkyRepo, times(1)).deleteProfile(fixture.deletion) + verify(pubkyRepo, never()).signOutForProfileRemoval() + verify(fixture.privateRepo, times(1)).removePublishedEndpointsForCleanup(any(), eq(true)) + assertNull(fixture.store.pendingAttempt()) } @Test - fun `failed local disconnect preserves private state`() = test { + fun `failed private cleanup retains marker and stops profile deletion`() = test { val sut = createSut() - whenever(pubkyRepo.forgetUnrestoredIdentity()).thenReturn(Result.failure(AppError("Storage failed"))) + whenever(fixture.privateRepo.removePublishedEndpointsForCleanup(any(), eq(true))) + .thenReturn(Result.failure(TestAppError("pending cleanup"))) + advanceUntilIdle() + sut.showDeleteConfirmation() advanceUntilIdle() + sut.effects.test { + sut.deleteProfile() + advanceUntilIdle() + expectNoEvents() + } + assertTrue(sut.uiState.value.showDeleteFailureDialog) + assertNotNull(fixture.store.pendingAttempt()) + verify(pubkyRepo, never()).deleteProfile(any()) + verify(fixture.privateRepo, never()).finishProfileRemoval(any()) + } + @Test + fun `local cleanup failure offers only local completion and retains safety state`() = test { + val sut = createSut() + whenever(fixture.privateRepo.finishProfileRemoval(fixture.pause)) + .thenReturn(Result.failure(TestAppError("disk unavailable"))) + advanceUntilIdle() + sut.showDeleteConfirmation() + advanceUntilIdle() + sut.effects.test { + sut.deleteProfile() + advanceUntilIdle() + expectNoEvents() + } + assertTrue(sut.uiState.value.showDeleteFailureDialog) + assertFalse(sut.uiState.value.canReviewRemoval) + assertNotNull(fixture.store.pendingAttempt()) + sut.retryDeleteProfile() + advanceUntilIdle() + assertFalse(sut.uiState.value.showDeleteDialog) sut.disconnectProfile() advanceUntilIdle() - - assertFalse(sut.uiState.value.isDeleting) - verify(privatePaykitRepo, never()).closeAndClear() - verify(pubkyRepo, never()).signOut() + assertTrue(sut.uiState.value.isLocalDisconnect) + assertTrue(sut.uiState.value.showDeleteDialog) } @Test - fun `pending deletion blocks duplicate actions and clears progress on failure`() = test { + fun `cancelled screen preserves pending removal without success`() = test { val sut = createSut() + val cleanup = CompletableDeferred>() + whenever(fixture.privateRepo.removePublishedEndpointsForCleanup(any(), eq(true))) + .doSuspendableAnswer { cleanup.await() } advanceUntilIdle() - val result = CompletableDeferred>() - whenever(pubkyRepo.deleteProfile()).doSuspendableAnswer { result.await() } - sut.showDeleteConfirmation() + advanceUntilIdle() sut.deleteProfile() advanceUntilIdle() assertTrue(sut.uiState.value.isDeleting) - assertFalse(sut.uiState.value.isSaving) - assertTrue(sut.uiState.value.isBusy) + sut.deleteProfile() + sut.disconnectProfile() + sut.save() + advanceUntilIdle() + verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any()) + sut.viewModelScope.cancel() + advanceUntilIdle() + assertFalse(sut.uiState.value.isBusy) + assertNotNull(fixture.store.pendingAttempt()) + verify(pubkyRepo, never()).deleteProfile(any()) + verify(fixture.privateRepo, never()).finishProfileRemoval(any()) + } + + @Test + fun `replacement identity cannot be removed from an older profile screen`() = test { + val sut = createSut() + advanceUntilIdle() + fixture.current = PubkyProfileOwner(PubkySignIn(TEST_PUBLIC_KEY, 3), 3) + sut.showDeleteConfirmation() + advanceUntilIdle() assertFalse(sut.uiState.value.showDeleteDialog) + verify(pubkyRepo, never()).prepareProfileDeletion(any()) + verify(pubkyRepo, never()).deleteProfile(any()) + } + @Test + fun `dismissal or replacement during preparation cannot reopen confirmation`() = test { + val sut = createSut() + val snapshot = CompletableDeferred>() + whenever(pubkyRepo.prepareProfileDeletion(fixture.original)).doSuspendableAnswer { snapshot.await() } + advanceUntilIdle() + sut.showDeleteConfirmation() + advanceUntilIdle() + assertTrue(sut.uiState.value.isPreparingRemoval) + sut.dismissDeleteDialog() + snapshot.complete(Result.success(fixture.deletion)) + advanceUntilIdle() + assertFalse(sut.uiState.value.showDeleteDialog) sut.deleteProfile() - sut.retryDeleteProfile() - sut.save() - sut.disconnectProfile() + verify(pubkyRepo, never()).deleteProfile(any()) + } + + @Test + fun `delayed Ring lookup does not install a replaced profile`() = test { + val ring = CompletableDeferred() + val sut = createSut(ringCheck = ring) + advanceUntilIdle() + fixture.current = PubkyProfileOwner(PubkySignIn("replacement", 2), 2) + ring.complete(true) + advanceUntilIdle() + assertEquals("", sut.uiState.value.name) sut.showDeleteConfirmation() advanceUntilIdle() - verify(pubkyRepo, times(1)).deleteProfile() - verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any()) - verify(pubkyRepo, never()).signOut() assertFalse(sut.uiState.value.showDeleteDialog) + } - result.complete(Result.failure(TestAppError("Offline"))) + @Test + fun `managed and Ring identity keep distinct removal copy`() = test { + val sut = createSut(isRingIdentity = true) advanceUntilIdle() - assertFalse(sut.uiState.value.isDeleting) - assertFalse(sut.uiState.value.isBusy) - assertTrue(sut.uiState.value.showDeleteFailureDialog) + assertEquals(ProfileRemoval.UNLINK, sut.uiState.value.removal) + sut.showDeleteConfirmation() + advanceUntilIdle() + assertFalse(sut.uiState.value.isLocalDisconnect) } @Test @@ -161,8 +254,8 @@ class EditProfileViewModelTest : BaseUnitTest() { sut.showDeleteConfirmation() advanceUntilIdle() verify(pubkyRepo, times(1)).saveProfile(any(), any(), any(), any(), any()) - verify(pubkyRepo, never()).deleteProfile() - verify(pubkyRepo, never()).forgetUnrestoredIdentity() + verify(pubkyRepo, never()).deleteProfile(any()) + verify(pubkyRepo, never()).prepareProfileDeletion(any()) assertFalse(sut.uiState.value.showDeleteDialog) result.complete(Result.failure(TestAppError("Offline"))) @@ -181,107 +274,6 @@ class EditProfileViewModelTest : BaseUnitTest() { assertEquals("https://updated.example.com", sut.uiState.value.links.first().url) } - @Test - fun `failed private cleanup stops deletion and preserves pending state`() = test { - val sut = createSut() - advanceUntilIdle() - whenever(privatePaykitRepo.removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true))) - .thenReturn(Result.failure(TestAppError("Withdrawal pending"))) - whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) - - sut.effects.test { - sut.deleteProfile() - advanceUntilIdle() - expectNoEvents() - } - - assertTrue(sut.uiState.value.showDeleteFailureDialog) - assertFalse(sut.uiState.value.isDeleting) - verify(pubkyRepo, never()).deleteProfile() - verify(privatePaykitRepo, never()).closeAndClear() - verify(privatePaykitRepo).endProfileDeletion() - } - - @Test - fun `failed local finalization does not report deletion success`() = test { - val sut = createSut() - advanceUntilIdle() - whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) - whenever( - privatePaykitRepo.closeAndClear() - ).thenReturn(Result.failure(TestAppError("Local storage unavailable"))) - - sut.effects.test { - sut.deleteProfile() - advanceUntilIdle() - expectNoEvents() - } - - assertFalse(sut.uiState.value.showDeleteFailureDialog) - assertFalse(sut.uiState.value.isDeleting) - verify(pubkyRepo).deleteProfile() - verify(privatePaykitRepo).closeAndClear() - verify(privatePaykitRepo).endProfileDeletion() - } - - @Test - fun `deleteProfile should emit success when repository delete succeeds`() = test { - whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) - - val sut = createSut() - advanceUntilIdle() - - sut.effects.test { - sut.deleteProfile() - advanceUntilIdle() - - assertEquals(EditProfileEffect.DeleteSuccess, awaitItem()) - } - assertFalse(sut.uiState.value.showDeleteFailureDialog) - inOrder(privatePaykitRepo, pubkyRepo).apply { - verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) - verify(pubkyRepo).deleteProfile() - verify(privatePaykitRepo).closeAndClear() - } - } - - @Test - fun `profile created in Bitkit keeps delete copy`() = test { - whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) - val sut = createSut() - advanceUntilIdle() - - assertEquals(ProfileRemoval.DELETE, sut.uiState.value.removal) - - sut.deleteProfile() - advanceUntilIdle() - verify(context).getString(R.string.profile__delete_success) - verify(context, never()).getString(R.string.profile__unlink_success) - } - - @Test - fun `ring identity is unlinked with the same cleanup`() = test { - whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) - val sut = createSut(isRingIdentity = true) - advanceUntilIdle() - - assertEquals(ProfileRemoval.UNLINK, sut.uiState.value.removal) - - sut.effects.test { - sut.deleteProfile() - advanceUntilIdle() - - assertEquals(EditProfileEffect.DeleteSuccess, awaitItem()) - } - verify(context).getString(R.string.profile__unlink_success) - verify(context, never()).getString(R.string.profile__delete_success) - inOrder(privatePaykitRepo, pubkyRepo).apply { - verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) - verify(pubkyRepo).deleteProfile() - verify(privatePaykitRepo).closeAndClear() - } - } - @Test fun `ring identity keeps loading until unlink copy is resolved`() = test { val ringCheck = CompletableDeferred() @@ -298,114 +290,83 @@ class EditProfileViewModelTest : BaseUnitTest() { } @Test - fun `retryDeleteProfile should emit success when repository delete succeeds`() = test { - whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) - + fun `dismissed failure flow cannot reopen after a delayed review`() = test { val sut = createSut() + whenever(pubkyRepo.deleteProfile(fixture.deletion)).thenReturn(Result.failure(TestAppError("lost response"))) advanceUntilIdle() - - sut.effects.test { - sut.retryDeleteProfile() - advanceUntilIdle() - - assertEquals(EditProfileEffect.DeleteSuccess, awaitItem()) - } - assertFalse(sut.uiState.value.showDeleteFailureDialog) - inOrder(privatePaykitRepo, pubkyRepo).apply { - verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) - verify(pubkyRepo).deleteProfile() - verify(privatePaykitRepo).closeAndClear() - } - } - - @Test - fun `deleteProfile should show retry dialog when delete still fails`() = test { - whenever(pubkyRepo.deleteProfile()).thenReturn( - Result.failure(TestAppError("expired session")), - ) - - val sut = createSut() + sut.showDeleteConfirmation() advanceUntilIdle() - sut.deleteProfile() advanceUntilIdle() - - assertTrue(sut.uiState.value.showDeleteFailureDialog) - assertFalse(sut.uiState.value.isDeleting) - verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) - verify(privatePaykitRepo, never()).closeAndClear() - } - - @Test - fun `disconnectProfile should emit disconnect success`() = test { - whenever(pubkyRepo.deleteProfile()).thenReturn( - Result.failure(TestAppError("expired session")), - ) - whenever(pubkyRepo.signOut()).thenReturn(Result.success(Unit)) - - val sut = createSut() + val snapshot = CompletableDeferred>() + whenever(pubkyRepo.prepareProfileDeletion(fixture.original)).doSuspendableAnswer { snapshot.await() } + sut.retryDeleteProfile() advanceUntilIdle() - sut.deleteProfile() + sut.dismissDeleteFailureDialog() + snapshot.complete(Result.success(fixture.deletion)) advanceUntilIdle() - clearInvocations(privatePaykitRepo) - - sut.effects.test { - sut.disconnectProfile() - advanceUntilIdle() - - assertEquals(EditProfileEffect.DisconnectSuccess, awaitItem()) - } + assertFalse(sut.uiState.value.showDeleteDialog) assertFalse(sut.uiState.value.showDeleteFailureDialog) - inOrder(privatePaykitRepo, pubkyRepo).apply { - verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any()) - verify(pubkyRepo).signOut() - verify(privatePaykitRepo).closeAndClear() - } + verify(pubkyRepo, times(1)).deleteProfile(fixture.deletion) } @Test - fun `disconnectProfile stops when private cleanup fails`() = test { + fun `early local-only failure offers disconnect without remote review`() = test { val sut = createSut() - whenever { privatePaykitRepo.removePublishedEndpointsForCleanup(any()) } - .thenReturn(Result.failure(TestAppError("cleanup failed"))) - whenever(pubkyRepo.signOut()).thenReturn(Result.success(Unit)) + whenever(pubkyRepo.deleteProfile(fixture.deletion)) + .thenReturn(Result.failure(TestAppError("Unknown response"))) advanceUntilIdle() - - sut.disconnectProfile() + sut.showDeleteConfirmation() advanceUntilIdle() - - assertFalse(sut.uiState.value.isDeleting) - verify(pubkyRepo, never()).signOut() - verify(privatePaykitRepo, never()).closeAndClear() - } - - @Test - fun `disconnectProfile preserves local Paykit state when Pubky sign out fails`() = test { - val sut = createSut() - whenever(pubkyRepo.signOut()).thenReturn(Result.failure(TestAppError("sign out failed"))) + sut.deleteProfile() advanceUntilIdle() - sut.disconnectProfile() advanceUntilIdle() - - assertFalse(sut.uiState.value.isDeleting) - verify(privatePaykitRepo, never()).closeAndClear() + whenever { fixture.privateRepo.withProfileDeletionPaused(any()) }.thenAnswer { + throw IllegalStateException("Pause unavailable") + } + sut.deleteProfile() + advanceUntilIdle() + assertTrue(sut.uiState.value.showDeleteFailureDialog) + assertFalse(sut.uiState.value.canReviewRemoval) + verify(pubkyRepo, times(1)).deleteProfile(fixture.deletion) } @Test - fun `dismissDeleteFailureDialog should hide retry dialog`() = test { - whenever(pubkyRepo.deleteProfile()).thenReturn( - Result.failure(TestAppError("expired session")), - ) - + fun `cancelled local completion retains its owner through a later admission failure`() = test { val sut = createSut() + org.mockito.kotlin.doAnswer { + fixture.current = fixture.ended + throw CancellationException("Cancelled after acknowledged credential removal") + }.whenever(pubkyRepo).finishProfileRemovalLocally() advanceUntilIdle() - sut.deleteProfile() + sut.showDeleteConfirmation() advanceUntilIdle() - - sut.dismissDeleteFailureDialog() - - assertFalse(sut.uiState.value.showDeleteFailureDialog) + sut.effects.test { + sut.deleteProfile() + advanceUntilIdle() + expectNoEvents() + assertNotNull(fixture.store.pendingAttempt()) + verify(fixture.privateRepo, never()).finishProfileRemoval(any()) + sut.disconnectProfile() + advanceUntilIdle() + fixture.admissionFailure = IllegalStateException("Temporarily busy") + sut.deleteProfile() + advanceUntilIdle() + expectNoEvents() + assertNotNull(fixture.store.pendingAttempt()) + fixture.admissionFailure = null + org.mockito.kotlin.doAnswer { fixture.current = fixture.ended }.whenever( + pubkyRepo + ).finishProfileRemovalLocally() + sut.disconnectProfile() + advanceUntilIdle() + sut.deleteProfile() + advanceUntilIdle() + assertIs(awaitItem()) + assertNull(fixture.store.pendingAttempt()) + } + verify(pubkyRepo, times(1)).signOutForProfileRemoval() } private fun createSut( @@ -418,19 +379,14 @@ class EditProfileViewModelTest : BaseUnitTest() { } else { whenever { pubkyRepo.isRingAdoptedIdentity() }.thenReturn(isRingIdentity) } - whenever { pubkyRepo.forgetUnrestoredIdentity() }.thenReturn(Result.success(false)) + fixture.setup() whenever(pubkyRepo.profile).thenReturn(MutableStateFlow(createProfile())) whenever(pubkyRepo.publicKey).thenReturn(MutableStateFlow(TEST_PUBLIC_KEY)) - whenever { privatePaykitRepo.removePublishedEndpointsForCleanup(any()) } - .thenReturn(Result.success(Unit)) - whenever { privatePaykitRepo.removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) } - .thenReturn(Result.success(Unit)) - whenever { privatePaykitRepo.closeAndClear() }.thenReturn(Result.success(Unit)) return EditProfileViewModel( context = context, pubkyRepo = pubkyRepo, - privatePaykitRepo = privatePaykitRepo, + removalCoordinator = fixture.coordinator, ) } diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/ProfileRemovalUiFixture.kt b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileRemovalUiFixture.kt new file mode 100644 index 0000000000..7989b7d3f3 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileRemovalUiFixture.kt @@ -0,0 +1,60 @@ +package to.bitkit.ui.screens.profile + +import org.mockito.kotlin.any +import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import to.bitkit.data.ProfileRemovalStore +import to.bitkit.ext.runSuspendCatching +import to.bitkit.repositories.ContactPaymentSettingsRepo +import to.bitkit.repositories.PrivatePaykitRepo +import to.bitkit.repositories.PubkyProfileDeletion +import to.bitkit.repositories.PubkyProfileOwner +import to.bitkit.repositories.PubkyRepo +import to.bitkit.repositories.PubkySignIn +import to.bitkit.services.PaykitProfileDeletionSnapshot +import to.bitkit.usecases.ProfileRemovalCoordinator + +/** Real orchestration and durable marker, with controllable local/native repository boundaries. */ +internal class ProfileRemovalUiFixture(val pubky: PubkyRepo) { + val privateRepo = mock() + private val sharing = mock() + val store = ProfileRemovalStore.inMemoryForTesting() + val original = PubkyProfileOwner(PubkySignIn("pubkyalice", 1), 1) + val ended = PubkyProfileOwner(null, 2) + var current = original + var admissionFailure: Throwable? = null + val pause = PrivatePaykitRepo.ProfileDeletionPause() + val deletion = + PubkyProfileDeletion(original, 1, PaykitProfileDeletionSnapshot("pubkyalice", "revision", emptyList())) + val coordinator = ProfileRemovalCoordinator(pubky, privateRepo, sharing, store) + + fun setup() { + whenever(pubky.profileOwner()).thenAnswer { current } + whenever(pubky.isProfileOwnerCurrent(any())).thenAnswer { it.getArgument(0) == current } + whenever { pubky.prepareProfileDeletion(original) }.thenReturn(Result.success(deletion)) + whenever { sharing.withProfileRemoval(any()) }.doSuspendableAnswer { + it.getArgument PubkyProfileOwner>(0).invoke() + } + whenever { pubky.performProfileRemoval(any(), any(), any()) }.doSuspendableAnswer { + val owner = it.getArgument(0) + val id = it.getArgument(1) + val operation = it.getArgument Unit>(2) + runSuspendCatching { + admissionFailure?.let { error -> throw error } + check(owner == current) + store.withAccess(id) { operation() } + current + } + } + whenever { privateRepo.withProfileDeletionPaused(any()) }.doSuspendableAnswer { + it.getArgument Unit>(0).invoke(pause) + } + whenever { privateRepo.removePublishedEndpointsForCleanup(any(), eq(true)) }.thenReturn(Result.success(Unit)) + whenever { pubky.removeBitkitPaymentEndpoints() }.thenReturn(Result.success(Unit)) + whenever { pubky.deleteProfile(deletion) }.thenReturn(Result.success(Unit)) + whenever { pubky.finishProfileRemovalLocally() }.thenAnswer { current = ended } + whenever { privateRepo.finishProfileRemoval(pause) }.thenReturn(Result.success(Unit)) + } +} diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt index 2a45e49029..70211e7042 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt @@ -1,11 +1,10 @@ package to.bitkit.ui.screens.profile import android.content.Context -import androidx.lifecycle.viewModelScope import app.cash.turbine.test +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.test.advanceUntilIdle import org.junit.Test @@ -22,13 +21,16 @@ import org.mockito.kotlin.whenever import to.bitkit.data.PubkyCachedProfile import to.bitkit.models.PubkyProfile import to.bitkit.models.PubkyProfileLink -import to.bitkit.repositories.PrivatePaykitRepo +import to.bitkit.repositories.PubkyProfileOwner import to.bitkit.repositories.PubkyRepo +import to.bitkit.repositories.PubkySignIn import to.bitkit.test.BaseUnitTest import to.bitkit.test.forEachCase import to.bitkit.utils.AppError +import java.util.UUID import kotlin.test.assertEquals import kotlin.test.assertFalse +import kotlin.test.assertIs import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue @@ -37,7 +39,7 @@ import kotlin.test.assertTrue class ProfileViewModelTest : BaseUnitTest() { private val context: Context = mock() private val pubkyRepo: PubkyRepo = mock() - private val privatePaykitRepo: PrivatePaykitRepo = mock() + private val fixture = ProfileRemovalUiFixture(pubkyRepo) @Test fun `saved public profile is shown without enabling edits while restoration waits`() = test { @@ -232,57 +234,6 @@ class ProfileViewModelTest : BaseUnitTest() { } } - @Test - fun `disconnect finishes private cleanup after the screen is closed`() = test { - val sut = createSut() - val forget = CompletableDeferred>() - whenever(pubkyRepo.forgetUnrestoredIdentity()).doSuspendableAnswer { forget.await() } - advanceUntilIdle() - - sut.signOut() - advanceUntilIdle() - sut.viewModelScope.cancel() - forget.complete(Result.success(true)) - advanceUntilIdle() - - verify(privatePaykitRepo).closeAndClear() - verify(pubkyRepo, never()).signOut() - } - - @Test - fun `disconnect forgets unrestored identity without remote cleanup`() = test { - val sut = createSut() - whenever(pubkyRepo.forgetUnrestoredIdentity()).thenReturn(Result.success(true)) - whenever(privatePaykitRepo.removePublishedEndpointsForCleanup(any())) - .thenReturn(Result.failure(AppError("No session"))) - advanceUntilIdle() - - sut.effects.test { - sut.signOut() - advanceUntilIdle() - assertEquals(ProfileEffect.SignedOut, awaitItem()) - } - - assertFalse(sut.uiState.value.isSigningOut) - verify(privatePaykitRepo, never()).removePublishedEndpointsForCleanup(any()) - verify(pubkyRepo, never()).signOut() - verify(privatePaykitRepo).closeAndClear() - } - - @Test - fun `failed local disconnect preserves private state`() = test { - val sut = createSut() - whenever(pubkyRepo.forgetUnrestoredIdentity()).thenReturn(Result.failure(AppError("Storage failed"))) - advanceUntilIdle() - - sut.signOut() - advanceUntilIdle() - - assertFalse(sut.uiState.value.isSigningOut) - verify(privatePaykitRepo, never()).closeAndClear() - verify(pubkyRepo, never()).signOut() - } - @Test fun `profile retry stays loading until session and profile are available`() = test { val sut = createSut() @@ -334,52 +285,6 @@ class ProfileViewModelTest : BaseUnitTest() { verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any()) } - @Test - fun `signOut marks profile recovery before signing out`() = test { - whenever(pubkyRepo.signOut()).thenReturn(Result.success(Unit)) - val sut = createSut() - advanceUntilIdle() - - sut.effects.test { - sut.signOut() - advanceUntilIdle() - - assertEquals(ProfileEffect.SignedOut, awaitItem()) - } - inOrder(privatePaykitRepo, pubkyRepo).apply { - verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any()) - verify(pubkyRepo).signOut() - verify(privatePaykitRepo).closeAndClear() - } - } - - @Test - fun `signOut stops when private cleanup fails`() = test { - val sut = createSut() - whenever { privatePaykitRepo.removePublishedEndpointsForCleanup(any()) } - .thenReturn(Result.failure(ProfileTestAppError("cleanup failed"))) - advanceUntilIdle() - - sut.signOut() - advanceUntilIdle() - - assertFalse(sut.uiState.value.isSigningOut) - verify(pubkyRepo, never()).signOut() - verify(privatePaykitRepo, never()).closeAndClear() - } - - @Test - fun `signOut preserves local Paykit state when Pubky sign out fails`() = test { - val sut = createSut() - whenever(pubkyRepo.signOut()).thenReturn(Result.failure(ProfileTestAppError("sign out failed"))) - advanceUntilIdle() - - sut.signOut() - advanceUntilIdle() - - verify(privatePaykitRepo, never()).closeAndClear() - } - @Test fun `addTag saves the updated profile and closes the sheet`() = test { val sut = createSut(createProfile()) @@ -503,8 +408,198 @@ class ProfileViewModelTest : BaseUnitTest() { } } + @Test + fun `pending restart without credentials shows local recovery without authentication`() = test { + val pending = MutableStateFlow(null) + fixture.current = PubkyProfileOwner(null, 4) + val sut = createSut(publicKey = null, recoveryPending = pending) + val id = UUID.randomUUID().toString() + fixture.store.withAccess(id) { fixture.store.begin(id) } + advanceUntilIdle() + verify(pubkyRepo, never()).restoreSessionIfNeeded() + verify(pubkyRepo, never()).loadProfile() + sut.uiState.test { + awaitItem() + pending.value = true + advanceUntilIdle() + assertTrue(sut.uiState.value.recoveryPending) + assertFalse(sut.uiState.value.isLoading) + assertFalse(sut.uiState.value.canEdit) + sut.showSignOutConfirmation() + advanceUntilIdle() + assertTrue(sut.uiState.value.localDisconnect) + assertTrue(sut.uiState.value.showSignOutDialog) + sut.effects.test { + sut.signOut() + advanceUntilIdle() + assertIs(awaitItem()) + } + cancelAndIgnoreRemainingEvents() + } + verify(pubkyRepo, never()).signOutForProfileRemoval() + verify(fixture.privateRepo, never()).removePublishedEndpointsForCleanup(any(), eq(true)) + assertNull(fixture.store.pendingAttempt()) + } + + @Test + fun `sign out waits for confirmation and delayed effect is bound to ended owner`() = test { + val sut = createSut(createProfile()) + advanceUntilIdle() + sut.signOut() + advanceUntilIdle() + verify(pubkyRepo, never()).signOutForProfileRemoval() + sut.showSignOutConfirmation() + advanceUntilIdle() + sut.effects.test { + sut.signOut() + sut.signOut() + advanceUntilIdle() + val effect = assertIs(awaitItem()) + assertTrue(sut.isRemovalCurrent(effect)) + fixture.current = PubkyProfileOwner(PubkySignIn("replacement", 3), 3) + assertFalse(sut.isRemovalCurrent(effect)) + expectNoEvents() + } + verify(pubkyRepo, times(1)).signOutForProfileRemoval() + } + + @Test + fun `uncertain sign out offers local confirmation without replaying revocation`() = test { + val sut = createSut(createProfile()) + whenever(pubkyRepo.signOutForProfileRemoval()).thenAnswer { throw ProfileTestAppError("lost response") } + advanceUntilIdle() + sut.showSignOutConfirmation() + advanceUntilIdle() + sut.effects.test { + sut.signOut() + advanceUntilIdle() + expectNoEvents() + } + assertNotNull(fixture.store.pendingAttempt()) + sut.showSignOutConfirmation() + advanceUntilIdle() + sut.effects.test { + sut.signOut() + advanceUntilIdle() + assertIs(awaitItem()) + } + verify(pubkyRepo, times(1)).signOutForProfileRemoval() + verify(fixture.privateRepo, times(1)).removePublishedEndpointsForCleanup(any(), eq(true)) + } + + @Test + fun `private completion failure is consumed and never reports signed out`() = test { + val sut = createSut(createProfile()) + whenever(fixture.privateRepo.finishProfileRemoval(fixture.pause)) + .thenReturn(Result.failure(ProfileTestAppError("storage unavailable"))) + advanceUntilIdle() + sut.showSignOutConfirmation() + advanceUntilIdle() + sut.effects.test { + sut.signOut() + advanceUntilIdle() + expectNoEvents() + } + assertNotNull(fixture.store.pendingAttempt()) + } + + @Test + fun `confirmation cannot sign out a replacement of the same identity`() = test { + val sut = createSut(createProfile()) + advanceUntilIdle() + sut.showSignOutConfirmation() + advanceUntilIdle() + fixture.current = PubkyProfileOwner(PubkySignIn("pubkyalice", 3), 3) + sut.signOut() + advanceUntilIdle() + verify(pubkyRepo, never()).signOutForProfileRemoval() + verify(fixture.privateRepo, never()).finishProfileRemoval(any()) + } + + @Test + fun `unrelated control emission never recaptures a replacement owner`() = test { + val sut = createSut(createProfile()) + advanceUntilIdle() + sut.uiState.test { + awaitItem() + fixture.current = PubkyProfileOwner(PubkySignIn("pubkyalice", 3), 3) + sut.showAddTagSheet() + advanceUntilIdle() + assertEquals(fixture.original, sut.uiState.value.owner) + sut.showSignOutConfirmation() + advanceUntilIdle() + assertFalse(sut.uiState.value.showSignOutDialog) + sut.signOut() + verify(pubkyRepo, never()).signOutForProfileRemoval() + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `initial restoration binds once and later same-key sessions cannot replace its owner`() = test { + fixture.current = PubkyProfileOwner(null, fixture.original.storedRevision) + val profileFlow = MutableStateFlow(null) + val sut = createSut(profileFlow = profileFlow, publicKey = null) + advanceUntilIdle() + sut.uiState.test { + awaitItem() + fixture.current = fixture.original + profileFlow.value = createProfile() + advanceUntilIdle() + assertEquals(fixture.original, sut.uiState.value.owner) + fixture.current = PubkyProfileOwner(PubkySignIn("pubkyalice", 3), 3) + sut.showAddTagSheet() + advanceUntilIdle() + assertEquals(fixture.original, sut.uiState.value.owner) + sut.showSignOutConfirmation() + advanceUntilIdle() + assertFalse(sut.uiState.value.showSignOutDialog) + sut.signOut() + verify(pubkyRepo, never()).signOutForProfileRemoval() + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `cancelled local completion retains its owner through a later admission failure`() = test { + val sut = createSut(createProfile()) + org.mockito.kotlin.doAnswer { + fixture.current = fixture.ended + throw CancellationException("Cancelled after acknowledged credential removal") + }.whenever(pubkyRepo).finishProfileRemovalLocally() + advanceUntilIdle() + sut.showSignOutConfirmation() + advanceUntilIdle() + sut.effects.test { + sut.signOut() + advanceUntilIdle() + expectNoEvents() + assertNotNull(fixture.store.pendingAttempt()) + verify(fixture.privateRepo, never()).finishProfileRemoval(any()) + sut.showSignOutConfirmation() + advanceUntilIdle() + fixture.admissionFailure = IllegalStateException("Temporarily busy") + sut.signOut() + advanceUntilIdle() + expectNoEvents() + assertNotNull(fixture.store.pendingAttempt()) + fixture.admissionFailure = null + org.mockito.kotlin.doAnswer { fixture.current = fixture.ended }.whenever( + pubkyRepo + ).finishProfileRemovalLocally() + sut.showSignOutConfirmation() + advanceUntilIdle() + sut.signOut() + advanceUntilIdle() + assertIs(awaitItem()) + assertNull(fixture.store.pendingAttempt()) + } + verify(pubkyRepo, times(1)).signOutForProfileRemoval() + } + private fun createSut( profile: PubkyProfile? = null, + recoveryPending: MutableStateFlow = MutableStateFlow(false), profileFlow: MutableStateFlow = MutableStateFlow(profile), readOnlyProfileFlow: MutableStateFlow = MutableStateFlow(null), publicKey: String? = "pubkyalice", @@ -517,7 +612,8 @@ class ProfileViewModelTest : BaseUnitTest() { onRestore: suspend () -> Boolean = { false }, ): ProfileViewModel { whenever(context.getString(any())).thenReturn("") - whenever { pubkyRepo.forgetUnrestoredIdentity() }.thenReturn(Result.success(false)) + fixture.setup() + whenever(pubkyRepo.profileRecoveryPending).thenReturn(recoveryPending) whenever(pubkyRepo.profile).thenReturn(profileFlow) whenever(pubkyRepo.readOnlyProfile).thenReturn(readOnlyProfileFlow) whenever(pubkyRepo.publicKey).thenReturn(publicKeyFlow) @@ -526,16 +622,12 @@ class ProfileViewModelTest : BaseUnitTest() { whenever(pubkyRepo.cachedProfile).thenReturn(MutableStateFlow(cachedProfile)) whenever { pubkyRepo.restoreSessionIfNeeded() }.doSuspendableAnswer { onRestore() } whenever { pubkyRepo.loadProfile() }.thenAnswer { onLoadProfile() } - whenever { pubkyRepo.signOut() }.thenReturn(Result.success(Unit)) whenever { pubkyRepo.saveProfile(any(), any(), any(), any(), any()) }.thenReturn(Result.success(Unit)) - whenever { privatePaykitRepo.removePublishedEndpointsForCleanup(any()) } - .thenReturn(Result.success(Unit)) - whenever { privatePaykitRepo.closeAndClear() }.thenReturn(Result.success(Unit)) return ProfileViewModel( context = context, pubkyRepo = pubkyRepo, - privatePaykitRepo = privatePaykitRepo, + removalCoordinator = fixture.coordinator, ) } diff --git a/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt b/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt new file mode 100644 index 0000000000..a573bb22f7 --- /dev/null +++ b/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt @@ -0,0 +1,416 @@ +package to.bitkit.usecases + +import androidx.datastore.core.DataStore +import com.synonym.paykit.ContactRecord +import com.synonym.paykit.PublicationStatus +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.MutableStateFlow +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import to.bitkit.data.ProfileRemovalState +import to.bitkit.data.ProfileRemovalStore +import to.bitkit.ext.runSuspendCatching +import to.bitkit.repositories.ContactPaymentSettingsRepo +import to.bitkit.repositories.PrivatePaykitRepo +import to.bitkit.repositories.PubkyProfileDeletion +import to.bitkit.repositories.PubkyProfileOwner +import to.bitkit.repositories.PubkyRepo +import to.bitkit.repositories.PubkySignIn +import to.bitkit.services.PaykitProfileDeletionSnapshot +import to.bitkit.test.BaseUnitTest +import java.util.UUID +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +class ProfileRemovalCoordinatorTest : BaseUnitTest() { + private val pubky = mock() + private val privateRepo = mock() + private val sharing = mock() + private var store = ProfileRemovalStore.inMemoryForTesting() + private val original = PubkyProfileOwner(PubkySignIn("identity", 1), 1) + private val ended = PubkyProfileOwner(null, 2) + private var current = original + private var rejectAdmission = false + private val pause = PrivatePaykitRepo.ProfileDeletionPause() + private val events = mutableListOf() + private val deletion = + PubkyProfileDeletion(original, 1, PaykitProfileDeletionSnapshot("identity", "revision", emptyList())) + private val sut get() = ProfileRemovalCoordinator(pubky, privateRepo, sharing, store) + + @Before + fun setup() = test { + whenever(pubky.profileOwner()).thenAnswer { current } + whenever(pubky.isProfileOwnerCurrent(any())).thenAnswer { it.getArgument(0) === current } + whenever(pubky.prepareProfileDeletion(original)).thenReturn(Result.success(deletion)) + whenever { sharing.withProfileRemoval(any()) }.doSuspendableAnswer { + it.getArgument PubkyProfileOwner>(0).invoke() + } + whenever { pubky.performProfileRemoval(any(), any(), any()) }.doSuspendableAnswer { + val owner = it.getArgument(0) + val id = it.getArgument(1) + val operation = it.getArgument Unit>(2) + runSuspendCatching { + check(!rejectAdmission) { "busy before operation admission" } + check(owner === current) + store.withAccess(id) { operation() } + current + } + } + whenever { privateRepo.withProfileDeletionPaused(any()) }.doSuspendableAnswer { + it.getArgument Unit>(0).invoke(pause) + } + whenever { pubky.validateProfileDeletion(deletion) }.doSuspendableAnswer { + events += "validate" + Unit + } + whenever { privateRepo.removePublishedEndpointsForCleanup(any(), eq(true)) }.doSuspendableAnswer { + assertNotNull(store.pendingAttempt()) + events += "private endpoints" + Result.success(Unit) + } + whenever { pubky.removeBitkitPaymentEndpoints() }.thenAnswer { + events += "public endpoints" + Result.success(Unit) + } + whenever { pubky.deleteProfile(deletion) }.thenAnswer { + events += "profile" + Result.success(Unit) + } + whenever { pubky.signOutForProfileRemoval() }.thenAnswer { + events += "revoke" + Unit + } + whenever { pubky.finishProfileRemovalLocally() }.doSuspendableAnswer { + assertNotNull(store.pendingAttempt()) + events += "local credentials and metadata" + current = ended + } + whenever { privateRepo.finishProfileRemoval(pause) }.doSuspendableAnswer { + assertNotNull(store.pendingAttempt()) + events += "private local" + Result.success(Unit) + } + } + + @Test + fun `confirmed removal acknowledges credentials before clearing private state and clears marker last`() = test { + val confirmation = sut.prepareDeletion(original).getOrThrow() + assertNull(store.pendingAttempt()) + assertSame(ended, sut.remove(confirmation).getOrThrow()) + assertEquals( + listOf( + "validate", + "private endpoints", + "public endpoints", + "profile", + "revoke", + "local credentials and metadata", + "private local" + ), + events + ) + assertNull(store.pendingAttempt()) + assertFalse(sut.isCurrent(original)) + assertTrue(sut.isCurrent(ended)) + } + + @Test + fun `one confirmation cannot repeat an uncertain profile mutation`() = test { + whenever(pubky.deleteProfile(deletion)).thenReturn(Result.failure(IllegalStateException("lost response"))) + val confirmation = sut.prepareDeletion(original).getOrThrow() + assertIs(sut.remove(confirmation).exceptionOrNull()) + assertTrue(sut.remove(confirmation).isFailure) + verify(pubky, times(1)).deleteProfile(deletion) + verify(pubky, never()).signOutForProfileRemoval() + verify(privateRepo, never()).finishProfileRemoval(any()) + assertEquals(confirmation.attemptId, store.pendingAttempt()) + } + + @Test + fun `review after uncertain deletion reads original owner and requires another confirmation`() = test { + whenever(pubky.deleteProfile(deletion)).thenReturn(Result.failure(IllegalStateException("lost response"))) + val first = sut.prepareDeletion(original).getOrThrow() + val failure = assertIs(sut.remove(first).exceptionOrNull()) + val second = sut.reviewAgain(failure).getOrThrow() + assertEquals(first.attemptId, second.attemptId) + assertFalse(second.used.get()) + verify(pubky, times(2)).prepareProfileDeletion(original) + verify(pubky, times(1)).deleteProfile(deletion) + current = PubkyProfileOwner(PubkySignIn("replacement", 3), 3) + assertTrue(sut.reviewAgain(failure).isFailure) + assertTrue(sut.prepareLocalDisconnect(failure).isFailure) + } + + @Test + fun `review rejects a later profile revision instead of replacing original intent`() = test { + val failure = failRemoval(deletion) + whenever(pubky.prepareProfileDeletion(original)).thenReturn( + Result.success(deletion.withSnapshot(deletion.snapshot.copy(profileRevision = "later-edit"))) + ) + assertTrue(sut.reviewAgain(failure).isFailure) + verify(pubky, times(1)).deleteProfile(deletion) + } + + @Test + fun `review rejects added or edited contacts before another confirmation`() = test { + val alice = contact("alice") + val first = deletion.withSnapshot(deletion.snapshot.copy(contacts = listOf(alice))) + val failure = failRemoval(first) + for (records in listOf(listOf(alice, contact("bob")), listOf(alice.copy(label = "Later edit")))) { + whenever(pubky.prepareProfileDeletion(original)).thenReturn( + Result.success(first.withSnapshot(first.snapshot.copy(contacts = records))) + ) + assertTrue(sut.reviewAgain(failure).isFailure) + } + verify(pubky, times(1)).deleteProfile(first) + } + + @Test + fun `review accepts only unchanged residuals and cannot restore a removed contact target`() = test { + val alice = contact("alice") + val bob = contact("bob") + val first = deletion.withSnapshot(deletion.snapshot.copy(contacts = listOf(alice, bob))) + val failure = failRemoval(first) + val residual = first.withSnapshot(first.snapshot.copy(profileRevision = null, contacts = listOf(bob))) + whenever(pubky.prepareProfileDeletion(original)).thenReturn(Result.success(residual)) + val second = sut.reviewAgain(failure).getOrThrow() + assertEquals(residual, second.deletion) + assertEquals(failure.confirmation.attemptId, second.attemptId) + verify(pubky, times(1)).deleteProfile(first) + whenever(pubky.deleteProfile(residual)).thenReturn(Result.failure(IllegalStateException("lost response"))) + val secondFailure = assertIs(sut.remove(second).exceptionOrNull()) + whenever(pubky.prepareProfileDeletion(original)).thenReturn( + Result.success(residual.withSnapshot(residual.snapshot.copy(contacts = listOf(alice, bob)))) + ) + assertTrue(sut.reviewAgain(secondFailure).isFailure) + verify(pubky, times(1)).deleteProfile(residual) + } + + @Test + fun `review rejects a profile recreated after an earlier review observed absence`() = test { + val failure = failRemoval(deletion) + val absent = deletion.withSnapshot(deletion.snapshot.copy(profileRevision = null)) + whenever(pubky.prepareProfileDeletion(original)).thenReturn(Result.success(absent)) + val second = sut.reviewAgain(failure).getOrThrow() + whenever(pubky.deleteProfile(absent)).thenReturn(Result.failure(IllegalStateException("unknown"))) + val secondFailure = assertIs(sut.remove(second).exceptionOrNull()) + whenever(pubky.prepareProfileDeletion(original)).thenReturn(Result.success(deletion)) + assertTrue(sut.reviewAgain(secondFailure).isFailure) + } + + @Test + fun `old failure cannot expand residuals after a confirmation admission failure`() = test { + val first = deletion.withSnapshot(deletion.snapshot.copy(contacts = listOf(contact("alice"), contact("bob")))) + val failure = failRemoval(first) + val remaining = first.withSnapshot(first.snapshot.copy(contacts = listOf(contact("bob")))) + whenever(pubky.prepareProfileDeletion(original)).thenReturn(Result.success(remaining)) + val second = sut.reviewAgain(failure).getOrThrow() + rejectAdmission = true + assertTrue(sut.remove(second).isFailure) + assertNull(sut.failureFor(second)) + rejectAdmission = false + whenever(pubky.prepareProfileDeletion(original)).thenReturn(Result.success(first)) + assertTrue(sut.reviewAgain(failure).isFailure) + verify(pubky, times(1)).deleteProfile(first) + verify(pubky, never()).deleteProfile(remaining) + } + + @Test + fun `cancelled residual review cannot reintroduce an absent profile through an older failure`() = test { + val failure = failRemoval(deletion) + val remaining = deletion.withSnapshot(deletion.snapshot.copy(profileRevision = null)) + whenever(pubky.prepareProfileDeletion(original)).thenReturn(Result.success(remaining)) + sut.reviewAgain(failure).getOrThrow() + whenever(pubky.prepareProfileDeletion(original)).thenReturn(Result.success(deletion)) + assertTrue(sut.reviewAgain(failure).isFailure) + verify(pubky, times(1)).deleteProfile(deletion) + } + + @Test + fun `new residual review invalidates an outstanding wider confirmation before cleanup`() = test { + val first = deletion.withSnapshot(deletion.snapshot.copy(contacts = listOf(contact("alice"), contact("bob")))) + val failure = failRemoval(first) + whenever(pubky.prepareProfileDeletion(original)).thenReturn(Result.success(first)) + val wider = sut.reviewAgain(failure).getOrThrow() + val remaining = first.withSnapshot(first.snapshot.copy(contacts = listOf(contact("bob")))) + whenever(pubky.prepareProfileDeletion(original)).thenReturn(Result.success(remaining)) + sut.reviewAgain(failure).getOrThrow() + val eventsBefore = events.toList() + assertTrue(sut.remove(wider).isFailure) + assertEquals(eventsBefore, events) + verify(pubky, times(1)).deleteProfile(first) + } + + @Test + fun `review read failure retains original obligation without a mutation`() = test { + val failure = failRemoval(deletion) + whenever(pubky.prepareProfileDeletion(original)).thenReturn(Result.failure(IllegalStateException("offline"))) + assertTrue(sut.reviewAgain(failure).isFailure) + assertEquals(failure.confirmation.attemptId, store.pendingAttempt()) + verify(pubky, times(1)).deleteProfile(deletion) + } + + private fun PubkyProfileDeletion.withSnapshot(snapshot: PaykitProfileDeletionSnapshot) = + PubkyProfileDeletion(owner, profileWriteRevision, snapshot) + + private suspend fun failRemoval(snapshot: PubkyProfileDeletion): ProfileRemovalFailure { + whenever(pubky.prepareProfileDeletion(original)).thenReturn(Result.success(snapshot)) + whenever(pubky.deleteProfile(snapshot)).thenReturn(Result.failure(IllegalStateException("lost response"))) + return assertIs(sut.remove(sut.prepareDeletion(original).getOrThrow()).exceptionOrNull()) + } + + private fun contact(key: String) = ContactRecord( + publicKey = key, + label = key, + profile = null, + profileFetchedAt = null, + createdAt = "2026-01-01T00:00:00Z", + updatedAt = "2026-01-01T00:00:00Z", + publicContactMarkerStatus = PublicationStatus.NOT_PUBLISHED, + publicContactPublishedAt = null, + publicContactRemovedAt = null, + publicContactLastError = null, + ) + + @Test + fun `later identity invalidates an unused confirmation before cleanup`() = test { + val confirmation = sut.prepareDeletion(original).getOrThrow() + current = ended + assertTrue(sut.remove(confirmation).isFailure) + assertNull(store.pendingAttempt()) + assertTrue(events.isEmpty()) + } + + @Test + fun `changed snapshot fails before durable marker and destructive work`() = test { + whenever { pubky.validateProfileDeletion(deletion) }.thenAnswer { error("profile revision changed") } + val confirmation = sut.prepareDeletion(original).getOrThrow() + assertTrue(sut.remove(confirmation).isFailure) + assertNull(store.pendingAttempt()) + verify(privateRepo, never()).removePublishedEndpointsForCleanup(any(), any()) + } + + @Test + fun `explicit local disconnect remains available after precondition failure without a marker`() = test { + whenever { pubky.validateProfileDeletion(deletion) }.thenAnswer { error("profile changed") } + val failure = assertIs( + sut.remove(sut.prepareDeletion(original).getOrThrow()).exceptionOrNull() + ) + assertNull(store.pendingAttempt()) + assertTrue(sut.remove(sut.prepareLocalDisconnect(failure).getOrThrow()).isSuccess) + assertNull(store.pendingAttempt()) + verify(pubky, never()).deleteProfile(any()) + verify(pubky, never()).signOutForProfileRemoval() + } + + @Test + fun `public cleanup failure retains marker and never revokes or clears private state`() = test { + whenever(pubky.removeBitkitPaymentEndpoints()).thenReturn(Result.failure(IllegalStateException("unknown"))) + val confirmation = sut.prepareDeletion(original).getOrThrow() + assertTrue(sut.remove(confirmation).isFailure) + assertEquals(confirmation.attemptId, store.pendingAttempt()) + verify(pubky, never()).deleteProfile(any()) + verify(pubky, never()).signOutForProfileRemoval() + verify(privateRepo, never()).finishProfileRemoval(any()) + } + + @Test + fun `failed local completion retains ended owner for explicit local disconnect`() = test { + doReturn(Result.failure(IllegalStateException("disk"))).whenever(privateRepo).finishProfileRemoval(pause) + val confirmation = sut.prepareDeletion(original).getOrThrow() + val failure = assertIs(sut.remove(confirmation).exceptionOrNull()) + assertTrue(failure.localCompletionStarted) + assertSame(ended, failure.recoveryOwner) + assertTrue(sut.reviewAgain(failure).isFailure) + val recovery = sut.prepareLocalDisconnect(failure).getOrThrow() + doReturn(Result.success(Unit)).whenever(privateRepo).finishProfileRemoval(pause) + assertTrue(sut.remove(recovery).isSuccess) + assertNull(store.pendingAttempt()) + verify(pubky, times(1)).deleteProfile(deletion) + verify(pubky, times(1)).signOutForProfileRemoval() + } + + @Test + fun `restart pending disconnect is local only and rejects stale UUID confirmation`() = test { + current = PubkyProfileOwner(null, 0) + val id = UUID.randomUUID().toString() + store.withAccess(id) { store.begin(id) } + val confirmation = sut.prepareSignOut(current).getOrThrow() + assertTrue(confirmation.localOnly) + assertTrue(sut.remove(confirmation).isSuccess) + verify(pubky, never()).signOutForProfileRemoval() + verify(pubky, never()).removeBitkitPaymentEndpoints() + verify(privateRepo, never()).removePublishedEndpointsForCleanup(any(), any()) + val unusedOldConfirmation = sut.prepareSignOut(current).getOrThrow() + val newerId = UUID.randomUUID().toString() + store.withAccess(newerId) { store.begin(newerId) } + assertTrue(sut.remove(confirmation).isFailure) + assertFalse(unusedOldConfirmation.used.get()) + assertEquals( + "Another profile removal needs local recovery", + sut.remove(unusedOldConfirmation).exceptionOrNull()?.message, + ) + assertEquals(newerId, store.pendingAttempt()) + } + + @Test + fun `failed final marker persistence retains local recovery without repeating remote work`() = test { + val data = MutableStateFlow(ProfileRemovalState()) + var rejectCompletion = true + store = ProfileRemovalStore(object : DataStore { + override val data = data + override suspend fun updateData( + transform: suspend (ProfileRemovalState) -> ProfileRemovalState + ): ProfileRemovalState { + val next = transform(data.value) + if (rejectCompletion && next.attemptId == null) error("marker write unavailable") + data.value = next + return next + } + }) + val confirmation = sut.prepareDeletion(original).getOrThrow() + val failure = assertIs(sut.remove(confirmation).exceptionOrNull()) + assertSame(ended, failure.recoveryOwner) + assertEquals(confirmation.attemptId, store.pendingAttempt()) + assertTrue(sut.reviewAgain(failure).isFailure) + rejectCompletion = false + assertTrue(sut.remove(sut.prepareLocalDisconnect(failure).getOrThrow()).isSuccess) + assertNull(store.pendingAttempt()) + verify(pubky, times(1)).deleteProfile(deletion) + verify(pubky, times(1)).signOutForProfileRemoval() + } + + @Test + fun `cancellation during destructive work leaves obligation and does not clear watermarks`() = test { + val entered = CompletableDeferred() + val wait = CompletableDeferred() + whenever { pubky.deleteProfile(deletion) }.doSuspendableAnswer { + entered.complete(Unit) + wait.await() + Result.success(Unit) + } + val confirmation = sut.prepareDeletion(original).getOrThrow() + val job = async { sut.remove(confirmation) } + entered.await() + job.cancelAndJoin() + assertTrue(job.isCancelled) + assertEquals(confirmation.attemptId, store.pendingAttempt()) + verify(privateRepo, never()).finishProfileRemoval(any()) + } +} diff --git a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt index 0c14b2144b..5a67ada663 100644 --- a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt @@ -4,10 +4,16 @@ import com.google.firebase.messaging.FirebaseMessaging import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch +import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout import org.junit.Before import org.junit.Test import org.mockito.kotlin.any @@ -19,13 +25,20 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.data.AppDb import to.bitkit.data.CacheStore +import to.bitkit.data.ProfileRemovalStore +import to.bitkit.data.PubkyImageCacheEpoch +import to.bitkit.data.PubkyStore +import to.bitkit.data.PubkyStoreData +import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.data.WidgetsStore import to.bitkit.data.keychain.Keychain +import to.bitkit.data.sharedpubky.SharedPubkyClient import to.bitkit.models.NodeLifecycleState import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.BackupRepo import to.bitkit.repositories.BlocktankRepo +import to.bitkit.repositories.ContactPaymentSettingsRepo import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState @@ -38,14 +51,21 @@ import to.bitkit.repositories.WatchOnlyAccountRepo import to.bitkit.services.CoreService import to.bitkit.services.MigrationService import to.bitkit.services.PaykitSdkService +import to.bitkit.services.PubkyService import to.bitkit.test.BaseUnitTest +import java.util.UUID import javax.inject.Provider +import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.ExperimentalTime -@OptIn(ExperimentalCoroutinesApi::class) +@OptIn(ExperimentalCoroutinesApi::class, ExperimentalTime::class) class WipeWalletUseCaseTest : BaseUnitTest() { private val backupRepo = mock() @@ -63,11 +83,20 @@ class WipeWalletUseCaseTest : BaseUnitTest() { private val hwWalletRepo = mock() private val lightningRepo = mock() private val pubkyRepo = mock() + private val profileRemovalStore = ProfileRemovalStore.inMemoryForTesting() + private val contactPaymentSettingsRepo = mock() + private val profilePause = PrivatePaykitRepo.ProfileDeletionPause() private val privatePaykitRepo = mock() private val privatePaykitAddressReservationRepo = mock() private val firebaseMessaging = mock() private val migrationService = mock() - private val paykitSdkService = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { mock() } + private val paykitSdkService = PaykitSdkService( + mock(), + keychain, + mock(), + settingsStore = mock(), + profileRemovalStore = profileRemovalStore, + ) { mock() } private val privatePaykitRepoProvider = Provider { privatePaykitRepo } private lateinit var sut: WipeWalletUseCase @@ -77,6 +106,17 @@ class WipeWalletUseCaseTest : BaseUnitTest() { @Before fun setUp() { + whenever { contactPaymentSettingsRepo.withWalletWipe(any(), any()) }.doSuspendableAnswer { + val admit = it.getArgument Unit) -> Unit>(0) + admit(it.getArgument(1)) + } + whenever { privatePaykitRepo.withProfileDeletionPaused(any()) }.doSuspendableAnswer { + it.getArgument Unit>(0).invoke(profilePause) + } + whenever { privatePaykitRepo.finishProfileRemoval(any()) }.thenReturn(Result.success(Unit)) + whenever { pubkyRepo.withWalletWipeAdmission(any()) }.doSuspendableAnswer { + it.getArgument Unit>(0).invoke() + } whenever { lightningRepo.stop() }.thenReturn(Result.success(Unit)) whenever { usdtRepo.wipe(any()) }.doSuspendableAnswer { it.getArgument Unit>(0).invoke() @@ -91,28 +131,211 @@ class WipeWalletUseCaseTest : BaseUnitTest() { onWipeCalled = false onSetWalletExistsStateCalled = false - sut = WipeWalletUseCase( - backupRepo = backupRepo, + sut = createSut() + } + + private fun createSut( + pubkyRepo: PubkyRepo = this.pubkyRepo, + sharingRepo: ContactPaymentSettingsRepo = contactPaymentSettingsRepo, + ) = WipeWalletUseCase( + backupRepo = backupRepo, + keychain = keychain, + coreService = coreService, + usdtRepo = usdtRepo, + paykitUsdtPaymentRepo = paykitUsdtPaymentRepo, + db = db, + settingsStore = settingsStore, + cacheStore = cacheStore, + watchOnlyAccountRepo = watchOnlyAccountRepo, + widgetsStore = widgetsStore, + blocktankRepo = blocktankRepo, + activityRepo = activityRepo, + hwWalletRepo = hwWalletRepo, + lightningRepo = lightningRepo, + pubkyRepo = pubkyRepo, + privatePaykitRepo = privatePaykitRepoProvider, + privatePaykitAddressReservationRepo = privatePaykitAddressReservationRepo, + firebaseMessaging = firebaseMessaging, + migrationService = migrationService, + paykitSdkService = paykitSdkService, + profileRemovalStore = profileRemovalStore, + contactPaymentSettingsRepo = Provider { sharingRepo }, + ) + + private fun realPubkyRepo(service: PubkyService, shared: SharedPubkyClient = mock()): PubkyRepo { + whenever { service.requireWalletWipe() }.doSuspendableAnswer { paykitSdkService.requireWalletWipe() } + whenever { service.observedContactRecords(any()) }.doSuspendableAnswer { service.contactRecords() } + val store = mock() + whenever(store.data).thenReturn(MutableStateFlow(PubkyStoreData())) + whenever(settingsStore.data).thenReturn(MutableStateFlow(SettingsData())) + whenever(settingsStore.isPubkyProfileSetupPending).thenReturn(MutableStateFlow(false)) + return PubkyRepo( + ioDispatcher = testDispatcher, + pubkyService = service, keychain = keychain, - coreService = coreService, - usdtRepo = usdtRepo, - paykitUsdtPaymentRepo = paykitUsdtPaymentRepo, - db = db, + sharedPubkyClient = shared, + imageLoader = mock(), + imageCacheEpoch = PubkyImageCacheEpoch(), + pubkyStore = store, settingsStore = settingsStore, - cacheStore = cacheStore, - watchOnlyAccountRepo = watchOnlyAccountRepo, - widgetsStore = widgetsStore, - blocktankRepo = blocktankRepo, - activityRepo = activityRepo, - hwWalletRepo = hwWalletRepo, - lightningRepo = lightningRepo, - pubkyRepo = pubkyRepo, - privatePaykitRepo = privatePaykitRepoProvider, - privatePaykitAddressReservationRepo = privatePaykitAddressReservationRepo, - firebaseMessaging = firebaseMessaging, - migrationService = migrationService, - paykitSdkService = paykitSdkService, + httpClient = mock(), + clock = Clock.System, + profileRemovalStore = profileRemovalStore, + ) + } + + @Test + fun `wipe drains real repository removal and noncancellable local cleanup before SDK reset`() = test { + val service = mock() + whenever { service.withProfileRemoval(any(), any()) }.doSuspendableAnswer { + paykitSdkService.withProfileRemoval(it.getArgument(0), it.getArgument(1)) + } + val repo = realPubkyRepo(service) + val sharing = ContactPaymentSettingsRepo(settingsStore, mock(), privatePaykitRepo, repo, testDispatcher) + advanceUntilIdle() + paykitSdkService.initialize() + val entered = CompletableDeferred() + val cleanupStarted = CompletableDeferred() + val releaseCleanup = CompletableDeferred() + val removed = launch { + sharing.withProfileRemoval { + repo.performProfileRemoval(repo.profileOwner()) { + entered.complete(Unit) + try { + awaitCancellation() + } finally { + withContext(NonCancellable) { + cleanupStarted.complete(Unit) + releaseCleanup.await() + } + } + } + } + } + withTimeout(5_000) { entered.await() } + val wipe = async { + withTimeout(5_000) { createSut(repo, sharing).invoke(resetWalletState = {}, onSuccess = {}) } + } + try { + cleanupStarted.await() + runCurrent() + assertFalse(wipe.isCompleted) + verify(backupRepo, never()).reset() + verify(keychain, never()).wipe() + } finally { + releaseCleanup.complete(Unit) + } + removed.join() + assertTrue(wipe.await().isSuccess) + verify(keychain).wipe() + } + + @Test + fun `wipe drains real Ring adoption local tail before entering SDK wipe barrier`() = test { + val service = mock() + val shared = mock() + val rawKey = "5rsduhcxpw74snwyct86m38c63j3pq8x4ycqikxg64roik8yw5xy" + whenever { shared.ringCredential(rawKey) }.thenReturn(Result.success("ring_secret")) + whenever { service.publicKeyFromSecret("ring_secret") }.thenReturn(rawKey) + val entered = CompletableDeferred() + val releaseContacts = CompletableDeferred() + whenever { service.contactRecords() }.doSuspendableAnswer { + entered.complete(Unit) + releaseContacts.await() + emptyList() + } + val repo = realPubkyRepo(service, shared) + advanceUntilIdle() + paykitSdkService.initialize() + val adoption = async { repo.adoptRingIdentity(rawKey) } + withTimeout(5_000) { entered.await() } + val wipe = async { + withTimeout(5_000) { createSut(repo).invoke(resetWalletState = {}, onSuccess = {}) } + } + try { + runCurrent() + assertFalse(wipe.isCompleted) + verify(backupRepo, never()).reset() + verify(keychain, never()).wipe() + } finally { + releaseContacts.complete(Unit) + } + adoption.await().getOrThrow() + wipe.await().getOrThrow() + verify(keychain).wipe() + } + + @Test + fun `pending restart wipe skips remote cleanup and only clears marker after local acknowledgement`() = test { + val id = UUID.randomUUID().toString() + profileRemovalStore.withAccess(id) { profileRemovalStore.begin(id) } + whenever { privatePaykitRepo.finishProfileRemoval(any()) }.doSuspendableAnswer { + assertEquals(id, profileRemovalStore.pendingAttempt()) + verify(keychain).wipe() + Result.success(Unit) + } + assertTrue(sut.invoke(resetWalletState = {}, onSuccess = {}).isSuccess) + assertNull(profileRemovalStore.pendingAttempt()) + verify(privatePaykitRepo, never()).removePublishedEndpointsForCleanup(any()) + verify(pubkyRepo, never()).removeBitkitPaymentEndpoints() + verify(privatePaykitRepo, never()).closeAndClear() + } + + @Test + fun `private persistence failure retains marker and suppresses completion callbacks`() = test { + whenever { + privatePaykitRepo.finishProfileRemoval( + any() + ) + }.thenReturn(Result.failure(IllegalStateException("disk"))) + assertTrue( + sut.invoke( + resetWalletState = { onWipeCalled = true }, + onSuccess = { onSetWalletExistsStateCalled = true } + ).isFailure ) + verify(keychain).wipe() + assertNotNull(profileRemovalStore.pendingAttempt()) + assertFalse(onWipeCalled) + assertFalse(onSetWalletExistsStateCalled) + } + + @Test + fun `profile metadata failure retains recovery after credentials were wiped`() = test { + val failure = IllegalStateException("profile persistence unavailable") + whenever { pubkyRepo.finishProfileWipeLocally() }.thenThrow(failure) + + val result = sut.invoke( + resetWalletState = { onWipeCalled = true }, + onSuccess = { onSetWalletExistsStateCalled = true }, + ) + + assertEquals(failure.message, result.exceptionOrNull()?.message) + verify(keychain).wipe() + verify(privatePaykitRepo).finishProfileRemoval(profilePause) + verify(privatePaykitAddressReservationRepo, never()).clear() + assertNotNull(profileRemovalStore.pendingAttempt()) + assertFalse(onWipeCalled) + assertFalse(onSetWalletExistsStateCalled) + } + + @Test + fun `settings failure after credential teardown retains recovery without success`() = test { + val failure = IllegalStateException("settings persistence unavailable") + whenever { settingsStore.reset() }.thenThrow(failure) + + val result = sut.invoke( + resetWalletState = { onWipeCalled = true }, + onSuccess = { onSetWalletExistsStateCalled = true }, + ) + + assertEquals(failure.message, result.exceptionOrNull()?.message) + verify(keychain).wipe() + verify(pubkyRepo).finishProfileWipeLocally() + verify(privatePaykitAddressReservationRepo).clear() + assertNotNull(profileRemovalStore.pendingAttempt()) + assertFalse(onWipeCalled) + assertFalse(onSetWalletExistsStateCalled) } @Test @@ -149,15 +372,15 @@ class WipeWalletUseCaseTest : BaseUnitTest() { inOrder.verify(lightningRepo).stop() inOrder.verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any()) inOrder.verify(pubkyRepo).removeBitkitPaymentEndpoints() - inOrder.verify(privatePaykitRepo).closeAndClear() inOrder.verify(lightningRepo).wipeStorage(0) inOrder.verify(migrationService).setNeedsPostMigrationSync(false) inOrder.verify(migrationService).cleanupAfterMigration() - inOrder.verify(privatePaykitAddressReservationRepo).clear() - inOrder.verify(pubkyRepo).wipeLocalState() inOrder.verify(usdtRepo).wipe(any()) inOrder.verify(keychain).wipe() inOrder.verify(paykitUsdtPaymentRepo).resetForWipe() + inOrder.verify(privatePaykitRepo).finishProfileRemoval(profilePause) + inOrder.verify(pubkyRepo).finishProfileWipeLocally() + inOrder.verify(privatePaykitAddressReservationRepo).clear() inOrder.verify(coreService).wipeData() inOrder.verify(db).clearAllTables() inOrder.verify(settingsStore).reset() @@ -217,7 +440,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { } @Test - fun `invoke should continue when address reservation clear fails`() = runTest { + fun `invoke retains pending recovery when address reservation clear fails`() = runTest { whenever { privatePaykitAddressReservationRepo.clear() }.thenThrow(RuntimeException("clear failed")) val result = sut.invoke( @@ -225,25 +448,30 @@ class WipeWalletUseCaseTest : BaseUnitTest() { onSuccess = { onSetWalletExistsStateCalled = true }, ) - assertTrue(result.isSuccess) + assertTrue(result.isFailure) verify(keychain).wipe() - assertTrue(onSetWalletExistsStateCalled) + assertFalse(onSetWalletExistsStateCalled) + assertFalse(onWipeCalled) + assertNotNull(profileRemovalStore.pendingAttempt()) } @Test - fun `invoke should fail after wiping the rest when keychain wipe fails`() = runTest { - whenever(keychain.wipe()).thenThrow(RuntimeException("keystore write failed")) + fun `invoke retains private safety state and recovery when keychain wipe fails`() = runTest { + val error = RuntimeException("keystore write failed") + whenever(keychain.wipe()).thenThrow(error) val result = sut.invoke( resetWalletState = { onWipeCalled = true }, onSuccess = { onSetWalletExistsStateCalled = true }, ) - assertIs(result.exceptionOrNull()) + assertEquals(error, assertIs(result.exceptionOrNull()).cause) verify(lightningRepo).wipeStorage(0) - verify(db).clearAllTables() - verify(settingsStore).reset() - assertTrue(onWipeCalled) + verify(db, never()).clearAllTables() + verify(settingsStore, never()).reset() + assertFalse(onWipeCalled) + verify(privatePaykitRepo, never()).finishProfileRemoval(any()) + assertNotNull(profileRemovalStore.pendingAttempt()) assertFalse(onSetWalletExistsStateCalled) } @@ -303,7 +531,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { ) assertTrue(result.isSuccess) - verify(pubkyRepo).wipeLocalState() + verify(pubkyRepo).finishProfileWipeLocally() verify(keychain).wipe() verify(backupRepo).setWiping(false) } @@ -320,8 +548,8 @@ class WipeWalletUseCaseTest : BaseUnitTest() { ) assertTrue(result.isSuccess) - verify(privatePaykitRepo).closeAndClear() - verify(pubkyRepo).wipeLocalState() + verify(privatePaykitRepo).finishProfileRemoval(profilePause) + verify(pubkyRepo).finishProfileWipeLocally() verify(keychain).wipe() verify(backupRepo).setWiping(false) } @@ -337,7 +565,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { ) assertTrue(result.isFailure) - verify(privatePaykitRepo).closeAndClear() + verify(privatePaykitRepo, never()).finishProfileRemoval(any()) verify(keychain, never()).wipe() verify(db, never()).clearAllTables() assertFalse(onWipeCalled) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index ea979a6e41..265c3ab25a 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -249,7 +249,7 @@ import com.synonym.bitkitcore.Activity as BitkitActivity @OptIn(ExperimentalCoroutinesApi::class, ExperimentalTime::class) @RunWith(RobolectricTestRunner::class) -@Config(sdk = [34]) +@Config(application = android.app.Application::class, sdk = [34]) class AppViewModelSendFlowTest : BaseUnitTest() { private lateinit var sut: AppViewModel @@ -731,6 +731,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever { pubkyRepo.awaitIdentityReady() }.thenAnswer { if (pubkyPublicKey.value != null) PubkyIdentityReadiness.Ready else PubkyIdentityReadiness.Missing } + whenever { pubkyRepo.requiresProfileRecovery() }.thenReturn(false) + whenever(pubkyRepo.profileRecoveryPending).thenReturn(MutableStateFlow(false)) whenever(pubkyRepo.contacts).thenReturn(pubkyContacts) whenever { pubkyRepo.refreshContacts() }.thenReturn(true) whenever { pubkyRepo.importShopContacts() }.thenReturn(Result.success(Unit)) @@ -4957,6 +4959,74 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(Sheet.PubkyAuth(authUrl), sut.currentSheet.value) } + @Test + fun `pending removal blocks scanner and signup authorization before retained key fallback`() = test { + enablePaykitUi() + advanceUntilIdle() + whenever(pubkyRepo.requiresProfileRecovery()).thenReturn(true) + whenever(pubkyRepo.localIdentityPublicKey()).thenReturn(testPublicKey) + whenever(context.getString(R.string.profile__cleanup_pending)).thenReturn("Complete local cleanup") + listOf("pubkyauth://signin_grant", grantSignupAuthUrl, legacyAuthorizedSignupAuthUrl).forEach { authUrl -> + sut.handleDeeplinkIntent(Intent(Intent.ACTION_VIEW, authUrl.toUri())) + advanceUntilIdle() + assertNull(sut.currentSheet.value) + sut.showScannerSheet() + advanceUntilIdle() + sut.onScannerSheetResult(authUrl) + advanceUntilIdle() + assertFalse(sut.currentSheet.value is Sheet.PubkyAuth) + sut.hideSheet() + advanceUntilIdle() + } + verify(pubkyRepo, never()).localIdentityPublicKey() + verify(pubkyRepo, never()).hasSecretKey() + verify(context, atLeastOnce()).getString(R.string.profile__cleanup_pending) + } + + @Test + fun `pending removal ends offline auth waiting and releases the scan queue`() = test { + enablePaykitUi() + advanceUntilIdle() + sut.setIsAuthenticated(true) + val pending = MutableStateFlow(false) + whenever(pubkyRepo.profileRecoveryPending).thenReturn(pending) + whenever(pubkyRepo.requiresProfileRecovery()).thenAnswer { pending.value == true } + whenever(pubkyRepo.hasIdentity()).thenReturn(true) + whenever(pubkyRepo.awaitIdentityReady()).thenAnswer { + if (pending.value == true) PubkyIdentityReadiness.RecoveryRequired else PubkyIdentityReadiness.Unavailable + } + connectivityState.value = ConnectivityState.DISCONNECTED + sut.handleDeeplinkIntent(Intent(Intent.ACTION_VIEW, "pubkyauth://signin_grant".toUri())) + advanceTimeBy(10_000) + runCurrent() + pending.value = true + runCurrent() + assertNull(sut.currentSheet.value) + verify(toastManager).dismiss(check { assertTrue(it.isLoading) }) + verify(pubkyRepo, never()).localIdentityPublicKey() + val bolt11 = "lnbcrt1postpendingcleanupscan" + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + connectivityState.value = ConnectivityState.CONNECTED + sut.onScanResult(bolt11) + advanceUntilIdle() + assertTrue(sut.currentSheet.value is Sheet.Send) + } + + @Test + fun `auth sheet cannot install after pending starts during its transition`() = test { + enablePaykitUi() + advanceUntilIdle() + sut.showScannerSheet() + advanceUntilIdle() + sut.showSheet(Sheet.PubkyAuth("pubkyauth://signin_grant")) + runCurrent() + whenever(pubkyRepo.requiresProfileRecovery()).thenReturn(true) + advanceUntilIdle() + assertNull(sut.currentSheet.value) + verify(context).getString(R.string.profile__cleanup_pending) + } + @Test fun `cold pubky auth deeplink waits for settings identity and wallet unlock`() = test { val initialized = CompletableDeferred() diff --git a/changelog.d/next/1687.fixed.md b/changelog.d/next/1687.fixed.md new file mode 100644 index 0000000000..c0a4d618a7 --- /dev/null +++ b/changelog.d/next/1687.fixed.md @@ -0,0 +1 @@ +Keep interrupted profile removal recoverable and prevent retries or delayed confirmations from changing a replacement identity. diff --git a/journeys/profile/README.md b/journeys/profile/README.md index 3a86acdfe4..244f505f55 100644 --- a/journeys/profile/README.md +++ b/journeys/profile/README.md @@ -4,11 +4,11 @@ `unlink-ring-pubky.xml` verifies that a pubky adopted from Pubky Ring shows "Unlink pubky" instead of "Delete Profile" in Edit Profile, returns to profile onboarding after unlinking, and stays available in Pubky Ring. It needs Pubky Ring (`to.pubky.ring`) on the same emulator or device, signed with the same key as the Bitkit build (`app/debug.keystore` for a dev build), which is not a listed capability. Use a disposable Ring identity; a profile created in Bitkit keeps "Delete Profile", covered by `delete-profile.xml`. -During profile deletion, automatic contact refresh, request intake and endpoint publication must not start new work. Already admitted operations and explicit deletion cleanup still finish. After a failed deletion, normal automatic work must resume for the retained identity. Verifying SDK admission and a controlled cleanup failure requires operation gates beyond the journey runner capabilities; this remains a manual check rather than a timed deletion guarantee. +During profile deletion, automatic contact refresh, request intake and endpoint publication must not start new work. Already admitted operations and explicit deletion cleanup still finish. Once destructive cleanup has begun, its durable pending state keeps authenticated work paused even after a failure or restart. Only an explicit local Disconnect may finish the interrupted local cleanup; it does not claim that the remote profile was deleted. A failure before that durable checkpoint may resume normal work for the unchanged identity. Verifying SDK admission and a controlled cleanup failure requires operation gates beyond the journey runner capabilities; this remains a manual check rather than a timed deletion guarantee. Contact-link retention after deletion is platform-specific. Android cancels a scan awaiting a signed-in contacts refresh when deletion signs out; it does not retry that scan as the iOS retained-link flow does. This change does not alter that cancellation behavior. -If public invoice replacement is deferred during deletion, make deletion fail and the first resumed publication fail transiently. Verify that public publication resumes without waiting for contact refresh to complete, remains pending after the publication error, and is retried by normal foreground maintenance without another foreground event or payment. After sign-out or identity replacement, an older refresh must not publish for the new identity. Controlled payment events and publication failures require gates beyond the journey runner capabilities. +If public invoice replacement is deferred before destructive deletion begins, make preparation fail before the durable cleanup checkpoint and the first resumed publication fail transiently. Verify that public publication resumes without waiting for contact refresh to complete, remains pending after the publication error, and is retried by normal foreground maintenance without another foreground event or payment. After sign-out or identity replacement, an older refresh must not publish for the new identity. Controlled payment events and publication failures require gates beyond the journey runner capabilities. Hold invoice preparation or the final identity lookup before publication, begin deletion, then release it. New public/private endpoint rotation must stay deferred while matching paid-invoice invalidation and receipt attribution still complete. Already-admitted writes may finish, but an older publication must not acknowledge a newer paid-invoice invalidation. These checks require controlled payment events and SDK-admission gates beyond the journey runner capabilities. @@ -18,7 +18,7 @@ Hold initial session restoration with public contact payments enabled, turn cont Hold endpoint preparation before publication admission, or queue a public publication behind SDK work. Begin deletion, complete endpoint removal while session revocation remains held, then release the queued preparation/publication. The removed endpoints must stay absent. Separately, let a publication enter its SDK write before deletion: cleanup must wait for it and remove its endpoints afterward, even if its caller is cancelled. This requires controlled operation gates beyond the journey runner capabilities. -While deletion is held, make a Lightning channel usable or ready, then fail deletion while retaining the same identity. Public and private endpoint preparation must refresh the invoice rather than reuse its old route hints. A skipped or failed publication must retain that refresh for normal maintenance; a new session must not inherit it. Also hold an older public refresh before publication, pay its invoice and publish the replacement, then release the older refresh. The replacement must become pending again and be republished by normal reconciliation. These checks require channel, failure and publication gates beyond the journey runner capabilities. +While preparation is held before the durable cleanup checkpoint, make a Lightning channel usable or ready, then fail preparation while retaining the same identity. Public and private endpoint preparation must refresh the invoice rather than reuse its old route hints. A skipped or failed publication must retain that refresh for normal maintenance; a new session must not inherit it. Also hold an older public refresh before publication, pay its invoice and publish the replacement, then release the older refresh. The replacement must become pending again and be republished by normal reconciliation. These checks require channel, failure and publication gates beyond the journey runner capabilities. Hold initial session restoration before sign-in completes, make a Lightning channel usable or ready, then release restoration while public publication remains blocked. Restore readiness or connectivity without another channel event. Normal public maintenance must retain the forced invoice refresh for the restored identity, including after a deferred or failed restoration and a skipped or failed publication. Work retained for the stored identity or an existing signed-in session must not transfer to a replacement identity or a new session for the same key. These checks require restoration, channel and publication gates beyond the journey runner capabilities. @@ -36,4 +36,32 @@ With an imported grant that cannot be restored and Ring unavailable, Disconnect Profile deletion withdraws private payment lists before removing the profile and performs App Registry reconciliation during final public cleanup. An intermediate registry update is deferred; the existing private cleanup marker stays pending until deletion succeeds or normal cleanup retry completes. Public endpoint removal, capability checks, session revocation and uncertain-write safety waits remain required. -For controlled fault testing, interrupt deletion after private withdrawal but before profile removal, then restart with the same identity. Verify cleanup remains pending, normal retry reconciles the registry, and a failed retry keeps the marker. Also hold a private withdrawal undelivered: it must remain pending, not be acknowledged by the deferred registry step. Check that Disconnect and disabling private sharing still reconcile the registry. These checks require operation gates and network fault injection beyond the journey runner capabilities. +For controlled fault testing, interrupt deletion after private withdrawal but before profile removal, then restart with the same identity. Verify cleanup remains pending and authenticated automatic work does not resume. Review reads the original identity again and requires a new confirmation; Disconnect only completes local cleanup and leaves remote state uncertain. Also hold a private withdrawal undelivered: it must remain pending, not be acknowledged by the deferred registry step. Check that disabling private sharing outside a pending removal still reconciles the registry. Local Disconnect does not make a registry mutation. These checks require operation gates and network fault injection beyond the journey runner capabilities. + +## Interrupted removal and local recovery + +`profile-removal-recovery.xml` specifies the changed failure-dialog and restart routes. The controlled +faults and identity/session interleavings require a disposable authenticated homeserver fixture with +operation gates; these are not supplied by the standard journey runner. Never apply these scenarios +to personal identities or use wallet wipe to prepare the fixture. A pending local obligation is not +proof that remote deletion or revocation succeeded. + +Before confirmation, the app captures the original sign-in, local write generation, native profile +revision and contact set. A confirmation can start once. Review only re-reads the original owner and +opens a new confirmation for unchanged records remaining from the previous confirmation. Added or +changed records stop the retry; records observed absent cannot become targets again in this attempt. +The reduced target set remains in force if the new confirmation is canceled or rejected before +cleanup starts. Absence does not establish which operation removed a record. After local credential +teardown has started, Review is unavailable and +Disconnect completes only local work. A dialog or completion queued for an older identity cannot +operate on, navigate away from or report success for its replacement. Ordinary receive accounting +continues; pending state blocks authenticated setup, automatic publication and complete WALLET +capture rather than substituting stale or empty Paykit data. + +Consumed payment-list versions remain until credential erasure is acknowledged. Failure to remove +credentials, settings, private state, contact attribution or the durable marker cannot report +completion. Pending state survives process restart even when all identity credentials were already +removed; Profile still offers an explicit local Disconnect. Malformed/unavailable marker storage +fails closed. Local success never asserts remote endpoint or profile removal after an uncertain +response. Native key-only contact batches do not establish cross-device edit/re-add/unblock/ABA +protection; that native conditional-mutation work remains separate. diff --git a/journeys/profile/delete-profile-uncertain-response.xml b/journeys/profile/delete-profile-uncertain-response.xml index fe825c36ff..ce66d6666a 100644 --- a/journeys/profile/delete-profile-uncertain-response.xml +++ b/journeys/profile/delete-profile-uncertain-response.xml @@ -12,6 +12,6 @@ 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 + Restart the app without choosing Review and verify it shows pending local cleanup without automatically repeating deletion or restoring authentication diff --git a/journeys/profile/delete-profile.xml b/journeys/profile/delete-profile.xml index cfb33769e3..1f358add6b 100644 --- a/journeys/profile/delete-profile.xml +++ b/journeys/profile/delete-profile.xml @@ -15,7 +15,8 @@ Open the existing profile from the Home header Open Edit Profile Scroll to Delete Profile and tap it - Confirm deletion + Wait for profile removal preparation to finish and verify the confirmation dialog appears without deleting the profile + Confirm deletion once Verify a progress indicator is visible while deletion is pending and profile actions cannot be used Wait for deletion to finish and verify profile onboarding is shown Return Home and reopen Profile; verify the deleted profile does not reappear diff --git a/journeys/profile/profile-cleanup-failure.xml b/journeys/profile/profile-cleanup-failure.xml index f9fd8c2e29..fb87f94734 100644 --- a/journeys/profile/profile-cleanup-failure.xml +++ b/journeys/profile/profile-cleanup-failure.xml @@ -5,7 +5,8 @@ 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. + cleanup; profile-removal-recovery.xml covers explicit recovery. Cross-device conditional contact deletion + requires the separate native contract. Open Edit Profile and confirm deletion with the cleanup fault enabled @@ -13,8 +14,8 @@ 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 + Verify an uncertain profile-deletion error retains recovery information without success feedback and keeps authenticated automatic work paused Cancel the failure dialog and verify the app starts no second deletion - Restart the app and verify no profile deletion is automatically replayed + Restart the app and verify pending local cleanup is shown without automatic profile deletion or authenticated reactivation diff --git a/journeys/profile/profile-removal-recovery.xml b/journeys/profile/profile-removal-recovery.xml new file mode 100644 index 0000000000..a9fa35b5bb --- /dev/null +++ b/journeys/profile/profile-removal-recovery.xml @@ -0,0 +1,25 @@ + + + Use a disposable authenticated profile and controlled homeserver/operation/storage faults. + These fault gates are outside the standard Capabilities; no live funds or wallet wipe is needed. + Keep a redacted operation counter. Recreate the fixture separately for each failure checkpoint. + Local Disconnect does not assert remote deletion. Conditional contact deletion across devices is + not proved by local ownership, and requires the separate native CAS fixture. + + + Open Edit Profile, request deletion and verify preparation opens a confirmation without a mutation + Confirm once, lose a mutation acknowledgement and verify failure feedback without success or automatic replay + Tap Review and verify only read-only reconciliation runs before a new confirmation appears + In separate fixtures, edit the profile or change or add a contact after the failure and verify Review rejects the changed targets without a mutation + Review unchanged remaining records, then recreate a record that was observed absent and verify a later Review cannot add it back to this attempt + Cancel that confirmation and verify the mutation count does not increase + Choose Disconnect from the failure options and verify a separate local-only confirmation appears + Cancel local Disconnect and verify neither local cleanup nor remote mutation runs + Confirm local Disconnect while credential erasure is unavailable and verify recovery remains pending without clearing consumed-payment-list safety state + Restore local storage, restart after credential erasure but before local completion and open Profile + Verify pending cleanup and Disconnect remain visible with no stored identity, no authenticated activation and no automatic remote mutation + Confirm local Disconnect and verify all required local cleanup finishes before leaving Profile + In a fresh fixture, replace the sign-in before an old confirmation or completion is delivered and verify it cannot act on or navigate away from the replacement + Open ordinary receive and verify address accounting remains available while profile cleanup is pending + + From ff4dc35e5eb7cb0b6a18d8e9f9d5ece1e9a08536 Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 26 Oct 2026 08:37:12 +0200 Subject: [PATCH 11/61] chore: rename changelog fragment --- changelog.d/next/{1687.fixed.md => 1693.fixed.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changelog.d/next/{1687.fixed.md => 1693.fixed.md} (100%) diff --git a/changelog.d/next/1687.fixed.md b/changelog.d/next/1693.fixed.md similarity index 100% rename from changelog.d/next/1687.fixed.md rename to changelog.d/next/1693.fixed.md From 7e2e466cafd10bc0883afe0630bfc094cb8c65be Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 26 Oct 2026 10:23:08 +0200 Subject: [PATCH 12/61] fix: complete profile removal recovery safely --- .../profile/ProfileRecoveryContentTest.kt | 9 ++- .../to/bitkit/data/ProfileRemovalStore.kt | 15 ++--- .../bitkit/repositories/PrivatePaykitRepo.kt | 8 +++ .../java/to/bitkit/repositories/PubkyRepo.kt | 7 +- .../java/to/bitkit/repositories/WalletRepo.kt | 16 +++-- .../to/bitkit/services/PaykitSdkService.kt | 3 +- .../screens/profile/EditProfileViewModel.kt | 13 +++- .../ui/screens/profile/ProfileScreen.kt | 7 +- .../ui/screens/profile/ProfileViewModel.kt | 7 +- .../usecases/ProfileRemovalCoordinator.kt | 7 +- .../to/bitkit/usecases/WipeWalletUseCase.kt | 11 +++- .../AppWidgetRefreshSchedulerTest.kt | 3 +- .../appwidget/AppWidgetRefreshWorkerTest.kt | 3 +- .../to/bitkit/build/PubkyAuthManifestTest.kt | 8 ++- .../to/bitkit/data/ProfileRemovalStoreTest.kt | 32 +++++++++- .../to/bitkit/repositories/BackupRepoTest.kt | 54 ++++++++++++++++ .../repositories/PrivatePaykitRepoTest.kt | 5 ++ .../to/bitkit/repositories/PubkyRepoTest.kt | 47 +++++++++++++- .../to/bitkit/repositories/WalletRepoTest.kt | 14 ++++ .../bitkit/services/PaykitSdkServiceTest.kt | 16 +++++ .../profile/EditProfileViewModelTest.kt | 31 +++++++-- .../screens/profile/ProfileViewModelTest.kt | 24 +++++++ .../usecases/ProfileRemovalCoordinatorTest.kt | 64 ++++++++++++++++--- .../bitkit/usecases/WipeWalletUseCaseTest.kt | 9 +-- 24 files changed, 362 insertions(+), 51 deletions(-) diff --git a/app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt b/app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt index 7c67be5946..c6a89d8da8 100644 --- a/app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt +++ b/app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt @@ -11,6 +11,7 @@ import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick +import androidx.test.espresso.Espresso.pressBackUnconditionally import androidx.test.platform.app.InstrumentationRegistry import org.junit.Rule import org.junit.Test @@ -30,12 +31,13 @@ class ProfileRecoveryContentTest { fun restartRecoveryWithoutCredentialsRequiresLocalConfirmation() { var state by mutableStateOf(ProfileUiState(recoveryPending = true, localDisconnect = true)) var confirmations = 0 + var back = 0 compose.setContent { AppThemeSurface { CompositionLocalProvider(LocalInspectionMode provides true) { ProfileContent( uiState = state, - onBackClick = {}, + onBackClick = { back++ }, onClickEdit = { error("Pending recovery must not offer editing") }, onClickCopy = {}, onClickShare = {}, @@ -67,6 +69,11 @@ class ProfileRecoveryContentTest { compose.onNodeWithTag("DialogConfirm").performClick() compose.runOnIdle { assertEquals(1, confirmations) } compose.onNodeWithTag("ProfileRecoveryDisconnect").assertIsNotEnabled() + compose.onNodeWithTag("NavigationBack").performClick() + compose.onNodeWithTag("HeaderMenu").assertDoesNotExist() + pressBackUnconditionally() + compose.onNodeWithTag("ProfileRecoveryDisconnect").assertIsDisplayed() + compose.runOnIdle { assertEquals(0, back) } } @Test diff --git a/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt b/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt index b0cc7033a7..8e4b775722 100644 --- a/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt +++ b/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt @@ -14,7 +14,6 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.map @@ -73,14 +72,9 @@ class ProfileRemovalStore internal constructor(private val store: DataStore emit(true) - if (attempt < 3) { - delay((250L shl attempt.toInt()).milliseconds) - true - } else { - false - } + delay((250L shl attempt.coerceAtMost(8).toInt()).coerceAtMost(60_000).milliseconds) + true } - .catch { emit(true) } } internal suspend fun pendingAttempt(): String? = store.data.first().attemptId @@ -195,6 +189,7 @@ internal object ProfileRemovalSerializer : Serializer { } } -internal class ProfileRemovalPending : AppError( - "Profile cleanup is pending. Disconnect the profile to finish local recovery." +internal class ProfileRemovalPending(cause: Throwable? = null) : AppError( + "Profile cleanup is pending. Disconnect the profile to finish local recovery.", + cause, ) diff --git a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt index 6ab085472a..04078a464d 100644 --- a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt @@ -587,6 +587,14 @@ class PrivatePaykitRepo @Inject constructor( } } + /** Retry a complete WALLET capture only after durable removal recovery has been acknowledged. */ + internal suspend fun notifyProfileRemovalCompleted(pause: ProfileDeletionPause) = withContext( + serializedDispatcher + ) { + check(pause in profileDeletionPauses) { "Profile removal has already finished" } + notifyBackupStateChanged() + } + private suspend fun clearLocalPaymentState() { clearPendingMessageDrainRetries() knownSavedContactKeys.clear() diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 784f1e0c6e..18bc8ec910 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -376,7 +376,7 @@ class PubkyRepo @Inject constructor( _sessionRestorationFailed.value = true runSuspendCatching { pubkyService.preparePublicProfileRecovery() } .onFailure { Logger.warn("Failed to prepare public profile access", it, context = TAG) } - throw failure + throw if (failure is ProfileRemovalPending) failure else ProfileRemovalPending(failure) } } @@ -1973,6 +1973,11 @@ class PubkyRepo @Inject constructor( clearProfileMetadataAfterCredentialTeardown() } + internal suspend fun notifyProfileRemovalCompleted() { + identityOperations.requireRemoval() + notifyBackupStateChanged() + } + /** The wallet wipe has acknowledged keychain deletion and still owns both teardown barriers. */ internal suspend fun finishProfileWipeLocally() { identityOperations.requireWipe() diff --git a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt index c7c9173a01..b1bb744dad 100644 --- a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt @@ -48,7 +48,6 @@ import to.bitkit.models.toDerivationPath import to.bitkit.services.AddressDerivationInfo import to.bitkit.services.CoreService import to.bitkit.usecases.DeriveBalanceStateUseCase -import to.bitkit.usecases.WipeIncomplete import to.bitkit.usecases.WipeWalletUseCase import to.bitkit.utils.Bip21Utils import to.bitkit.utils.Logger @@ -642,12 +641,15 @@ class WalletRepo @Inject constructor( } suspend fun wipeWallet(walletIndex: Int = 0): Result = withContext(bgDispatcher) { - wipeWalletUseCase( - walletIndex = walletIndex, - resetWalletState = ::resetState, - onSuccess = ::setWalletExistsState, - ).onFailure { - if (it is WipeIncomplete) setWalletExistsState() + try { + wipeWalletUseCase( + walletIndex = walletIndex, + resetWalletState = ::resetState, + onSuccess = {}, + ) + } finally { + runCatching { setWalletExistsState() } + .onFailure { Logger.warn("Failed to refresh wallet existence after wipe", it, context = TAG) } } } diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt index 713f3c5111..e1a18f4e04 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt @@ -1692,7 +1692,8 @@ class PaykitSdkService @Inject constructor( runSuspendCatching { initialize() } .onFailure { Logger.warn("Failed to initialize Paykit before wallet wipe", it, context = TAG) - preparePublicProfileRecovery() + runSuspendCatching { preparePublicProfileRecovery() } + .onFailure { Logger.warn("Failed to prepare public access before wallet wipe", it, context = TAG) } } return operationLock.withWalletWipe { // Removal has drained. Bootstrap publication never waits for the SDK lock. diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt index c99f3aa71f..ffe9b84561 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt @@ -298,7 +298,18 @@ class EditProfileViewModel @Inject constructor( removalCoordinator.remove(confirmation).onSuccess { endedOwner -> removalFailure = null if (removalCoordinator.isCurrent(endedOwner)) { - _effects.emit(EditProfileEffect.RemovalCompleted(endedOwner)) + val successToast = if (confirmation.localOnly) { + ProfileRemoval.UNLINK.successToast + } else { + _uiState.value.removal.successToast + } + ToastEventBus.send( + type = Toast.ToastType.SUCCESS, + title = context.getString(successToast), + ) + if (removalCoordinator.isCurrent(endedOwner)) { + _effects.emit(EditProfileEffect.RemovalCompleted(endedOwner)) + } } }.onFailure { error -> removalFailure = (error as? ProfileRemovalFailure) ?: removalFailure diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt index f46736a047..221769a74c 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt @@ -1,5 +1,6 @@ package to.bitkit.ui.screens.profile +import androidx.activity.compose.BackHandler import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut @@ -127,13 +128,15 @@ internal fun ProfileContent( onSaveTag: (String) -> Unit, onDismissCopiedPopup: () -> Unit, ) { + BackHandler(enabled = uiState.isSigningOut) {} + val currentProfile = uiState.profile val cachedProfile = uiState.cachedProfile val topBar = @Composable { modifier: Modifier -> AppTopBar( titleText = stringResource(R.string.profile__nav_title), - onBackClick = onBackClick, - actions = { DrawerNavIcon() }, + onBackClick = { if (!uiState.isSigningOut) onBackClick() }, + actions = { if (!uiState.isSigningOut) DrawerNavIcon() }, modifier = modifier, ) } diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt index abb6c6af76..f8465e7044 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt @@ -147,7 +147,12 @@ class ProfileViewModel @Inject constructor( fun showSignOutConfirmation() { if (_isSigningOut.value) return - val owner = uiState.value.owner ?: return + val state = uiState.value + val owner = if (state.recoveryPending) { + pubkyRepo.profileOwner().takeIf { it.signIn == null } ?: state.owner + } else { + state.owner + } ?: return val revision = ++preparationRevision _isSigningOut.value = true viewModelScope.launch { diff --git a/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt b/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt index a6c1757934..bf6e1c7a0e 100644 --- a/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt +++ b/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt @@ -118,12 +118,14 @@ class ProfileRemovalCoordinator @Inject constructor( sharingRepo.withProfileRemoval { pubkyRepo.performProfileRemoval(confirmation.owner, confirmation.attemptId) { var localCompletionStarted = false + var removalMayHaveStarted = removalStore.pendingAttempt() != null try { check(confirmation.deletion == null || confirmation.reviewCeiling.get() === confirmation.deletion) { "This confirmation was replaced by a later review" } privatePaykitRepo.withProfileDeletionPaused { pause -> confirmation.deletion?.let { pubkyRepo.validateProfileDeletion(it) } + removalMayHaveStarted = true removalStore.begin(confirmation.attemptId) if (!confirmation.localOnly) { privatePaykitRepo.removePublishedEndpointsForCleanup(TAG, deferAppSync = true).getOrThrow() @@ -136,12 +138,15 @@ class ProfileRemovalCoordinator @Inject constructor( withContext(NonCancellable) { privatePaykitRepo.finishProfileRemoval(pause).getOrThrow() removalStore.complete(confirmation.attemptId) + privatePaykitRepo.notifyProfileRemovalCompleted(pause) + pubkyRepo.notifyProfileRemovalCompleted() } } } catch (error: CancellationException) { - captureFailure(error, confirmation, localCompletionStarted) + if (removalMayHaveStarted) captureFailure(error, confirmation, localCompletionStarted) throw error } catch (error: Throwable) { + if (!removalMayHaveStarted) throw error throw captureFailure(error, confirmation, localCompletionStarted) } }.getOrThrow() diff --git a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt index 4262c8933c..fc39095026 100644 --- a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt @@ -66,6 +66,7 @@ class WipeWalletUseCase @Inject constructor( if (!wipeMutex.tryLock()) return Result.failure(WipeAlreadyInProgress()) backupRepo.setWiping(true) lightningRepo.setWiping(true) + var credentialsMayBeErased = false val result = try { runSuspendCatching { contactPaymentSettingsRepo.get().withWalletWipe(pubkyRepo::withWalletWipeAdmission) { @@ -77,7 +78,7 @@ class WipeWalletUseCase @Inject constructor( stopNode().getOrThrow() profileRemovalStore.begin(attemptId) if (pending == null) cleanupRemote() - wipeLocal(walletIndex, pause).getOrThrow() + wipeLocal(walletIndex, pause) { credentialsMayBeErased = true }.getOrThrow() profileRemovalStore.complete(attemptId) resetWalletState() onSuccess() @@ -85,6 +86,9 @@ class WipeWalletUseCase @Inject constructor( } } } + }.let { outcome -> + val error = outcome.exceptionOrNull() + if (error != null && credentialsMayBeErased) Result.failure(WipeIncomplete(error)) else outcome } } finally { lightningRepo.setWiping(false) @@ -112,12 +116,13 @@ class WipeWalletUseCase @Inject constructor( private suspend fun wipeLocal( walletIndex: Int, pause: PrivatePaykitRepo.ProfileDeletionPause, + onCredentialWipe: () -> Unit, ): Result { lightningRepo.wipeStorage(walletIndex).onFailure { return Result.failure(it) } step("clear post-migration sync flag") { migrationService.setNeedsPostMigrationSync(false) } step("clear migration data") { migrationService.cleanupAfterMigration() } - runSuspendCatching { usdtRepo.wipe { keychain.wipe() }.getOrThrow() } - .getOrElse { return Result.failure(WipeIncomplete(it)) } + onCredentialWipe() + usdtRepo.wipe { keychain.wipe() }.getOrThrow() paykitUsdtPaymentRepo.resetForWipe() // Consumption watermarks survive until the keychain wipe is acknowledged. Pending remains on any failure. privatePaykitRepo.get().finishProfileRemoval(pause).getOrElse { return Result.failure(it) } diff --git a/app/src/test/java/to/bitkit/appwidget/AppWidgetRefreshSchedulerTest.kt b/app/src/test/java/to/bitkit/appwidget/AppWidgetRefreshSchedulerTest.kt index 4e0ff760e7..e999472ed8 100644 --- a/app/src/test/java/to/bitkit/appwidget/AppWidgetRefreshSchedulerTest.kt +++ b/app/src/test/java/to/bitkit/appwidget/AppWidgetRefreshSchedulerTest.kt @@ -1,6 +1,7 @@ package to.bitkit.appwidget import android.app.AlarmManager +import android.app.Application import android.app.PendingIntent import android.content.Context import android.content.Intent @@ -20,7 +21,7 @@ import to.bitkit.appwidget.model.AppWidgetType import kotlin.test.assertEquals import kotlin.time.Duration.Companion.seconds -@Config(sdk = [34]) +@Config(application = Application::class, sdk = [34]) @RunWith(RobolectricTestRunner::class) class AppWidgetRefreshSchedulerTest { private val context = ApplicationProvider.getApplicationContext() diff --git a/app/src/test/java/to/bitkit/appwidget/AppWidgetRefreshWorkerTest.kt b/app/src/test/java/to/bitkit/appwidget/AppWidgetRefreshWorkerTest.kt index 1189084e03..74860a7d31 100644 --- a/app/src/test/java/to/bitkit/appwidget/AppWidgetRefreshWorkerTest.kt +++ b/app/src/test/java/to/bitkit/appwidget/AppWidgetRefreshWorkerTest.kt @@ -1,5 +1,6 @@ package to.bitkit.appwidget +import android.app.Application import android.content.Context import androidx.test.core.app.ApplicationProvider import androidx.work.WorkerParameters @@ -38,7 +39,7 @@ import kotlin.time.ExperimentalTime import kotlin.time.Instant @OptIn(ExperimentalTime::class) -@Config(sdk = [34]) +@Config(application = Application::class, sdk = [34]) @RunWith(RobolectricTestRunner::class) class AppWidgetRefreshWorkerTest : BaseUnitTest() { private val context = ApplicationProvider.getApplicationContext() diff --git a/app/src/test/java/to/bitkit/build/PubkyAuthManifestTest.kt b/app/src/test/java/to/bitkit/build/PubkyAuthManifestTest.kt index 8354250793..26706fb82d 100644 --- a/app/src/test/java/to/bitkit/build/PubkyAuthManifestTest.kt +++ b/app/src/test/java/to/bitkit/build/PubkyAuthManifestTest.kt @@ -121,7 +121,13 @@ class PubkyAuthManifestTest { .setPackage(packageName) val resolved = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) if (alias == null) { - assertTrue(resolved.isEmpty(), it) + val actual = resolved.map { result -> + val activity = result.activityInfo + val component = ComponentName(packageName, activity.name) + val override = packageManager.getComponentEnabledSetting(component) + "${activity.name}: enabled=${activity.enabled}, override=$override" + } + assertTrue(resolved.isEmpty(), "$it resolved to $actual") } else { val activity = resolved.single().activityInfo assertEquals(alias.className, activity.name, it) diff --git a/app/src/test/java/to/bitkit/data/ProfileRemovalStoreTest.kt b/app/src/test/java/to/bitkit/data/ProfileRemovalStoreTest.kt index 476cc1375d..31d0581525 100644 --- a/app/src/test/java/to/bitkit/data/ProfileRemovalStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/ProfileRemovalStoreTest.kt @@ -37,7 +37,7 @@ class ProfileRemovalStoreTest { val folder = TemporaryFolder() @Test - fun `observation fails closed with bounded retries and restarts after explicit durable completion`() = runTest { + fun `observation fails closed with backoff and restarts after explicit durable completion`() = runTest { val id = UUID.randomUUID().toString() val state = MutableStateFlow(ProfileRemovalState(attemptId = id)) var unavailable = true @@ -54,7 +54,7 @@ class ProfileRemovalStoreTest { val observed = mutableListOf() backgroundScope.launch { store.pending.collect { observed += it } } runCurrent() - advanceTimeBy(10_000) + advanceTimeBy(1_750) runCurrent() assertEquals(4, reads) assertEquals(true, observed.last()) @@ -65,6 +65,34 @@ class ProfileRemovalStoreTest { assertNull(store.pendingAttempt()) } + @Test + fun `observation recovers from prolonged read errors without a cleanup mutation`() = runTest { + var available = false + var reads = 0 + val store = ProfileRemovalStore(object : DataStore { + override val data = flow { + reads++ + if (!available) throw IOException("Local storage unavailable") + emit(ProfileRemovalState()) + } + override suspend fun updateData( + transform: suspend (ProfileRemovalState) -> ProfileRemovalState + ): ProfileRemovalState = + error("Read-only recovery must not mutate cleanup state") + }) + val observed = mutableListOf() + backgroundScope.launch { store.pending.collect { observed += it } } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + assertEquals(true, observed.last()) + available = true + advanceTimeBy(60_000) + runCurrent() + assertEquals(false, observed.last()) + assertTrue(reads <= 12, "Local recovery must retain capped backoff") + } + @Test fun `restart retains pending without authorizing cleanup or another attempt`() = runTest { val file = folder.newFile("removal").also { it.delete() } diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 188ae1f8c2..adb0281473 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -41,6 +41,7 @@ import to.bitkit.data.BlocktankRefundAddress import to.bitkit.data.CacheStore import to.bitkit.data.HwWalletData import to.bitkit.data.HwWalletStore +import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.data.WatchOnlyAccountAllocationState @@ -73,6 +74,7 @@ import to.bitkit.services.LightningService import to.bitkit.services.PaykitSdkService import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError +import java.util.UUID import javax.inject.Provider import kotlin.coroutines.cancellation.CancellationException import kotlin.test.assertEquals @@ -1235,6 +1237,58 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `acknowledged removal wakes the suppressed wallet category after delayed completion`() = test { + val removal = ProfileRemovalStore.inMemoryForTesting() + val attempt = UUID.randomUUID().toString() + removal.withAccess(attempt) { removal.begin(attempt) } + whenever(clock.now()).thenAnswer { Instant.fromEpochMilliseconds(3_000 + currentTime) } + val statuses = MutableStateFlow( + mapOf(BackupCategory.WALLET to BackupItemStatus(synced = 1_000, required = 2_000)) + ) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + stubMetadataBackupReads() + val metadataVersion = MutableStateFlow(0L) + val walletVersion = MutableStateFlow(0L) + whenever(pubkyRepo.backupStateVersion).thenReturn(metadataVersion) + whenever(privatePaykitRepo.backupStateVersion).thenReturn(walletVersion) + whenever { privatePaykitRepo.backupSnapshot() }.doSuspendableAnswer { + runCatching { + removal.requireNoPending() + PrivatePaykitBackupSnapshot(null, 0) + } + } + try { + sut.startObservingBackups() + runCurrent() + advanceTimeBy(5_000) + runCurrent() + verify(privatePaykitRepo, times(1)).backupSnapshot() + verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) + advanceTimeBy(20_000) + runCurrent() + verify(privatePaykitRepo, times(1)).backupSnapshot() + removal.withAccess(attempt) { removal.complete(attempt) } + metadataVersion.value++ + runCurrent() + advanceTimeBy(5_000) + runCurrent() + // Pubky metadata notifications cannot release a failed WALLET capture. + verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) + assertTrue(statuses.value.getValue(BackupCategory.WALLET).isRequired) + walletVersion.value++ + runCurrent() + advanceTimeBy(5_000) + runCurrent() + verify(privatePaykitRepo, times(2)).backupSnapshot() + verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), any()) + assertFalse(statuses.value.getValue(BackupCategory.WALLET).isRequired) + } finally { + sut.stopObservingBackups() + } + } + @Test fun `wallet backup retains pending work while profile removal owns the SDK`() = test { whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(3_000)) diff --git a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt index 2f3bbd7bbb..9db8bea722 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt @@ -362,10 +362,15 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { fun `profile removal finalization is local and rejects an ended pause`() = test { val pause = sut.beginProfileDeletion() assertTrue(sut.finishProfileRemoval(pause).isSuccess) + val beforeCompletion = sut.backupStateVersion.value + sut.notifyProfileRemovalCompleted(pause) + assertEquals(beforeCompletion + 1, sut.backupStateVersion.value) verify(paykitSdkService, never()).clearState() sut.endProfileDeletion(pause) clearInvocations(cacheStore) assertTrue(sut.finishProfileRemoval(pause).isFailure) + assertFailsWith { sut.notifyProfileRemovalCompleted(pause) } + assertEquals(beforeCompletion + 1, sut.backupStateVersion.value) verify(cacheStore, never()).reset() } diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 4f753fd1eb..b9c7dfc482 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -1,5 +1,6 @@ package to.bitkit.repositories +import androidx.datastore.core.DataStore import app.cash.turbine.test import coil3.ImageLoader import coil3.disk.DiskCache @@ -39,6 +40,7 @@ import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.job import kotlinx.coroutines.launch @@ -66,6 +68,7 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.verifyBlocking import org.mockito.kotlin.whenever import org.mockito.verification.VerificationMode +import to.bitkit.data.ProfileRemovalState import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.PubkyCachedProfile import to.bitkit.data.PubkyImageCacheEpoch @@ -93,6 +96,7 @@ import to.bitkit.test.forEachCase import to.bitkit.usecases.ProfileRemovalCoordinator import to.bitkit.usecases.ProfileRemovalFailure import to.bitkit.utils.AppError +import java.io.IOException import java.util.UUID import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -211,6 +215,42 @@ class PubkyRepoTest : BaseUnitTest() { assertTrue(sut.performProfileRemoval(original) { error("obsolete owner admitted") }.isFailure) } + @Test + fun `completed removal schedules a new backup under its original admission`() = test { + advanceUntilIdle() + whenever { pubkyService.withProfileRemoval(any(), any()) }.doSuspendableAnswer { + it.getArgument Unit>(1).invoke() + } + val version = sut.backupStateVersion.value + sut.performProfileRemoval(sut.profileOwner()) { + sut.notifyProfileRemovalCompleted() + }.getOrThrow() + assertEquals(version + 1, sut.backupStateVersion.value) + assertFailsWith { sut.notifyProfileRemovalCompleted() } + } + + @Test + fun `unreadable removal state fails restoration closed without escaping resume`() = test { + var unavailable = true + val store = ProfileRemovalStore(object : DataStore { + override val data = flow { + if (unavailable) throw IOException("Local read unavailable") + emit(ProfileRemovalState()) + } + override suspend fun updateData( + transform: suspend (ProfileRemovalState) -> ProfileRemovalState, + ): ProfileRemovalState = error("Resume must not change recovery state") + }) + val resumed = createSut(removalStore = store) + try { + assertFalse(resumed.restoreSessionIfNeeded()) + assertFalse(resumed.isRestoringSession.value) + assertTrue(resumed.sessionRestorationFailed.value) + } finally { + unavailable = false + } + } + @Test fun `pending removal restart refuses activation and settles restoration without clearing credentials`() = test { advanceUntilIdle() @@ -355,7 +395,10 @@ class PubkyRepoTest : BaseUnitTest() { sut = createSut() } - private fun createSut(httpClient: HttpClient = mock()) = PubkyRepo( + private fun createSut( + httpClient: HttpClient = mock(), + removalStore: ProfileRemovalStore = profileRemovalStore, + ) = PubkyRepo( ioDispatcher = testDispatcher, pubkyService = pubkyService, keychain = keychain, @@ -366,7 +409,7 @@ class PubkyRepoTest : BaseUnitTest() { settingsStore = settingsStore, httpClient = httpClient, clock = clock, - profileRemovalStore = profileRemovalStore, + profileRemovalStore = removalStore, ) private fun PubkyRepo.removalCoordinatorForTest(): ProfileRemovalCoordinator { diff --git a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt index e4506b8a6b..c43fa58c3d 100644 --- a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt @@ -58,6 +58,7 @@ import java.util.ArrayDeque import kotlin.coroutines.CoroutineContext import kotlin.coroutines.cancellation.CancellationException import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue @@ -1700,6 +1701,19 @@ class WalletRepoTest : BaseUnitTest() { assertTrue(sut.walletState.value.walletExists) } + @Test + fun `canceled wipe refreshes acknowledged credential erasure without claiming completion`() = test { + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) + sut.setWalletExistsState() + assertTrue(sut.walletState.value.walletExists) + whenever(wipeWalletUseCase.invoke(any(), any(), any())).thenAnswer { + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(false) + throw CancellationException("Canceled after credential erasure") + } + assertFailsWith { sut.wipeWallet() } + assertFalse(sut.walletState.value.walletExists) + } + @Test fun `wipeWallet should return failure when use case fails`() = test { whenever(wipeWalletUseCase.invoke(any(), any(), any())).thenReturn(Result.failure(error)) diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt index 85123ce5d2..6470453f3d 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt @@ -2180,6 +2180,22 @@ class PaykitSdkServiceTest { } } + @Test + fun `wallet wipe remains available when platform initialization keeps failing`() = runTest { + val service = PaykitSdkService( + mock(), + mock(), + mock(), + ioDispatcher = StandardTestDispatcher(testScheduler), + platformInitializer = { throw AppError("Native setup unavailable") }, + settingsStore = mock(), + sdkFactory = { error("A failed setup must not create an SDK handle") }, + ) + var localCleanup = false + service.withWalletWipe { localCleanup = true } + assertTrue(localCleanup) + } + @Test fun `wallet wipe drains initialization before cleanup and allows fresh work`() = runTest { val sdk = mock() diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt index 627e4ffd85..ae6f266b14 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt @@ -19,12 +19,15 @@ import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import to.bitkit.R import to.bitkit.models.PubkyProfile import to.bitkit.models.PubkyProfileLink +import to.bitkit.models.Toast import to.bitkit.repositories.PubkyProfileOwner import to.bitkit.repositories.PubkyRepo import to.bitkit.repositories.PubkySignIn import to.bitkit.test.BaseUnitTest +import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.utils.AppError import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -64,6 +67,21 @@ class EditProfileViewModelTest : BaseUnitTest() { assertNull(fixture.store.pendingAttempt()) } + @Test + fun `completed removal shows success only for its ended owner`() = test { + val sut = createSut() + advanceUntilIdle() + sut.showDeleteConfirmation() + advanceUntilIdle() + ToastEventBus.events.test { + sut.deleteProfile() + advanceUntilIdle() + val toast = expectMostRecentItem() + assertEquals(Toast.ToastType.SUCCESS, toast.type) + assertEquals("Profile deleted", toast.title) + } + } + @Test fun `uncertain deletion review reads state and requires fresh confirmation`() = test { val sut = createSut() @@ -101,10 +119,13 @@ class EditProfileViewModelTest : BaseUnitTest() { assertTrue(sut.uiState.value.showDeleteDialog) assertTrue(sut.uiState.value.isLocalDisconnect) verify(pubkyRepo, never()).finishProfileRemovalLocally() - sut.effects.test { - sut.deleteProfile() - advanceUntilIdle() - assertIs(awaitItem()) + ToastEventBus.events.test { + sut.effects.test { + sut.deleteProfile() + advanceUntilIdle() + assertIs(awaitItem()) + } + assertEquals("Pubky unlinked", expectMostRecentItem().title) } verify(pubkyRepo, times(1)).deleteProfile(fixture.deletion) verify(pubkyRepo, never()).signOutForProfileRemoval() @@ -374,6 +395,8 @@ class EditProfileViewModelTest : BaseUnitTest() { ringCheck: CompletableDeferred? = null, ): EditProfileViewModel { whenever(context.getString(any())).thenReturn("") + whenever(context.getString(R.string.profile__delete_success)).thenReturn("Profile deleted") + whenever(context.getString(R.string.profile__unlink_success)).thenReturn("Pubky unlinked") if (ringCheck != null) { whenever { pubkyRepo.isRingAdoptedIdentity() }.doSuspendableAnswer { ringCheck.await() } } else { diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt index 70211e7042..e90fbd80a9 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt @@ -441,6 +441,30 @@ class ProfileViewModelTest : BaseUnitTest() { assertNull(fixture.store.pendingAttempt()) } + @Test + fun `existing profile screen can finish its ended profile cleanup locally`() = test { + val pending = MutableStateFlow(false) + val sut = createSut(recoveryPending = pending) + advanceUntilIdle() + sut.uiState.test { + awaitItem() + val id = UUID.randomUUID().toString() + fixture.store.withAccess(id) { fixture.store.begin(id) } + fixture.current = fixture.ended + pending.value = true + advanceUntilIdle() + sut.showSignOutConfirmation() + advanceUntilIdle() + assertTrue(sut.uiState.value.showSignOutDialog) + assertTrue(sut.uiState.value.localDisconnect) + sut.signOut() + advanceUntilIdle() + assertNull(fixture.store.pendingAttempt()) + verify(pubkyRepo, never()).signOutForProfileRemoval() + cancelAndIgnoreRemainingEvents() + } + } + @Test fun `sign out waits for confirmation and delayed effect is bound to ended owner`() = test { val sut = createSut(createProfile()) diff --git a/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt b/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt index a573bb22f7..e8765fed77 100644 --- a/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt +++ b/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt @@ -101,6 +101,16 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { events += "local credentials and metadata" current = ended } + whenever { privateRepo.notifyProfileRemovalCompleted(pause) }.doSuspendableAnswer { + assertNull(store.pendingAttempt()) + events += "wallet backup ready" + Unit + } + whenever { pubky.notifyProfileRemovalCompleted() }.doSuspendableAnswer { + assertNull(store.pendingAttempt()) + events += "backup ready" + Unit + } whenever { privateRepo.finishProfileRemoval(pause) }.doSuspendableAnswer { assertNotNull(store.pendingAttempt()) events += "private local" @@ -121,7 +131,9 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { "profile", "revoke", "local credentials and metadata", - "private local" + "private local", + "wallet backup ready", + "backup ready" ), events ) @@ -130,6 +142,38 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { assertTrue(sut.isCurrent(ended)) } + @Test + fun `backup readiness waits for delayed durable marker completion`() = test { + val data = MutableStateFlow(ProfileRemovalState()) + val completing = CompletableDeferred() + val release = CompletableDeferred() + store = ProfileRemovalStore(object : DataStore { + override val data = data + override suspend fun updateData( + transform: suspend (ProfileRemovalState) -> ProfileRemovalState + ): ProfileRemovalState { + val next = transform(data.value) + if (next.attemptId == null) { + completing.complete(Unit) + release.await() + } + data.value = next + return next + } + }) + val confirmation = sut.prepareDeletion(original).getOrThrow() + val removal = async { sut.remove(confirmation) } + completing.await() + assertEquals(confirmation.attemptId, store.pendingAttempt()) + verify(privateRepo, never()).notifyProfileRemovalCompleted(any()) + verify(pubky, never()).notifyProfileRemovalCompleted() + release.complete(Unit) + assertTrue(removal.await().isSuccess) + verify(privateRepo).notifyProfileRemovalCompleted(pause) + verify(pubky).notifyProfileRemovalCompleted() + assertNull(store.pendingAttempt()) + } + @Test fun `one confirmation cannot repeat an uncertain profile mutation`() = test { whenever(pubky.deleteProfile(deletion)).thenReturn(Result.failure(IllegalStateException("lost response"))) @@ -307,16 +351,16 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { } @Test - fun `explicit local disconnect remains available after precondition failure without a marker`() = test { + fun `changed confirmation before any cleanup permits a fresh deletion without uncertainty`() = test { whenever { pubky.validateProfileDeletion(deletion) }.thenAnswer { error("profile changed") } - val failure = assertIs( - sut.remove(sut.prepareDeletion(original).getOrThrow()).exceptionOrNull() - ) - assertNull(store.pendingAttempt()) - assertTrue(sut.remove(sut.prepareLocalDisconnect(failure).getOrThrow()).isSuccess) + val confirmation = sut.prepareDeletion(original).getOrThrow() + val failure = sut.remove(confirmation).exceptionOrNull() + assertIs(failure) + assertNull(sut.failureFor(confirmation)) assertNull(store.pendingAttempt()) verify(pubky, never()).deleteProfile(any()) - verify(pubky, never()).signOutForProfileRemoval() + verify(privateRepo, never()).removePublishedEndpointsForCleanup(any(), any()) + assertTrue(sut.prepareDeletion(original).isSuccess) } @Test @@ -389,8 +433,12 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { assertSame(ended, failure.recoveryOwner) assertEquals(confirmation.attemptId, store.pendingAttempt()) assertTrue(sut.reviewAgain(failure).isFailure) + verify(privateRepo, never()).notifyProfileRemovalCompleted(any()) + verify(pubky, never()).notifyProfileRemovalCompleted() rejectCompletion = false assertTrue(sut.remove(sut.prepareLocalDisconnect(failure).getOrThrow()).isSuccess) + verify(privateRepo).notifyProfileRemovalCompleted(pause) + verify(pubky).notifyProfileRemovalCompleted() assertNull(store.pendingAttempt()) verify(pubky, times(1)).deleteProfile(deletion) verify(pubky, times(1)).signOutForProfileRemoval() diff --git a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt index 5a67ada663..6a54104208 100644 --- a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt @@ -310,7 +310,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { onSuccess = { onSetWalletExistsStateCalled = true }, ) - assertEquals(failure.message, result.exceptionOrNull()?.message) + assertEquals(failure.message, assertIs(result.exceptionOrNull()).cause?.message) verify(keychain).wipe() verify(privatePaykitRepo).finishProfileRemoval(profilePause) verify(privatePaykitAddressReservationRepo, never()).clear() @@ -329,7 +329,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { onSuccess = { onSetWalletExistsStateCalled = true }, ) - assertEquals(failure.message, result.exceptionOrNull()?.message) + assertEquals(failure.message, assertIs(result.exceptionOrNull()).cause?.message) verify(keychain).wipe() verify(pubkyRepo).finishProfileWipeLocally() verify(privatePaykitAddressReservationRepo).clear() @@ -448,7 +448,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { onSuccess = { onSetWalletExistsStateCalled = true }, ) - assertTrue(result.isFailure) + assertEquals("clear failed", assertIs(result.exceptionOrNull()).cause?.message) verify(keychain).wipe() assertFalse(onSetWalletExistsStateCalled) assertFalse(onWipeCalled) @@ -465,7 +465,8 @@ class WipeWalletUseCaseTest : BaseUnitTest() { onSuccess = { onSetWalletExistsStateCalled = true }, ) - assertEquals(error, assertIs(result.exceptionOrNull()).cause) + val failure = assertIs(result.exceptionOrNull()) + assertTrue(generateSequence(failure.cause) { it.cause }.any { it === error }) verify(lightningRepo).wipeStorage(0) verify(db, never()).clearAllTables() verify(settingsStore, never()).reset() From d4ba9076b18901721fd9c5a156a0005d16fe6380 Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 26 Oct 2026 11:09:53 +0200 Subject: [PATCH 13/61] fix: preserve active identity during scheduled restore setup --- .../java/to/bitkit/repositories/PubkyRepo.kt | 7 ++++- .../to/bitkit/repositories/PubkyRepoTest.kt | 30 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 8340349b42..41854bbf9a 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -379,7 +379,12 @@ class PubkyRepo @Inject constructor( if (expectedRevision != null && expectedRevision != storedIdentityRevision.get()) { return@withContext Result.success(Unit) } - initializeSession() to storedIdentityRevision.get() + val restored = if (expectedRevision != null && _publicKey.value != null) { + true + } else { + initializeSession() + } + restored to storedIdentityRevision.get() } if (revision != storedIdentityRevision.get()) return@withContext Result.success(Unit) if (restored) loadIdentityData() diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index a6d429a882..937806b02b 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -48,6 +48,8 @@ import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.currentTime import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.yield import org.junit.Before import org.junit.Test import org.mockito.Mockito.clearInvocations @@ -2433,6 +2435,34 @@ class PubkyRepoTest : BaseUnitTest() { verify(pubkyService).importSession("restored_session") } + @Test + fun `scheduled metadata refresh preserves an identity already activated by restore`() = test { + sut.awaitInitialization() + whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn("restored_session") + whenever(pubkyService.importSession("restored_session")).thenReturn(VALID_SELF_KEY) + assertTrue(sut.restoreSessionIfNeeded()) + val originalSignIn = assertNotNull(sut.currentSignIn()) + assertEquals(VALID_SELF_KEY, sut.publicKey.value) + clearInvocations(pubkyService) + whenever(pubkyService.importSession("restored_session")).doSuspendableAnswer { + throw PaykitException.Transport("transport_error", "controlled unavailable re-import") + } + val refreshed = CompletableDeferred() + whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + refreshed.complete(Unit) + createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile(name = "Refreshed")) + } + sut.scheduleInitializationAfterRestore() + yield() + advanceUntilIdle() + assertEquals(VALID_SELF_KEY, sut.publicKey.value) + assertTrue(sut.isCurrent(originalSignIn)) + assertFalse(sut.sessionRestorationFailed.value) + verify(pubkyService, never()).importSession(any()) + withTimeout(1.seconds) { refreshed.await() } + verify(pubkyService).resolveContactProfile(VALID_SELF_KEY, true) + } + @Test fun `new restored identity proceeds while old scheduled profile loading is held`() = test { sut.awaitInitialization() From 7e2fd14f0ba6d5cab66c98401abc813dc6a05a0b Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 26 Oct 2026 19:58:10 +0200 Subject: [PATCH 14/61] fix: keep pending profile cleanup distinct from expiry --- .../main/java/to/bitkit/repositories/PubkyRepo.kt | 2 +- .../java/to/bitkit/repositories/PubkyRepoTest.kt | 12 +++++++++--- changelog.d/next/1693.fixed.md | 2 +- journeys/profile/profile-removal-recovery.xml | 1 + 4 files changed, 12 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 18bc8ec910..b809e80dd2 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -373,7 +373,7 @@ class PubkyRepo @Inject constructor( runSuspendCatching { profileRemovalStore.requireNoPending() }.exceptionOrNull()?.let { failure -> // Retained credentials must not activate while local teardown is unresolved or unreadable. _isRestoringSession.value = false - _sessionRestorationFailed.value = true + _sessionRestorationFailed.update { false } runSuspendCatching { pubkyService.preparePublicProfileRecovery() } .onFailure { Logger.warn("Failed to prepare public profile access", it, context = TAG) } throw if (failure is ProfileRemovalPending) failure else ProfileRemovalPending(failure) diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index b9c7dfc482..a2e892d1f2 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -245,7 +245,8 @@ class PubkyRepoTest : BaseUnitTest() { try { assertFalse(resumed.restoreSessionIfNeeded()) assertFalse(resumed.isRestoringSession.value) - assertTrue(resumed.sessionRestorationFailed.value) + assertFalse(resumed.sessionRestorationFailed.value) + assertTrue(resumed.requiresProfileRecovery()) } finally { unavailable = false } @@ -261,8 +262,13 @@ class PubkyRepoTest : BaseUnitTest() { val restarted = createSut() advanceUntilIdle() assertFalse(restarted.isRestoringSession.value) - assertTrue(restarted.sessionRestorationFailed.value) - assertFalse(restarted.restoreSessionIfNeeded()) + assertFalse(restarted.sessionRestorationFailed.value) + repeat(3) { + restarted.clearSessionRestorationFailed() + assertFalse(restarted.restoreSessionIfNeeded()) + assertFalse(restarted.sessionRestorationFailed.value) + assertTrue(restarted.requiresProfileRecovery()) + } assertEquals(PubkyIdentityReadiness.RecoveryRequired, restarted.awaitIdentityReady()) assertTrue(restarted.initialize().isFailure) verify(pubkyService, never()).initialize() diff --git a/changelog.d/next/1693.fixed.md b/changelog.d/next/1693.fixed.md index c0a4d618a7..83a3879057 100644 --- a/changelog.d/next/1693.fixed.md +++ b/changelog.d/next/1693.fixed.md @@ -1 +1 @@ -Keep interrupted profile removal recoverable and prevent retries or delayed confirmations from changing a replacement identity. +Keep interrupted profile removal recoverable with the correct cleanup guidance and prevent retries or delayed confirmations from changing a replacement identity. diff --git a/journeys/profile/profile-removal-recovery.xml b/journeys/profile/profile-removal-recovery.xml index a9fa35b5bb..adcb0a4176 100644 --- a/journeys/profile/profile-removal-recovery.xml +++ b/journeys/profile/profile-removal-recovery.xml @@ -18,6 +18,7 @@ Confirm local Disconnect while credential erasure is unavailable and verify recovery remains pending without clearing consumed-payment-list safety state Restore local storage, restart after credential erasure but before local completion and open Profile Verify pending cleanup and Disconnect remain visible with no stored identity, no authenticated activation and no automatic remote mutation + Background and foreground the app, then reconnect the test device network; verify cleanup guidance remains available without an expired-session or reconnect-profile error Confirm local Disconnect and verify all required local cleanup finishes before leaving Profile In a fresh fixture, replace the sign-in before an old confirmation or completion is delivered and verify it cannot act on or navigate away from the replacement Open ordinary receive and verify address accounting remains available while profile cleanup is pending From a102e0ede565e60aaf7e033f3ad66a870739066b Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 26 Oct 2026 21:51:51 +0200 Subject: [PATCH 15/61] fix: recognize native backup request transport failures --- .../java/to/bitkit/repositories/BackupRepo.kt | 9 ++++ .../to/bitkit/repositories/BackupRepoTest.kt | 54 +++++++++++++++++++ changelog.d/next/1689.fixed.md | 2 +- 3 files changed, 64 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 8572f5da4b..018d7cf762 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -86,6 +86,7 @@ import to.bitkit.utils.AppError import to.bitkit.utils.Logger import to.bitkit.utils.NetworkValidationHelper import to.bitkit.utils.jsonLogOf +import java.net.URI import java.util.concurrent.ConcurrentHashMap import javax.inject.Inject import javax.inject.Provider @@ -1412,5 +1413,13 @@ internal fun Throwable.isTemporaryBackupFailure(): Boolean = isPaykitTemporarily is VssException.StoreException, is VssException.PutException, -> true + is VssException.UnknownException -> isVssRequestSendFailure(errorDetails) else -> false } + +private fun isVssRequestSendFailure(details: String): Boolean { + val prefix = "error sending request for url (" + if (!details.startsWith(prefix) || !details.endsWith(")")) return false + val url = runCatching { URI(details.removePrefix(prefix).dropLast(1)) }.getOrNull() ?: return false + return url.scheme in setOf("http", "https") && !url.host.isNullOrEmpty() && url.path.endsWith("/putObjects") +} diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 94b1d4d5cc..ada69920ad 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -6,6 +6,7 @@ import androidx.datastore.core.DataStoreFactory import com.synonym.bitkitcore.ActivityTags import com.synonym.bitkitcore.PreActivityMetadata import com.synonym.paykit.PaykitException +import com.synonym.vssclient.VssException import com.synonym.vssclient.VssItem import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher @@ -1253,6 +1254,59 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `released VSS connection failure is temporary without broad unknown retry`() { + assertTrue( + VssException.UnknownException("error sending request for url (http://127.0.0.1:1/putObjects)") + .isTemporaryBackupFailure(), + ) + listOf( + "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", + ).forEach { assertFalse(VssException.UnknownException(it).isTemporaryBackupFailure()) } + } + + @Test + fun `settings backup retries the released VSS connection error and acknowledges recovery`() = test { + whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(3_000)) + val category = BackupCategory.SETTINGS + val backupStatuses = MutableStateFlow(mapOf(category to BackupItemStatus(synced = 1_000, required = 2_000))) + stubBackupStatuses(backupStatuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + var attempts = 0 + whenever(vssBackupClient.putObject(eq(category.name), any())).doSuspendableAnswer { + attempts += 1 + if (attempts == 1) { + Result.failure( + VssException.UnknownException("error sending request for url (http://127.0.0.1:1/putObjects)") + ) + } else { + Result.success(VssItem(category.name, it.getArgument(1), 1)) + } + } + try { + sut.startObservingBackups() + runCurrent() + advanceTimeBy(5_000) + runCurrent() + assertEquals(1, attempts) + assertTrue(backupStatuses.value.getValue(category).isRequired) + advanceTimeBy(20_000) + runCurrent() + assertEquals(2, attempts) + assertFalse(backupStatuses.value.getValue(category).isRequired) + } finally { + sut.stopObservingBackups() + } + } + @Test fun `wallet backup retries after a busy Paykit shared state`() = test { whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(3_000)) diff --git a/changelog.d/next/1689.fixed.md b/changelog.d/next/1689.fixed.md index 3af930d512..191f325f77 100644 --- a/changelog.d/next/1689.fixed.md +++ b/changelog.d/next/1689.fixed.md @@ -1 +1 @@ -Prevent interrupted backup work from leaking across wallet reset or leaving pending backups stuck after observation restarts. +Prevent interrupted backup work from leaking across wallet reset and resume pending backups after observation restarts or temporary connection failures. From 49e9a99d35f72685f3187b9585fb2aaa3d64a904 Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 26 Oct 2026 22:55:56 +0200 Subject: [PATCH 16/61] fix: retain explicit backup retry ownership --- .../java/to/bitkit/repositories/BackupRepo.kt | 145 ++++-- .../to/bitkit/repositories/BackupRepoTest.kt | 489 +++++++++++++++++- changelog.d/next/1689.fixed.md | 2 +- 3 files changed, 588 insertions(+), 48 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 018d7cf762..b06ed2e9a4 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -164,6 +164,7 @@ class BackupRepo @Inject constructor( private var observation: Observation? = null private val retiringObservations = mutableSetOf() private val backupJobs = mutableMapOf() + private val explicitBackups = mutableSetOf() private val categoryMutexes = BackupCategory.entries.associateWith { Mutex() } private val runningBackups = ConcurrentHashMap.newKeySet() // Tracks active jobs since app start @@ -203,6 +204,7 @@ class BackupRepo @Inject constructor( vssBackupClientLdk.reset() synchronized(lifecycleLock) { backupJobs.clear() + explicitBackups.clear() failedBackupRequired.clear() temporaryFailureRetries.clear() temporaryFailureSince.clear() @@ -527,6 +529,7 @@ class BackupRepo @Inject constructor( ) { return } + if (owner == null) explicitBackups += category val existing = backupJobs[category] if (existing != null && !existing.isCompleted && !existing.isCancelled) return val expectedGeneration = generation @@ -543,7 +546,9 @@ class BackupRepo @Inject constructor( paykitSdkService.isPaymentSubmissionActive.first { !it } } val status = cacheStore.backupStatuses.first()[category] ?: BackupItemStatus() - if (status.isRequired && !shouldSkipBackup(category)) { + if (status.isRequired && !shouldSkipBackup(category) && + !failedBackupRequired.containsKey(category) + ) { performBackup(category, expectedGeneration) } } finally { @@ -553,12 +558,8 @@ class BackupRepo @Inject constructor( } finally { val currentJob = currentCoroutineContext()[Job] synchronized(lifecycleLock) { backupJobs.remove(category, currentJob) } - val nextOwner = synchronized(lifecycleLock) { - observation?.takeIf { generation == expectedGeneration && (owner == null || owner === it) } - } - if (nextOwner != null && nextOwner.scope.isActive) { - val status = cacheStore.backupStatuses.first()[category] ?: BackupItemStatus() - if (status.shouldBackup(category)) scheduleBackup(category, nextOwner) + withContext(NonCancellable) { + schedulePendingBackup(category, expectedGeneration, owner) } } }.also { backupJobs[category] = it } @@ -566,6 +567,30 @@ class BackupRepo @Inject constructor( job.start() } + private suspend fun schedulePendingBackup( + category: BackupCategory, + expectedGeneration: Long, + previousOwner: Observation? = null, + ) { + var status = BackupItemStatus() + updateBackupStatus(category, expectedGeneration) { + status = it + if (!it.isRequired) explicitBackups -= category + it + } + synchronized(lifecycleLock) { + if (resetting || generation != expectedGeneration) return + if (failedBackupRequired.containsKey(category)) return + if (!status.shouldBackup(category)) return + if (category in explicitBackups) { + scheduleBackup(category, requestedGeneration = expectedGeneration) + } else { + val owner = observation?.takeIf { previousOwner == null || previousOwner === it } ?: return + if (owner.scope.isActive) scheduleBackup(category, owner) + } + } + } + private suspend fun finishBackup(category: BackupCategory, expectedGeneration: Long) = withContext(NonCancellable) { try { updateBackupStatus(category, expectedGeneration) { it.copy(running = false) } @@ -612,34 +637,67 @@ class BackupRepo @Inject constructor( } } - suspend fun triggerBackup(category: BackupCategory): Result = withBackupOperation { expectedGeneration -> + suspend fun triggerBackup(category: BackupCategory): Result = performExplicitBackup(category) + + private suspend fun performExplicitBackup( + category: BackupCategory, + usdtSnapshot: String? = null, + ): Result = withBackupOperation { expectedGeneration -> + var reservedRequired: Long? = null + if (usdtSnapshot != null) { + withContext(NonCancellable) { + updateBackupStatus(category, expectedGeneration) { + val required = maxOf(currentTimeMillis(), it.required + 1, it.synced + 1) + reservedRequired = required + it.copy(required = required) + } + } + } categoryMutexes.getValue(category).withLock { if (synchronized(lifecycleLock) { resetting || generation != expectedGeneration }) { return@withLock Result.failure(UsdtException.BackupUnavailable()) } runningBackups += category try { - performBackup(category, expectedGeneration) + performBackup( + category, + expectedGeneration, + usdtSnapshot, + explicitAttempt = true, + reservedRequired = reservedRequired, + ) } finally { finishBackup(category, expectedGeneration) + withContext(NonCancellable) { + schedulePendingBackup(category, expectedGeneration) + } } } } - private suspend fun performBackup(category: BackupCategory, expectedGeneration: Long): Result { + private suspend fun performBackup( + category: BackupCategory, + expectedGeneration: Long, + usdtSnapshot: String? = null, + explicitAttempt: Boolean = false, + reservedRequired: Long? = null, + ): Result { Logger.debug("Backup starting for: '$category'", context = TAG) - var backupRequired = currentTimeMillis() + var backupRequired = reservedRequired ?: currentTimeMillis() updateBackupStatus(category, expectedGeneration) { - failedBackupRequired -= category - backupRequired = maxOf(backupRequired, it.required, it.synced + 1) - it.copy(running = true, required = backupRequired) + if (reservedRequired == null) { + val required = if (explicitAttempt) it.required + 1 else it.required + backupRequired = maxOf(backupRequired, required, it.synced + 1) + } + if ((failedBackupRequired[category] ?: 0) <= backupRequired) failedBackupRequired -= category + it.copy(running = true, required = maxOf(it.required, backupRequired)) } if (synchronized(lifecycleLock) { resetting || generation != expectedGeneration }) { return Result.failure(UsdtException.BackupUnavailable()) } val upload = when (category) { BackupCategory.WALLET -> uploadWalletBackup() - BackupCategory.USDT_RECOVERY -> uploadUsdtRecoveryBackup() + BackupCategory.USDT_RECOVERY -> uploadUsdtRecoveryBackup(usdtSnapshot) else -> runSuspendCatching { vssBackupClient.putObject(key = category.name, data = getBackupDataBytes(category)).getOrThrow() } @@ -648,15 +706,22 @@ class BackupRepo @Inject constructor( .onSuccess { withContext(NonCancellable) { updateBackupStatus(category, expectedGeneration) { - failedBackupRequired -= category - temporaryFailureRetries -= category - temporaryFailureSince -= category - it.copy(running = false, synced = backupRequired) + if ((failedBackupRequired[category] ?: 0) <= backupRequired) { + failedBackupRequired -= category + temporaryFailureRetries -= category + temporaryFailureSince -= category + } + if (it.required <= backupRequired) { + explicitBackups -= category + } else if (explicitAttempt) { + explicitBackups += category + } + it.copy(running = false, synced = maxOf(it.synced, backupRequired)) } } Logger.info("Backup succeeded for: '$category'", context = TAG) } - .onFailure { markBackupFailed(category, backupRequired, expectedGeneration, it) } + .onFailure { markBackupFailed(category, backupRequired, expectedGeneration, it, explicitAttempt) } .map { } } @@ -664,14 +729,8 @@ class BackupRepo @Inject constructor( uploadWalletBackup().onFailure { markBackupRequired(BackupCategory.WALLET, expectedGeneration) } } - suspend fun persistUsdtRecoveryBackup(snapshot: String): Result = withBackupOperation { expectedGeneration -> - runSuspendCatching { - updateBackupStatus(BackupCategory.USDT_RECOVERY, expectedGeneration) { - it.copy(required = maxOf(currentTimeMillis(), it.required + 1, it.synced + 1)) - } - uploadUsdtRecoveryBackup(snapshot).getOrThrow() - }.onFailure { markBackupRequired(BackupCategory.USDT_RECOVERY, expectedGeneration) } - } + suspend fun persistUsdtRecoveryBackup(snapshot: String): Result = + performExplicitBackup(BackupCategory.USDT_RECOVERY, snapshot) private suspend fun withBackupOperation( operation: suspend (Long) -> Result, @@ -733,12 +792,18 @@ class BackupRepo @Inject constructor( backupRequired: Long, expectedGeneration: Long, e: Throwable, + explicitAttempt: Boolean, ) { + val temporary = e.isTemporaryBackupFailure() withContext(NonCancellable) { updateBackupStatus(category, expectedGeneration) { + if (temporary && explicitAttempt) explicitBackups += category + if (!temporary && e !is WalletBackupSnapshotChanged && it.required == backupRequired) { + explicitBackups -= category + } if (it.required == backupRequired && e !is WalletBackupSnapshotChanged) { failedBackupRequired[category] = backupRequired - } else { + } else if ((failedBackupRequired[category] ?: 0) <= backupRequired) { failedBackupRequired -= category } it.copy(running = false) @@ -747,7 +812,7 @@ class BackupRepo @Inject constructor( when { e is WalletBackupSnapshotChanged -> Logger.debug("Deferred changing backup snapshot for: '$category'", context = TAG) - e.isTemporaryBackupFailure() -> retryAfterTemporaryFailure(category, backupRequired, expectedGeneration, e) + temporary -> retryAfterTemporaryFailure(category, backupRequired, expectedGeneration, e) else -> Logger.error("Backup failed for: '$category'", e, context = TAG) } } @@ -759,7 +824,11 @@ class BackupRepo @Inject constructor( e: Throwable, ) { val job = synchronized(lifecycleLock) { - if (resetting || generation != expectedGeneration) return + if (resetting || generation != expectedGeneration || + (failedBackupRequired[category] ?: 0) > backupRequired + ) { + return + } val attempt = temporaryFailureRetries.merge(category, 1, Int::plus) ?: 1 temporaryFailureSince.putIfAbsent(category, backupRequired) val retryDelay = (TEMPORARY_FAILURE_RETRY_DELAY * (1 shl (attempt - 1).coerceAtMost(MAX_RETRY_SHIFT))) @@ -767,14 +836,16 @@ class BackupRepo @Inject constructor( Logger.warn("Retrying backup for: '$category' in '$retryDelay'", e, context = TAG) pendingScope.launch(start = CoroutineStart.LAZY) { delay(retryDelay) - val owner = synchronized(lifecycleLock) { - if (generation != expectedGeneration || !failedBackupRequired.remove(category, backupRequired)) { + synchronized(lifecycleLock) { + if (resetting || generation != expectedGeneration) return@launch + val failed = failedBackupRequired[category] + if (failed == backupRequired) { + failedBackupRequired.remove(category, backupRequired) + } else if (failed != null || category !in explicitBackups) { return@launch } - observation - } ?: return@launch - val status = cacheStore.backupStatuses.first()[category] ?: return@launch - if (status.shouldBackup(category)) scheduleBackup(category, owner) + } + schedulePendingBackup(category, expectedGeneration) } } job.start() diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index ada69920ad..d839c91989 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -22,6 +22,7 @@ import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.test.TestScope @@ -178,6 +179,7 @@ class BackupRepoTest : BaseUnitTest() { cacheData.update(transform) } whenever(cacheStore.data).thenReturn(cacheData) + whenever(cacheStore.backupStatuses).thenReturn(cacheData.map { it.backupStatuses }) whenever(settingsStore.data).thenReturn(settingsData) whenever { settingsStore.update(any()) }.thenReturn(Unit) whenever(widgetsStore.data).thenReturn(widgetsData) @@ -988,16 +990,20 @@ class BackupRepoTest : BaseUnitTest() { whenever(privatePaykitRepo.backupSnapshot()).thenReturn( Result.failure(PaykitException.SharedStateBusy("shared_state_busy", "lock unavailable")), ) - assertTrue(sut.triggerBackup(BackupCategory.WALLET).isFailure) - sut.persistUsdtRecoveryBackup("same-signed-operation").getOrThrow() - val payload = argumentCaptor() - verify(vssBackupClient).putObject(argThat { startsWith(UsdtRecoveryBackupStore.PREFIX) }, payload.capture()) - assertEquals( - "same-signed-operation", - json.decodeFromString(payload.firstValue.decodeToString()).usdtWallet, - ) - verify(privatePaykitRepo, times(1)).backupSnapshot() - verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) + try { + assertTrue(sut.triggerBackup(BackupCategory.WALLET).isFailure) + sut.persistUsdtRecoveryBackup("same-signed-operation").getOrThrow() + val payload = argumentCaptor() + verify(vssBackupClient).putObject(argThat { startsWith(UsdtRecoveryBackupStore.PREFIX) }, payload.capture()) + assertEquals( + "same-signed-operation", + json.decodeFromString(payload.firstValue.decodeToString()).usdtWallet, + ) + verify(privatePaykitRepo, times(1)).backupSnapshot() + verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) + } finally { + sut.reset() + } } @Test @@ -1738,6 +1744,469 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `failed explicit USDT callback retries backup after observation stops without acknowledging Core`() = test { + val statuses = MutableStateFlow>(emptyMap()) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + sut.startObservingBackups() + sut.stopObservingBackups() + runCurrent() + val service = UsdtService(keychain, Provider { sut }) + whenever(usdtRepo.backupSnapshot()).thenReturn("same-signed-operation") + whenever { vssBackupClient.putObject(argThat { startsWith(UsdtRecoveryBackupStore.PREFIX) }, any()) } + .thenReturn( + Result.failure( + VssException.UnknownException("error sending request for url (http://127.0.0.1:1/putObjects)") + ) + ) + .thenReturn(Result.success(VssItem(key = "recovery", value = byteArrayOf(), version = 1))) + try { + assertTrue(runCatching { service.recoveryBackup.persist("same-signed-operation") }.isFailure) + assertEquals(0L, service.recoveryGeneration) + advanceTimeBy(15_001) + runCurrent() + assertFalse(statuses.value.getValue(BackupCategory.USDT_RECOVERY).isRequired) + assertEquals(0L, service.recoveryGeneration) + service.recoveryBackup.persist("same-signed-operation") + assertEquals(1L, service.recoveryGeneration) + val keys = argumentCaptor() + val payloads = argumentCaptor() + verify(vssBackupClient, times(3)).putObject(keys.capture(), payloads.capture()) + assertEquals(1, keys.allValues.distinct().size) + assertTrue(payloads.allValues.all { it.contentEquals(payloads.firstValue) }) + verify(privatePaykitRepo, never()).backupSnapshot() + } finally { + sut.reset() + } + } + + @Test + fun `manual backup failure retries without observation`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow>(emptyMap()) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + whenever { vssBackupClient.putObject(eq(category.name), any()) } + .thenReturn(Result.failure(VssException.NetworkException("offline"))) + .thenReturn(Result.success(VssItem(key = category.name, value = byteArrayOf(), version = 1))) + try { + assertTrue(sut.triggerBackup(category).isFailure) + advanceTimeBy(15_001) + runCurrent() + verify(vssBackupClient, times(2)).putObject(eq(category.name), any()) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + sut.reset() + } + } + + @Test + fun `reset and wipe revoke explicit retry admission before client replacement`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow>(emptyMap()) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + whenever { vssBackupClient.putObject(eq(category.name), any()) } + .thenReturn(Result.failure(VssException.NetworkException("offline"))) + .thenReturn(Result.success(VssItem(key = category.name, value = byteArrayOf(), version = 1))) + assertTrue(sut.triggerBackup(category).isFailure) + sut.setWiping(true) + sut.reset() + advanceTimeBy(20_000) + runCurrent() + verify(vssBackupClient, times(1)).putObject(eq(category.name), any()) + assertTrue(sut.triggerBackup(category).isFailure) + sut.setWiping(false) + sut.triggerBackup(category).getOrThrow() + advanceTimeBy(20_000) + runCurrent() + verify(vssBackupClient, times(2)).putObject(eq(category.name), any()) + assertFalse(statuses.value.getValue(category).isRequired) + sut.reset() + } + + @Test + fun `explicit retry retains newer required data until the successor succeeds`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow>(emptyMap()) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + var attempts = 0 + whenever { vssBackupClient.putObject(eq(category.name), any()) }.doSuspendableAnswer { + attempts += 1 + if (attempts == 1) return@doSuspendableAnswer Result.failure(VssException.NetworkException("offline")) + if (attempts == 2) { + statuses.update { data -> + val current = data.getValue(category) + data + (category to current.copy(required = current.required + 1)) + } + } + Result.success(VssItem(key = category.name, value = byteArrayOf(), version = 1)) + } + try { + assertTrue(sut.triggerBackup(category).isFailure) + advanceTimeBy(20_001) + runCurrent() + assertEquals(3, attempts) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + sut.reset() + } + } + + @Test + fun `full request survives coalescing with a cancelled observer upload`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + val entered = CompletableDeferred() + val release = CompletableDeferred() + var attempts = 0 + whenever { vssBackupClient.putObject(eq(category.name), any()) }.doSuspendableAnswer { + attempts += 1 + if (attempts == 1) { + entered.complete(Unit) + try { + awaitCancellation() + } finally { + withContext(NonCancellable) { release.await() } + } + } + Result.success(VssItem(key = category.name, value = byteArrayOf(), version = 1)) + } + sut.startObservingBackups() + advanceTimeBy(5_000) + runCurrent() + entered.await() + sut.scheduleFullBackup() + sut.stopObservingBackups() + try { + advanceTimeBy(20_000) + runCurrent() + assertEquals(1, attempts) + release.complete(Unit) + runCurrent() + advanceTimeBy(5_000) + runCurrent() + assertEquals(2, attempts) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + release.complete(Unit) + sut.reset() + } + } + + @Test + fun `permanent failure and caller cancellation do not admit explicit retry`() = test { + val statuses = MutableStateFlow>(emptyMap()) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + val entered = CompletableDeferred() + var attempts = 0 + whenever { vssBackupClient.putObject(argThat { startsWith(UsdtRecoveryBackupStore.PREFIX) }, any()) } + .doSuspendableAnswer { + attempts += 1 + if (attempts == 1) { + Result.failure(VssException.UnknownException("invalid credentials")) + } else { + entered.complete(Unit) + awaitCancellation() + } + } + assertTrue(sut.persistUsdtRecoveryBackup("signed").isFailure) + advanceTimeBy(600_000) + runCurrent() + assertEquals(1, attempts) + val caller = launch { sut.persistUsdtRecoveryBackup("signed") } + entered.await() + caller.cancelAndJoin() + advanceTimeBy(600_000) + runCurrent() + assertEquals(2, attempts) + assertTrue(statuses.value.getValue(BackupCategory.USDT_RECOVERY).isRequired) + sut.reset() + } + + @Test + fun `manual success follows a consumed change after observers stop`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000, synced = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + sut.startObservingBackups() + runCurrent() + val entered = CompletableDeferred() + val release = CompletableDeferred() + var attempts = 0 + whenever { vssBackupClient.putObject(eq(category.name), any()) }.doSuspendableAnswer { + attempts += 1 + if (attempts == 1) { + entered.complete(Unit) + release.await() + } + Result.success(VssItem(key = category.name, value = byteArrayOf(), version = 1)) + } + val manual = async { sut.triggerBackup(category) } + entered.await() + settingsData.update { it.copy(selectedCurrency = "EUR") } + runCurrent() + sut.stopObservingBackups() + try { + release.complete(Unit) + manual.await().getOrThrow() + advanceTimeBy(5_001) + runCurrent() + assertEquals(2, attempts) + assertFalse(statuses.value.getValue(category).isRequired) + val payloads = argumentCaptor() + verify(vssBackupClient, times(2)).putObject(eq(category.name), payloads.capture()) + assertTrue(payloads.secondValue.decodeToString().contains("EUR")) + } finally { + release.complete(Unit) + sut.reset() + } + } + + @Test + fun `consumed change cannot orphan a retained explicit retry timer`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000, synced = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + sut.startObservingBackups() + runCurrent() + whenever { vssBackupClient.putObject(eq(category.name), any()) } + .thenReturn(Result.failure(VssException.NetworkException("offline"))) + .thenReturn(Result.success(VssItem(key = category.name, value = byteArrayOf(), version = 1))) + assertTrue(sut.triggerBackup(category).isFailure) + val entered = CompletableDeferred() + val release = CompletableDeferred() + var holdNextWrite = true + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + if (holdNextWrite) { + holdNextWrite = false + entered.complete(Unit) + release.await() + } + statuses.update { current -> transform(AppCacheData(backupStatuses = current)).backupStatuses } + } + settingsData.update { it.copy(selectedCurrency = "EUR") } + entered.await() + sut.stopObservingBackups() + try { + release.complete(Unit) + runCurrent() + advanceTimeBy(15_001) + runCurrent() + verify(vssBackupClient, times(2)).putObject(eq(category.name), any()) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + release.complete(Unit) + sut.reset() + } + } + + @Test + fun `older retry timer cannot shorten a newer explicit failure backoff`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow>(emptyMap()) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + var attempts = 0 + whenever { vssBackupClient.putObject(eq(category.name), any()) }.doSuspendableAnswer { + attempts += 1 + if (attempts < 3) { + Result.failure(VssException.NetworkException("offline")) + } else { + Result.success(VssItem(key = category.name, value = byteArrayOf(), version = 1)) + } + } + try { + assertTrue(sut.triggerBackup(category).isFailure) + advanceTimeBy(5_000) + assertTrue(sut.triggerBackup(category).isFailure) + advanceTimeBy(15_000) + runCurrent() + assertEquals(2, attempts) + advanceTimeBy(10_001) + runCurrent() + assertEquals(3, attempts) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + sut.reset() + } + } + + @Test + fun `stale timer continuation respects a concurrent explicit failure backoff`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow>(emptyMap()) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + var attempts = 0 + whenever { vssBackupClient.putObject(eq(category.name), any()) }.doSuspendableAnswer { + attempts += 1 + if (attempts < 3) { + Result.failure(VssException.NetworkException("offline")) + } else { + Result.success(VssItem(key = category.name, value = byteArrayOf(), version = 1)) + } + } + assertTrue(sut.triggerBackup(category).isFailure) + val entered = CompletableDeferred() + val release = CompletableDeferred() + var holdNextReturn = true + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + statuses.update { current -> transform(AppCacheData(backupStatuses = current)).backupStatuses } + if (holdNextReturn) { + holdNextReturn = false + entered.complete(Unit) + release.await() + } + } + advanceTimeBy(10_000) + runCurrent() + entered.await() + try { + assertTrue(sut.triggerBackup(category).isFailure) + release.complete(Unit) + runCurrent() + advanceTimeBy(5_001) + runCurrent() + assertEquals(2, attempts) + advanceTimeBy(20_000) + runCurrent() + assertEquals(3, attempts) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + release.complete(Unit) + sut.reset() + } + } + + @Test + fun `cancelled queued USDT callback retains its required revision`() = test { + val category = BackupCategory.USDT_RECOVERY + val statuses = MutableStateFlow>(emptyMap()) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + val release = CompletableDeferred() + val uploads = mutableListOf() + val service = UsdtService(keychain, Provider { sut }) + whenever(usdtRepo.backupSnapshot()).thenReturn("older") + whenever { vssBackupClient.putObject(argThat { startsWith(UsdtRecoveryBackupStore.PREFIX) }, any()) } + .doSuspendableAnswer { + val payload = json.decodeFromString(it.getArgument(1).decodeToString()) + uploads += payload.usdtWallet + release.await() + Result.success(VssItem(key = "recovery", value = byteArrayOf(), version = 1)) + } + val older = async { sut.triggerBackup(category) } + runCurrent() + val olderRequired = statuses.value.getValue(category).required + val queued = launch { service.recoveryBackup.persist("newer") } + try { + runCurrent() + queued.cancelAndJoin() + release.complete(Unit) + older.await().getOrThrow() + runCurrent() + val status = statuses.value.getValue(category) + assertTrue(status.required > olderRequired) + assertTrue(status.isRequired) + assertEquals(0L, service.recoveryGeneration) + assertEquals(listOf("older"), uploads) + } finally { + queued.cancelAndJoin() + release.complete(Unit) + sut.reset() + } + } + + @Test + fun `queued USDT callback cannot satisfy a later cancelled revision`() = test { + val category = BackupCategory.USDT_RECOVERY + val statuses = MutableStateFlow>(emptyMap()) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + val release = CompletableDeferred() + val uploads = mutableListOf() + whenever(usdtRepo.backupSnapshot()).thenReturn("older") + whenever { vssBackupClient.putObject(argThat { startsWith(UsdtRecoveryBackupStore.PREFIX) }, any()) } + .doSuspendableAnswer { + val payload = json.decodeFromString(it.getArgument(1).decodeToString()) + uploads += payload.usdtWallet + if (payload.usdtWallet == "older") release.await() + Result.success(VssItem(key = "recovery", value = byteArrayOf(), version = 1)) + } + val older = async { sut.triggerBackup(category) } + runCurrent() + val first = async { sut.persistUsdtRecoveryBackup("first") } + runCurrent() + val second = launch { sut.persistUsdtRecoveryBackup("second") } + try { + runCurrent() + second.cancelAndJoin() + release.complete(Unit) + older.await().getOrThrow() + first.await().getOrThrow() + runCurrent() + assertTrue(statuses.value.getValue(category).isRequired) + assertEquals(listOf("older", "first"), uploads) + } finally { + second.cancelAndJoin() + release.complete(Unit) + sut.reset() + } + } + + @Test + fun `older reserved callback preserves a newer failure backoff`() = test { + val category = BackupCategory.USDT_RECOVERY + val statuses = MutableStateFlow>(emptyMap()) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + whenever(usdtRepo.backupSnapshot()).thenReturn("newer") + val uploads = mutableListOf() + whenever { vssBackupClient.putObject(argThat { startsWith(UsdtRecoveryBackupStore.PREFIX) }, any()) } + .doSuspendableAnswer { + val payload = json.decodeFromString(it.getArgument(1).decodeToString()) + uploads += payload.usdtWallet + if (uploads.size == 1) { + Result.failure(VssException.NetworkException("offline")) + } else { + Result.success(VssItem(key = "recovery", value = byteArrayOf(), version = 1)) + } + } + val entered = CompletableDeferred() + val release = CompletableDeferred() + var holdNextReturn = true + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + statuses.update { current -> transform(AppCacheData(backupStatuses = current)).backupStatuses } + if (holdNextReturn) { + holdNextReturn = false + entered.complete(Unit) + release.await() + } + } + val older = async { sut.persistUsdtRecoveryBackup("older") } + entered.await() + try { + assertTrue(sut.persistUsdtRecoveryBackup("newer").isFailure) + advanceTimeBy(5_000) + release.complete(Unit) + older.await().getOrThrow() + runCurrent() + advanceTimeBy(5_001) + runCurrent() + assertEquals(listOf("newer", "older"), uploads) + assertTrue(statuses.value.getValue(category).isRequired) + advanceTimeBy(5_000) + runCurrent() + assertEquals(listOf("newer", "older", "newer"), uploads) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + release.complete(Unit) + sut.reset() + } + } + @Test fun `USDT callback does not acknowledge reset cancellation and retries the same recovery record`() = test { val entered = CompletableDeferred() diff --git a/changelog.d/next/1689.fixed.md b/changelog.d/next/1689.fixed.md index 191f325f77..b2ac2cf3ec 100644 --- a/changelog.d/next/1689.fixed.md +++ b/changelog.d/next/1689.fixed.md @@ -1 +1 @@ -Prevent interrupted backup work from leaking across wallet reset and resume pending backups after observation restarts or temporary connection failures. +Prevent interrupted backups from crossing wallet resets and keep explicit backup retries running through temporary connection failures even when observation stops. From e6a75f0e7f5e22d7f4f5ec23d8109b6107f1c9bd Mon Sep 17 00:00:00 2001 From: benk10 Date: Thu, 29 Oct 2026 01:47:14 +0200 Subject: [PATCH 17/61] fix: preserve receipt and recovery state through cleanup --- .../profile/ProfileRecoveryContentTest.kt | 7 +- .../to/bitkit/data/ProfileRemovalStore.kt | 14 ++- .../to/bitkit/repositories/LightningRepo.kt | 14 ++- .../PrivatePaykitAddressReservationRepo.kt | 14 ++- .../PrivatePaykitContactResolver.kt | 8 +- .../java/to/bitkit/repositories/PubkyRepo.kt | 3 + .../ui/screens/profile/ProfileScreen.kt | 24 ++++-- .../ui/screens/profile/ProfileViewModel.kt | 19 ++++- .../to/bitkit/usecases/WipeWalletUseCase.kt | 4 +- app/src/main/res/values-ar/strings.xml | 1 + app/src/main/res/values-b+es+419/strings.xml | 1 + app/src/main/res/values-ca/strings.xml | 1 + app/src/main/res/values-cs/strings.xml | 1 + app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-el/strings.xml | 1 + app/src/main/res/values-es-rES/strings.xml | 1 + app/src/main/res/values-es/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-it/strings.xml | 1 + app/src/main/res/values-nl/strings.xml | 1 + app/src/main/res/values-pl/strings.xml | 1 + app/src/main/res/values-pt-rBR/strings.xml | 1 + app/src/main/res/values-pt/strings.xml | 1 + app/src/main/res/values-ru/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + .../to/bitkit/data/ProfileRemovalStoreTest.kt | 7 ++ .../bitkit/repositories/LightningRepoTest.kt | 41 +++++++++ ...PrivatePaykitAddressReservationRepoTest.kt | 35 ++++++++ .../PrivatePaykitContactResolverTest.kt | 2 + .../ActivityServicePaykitContactsTest.kt | 28 ++++++ .../screens/profile/ProfileViewModelTest.kt | 22 +++++ .../bitkit/usecases/WipeWalletUseCaseTest.kt | 85 ++++++++++++++++++- changelog.d/next/1693.fixed.md | 2 +- 33 files changed, 315 insertions(+), 30 deletions(-) diff --git a/app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt b/app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt index c6a89d8da8..d4fa93388a 100644 --- a/app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt +++ b/app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt @@ -29,7 +29,9 @@ class ProfileRecoveryContentTest { @Test fun restartRecoveryWithoutCredentialsRequiresLocalConfirmation() { - var state by mutableStateOf(ProfileUiState(recoveryPending = true, localDisconnect = true)) + var state by mutableStateOf( + ProfileUiState(recoveryPending = true, localDisconnect = true), + ) var confirmations = 0 var back = 0 compose.setContent { @@ -57,6 +59,9 @@ class ProfileRecoveryContentTest { } } } + compose.onNodeWithText(context.getString(R.string.profile__wallet_recovery_pending)).assertIsDisplayed() + compose.onNodeWithTag("ProfileRecoveryDisconnect").assertDoesNotExist() + compose.runOnIdle { state = state.copy(recoveryCanDisconnect = true) } compose.onNodeWithText(context.getString(R.string.profile__cleanup_pending)).assertIsDisplayed() compose.onNodeWithTag("ProfileRecoveryDisconnect").assertIsDisplayed().performClick() compose.onNodeWithText(context.getString(R.string.profile__disconnect_local_description)).assertIsDisplayed() diff --git a/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt b/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt index b6be5ac0c9..5559384236 100644 --- a/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt +++ b/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt @@ -70,15 +70,21 @@ class ProfileRemovalStore internal constructor(private val store: DataStore = observationRevision.flatMapLatest { - store.data.map { it.attemptId != null } + private val observedState: Flow = observationRevision.flatMapLatest { + store.data.map { it } .retryWhen { _, attempt -> - emit(true) + emit(null) delay((250L shl attempt.coerceAtMost(8).toInt()).coerceAtMost(60_000).milliseconds) true } } + internal val pending: Flow = observedState.map { it == null || it.attemptId != null } + + internal val localDisconnectAvailable: Flow = observedState.map { + it?.attemptId != null && it.scope == ProfileRemovalScope.PROFILE + } + internal suspend fun pendingAttempt(): String? = store.data.first().attemptId internal suspend fun requireNoPending() { @@ -263,7 +269,7 @@ internal object ProfileRemovalSerializer : Serializer { } internal class ProfileRemovalPending(cause: Throwable? = null) : AppError( - "Profile cleanup is pending. Disconnect the profile to finish local recovery.", + "Local recovery is pending. Open the profile for recovery options.", cause, ) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 4f25822652..9f3bf97644 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -20,7 +20,9 @@ import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async +import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow @@ -575,8 +577,16 @@ class LightningRepo @Inject constructor( settledReceiveInvoice = invalidateSettledReceiveInvoice(event) settledReceiveAddress = null val paymentId = event.paymentId ?: event.paymentHash - runSuspendCatching { coreService.activity.handlePaymentEvent(paymentId) } - .onFailure { Logger.error("Failed to record received payment '$paymentId'", it, context = TAG) } + runCatching { coreService.activity.handlePaymentEvent(paymentId) } + .onFailure { + if (it is CancellationException) { + // Receipt admission can be revoked without cancelling the node listener. + currentCoroutineContext().ensureActive() + Logger.debug("Receipt admission ended for '$paymentId'", context = TAG) + } else { + Logger.error("Failed to record received payment '$paymentId'", it, context = TAG) + } + } } is Event.OnchainTransactionReceived -> { diff --git a/app/src/main/java/to/bitkit/repositories/PrivatePaykitAddressReservationRepo.kt b/app/src/main/java/to/bitkit/repositories/PrivatePaykitAddressReservationRepo.kt index 5ce29fdcbe..4ab5a410e7 100644 --- a/app/src/main/java/to/bitkit/repositories/PrivatePaykitAddressReservationRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PrivatePaykitAddressReservationRepo.kt @@ -272,8 +272,9 @@ class PrivatePaykitAddressReservationRepo @Inject constructor( suspend fun clear() = withContext(ioDispatcher) { locked { - ledger = PrivatePaykitReservationData() + ledger = null reservationStore.reset() + ledger = PrivatePaykitReservationData() notifyBackupStateChanged() } } @@ -303,10 +304,15 @@ class PrivatePaykitAddressReservationRepo @Inject constructor( contactAssignments = current.contactAssignments + (assignmentKey to assignment), contactAssignmentHistory = current.contactAssignmentHistory + (assignmentKey to history), ) - ledger = next - persist(next) + // A cancelled return can follow a committed write. Reload durable state on uncertainty. + ledger = null + try { + persist(next) + ledger = next + } finally { + notifyBackupStateChanged() + } } - notifyBackupStateChanged() addressInfo.address } } diff --git a/app/src/main/java/to/bitkit/repositories/PrivatePaykitContactResolver.kt b/app/src/main/java/to/bitkit/repositories/PrivatePaykitContactResolver.kt index 1296eea026..5cfe7dc6b5 100644 --- a/app/src/main/java/to/bitkit/repositories/PrivatePaykitContactResolver.kt +++ b/app/src/main/java/to/bitkit/repositories/PrivatePaykitContactResolver.kt @@ -112,9 +112,13 @@ class PrivatePaykitContactResolver @Inject constructor( suspend fun isReservedReceiveAddress(address: String): Boolean { requireCurrent() - val source = snapshot ?: return false return lookupAssociations { - addressReservationRepo.get().contactsForReceipt(address, source.assignments).isNotEmpty() + val source = snapshot + if (source == null) { + addressReservationRepo.get().isUnavailableForReusableReceive(address) + } else { + addressReservationRepo.get().contactsForReceipt(address, source.assignments).isNotEmpty() + } } ?: false } } diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index df60438c9b..2e8c5112ed 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -272,6 +272,9 @@ class PubkyRepo @Inject constructor( .map { it } .stateIn(scope, SharingStarted.Eagerly, null) + val profileRecoveryCanDisconnect: StateFlow = profileRemovalStore.localDisconnectAvailable + .stateIn(scope, SharingStarted.Eagerly, false) + suspend fun requiresProfileRecovery(): Boolean = withContext(ioDispatcher) { runSuspendCatching { profileRemovalStore.requireNoPending() }.isFailure } diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt index 221769a74c..6acbdbe1f0 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt @@ -145,14 +145,24 @@ internal fun ProfileContent( uiState.recoveryPending -> ScreenColumn { topBar(Modifier) VerticalSpacer(32.dp) - BodyM(text = stringResource(R.string.profile__cleanup_pending)) - VerticalSpacer(24.dp) - PrimaryButton( - text = stringResource(R.string.profile__sign_out), - onClick = onClickSignOut, - enabled = !uiState.isSigningOut, - modifier = Modifier.testTag("ProfileRecoveryDisconnect"), + BodyM( + text = stringResource( + if (uiState.recoveryCanDisconnect) { + R.string.profile__cleanup_pending + } else { + R.string.profile__wallet_recovery_pending + }, + ), ) + if (uiState.recoveryCanDisconnect) { + VerticalSpacer(24.dp) + PrimaryButton( + text = stringResource(R.string.profile__sign_out), + onClick = onClickSignOut, + enabled = !uiState.isSigningOut, + modifier = Modifier.testTag("ProfileRecoveryDisconnect"), + ) + } if (uiState.isSigningOut) GradientCircularProgressIndicator(Modifier.size(32.dp)) } diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt index f8465e7044..30d265ae4e 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt @@ -83,9 +83,13 @@ class ProfileViewModel @Inject constructor( ) } - private val controls = combine(dialogControls, pubkyRepo.profileRecoveryPending, _localDisconnect) { - controls, pending, localOnly -> - controls.copy(recoveryPending = pending, localDisconnect = localOnly) + private val controls = combine( + dialogControls, + pubkyRepo.profileRecoveryPending, + _localDisconnect, + pubkyRepo.profileRecoveryCanDisconnect, + ) { controls, pending, localOnly, canDisconnect -> + controls.copy(recoveryPending = pending, localDisconnect = localOnly, recoveryCanDisconnect = canDisconnect) } init { @@ -108,7 +112,10 @@ class ProfileViewModel @Inject constructor( publicKey = pubkyRepo.publicKey.value, isLoading = pubkyRepo.isLoadingProfile.value || pubkyRepo.isRestoringSession.value || _isRefreshing.value, cachedProfile = pubkyRepo.cachedProfile.value, - controls = ProfileControls(recoveryPending = pubkyRepo.profileRecoveryPending.value), + controls = ProfileControls( + recoveryPending = pubkyRepo.profileRecoveryPending.value, + recoveryCanDisconnect = pubkyRepo.profileRecoveryCanDisconnect.value, + ), ), ) @@ -148,6 +155,7 @@ class ProfileViewModel @Inject constructor( fun showSignOutConfirmation() { if (_isSigningOut.value) return val state = uiState.value + if (state.recoveryPending && !state.recoveryCanDisconnect) return val owner = if (state.recoveryPending) { pubkyRepo.profileOwner().takeIf { it.signIn == null } ?: state.owner } else { @@ -274,6 +282,7 @@ class ProfileViewModel @Inject constructor( publicKey == pubkyRepo.profile.value?.publicKey, isLoading = controls.recoveryPending == null || (controls.recoveryPending == false && isLoading), recoveryPending = controls.recoveryPending == true, + recoveryCanDisconnect = controls.recoveryCanDisconnect, localDisconnect = controls.localDisconnect, owner = displayedOwner, showSignOutDialog = controls.showSignOutDialog, @@ -325,6 +334,7 @@ data class ProfileUiState( val publicKey: String? = null, val canEdit: Boolean = false, val recoveryPending: Boolean = false, + val recoveryCanDisconnect: Boolean = false, val localDisconnect: Boolean = false, val owner: PubkyProfileOwner? = null, val isLoading: Boolean = true, @@ -336,6 +346,7 @@ data class ProfileUiState( private data class ProfileControls( val recoveryPending: Boolean? = null, + val recoveryCanDisconnect: Boolean = false, val localDisconnect: Boolean = false, val showSignOutDialog: Boolean = false, val isSigningOut: Boolean = false, diff --git a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt index ccddeaf39a..94288b9cd1 100644 --- a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt @@ -78,9 +78,9 @@ class WipeWalletUseCase @Inject constructor( val pending = profileRemovalStore.pendingAttempt() val attemptId = pending ?: UUID.randomUUID().toString() profileRemovalStore.withAccess(attemptId, ProfileRemovalScope.WALLET_WIPE) { - profileRemovalStore.begin(attemptId) privatePaykitRepo.get().withProfileDeletionPaused { pause -> stopNode().getOrThrow() + profileRemovalStore.begin(attemptId) if (pending == null) cleanupRemote() wipeLocal(walletIndex, pause) { credentialsMayBeErased = true }.getOrThrow() profileRemovalStore.complete(attemptId) @@ -130,9 +130,9 @@ class WipeWalletUseCase @Inject constructor( usdtRepo.wipe { keychain.wipe() }.getOrThrow() paykitUsdtPaymentRepo.resetForWipe() // Consumption watermarks survive until the keychain wipe is acknowledged. Pending remains on any failure. + privatePaykitAddressReservationRepo.clear() privatePaykitRepo.get().finishProfileRemoval(pause).getOrElse { return Result.failure(it) } pubkyRepo.finishProfileWipeLocally() - privatePaykitAddressReservationRepo.clear() step("delete FCM token") { firebaseMessaging.deleteToken() } step("wipe core data") { coreService.wipeData() } step("clear database") { db.clearAllTables() } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index ad4ec1fd94..25f36a5483 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1346,6 +1346,7 @@ تعذر إلغاء ربط الـ pubky إلغاء ربط الـ pubky تم إلغاء ربط الـ pubky + يجب إكمال استرداد المحفظة قبل فصل هذا الملف الشخصي. راجع استرداد المحفظة في الإعدادات. اسمك Pubky الخاص بك تم تسجيل الدخول بالفعل diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 9f367761fc..40e2af3b6d 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1363,6 +1363,7 @@ Esto desconectará su perfil de Pubky de Bitkit. Puede volver a conectarlo en cualquier momento. Desconectar perfil Este pubky ya no está disponible en Pubky Ring. Su perfil se desconectó. + Debes completar la recuperación de la billetera antes de desconectar este perfil. Revisa la recuperación de la billetera en Ajustes. Su pubky Ya inició sesión Homeserver diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index ce4e50acad..0c92cca295 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1360,6 +1360,7 @@ Desconnectar el perfil Aquest pubky ja no està disponible a Pubky Ring. El teu perfil s\'ha desconnectat. Suggeriments per afegir + Cal completar la recuperació de la cartera abans de desconnectar aquest perfil. Consulta la recuperació de la cartera a Configuració. El teu pubky Ja has iniciat sessió Homeserver diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index eee8f6760e..ae9806b4a6 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1362,6 +1362,7 @@ Odpojit profil Tento pubky již není v Pubky Ring k dispozici. Váš profil byl odpojen. Návrhy k přidání + Před odpojením tohoto profilu je nutné dokončit obnovu peněženky. Zkontrolujte obnovu peněženky v Nastavení. Váš pubky Již přihlášeno Homeserver diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index da2ec2662b..8e07554337 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1360,6 +1360,7 @@ Profil trennen Dieser pubky ist in Pubky Ring nicht mehr verfügbar. Dein Profil wurde getrennt. Vorschläge zum Hinzufügen + Bevor dieses Profil getrennt werden kann, muss die Wallet-Wiederherstellung abgeschlossen werden. Prüfe die Wallet-Wiederherstellung in den Einstellungen. Dein Pubky Bereits angemeldet Homeserver diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 8ebbdf1936..e8711e517e 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1352,6 +1352,7 @@ Αδυναμία αποσύνδεσης pubky Αποσύνδεση pubky Το pubky αποσυνδέθηκε + Πρέπει να ολοκληρωθεί η ανάκτηση του πορτοφολιού πριν αποσυνδεθεί αυτό το προφίλ. Ελέγξτε την ανάκτηση πορτοφολιού στις Ρυθμίσεις. Το όνομά σου Το pubky σου Είσαι ήδη συνδεδεμένος diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 5cff213254..e19dbf5288 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1357,6 +1357,7 @@ Esto desconectará tu perfil de Pubky de Bitkit. Puedes volver a conectarlo en cualquier momento. Desconectar perfil Este pubky ya no está disponible en Pubky Ring. Tu perfil se ha desconectado. + Debes completar la recuperación de la cartera antes de desconectar este perfil. Revisa la recuperación de la cartera en Ajustes. Tu pubky Ya has iniciado sesión Servidor principal diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 8ded52f6a1..24337bc3e9 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1356,6 +1356,7 @@ Esto desconectará su perfil de Pubky de Bitkit. Puede volver a conectarlo en cualquier momento. Desconectar perfil Este pubky ya no está disponible en Pubky Ring. Su perfil se ha desconectado. + Debes completar la recuperación de la cartera antes de desconectar este perfil. Revisa la recuperación de la cartera en Ajustes. Su pubky Ya ha iniciado sesión Servidor principal diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 7c049eb669..85594b0ed5 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1358,6 +1358,7 @@ Déconnecter le profil Ce pubky n\'est plus disponible dans Pubky Ring. Votre profil a été déconnecté. Suggestions + La récupération du portefeuille doit être terminée avant de déconnecter ce profil. Consultez la récupération du portefeuille dans les Paramètres. Votre pubky Déjà connecté Serveur domestique diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 939c892ca8..4c0d1b0feb 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1362,6 +1362,7 @@ Questo disconnetterà il tuo profilo Pubky da Bitkit. Puoi ricollegarlo in qualsiasi momento. Disconnetti Profilo Questo pubky non è più disponibile in Pubky Ring. Il tuo profilo è stato disconnesso. + Devi completare il recupero del portafoglio prima di disconnettere questo profilo. Controlla il recupero del portafoglio nelle Impostazioni. Il Tuo Pubky Accesso già effettuato Homeserver diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 531f52463d..34bb1135f6 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1359,6 +1359,7 @@ Hiermee wordt uw Pubky-profiel ontkoppeld van Bitkit. U kunt op elk moment opnieuw verbinden. Profiel ontkoppelen Deze pubky is niet meer beschikbaar in Pubky Ring. Uw profiel is ontkoppeld. + Het wallet-herstel moet worden voltooid voordat dit profiel kan worden losgekoppeld. Controleer het wallet-herstel in Instellingen. Uw pubky Al ingelogd Homeserver diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 2ecd17de7c..c70056576e 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1360,6 +1360,7 @@ Spowoduje to odłączenie Twojego profilu Pubky od Bitkit. Możesz połączyć się ponownie w dowolnym momencie. Odłącz profil Ten pubky nie jest już dostępny w Pubky Ring. Twój profil został odłączony. + Przed odłączeniem tego profilu należy ukończyć odzyskiwanie portfela. Sprawdź odzyskiwanie portfela w Ustawieniach. Twój pubky Już zalogowano Serwer domowy diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 033ba77f40..454adcf5be 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1362,6 +1362,7 @@ Isso desconectará seu perfil Pubky da Bitkit. Você pode reconectar a qualquer momento. Desconectar Perfil Esta pubky não está mais disponível no Pubky Ring. Seu perfil foi desconectado. + É necessário concluir a recuperação da carteira antes de desconectar este perfil. Confira a recuperação da carteira nas Configurações. Sua Pubky Já conectado Homeserver diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 4862c52a57..6ffa9bb206 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1345,6 +1345,7 @@ Não foi possível desassociar o pubky Desassociar pubky Pubky desassociado + É necessário concluir a recuperação da carteira antes de desligar este perfil. Consulte a recuperação da carteira nas Definições. O seu nome O seu pubky Sessão já iniciada diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index c1b2d97454..838c3fd7dd 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1377,6 +1377,7 @@ Ваш профиль Pubky будет отключён от Bitkit. Вы можете переподключиться в любое время. Отключить Профиль Этот pubky больше не доступен в Pubky Ring. Ваш профиль отключён. + Перед отключением этого профиля необходимо завершить восстановление кошелька. Проверьте восстановление кошелька в Настройках. Ваш Pubky Вход уже выполнен Домашний сервер diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0011b8f913..c158c2e516 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -682,6 +682,7 @@ Unable to Unlink Pubky Unlink pubky Pubky unlinked + Wallet recovery is required before this profile can be disconnected. Check wallet recovery in Settings. Your Name Your Pubky Already signed in diff --git a/app/src/test/java/to/bitkit/data/ProfileRemovalStoreTest.kt b/app/src/test/java/to/bitkit/data/ProfileRemovalStoreTest.kt index f2c5b307e4..b38f32c97b 100644 --- a/app/src/test/java/to/bitkit/data/ProfileRemovalStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/ProfileRemovalStoreTest.kt @@ -13,6 +13,7 @@ import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.emitAll +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher @@ -44,9 +45,11 @@ class ProfileRemovalStoreTest { val id = UUID.randomUUID().toString() store.withAccess(id) { store.begin(id) + assertTrue(store.localDisconnectAvailable.first()) assertEquals("historical receipt", store.withReceiptSnapshot { "historical receipt" }) } store.withAccess(id, ProfileRemovalScope.WALLET_WIPE) { store.begin(id) } + assertFalse(store.localDisconnectAvailable.first()) assertFailsWith { store.withReceiptSnapshot { error("must not copy") } } assertFailsWith { store.withAccess(id) { store.complete(id) } } assertEquals(id, store.pendingAttempt()) @@ -129,7 +132,9 @@ class ProfileRemovalStoreTest { transform(state.value).also { state.value = it } }) assertFailsWith { store.withReceiptSnapshot { error("legacy state") } } + assertFalse(store.localDisconnectAvailable.first()) unavailable = true + assertFalse(store.localDisconnectAvailable.first()) assertTrue( assertFailsWith { store.withReceiptSnapshot { error("unavailable state") } @@ -275,6 +280,8 @@ class ProfileRemovalStoreTest { ) { file } ) assertEquals(recovered, second.pendingAttempt()) + assertFalse(second.localDisconnectAvailable.first()) + assertFailsWith { second.requireReceiptAccountingAccess() } assertFailsWith { second.withAccess(recovered) { second.complete(recovered) } } second.withAccess(recovered, ProfileRemovalScope.WALLET_WIPE) { second.begin(recovered) diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 9e6b882d37..bd6322ff1f 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -410,6 +410,47 @@ class LightningRepoTest : BaseUnitTest() { ) } + @Test + fun `receipt admission cancellation preserves the active listener event dispatch`() = test { + val activityService = mock() + whenever(coreService.activity).thenReturn(activityService) + whenever(activityService.handlePaymentEvent("payment-id")).doSuspendableAnswer { + throw CancellationException("Receipt admission refused") + } + val eventHandler = startNodeAndCaptureEvents() + val publishedUpdate = async { sut.nodeEventUpdates.first() } + val event = Event.PaymentReceived("payment-id", "010203", 1_000uL, emptyList()) + + val outcome = runCatching { eventHandler(event) } + + try { + assertTrue(outcome.isSuccess) + assertEquals(event, publishedUpdate.await().event) + } finally { + publishedUpdate.cancel() + } + } + + @Test + fun `cancelling the listener still propagates through received payment admission`() = test { + val entered = CompletableDeferred() + val activityService = mock() + whenever(coreService.activity).thenReturn(activityService) + whenever(activityService.handlePaymentEvent("payment-id")).doSuspendableAnswer { + entered.complete(Unit) + awaitCancellation() + } + val eventHandler = startNodeAndCaptureEvents() + var returned = false + val handling = launch { + eventHandler(Event.PaymentReceived("payment-id", "010203", 1_000uL, emptyList())) + returned = true + } + entered.await() + handling.cancelAndJoin() + assertFalse(returned) + } + @Test fun `PaymentReceived preserves a cached invoice with a different payment hash`() = test { val bolt11 = "lnbc1" diff --git a/app/src/test/java/to/bitkit/repositories/PrivatePaykitAddressReservationRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PrivatePaykitAddressReservationRepoTest.kt index c484fbf6a3..934f187205 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitAddressReservationRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitAddressReservationRepoTest.kt @@ -1,6 +1,7 @@ package to.bitkit.repositories import com.synonym.bitkitcore.AddressType +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async @@ -25,6 +26,7 @@ import to.bitkit.models.NodeLifecycleState import to.bitkit.services.AddressDerivationInfo import to.bitkit.services.CoreService import to.bitkit.test.BaseUnitTest +import java.io.IOException import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse @@ -68,6 +70,39 @@ class PrivatePaykitAddressReservationRepoTest : BaseUnitTest() { ) } + @Test + fun `failed reservation persistence cannot expose the unacknowledged address on retry`() = test { + whenever(lightningRepo.newAddressInfoForType(AddressType.P2WPKH)).thenReturn( + Result.success(AddressDerivationInfo(address = PRIVATE_ADDRESS, index = 1)), + ) + whenever(reservationStore.update(any())).doSuspendableAnswer { throw IOException("Reservation write refused") } + whenever(coreService.isAddressUsed(PRIVATE_ADDRESS)).thenReturn(false) + whenever(lightningRepo.getAddressBalance(PRIVATE_ADDRESS)).thenReturn(Result.success(0u)) + + assertTrue(sut.currentOrRotatedAddress(CONTACT_KEY).exceptionOrNull() is IOException) + assertTrue(sut.currentOrRotatedAddress(CONTACT_KEY).isFailure) + assertTrue(reservationData.value.contactAssignments.isEmpty()) + } + + @Test + fun `lost reservation write acknowledgement reloads committed state without allocating again`() = test { + whenever(lightningRepo.newAddressInfoForType(AddressType.P2WPKH)).thenReturn( + Result.success(AddressDerivationInfo(address = PRIVATE_ADDRESS, index = 1)), + ) + whenever(coreService.isAddressUsed(PRIVATE_ADDRESS)).thenReturn(false) + whenever(lightningRepo.getAddressBalance(PRIVATE_ADDRESS)).thenReturn(Result.success(0u)) + whenever(reservationStore.update(any())).doSuspendableAnswer { + val transform = it.getArgument<(PrivatePaykitReservationData) -> PrivatePaykitReservationData>(0) + reservationData.value = transform(reservationData.value) + throw CancellationException("Committed write lost its acknowledgement") + } + assertFailsWith { sut.currentOrRotatedAddress(CONTACT_KEY) } + assertEquals(PRIVATE_ADDRESS, sut.currentOrRotatedAddress(CONTACT_KEY).getOrThrow()) + assertEquals(mapOf("nativeSegwit" to 1), sut.backupSnapshot().getOrThrow()) + assertTrue(sut.backupStateVersion.value > 0) + verify(lightningRepo).newAddressInfoForType(AddressType.P2WPKH) + } + @OptIn(ExperimentalCoroutinesApi::class) @Test fun `contact cleanup rechecks snapshot after ledger load and lock handoff`() = test { diff --git a/app/src/test/java/to/bitkit/repositories/PrivatePaykitContactResolverTest.kt b/app/src/test/java/to/bitkit/repositories/PrivatePaykitContactResolverTest.kt index 637682c5a0..3dc1631e5e 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitContactResolverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitContactResolverTest.kt @@ -139,9 +139,11 @@ class PrivatePaykitContactResolverTest : BaseUnitTest() { val storageScope = CoroutineScope(SupervisorJob() + testDispatcher) val storage = DataStoreFactory.create(PrivatePaykitCacheSerializer, scope = storageScope) { file } whenever(cacheStore.data).thenReturn(storage.data) + whenever(addressReservationRepo.isUnavailableForReusableReceive(PRIVATE_ADDRESS)).thenReturn(true) sut.withReceiptOperation { assertNull(it.snapshot) assertNull(it.contactForInvoice(PAYMENT_HASH)) + assertTrue(it.isReservedReceiveAddress(PRIVATE_ADDRESS)) } assertFailsWith { storage.updateData { it.copy(cleanupPending = true) } } requireNotNull(storageScope.coroutineContext[Job]).cancelAndJoin() diff --git a/app/src/test/java/to/bitkit/services/ActivityServicePaykitContactsTest.kt b/app/src/test/java/to/bitkit/services/ActivityServicePaykitContactsTest.kt index 40d7e4e521..076cb9a173 100644 --- a/app/src/test/java/to/bitkit/services/ActivityServicePaykitContactsTest.kt +++ b/app/src/test/java/to/bitkit/services/ActivityServicePaykitContactsTest.kt @@ -490,6 +490,34 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { assertEquals(2, activityReads) } + @Test + fun `unavailable invoice attribution still records a high reserved receiving address`() = coreTest { + val address = "bcrt1qterdweva9vextackckt6pjy0mmuc54g87g6lsq" + val store = mock() + whenever(store.data).thenReturn( + flowOf( + PrivatePaykitReservationData(reservedReceiveIndexesByAddressType = mapOf("nativeSegwit" to setOf(9000))) + ), + ) + val derivation = mock() + whenever(derivation.addressInfoForType(addressType = AddressType.P2WPKH, receiveIndex = 9000)).thenReturn( + Result.success(AddressDerivationInfo(address, 9000)), + ) + receiptReservations = PrivatePaykitAddressReservationRepo( + testDispatcher, store, settingsStore, coreService, derivation, + ) + whenever(privateCacheStore.data).thenReturn(flowOf(PrivatePaykitCacheData(receiptSourceReadable = false))) + whenever(lightningService.addressInfosForType(any(), any(), any(), any(), any())).thenReturn(emptyList()) + + receive(address) + + val row = (updates.single() as Activity.Onchain).v1 + assertEquals(address, row.address) + assertEquals(15_000uL, row.value) + assertNull(row.contact) + assertFalse(sut.backfillPaykitContacts()) + } + @Test fun `held incoming search uses its captured high index reservation after profile cleanup`() = coreTest { val address = "bcrt1qterdweva9vextackckt6pjy0mmuc54g87g6lsq" diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt index e90fbd80a9..939eeef1ab 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt @@ -408,6 +408,26 @@ class ProfileViewModelTest : BaseUnitTest() { } } + @Test + fun `unknown wallet recovery cannot prepare profile disconnect`() = test { + val sut = createSut( + publicKey = null, + recoveryPending = MutableStateFlow(true), + recoveryCanDisconnect = MutableStateFlow(false), + ) + sut.uiState.test { + advanceUntilIdle() + assertTrue(sut.uiState.value.recoveryPending) + assertFalse(sut.uiState.value.recoveryCanDisconnect) + sut.showSignOutConfirmation() + advanceUntilIdle() + assertFalse(sut.uiState.value.showSignOutDialog) + assertFalse(sut.uiState.value.isSigningOut) + cancelAndIgnoreRemainingEvents() + } + verify(pubkyRepo, never()).signOutForProfileRemoval() + } + @Test fun `pending restart without credentials shows local recovery without authentication`() = test { val pending = MutableStateFlow(null) @@ -624,6 +644,7 @@ class ProfileViewModelTest : BaseUnitTest() { private fun createSut( profile: PubkyProfile? = null, recoveryPending: MutableStateFlow = MutableStateFlow(false), + recoveryCanDisconnect: MutableStateFlow = MutableStateFlow(true), profileFlow: MutableStateFlow = MutableStateFlow(profile), readOnlyProfileFlow: MutableStateFlow = MutableStateFlow(null), publicKey: String? = "pubkyalice", @@ -638,6 +659,7 @@ class ProfileViewModelTest : BaseUnitTest() { whenever(context.getString(any())).thenReturn("") fixture.setup() whenever(pubkyRepo.profileRecoveryPending).thenReturn(recoveryPending) + whenever(pubkyRepo.profileRecoveryCanDisconnect).thenReturn(recoveryCanDisconnect) whenever(pubkyRepo.profile).thenReturn(profileFlow) whenever(pubkyRepo.readOnlyProfile).thenReturn(readOnlyProfileFlow) whenever(pubkyRepo.publicKey).thenReturn(publicKeyFlow) diff --git a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt index ba6965f388..402e6107b5 100644 --- a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt @@ -1,6 +1,8 @@ package to.bitkit.usecases +import androidx.datastore.core.DataStoreFactory import com.google.firebase.messaging.FirebaseMessaging +import com.synonym.bitkitcore.AddressType import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -8,6 +10,7 @@ import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent @@ -15,7 +18,9 @@ import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout import org.junit.Before +import org.junit.Rule import org.junit.Test +import org.junit.rules.TemporaryFolder import org.mockito.kotlin.any import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.inOrder @@ -26,6 +31,9 @@ import org.mockito.kotlin.whenever import to.bitkit.async.ServiceQueue import to.bitkit.data.AppDb import to.bitkit.data.CacheStore +import to.bitkit.data.PrivatePaykitReservationData +import to.bitkit.data.PrivatePaykitReservationSerializer +import to.bitkit.data.PrivatePaykitReservationStore import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.PubkyImageCacheEpoch import to.bitkit.data.PubkyStore @@ -49,6 +57,7 @@ import to.bitkit.repositories.PrivatePaykitRepo import to.bitkit.repositories.PubkyRepo import to.bitkit.repositories.UsdtRepo import to.bitkit.repositories.WatchOnlyAccountRepo +import to.bitkit.services.AddressDerivationInfo import to.bitkit.services.CoreService import to.bitkit.services.MigrationService import to.bitkit.services.PaykitSdkService @@ -69,6 +78,8 @@ import kotlin.time.ExperimentalTime @OptIn(ExperimentalCoroutinesApi::class, ExperimentalTime::class) class WipeWalletUseCaseTest : BaseUnitTest() { + @get:Rule + val folder = TemporaryFolder() private val backupRepo = mock() private val keychain = mock() @@ -140,6 +151,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { private fun createSut( pubkyRepo: PubkyRepo = this.pubkyRepo, sharingRepo: ContactPaymentSettingsRepo = contactPaymentSettingsRepo, + reservations: PrivatePaykitAddressReservationRepo = privatePaykitAddressReservationRepo, ) = WipeWalletUseCase( backupRepo = backupRepo, keychain = keychain, @@ -157,7 +169,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { lightningRepo = lightningRepo, pubkyRepo = pubkyRepo, privatePaykitRepo = privatePaykitRepoProvider, - privatePaykitAddressReservationRepo = privatePaykitAddressReservationRepo, + privatePaykitAddressReservationRepo = reservations, firebaseMessaging = firebaseMessaging, migrationService = migrationService, paykitSdkService = paykitSdkService, @@ -310,6 +322,46 @@ class WipeWalletUseCaseTest : BaseUnitTest() { verify(keychain).wipe() } + @Test + fun `wipe replaces unreadable reservations after key acknowledgement before profile cleanup`() = test { + val file = folder.newFile("reservations").also { it.writeText("{broken") } + val storage = DataStoreFactory.create(PrivatePaykitReservationSerializer, scope = backgroundScope) { file } + val store = mock() + whenever(store.data).thenReturn(storage.data) + whenever(store.update(any())).doSuspendableAnswer { + val transform = it.getArgument<(PrivatePaykitReservationData) -> PrivatePaykitReservationData>(0) + storage.updateData { current -> transform(current) } + Unit + } + whenever(store.reset()).doSuspendableAnswer { + verify(keychain).wipe() + storage.updateData { PrivatePaykitReservationData() } + Unit + } + whenever(settingsStore.data).thenReturn(MutableStateFlow(SettingsData())) + val reservations = PrivatePaykitAddressReservationRepo( + testDispatcher, + store, + settingsStore, + coreService, + lightningRepo, + ) + val contact = "pubky3rsduhcxpw74snwyct86m38c63j3pq8x4ycqikxg64roik8yw5xg" + whenever(lightningRepo.newAddressInfoForType(AddressType.P2WPKH)).thenReturn( + Result.success(AddressDerivationInfo("bcrt1qterdweva9vextackckt6pjy0mmuc54g87g6lsq", 1)), + ) + assertTrue(reservations.currentOrRotatedAddress(contact).isFailure) + assertFalse(storage.data.first().receiptSourceReadable) + whenever(privatePaykitRepo.finishProfileRemoval(any())).doSuspendableAnswer { + assertTrue(storage.data.first().receiptSourceReadable) + reservations.clearContactAssignments(emptySet()) + Result.success(Unit) + } + assertTrue(createSut(reservations = reservations).invoke(resetWalletState = {}, onSuccess = {}).isSuccess) + assertEquals(PrivatePaykitReservationData(), storage.data.first()) + assertNull(profileRemovalStore.pendingAttempt()) + } + @Test fun `pending restart wipe skips remote cleanup and only clears marker after local acknowledgement`() = test { val id = UUID.randomUUID().toString() @@ -358,7 +410,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { assertEquals(failure.message, assertIs(result.exceptionOrNull()).cause?.message) verify(keychain).wipe() verify(privatePaykitRepo).finishProfileRemoval(profilePause) - verify(privatePaykitAddressReservationRepo, never()).clear() + verify(privatePaykitAddressReservationRepo).clear() assertNotNull(profileRemovalStore.pendingAttempt()) assertFalse(onWipeCalled) assertFalse(onSetWalletExistsStateCalled) @@ -423,9 +475,9 @@ class WipeWalletUseCaseTest : BaseUnitTest() { inOrder.verify(usdtRepo).wipe(any()) inOrder.verify(keychain).wipe() inOrder.verify(paykitUsdtPaymentRepo).resetForWipe() + inOrder.verify(privatePaykitAddressReservationRepo).clear() inOrder.verify(privatePaykitRepo).finishProfileRemoval(profilePause) inOrder.verify(pubkyRepo).finishProfileWipeLocally() - inOrder.verify(privatePaykitAddressReservationRepo).clear() inOrder.verify(coreService).wipeData() inOrder.verify(db).clearAllTables() inOrder.verify(settingsStore).reset() @@ -480,10 +532,36 @@ class WipeWalletUseCaseTest : BaseUnitTest() { verify(lightningRepo, never()).wipeStorage(any()) verify(keychain, never()).wipe() verify(db, never()).clearAllTables() + assertNull(profileRemovalStore.pendingAttempt()) assertFalse(onWipeCalled) assertFalse(onSetWalletExistsStateCalled) } + @Test + fun `cancellation while stopping preserves prior recovery scope without arming a fresh wipe`() = test { + for (pending in listOf(null, UUID.randomUUID().toString())) { + if (pending != null) profileRemovalStore.withAccess(pending) { profileRemovalStore.begin(pending) } + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever(lightningRepo.stop()).doSuspendableAnswer { + entered.complete(Unit) + release.await() + Result.failure(CancellationException("Node stop cancelled")) + } + val wiping = launch { sut.invoke(resetWalletState = {}, onSuccess = {}) } + entered.await() + wiping.cancel() + release.complete(Unit) + wiping.join() + assertEquals(pending, profileRemovalStore.pendingAttempt()) + // A failed pre-stop wipe must not upgrade an existing PROFILE obligation. + if (pending != null) profileRemovalStore.withAccess(pending) { profileRemovalStore.complete(pending) } + connectionRecovery.withReceiptOperation { it.requireCurrent() } + } + verify(keychain, never()).wipe() + verify(lightningRepo, never()).wipeStorage(any()) + } + @Test fun `invoke retains pending recovery when address reservation clear fails`() = runTest { whenever { privatePaykitAddressReservationRepo.clear() }.thenThrow(RuntimeException("clear failed")) @@ -517,6 +595,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { verify(settingsStore, never()).reset() assertFalse(onWipeCalled) verify(privatePaykitRepo, never()).finishProfileRemoval(any()) + verify(privatePaykitAddressReservationRepo, never()).clear() assertNotNull(profileRemovalStore.pendingAttempt()) assertFalse(onSetWalletExistsStateCalled) } diff --git a/changelog.d/next/1693.fixed.md b/changelog.d/next/1693.fixed.md index 8648293a8c..3c8ab81c1c 100644 --- a/changelog.d/next/1693.fixed.md +++ b/changelog.d/next/1693.fixed.md @@ -1 +1 @@ -Keep interrupted profile removal recoverable without changing a replacement identity or losing contact details already captured for incoming payments. +Keep interrupted profile removal recoverable without changing replacement identities or losing incoming payment details, and show recovery options that match the pending wallet state. From 9a837a6e7b9286d4dca24d57c451929131285b27 Mon Sep 17 00:00:00 2001 From: benk10 Date: Thu, 29 Oct 2026 02:10:41 +0200 Subject: [PATCH 18/61] fix: keep recovery callbacks ahead of backup debounce --- .../java/to/bitkit/repositories/BackupRepo.kt | 6 +- .../to/bitkit/repositories/BackupRepoTest.kt | 91 +++++++++++++++++++ changelog.d/next/1689.fixed.md | 2 +- 3 files changed, 95 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 18b66ecaac..b7a1441431 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -536,17 +536,18 @@ class BackupRepo @Inject constructor( jobScope.launch(start = CoroutineStart.LAZY) { try { owner?.ready?.await() + // Coalescing pending work must not delay an explicit recovery acknowledgement. + delay(BACKUP_DEBOUNCE) categoryMutexes.getValue(category).withLock { runningBackups += category try { updateBackupStatus(category, expectedGeneration) { it.copy(running = true) } - delay(BACKUP_DEBOUNCE) if (category == BackupCategory.WALLET) { paykitSdkService.isPaymentSubmissionActive.first { !it } } val status = cacheStore.backupStatuses.first()[category] ?: BackupItemStatus() if (status.isRequired && !shouldSkipBackup(category) && - !failedBackupRequired.containsKey(category) + failedBackupRequired[category] != status.required ) { performBackup(category, expectedGeneration) } @@ -579,7 +580,6 @@ class BackupRepo @Inject constructor( } synchronized(lifecycleLock) { if (resetting || generation != expectedGeneration) return - if (failedBackupRequired.containsKey(category)) return if (!status.shouldBackup(category)) return if (category in explicitBackups) { scheduleBackup(category, requestedGeneration = expectedGeneration) diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 6a6d4a42a8..47c6f6acb2 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -2070,6 +2070,97 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `committed recovery revision survives cancellation after an older permanent failure`() = test { + val category = BackupCategory.USDT_RECOVERY + val statuses = MutableStateFlow>(emptyMap()) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + whenever(usdtRepo.backupSnapshot()).thenReturn("signed") + var attempts = 0 + whenever { vssBackupClient.putObject(argThat { startsWith(UsdtRecoveryBackupStore.PREFIX) }, any()) } + .doSuspendableAnswer { + attempts++ + if (attempts == 1) { + Result.failure(VssException.UnknownException("invalid data")) + } else { + Result.success(VssItem(key = "recovery", value = byteArrayOf(), version = 1)) + } + } + assertTrue(sut.persistUsdtRecoveryBackup("signed").isFailure) + val failedRevision = statuses.value.getValue(category).required + sut.startObservingBackups() + runCurrent() + advanceTimeBy(10_000) + runCurrent() + assertEquals(1, attempts) + val committed = CompletableDeferred() + val release = CompletableDeferred() + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + statuses.update { current -> transform(AppCacheData(backupStatuses = current)).backupStatuses } + val status = statuses.value.getValue(category) + if (!committed.isCompleted && status.required > failedRevision && !status.running) { + committed.complete(Unit) + release.await() + } + } + val service = UsdtService(keychain, Provider { sut }) + val callback = launch { service.recoveryBackup.persist("signed") } + try { + committed.await() + callback.cancel() + runCurrent() + release.complete(Unit) + callback.join() + assertEquals(0L, service.recoveryGeneration) + assertTrue(statuses.value.getValue(category).required > failedRevision) + advanceTimeBy(10_000) + runCurrent() + assertEquals(2, attempts) + assertFalse(statuses.value.getValue(category).isRequired) + assertEquals(0L, service.recoveryGeneration) + } finally { + release.complete(Unit) + callback.cancelAndJoin() + sut.reset() + } + } + + @Test + fun `explicit recovery callback bypasses scheduled debounce and owns its acknowledgement`() = test { + val category = BackupCategory.USDT_RECOVERY + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + whenever(usdtRepo.backupSnapshot()).thenReturn("background") + val uploads = mutableListOf() + whenever { vssBackupClient.putObject(argThat { startsWith(UsdtRecoveryBackupStore.PREFIX) }, any()) } + .doSuspendableAnswer { + val payload = json.decodeFromString(it.getArgument(1).decodeToString()) + uploads += payload.usdtWallet + Result.success(VssItem(key = "recovery", value = byteArrayOf(), version = 1)) + } + sut.startObservingBackups() + runCurrent() + advanceTimeBy(150) + val service = UsdtService(keychain, Provider { sut }) + val callback = async { service.recoveryBackup.persist("signed") } + try { + runCurrent() + assertTrue(callback.isCompleted, "Explicit recovery must not wait for scheduled debounce") + callback.await() + assertEquals(listOf("signed"), uploads) + assertEquals(1L, service.recoveryGeneration) + advanceTimeBy(5_000) + runCurrent() + assertEquals(listOf("signed"), uploads) + } finally { + callback.cancelAndJoin() + sut.reset() + } + } + @Test fun `cancelled queued USDT callback retains its required revision`() = test { val category = BackupCategory.USDT_RECOVERY diff --git a/changelog.d/next/1689.fixed.md b/changelog.d/next/1689.fixed.md index b2ac2cf3ec..8e1c25855d 100644 --- a/changelog.d/next/1689.fixed.md +++ b/changelog.d/next/1689.fixed.md @@ -1 +1 @@ -Prevent interrupted backups from crossing wallet resets and keep explicit backup retries running through temporary connection failures even when observation stops. +Keep interrupted backups within their wallet lifecycle, retry newer pending data after failures, and let explicit recovery acknowledgements proceed without the background delay. From 7afdd3e3ba88ab5dded792073a44b4a975728ebb Mon Sep 17 00:00:00 2001 From: benk10 Date: Thu, 29 Oct 2026 02:41:50 +0200 Subject: [PATCH 19/61] fix: block profile removal with active subscriptions --- .../java/to/bitkit/repositories/PubkyRepo.kt | 13 +++- .../to/bitkit/services/PaykitSdkService.kt | 51 ++++++++++++---- .../java/to/bitkit/services/PubkyService.kt | 8 +++ .../screens/profile/EditProfileViewModel.kt | 21 +++++-- app/src/main/res/values-ar/strings.xml | 1 + app/src/main/res/values-b+es+419/strings.xml | 1 + app/src/main/res/values-ca/strings.xml | 1 + app/src/main/res/values-cs/strings.xml | 1 + app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-el/strings.xml | 1 + app/src/main/res/values-es-rES/strings.xml | 1 + app/src/main/res/values-es/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-it/strings.xml | 1 + app/src/main/res/values-nl/strings.xml | 1 + app/src/main/res/values-pl/strings.xml | 1 + app/src/main/res/values-pt-rBR/strings.xml | 1 + app/src/main/res/values-pt/strings.xml | 1 + app/src/main/res/values-ru/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + .../to/bitkit/repositories/PubkyRepoTest.kt | 49 +++++++++++++-- .../bitkit/services/PaykitSdkServiceTest.kt | 45 ++++++++++++++ .../profile/EditProfileViewModelTest.kt | 60 +++++++++++++++++++ changelog.d/next/1690.fixed.md | 2 +- journeys/profile/profile-cleanup-failure.xml | 9 ++- 25 files changed, 248 insertions(+), 26 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index ce29f89952..46949cf7cd 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -1093,11 +1093,19 @@ class PubkyRepo @Inject constructor( } } + suspend fun checkProfileDeletionAllowed(): Result = runSuspendCatching { + withContext(ioDispatcher) { pubkyService.checkProfileDeletionAllowed() } + }.recoverCatching { + if (it.hasCause(PubkyContactError.ActiveSubscription)) throw PubkyContactError.ActiveSubscription + throw it + } + suspend fun deleteProfile(): Result = runSuspendCatching { withContext(ioDispatcher) { requireNotNull(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)) { "No session available" } + checkProfileDeletionAllowed().getOrThrow() clearSessionContactProfiles() deleteAllContacts() pubkyService.deletePaykitProfile() @@ -1105,13 +1113,16 @@ class PubkyRepo @Inject constructor( } settingsStore.update { it.paykitDisabled(markPublicCleanupPending = it.hasPaykitState()) } signOut().getOrThrow() + }.recoverCatching { + if (it.hasCause(PubkyContactError.ActiveSubscription)) throw PubkyContactError.ActiveSubscription + throw it } private suspend fun deleteAllContacts() { val records = pubkyService.contactRecords() if (records.isEmpty()) return val keys = records.map { it.publicKey.ensurePubkyPrefix() }.toSet() - val removedKeys = pubkyService.removeContacts(records.map { it.publicKey }) + val removedKeys = pubkyService.removeContactsForProfile(records.map { it.publicKey }) .map { it.publicKey.ensurePubkyPrefix() }.toSet().intersect(keys) pubkyStore.update { it.copy(contactProfileOverrides = it.contactProfileOverrides - removedKeys) } notifyBackupStateChanged() diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt index 87c452f640..076e3fa652 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt @@ -764,6 +764,25 @@ class PaykitSdkService @Inject constructor( return imported } + suspend fun checkProfileDeletionAllowed() { + isSetup.await() + operationLock.withLock { + withStateRevisionTracking { handle -> + val now = nowMillis() + if (completeSdkCall { handle.paymentRequests() }.any { it.hasActiveSubscription(now) }) { + throw PubkyContactError.ActiveSubscription + } + } + } + } + + private fun PaymentRequestRecord.hasActiveSubscription(now: Long): Boolean { + val endsAt = terms?.recurrence?.endsAt?.let { timestamp -> + runCatching { Instant.parse(timestamp).toEpochMilliseconds() }.getOrNull() + } + return state == PaymentRequestLifecycleState.ACTIVE_RECURRING && (endsAt == null || endsAt > now) + } + suspend fun removeContact(publicKey: String): ContactRecord? { isSetup.await() return operationLock.withLock { @@ -773,12 +792,7 @@ class PaykitSdkService @Inject constructor( } val now = nowMillis() val hasActiveSubscription = completeSdkCall { handle.paymentRequests() }.any { - val endsAt = it.terms?.recurrence?.endsAt?.let { timestamp -> - runSuspendCatching { Instant.parse(timestamp).toEpochMilliseconds() }.getOrNull() - } - PubkyPublicKeyFormat.matches(it.counterparty, publicKey) && - it.state == PaymentRequestLifecycleState.ACTIVE_RECURRING && - (endsAt == null || endsAt > now) + PubkyPublicKeyFormat.matches(it.counterparty, publicKey) && it.hasActiveSubscription(now) } if (hasActiveSubscription) throw PubkyContactError.ActiveSubscription peers.filter { it.state == LinkedPeerState.LINKED }.forEach { @@ -798,18 +812,29 @@ class PaykitSdkService @Inject constructor( } } - suspend fun removeContacts(publicKeys: List): List { + suspend fun removeContacts(publicKeys: List): List = + removeContacts(publicKeys, requireAll = false) + + suspend fun removeContactsForProfile(publicKeys: List): List = + removeContacts(publicKeys, requireAll = true) + + private suspend fun removeContacts(publicKeys: List, requireAll: Boolean): List { if (publicKeys.isEmpty()) return emptyList() isSetup.await() return operationLock.withLock { withStateRevisionTracking { handle -> val now = nowMillis() - val subscribedKeys = completeSdkCall { handle.paymentRequests() }.filter { - val endsAt = it.terms?.recurrence?.endsAt?.let { timestamp -> - runSuspendCatching { Instant.parse(timestamp).toEpochMilliseconds() }.getOrNull() - } - it.state == PaymentRequestLifecycleState.ACTIVE_RECURRING && (endsAt == null || endsAt > now) - }.mapNotNull { PubkyPublicKeyFormat.normalized(it.counterparty) }.toSet() + val subscriptions = completeSdkCall { handle.paymentRequests() }.filter { + it.hasActiveSubscription( + now + ) + } + if (requireAll && subscriptions.isNotEmpty()) throw PubkyContactError.ActiveSubscription + val subscribedKeys = subscriptions.mapNotNull { + PubkyPublicKeyFormat.normalized( + it.counterparty + ) + }.toSet() val removableKeys = publicKeys.filter { PubkyPublicKeyFormat.normalized(it) !in subscribedKeys } if (removableKeys.isEmpty()) return@withStateRevisionTracking emptyList() completeSdkCall { handle.removeContactsAndBlockPeers(removableKeys) } diff --git a/app/src/main/java/to/bitkit/services/PubkyService.kt b/app/src/main/java/to/bitkit/services/PubkyService.kt index e9105a40c9..18cf817116 100644 --- a/app/src/main/java/to/bitkit/services/PubkyService.kt +++ b/app/src/main/java/to/bitkit/services/PubkyService.kt @@ -207,6 +207,14 @@ class PubkyService @Inject constructor( paykitSdkService.uploadProfileAvatar(bytes, contentType) } + suspend fun checkProfileDeletionAllowed() = ServiceQueue.CORE.background { + paykitSdkService.checkProfileDeletionAllowed() + } + + suspend fun removeContactsForProfile(publicKeys: List): List = ServiceQueue.CORE.background { + paykitSdkService.removeContactsForProfile(publicKeys) + } + suspend fun deletePaykitProfile() = ServiceQueue.CORE.background { paykitSdkService.deletePaykitProfile() } diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt index f72026cafe..793726d570 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt @@ -25,6 +25,7 @@ import to.bitkit.ext.runSuspendCatching import to.bitkit.models.PubkyProfileLink import to.bitkit.models.Toast import to.bitkit.repositories.PrivatePaykitRepo +import to.bitkit.repositories.PubkyContactError import to.bitkit.repositories.PubkyRepo import to.bitkit.ui.components.ProfileEditLink import to.bitkit.ui.shared.toast.ToastEventBus @@ -270,9 +271,12 @@ class EditProfileViewModel @Inject constructor( isDeleting = true, ) } + var privatePauseStarted = false try { - privatePaykitRepo.beginProfileDeletion() val result = runSuspendCatching { + pubkyRepo.checkProfileDeletionAllowed().getOrThrow() + privatePauseStarted = true + privatePaykitRepo.beginProfileDeletion() privatePaykitRepo.removePublishedEndpointsForCleanup(TAG, deferAppSync = true).getOrThrow() pubkyRepo.deleteProfile().getOrThrow() } @@ -293,11 +297,20 @@ class EditProfileViewModel @Inject constructor( _effects.emit(EditProfileEffect.DeleteSuccess) } else { val error = requireNotNull(result.exceptionOrNull()) { "Profile delete failed without an error" } - Logger.error("Failed to delete profile", error, context = TAG) - _uiState.update { it.copy(showDeleteFailureDialog = true) } + if (error == PubkyContactError.ActiveSubscription) { + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.profile__delete_active_subscription), + ) + } else { + Logger.error("Failed to delete profile", error, context = TAG) + _uiState.update { it.copy(showDeleteFailureDialog = true) } + } } } finally { - withContext(NonCancellable) { privatePaykitRepo.endProfileDeletion() } + if (privatePauseStarted) { + withContext(NonCancellable) { privatePaykitRepo.endProfileDeletion() } + } _uiState.update { it.copy(isDeleting = false) } } } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 045e83ac9b..a3dcb89358 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1297,6 +1297,7 @@ جارٍ تحميل ملفك الشخصي… ادخل إلى\n<accent>ويب الحرية</accent> فشل إنشاء الملف الشخصي + أنه الاشتراكات النشطة قبل إزالة هذا الملف الشخصي. يؤدي حذف ملفك الشخصي إلى إزالته من Pubky. قد تحتفظ جهات الاتصال بمعلومات الملف الشخصي والدفع التي شاركتها معهم سابقًا. حذف الملف الشخصي؟ تعذر علينا حذف بيانات ملفك الشخصي. أعد المحاولة، أو افصل هذا الـ pubky عن Bitkit. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 2e3d9b1f9f..49633ef5b0 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1323,6 +1323,7 @@ Cargando su perfil… Entre a la\n<accent>web de la libertad</accent> No se pudo crear el perfil + Finaliza las suscripciones activas antes de eliminar este perfil. 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. ¿Eliminar perfil? No pudimos eliminar los datos de su perfil. Vuelva a intentarlo o desconecte este pubky de Bitkit. diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 24dcb34d0a..f4f9a51d03 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1319,6 +1319,7 @@ Carregant el teu perfil… Entra a la\n<accent>web de la llibertat</accent> No s\'ha pogut crear el perfil + Finalitza les subscripcions actives abans d’eliminar aquest perfil. 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. Eliminar el perfil? No hem pogut eliminar les dades del teu perfil. Torna-ho a provar o desconnecta aquest pubky de Bitkit. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index f0336264d1..998983747d 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1321,6 +1321,7 @@ Načítání vašeho profilu… Vstupte do\n<accent>svobodného webu</accent> Profil se nepodařilo vytvořit + Před odstraněním tohoto profilu ukončete aktivní předplatná. 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. Smazat profil? Data vašeho profilu se nepodařilo smazat. Zkuste to znovu, nebo tento pubky od Bitkitu odpojte. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 2a45ff0fe4..eae0affb2c 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1319,6 +1319,7 @@ Dein Profil wird geladen… Betritt das\n<accent>freie Web</accent> Profil konnte nicht erstellt werden + Beende aktive Abonnements, bevor du dieses Profil entfernst. Durch das Löschen deines Profils wird es von Pubky entfernt. Kontakte können zuvor mit ihnen geteilte Profil- und Zahlungsinformationen weiterhin behalten. Profil löschen? Wir konnten deine Profildaten nicht löschen. Versuche es erneut oder trenne diesen pubky von Bitkit. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 8587ae5710..29d0a85d45 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1303,6 +1303,7 @@ Φόρτωση του προφίλ σου… Μπες στον\n<accent>ελεύθερο ιστό</accent> Αποτυχία δημιουργίας προφίλ + Τερμάτισε τις ενεργές συνδρομές πριν αφαιρέσεις αυτό το προφίλ. Η διαγραφή του προφίλ σου το αφαιρεί από το Pubky. Οι επαφές μπορεί να διατηρούν ακόμα πληροφορίες προφίλ και πληρωμών που τους κοινοποιήθηκαν παλαιότερα. Διαγραφή προφίλ; Δεν μπορέσαμε να διαγράψουμε τα δεδομένα του προφίλ σου. Δοκίμασε ξανά ή αποσύνδεσε αυτό το pubky από το Bitkit. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 9d926c39bd..d989aa673f 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1317,6 +1317,7 @@ Cargando tu perfil… Entra en la\n<accent>web libre</accent> No se pudo crear el perfil + Finaliza las suscripciones activas antes de eliminar este perfil. Al eliminar tu perfil, se elimina de Pubky. Es posible que tus contactos conserven la información de perfil y de pago que compartiste con ellos anteriormente. ¿Eliminar el perfil? No pudimos eliminar los datos de tu perfil. Vuelve a intentarlo o desconecta este pubky de Bitkit. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 940f3de425..bc05be7c2b 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1316,6 +1316,7 @@ Cargando su perfil… Entre en la\n<accent>web libre</accent> No se pudo crear el perfil + Finaliza las suscripciones activas antes de eliminar este perfil. 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. ¿Eliminar el perfil? No pudimos eliminar los datos de su perfil. Vuelva a intentarlo o desconecte este pubky de Bitkit. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 61cd95d307..b4032906f9 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1317,6 +1317,7 @@ Chargement de votre profil… Entrez dans le\n<accent>web de la liberté</accent> Échec de la création du profil + Mettez fin aux abonnements actifs avant de supprimer ce profil. 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. Supprimer le profil ? Nous n\'avons pas pu supprimer les données de votre profil. Réessayez ou déconnectez ce pubky de Bitkit. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 2141ffc645..cc3402e604 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1322,6 +1322,7 @@ Caricamento del profilo… Entra nel\n<accent>web della libertà</accent> Impossibile creare il profilo + Termina gli abbonamenti attivi prima di rimuovere questo profilo. Eliminando il profilo lo rimuovi da Pubky. I contatti potrebbero conservare le informazioni di profilo e di pagamento condivise in precedenza con loro. Eliminare il Profilo? Non è stato possibile eliminare i dati del tuo profilo. Riprova, oppure disconnetti questo pubky da Bitkit. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 0f16a7c531..c8bc711174 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1319,6 +1319,7 @@ Uw profiel laden… Betreed het\n<accent>vrije web</accent> Profiel aanmaken mislukt + Beëindig actieve abonnementen voordat je dit profiel verwijdert. Als u uw profiel verwijdert, wordt het van Pubky verwijderd. Contacten kunnen eerder gedeelde profiel- en betaalgegevens nog bewaren. Profiel verwijderen? We konden uw profielgegevens niet verwijderen. Probeer het opnieuw, of ontkoppel deze pubky van Bitkit. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index d1a5a29132..8e7d1cdf09 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1320,6 +1320,7 @@ Wczytywanie Twojego profilu… Wejdź do\n<accent>wolnej sieci</accent> Nie udało się utworzyć profilu + Zakończ aktywne subskrypcje przed usunięciem tego profilu. Usunięcie profilu usuwa go z Pubky. Kontakty mogą nadal przechowywać udostępnione im wcześniej dane profilu i płatności. Usunąć profil? Nie udało się usunąć danych Twojego profilu. Spróbuj ponownie lub odłącz ten pubky od Bitkit. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 0266a4b1e4..d893d9b6bf 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1322,6 +1322,7 @@ Carregando seu perfil… Entre na\n<accent>web da liberdade</accent> Falha ao criar perfil + Encerre as assinaturas ativas antes de remover este perfil. Excluir seu perfil o remove do Pubky. Os contatos ainda podem manter informações de perfil e de pagamento compartilhadas anteriormente com eles. Excluir Perfil? Não conseguimos excluir os dados do seu perfil. Tente novamente ou desconecte esta pubky da Bitkit. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index c9f113920f..fddd7e88ea 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1296,6 +1296,7 @@ A carregar o seu perfil… Entre na\n<accent>web da liberdade</accent> Falha ao criar perfil + Termina as subscrições ativas antes de remover este perfil. Eliminar o seu perfil remove-o do Pubky. Os contactos podem manter as informações de perfil e pagamento partilhadas anteriormente com eles. Eliminar perfil? Não foi possível eliminar os dados do seu perfil. Tente novamente ou desligue este pubky da Bitkit. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index cd61bf299f..18e67a6899 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1337,6 +1337,7 @@ Загрузка вашего профиля… Войдите в\n<accent>свободный веб</accent> Не удалось создать профиль + Завершите активные подписки перед удалением этого профиля. Удаление профиля удалит его из Pubky. У контактов могут остаться данные профиля и платёжные данные, которыми вы делились ранее. Удалить Профиль? Не удалось удалить данные вашего профиля. Повторите попытку или отключите этот pubky от Bitkit. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e0f1418c67..eb64b1d4a0 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -630,6 +630,7 @@ Enter the\n<accent>freedom web</accent> Failed to create profile Create Profile + End active subscriptions before removing this profile. Deleting your profile removes it from Pubky. Contacts may still retain profile and payment information previously shared with them. Delete Profile? We couldn\'t delete your profile data. Retry, or disconnect this pubky from Bitkit. diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 241ea156b3..a86492a240 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -1313,7 +1313,7 @@ class PubkyRepoTest : BaseUnitTest() { createContactRecord(VALID_CONTACT_KEY_B, label = "Bob"), ) whenever(pubkyService.contactRecords()).thenReturn(records) - whenever(pubkyService.removeContacts(records.map { it.publicKey })).thenReturn(records) + whenever(pubkyService.removeContactsForProfile(records.map { it.publicKey })).thenReturn(records) val bulkCancelled = CompletableDeferred() val screenCancelled = CompletableDeferred() whenever(pubkyService.resolveContactProfile(VALID_CONTACT_KEY_A, true, PaykitReadLane.Bulk)) @@ -1352,10 +1352,45 @@ class PubkyRepoTest : BaseUnitTest() { deletion.await().getOrThrow() screenLookup.await() assertTrue(sut.contacts.value.isEmpty()) - verify(pubkyService).removeContacts(records.map { it.publicKey }) + verify(pubkyService).removeContactsForProfile(records.map { it.publicKey }) verify(pubkyService, never()).removeContact(any()) } + @Test + fun `active subscription is preserved through service wrappers before profile cleanup`() = test { + authenticateForTesting() + val wrapped = IllegalStateException("Service operation failed", PubkyContactError.ActiveSubscription) + whenever(pubkyService.checkProfileDeletionAllowed()).thenAnswer { throw wrapped } + clearInvocations(pubkyStore, pubkyService) + + assertSame(PubkyContactError.ActiveSubscription, sut.checkProfileDeletionAllowed().exceptionOrNull()) + assertSame(PubkyContactError.ActiveSubscription, sut.deleteProfile().exceptionOrNull()) + + verify(pubkyService, never()).contactRecords() + verify(pubkyService, never()).removeContactsForProfile(any()) + verify(pubkyService, never()).deletePaykitProfile() + verify(pubkyService, never()).signOut() + verify(pubkyStore, never()).update(any()) + } + + @Test + fun `late subscription rejection retains contacts and credentials`() = test { + authenticateForTesting() + val records = listOf(createContactRecord(VALID_CONTACT_KEY_A, label = "Retained")) + whenever(pubkyService.contactRecords()).thenReturn(records) + sut.loadContacts() + val wrapped = IllegalStateException("Service operation failed", PubkyContactError.ActiveSubscription) + whenever(pubkyService.removeContactsForProfile(any())).thenAnswer { throw wrapped } + clearInvocations(pubkyStore) + + assertSame(PubkyContactError.ActiveSubscription, sut.deleteProfile().exceptionOrNull()) + + assertEquals(listOf(VALID_CONTACT_KEY_A), sut.contacts.value.map { it.publicKey }) + verify(pubkyStore, never()).update(any()) + verify(pubkyService, never()).deletePaykitProfile() + verify(pubkyService, never()).signOut() + } + @Test fun `partial contact cleanup preserves retained contacts and stops profile deletion`() = test { authenticateForTesting() @@ -1373,7 +1408,9 @@ class PubkyRepoTest : BaseUnitTest() { Unit } whenever(pubkyService.contactRecords()).thenReturn(records) - whenever(pubkyService.removeContacts(records.map { it.publicKey })).thenReturn(listOf(records.first())) + whenever( + pubkyService.removeContactsForProfile(records.map { it.publicKey }) + ).thenReturn(listOf(records.first())) sut.loadContacts() val result = sut.deleteProfile() @@ -1396,7 +1433,7 @@ class PubkyRepoTest : BaseUnitTest() { assertSame(error, result.exceptionOrNull()) verify(pubkyStore, never()).update(any()) - verify(pubkyService, never()).removeContacts(any()) + verify(pubkyService, never()).removeContactsForProfile(any()) verify(pubkyService, never()).deletePaykitProfile() verify(pubkyService, never()).signOut() } @@ -1408,7 +1445,7 @@ class PubkyRepoTest : BaseUnitTest() { val records = listOf(record) val error = TestAppError("Contact removal acknowledgement lost") whenever(pubkyService.contactRecords()).thenReturn(records) - whenever(pubkyService.removeContacts(listOf(record.publicKey))).thenAnswer { throw error } + whenever(pubkyService.removeContactsForProfile(listOf(record.publicKey))).thenAnswer { throw error } sut.loadContacts() clearInvocations(pubkyStore) @@ -4776,7 +4813,7 @@ class PubkyRepoTest : BaseUnitTest() { authenticateForTesting() whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn("test_secret") val records = listOf(createContactRecord(VALID_CONTACT_KEY_A, "Saved")) - whenever(pubkyService.removeContacts(records.map { it.publicKey })).thenReturn(records) + whenever(pubkyService.removeContactsForProfile(records.map { it.publicKey })).thenReturn(records) whenever(pubkyService.deletePaykitProfile()).thenAnswer { throw TestAppError("Offline") } val newRead = createResolution(VALID_CONTACT_KEY_A, paykitProfile = createPaykitProfile("Alice", "New")) val oldRead = holdScreenLookup(VALID_CONTACT_KEY_A, laterRead = newRead) diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt index f4056f8672..b9d07e0483 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt @@ -2090,6 +2090,10 @@ class PaykitSdkServiceTest { val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } assertFailsWith { service.removeContact(RING_PUBKY) } assertTrue(service.removeContacts(listOf(RING_PUBKY)).isEmpty()) + assertFailsWith { service.checkProfileDeletionAllowed() } + assertFailsWith { + service.removeContactsForProfile(listOf(RING_PUBKY, "pubkyunrelated")) + } verify(sdk, never()).blockPeer(any()) verify(sdk, never()).removeContact(any()) verify(sdk, never()).removeContactsAndBlockPeers(any()) @@ -2103,9 +2107,50 @@ class PaykitSdkServiceTest { val removed = listOf(mock()) whenever(sdk.removeContactsAndBlockPeers(listOf(RING_PUBKY))).thenReturn(removed) assertEquals(removed, service.removeContacts(listOf(RING_PUBKY))) + service.checkProfileDeletionAllowed() + assertEquals(removed, service.removeContactsForProfile(listOf(RING_PUBKY))) } } + @Test + fun `profile removal conservatively blocks unknown or future subscription expiry`() = runTest { + for (endsAt in listOf(null, "invalid", "2999-01-01T00:00:00Z")) { + val sdk = mock() + val recurrence = mock { on { this.endsAt } doReturn endsAt } + val requestTerms = mock { on { this.recurrence } doReturn recurrence } + val request = mock { + on { counterparty } doReturn RING_PUBKY + on { state } doReturn PaymentRequestLifecycleState.ACTIVE_RECURRING + on { terms } doReturn requestTerms + } + whenever(sdk.paymentRequests()).thenReturn(listOf(request)) + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + + assertFailsWith { service.checkProfileDeletionAllowed() } + assertFailsWith { + service.removeContactsForProfile(listOf("pubkyunrelated")) + } + verify(sdk, never()).removeContactsAndBlockPeers(any()) + } + } + + @Test + fun `profile removal fails closed when subscriptions cannot be read`() = runTest { + val sdk = mock() + val error = IllegalStateException("Subscription storage unavailable") + whenever(sdk.paymentRequests()).thenAnswer { throw error } + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + + assertSame(error, assertFailsWith { service.checkProfileDeletionAllowed() }) + assertSame( + error, + assertFailsWith { + service.removeContactsForProfile(listOf(RING_PUBKY)) + } + ) + verify(sdk, never()).removeContactsAndBlockPeers(any()) + } + @Test fun `unreadable profile cache stops activation`() = runTest { for (error in listOf( diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt index 30f48762ae..7045867cb3 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt @@ -24,6 +24,7 @@ import to.bitkit.R import to.bitkit.models.PubkyProfile import to.bitkit.models.PubkyProfileLink import to.bitkit.repositories.PrivatePaykitRepo +import to.bitkit.repositories.PubkyContactError import to.bitkit.repositories.PubkyRepo import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError @@ -41,6 +42,64 @@ class EditProfileViewModelTest : BaseUnitTest() { private val pubkyRepo: PubkyRepo = mock() private val privatePaykitRepo: PrivatePaykitRepo = mock() + @Test + fun `active subscription stops profile deletion before private or contact cleanup`() = test { + val sut = createSut() + whenever( + pubkyRepo.checkProfileDeletionAllowed() + ).thenReturn(Result.failure(PubkyContactError.ActiveSubscription)) + whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) + advanceUntilIdle() + + sut.deleteProfile() + advanceUntilIdle() + + verify(pubkyRepo).checkProfileDeletionAllowed() + verify(context).getString(R.string.profile__delete_active_subscription) + verify(privatePaykitRepo, never()).beginProfileDeletion() + verify(privatePaykitRepo, never()).endProfileDeletion() + verify(privatePaykitRepo, never()).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) + verify(privatePaykitRepo, never()).closeAndClear() + verify(pubkyRepo, never()).deleteProfile() + assertFalse(sut.uiState.value.showDeleteFailureDialog) + assertFalse(sut.uiState.value.isDeleting) + } + + @Test + fun `unavailable subscription read retains cleanup and shows failure`() = test { + val sut = createSut() + whenever(pubkyRepo.checkProfileDeletionAllowed()).thenReturn(Result.failure(TestAppError("Unavailable"))) + advanceUntilIdle() + + sut.deleteProfile() + advanceUntilIdle() + + assertTrue(sut.uiState.value.showDeleteFailureDialog) + assertFalse(sut.uiState.value.isDeleting) + verify(privatePaykitRepo, never()).beginProfileDeletion() + verify(privatePaykitRepo, never()).endProfileDeletion() + verify(pubkyRepo, never()).deleteProfile() + } + + @Test + fun `cancellation during subscription read does not start or end private cleanup`() = test { + val sut = createSut() + val read = CompletableDeferred>() + whenever(pubkyRepo.checkProfileDeletionAllowed()).doSuspendableAnswer { read.await() } + advanceUntilIdle() + sut.deleteProfile() + advanceUntilIdle() + + sut.viewModelScope.cancel() + advanceUntilIdle() + + assertFalse(sut.uiState.value.isDeleting) + assertFalse(sut.uiState.value.showDeleteFailureDialog) + verify(privatePaykitRepo, never()).beginProfileDeletion() + verify(privatePaykitRepo, never()).endProfileDeletion() + verify(pubkyRepo, never()).deleteProfile() + } + @Test fun `disconnect finishes private cleanup after the screen is closed`() = test { val sut = createSut() @@ -418,6 +477,7 @@ class EditProfileViewModelTest : BaseUnitTest() { } else { whenever { pubkyRepo.isRingAdoptedIdentity() }.thenReturn(isRingIdentity) } + whenever { pubkyRepo.checkProfileDeletionAllowed() }.thenReturn(Result.success(Unit)) whenever { pubkyRepo.forgetUnrestoredIdentity() }.thenReturn(Result.success(false)) whenever(pubkyRepo.profile).thenReturn(MutableStateFlow(createProfile())) whenever(pubkyRepo.publicKey).thenReturn(MutableStateFlow(TEST_PUBLIC_KEY)) diff --git a/changelog.d/next/1690.fixed.md b/changelog.d/next/1690.fixed.md index f05f0a6f84..ee2cf196bc 100644 --- a/changelog.d/next/1690.fixed.md +++ b/changelog.d/next/1690.fixed.md @@ -1 +1 @@ -Preserve session and contact data after failed profile deletion or incomplete payment-link cleanup. +Preserve profile data when cleanup is incomplete and explain when active subscriptions prevent removal. 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 98797f24432138b198a435ca2ee8f2dda696cba8 Mon Sep 17 00:00:00 2001 From: benk10 Date: Thu, 29 Oct 2026 14:02:29 +0200 Subject: [PATCH 20/61] fix: explain fixed-term profile removal restrictions --- .../java/to/bitkit/repositories/PubkyRepo.kt | 7 +++ .../to/bitkit/services/PaykitSdkService.kt | 23 +++++++--- .../screens/profile/EditProfileViewModel.kt | 8 +++- app/src/main/res/values-ar/strings.xml | 2 +- app/src/main/res/values-b+es+419/strings.xml | 2 +- app/src/main/res/values-ca/strings.xml | 2 +- app/src/main/res/values-cs/strings.xml | 2 +- app/src/main/res/values-de/strings.xml | 2 +- app/src/main/res/values-el/strings.xml | 2 +- app/src/main/res/values-es-rES/strings.xml | 2 +- app/src/main/res/values-es/strings.xml | 2 +- app/src/main/res/values-fr/strings.xml | 2 +- app/src/main/res/values-it/strings.xml | 2 +- app/src/main/res/values-nl/strings.xml | 2 +- app/src/main/res/values-pl/strings.xml | 2 +- app/src/main/res/values-pt-rBR/strings.xml | 2 +- app/src/main/res/values-pt/strings.xml | 2 +- app/src/main/res/values-ru/strings.xml | 2 +- app/src/main/res/values/strings.xml | 2 +- .../to/bitkit/repositories/PubkyRepoTest.kt | 12 ++--- .../bitkit/services/PaykitSdkServiceTest.kt | 44 +++++++++++++++++-- .../profile/EditProfileViewModelTest.kt | 28 ++++++++++++ changelog.d/next/1690.fixed.md | 2 +- journeys/profile/profile-cleanup-failure.xml | 2 +- 24 files changed, 123 insertions(+), 35 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 46949cf7cd..257676adfe 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -89,6 +89,7 @@ sealed class PubkyContactError(message: String) : AppError(message) { data object CannotAddSelf : PubkyContactError("Cannot add your own pubky as a contact") data object InvalidFormat : PubkyContactError("Invalid pubky key format") data object ActiveSubscription : PubkyContactError("Contact has an active subscription") + class ActiveProfileSubscriptions(val endsAtMillis: Long?) : PubkyContactError("Profile has active subscriptions") data object SignInChanged : PubkyContactError("Pubky sign-in changed while saving the contact") } @@ -1096,6 +1097,9 @@ class PubkyRepo @Inject constructor( suspend fun checkProfileDeletionAllowed(): Result = runSuspendCatching { withContext(ioDispatcher) { pubkyService.checkProfileDeletionAllowed() } }.recoverCatching { + generateSequence(it) { error -> error.cause } + .filterIsInstance() + .firstOrNull()?.let { error -> throw error } if (it.hasCause(PubkyContactError.ActiveSubscription)) throw PubkyContactError.ActiveSubscription throw it } @@ -1114,6 +1118,9 @@ class PubkyRepo @Inject constructor( settingsStore.update { it.paykitDisabled(markPublicCleanupPending = it.hasPaykitState()) } signOut().getOrThrow() }.recoverCatching { + generateSequence(it) { error -> error.cause } + .filterIsInstance() + .firstOrNull()?.let { error -> throw error } if (it.hasCause(PubkyContactError.ActiveSubscription)) throw PubkyContactError.ActiveSubscription throw it } diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt index 076e3fa652..b67369c361 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt @@ -769,20 +769,29 @@ class PaykitSdkService @Inject constructor( operationLock.withLock { withStateRevisionTracking { handle -> val now = nowMillis() - if (completeSdkCall { handle.paymentRequests() }.any { it.hasActiveSubscription(now) }) { - throw PubkyContactError.ActiveSubscription - } + val requests = completeSdkCall { handle.paymentRequests() } + val subscriptions = requests.filter { it.hasActiveSubscription(now) } + requireNoProfileSubscriptions(subscriptions) } } } private fun PaymentRequestRecord.hasActiveSubscription(now: Long): Boolean { - val endsAt = terms?.recurrence?.endsAt?.let { timestamp -> - runCatching { Instant.parse(timestamp).toEpochMilliseconds() }.getOrNull() - } + val endsAt = subscriptionEndsAtMillis() return state == PaymentRequestLifecycleState.ACTIVE_RECURRING && (endsAt == null || endsAt > now) } + private fun PaymentRequestRecord.subscriptionEndsAtMillis(): Long? = terms?.recurrence?.endsAt?.let { timestamp -> + runCatching { Instant.parse(timestamp).toEpochMilliseconds() }.getOrNull() + } + + private fun requireNoProfileSubscriptions(subscriptions: List) { + if (subscriptions.isEmpty()) return + val endDates = subscriptions.mapNotNull { it.subscriptionEndsAtMillis() } + val latestEnd = if (endDates.size == subscriptions.size) endDates.maxOrNull() else null + throw PubkyContactError.ActiveProfileSubscriptions(latestEnd) + } + suspend fun removeContact(publicKey: String): ContactRecord? { isSetup.await() return operationLock.withLock { @@ -829,7 +838,7 @@ class PaykitSdkService @Inject constructor( now ) } - if (requireAll && subscriptions.isNotEmpty()) throw PubkyContactError.ActiveSubscription + if (requireAll) requireNoProfileSubscriptions(subscriptions) val subscribedKeys = subscriptions.mapNotNull { PubkyPublicKeyFormat.normalized( it.counterparty diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt index 793726d570..3f9216f71e 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt @@ -22,6 +22,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import to.bitkit.R import to.bitkit.ext.runSuspendCatching +import to.bitkit.ext.toLocalizedTimestamp import to.bitkit.models.PubkyProfileLink import to.bitkit.models.Toast import to.bitkit.repositories.PrivatePaykitRepo @@ -297,10 +298,15 @@ class EditProfileViewModel @Inject constructor( _effects.emit(EditProfileEffect.DeleteSuccess) } else { val error = requireNotNull(result.exceptionOrNull()) { "Profile delete failed without an error" } - if (error == PubkyContactError.ActiveSubscription) { + if (error is PubkyContactError.ActiveProfileSubscriptions || + error == PubkyContactError.ActiveSubscription + ) { ToastEventBus.send( type = Toast.ToastType.ERROR, title = context.getString(R.string.profile__delete_active_subscription), + description = (error as? PubkyContactError.ActiveProfileSubscriptions)?.endsAtMillis?.let { + context.getString(R.string.subscriptions__expires_date, it.toLocalizedTimestamp()) + }, ) } else { Logger.error("Failed to delete profile", error, context = TAG) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index a3dcb89358..df576cc42d 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1297,7 +1297,7 @@ جارٍ تحميل ملفك الشخصي… ادخل إلى\n<accent>ويب الحرية</accent> فشل إنشاء الملف الشخصي - أنه الاشتراكات النشطة قبل إزالة هذا الملف الشخصي. + تمنع الاشتراكات النشطة إزالة هذا الملف الشخصي. يؤدي حذف ملفك الشخصي إلى إزالته من Pubky. قد تحتفظ جهات الاتصال بمعلومات الملف الشخصي والدفع التي شاركتها معهم سابقًا. حذف الملف الشخصي؟ تعذر علينا حذف بيانات ملفك الشخصي. أعد المحاولة، أو افصل هذا الـ pubky عن Bitkit. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 49633ef5b0..ad45c5d0b9 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1323,7 +1323,7 @@ Cargando su perfil… Entre a la\n<accent>web de la libertad</accent> No se pudo crear el perfil - Finaliza las suscripciones activas antes de eliminar este perfil. + Las suscripciones activas impiden eliminar este perfil. 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. ¿Eliminar perfil? No pudimos eliminar los datos de su perfil. Vuelva a intentarlo o desconecte este pubky de Bitkit. diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index f4f9a51d03..6398041ddb 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1319,7 +1319,7 @@ Carregant el teu perfil… Entra a la\n<accent>web de la llibertat</accent> No s\'ha pogut crear el perfil - Finalitza les subscripcions actives abans d’eliminar aquest perfil. + Les subscripcions actives impedeixen eliminar aquest perfil. 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. Eliminar el perfil? No hem pogut eliminar les dades del teu perfil. Torna-ho a provar o desconnecta aquest pubky de Bitkit. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 998983747d..de37563d31 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1321,7 +1321,7 @@ Načítání vašeho profilu… Vstupte do\n<accent>svobodného webu</accent> Profil se nepodařilo vytvořit - Před odstraněním tohoto profilu ukončete aktivní předplatná. + Aktivní předplatná brání odstranění tohoto profilu. 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. Smazat profil? Data vašeho profilu se nepodařilo smazat. Zkuste to znovu, nebo tento pubky od Bitkitu odpojte. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index eae0affb2c..0b38baa262 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1319,7 +1319,7 @@ Dein Profil wird geladen… Betritt das\n<accent>freie Web</accent> Profil konnte nicht erstellt werden - Beende aktive Abonnements, bevor du dieses Profil entfernst. + Aktive Abonnements verhindern das Entfernen dieses Profils. Durch das Löschen deines Profils wird es von Pubky entfernt. Kontakte können zuvor mit ihnen geteilte Profil- und Zahlungsinformationen weiterhin behalten. Profil löschen? Wir konnten deine Profildaten nicht löschen. Versuche es erneut oder trenne diesen pubky von Bitkit. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 29d0a85d45..c3c979cbec 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1303,7 +1303,7 @@ Φόρτωση του προφίλ σου… Μπες στον\n<accent>ελεύθερο ιστό</accent> Αποτυχία δημιουργίας προφίλ - Τερμάτισε τις ενεργές συνδρομές πριν αφαιρέσεις αυτό το προφίλ. + Οι ενεργές συνδρομές εμποδίζουν την αφαίρεση αυτού του προφίλ. Η διαγραφή του προφίλ σου το αφαιρεί από το Pubky. Οι επαφές μπορεί να διατηρούν ακόμα πληροφορίες προφίλ και πληρωμών που τους κοινοποιήθηκαν παλαιότερα. Διαγραφή προφίλ; Δεν μπορέσαμε να διαγράψουμε τα δεδομένα του προφίλ σου. Δοκίμασε ξανά ή αποσύνδεσε αυτό το pubky από το Bitkit. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index d989aa673f..f77cfc9650 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1317,7 +1317,7 @@ Cargando tu perfil… Entra en la\n<accent>web libre</accent> No se pudo crear el perfil - Finaliza las suscripciones activas antes de eliminar este perfil. + Las suscripciones activas impiden eliminar este perfil. Al eliminar tu perfil, se elimina de Pubky. Es posible que tus contactos conserven la información de perfil y de pago que compartiste con ellos anteriormente. ¿Eliminar el perfil? No pudimos eliminar los datos de tu perfil. Vuelve a intentarlo o desconecta este pubky de Bitkit. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index bc05be7c2b..0c47777882 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1316,7 +1316,7 @@ Cargando su perfil… Entre en la\n<accent>web libre</accent> No se pudo crear el perfil - Finaliza las suscripciones activas antes de eliminar este perfil. + Las suscripciones activas impiden eliminar este perfil. 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. ¿Eliminar el perfil? No pudimos eliminar los datos de su perfil. Vuelva a intentarlo o desconecte este pubky de Bitkit. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index b4032906f9..f889c05324 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1317,7 +1317,7 @@ Chargement de votre profil… Entrez dans le\n<accent>web de la liberté</accent> Échec de la création du profil - Mettez fin aux abonnements actifs avant de supprimer ce profil. + Les abonnements actifs empêchent la suppression de ce profil. 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. Supprimer le profil ? Nous n\'avons pas pu supprimer les données de votre profil. Réessayez ou déconnectez ce pubky de Bitkit. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index cc3402e604..a5a653dd54 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1322,7 +1322,7 @@ Caricamento del profilo… Entra nel\n<accent>web della libertà</accent> Impossibile creare il profilo - Termina gli abbonamenti attivi prima di rimuovere questo profilo. + Gli abbonamenti attivi impediscono la rimozione di questo profilo. Eliminando il profilo lo rimuovi da Pubky. I contatti potrebbero conservare le informazioni di profilo e di pagamento condivise in precedenza con loro. Eliminare il Profilo? Non è stato possibile eliminare i dati del tuo profilo. Riprova, oppure disconnetti questo pubky da Bitkit. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index c8bc711174..66cbffd5c4 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1319,7 +1319,7 @@ Uw profiel laden… Betreed het\n<accent>vrije web</accent> Profiel aanmaken mislukt - Beëindig actieve abonnementen voordat je dit profiel verwijdert. + Actieve abonnementen verhinderen het verwijderen van dit profiel. Als u uw profiel verwijdert, wordt het van Pubky verwijderd. Contacten kunnen eerder gedeelde profiel- en betaalgegevens nog bewaren. Profiel verwijderen? We konden uw profielgegevens niet verwijderen. Probeer het opnieuw, of ontkoppel deze pubky van Bitkit. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 8e7d1cdf09..471d3e6e46 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1320,7 +1320,7 @@ Wczytywanie Twojego profilu… Wejdź do\n<accent>wolnej sieci</accent> Nie udało się utworzyć profilu - Zakończ aktywne subskrypcje przed usunięciem tego profilu. + Aktywne subskrypcje uniemożliwiają usunięcie tego profilu. Usunięcie profilu usuwa go z Pubky. Kontakty mogą nadal przechowywać udostępnione im wcześniej dane profilu i płatności. Usunąć profil? Nie udało się usunąć danych Twojego profilu. Spróbuj ponownie lub odłącz ten pubky od Bitkit. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index d893d9b6bf..4e6fc51ca2 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1322,7 +1322,7 @@ Carregando seu perfil… Entre na\n<accent>web da liberdade</accent> Falha ao criar perfil - Encerre as assinaturas ativas antes de remover este perfil. + As assinaturas ativas impedem a remoção deste perfil. Excluir seu perfil o remove do Pubky. Os contatos ainda podem manter informações de perfil e de pagamento compartilhadas anteriormente com eles. Excluir Perfil? Não conseguimos excluir os dados do seu perfil. Tente novamente ou desconecte esta pubky da Bitkit. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index fddd7e88ea..bd31b62822 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1296,7 +1296,7 @@ A carregar o seu perfil… Entre na\n<accent>web da liberdade</accent> Falha ao criar perfil - Termina as subscrições ativas antes de remover este perfil. + As subscrições ativas impedem a remoção deste perfil. Eliminar o seu perfil remove-o do Pubky. Os contactos podem manter as informações de perfil e pagamento partilhadas anteriormente com eles. Eliminar perfil? Não foi possível eliminar os dados do seu perfil. Tente novamente ou desligue este pubky da Bitkit. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 18e67a6899..0e4f874b6e 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1337,7 +1337,7 @@ Загрузка вашего профиля… Войдите в\n<accent>свободный веб</accent> Не удалось создать профиль - Завершите активные подписки перед удалением этого профиля. + Активные подписки не позволяют удалить этот профиль. Удаление профиля удалит его из Pubky. У контактов могут остаться данные профиля и платёжные данные, которыми вы делились ранее. Удалить Профиль? Не удалось удалить данные вашего профиля. Повторите попытку или отключите этот pubky от Bitkit. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index eb64b1d4a0..9d364d8a95 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -630,7 +630,7 @@ Enter the\n<accent>freedom web</accent> Failed to create profile Create Profile - End active subscriptions before removing this profile. + Active subscriptions prevent removing this profile. Deleting your profile removes it from Pubky. Contacts may still retain profile and payment information previously shared with them. Delete Profile? We couldn\'t delete your profile data. Retry, or disconnect this pubky from Bitkit. diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index a86492a240..181398cf36 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -1359,12 +1359,13 @@ class PubkyRepoTest : BaseUnitTest() { @Test fun `active subscription is preserved through service wrappers before profile cleanup`() = test { authenticateForTesting() - val wrapped = IllegalStateException("Service operation failed", PubkyContactError.ActiveSubscription) + val expected = PubkyContactError.ActiveProfileSubscriptions(1_800_000_000_000L) + val wrapped = IllegalStateException("Service operation failed", expected) whenever(pubkyService.checkProfileDeletionAllowed()).thenAnswer { throw wrapped } clearInvocations(pubkyStore, pubkyService) - assertSame(PubkyContactError.ActiveSubscription, sut.checkProfileDeletionAllowed().exceptionOrNull()) - assertSame(PubkyContactError.ActiveSubscription, sut.deleteProfile().exceptionOrNull()) + assertSame(expected, sut.checkProfileDeletionAllowed().exceptionOrNull()) + assertSame(expected, sut.deleteProfile().exceptionOrNull()) verify(pubkyService, never()).contactRecords() verify(pubkyService, never()).removeContactsForProfile(any()) @@ -1379,11 +1380,12 @@ class PubkyRepoTest : BaseUnitTest() { val records = listOf(createContactRecord(VALID_CONTACT_KEY_A, label = "Retained")) whenever(pubkyService.contactRecords()).thenReturn(records) sut.loadContacts() - val wrapped = IllegalStateException("Service operation failed", PubkyContactError.ActiveSubscription) + val expected = PubkyContactError.ActiveProfileSubscriptions(1_800_000_000_000L) + val wrapped = IllegalStateException("Service operation failed", expected) whenever(pubkyService.removeContactsForProfile(any())).thenAnswer { throw wrapped } clearInvocations(pubkyStore) - assertSame(PubkyContactError.ActiveSubscription, sut.deleteProfile().exceptionOrNull()) + assertSame(expected, sut.deleteProfile().exceptionOrNull()) assertEquals(listOf(VALID_CONTACT_KEY_A), sut.contacts.value.map { it.publicKey }) verify(pubkyStore, never()).update(any()) diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt index b9d07e0483..878a42e4ea 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt @@ -96,6 +96,7 @@ import to.bitkit.repositories.PubkyContactError import to.bitkit.services.PaykitSdkOperationLock.Priority import to.bitkit.test.forEachCase import to.bitkit.utils.AppError +import java.time.Instant import kotlin.coroutines.cancellation.CancellationException import kotlin.test.assertContentEquals import kotlin.test.assertEquals @@ -2090,8 +2091,8 @@ class PaykitSdkServiceTest { val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } assertFailsWith { service.removeContact(RING_PUBKY) } assertTrue(service.removeContacts(listOf(RING_PUBKY)).isEmpty()) - assertFailsWith { service.checkProfileDeletionAllowed() } - assertFailsWith { + assertFailsWith { service.checkProfileDeletionAllowed() } + assertFailsWith { service.removeContactsForProfile(listOf(RING_PUBKY, "pubkyunrelated")) } verify(sdk, never()).blockPeer(any()) @@ -2126,14 +2127,49 @@ class PaykitSdkServiceTest { whenever(sdk.paymentRequests()).thenReturn(listOf(request)) val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } - assertFailsWith { service.checkProfileDeletionAllowed() } - assertFailsWith { + assertFailsWith { service.checkProfileDeletionAllowed() } + assertFailsWith { service.removeContactsForProfile(listOf("pubkyunrelated")) } verify(sdk, never()).removeContactsAndBlockPeers(any()) } } + @Test + fun `profile refusal reports a date only when every blocking subscription has a finite end`() = runTest { + val earlier = "2999-01-01T00:00:00Z" + val later = "3000-01-01T00:00:00Z" + val cases = listOf( + listOf(earlier, later) to later, + listOf(later, earlier) to later, + listOf(earlier, null) to null, + listOf("invalid", later) to null, + listOf("2000-01-01T00:00:00Z", later) to later, + ) + for ((ends, expected) in cases) { + val sdk = mock() + val requests = ends.map { end -> + val recurrence = mock { on { endsAt } doReturn end } + val terms = mock { on { this.recurrence } doReturn recurrence } + mock { + on { state } doReturn PaymentRequestLifecycleState.ACTIVE_RECURRING + on { this.terms } doReturn terms + } + } + whenever(sdk.paymentRequests()).thenReturn(requests) + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + val refusal = assertFailsWith { + service.checkProfileDeletionAllowed() + } + assertEquals(expected?.let { Instant.parse(it).toEpochMilli() }, refusal.endsAtMillis) + val lateRefusal = assertFailsWith { + service.removeContactsForProfile(listOf(RING_PUBKY)) + } + assertEquals(refusal.endsAtMillis, lateRefusal.endsAtMillis) + verify(sdk, never()).removeContactsAndBlockPeers(any()) + } + } + @Test fun `profile removal fails closed when subscriptions cannot be read`() = runTest { val sdk = mock() diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt index 7045867cb3..3e5c1da83d 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt @@ -21,6 +21,7 @@ import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.R +import to.bitkit.ext.toLocalizedTimestamp import to.bitkit.models.PubkyProfile import to.bitkit.models.PubkyProfileLink import to.bitkit.repositories.PrivatePaykitRepo @@ -28,6 +29,7 @@ import to.bitkit.repositories.PubkyContactError import to.bitkit.repositories.PubkyRepo import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError +import java.util.Locale import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -65,6 +67,32 @@ class EditProfileViewModelTest : BaseUnitTest() { assertFalse(sut.uiState.value.isDeleting) } + @Test + fun `fixed term refusal displays the supplied expiry without starting cleanup`() = test { + val previousLocale = Locale.getDefault() + Locale.setDefault(Locale.US) + try { + val sut = createSut() + val endsAt = 1_800_000_000_000L + whenever(pubkyRepo.checkProfileDeletionAllowed()).thenReturn( + Result.failure(PubkyContactError.ActiveProfileSubscriptions(endsAt)), + ) + advanceUntilIdle() + + sut.deleteProfile() + advanceUntilIdle() + + verify(context).getString(R.string.profile__delete_active_subscription) + verify(context).getString(R.string.subscriptions__expires_date, endsAt.toLocalizedTimestamp()) + verify(privatePaykitRepo, never()).beginProfileDeletion() + verify(privatePaykitRepo, never()).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) + verify(pubkyRepo, never()).deleteProfile() + assertFalse(sut.uiState.value.showDeleteFailureDialog) + } finally { + Locale.setDefault(previousLocale) + } + } + @Test fun `unavailable subscription read retains cleanup and shows failure`() = test { val sut = createSut() diff --git a/changelog.d/next/1690.fixed.md b/changelog.d/next/1690.fixed.md index ee2cf196bc..1ff078f5b7 100644 --- a/changelog.d/next/1690.fixed.md +++ b/changelog.d/next/1690.fixed.md @@ -1 +1 @@ -Preserve profile data when cleanup is incomplete and explain when active subscriptions prevent removal. +Preserve profile data when cleanup is incomplete and explain when active subscriptions prevent removal. Show a known expiry instead of asking users to cancel fixed-term subscriptions. 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 0dcad96fb2991bea01d60934c47f049ce7b286f4 Mon Sep 17 00:00:00 2001 From: benk10 Date: Thu, 29 Oct 2026 14:20:22 +0200 Subject: [PATCH 21/61] fix: offer original-owner local disconnect after removal refusal --- .../bitkit/ui/components/ProfileEditForm.kt | 2 + .../ui/screens/profile/EditProfileScreen.kt | 23 ++++ .../screens/profile/EditProfileViewModel.kt | 18 ++- .../usecases/ProfileRemovalCoordinator.kt | 8 ++ app/src/main/res/values-ar/strings.xml | 2 +- app/src/main/res/values-b+es+419/strings.xml | 2 +- app/src/main/res/values-ca/strings.xml | 2 +- app/src/main/res/values-cs/strings.xml | 2 +- app/src/main/res/values-de/strings.xml | 2 +- app/src/main/res/values-el/strings.xml | 2 +- app/src/main/res/values-es-rES/strings.xml | 2 +- app/src/main/res/values-es/strings.xml | 2 +- app/src/main/res/values-fr/strings.xml | 2 +- app/src/main/res/values-it/strings.xml | 2 +- app/src/main/res/values-nl/strings.xml | 2 +- app/src/main/res/values-pl/strings.xml | 2 +- app/src/main/res/values-pt-rBR/strings.xml | 2 +- app/src/main/res/values-pt/strings.xml | 2 +- app/src/main/res/values-ru/strings.xml | 2 +- app/src/main/res/values/strings.xml | 2 +- .../profile/EditProfileViewModelTest.kt | 53 +++++++++ .../usecases/ProfileRemovalCoordinatorTest.kt | 109 ++++++++++++++++++ changelog.d/next/1693.fixed.md | 2 +- .../profile/profile-fixed-term-disconnect.xml | 23 ++++ 24 files changed, 252 insertions(+), 18 deletions(-) create mode 100644 journeys/profile/profile-fixed-term-disconnect.xml diff --git a/app/src/main/java/to/bitkit/ui/components/ProfileEditForm.kt b/app/src/main/java/to/bitkit/ui/components/ProfileEditForm.kt index ba463f8eb7..ab9ff68bc1 100644 --- a/app/src/main/java/to/bitkit/ui/components/ProfileEditForm.kt +++ b/app/src/main/java/to/bitkit/ui/components/ProfileEditForm.kt @@ -90,6 +90,7 @@ fun ProfileEditForm( deleteLabel: String = "", deleteSectionLabel: String? = null, @DrawableRes deleteIcon: Int = R.drawable.ic_trash, + additionalActions: @Composable () -> Unit = {}, ) { val isBusy = isSaving || isDeleting val resolvedPublicKeyLabel = publicKeyLabel ?: stringResource(R.string.profile__your_pubky) @@ -263,6 +264,7 @@ fun ProfileEditForm( } } + additionalActions() VerticalSpacer(footerHeight + 16.dp) } diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt index bb5728a27e..f50800f57c 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt @@ -32,10 +32,13 @@ import kotlinx.collections.immutable.persistentListOf import to.bitkit.R import to.bitkit.ui.components.AddLinkSheet import to.bitkit.ui.components.AddTagSheet +import to.bitkit.ui.components.BodyS import to.bitkit.ui.components.GradientCircularProgressIndicator import to.bitkit.ui.components.ProfileEditForm import to.bitkit.ui.components.ProfileEditLink import to.bitkit.ui.components.PubkyImage +import to.bitkit.ui.components.SecondaryButton +import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.scaffold.AppAlertDialog import to.bitkit.ui.scaffold.AppTopBar import to.bitkit.ui.scaffold.DrawerNavIcon @@ -78,6 +81,7 @@ fun EditProfileScreen( onRetryDelete = viewModel::retryDeleteProfile, onDismissDeleteFailureDialog = viewModel::dismissDeleteFailureDialog, onDisconnectProfile = viewModel::disconnectProfile, + onLocalDisconnect = viewModel::showLocalDisconnectConfirmation, onDismissAddLinkSheet = viewModel::dismissAddLinkSheet, onSaveLink = viewModel::addLink, onDismissAddTagSheet = viewModel::dismissAddTagSheet, @@ -104,6 +108,7 @@ internal fun EditProfileContent( onRetryDelete: () -> Unit, onDismissDeleteFailureDialog: () -> Unit, onDisconnectProfile: () -> Unit, + onLocalDisconnect: () -> Unit, onDismissAddLinkSheet: () -> Unit, onSaveLink: (String, String) -> Unit, onDismissAddTagSheet: () -> Unit, @@ -180,6 +185,22 @@ internal fun EditProfileContent( deleteLabel = stringResource(removal.label), deleteSectionLabel = stringResource(removal.sectionLabel), deleteIcon = removal.icon, + additionalActions = { + if (uiState.canDisconnectLocally) { + VerticalSpacer(16.dp) + BodyS( + text = stringResource(R.string.profile__disconnect_local_description), + color = Colors.White64, + ) + VerticalSpacer(12.dp) + SecondaryButton( + text = stringResource(R.string.profile__sign_out), + enabled = !uiState.isBusy, + onClick = onLocalDisconnect, + modifier = Modifier.testTag("ProfileLocalDisconnect") + ) + } + }, ) } } @@ -201,6 +222,7 @@ internal fun EditProfileContent( ), onConfirm = onConfirmDelete, onDismiss = onDismissDeleteDialog, + confirmTestTag = if (uiState.isLocalDisconnect) "ProfileLocalDisconnectConfirm" else "DialogConfirm", ) } @@ -306,6 +328,7 @@ private fun Preview() { onRetryDelete = {}, onDismissDeleteFailureDialog = {}, onDisconnectProfile = {}, + onLocalDisconnect = {}, onDismissAddLinkSheet = {}, onSaveLink = { _, _ -> }, onDismissAddTagSheet = {}, diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt index eeb3b43f83..d6db9f27e8 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt @@ -296,9 +296,23 @@ class EditProfileViewModel @Inject constructor( } } + fun showLocalDisconnectConfirmation() { + if (_uiState.value.isBusy || !_uiState.value.canDisconnectLocally) return + viewModelScope.launch { + prepareConfirmation(screenOwner) { removalCoordinator.prepareLocalDisconnect(screenOwner) } + } + } + private suspend fun performRemoval(confirmation: ProfileRemovalConfirmation) { if (_uiState.value.isBusy) return - _uiState.update { it.copy(showDeleteDialog = false, showDeleteFailureDialog = false, isDeleting = true) } + _uiState.update { + it.copy( + showDeleteDialog = false, + showDeleteFailureDialog = false, + canDisconnectLocally = false, + isDeleting = true, + ) + } try { removalCoordinator.remove(confirmation).onSuccess { endedOwner -> removalFailure = null @@ -343,6 +357,7 @@ class EditProfileViewModel @Inject constructor( private suspend fun showRemovalError(error: Throwable) { if (error == PubkyContactError.ActiveSubscription) { + _uiState.update { it.copy(canDisconnectLocally = true) } ToastEventBus.send( Toast.ToastType.ERROR, context.getString(R.string.profile__delete_error_title), @@ -377,6 +392,7 @@ data class EditProfileUiState( val isDeleting: Boolean = false, val isPreparingRemoval: Boolean = false, val isLocalDisconnect: Boolean = false, + val canDisconnectLocally: Boolean = false, val canReviewRemoval: Boolean = true, val showDeleteDialog: Boolean = false, val showDeleteFailureDialog: Boolean = false, diff --git a/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt b/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt index 80b46f6cef..ad50d9993a 100644 --- a/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt +++ b/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt @@ -97,6 +97,14 @@ class ProfileRemovalCoordinator @Inject constructor( ) } + suspend fun prepareLocalDisconnect(owner: PubkyProfileOwner): Result = + runSuspendCatching { + check(pubkyRepo.isProfileOwnerCurrent(owner)) { "The profile identity changed" } + removalStore.requireNoPending() + check(pubkyRepo.isProfileOwnerCurrent(owner)) { "The profile identity changed" } + ProfileRemovalConfirmation(owner, UUID.randomUUID().toString(), deletion = null, localOnly = true) + } + suspend fun prepareLocalDisconnect(failure: ProfileRemovalFailure): Result = runSuspendCatching { val pending = removalStore.pendingAttempt() diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index aac82188d8..c52d921422 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -386,7 +386,7 @@ لم يكتمل تنظيف الملف الشخصي. افصل الاتصال محليًا لإزالة وصول هذا الجهاز دون إعادة محاولة الحذف عن بُعد. إنشاء ملف شخصي قد تكون بعض التغييرات قد اكتملت. راجع الحالة الحالية قبل التأكيد مجددًا، أو افصل الاتصال محليًا. - أزل وصول هذا الجهاز وأكمل التنظيف المحلي. لن يؤدي هذا إلى حذف الملف الشخصي من Pubky. + أزل وصول هذا الجهاز وأكمل التنظيف المحلي. لا يُجري هذا أي تغييرات إضافية على ملفك الشخصي أو اشتراكاتك أو صلاحيات وصولك على الخادم. الملف الشخصي حاول مرة أخرى مراجعة diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index fb4331b144..33c13e89c2 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -397,7 +397,7 @@ La limpieza del perfil está incompleta. Desconéctate localmente para retirar el acceso de este dispositivo sin volver a intentar la eliminación remota. Crear perfil Es posible que algunos cambios se hayan completado. Revisa el estado actual antes de confirmar de nuevo o desconéctate localmente. - Retira el acceso de este dispositivo y completa la limpieza local. Esto no elimina el perfil de Pubky. + Elimina el acceso de este dispositivo y finaliza la limpieza local. Esto no realiza más cambios en tu perfil, tus suscripciones ni tu acceso en el servidor. Editar Perfil Perfil Inténtelo de nuevo diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 350232d150..f55ae14bf5 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -392,7 +392,7 @@ La neteja del perfil és incompleta. Desconnecta localment per eliminar l’accés d’aquest dispositiu sense tornar a intentar la supressió remota. Crear perfil És possible que alguns canvis s’hagin completat. Revisa l’estat actual abans de tornar a confirmar, o desconnecta localment. - Elimina l’accés d’aquest dispositiu i completa la neteja local. Això no suprimeix el perfil de Pubky. + Elimina l’accés d’aquest dispositiu i acaba la neteja local. Això no fa cap altre canvi al perfil, les subscripcions ni l’accés al servidor. Editar perfil Perfil Torna a intentar diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 712fd0fb3f..ff33c28343 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -397,7 +397,7 @@ Vyčištění profilu není dokončeno. Odpojte se místně a odeberte přístup tohoto zařízení bez dalšího pokusu o vzdálené smazání. Vytvořit profil Některé změny již mohly být dokončeny. Před dalším potvrzením zkontrolujte aktuální stav nebo se odpojte místně. - Odeberte přístup tohoto zařízení a dokončete místní vyčištění. Tím se profil z Pubky nesmaže. + Odeberte přístup tohoto zařízení a dokončete místní vyčištění. Tím se neprovedou žádné další změny vašeho profilu, předplatných ani přístupu na serveru. Upravit profil Profil Zkusit znovu diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 4b5bb1021a..d4932e73de 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -378,7 +378,7 @@ Die Profilbereinigung ist unvollständig. Trenne die Verbindung lokal, um den Zugriff dieses Geräts zu entfernen, ohne die entfernte Löschung erneut zu versuchen. Profil erstellen Einige Änderungen wurden möglicherweise abgeschlossen. Prüfe den aktuellen Stand vor einer erneuten Bestätigung oder trenne die Verbindung lokal. - Entferne den Zugriff dieses Geräts und schließe die lokale Bereinigung ab. Dadurch wird das Profil nicht aus Pubky gelöscht. + Entferne den Zugriff dieses Geräts und schließe die lokale Bereinigung ab. Dadurch werden keine weiteren Änderungen an deinem Profil, deinen Abonnements oder deinem Zugriff auf dem Server vorgenommen. Profil bearbeiten Profil Erneut versuchen diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 709c1b5668..dddcdbacdc 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -386,7 +386,7 @@ Η εκκαθάριση του προφίλ δεν ολοκληρώθηκε. Αποσυνδεθείτε τοπικά για να καταργήσετε την πρόσβαση αυτής της συσκευής χωρίς νέα προσπάθεια απομακρυσμένης διαγραφής. Δημιουργία προφίλ Ορισμένες αλλαγές ενδέχεται να έχουν ολοκληρωθεί. Ελέγξτε την τρέχουσα κατάσταση πριν επιβεβαιώσετε ξανά ή αποσυνδεθείτε τοπικά. - Καταργήστε την πρόσβαση αυτής της συσκευής και ολοκληρώστε την τοπική εκκαθάριση. Αυτό δεν διαγράφει το προφίλ από το Pubky. + Αφαιρέστε την πρόσβαση αυτής της συσκευής και ολοκληρώστε την τοπική εκκαθάριση. Αυτό δεν κάνει άλλες αλλαγές στο προφίλ, τις συνδρομές ή την πρόσβασή σας στον διακομιστή. Προφίλ Προσπαθήστε Ξανά Έλεγχος diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index dea38e7b58..506b36a2dc 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -394,7 +394,7 @@ La limpieza del perfil está incompleta. Desconéctate localmente para retirar el acceso de este dispositivo sin volver a intentar la eliminación remota. Crear perfil Es posible que algunos cambios se hayan completado. Revisa el estado actual antes de confirmar de nuevo o desconéctate localmente. - Retira el acceso de este dispositivo y completa la limpieza local. Esto no elimina el perfil de Pubky. + Elimina el acceso de este dispositivo y finaliza la limpieza local. Esto no realiza más cambios en tu perfil, tus suscripciones ni tu acceso en el servidor. Editar Perfil Perfil Inténtelo de nuevo diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 5dfe5cefed..34ccf0dca1 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -391,7 +391,7 @@ La limpieza del perfil está incompleta. Desconéctate localmente para retirar el acceso de este dispositivo sin volver a intentar la eliminación remota. Crear perfil Es posible que algunos cambios se hayan completado. Revisa el estado actual antes de confirmar de nuevo o desconéctate localmente. - Retira el acceso de este dispositivo y completa la limpieza local. Esto no elimina el perfil de Pubky. + Elimina el acceso de este dispositivo y finaliza la limpieza local. Esto no realiza más cambios en tu perfil, tus suscripciones ni tu acceso en el servidor. Editar Perfil Perfil Inténtelo de nuevo diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 64b6799258..d8aaa40fed 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -378,7 +378,7 @@ Le nettoyage du profil est incomplet. Déconnectez-vous localement pour retirer l’accès de cet appareil sans réessayer la suppression à distance. Créer un profil Certaines modifications ont peut-être été effectuées. Vérifiez l’état actuel avant de confirmer à nouveau, ou déconnectez-vous localement. - Retirez l’accès de cet appareil et terminez le nettoyage local. Cela ne supprime pas le profil de Pubky. + Retirez l’accès de cet appareil et terminez le nettoyage local. Cela n’apporte aucune autre modification à votre profil, à vos abonnements ou à votre accès sur le serveur. Modifier le profil Profil Réessayer diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 46e5d0de3a..612a447878 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -393,7 +393,7 @@ La pulizia del profilo è incompleta. Disconnettiti localmente per rimuovere l’accesso di questo dispositivo senza ritentare l’eliminazione remota. Crea Profilo Alcune modifiche potrebbero essere state completate. Verifica lo stato attuale prima di confermare di nuovo, oppure disconnettiti localmente. - Rimuovi l’accesso di questo dispositivo e completa la pulizia locale. Il profilo non verrà eliminato da Pubky. + Rimuovi l’accesso di questo dispositivo e completa la pulizia locale. Questa operazione non apporta ulteriori modifiche al profilo, agli abbonamenti o all’accesso sul server. Modifica Profilo Profilo Riprova diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index b73585d04f..b3c45f5dd7 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -391,7 +391,7 @@ Het opschonen van het profiel is niet voltooid. Verbreek lokaal de verbinding om de toegang van dit apparaat te verwijderen zonder de verwijdering op afstand opnieuw te proberen. Profiel aanmaken Sommige wijzigingen zijn mogelijk voltooid. Controleer de huidige status voordat je opnieuw bevestigt, of verbreek lokaal de verbinding. - Verwijder de toegang van dit apparaat en voltooi het lokaal opschonen. Dit verwijdert het profiel niet uit Pubky. + Verwijder de toegang van dit apparaat en voltooi de lokale opschoning. Dit brengt geen verdere wijzigingen aan in je profiel, abonnementen of toegang op de server. Profiel Bewerken Profiel Probeer opnieuw diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 1cd5959170..3b9863befb 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -378,7 +378,7 @@ Czyszczenie profilu nie zostało ukończone. Odłącz się lokalnie, aby usunąć dostęp tego urządzenia bez ponawiania zdalnego usuwania. Utwórz profil Niektóre zmiany mogły zostać ukończone. Sprawdź bieżący stan przed ponownym potwierdzeniem lub odłącz się lokalnie. - Usuń dostęp tego urządzenia i dokończ lokalne czyszczenie. Nie spowoduje to usunięcia profilu z Pubky. + Usuń dostęp tego urządzenia i zakończ lokalne czyszczenie. Nie wprowadzi to dalszych zmian w profilu, subskrypcjach ani dostępie na serwerze. Edytuj profil Profil Spróbuj ponownie diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 458cc9928d..3ce14d1b99 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -398,7 +398,7 @@ A limpeza do perfil está incompleta. Desconecte-se localmente para remover o acesso deste dispositivo sem tentar novamente a exclusão remota. Criar Perfil Algumas alterações podem ter sido concluídas. Revise o estado atual antes de confirmar novamente ou desconecte-se localmente. - Remova o acesso deste dispositivo e conclua a limpeza local. Isso não exclui o perfil do Pubky. + Remova o acesso deste dispositivo e conclua a limpeza local. Isso não faz outras alterações no seu perfil, nas assinaturas ou no acesso no servidor. Editar perfil Perfil Tente novamente diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 525d3de757..f39c7bfe46 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -356,7 +356,7 @@ A limpeza do perfil está incompleta. Desligue-se localmente para remover o acesso deste dispositivo sem voltar a tentar a eliminação remota. Criar Perfil Algumas alterações poderão ter sido concluídas. Reveja o estado atual antes de confirmar novamente ou desligue-se localmente. - Remova o acesso deste dispositivo e conclua a limpeza local. Isto não elimina o perfil do Pubky. + Remove o acesso deste dispositivo e conclui a limpeza local. Isto não faz mais alterações ao teu perfil, às subscrições ou ao acesso no servidor. Perfil Tente novamente Rever diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 413256ba81..34e5d88ec4 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -409,7 +409,7 @@ Очистка профиля не завершена. Отключитесь локально, чтобы убрать доступ этого устройства без повторной попытки удалённого удаления. Создать Профиль Некоторые изменения могли быть выполнены. Проверьте текущее состояние перед повторным подтверждением или отключитесь локально. - Уберите доступ этого устройства и завершите локальную очистку. Профиль в Pubky удалён не будет. + Удалите доступ этого устройства и завершите локальную очистку. Это не вносит дополнительных изменений в ваш профиль, подписки или доступ на сервере. Редактировать Профиль Профиль Попробовать снова diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index d77281e861..ba81a01fd3 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -641,7 +641,7 @@ Profile deleted Deriving your keys… Failed to disconnect profile - Remove this device’s access and finish local cleanup. This does not delete the profile from Pubky. + Remove this device’s access and finish local cleanup. This makes no further changes to your profile, subscriptions or access on the server. BIO Short note. Tell a bit about yourself. DELETE diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt index 040da7ead7..323cb23cba 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt @@ -58,11 +58,63 @@ class EditProfileViewModelTest : BaseUnitTest() { } assertFalse(sut.uiState.value.showDeleteDialog) assertFalse(sut.uiState.value.showDeleteFailureDialog) + assertTrue(sut.uiState.value.canDisconnectLocally) assertNull(fixture.store.pendingAttempt()) verify(fixture.privateRepo, never()).withProfileDeletionPaused(any()) verify(pubkyRepo, never()).deleteProfile(any()) } + @Test + fun `subscription refusal offers fresh local confirmation without remote cleanup`() = test { + val sut = createSut() + whenever(pubkyRepo.prepareProfileDeletion(fixture.original)) + .thenReturn(Result.failure(PubkyContactError.ActiveSubscription)) + advanceUntilIdle() + sut.showLocalDisconnectConfirmation() + advanceUntilIdle() + assertFalse(sut.uiState.value.showDeleteDialog) + sut.showDeleteConfirmation() + advanceUntilIdle() + sut.showLocalDisconnectConfirmation() + advanceUntilIdle() + assertTrue(sut.uiState.value.showDeleteDialog) + assertTrue(sut.uiState.value.isLocalDisconnect) + assertNull(fixture.store.pendingAttempt()) + sut.dismissDeleteDialog() + sut.deleteProfile() + advanceUntilIdle() + verify(pubkyRepo, never()).finishProfileRemovalLocally() + sut.showLocalDisconnectConfirmation() + advanceUntilIdle() + sut.effects.test { + sut.deleteProfile() + advanceUntilIdle() + assertIs(awaitItem()) + } + verify(pubkyRepo, times(1)).prepareProfileDeletion(fixture.original) + verify(pubkyRepo, never()).deleteProfile(any()) + verify(pubkyRepo, never()).removeBitkitPaymentEndpoints() + verify(pubkyRepo, never()).signOutForProfileRemoval() + verify(fixture.privateRepo, never()).removePublishedEndpointsForCleanup(any(), any()) + assertNull(fixture.store.pendingAttempt()) + } + + @Test + fun `fresh local disconnect never recaptures the replacement screen owner`() = test { + val sut = createSut() + whenever(pubkyRepo.prepareProfileDeletion(fixture.original)) + .thenReturn(Result.failure(PubkyContactError.ActiveSubscription)) + advanceUntilIdle() + sut.showDeleteConfirmation() + advanceUntilIdle() + fixture.current = PubkyProfileOwner(PubkySignIn(TEST_PUBLIC_KEY, 3), 3) + sut.showLocalDisconnectConfirmation() + advanceUntilIdle() + assertFalse(sut.uiState.value.showDeleteDialog) + assertNull(fixture.store.pendingAttempt()) + verify(pubkyRepo, never()).finishProfileRemovalLocally() + } + @Test fun `subscription beginning after confirmation prevents endpoint withdrawal and marker`() = test { val sut = createSut() @@ -78,6 +130,7 @@ class EditProfileViewModelTest : BaseUnitTest() { } assertNull(fixture.store.pendingAttempt()) assertFalse(sut.uiState.value.showDeleteFailureDialog) + assertTrue(sut.uiState.value.canDisconnectLocally) verify(fixture.privateRepo, never()).removePublishedEndpointsForCleanup(any(), any()) verify(pubkyRepo, never()).deleteProfile(any()) } diff --git a/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt b/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt index fd7718f234..8839f1fe11 100644 --- a/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt +++ b/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt @@ -7,6 +7,7 @@ import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.async import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flow import org.junit.Before import org.junit.Test import org.mockito.kotlin.any @@ -136,6 +137,114 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { } } + @Test + fun `fresh local disconnect reads no remote state and clears only after confirmation`() = test { + val confirmation = sut.prepareLocalDisconnect(original).getOrThrow() + assertTrue(confirmation.localOnly) + assertNull(confirmation.deletion) + assertNull(store.pendingAttempt()) + assertTrue(events.isEmpty()) + verify(pubky, never()).prepareProfileDeletion(any()) + assertSame(ended, sut.remove(confirmation).getOrThrow()) + assertEquals( + listOf("local credentials and metadata", "private local", "wallet backup ready", "backup ready"), + events, + ) + verify(privateRepo, never()).removePublishedEndpointsForCleanup(any(), any()) + verify(pubky, never()).removeBitkitPaymentEndpoints() + verify(pubky, never()).deleteProfile(any()) + verify(pubky, never()).signOutForProfileRemoval() + assertTrue(sut.remove(confirmation).isFailure) + assertNull(store.pendingAttempt()) + } + + @Test + fun `fresh local disconnect retains private watermarks when credential forget fails`() = test { + doSuspendableAnswer { + throw IOException("credential store unavailable") + }.whenever(pubky).finishProfileRemovalLocally() + val confirmation = sut.prepareLocalDisconnect(original).getOrThrow() + val failure = assertIs(sut.remove(confirmation).exceptionOrNull()) + assertSame(confirmation, failure.confirmation) + assertEquals(confirmation.attemptId, store.pendingAttempt()) + verify(privateRepo, never()).finishProfileRemoval(any()) + verify(privateRepo, never()).notifyProfileRemovalCompleted(any()) + verify(pubky, never()).signOutForProfileRemoval() + } + + @Test + fun `fresh local disconnect cannot prepare when pending state is unreadable`() = test { + val failure = IOException("pending store unavailable") + store = ProfileRemovalStore(object : DataStore { + override val data = flow { throw failure } + override suspend fun updateData( + transform: suspend (ProfileRemovalState) -> ProfileRemovalState + ): ProfileRemovalState = error("Preparation must not write removal state") + }) + assertSame(failure, sut.prepareLocalDisconnect(original).exceptionOrNull()) + assertTrue(events.isEmpty()) + verify(pubky, never()).performProfileRemoval(any(), any(), any()) + verify(pubky, never()).finishProfileRemovalLocally() + verify(privateRepo, never()).finishProfileRemoval(any()) + verify(pubky, never()).deleteProfile(any()) + verify(pubky, never()).signOutForProfileRemoval() + } + + @Test + fun `fresh local disconnect cannot clear credentials when durable begin fails`() = test { + val failure = IOException("pending marker not acknowledged") + var writes = 0 + store = ProfileRemovalStore(object : DataStore { + override val data = MutableStateFlow(ProfileRemovalState()) + override suspend fun updateData( + transform: suspend (ProfileRemovalState) -> ProfileRemovalState + ): ProfileRemovalState { + writes++ + throw failure + } + }) + val confirmation = sut.prepareLocalDisconnect(original).getOrThrow() + val result = assertIs(sut.remove(confirmation).exceptionOrNull()) + assertSame(failure, result.cause) + assertEquals(1, writes) + assertNull(store.pendingAttempt()) + assertTrue(events.isEmpty()) + verify(pubky, never()).finishProfileRemovalLocally() + verify(privateRepo, never()).finishProfileRemoval(any()) + verify(privateRepo, never()).removePublishedEndpointsForCleanup(any(), any()) + verify(pubky, never()).removeBitkitPaymentEndpoints() + verify(pubky, never()).deleteProfile(any()) + verify(pubky, never()).signOutForProfileRemoval() + assertTrue(sut.remove(confirmation).isFailure) + assertEquals(1, writes) + } + + @Test + fun `fresh local disconnect rejects replacement owner and unrelated pending cleanup`() = test { + current = PubkyProfileOwner(PubkySignIn("identity", 3), 3) + assertTrue(sut.prepareLocalDisconnect(original).isFailure) + current = original + val pending = UUID.randomUUID().toString() + store.withAccess(pending) { store.begin(pending) } + assertTrue(sut.prepareLocalDisconnect(original).isFailure) + assertEquals(pending, store.pendingAttempt()) + assertTrue(events.isEmpty()) + } + + @Test + fun `fresh local confirmation cannot clear a replacement or another pending attempt`() = test { + val confirmation = sut.prepareLocalDisconnect(original).getOrThrow() + current = PubkyProfileOwner(PubkySignIn("identity", 3), 3) + assertTrue(sut.remove(confirmation).isFailure) + current = original + val second = sut.prepareLocalDisconnect(original).getOrThrow() + val pending = UUID.randomUUID().toString() + store.withAccess(pending) { store.begin(pending) } + assertTrue(sut.remove(second).isFailure) + assertEquals(pending, store.pendingAttempt()) + assertTrue(events.isEmpty()) + } + @Test fun `confirmed removal acknowledges credentials before clearing private state and clears marker last`() = test { val confirmation = sut.prepareDeletion(original).getOrThrow() diff --git a/changelog.d/next/1693.fixed.md b/changelog.d/next/1693.fixed.md index 3c8ab81c1c..170ae7beb9 100644 --- a/changelog.d/next/1693.fixed.md +++ b/changelog.d/next/1693.fixed.md @@ -1 +1 @@ -Keep interrupted profile removal recoverable without changing replacement identities or losing incoming payment details, and show recovery options that match the pending wallet state. +Keep interrupted profile removal recoverable without changing replacement identities or losing incoming payment details, and show recovery options that match the pending wallet state and allow a separately confirmed local disconnect when subscriptions prevent profile removal. diff --git a/journeys/profile/profile-fixed-term-disconnect.xml b/journeys/profile/profile-fixed-term-disconnect.xml new file mode 100644 index 0000000000..cfc1ffd477 --- /dev/null +++ b/journeys/profile/profile-fixed-term-disconnect.xml @@ -0,0 +1,23 @@ + + + Use a disposable authenticated identity with an accepted future fixed-term subscription and no + pending irreversible payment. Run separately as payer and payee, then repeat with a disposable + identity adopted from Pubky Ring for Unlink parity. Provision each fixture without live funds. + A controlled homeserver and independent authenticated peer must observe the original profile, + subscription, contacts, endpoints and session grant before and after the flow. Record app and + SDK revisions. The fixture and remote mutation journal are beyond standard runner capabilities. + To test late refusal, hold the original Delete/Unlink confirmation, then accept the subscription + independently before confirming; do not alter the app's eligibility result or cancellation policy. + A real post-marker failure belongs to the separate profile-removal-recovery journey. + + + Open the fixed-term subscription and verify End subscription is unavailable + Open Edit Profile and request Delete Profile, or Unlink pubky for a Ring identity; verify subscription refusal and truthful expiry guidance without remote mutation + Verify the separate Disconnect choice (id "ProfileLocalDisconnect") is visible and explains that this action only removes this device’s access and makes no further changes to the profile, subscriptions or access on the server + Choose Disconnect and verify a fresh local-only confirmation; cancel it and verify the original profile remains connected with no pending cleanup or remote mutation + Choose Disconnect again and confirm (id "ProfileLocalDisconnectConfirm"); verify profile onboarding appears only after required local cleanup completes, without claiming remote deletion + Using the independent peer and homeserver journal, verify that the original profile, subscription, contacts, endpoints and grant remain unchanged and no remote cleanup or cancellation was sent + Close and relaunch Bitkit; open Profile and verify onboarding remains visible with no restored credentials or automatic publication + For the Ring fixture, open Pubky Ring and verify the original identity and profile remain available + + From 4d6773427c08b6e78fb8ee6f114b6d0374bf8b71 Mon Sep 17 00:00:00 2001 From: benk10 Date: Thu, 29 Oct 2026 17:55:32 +0200 Subject: [PATCH 22/61] test: wire local disconnect in profile recovery content --- .../to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt b/app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt index d4fa93388a..506ee64ee1 100644 --- a/app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt +++ b/app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt @@ -129,6 +129,7 @@ class ProfileRecoveryContentTest { onAvatarSelected = {}, onAddLink = {}, onRemoveLink = {}, onAddTag = {}, onRemoveTag = {}, onSave = {}, onDelete = {}, onDismissDeleteDialog = {}, onConfirmDelete = onConfirm, onRetryDelete = onReview, onDismissDeleteFailureDialog = {}, onDisconnectProfile = onDisconnect, + onLocalDisconnect = { error("Fresh local disconnect is not part of this recovery scenario") }, onDismissAddLinkSheet = {}, onSaveLink = { _, _ -> }, onDismissAddTagSheet = {}, onSaveTag = {}, ) } From f311807ea0c489c05b910d40df07ce9041cd5658 Mon Sep 17 00:00:00 2001 From: benk10 Date: Fri, 30 Oct 2026 06:57:18 +0200 Subject: [PATCH 23/61] fix: require acknowledged private endpoint withdrawal --- .../bitkit/repositories/PrivatePaykitRepo.kt | 71 +++++++-- .../usecases/ProfileRemovalCoordinator.kt | 34 +++-- .../repositories/PaykitIssuerInteropTest.kt | 2 + .../PaykitPaymentProofRepoTest.kt | 2 + ...aykitPaymentRequestRepoSubscriptionTest.kt | 2 + .../PaykitPaymentRequestRepoTest.kt | 2 + .../repositories/PaykitUsdtPaymentRepoTest.kt | 2 + .../repositories/PrivatePaykitRepoTest.kt | 139 ++++++++++++++++++ .../bitkit/services/PaykitSdkServiceTest.kt | 15 +- .../profile/EditProfileViewModelTest.kt | 11 +- .../profile/ProfileRemovalUiFixture.kt | 3 +- .../screens/profile/ProfileViewModelTest.kt | 4 +- .../usecases/ProfileRemovalCoordinatorTest.kt | 34 ++++- changelog.d/next/1693.fixed.md | 2 +- gradle/libs.versions.toml | 2 +- 15 files changed, 280 insertions(+), 45 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt index d71160d999..3cad76d06b 100644 --- a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt @@ -559,10 +559,19 @@ class PrivatePaykitRepo @Inject constructor( suspend fun removePublishedEndpointsForCleanup( context: String, deferAppSync: Boolean, + ): Result = removePublishedEndpointsForCleanup(context, deferAppSync, requireAcknowledgement = false) + + suspend fun removePublishedEndpointsForProfileRemoval(): Result = + removePublishedEndpointsForCleanup("profile removal", deferAppSync = true, requireAcknowledgement = true) + + private suspend fun removePublishedEndpointsForCleanup( + context: String, + deferAppSync: Boolean, + requireAcknowledgement: Boolean, ): Result = withContext(serializedDispatcher) { runSuspendCatching { updateContactSharingCleanupPending(true) - removePublishedEndpoints().getOrThrow() + removePublishedEndpoints(requireAcknowledgement).getOrThrow() if (!deferAppSync) { syncPaykitAppAfterCleanup().getOrThrow() updateContactSharingCleanupPending(false) @@ -2063,13 +2072,14 @@ class PrivatePaykitRepo @Inject constructor( persistState(markWalletBackup = true) } - private suspend fun removePublishedEndpoints(): Result = withContext(serializedDispatcher) { - runSuspendCatching { - publicationMutex.withLock { - removePublishedEndpointsLocked().getOrThrow() + private suspend fun removePublishedEndpoints(requireAcknowledgement: Boolean = false): Result = + withContext(serializedDispatcher) { + runSuspendCatching { + publicationMutex.withLock { + removePublishedEndpointsLocked(requireAcknowledgement = requireAcknowledgement).getOrThrow() + } } } - } private suspend fun removePublishedEndpoints( publicKeys: Collection, @@ -2084,23 +2094,29 @@ class PrivatePaykitRepo @Inject constructor( private suspend fun removePublishedEndpointsLocked( publicKeys: Collection? = null, isStillCurrent: (() -> Boolean)? = null, + requireAcknowledgement: Boolean = false, ): Result = runSuspendCatching { checkPaykitContactSync(isStillCurrent) val peers = paykitSdkService.linkedPeers() checkPaykitContactSync(isStillCurrent) - val linkedPublicKeys = peers + val cleanupPeers = peers .filter { it.state == LinkedPeerState.LINKED || it.state == LinkedPeerState.LINKING || it.state == LinkedPeerState.RECOVERY_REQUIRED } - .mapNotNull { normalizedPublicKey(it.counterparty) } - .toSet() + if (requireAcknowledgement && cleanupPeers.any { normalizedPublicKey(it.counterparty) == null }) { + throw PrivatePaykitError.PrivateUnavailable + } + val linkedPublicKeys = cleanupPeers.mapNotNull { normalizedPublicKey(it.counterparty) }.toSet() val keys = publicKeys ?: ( knownSavedContactKeys + ensureState().contacts.keys + pendingDeletedContactCleanupPublicKeys() + linkedPublicKeys ) val normalizedBatch = normalizedPublicKeyBatch(keys) + if (requireAcknowledgement && normalizedBatch.invalidKeys.isNotEmpty()) { + throw PrivatePaykitError.PrivateUnavailable + } discardInvalidCleanupKeys(normalizedBatch.invalidKeys, isStillCurrent) val normalizedKeys = normalizedBatch.normalizedKeys if (normalizedKeys.isEmpty()) return@runSuspendCatching @@ -2108,12 +2124,21 @@ class PrivatePaykitRepo @Inject constructor( ensureState() checkPaykitContactSync(isStillCurrent) val cleanupStateByPublicKey = normalizedKeys.associateWith(::publishedEndpointCleanupState) - val preparation = clearPrivatePaymentLists(normalizedKeys, linkedPublicKeys, isStillCurrent) + val preparation = clearPrivatePaymentLists( + normalizedKeys, + linkedPublicKeys, + isStillCurrent, + requireAcknowledgement, + ) checkPaykitContactSync(isStillCurrent) val failedPublicKeys = preparation.failedPublicKeys.toMutableSet() var firstError = preparation.firstError - val pendingRetryKeys = drainPendingEndpointWithdrawals(preparation.clearedRetryKeys, isStillCurrent) + val pendingRetryKeys = if (requireAcknowledgement) { + emptySet() + } else { + drainPendingEndpointWithdrawals(preparation.clearedRetryKeys, isStillCurrent) + } if (pendingRetryKeys.isNotEmpty()) { failedPublicKeys += pendingRetryKeys firstError = firstError ?: PrivatePaykitError.PrivateUnavailable @@ -2181,6 +2206,7 @@ class PrivatePaykitRepo @Inject constructor( publicKeys: Collection, linkedPublicKeys: Set, isStillCurrent: (() -> Boolean)? = null, + requireAcknowledgement: Boolean = false, ): PrivateEndpointCleanupPreparation { val cleanupKeys = publicKeys.filter { it in linkedPublicKeys || state?.contacts?.get(it)?.hasPublishedPrivatePaymentList == true @@ -2189,7 +2215,14 @@ class PrivatePaykitRepo @Inject constructor( return runSuspendCatching { val report = paykitSdkService.clearPrivatePaymentLists(cleanupKeys, isStillCurrent) - ?: return@runSuspendCatching PrivateEndpointCleanupPreparation(emptyList(), emptySet(), null) + if (requireAcknowledgement) { + if (report == null || !hasAcknowledgedWithdrawals(report, cleanupKeys)) { + throw PrivatePaykitError.PrivateUnavailable + } + } + if (report == null) { + return@runSuspendCatching PrivateEndpointCleanupPreparation(emptyList(), emptySet(), null) + } logPrivatePaymentListDeliveryFailures(report, "cleanup") val failedPublicKeys = ( report.failedToQueue.map { it.counterparty } + @@ -2208,6 +2241,20 @@ class PrivatePaykitRepo @Inject constructor( } } + private fun hasAcknowledgedWithdrawals( + report: PrivatePaymentListDeliveryReport, + publicKeys: Collection, + ): Boolean { + if (report.failedToQueue.isNotEmpty() || report.failedToDeliver.isNotEmpty()) return false + return publicKeys.all { publicKey -> + val clear = report.cleared.singleOrNull { normalizedPublicKey(it.counterparty) == publicKey } + val messageId = clear?.outboundMessageId + clear?.error == null && messageId != null && report.acknowledged.any { + normalizedPublicKey(it.counterparty) == publicKey && it.outboundMessageId == messageId + } + } + } + private suspend fun clearPublishedEndpointCache( publicKeys: Collection, isStillCurrent: (() -> Boolean)? = null, diff --git a/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt b/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt index ad50d9993a..5b269ff5c3 100644 --- a/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt +++ b/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt @@ -34,8 +34,10 @@ class ProfileRemovalFailure internal constructor( internal val confirmation: ProfileRemovalConfirmation, internal val recoveryOwner: PubkyProfileOwner, internal val localCompletionStarted: Boolean, + private val privateWithdrawalAcknowledged: Boolean, ) : AppError("Profile removal did not finish. Review its state or disconnect locally.", cause) { - internal val canReview: Boolean get() = confirmation.deletion != null && !localCompletionStarted + internal val canReview: Boolean + get() = confirmation.deletion != null && !localCompletionStarted && privateWithdrawalAcknowledged } /** Remote work never resumes automatically from the durable local cleanup obligation. */ @@ -69,7 +71,7 @@ class ProfileRemovalCoordinator @Inject constructor( /** Re-read the original identity's remote state, then require a new user confirmation. */ suspend fun reviewAgain(failure: ProfileRemovalFailure): Result = runSuspendCatching { - check(!failure.localCompletionStarted) { "Finish disconnecting this profile locally" } + check(failure.canReview) { "Finish disconnecting this profile locally" } val previous = failure.confirmation check(previous.deletion != null) { "Disconnect this profile locally to finish cleanup" } var deletion: PubkyProfileDeletion? = null @@ -126,6 +128,7 @@ class ProfileRemovalCoordinator @Inject constructor( sharingRepo.withProfileRemoval { pubkyRepo.performProfileRemoval(confirmation.owner, confirmation.attemptId) { var localCompletionStarted = false + var privateWithdrawalAcknowledged = false var removalMayHaveStarted = removalStore.pendingAttempt() != null try { check(confirmation.deletion == null || confirmation.reviewCeiling.get() === confirmation.deletion) { @@ -136,7 +139,8 @@ class ProfileRemovalCoordinator @Inject constructor( removalMayHaveStarted = true removalStore.begin(confirmation.attemptId) if (!confirmation.localOnly) { - privatePaykitRepo.removePublishedEndpointsForCleanup(TAG, deferAppSync = true).getOrThrow() + privatePaykitRepo.removePublishedEndpointsForProfileRemoval().getOrThrow() + privateWithdrawalAcknowledged = true pubkyRepo.removeBitkitPaymentEndpoints().getOrThrow() confirmation.deletion?.let { pubkyRepo.deleteProfile(it).getOrThrow() } pubkyRepo.signOutForProfileRemoval() @@ -152,11 +156,18 @@ class ProfileRemovalCoordinator @Inject constructor( } } } catch (error: CancellationException) { - if (removalMayHaveStarted) captureFailure(error, confirmation, localCompletionStarted) + if (removalMayHaveStarted) { + captureFailure( + error, + confirmation, + localCompletionStarted, + privateWithdrawalAcknowledged + ) + } throw error } catch (error: Throwable) { if (!removalMayHaveStarted) throw error - throw captureFailure(error, confirmation, localCompletionStarted) + throw captureFailure(error, confirmation, localCompletionStarted, privateWithdrawalAcknowledged) } }.getOrThrow() } @@ -166,9 +177,16 @@ class ProfileRemovalCoordinator @Inject constructor( error: Throwable, confirmation: ProfileRemovalConfirmation, localCompletionStarted: Boolean, + privateWithdrawalAcknowledged: Boolean, ): ProfileRemovalFailure { // Admission still excludes replacements, even when our own cleanup has ended the sign-in. - val failure = ProfileRemovalFailure(error, confirmation, pubkyRepo.profileOwner(), localCompletionStarted) + val failure = ProfileRemovalFailure( + error, + confirmation, + pubkyRepo.profileOwner(), + localCompletionStarted, + privateWithdrawalAcknowledged, + ) confirmation.failure.set(failure) return failure } @@ -176,8 +194,4 @@ class ProfileRemovalCoordinator @Inject constructor( fun failureFor(confirmation: ProfileRemovalConfirmation): ProfileRemovalFailure? = confirmation.failure.get() fun isCurrent(owner: PubkyProfileOwner): Boolean = pubkyRepo.isProfileOwnerCurrent(owner) - - private companion object { - const val TAG = "ProfileRemovalCoordinator" - } } diff --git a/app/src/test/java/to/bitkit/repositories/PaykitIssuerInteropTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitIssuerInteropTest.kt index a5febcda89..4c1ef3e79d 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitIssuerInteropTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitIssuerInteropTest.kt @@ -135,6 +135,7 @@ class PaykitIssuerInteropTest { ), acceptedEventId = null, acceptedOutboundStatus = null, + acceptanceRecordedAt = null, rejectedEventId = null, rejectedOutboundStatus = null, canceledEventId = null, @@ -147,6 +148,7 @@ class PaykitIssuerInteropTest { lastEventAt = NOW.toString(), invalidReason = null, proposalAppId = "bitkit", + proposalRecordedAt = null, payerAppId = null, executionClaimAppId = null, ) diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index c6f146bb78..ba0ae29a24 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -3652,6 +3652,7 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { ), acceptedEventId = null, acceptedOutboundStatus = null, + acceptanceRecordedAt = null, rejectedEventId = null, rejectedOutboundStatus = null, canceledEventId = null, @@ -3664,6 +3665,7 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { lastEventAt = "2027-01-15T08:00:00Z", invalidReason = null, proposalAppId = "bitkit", + proposalRecordedAt = null, payerAppId = null, executionClaimAppId = null, ) diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoSubscriptionTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoSubscriptionTest.kt index e51e73d959..e1ab27e870 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoSubscriptionTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoSubscriptionTest.kt @@ -1655,6 +1655,7 @@ class PaykitPaymentRequestRepoSubscriptionTest : BaseUnitTest(StandardTestDispat ), acceptedEventId = null, acceptedOutboundStatus = null, + acceptanceRecordedAt = null, rejectedEventId = null, rejectedOutboundStatus = null, canceledEventId = null, @@ -1667,6 +1668,7 @@ class PaykitPaymentRequestRepoSubscriptionTest : BaseUnitTest(StandardTestDispat lastEventAt = clock.now().toString(), invalidReason = null, proposalAppId = "bitkit", + proposalRecordedAt = null, payerAppId = null, executionClaimAppId = null, ) diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt index baf0390eaa..e77fd02072 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt @@ -3516,6 +3516,7 @@ class PaykitPaymentRequestRepoTest : BaseUnitTest(StandardTestDispatcher()) { ), acceptedEventId = null, acceptedOutboundStatus = null, + acceptanceRecordedAt = null, rejectedEventId = null, rejectedOutboundStatus = null, canceledEventId = null, @@ -3528,6 +3529,7 @@ class PaykitPaymentRequestRepoTest : BaseUnitTest(StandardTestDispatcher()) { lastEventAt = clock.now().toString(), invalidReason = null, proposalAppId = "bitkit", + proposalRecordedAt = null, payerAppId = null, executionClaimAppId = null, ) diff --git a/app/src/test/java/to/bitkit/repositories/PaykitUsdtPaymentRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitUsdtPaymentRepoTest.kt index e4f2795f08..e6ac738bd8 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitUsdtPaymentRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitUsdtPaymentRepoTest.kt @@ -804,6 +804,7 @@ class PaykitUsdtPaymentRepoTest : BaseUnitTest() { proposalStreamItemId = 1u, proposalOutboundMessageId = null, proposalOutboundStatus = null, proposalEventId = "proposal", proposalAppId = "bitkit", + proposalRecordedAt = null, payerAppId = "bitkit", executionClaimAppId = "bitkit", terms = PaymentRequestTerms( @@ -818,6 +819,7 @@ class PaykitUsdtPaymentRepoTest : BaseUnitTest() { mock() ), acceptedEventId = "accepted", acceptedOutboundStatus = null, + acceptanceRecordedAt = null, rejectedEventId = null, rejectedOutboundStatus = null, canceledEventId = null, canceledOutboundStatus = null, paymentProofs = listOf( diff --git a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt index d61ee95250..fd844efcd9 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt @@ -15,6 +15,7 @@ import com.synonym.paykit.OutboundPrivateSendReport import com.synonym.paykit.PaykitException import com.synonym.paykit.PaymentRequestLifecycleState import com.synonym.paykit.PrivateMessageSchedulingSnapshot +import com.synonym.paykit.PrivatePaymentListAcknowledgement import com.synonym.paykit.PrivatePaymentListDeliveryFailure import com.synonym.paykit.PrivatePaymentListDeliveryReport import com.synonym.paykit.PrivatePaymentListReservationUpdateInput @@ -2715,6 +2716,142 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { ) } + @Test + fun `profile removal requires a matching acknowledgement for every original clear`() = test { + val validClear = PrivatePaymentListSyncChange(CONTACT_KEY, 17uL, null) + val validAck = PrivatePaymentListAcknowledgement(CONTACT_KEY, 17uL) + val reports = listOf( + null, + privateListDeliveryReport(), + privateListDeliveryReport().copy(cleared = listOf(validClear)), + privateListDeliveryReport().copy(acknowledged = listOf(validAck)), + privateListDeliveryReport().copy( + cleared = listOf(validClear), + acknowledged = listOf(PrivatePaymentListAcknowledgement(OTHER_CONTACT_KEY, 17uL)), + ), + privateListDeliveryReport().copy( + cleared = listOf(validClear), + acknowledged = listOf(PrivatePaymentListAcknowledgement(CONTACT_KEY, 18uL)), + ), + privateListDeliveryReport().copy( + cleared = listOf(validClear.copy(outboundMessageId = null)), + acknowledged = listOf(validAck), + ), + privateListDeliveryReport().copy( + cleared = listOf(validClear.copy(error = mock())), + acknowledged = listOf(validAck), + ), + privateListDeliveryReport(failedToQueue = listOf(validClear)).copy( + cleared = listOf(validClear), + acknowledged = listOf(validAck), + ), + privateListDeliveryReport( + failedToDeliver = listOf(PrivatePaymentListDeliveryFailure(CONTACT_KEY, null, null, mock())), + ).copy(cleared = listOf(validClear), acknowledged = listOf(validAck)), + privateListDeliveryReport().copy( + cleared = listOf(validClear, validClear.copy(outboundMessageId = 18uL)), + acknowledged = listOf(validAck), + ), + ) + for ((index, report) in reports.withIndex()) { + cacheData.value = PrivatePaykitCacheData(contacts = mapOf(CONTACT_KEY to cachedPublishedContact())) + sut = createSut() + whenever(paykitSdkService.clearPrivatePaymentLists(listOf(CONTACT_KEY))).thenReturn(report) + + val result = sut.removePublishedEndpointsForProfileRemoval() + + assertTrue(result.isFailure, "Withdrawal report $index must remain unacknowledged") + assertTrue(cacheData.value.cleanupPending) + assertTrue(cacheData.value.contacts.getValue(CONTACT_KEY).hasPublishedPrivatePaymentList) + } + verify(publicPaykitRepo, never()).syncPaykitApp() + verify(paykitSdkService, never()).processOutboundPrivateMessages(any(), any()) + } + + @Test + fun `profile removal accepts only the exact clear receipt without a registry sync`() = test { + cacheData.value = PrivatePaykitCacheData( + contacts = mapOf( + CONTACT_KEY to cachedPublishedContact().copy( + consumedPrivatePaymentListVersion = 88uL, + consumedPrivatePaymentListOwner = CONTACT_KEY, + ) + ) + ) + sut = createSut() + whenever(paykitSdkService.clearPrivatePaymentLists(listOf(CONTACT_KEY))).thenReturn( + privateListDeliveryReport().copy( + cleared = listOf(PrivatePaymentListSyncChange(CONTACT_KEY, 17uL, null)), + acknowledged = listOf(PrivatePaymentListAcknowledgement(CONTACT_KEY, 17uL)), + ), + ) + + whenever(paykitSdkService.pendingOutboundPrivateCounterparties()).thenReturn(listOf(CONTACT_KEY)) + + sut.removePublishedEndpointsForProfileRemoval().getOrThrow() + + assertTrue(cacheData.value.cleanupPending) + val retained = cacheData.value.contacts.getValue(CONTACT_KEY) + assertFalse(retained.hasPublishedPrivatePaymentList) + assertEquals(88uL, retained.consumedPrivatePaymentListVersion) + assertEquals(CONTACT_KEY, retained.consumedPrivatePaymentListOwner) + verify(publicPaykitRepo, never()).syncPaykitApp() + verify(paykitSdkService, never()).processOutboundPrivateMessages(any(), any()) + verify(paykitSdkService, times(1)).clearPrivatePaymentLists(listOf(CONTACT_KEY)) + } + + @Test + fun `profile removal cannot infer an empty cleanup scope from invalid stored keys`() = test { + val invalid = "not-a-pubky" + cacheData.value = PrivatePaykitCacheData(contacts = mapOf(invalid to cachedPublishedContact())) + sut = createSut() + + assertTrue(sut.removePublishedEndpointsForProfileRemoval().isFailure) + + assertTrue(cacheData.value.contacts.getValue(invalid).hasPublishedPrivatePaymentList) + assertTrue(cacheData.value.cleanupPending) + verify(paykitSdkService, never()).clearPrivatePaymentLists(any(), anyOrNull()) + } + + @Test + fun `profile removal retains all intended targets when the report acknowledges only one`() = test { + cacheData.value = PrivatePaykitCacheData( + contacts = mapOf(CONTACT_KEY to cachedPublishedContact(), OTHER_CONTACT_KEY to cachedPublishedContact()), + ) + sut = createSut() + whenever(paykitSdkService.clearPrivatePaymentLists(listOf(CONTACT_KEY, OTHER_CONTACT_KEY))).thenReturn( + privateListDeliveryReport().copy( + cleared = listOf(PrivatePaymentListSyncChange(CONTACT_KEY, 17uL, null)), + acknowledged = listOf(PrivatePaymentListAcknowledgement(CONTACT_KEY, 17uL)), + ), + ) + + assertTrue(sut.removePublishedEndpointsForProfileRemoval().isFailure) + + assertTrue(cacheData.value.contacts.values.all { it.hasPublishedPrivatePaymentList }) + assertTrue(cacheData.value.cleanupPending) + verify(paykitSdkService, never()).processOutboundPrivateMessages(any(), any()) + } + + @Test + fun `profile removal refuses an unreadable linked counterparty instead of treating scope as empty`() = test { + whenever(paykitSdkService.linkedPeers()).thenReturn(listOf(linkedPeer("invalid-key", LinkedPeerState.LINKED))) + + assertTrue(sut.removePublishedEndpointsForProfileRemoval().isFailure) + + assertTrue(cacheData.value.cleanupPending) + verify(paykitSdkService, never()).clearPrivatePaymentLists(any(), anyOrNull()) + } + + @Test + fun `profile removal accepts an explicitly empty withdrawal scope`() = test { + sut.removePublishedEndpointsForProfileRemoval().getOrThrow() + + assertTrue(cacheData.value.cleanupPending) + verify(paykitSdkService, never()).clearPrivatePaymentLists(any(), anyOrNull()) + verify(publicPaykitRepo, never()).syncPaykitApp() + } + @Test fun `profile deletion withdraws private lists without an intermediate registry sync`() = test { cacheData.value = PrivatePaykitCacheData(contacts = mapOf(CONTACT_KEY to cachedPublishedContact())) @@ -4524,6 +4661,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { error = null, ) }, + acknowledged = emptyList(), failedToQueue = failedToQueue, failedToDeliver = failedToDeliver, ) @@ -4541,6 +4679,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { cleared = updates .filter { it.reservations.isEmpty() } .map { privateListSyncChange(it.counterparty) }, + acknowledged = emptyList(), failedToQueue = emptyList(), failedToDeliver = emptyList(), ) diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt index 7ab02cf34f..5e8b270bc8 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt @@ -722,7 +722,13 @@ class PaykitSdkServiceTest { } "revision" } - val report = PrivatePaymentListDeliveryReport(emptyList(), emptyList(), emptyList(), emptyList()) + val report = PrivatePaymentListDeliveryReport( + emptyList(), + emptyList(), + emptyList(), + emptyList(), + emptyList() + ) whenever(sdk.syncPrivatePaymentListsWithReservationsAndProcessOutbound(any(), any())).thenReturn(report) val updates = listOf(PrivatePaymentListReservationUpdateInput(RING_PUBKY, listOf(mock()))) val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } @@ -2991,7 +2997,7 @@ class PaykitSdkServiceTest { withdrawal.thenThrow(IllegalStateException("network unavailable")) } else { withdrawal.thenReturn( - PrivatePaymentListDeliveryReport(emptyList(), emptyList(), emptyList(), emptyList()), + PrivatePaymentListDeliveryReport(emptyList(), emptyList(), emptyList(), emptyList(), emptyList()), ) } val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } @@ -3809,7 +3815,7 @@ class PaykitSdkServiceTest { val sdk = mock() val started = CompletableDeferred() val resume = CompletableDeferred() - val report = PrivatePaymentListDeliveryReport(emptyList(), emptyList(), emptyList(), emptyList()) + val report = PrivatePaymentListDeliveryReport(emptyList(), emptyList(), emptyList(), emptyList(), emptyList()) whenever(sdk.linkedPeers()).thenReturn(listOf(contactPeer(LinkedPeerState.LINKED))) whenever(sdk.syncPrivatePaymentListsWithReservationsAndProcessOutbound(any(), any())).doSuspendableAnswer { started.complete(Unit) @@ -3869,7 +3875,7 @@ class PaykitSdkServiceTest { whenever(sdk.paykitAppRegistry(RING_PUBKY)).thenReturn( PaykitAppRegistry(1u, null, listOf(PaykitApp("bitkit", "Bitkit", capabilities)), null, emptyMap()), ) - val report = PrivatePaymentListDeliveryReport(emptyList(), emptyList(), emptyList(), emptyList()) + val report = PrivatePaymentListDeliveryReport(emptyList(), emptyList(), emptyList(), emptyList(), emptyList()) val updates = listOf(RING_PUBKY, other).map { PrivatePaymentListReservationUpdateInput(it, emptyList()) } whenever(sdk.syncPrivatePaymentListsWithReservationsAndProcessOutbound(updates, false)).thenReturn(report) val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } @@ -3910,6 +3916,7 @@ class PaykitSdkServiceTest { cleared = (if (failRecovery) listOf(other) else keys).map { PrivatePaymentListSyncChange(it, 1uL, null) }, + acknowledged = emptyList(), failedToQueue = if (failRecovery) { listOf(PrivatePaymentListSyncChange(RING_PUBKY, null, null)) } else { diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt index 2289e61907..80d3f62a1b 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt @@ -14,7 +14,6 @@ import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doSuspendableAnswer -import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times @@ -129,7 +128,7 @@ class EditProfileViewModelTest : BaseUnitTest() { verify(pubkyRepo, never()).deleteProfile(any()) verify(pubkyRepo, never()).removeBitkitPaymentEndpoints() verify(pubkyRepo, never()).signOutForProfileRemoval() - verify(fixture.privateRepo, never()).removePublishedEndpointsForCleanup(any(), any()) + verify(fixture.privateRepo, never()).removePublishedEndpointsForProfileRemoval() assertNull(fixture.store.pendingAttempt()) } @@ -165,7 +164,7 @@ class EditProfileViewModelTest : BaseUnitTest() { assertNull(fixture.store.pendingAttempt()) assertFalse(sut.uiState.value.showDeleteFailureDialog) assertTrue(sut.uiState.value.canDisconnectLocally) - verify(fixture.privateRepo, never()).removePublishedEndpointsForCleanup(any(), any()) + verify(fixture.privateRepo, never()).removePublishedEndpointsForProfileRemoval() verify(pubkyRepo, never()).deleteProfile(any()) } @@ -274,14 +273,14 @@ class EditProfileViewModelTest : BaseUnitTest() { } verify(pubkyRepo, times(1)).deleteProfile(fixture.deletion) verify(pubkyRepo, never()).signOutForProfileRemoval() - verify(fixture.privateRepo, times(1)).removePublishedEndpointsForCleanup(any(), eq(true)) + verify(fixture.privateRepo, times(1)).removePublishedEndpointsForProfileRemoval() assertNull(fixture.store.pendingAttempt()) } @Test fun `failed private cleanup retains marker and stops profile deletion`() = test { val sut = createSut() - whenever(fixture.privateRepo.removePublishedEndpointsForCleanup(any(), eq(true))) + whenever(fixture.privateRepo.removePublishedEndpointsForProfileRemoval()) .thenReturn(Result.failure(TestAppError("pending cleanup"))) advanceUntilIdle() sut.showDeleteConfirmation() @@ -326,7 +325,7 @@ class EditProfileViewModelTest : BaseUnitTest() { fun `cancelled screen preserves pending removal without success`() = test { val sut = createSut() val cleanup = CompletableDeferred>() - whenever(fixture.privateRepo.removePublishedEndpointsForCleanup(any(), eq(true))) + whenever(fixture.privateRepo.removePublishedEndpointsForProfileRemoval()) .doSuspendableAnswer { cleanup.await() } advanceUntilIdle() sut.showDeleteConfirmation() diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/ProfileRemovalUiFixture.kt b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileRemovalUiFixture.kt index 7989b7d3f3..cfff85ce32 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/ProfileRemovalUiFixture.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileRemovalUiFixture.kt @@ -2,7 +2,6 @@ package to.bitkit.ui.screens.profile import org.mockito.kotlin.any import org.mockito.kotlin.doSuspendableAnswer -import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import to.bitkit.data.ProfileRemovalStore @@ -51,7 +50,7 @@ internal class ProfileRemovalUiFixture(val pubky: PubkyRepo) { whenever { privateRepo.withProfileDeletionPaused(any()) }.doSuspendableAnswer { it.getArgument Unit>(0).invoke(pause) } - whenever { privateRepo.removePublishedEndpointsForCleanup(any(), eq(true)) }.thenReturn(Result.success(Unit)) + whenever { privateRepo.removePublishedEndpointsForProfileRemoval() }.thenReturn(Result.success(Unit)) whenever { pubky.removeBitkitPaymentEndpoints() }.thenReturn(Result.success(Unit)) whenever { pubky.deleteProfile(deletion) }.thenReturn(Result.success(Unit)) whenever { pubky.finishProfileRemovalLocally() }.thenAnswer { current = ended } diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt index 939eeef1ab..eb76380ede 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt @@ -457,7 +457,7 @@ class ProfileViewModelTest : BaseUnitTest() { cancelAndIgnoreRemainingEvents() } verify(pubkyRepo, never()).signOutForProfileRemoval() - verify(fixture.privateRepo, never()).removePublishedEndpointsForCleanup(any(), eq(true)) + verify(fixture.privateRepo, never()).removePublishedEndpointsForProfileRemoval() assertNull(fixture.store.pendingAttempt()) } @@ -528,7 +528,7 @@ class ProfileViewModelTest : BaseUnitTest() { assertIs(awaitItem()) } verify(pubkyRepo, times(1)).signOutForProfileRemoval() - verify(fixture.privateRepo, times(1)).removePublishedEndpointsForCleanup(any(), eq(true)) + verify(fixture.privateRepo, times(1)).removePublishedEndpointsForProfileRemoval() } @Test diff --git a/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt b/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt index 8839f1fe11..962160ca14 100644 --- a/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt +++ b/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt @@ -13,7 +13,6 @@ import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.doSuspendableAnswer -import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times @@ -98,7 +97,7 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { events += "validate" Unit } - whenever { privateRepo.removePublishedEndpointsForCleanup(any(), eq(true)) }.doSuspendableAnswer { + whenever { privateRepo.removePublishedEndpointsForProfileRemoval() }.doSuspendableAnswer { assertNotNull(store.pendingAttempt()) events += "private endpoints" Result.success(Unit) @@ -137,6 +136,27 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { } } + @Test + fun `missing private withdrawal receipt prevents every destructive profile stage`() = test { + val failure = IOException("withdrawal acknowledgement missing") + doReturn(Result.failure(failure)).whenever(privateRepo).removePublishedEndpointsForProfileRemoval() + val confirmation = sut.prepareDeletion(original).getOrThrow() + + val result = assertIs(sut.remove(confirmation).exceptionOrNull()) + + assertSame(failure, result.cause) + assertFalse(result.canReview) + assertTrue(sut.reviewAgain(result).isFailure) + verify(pubky, times(1)).prepareProfileDeletion(original) + verify(privateRepo, times(1)).removePublishedEndpointsForProfileRemoval() + assertEquals(confirmation.attemptId, store.pendingAttempt()) + verify(pubky, never()).removeBitkitPaymentEndpoints() + verify(pubky, never()).deleteProfile(any()) + verify(pubky, never()).signOutForProfileRemoval() + verify(pubky, never()).finishProfileRemovalLocally() + verify(privateRepo, never()).finishProfileRemoval(any()) + } + @Test fun `fresh local disconnect reads no remote state and clears only after confirmation`() = test { val confirmation = sut.prepareLocalDisconnect(original).getOrThrow() @@ -150,7 +170,7 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { listOf("local credentials and metadata", "private local", "wallet backup ready", "backup ready"), events, ) - verify(privateRepo, never()).removePublishedEndpointsForCleanup(any(), any()) + verify(privateRepo, never()).removePublishedEndpointsForProfileRemoval() verify(pubky, never()).removeBitkitPaymentEndpoints() verify(pubky, never()).deleteProfile(any()) verify(pubky, never()).signOutForProfileRemoval() @@ -211,7 +231,7 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { assertTrue(events.isEmpty()) verify(pubky, never()).finishProfileRemovalLocally() verify(privateRepo, never()).finishProfileRemoval(any()) - verify(privateRepo, never()).removePublishedEndpointsForCleanup(any(), any()) + verify(privateRepo, never()).removePublishedEndpointsForProfileRemoval() verify(pubky, never()).removeBitkitPaymentEndpoints() verify(pubky, never()).deleteProfile(any()) verify(pubky, never()).signOutForProfileRemoval() @@ -474,7 +494,7 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { val confirmation = sut.prepareDeletion(original).getOrThrow() assertTrue(sut.remove(confirmation).isFailure) assertNull(store.pendingAttempt()) - verify(privateRepo, never()).removePublishedEndpointsForCleanup(any(), any()) + verify(privateRepo, never()).removePublishedEndpointsForProfileRemoval() } @Test @@ -486,7 +506,7 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { assertNull(sut.failureFor(confirmation)) assertNull(store.pendingAttempt()) verify(pubky, never()).deleteProfile(any()) - verify(privateRepo, never()).removePublishedEndpointsForCleanup(any(), any()) + verify(privateRepo, never()).removePublishedEndpointsForProfileRemoval() assertTrue(sut.prepareDeletion(original).isSuccess) } @@ -527,7 +547,7 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { assertTrue(sut.remove(confirmation).isSuccess) verify(pubky, never()).signOutForProfileRemoval() verify(pubky, never()).removeBitkitPaymentEndpoints() - verify(privateRepo, never()).removePublishedEndpointsForCleanup(any(), any()) + verify(privateRepo, never()).removePublishedEndpointsForProfileRemoval() val unusedOldConfirmation = sut.prepareSignOut(current).getOrThrow() val newerId = UUID.randomUUID().toString() store.withAccess(newerId) { store.begin(newerId) } diff --git a/changelog.d/next/1693.fixed.md b/changelog.d/next/1693.fixed.md index 170ae7beb9..aae2c825b5 100644 --- a/changelog.d/next/1693.fixed.md +++ b/changelog.d/next/1693.fixed.md @@ -1 +1 @@ -Keep interrupted profile removal recoverable without changing replacement identities or losing incoming payment details, and show recovery options that match the pending wallet state and allow a separately confirmed local disconnect when subscriptions prevent profile removal. +Keep interrupted profile removal recoverable, require acknowledged private endpoint withdrawals before deletion, preserve replacement identities and incoming payment details, and offer a separately confirmed local disconnect when subscriptions prevent removal. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 9767d1a465..00984a2478 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -22,7 +22,7 @@ appcompat = { module = "androidx.appcompat:appcompat", version = "1.7.1" } barcode-scanning = { module = "com.google.mlkit:barcode-scanning", version = "17.3.0" } biometric = { module = "androidx.biometric:biometric", version = "1.4.0-alpha05" } bitkit-core = { module = "com.synonym:bitkit-core-android", version = "0.8.0-rc11" } -paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc2" } +paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc3" } bouncycastle-pkix-jdk = { module = "org.bouncycastle:bcpkix-jdk18on", version = "1.83" } bouncycastle-provider-jdk = { module = "org.bouncycastle:bcprov-jdk18on", version = "1.83" } camera-camera2 = { module = "androidx.camera:camera-camera2", version.ref = "camera" } From 716e88e91894fdada352d20d9261e33e7a1c770b Mon Sep 17 00:00:00 2001 From: benk10 Date: Fri, 30 Oct 2026 07:50:12 +0200 Subject: [PATCH 24/61] fix: retain acknowledged profile withdrawal on review --- .../usecases/ProfileRemovalCoordinator.kt | 12 ++- .../repositories/PrivatePaykitRepoTest.kt | 89 +++++++++++++++++++ .../usecases/ProfileRemovalCoordinatorTest.kt | 20 +++++ 3 files changed, 117 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt b/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt index 5b269ff5c3..9e9dda714e 100644 --- a/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt +++ b/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt @@ -24,6 +24,7 @@ class ProfileRemovalConfirmation internal constructor( internal val deletion: PubkyProfileDeletion?, internal val localOnly: Boolean, internal val reviewCeiling: AtomicReference = AtomicReference(deletion), + internal val privateWithdrawalAcknowledged: Boolean = false, ) { internal val used = AtomicBoolean(false) internal val failure = AtomicReference(null) @@ -95,7 +96,8 @@ class ProfileRemovalCoordinator @Inject constructor( previous.attemptId, deletion, previous.localOnly, - previous.reviewCeiling + previous.reviewCeiling, + privateWithdrawalAcknowledged = true, ) } @@ -128,7 +130,7 @@ class ProfileRemovalCoordinator @Inject constructor( sharingRepo.withProfileRemoval { pubkyRepo.performProfileRemoval(confirmation.owner, confirmation.attemptId) { var localCompletionStarted = false - var privateWithdrawalAcknowledged = false + var privateWithdrawalAcknowledged = confirmation.privateWithdrawalAcknowledged var removalMayHaveStarted = removalStore.pendingAttempt() != null try { check(confirmation.deletion == null || confirmation.reviewCeiling.get() === confirmation.deletion) { @@ -139,8 +141,10 @@ class ProfileRemovalCoordinator @Inject constructor( removalMayHaveStarted = true removalStore.begin(confirmation.attemptId) if (!confirmation.localOnly) { - privatePaykitRepo.removePublishedEndpointsForProfileRemoval().getOrThrow() - privateWithdrawalAcknowledged = true + if (!privateWithdrawalAcknowledged) { + privatePaykitRepo.removePublishedEndpointsForProfileRemoval().getOrThrow() + privateWithdrawalAcknowledged = true + } pubkyRepo.removeBitkitPaymentEndpoints().getOrThrow() confirmation.deletion?.let { pubkyRepo.deleteProfile(it).getOrThrow() } pubkyRepo.signOutForProfileRemoval() diff --git a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt index fd844efcd9..66af2c8efe 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt @@ -68,6 +68,7 @@ import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.data.UsdtPreference +import to.bitkit.ext.runSuspendCatching import to.bitkit.models.NodeLifecycleState import to.bitkit.models.PaykitAmount import to.bitkit.models.PaykitAsset @@ -75,12 +76,15 @@ import to.bitkit.models.PaykitUsdt import to.bitkit.services.CoreService import to.bitkit.services.PaykitPreparedPrivateContactPayment import to.bitkit.services.PaykitPrivateContactPaymentResolution +import to.bitkit.services.PaykitProfileDeletionSnapshot import to.bitkit.services.PaykitResolvedPaymentEndpoint import to.bitkit.services.PaykitSdkBackupExport import to.bitkit.services.PaykitSdkOperationLock.Priority import to.bitkit.services.PaykitSdkService import to.bitkit.services.PubkyService import to.bitkit.test.BaseUnitTest +import to.bitkit.usecases.ProfileRemovalCoordinator +import to.bitkit.usecases.ProfileRemovalFailure import to.bitkit.utils.AppError import java.util.UUID import kotlin.test.assertEquals @@ -2852,6 +2856,91 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { verify(publicPaykitRepo, never()).syncPaykitApp() } + @Test + fun `review preserves acknowledged withdrawal after profile deletion fails with private sharing disabled`() = test { + reviewAfterAcknowledgedWithdrawal(failPublicWithdrawal = false) + } + + @Test + fun `review preserves acknowledged withdrawal when public withdrawal disables sharing then fails`() = test { + reviewAfterAcknowledgedWithdrawal(failPublicWithdrawal = true) + } + + private suspend fun reviewAfterAcknowledgedWithdrawal(failPublicWithdrawal: Boolean) { + val owner = PubkyProfileOwner(PubkySignIn(OWN_KEY, 1), 1) + val ended = PubkyProfileOwner(null, 2) + var current = owner + var privatePaymentsEnabled = true + var failOnce = true + val deletion = PubkyProfileDeletion( + owner, + 1, + PaykitProfileDeletionSnapshot(OWN_KEY, "revision", listOf(contactRecord(CONTACT_KEY))), + ) + val pubky = mock() + val sharing = mock() + whenever(pubky.profileOwner()).thenAnswer { current } + whenever(pubky.isProfileOwnerCurrent(any())).thenAnswer { it.getArgument(0) === current } + whenever(pubky.prepareProfileDeletion(owner)).thenReturn(Result.success(deletion)) + whenever(sharing.withProfileRemoval(any())).doSuspendableAnswer { + it.getArgument PubkyProfileOwner>(0).invoke() + } + whenever(pubky.performProfileRemoval(any(), any(), any())).doSuspendableAnswer { + val admittedOwner = it.getArgument(0) + val attempt = it.getArgument(1) + val operation = it.getArgument Unit>(2) + runSuspendCatching { + check(admittedOwner === current) + profileRemovalStore.withAccess(attempt) { operation() } + current + } + } + whenever(paykitSdkService.linkedPeers()).thenReturn(listOf(linkedPeer(CONTACT_KEY, LinkedPeerState.LINKED))) + whenever(paykitSdkService.clearPrivatePaymentLists(listOf(CONTACT_KEY))).thenAnswer { + if (!privatePaymentsEnabled) { + null + } else { + privateListDeliveryReport().copy( + cleared = listOf(PrivatePaymentListSyncChange(CONTACT_KEY, 17uL, null)), + acknowledged = listOf(PrivatePaymentListAcknowledgement(CONTACT_KEY, 17uL)), + ) + } + } + whenever(pubky.removeBitkitPaymentEndpoints()).doSuspendableAnswer { + privatePaymentsEnabled = false + if (failPublicWithdrawal && failOnce) { + failOnce = false + Result.failure(IllegalStateException("public withdrawal response lost")) + } else { + Result.success(Unit) + } + } + whenever(pubky.deleteProfile(deletion)).doSuspendableAnswer { + if (failOnce) { + failOnce = false + Result.failure(IllegalStateException("profile deletion response lost")) + } else { + Result.success(Unit) + } + } + whenever(pubky.finishProfileRemovalLocally()).thenAnswer { current = ended } + val coordinator = ProfileRemovalCoordinator(pubky, sut, sharing, profileRemovalStore) + val original = coordinator.prepareDeletion(owner).getOrThrow() + val failure = assertIs(coordinator.remove(original).exceptionOrNull()) + assertTrue(failure.canReview) + assertFalse(privatePaymentsEnabled) + assertEquals(original.attemptId, profileRemovalStore.pendingAttempt()) + + val reviewed = coordinator.reviewAgain(failure).getOrThrow() + verify(paykitSdkService, times(1)).clearPrivatePaymentLists(listOf(CONTACT_KEY)) + assertEquals(original.attemptId, reviewed.attemptId) + assertEquals(ended, coordinator.remove(reviewed).getOrThrow()) + assertNull(profileRemovalStore.pendingAttempt()) + verify(paykitSdkService, times(1)).clearPrivatePaymentLists(listOf(CONTACT_KEY)) + verify(pubky, times(2)).prepareProfileDeletion(owner) + verify(pubky, times(1)).signOutForProfileRemoval() + } + @Test fun `profile deletion withdraws private lists without an intermediate registry sync`() = test { cacheData.value = PrivatePaykitCacheData(contacts = mapOf(CONTACT_KEY to cachedPublishedContact())) diff --git a/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt b/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt index 962160ca14..5c6f086348 100644 --- a/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt +++ b/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt @@ -348,6 +348,26 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { assertTrue(sut.prepareLocalDisconnect(failure).isFailure) } + @Test + fun `successive confirmed reviews retain the original private withdrawal acknowledgement`() = test { + val firstFailure = failRemoval(deletion) + val second = sut.reviewAgain(firstFailure).getOrThrow() + val secondFailure = assertIs(sut.remove(second).exceptionOrNull()) + assertTrue(secondFailure.canReview) + assertEquals(firstFailure.confirmation.attemptId, second.attemptId) + + val third = sut.reviewAgain(secondFailure).getOrThrow() + whenever(pubky.deleteProfile(deletion)).thenReturn(Result.success(Unit)) + + assertSame(ended, sut.remove(third).getOrThrow()) + assertEquals(second.attemptId, third.attemptId) + verify(privateRepo, times(1)).removePublishedEndpointsForProfileRemoval() + verify(pubky, times(3)).prepareProfileDeletion(original) + verify(pubky, times(3)).deleteProfile(deletion) + verify(pubky, times(1)).signOutForProfileRemoval() + assertNull(store.pendingAttempt()) + } + @Test fun `review rejects a later profile revision instead of replacing original intent`() = test { val failure = failRemoval(deletion) From 3001faf36a6e74e04e8cc1aac80c4bc8a7f4e714 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sat, 31 Oct 2026 00:34:36 +0200 Subject: [PATCH 25/61] test: report Pubky alias state on routing failures --- .../to/bitkit/build/PubkyAuthManifestTest.kt | 62 +++++++++++++++---- 1 file changed, 50 insertions(+), 12 deletions(-) diff --git a/app/src/test/java/to/bitkit/build/PubkyAuthManifestTest.kt b/app/src/test/java/to/bitkit/build/PubkyAuthManifestTest.kt index 8354250793..9029439678 100644 --- a/app/src/test/java/to/bitkit/build/PubkyAuthManifestTest.kt +++ b/app/src/test/java/to/bitkit/build/PubkyAuthManifestTest.kt @@ -74,18 +74,25 @@ class PubkyAuthManifestTest { ) val allUrls = signupUrls + authUrls + unrelatedUrls - assertRoutes(packageManager, application.packageName, allUrls, null) + assertRoutes(packageManager, application.packageName, allUrls, null, "initial defaults") packageManager.setComponentEnabledSetting( signupAlias, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP, ) - assertRoutes(packageManager, application.packageName, signupUrls + authUrls.last(), signupAlias) + assertRoutes( + packageManager, + application.packageName, + signupUrls + authUrls.last(), + signupAlias, + "signup enabled", + ) assertRoutes( packageManager, application.packageName, authUrls.dropLast(1) + unrelatedUrls, null, + "signup enabled", ) packageManager.setComponentEnabledSetting( @@ -98,15 +105,15 @@ class PubkyAuthManifestTest { PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP, ) - assertRoutes(packageManager, application.packageName, authUrls, authAlias) - assertRoutes(packageManager, application.packageName, signupUrls + unrelatedUrls, null) + assertRoutes(packageManager, application.packageName, authUrls, authAlias, "authorization enabled") + assertRoutes(packageManager, application.packageName, signupUrls + unrelatedUrls, null, "authorization enabled") packageManager.setComponentEnabledSetting( authAlias, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP, ) - assertRoutes(packageManager, application.packageName, allUrls, null) + assertRoutes(packageManager, application.packageName, allUrls, null, "both explicitly disabled") } private fun assertRoutes( @@ -114,19 +121,50 @@ class PubkyAuthManifestTest { packageName: String, urls: List, alias: ComponentName?, + phase: String, ) { urls.forEach { val intent = Intent(Intent.ACTION_VIEW, it.toUri()) .addCategory(Intent.CATEGORY_BROWSABLE) .setPackage(packageName) val resolved = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) - if (alias == null) { - assertTrue(resolved.isEmpty(), it) - } else { - val activity = resolved.single().activityInfo - assertEquals(alias.className, activity.name, it) - assertEquals("to.bitkit.ui.MainActivity", activity.targetActivity) - assertTrue(activity.exported) + fun diagnostics() = buildString { + append("phase=$phase url=$it package=$packageName expected=${alias?.className}") + listOf("to.bitkit.ui.MainActivityPubkySignup", "to.bitkit.ui.MainActivityPubkyAuth").forEach { name -> + val component = ComponentName(packageName, name) + append("; alias=$name override=${packageManager.getComponentEnabledSetting(component)}") + runCatching { + packageManager.getActivityInfo( + component, + PackageManager.ComponentInfoFlags.of(PackageManager.MATCH_DISABLED_COMPONENTS.toLong()), + ) + }.onSuccess { info -> + append(" enabled=${info.enabled} exported=${info.exported} target=${info.targetActivity}") + }.onFailure { error -> + append(" activityInfoError=${error.javaClass.simpleName}") + } + } + resolved.forEach { result -> + val info = result.activityInfo + append("; resolved=${info.packageName}/${info.name} target=${info.targetActivity}") + append(" enabled=${info.enabled} exported=${info.exported} match=${result.match}") + } + } + try { + if (alias == null) { + assertTrue(resolved.isEmpty(), it) + } else { + assertEquals(1, resolved.size, it) + val activity = resolved.single().activityInfo + assertEquals(alias.className, activity.name, it) + assertEquals("to.bitkit.ui.MainActivity", activity.targetActivity) + assertTrue(activity.exported) + } + } catch (error: AssertionError) { + val message = runCatching { diagnostics() }.getOrElse { diagnosticError -> + "phase=$phase url=$it diagnosticsUnavailable=${diagnosticError.javaClass.simpleName}" + } + throw AssertionError(message, error) } } } From b2cd2aa3d12fa6a2a817e2e0b03e45af96ec3528 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sat, 31 Oct 2026 18:19:23 +0200 Subject: [PATCH 26/61] fix: preserve profile cleanup retries --- .../java/to/bitkit/data/keychain/Keychain.kt | 5 + .../data/keychain/ProfileCredentials.kt | 102 ++++++++---- .../to/bitkit/services/PaykitSdkService.kt | 9 +- .../usecases/ProfileRemovalCoordinator.kt | 26 ++- .../data/keychain/ProfileCredentialsTest.kt | 150 ++++++++++++++++++ .../bitkit/services/PaykitSdkServiceTest.kt | 95 ++++++++++- .../services/ProfileLogoutSignerTest.kt | 4 +- .../usecases/ProfileRemovalCoordinatorTest.kt | 130 +++++++++++++++ 8 files changed, 483 insertions(+), 38 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/keychain/Keychain.kt b/app/src/main/java/to/bitkit/data/keychain/Keychain.kt index 912ede245d..124c46a97d 100644 --- a/app/src/main/java/to/bitkit/data/keychain/Keychain.kt +++ b/app/src/main/java/to/bitkit/data/keychain/Keychain.kt @@ -59,6 +59,11 @@ class Keychain @Inject constructor( internal suspend fun eraseProfileCredentials(target: ProfileCredentials, requireCurrent: () -> Unit) = profileCredentials.erase(target, requireCurrent) + internal suspend fun eraseProfileCredentialsAfterLocalConfirmation( + target: ProfileCredentials, + requireCurrent: () -> Unit, + ) = profileCredentials.eraseAfterLocalConfirmation(target, requireCurrent) + internal suspend fun validateProfileCredentials(target: ProfileCredentials, requireCurrent: () -> Unit) = profileCredentials.validate(target, requireCurrent) diff --git a/app/src/main/java/to/bitkit/data/keychain/ProfileCredentials.kt b/app/src/main/java/to/bitkit/data/keychain/ProfileCredentials.kt index b899eb5ea8..7d86ce8ac6 100644 --- a/app/src/main/java/to/bitkit/data/keychain/ProfileCredentials.kt +++ b/app/src/main/java/to/bitkit/data/keychain/ProfileCredentials.kt @@ -8,7 +8,7 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.first import to.bitkit.utils.AppError import java.security.MessageDigest -import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference /** A local erase target; it conveys neither remote authority nor acknowledged logout. */ internal class ProfileCredentials internal constructor( @@ -16,25 +16,35 @@ internal class ProfileCredentials internal constructor( internal val walletIndex: Long, private val values: Map, ByteArray?>, ) { - private val current = AtomicBoolean(true) + private enum class Invalidation { UNREADABLE, CHANGED } + + private val invalidation = AtomicReference(null) internal fun requireCurrent() { - if (!current.get()) throw ProfileCredentialsChanged() + if (invalidation.get() != null) throw ProfileCredentialsChanged() + } + + internal fun requireLocalErase() { + if (invalidation.get() == Invalidation.CHANGED) throw ProfileCredentialsChanged() } internal fun invalidate() { - current.set(false) + invalidation.set(Invalidation.CHANGED) } - internal fun matches(current: Map, ByteArray?>): Boolean = - values.keys == current.keys && values.all { (key, expected) -> - val actual = current[key] - if (expected == null || actual == null) { - expected == null && actual == null - } else { - MessageDigest.isEqual(expected, actual) - } + internal fun markUnreadable() { + invalidation.compareAndSet(null, Invalidation.UNREADABLE) + } + + internal fun matches(key: Preferences.Key, actual: ByteArray?): Boolean { + if (!values.containsKey(key)) return false + val expected = values[key] + return if (expected == null || actual == null) { + expected == null && actual == null + } else { + MessageDigest.isEqual(expected, actual) } + } } /** The caller retains identity admission across capture or erase, including the durable commit. */ @@ -52,46 +62,73 @@ internal class ProfileCredentialStore( return ProfileCredentials(this, index, values) } - suspend fun erase(target: ProfileCredentials, requireCurrent: () -> Unit) { - requireCurrent() + suspend fun erase(target: ProfileCredentials, requireCurrent: () -> Unit) = + erase(target, requireCurrent, localOnly = false) + + /** A fresh local confirmation can recheck unreadable original bytes without restoring remote permission. */ + suspend fun eraseAfterLocalConfirmation(target: ProfileCredentials, requireCurrent: () -> Unit) = + erase(target, requireCurrent, localOnly = true) + + private suspend fun erase(target: ProfileCredentials, requireCurrent: () -> Unit, localOnly: Boolean) { + validateAdmission(target, requireCurrent) if (target.store !== this) throw ProfileCredentialsChanged() - target.requireCurrent() - var validated = false + if (localOnly) target.requireLocalErase() else target.requireCurrent() + var validationStarted = false try { store.edit { preferences -> - validateOwnedCredentials(target, requireCurrent) { - read(preferences, target.walletIndex) + validationStarted = true + validateOwnedCredentials(target, requireCurrent, localOnly) { + preferences } keys(target.walletIndex).forEach(preferences::remove) - validated = true } } catch (e: CancellationException) { throw e } catch (e: Exception) { - if (!validated) target.invalidate() + if (!validationStarted) target.markUnreadable() throw e } } /** Read-only admission check before using the captured grant for remote cleanup. */ suspend fun validate(target: ProfileCredentials, requireCurrent: () -> Unit) { - requireCurrent() + validateAdmission(target, requireCurrent) if (target.store !== this) throw ProfileCredentialsChanged() - validateOwnedCredentials(target, requireCurrent) { read(store.data.first(), target.walletIndex) } + validateOwnedCredentials(target, requireCurrent) { store.data.first() } } private suspend fun validateOwnedCredentials( target: ProfileCredentials, requireCurrent: () -> Unit, - values: suspend () -> Map, ByteArray?>, + localOnly: Boolean = false, + values: suspend () -> Preferences, ) { - target.requireCurrent() + if (localOnly) target.requireLocalErase() else target.requireCurrent() + validateAdmission(target, requireCurrent) + validateWallet(target) + val preferences = readOwnedState(target, values) + keys(target.walletIndex).forEach { key -> + val actual = readOwnedState(target) { preferences[key]?.let(decrypt) } + if (!target.matches(key, actual)) { + target.invalidate() + throw ProfileCredentialsChanged() + } + } + validateAdmission(target, requireCurrent) + validateWallet(target) + if (localOnly) target.requireLocalErase() else target.requireCurrent() + } + + private suspend fun validateWallet(target: ProfileCredentials) { + if (readOwnedState(target) { walletIndex() } != target.walletIndex) { + target.invalidate() + throw ProfileCredentialsChanged() + } + } + + private fun validateAdmission(target: ProfileCredentials, requireCurrent: () -> Unit) { try { requireCurrent() - if (walletIndex() != target.walletIndex || !target.matches(values())) throw ProfileCredentialsChanged() - requireCurrent() - if (walletIndex() != target.walletIndex) throw ProfileCredentialsChanged() - target.requireCurrent() } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -100,6 +137,15 @@ internal class ProfileCredentialStore( } } + private suspend fun readOwnedState(target: ProfileCredentials, read: suspend () -> T): T = try { + read() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + target.markUnreadable() + throw e + } + private fun read(preferences: Preferences, index: Long): Map, ByteArray?> = keys(index).associateWith { key -> preferences[key]?.let(decrypt) } diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt index 5e3b1e0da8..5851273ad4 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt @@ -470,7 +470,14 @@ class PaykitSdkService @Inject constructor( operationLock.withLock { logout.requireOriginalCredentials() withContext(NonCancellable) { - keychain.eraseProfileCredentials(logout.credentials, logout::requireOriginalCredentials) + if (localOnly) { + keychain.eraseProfileCredentialsAfterLocalConfirmation( + logout.credentials, + logout::requireOriginalCredentials, + ) + } else { + keychain.eraseProfileCredentials(logout.credentials, logout::requireOriginalCredentials) + } logout.credentialsErased.set(true) sessionProvider.clearLiveSessionAccess() resetRuntime() diff --git a/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt b/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt index 5d489700c0..6854ec74b4 100644 --- a/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt +++ b/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt @@ -48,6 +48,7 @@ internal class ProfileRemovalIntent( val owner: PubkyProfileOwner, val attemptId: String, val logout: PaykitProfileLogout, + val deletingProfile: Boolean, ) { val confirmation = AtomicReference(null) val started = AtomicBoolean(false) @@ -58,6 +59,9 @@ internal class ProfileRemovalIntent( val logoutStarted = AtomicBoolean(false) val executing = AtomicBoolean(false) val retryReady = AtomicBoolean(false) + + val canRetryRemoteWork: Boolean + get() = logoutStarted.get() || (!deletingProfile && privateWithdrawal.get()) } class ProfileRemovalFailure internal constructor( @@ -68,8 +72,13 @@ class ProfileRemovalFailure internal constructor( private val privateWithdrawalAcknowledged: Boolean, ) : AppError("Profile removal did not finish. Review its state or disconnect locally.", cause) { internal val canReview: Boolean - get() = confirmation.deletion != null && !localCompletionStarted && privateWithdrawalAcknowledged && - confirmation.intent?.logout?.reconcileAcknowledgement() != true + get() { + val intent = confirmation.intent ?: return false + return confirmation.deletion != null && !localCompletionStarted && privateWithdrawalAcknowledged && + intent.logout.isCurrent() && !intent.executing.get() && + (!intent.logoutStarted.get() || intent.retryReady.get()) && + !intent.logout.reconcileAcknowledgement() + } } internal class ProfileRemovalLocalOnly(cause: Throwable) : @@ -93,7 +102,7 @@ class ProfileRemovalCoordinator @Inject constructor( val deletion = pubkyRepo.prepareProfileDeletion(owner).getOrThrow() removalStore.requireNoPending() check(pubkyRepo.isProfileOwnerCurrent(owner)) { "The profile identity changed" } - val intent = captureIntent(owner) + val intent = captureIntent(owner, deletingProfile = true) ProfileRemovalConfirmation(owner, intent.attemptId, deletion, localOnly = false, intent = intent) } @@ -125,7 +134,10 @@ class ProfileRemovalCoordinator @Inject constructor( } } - private suspend fun captureIntent(owner: PubkyProfileOwner): ProfileRemovalIntent { + private suspend fun captureIntent( + owner: PubkyProfileOwner, + deletingProfile: Boolean = false, + ): ProfileRemovalIntent { retainedIntent.get()?.takeUnless { it.logout.isCurrent() }?.let { retainedIntent.compareAndSet(it, null) } @@ -133,7 +145,7 @@ class ProfileRemovalCoordinator @Inject constructor( return try { check(isCurrent(owner)) { "The profile identity changed" } removalStore.requireNoPending() - ProfileRemovalIntent(owner, UUID.randomUUID().toString(), logout).also { + ProfileRemovalIntent(owner, UUID.randomUUID().toString(), logout, deletingProfile).also { check(retainedIntent.compareAndSet(null, it)) { "A profile removal confirmation is already active" } } } catch (error: Throwable) { @@ -144,7 +156,7 @@ class ProfileRemovalCoordinator @Inject constructor( fun canRetry(owner: PubkyProfileOwner?): Boolean { val intent = retainedIntent.get() ?: return false - return owner != null && isCurrent(owner) && isCurrent(intent.owner) && intent.logoutStarted.get() && + return owner != null && isCurrent(owner) && isCurrent(intent.owner) && intent.canRetryRemoteWork && intent.retryReady.get() && !intent.executing.get() && intent.logout.isCurrent() && !intent.logout.reconcileAcknowledgement() } @@ -364,7 +376,7 @@ class ProfileRemovalCoordinator @Inject constructor( it.executing.set(false) if (!it.started.get() && retainedIntent.compareAndSet(it, null)) it.logout.revoke() it.retryReady.set( - confirmation.failure.get() != null && it.logoutStarted.get() && + confirmation.failure.get() != null && it.canRetryRemoteWork && it.logout.isCurrent() && !it.logout.reconcileAcknowledgement() ) } diff --git a/app/src/test/java/to/bitkit/data/keychain/ProfileCredentialsTest.kt b/app/src/test/java/to/bitkit/data/keychain/ProfileCredentialsTest.kt index 1e2c37a16b..597cfc56bf 100644 --- a/app/src/test/java/to/bitkit/data/keychain/ProfileCredentialsTest.kt +++ b/app/src/test/java/to/bitkit/data/keychain/ProfileCredentialsTest.kt @@ -57,6 +57,156 @@ class ProfileCredentialsTest { otherWallet to "other-wallet-session", ) + @Test + fun `local confirmation can recover an unavailable read without restoring ordinary permission`() = runTest { + val backing = InMemoryDataStore(initial()) + var unavailable = false + val store = object : DataStore { + override val data = backing.data.map { + if (unavailable) throw IOException("Read unavailable") + it + } + override suspend fun updateData(transform: suspend (Preferences) -> Preferences): Preferences { + if (unavailable) throw IOException("Read unavailable") + return backing.updateData(transform) + } + } + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + unavailable = true + assertFailsWith { credentials.validate(target, ::requireCurrent) } + assertFailsWith { credentials.eraseAfterLocalConfirmation(target, ::requireCurrent) } + assertEquals(initial(), backing.data.first()) + unavailable = false + assertFailsWith { credentials.erase(target, ::requireCurrent) } + credentials.eraseAfterLocalConfirmation(target, ::requireCurrent) + assertEquals( + mutablePreferencesOf(mnemonic to "unchanged-wallet", otherWallet to "other-wallet-session").asMap(), + backing.data.first().asMap(), + ) + assertFailsWith { credentials.validate(target, ::requireCurrent) } + } + + @Test + fun `local confirmation compares original values again after decryption recovers`() = runTest { + val store = InMemoryDataStore(initial()) + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + store.edit { it[secret] = "unreadable" } + assertFailsWith { credentials.validate(target, ::requireCurrent) } + assertFailsWith { credentials.eraseAfterLocalConfirmation(target, ::requireCurrent) } + assertEquals("first:session", store.data.first()[session]) + store.updateData { initial() } + credentials.eraseAfterLocalConfirmation(target, ::requireCurrent) + assertFalse(store.data.first().contains(secret)) + assertEquals("unchanged-wallet", store.data.first()[mnemonic]) + assertFailsWith { credentials.validate(target, ::requireCurrent) } + } + + @Test + fun `local recovery rejects changed or absent entries and never accepts their restoration`() = runTest { + listOf(session, secret, sharedSource).forEach { key -> + listOf("replacement", null).forEach { replacement -> + val store = InMemoryDataStore(initial()) + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + store.edit { it[sharedSource] = "unreadable" } + assertFailsWith { credentials.validate(target, ::requireCurrent) } + store.updateData { initial() } + store.edit { + if (replacement == null) it.remove(key) else it[key] = replacement + } + val changed = store.data.first() + assertFailsWith { + credentials.eraseAfterLocalConfirmation(target, ::requireCurrent) + } + assertEquals(changed, store.data.first()) + store.updateData { initial() } + assertFailsWith { + credentials.eraseAfterLocalConfirmation(target, ::requireCurrent) + } + assertEquals(initial(), store.data.first()) + } + } + } + + @Test + fun `local recovery cannot adopt an added originally absent key`() = runTest { + val original = initial().also { it.remove(secret) } + val store = InMemoryDataStore(original) + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + store.edit { it[sharedSource] = "unreadable" } + assertFailsWith { credentials.validate(target, ::requireCurrent) } + store.updateData { original } + store.edit { it[secret] = "new-key" } + val changed = store.data.first() + assertFailsWith { + credentials.eraseAfterLocalConfirmation(target, ::requireCurrent) + } + assertEquals(changed, store.data.first()) + store.updateData { original } + assertFailsWith { + credentials.eraseAfterLocalConfirmation(target, ::requireCurrent) + } + } + + @Test + fun `an observed mismatch remains terminal even when another entry is unreadable`() = runTest { + val store = InMemoryDataStore(initial()) + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + store.edit { + it[session] = "replacement" + it[secret] = "unreadable" + } + assertFailsWith { credentials.validate(target, ::requireCurrent) } + store.updateData { initial() } + assertFailsWith { + credentials.eraseAfterLocalConfirmation(target, ::requireCurrent) + } + assertEquals(initial(), store.data.first()) + } + + @Test + fun `local recovery rejects store wallet and ended lifecycle even when original bytes return`() = runTest { + listOf("wallet", "lifecycle", "store").forEach { changed -> + walletIndex = 0 + admitted = true + val store = InMemoryDataStore(initial()) + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + store.edit { it[sharedSource] = "unreadable" } + assertFailsWith { credentials.validate(target, ::requireCurrent) } + store.updateData { initial() } + when (changed) { + "wallet" -> { + walletIndex = 1 + assertFailsWith { + credentials.eraseAfterLocalConfirmation(target, ::requireCurrent) + } + walletIndex = 0 + } + "lifecycle" -> { + admitted = false + assertFailsWith { + credentials.eraseAfterLocalConfirmation(target, ::requireCurrent) + } + admitted = true + } + "store" -> assertFailsWith { + credentials(store).eraseAfterLocalConfirmation(target, ::requireCurrent) + } + } + if (changed != "store") { + assertFailsWith { + credentials.eraseAfterLocalConfirmation(target, ::requireCurrent) + } + } + assertEquals(initial(), store.data.first()) + } + } + @Test fun `validation rejects changed absent or unreadable captured entries without writing`() = runTest { listOf(session, secret, sharedSource).forEach { changed -> diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt index 697309665c..b9a9efc1d2 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt @@ -60,6 +60,7 @@ import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.launch @@ -114,6 +115,7 @@ import to.bitkit.services.PaykitSdkOperationLock.Priority import to.bitkit.test.InMemoryDataStore import to.bitkit.test.forEachCase import to.bitkit.utils.AppError +import java.io.IOException import java.time.Instant import java.util.UUID import kotlin.coroutines.cancellation.CancellationException @@ -130,6 +132,97 @@ import kotlin.time.Duration.Companion.seconds @OptIn(ExperimentalCoroutinesApi::class) class PaykitSdkServiceTest { + @Test + fun `fresh local cleanup after failed credential read erases only the original bundle`() = runTest { + val session = stringPreferencesKey("PAYKIT_SESSION_0") + val secret = stringPreferencesKey("PUBKY_SECRET_KEY_0") + val sharedSource = stringPreferencesKey("SHARED_PUBKY_SOURCE_0") + val wallet = stringPreferencesKey("MNEMONIC_0") + val store = InMemoryDataStore( + mutablePreferencesOf( + session to "session", + secret to "original", + sharedSource to "ring", + wallet to "wallet", + ), + ) + var refuseRead = false + val credentials = ProfileCredentialStore(store, { 0L }) { + if (refuseRead) throw IOException("Credential read unavailable") + it.toByteArray() + } + val target = credentials.capture {} + val keychain = mock() + whenever(keychain.validateProfileCredentials(org.mockito.kotlin.eq(target), any())).doSuspendableAnswer { + credentials.validate(target, it.getArgument(1)) + } + whenever( + keychain.eraseProfileCredentialsAfterLocalConfirmation(org.mockito.kotlin.eq(target), any()) + ).doSuspendableAnswer { + credentials.eraseAfterLocalConfirmation(target, it.getArgument(1)) + } + val receipt = PubkyGrantLogoutReceipt(RING_PUBKY, "homeserver", "original-grant", "bitkit") + val native = mock { on { binding() }.thenReturn(receipt) } + val logout = PaykitProfileLogout(native, target) { true } + val service = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { mock() } + + refuseRead = true + service.withProfileRemoval({ true }) { + assertFailsWith { service.executeProfileLogout(logout) } + } + assertFalse(logout.isCurrent()) + verify(native, never()).prepareAttempt() + assertFalse(logout.credentialsErased.get()) + refuseRead = false + service.withProfileRemoval({ true }) { + service.eraseProfileLogoutCredentials(logout, localOnly = true) + } + assertEquals(mutablePreferencesOf(wallet to "wallet").asMap(), store.data.first().asMap()) + assertTrue(logout.credentialsErased.get()) + assertFalse(logout.isCurrent()) + assertFailsWith { credentials.validate(target) {} } + verify(native, never()).prepareAttempt() + } + + @Test + fun `local confirmed erase drains durable commit before cancellation and wallet wipe`() = runTest { + val receipt = PubkyGrantLogoutReceipt(RING_PUBKY, "homeserver", "original-grant", "bitkit") + val native = mock { on { binding() }.thenReturn(receipt) } + val logout = PaykitProfileLogout(native, mock()) { true } + logout.revoke() + val entered = CompletableDeferred() + val release = CompletableDeferred() + var committed = false + val keychain = mock() + whenever(keychain.eraseProfileCredentialsAfterLocalConfirmation(any(), any())).doSuspendableAnswer { + entered.complete(Unit) + release.await() + it.getArgument<() -> Unit>(1).invoke() + committed = true + } + val service = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { mock() } + val removal = launch { + service.withProfileRemoval({ true }) { service.eraseProfileLogoutCredentials(logout, localOnly = true) } + } + entered.await() + removal.cancel() + val wipe = async { + service.withWalletWipe { + assertTrue(committed) + assertTrue(logout.credentialsErased.get()) + } + } + runCurrent() + assertFalse(removal.isCompleted) + assertFalse(wipe.isCompleted) + assertFalse(logout.credentialsErased.get()) + release.complete(Unit) + removal.join() + wipe.await() + verify(native, never()).prepareAttempt() + verify(keychain, never()).eraseProfileCredentials(any(), any()) + } + @Test fun `changed original credentials between native reads prevent profile deletion`() = runTest { val secret = stringPreferencesKey("PUBKY_SECRET_KEY_0") @@ -274,7 +367,7 @@ class PaykitSdkServiceTest { assertIs(execution.await().exceptionOrNull()) verify(attempt, never()).execute() service.withProfileRemoval({ true }) { service.eraseProfileLogoutCredentials(logout, localOnly = true) } - verify(keychain).eraseProfileCredentials(org.mockito.kotlin.eq(logout.credentials), any()) + verify(keychain).eraseProfileCredentialsAfterLocalConfirmation(org.mockito.kotlin.eq(logout.credentials), any()) assertTrue(logout.credentialsErased.get()) } diff --git a/app/src/test/java/to/bitkit/services/ProfileLogoutSignerTest.kt b/app/src/test/java/to/bitkit/services/ProfileLogoutSignerTest.kt index dc3756335d..2e8b04c388 100644 --- a/app/src/test/java/to/bitkit/services/ProfileLogoutSignerTest.kt +++ b/app/src/test/java/to/bitkit/services/ProfileLogoutSignerTest.kt @@ -5,6 +5,7 @@ import com.synonym.paykit.PubkyGrantLogoutReceipt import kotlinx.coroutines.test.runTest import org.junit.Test import org.mockito.kotlin.any +import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times @@ -81,7 +82,8 @@ class ProfileLogoutSignerTest { assertTrue(logout.credentialsErased.get()) verify(native, never()).prepareAttempt() verify(shared, times(3)).readCredential(owner) - verify(keychain).eraseProfileCredentials(any(), any()) + verify(keychain).eraseProfileCredentialsAfterLocalConfirmation(eq(logout.credentials), any()) + verify(keychain, never()).eraseProfileCredentials(any(), any()) } @Test diff --git a/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt b/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt index 614d009970..548587bf74 100644 --- a/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt +++ b/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt @@ -1,6 +1,9 @@ package to.bitkit.usecases import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.mutablePreferencesOf +import androidx.datastore.preferences.core.stringPreferencesKey import com.synonym.paykit.ContactRecord import com.synonym.paykit.PubkyGrantLogout import com.synonym.paykit.PubkyGrantLogoutReceipt @@ -9,6 +12,7 @@ import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.async import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import org.junit.Before import org.junit.Test @@ -24,6 +28,7 @@ import org.mockito.kotlin.whenever import to.bitkit.data.ProfileRemovalState import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.ReceiptAssociationsUnavailable +import to.bitkit.data.keychain.ProfileCredentialStore import to.bitkit.ext.runSuspendCatching import to.bitkit.repositories.ContactPaymentSettingsRepo import to.bitkit.repositories.PrivatePaykitRepo @@ -34,6 +39,7 @@ import to.bitkit.repositories.PubkySignIn import to.bitkit.services.PaykitProfileDeletionSnapshot import to.bitkit.services.PaykitProfileLogout import to.bitkit.test.BaseUnitTest +import to.bitkit.test.InMemoryDataStore import java.io.IOException import java.util.UUID import kotlin.test.assertEquals @@ -61,6 +67,82 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { private val logouts = mutableListOf() private val binding = PubkyGrantLogoutReceipt("identity", "homeserver", "original-grant", "bitkit") + @Test + fun `retired credential read requires fresh local confirmation and preserves the original attempt`() = test { + val secret = stringPreferencesKey("PUBKY_SECRET_KEY_0") + val localStore = InMemoryDataStore(mutablePreferencesOf(secret to "original")) + var unreadable = false + val credentials = ProfileCredentialStore(localStore, { 0L }) { + if (unreadable) throw IOException("Keystore unavailable") + it.toByteArray() + } + val target = credentials.capture {} + val native = mock { on { binding() } doReturn binding } + val logout = PaykitProfileLogout(native, target) { current === original } + doReturn(Result.success(logout)).whenever(pubky).captureProfileLogout(original) + doSuspendableAnswer { + assertNotNull(store.pendingAttempt()) + unreadable = true + try { + credentials.validate(target, logout::requireCurrent) + } finally { + logout.revoke() + } + }.whenever(pubky).executeProfileLogout(logout) + doSuspendableAnswer { + credentials.eraseAfterLocalConfirmation(target, logout::requireOriginalCredentials) + current = ended + }.whenever(pubky).finishProfileRemovalLocally(logout, true) + val originalConfirmation = sut.prepareDeletion(original).getOrThrow() + val failure = assertIs(sut.remove(originalConfirmation).exceptionOrNull()) + val pending = assertNotNull(store.pendingAttempt()) + assertFalse(failure.canReview) + assertFalse(sut.canRetry(original)) + unreadable = false + val cancelled = sut.prepareLocalDisconnect(failure).getOrThrow() + sut.discard(cancelled) + assertEquals("original", localStore.data.first()[secret]) + assertEquals(pending, store.pendingAttempt()) + verify(privateRepo, never()).finishProfileRemoval(any()) + + val fresh = sut.prepareSignOut(original).getOrThrow() + assertTrue(fresh.localOnly) + assertEquals(pending, fresh.attemptId) + assertSame(originalConfirmation.intent, fresh.intent) + assertSame(ended, sut.remove(fresh).getOrThrow()) + assertTrue(sut.remove(fresh).isFailure) + assertNull(localStore.data.first()[secret]) + assertNull(store.pendingAttempt()) + assertFalse(logout.isCurrent()) + verify(pubky, times(1)).executeProfileLogout(logout) + verify(privateRepo, times(1)).removePublishedEndpointsForProfileRemoval(any()) + verify(pubky, never()).finishProfileRemovalLocally() + } + + @Test + fun `review waits for original outer removal drainage`() = test { + val draining = CompletableDeferred() + val release = CompletableDeferred() + doSuspendableAnswer { + try { + it.getArgument PubkyProfileOwner>(0).invoke() + } finally { + draining.complete(Unit) + release.await() + } + }.whenever(sharing).withProfileRemoval(any()) + doSuspendableAnswer { throw IOException("response lost") }.whenever(pubky).executeProfileLogout(any()) + val confirmation = sut.prepareDeletion(original).getOrThrow() + val removal = async { sut.remove(confirmation) } + draining.await() + val failure = assertNotNull(sut.failureFor(confirmation)) + assertFalse(failure.canReview) + assertTrue(sut.reviewAgain(failure).isFailure) + release.complete(Unit) + assertTrue(removal.await().isFailure) + assertTrue(failure.canReview) + } + @Test fun `changed captured access after admission drain prevents even the first cleanup stage`() = test { val confirmation = sut.prepareDeletion(original).getOrThrow() @@ -133,6 +215,51 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { assertTrue(sut.reviewAgain(failure).isFailure) } + @Test + fun `confirmed sign out resumes endpoint cleanup without repeating acknowledged private withdrawal`() = test { + var attempts = 0 + whenever(pubky.removeBitkitPaymentEndpointsForRemoval(any(), any(), any(), any())).thenAnswer { + attempts++ + if (attempts == 1) { + Result.failure(IOException("public endpoint cleanup unavailable")) + } else { + it.getArgument<() -> Unit>(2).invoke() + it.getArgument<() -> Unit>(3).invoke() + Result.success(Unit) + } + } + val first = sut.prepareSignOut(original).getOrThrow() + assertIs(sut.remove(first).exceptionOrNull()) + assertEquals(first.attemptId, store.pendingAttempt()) + assertTrue(sut.canRetry(original)) + verify(pubky, never()).executeProfileLogout(any()) + + val canceled = sut.prepareRemoteRetry(original).getOrThrow() + sut.discard(canceled) + assertEquals(1, attempts) + val retry = sut.prepareRemoteRetry(original).getOrThrow() + assertEquals(first.attemptId, retry.attemptId) + assertSame(ended, sut.remove(retry).getOrThrow()) + verify(privateRepo, times(1)).removePublishedEndpointsForProfileRemoval(any()) + verify(pubky, times(1)).captureProfileLogout(original) + verify(pubky, times(1)).executeProfileLogout(logouts.single()) + verify(pubky, never()).deleteProfile(any(), any()) + assertNull(store.pendingAttempt()) + } + + @Test + fun `sign out cannot retry remote cleanup without the original private withdrawal acknowledgement`() = test { + doReturn(Result.failure(IOException("withdrawal unknown"))) + .whenever(privateRepo).removePublishedEndpointsForProfileRemoval(any()) + val confirmation = sut.prepareSignOut(original).getOrThrow() + assertIs(sut.remove(confirmation).exceptionOrNull()) + assertEquals(confirmation.attemptId, store.pendingAttempt()) + assertFalse(sut.canRetry(original)) + assertTrue(sut.prepareRemoteRetry(original).isFailure) + verify(pubky, never()).removeBitkitPaymentEndpointsForRemoval(any(), any(), any(), any()) + verify(pubky, never()).executeProfileLogout(any()) + } + @Test fun `acknowledged logout hidden by cancellation allows only local completion`() = test { whenever { pubky.executeProfileLogout(any()) }.doSuspendableAnswer { @@ -162,6 +289,7 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { assertTrue(sut.canRetry(original)) logouts.single().revoke() assertFalse(sut.canRetry(original)) + assertFalse(assertNotNull(sut.failureFor(confirmation)).canReview) assertTrue(sut.prepareRemoteRetry(original).isFailure) val restarted = ProfileRemovalCoordinator(pubky, privateRepo, sharing, store) @@ -693,6 +821,8 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { val confirmation = sut.prepareDeletion(original).getOrThrow() assertTrue(sut.remove(confirmation).isFailure) assertEquals(confirmation.attemptId, store.pendingAttempt()) + assertFalse(sut.canRetry(original)) + assertTrue(sut.prepareRemoteRetry(original).isFailure) verify(pubky, never()).deleteProfile(any(), any()) verify(pubky, never()).executeProfileLogout(any()) verify(privateRepo, never()).finishProfileRemoval(any()) From 7b795fdc057c708ad01196c07f750b94a777508b Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 1 Nov 2026 02:10:32 +0200 Subject: [PATCH 27/61] fix: stop queued allowance offers after deactivation --- .../repositories/PaykitAllowanceRepo.kt | 32 +++-- .../to/bitkit/services/PaykitSdkService.kt | 2 + .../repositories/PaykitAllowanceRepoTest.kt | 109 +++++++++++++----- changelog.d/next/1686.fixed.md | 2 +- 4 files changed, 106 insertions(+), 39 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt index 7fe687eaac..0d3384955f 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt @@ -122,7 +122,11 @@ class PaykitAllowanceRepo @Inject constructor( { limits, monthAnchor, endpoints -> limits.terms(monthAnchor, endpoints) } @Volatile - private var activeIdentity: String? = null + private var activation: Activation? = null + + private val activeIdentity: String? get() = activation?.identity + + private class Activation(val identity: String) private val _entries = MutableStateFlow>(emptyList()) @@ -185,7 +189,7 @@ class PaykitAllowanceRepo @Inject constructor( } withContext(ioDispatcher) { val identityChanged = activeIdentity != normalizedIdentity - activeIdentity = normalizedIdentity + activation = Activation(normalizedIdentity) executor.activate(normalizedIdentity) if (identityChanged) { manualRequestSignatures.clear() @@ -214,7 +218,7 @@ class PaykitAllowanceRepo @Inject constructor( } private fun clear() { - activeIdentity = null + activation = null manualRequestSignatures.clear() _offersToAnnounce.update { emptyList() } announcedOfferKeys.clear() @@ -317,11 +321,22 @@ class PaykitAllowanceRepo @Inject constructor( } } - suspend fun accept(entryId: String): Result = respond(entry(entryId)) { acceptProposal(it) } + suspend fun accept(entryId: String): Result { + val acceptingActivation = activation + return respond(entry(entryId)) { acceptProposal(it, acceptingActivation) } + } - private suspend fun acceptProposal(allowance: PaykitAllowance): AllowanceRecord { + private suspend fun acceptProposal( + allowance: PaykitAllowance, + acceptingActivation: Activation?, + canContinue: () -> Boolean = { true }, + ): AllowanceRecord { val proposalStreamItemId = allowance.proposalStreamItemId ?: throw PaykitAllowanceError.Unavailable - return paykitSdkService.acceptAllowance(allowance.counterparty, allowance.allowanceId, proposalStreamItemId) + return paykitSdkService.acceptAllowance(allowance.counterparty, allowance.allowanceId, proposalStreamItemId) { + if (acceptingActivation == null || activation !== acceptingActivation || !canContinue()) { + throw PaykitAllowanceError.Unavailable + } + } } /** @@ -336,7 +351,8 @@ class PaykitAllowanceRepo @Inject constructor( canAnnounce: () -> Boolean = { true }, canContinue: () -> Boolean = { true }, ): List = withContext(ioDispatcher) { - val identity = activeIdentity ?: return@withContext emptyList() + val acceptingActivation = activation ?: return@withContext emptyList() + val identity = acceptingActivation.identity val isCurrent = { activeIdentity == identity && canAnnounce() } val offers = _entries.value.filter { entry -> val answerable = entry.allowances.filter { it.isAnswerable } @@ -359,7 +375,7 @@ class PaykitAllowanceRepo @Inject constructor( }.onFailure { Logger.warn("Failed to mark an allowance offer before accepting it", it, context = TAG) } .isSuccess if (isMarked) { - respond(offer) { acceptProposal(it) } + respond(offer) { acceptProposal(it, acceptingActivation, canContinue) } .onSuccess { accepted += offer } .onFailure { Logger.warn("Failed to accept an allowance offer", it, context = TAG) } } diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt index 314ae4ef7f..3ac3016d1a 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt @@ -1321,10 +1321,12 @@ class PaykitSdkService @Inject constructor( counterparty: String, allowanceId: String, expectedProposalStreamItemId: ULong, + admit: suspend () -> Unit, ): AllowanceRecord { isSetup.await() return operationLock.withLock(Priority.Interactive) { withStateRevisionTracking { handle -> + admit() completeSdkCall { handle.acceptAllowance(counterparty, allowanceId, expectedProposalStreamItemId) } } } diff --git a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt index f796489cfa..d080b226c2 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt @@ -9,6 +9,8 @@ import com.synonym.paykit.LinkedPeerState import com.synonym.paykit.OutboundPrivateSendReport import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.update @@ -334,7 +336,10 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { fun `received ask is presented once and accepting answers it`() = test { val proposalRecord = receivedAsk() records = listOf(proposalRecord) - whenever(sdk.acceptAllowance(any(), any(), any())).thenReturn(proposalRecord) + whenever(sdk.acceptAllowance(any(), any(), any(), any())).doSuspendableAnswer { + it.getArgument Unit>(3).invoke() + proposalRecord + } sut.activate(identity) val proposal = checkNotNull(sut.proposalForPresentation()) @@ -345,16 +350,45 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { assertTrue(sut.accept(proposal.id).isSuccess) - verify(sdk).acceptAllowance(fixtures.counterpartyKey, ALLOWANCE_ID, 1uL) + verify(sdk).acceptAllowance(eq(fixtures.counterpartyKey), eq(ALLOWANCE_ID), eq(1uL), any()) verify(sdk).processOutboundPrivateMessages(fixtures.counterpartyKey) } + @Test + fun `paused repository does not accept a queued offer`() = test { + for (reactivate in listOf(false, true)) { + records = listOf(receivedProposal()) + val waiting = CompletableDeferred() + val release = CompletableDeferred() + var accepted = 0 + whenever(sdk.acceptAllowance(any(), any(), any(), any())).doSuspendableAnswer { + waiting.complete(Unit) + release.await() + it.getArgument Unit>(3).invoke() + accepted += 1 + records.single() + } + sut.activate(identity) + val accepting = async { sut.acceptOffersFromAllowers() } + waiting.await() + + sut.pause(identity) + assertTrue(sut.entries.value.isEmpty()) + if (reactivate) sut.activate(identity) + release.complete(Unit) + assertTrue(accepting.await().isEmpty()) + + assertEquals(0, accepted, "A queued offer stays unanswered while allowances are disabled") + } + } + @Test fun `offer from the allower is accepted without the review sheet and not announced twice`() = test { // The proposer took the allower role, so this wallet is the allowee. val offer = receivedProposal() records = listOf(offer) - whenever(sdk.acceptAllowance(any(), any(), any())).thenAnswer { + whenever(sdk.acceptAllowance(any(), any(), any(), any())).doSuspendableAnswer { + it.getArgument Unit>(3).invoke() records = listOf(fixtures.record(localRole = AllowanceLocalRole.ALLOWEE, proposedByMe = false)) records.single() } @@ -364,7 +398,7 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { val accepted = sut.acceptOffersFromAllowers() assertEquals(listOf(fixtures.counterpartyKey), accepted.map { it.counterparty }) - verify(sdk).acceptAllowance(fixtures.counterpartyKey, ALLOWANCE_ID, 1uL) + verify(sdk).acceptAllowance(eq(fixtures.counterpartyKey), eq(ALLOWANCE_ID), eq(1uL), any()) verify(sdk).processOutboundPrivateMessages(fixtures.counterpartyKey) val entry = sut.entries.value.single() assertEquals(PaykitAllowance.Status.ACTIVE, entry.status(fixtures.now)) @@ -374,13 +408,13 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { sut.markOffersAnnounced(accepted) assertTrue(sut.acceptOffersFromAllowers().isEmpty(), "An accepted offer is not accepted or announced twice") - verify(sdk, times(1)).acceptAllowance(any(), any(), any()) + verify(sdk, times(1)).acceptAllowance(any(), any(), any(), any()) } @Test fun `failed offer accept stays unanswered and is retried and announced once on the next refresh`() = test { records = listOf(receivedProposal()) - whenever(sdk.acceptAllowance(any(), any(), any())).thenThrow(RuntimeException("offline")) + whenever(sdk.acceptAllowance(any(), any(), any(), any())).thenThrow(RuntimeException("offline")) sut.activate(identity) assertTrue(sut.acceptOffersFromAllowers().isEmpty(), "A failed accept is not announced") @@ -392,7 +426,7 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { assertEquals(listOf(fixtures.counterpartyKey), accepted.map { it.counterparty }) sut.markOffersAnnounced(accepted) assertTrue(sut.acceptOffersFromAllowers().isEmpty()) - verify(sdk, times(2)).acceptAllowance(any(), any(), any()) + verify(sdk, times(2)).acceptAllowance(any(), any(), any(), any()) } @Test @@ -404,7 +438,7 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { assertTrue(sut.acceptOffersFromAllowers(canAnnounce = { false }).isEmpty()) assertTrue(sut.acceptOffersFromAllowers(canContinue = { false }).isEmpty()) - verify(sdk, never()).acceptAllowance(any(), any(), any()) + verify(sdk, never()).acceptAllowance(any(), any(), any(), any()) } @Test @@ -417,20 +451,26 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { proposedByMe = false, ) records = listOf(receivedProposal(), secondOffer) - whenever(sdk.acceptAllowance(any(), any(), any())).thenAnswer { records.first() } + var isActive = true + whenever(sdk.acceptAllowance(any(), any(), any(), any())).doSuspendableAnswer { + it.getArgument Unit>(3).invoke() + records = listOf(fixtures.record(localRole = AllowanceLocalRole.ALLOWEE, proposedByMe = false), secondOffer) + isActive = false + records.first() + } sut.activate(identity) - var checks = 0 - val announced = sut.acceptOffersFromAllowers(canContinue = { ++checks == 1 }) + val announced = sut.acceptOffersFromAllowers(canContinue = { isActive }) assertEquals(1, announced.size, "An offer already accepted is announced, since it is never announced later") - verify(sdk, times(1)).acceptAllowance(any(), any(), any()) + verify(sdk, times(1)).acceptAllowance(any(), any(), any(), any()) } @Test fun `offer whose accept committed as its refresh was cancelled is announced once on the next refresh`() = test { records = listOf(receivedProposal()) - whenever(sdk.acceptAllowance(any(), any(), any())).thenAnswer { + whenever(sdk.acceptAllowance(any(), any(), any(), any())).doSuspendableAnswer { + it.getArgument Unit>(3).invoke() records = listOf(fixtures.record(localRole = AllowanceLocalRole.ALLOWEE, proposedByMe = false)) throw CancellationException("The app left the foreground") } @@ -449,7 +489,7 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { assertTrue(sut.acceptOffersFromAllowers().isEmpty()) assertTrue(sut.acceptOffersFromAllowers().isEmpty(), "It is announced once") assertTrue(localState.acceptingOfferIds.isEmpty()) - verify(sdk, times(1)).acceptAllowance(any(), any(), any()) + verify(sdk, times(1)).acceptAllowance(any(), any(), any(), any()) } @Test @@ -503,7 +543,7 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { assertTrue(sut.acceptOffersFromAllowers().isEmpty()) - verify(sdk, never()).acceptAllowance(any(), any(), any()) + verify(sdk, never()).acceptAllowance(any(), any(), any(), any()) } @Test @@ -516,7 +556,7 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { val announced = sut.acceptOffersFromAllowers(canAnnounce = { ++checks == 1 }) assertTrue(announced.isEmpty(), "An accept that outlived its session is not announced") - verify(sdk).acceptAllowance(fixtures.counterpartyKey, ALLOWANCE_ID, 1uL) + verify(sdk).acceptAllowance(eq(fixtures.counterpartyKey), eq(ALLOWANCE_ID), eq(1uL), any()) } @Test @@ -539,7 +579,8 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { ), offerX, ) - whenever(sdk.acceptAllowance(any(), any(), any())).thenAnswer { + whenever(sdk.acceptAllowance(any(), any(), any(), any())).doSuspendableAnswer { + it.getArgument Unit>(3).invoke() if (it.getArgument(1) == "Y") { records = listOf( fixtures.record( @@ -564,21 +605,22 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { sut.acceptOffersFromAllowers() - verify(sdk).acceptAllowance(eq(fixtures.counterpartyKey), eq("X"), any()) - verify(sdk, never()).acceptAllowance(eq(asker), eq("X"), any()) + verify(sdk).acceptAllowance(eq(fixtures.counterpartyKey), eq("X"), any(), any()) + verify(sdk, never()).acceptAllowance(eq(asker), eq("X"), any(), any()) } @Test fun `offer accepted after the identity changed is not announced`() = test { records = listOf(receivedProposal()) - whenever(sdk.acceptAllowance(any(), any(), any())).thenAnswer { + whenever(sdk.acceptAllowance(any(), any(), any(), any())).doSuspendableAnswer { + it.getArgument Unit>(3).invoke() sut.deactivate() records.single() } sut.activate(identity) assertTrue(sut.acceptOffersFromAllowers().isEmpty()) - verify(sdk).acceptAllowance(fixtures.counterpartyKey, ALLOWANCE_ID, 1uL) + verify(sdk).acceptAllowance(eq(fixtures.counterpartyKey), eq(ALLOWANCE_ID), eq(1uL), any()) } @Test @@ -589,7 +631,7 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { assertTrue(sut.acceptOffersFromAllowers().isEmpty()) - verify(sdk, never()).acceptAllowance(any(), any(), any()) + verify(sdk, never()).acceptAllowance(any(), any(), any(), any()) assertEquals(entryKey, sut.proposalForPresentation()?.id) assertEquals(PaykitAllowance.Status.AWAITING_MY_ANSWER, sut.entries.value.single().status(fixtures.now)) } @@ -621,7 +663,7 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { assertTrue(sut.acceptOffersFromAllowers().isEmpty()) - verify(sdk, never()).acceptAllowance(any(), any(), any()) + verify(sdk, never()).acceptAllowance(any(), any(), any(), any()) } @Test @@ -630,7 +672,7 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { assertTrue(sut.acceptOffersFromAllowers().isEmpty()) - verify(sdk, never()).acceptAllowance(any(), any(), any()) + verify(sdk, never()).acceptAllowance(any(), any(), any(), any()) } @Test @@ -644,7 +686,10 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { lastEventAt = "2026-09-01T10:00:00Z", ) records = listOf(offer, ask) - whenever(sdk.acceptAllowance(any(), any(), any())).thenReturn(ask) + whenever(sdk.acceptAllowance(any(), any(), any(), any())).doSuspendableAnswer { + it.getArgument Unit>(3).invoke() + ask + } sut.activate(identity) // The offer is accepted automatically, so the sheet presents the other contact's ask. @@ -653,8 +698,8 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { assertEquals(fixtures.otherCounterpartyKey, presented.counterparty) assertTrue(sut.accept(presented.id).isSuccess) - verify(sdk).acceptAllowance(fixtures.otherCounterpartyKey, ALLOWANCE_ID, 1uL) - verify(sdk, never()).acceptAllowance(eq(fixtures.counterpartyKey), any(), any()) + verify(sdk).acceptAllowance(eq(fixtures.otherCounterpartyKey), eq(ALLOWANCE_ID), eq(1uL), any()) + verify(sdk, never()).acceptAllowance(eq(fixtures.counterpartyKey), any(), any(), any()) } @Test @@ -666,12 +711,15 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { terms = fixtures.terms(perPaymentMaximum = null, monthlyLimit = null, expiresAt = "2027-09-24T12:00:00Z"), ) records = listOf(expiryOnly) - whenever(sdk.acceptAllowance(any(), any(), any())).thenReturn(expiryOnly) + whenever(sdk.acceptAllowance(any(), any(), any(), any())).doSuspendableAnswer { + it.getArgument Unit>(3).invoke() + expiryOnly + } sut.activate(identity) assertNull(sut.proposalForPresentation()) assertTrue(sut.accept(entryKey).isFailure) - verify(sdk, never()).acceptAllowance(any(), any(), any()) + verify(sdk, never()).acceptAllowance(any(), any(), any(), any()) } @Test @@ -905,7 +953,8 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { ) private fun acceptFlipsRecordToActive() { - whenever { sdk.acceptAllowance(any(), any(), any()) }.thenAnswer { + whenever { sdk.acceptAllowance(any(), any(), any(), any()) }.doSuspendableAnswer { + it.getArgument Unit>(3).invoke() records = listOf(fixtures.record(localRole = AllowanceLocalRole.ALLOWEE, proposedByMe = false)) records.single() } diff --git a/changelog.d/next/1686.fixed.md b/changelog.d/next/1686.fixed.md index 0bb5e1f700..95cf1e5b08 100644 --- a/changelog.d/next/1686.fixed.md +++ b/changelog.d/next/1686.fixed.md @@ -1 +1 @@ -Wallet restore finishes without waiting for optional profile refresh, retries missing profiles after reconnecting, and protects complete backups from incomplete identity data. +Wallet restore finishes without optional profile refresh waits and retries missing profiles after reconnecting, while complete backups reject incomplete identity data and queued allowance offers respect disabled allowances. From 78269d8a1cae1ac127be93a96fba16f7d68d1019 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 1 Nov 2026 06:05:32 +0200 Subject: [PATCH 28/61] Preserve active allowance ownership during contact refresh --- .../repositories/PaykitAllowanceRepo.kt | 2 +- .../repositories/PaykitAllowanceRepoTest.kt | 52 +++++++++++++++++++ changelog.d/next/1686.fixed.md | 2 +- 3 files changed, 54 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt index 0d3384955f..80c5b0311a 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt @@ -189,7 +189,7 @@ class PaykitAllowanceRepo @Inject constructor( } withContext(ioDispatcher) { val identityChanged = activeIdentity != normalizedIdentity - activation = Activation(normalizedIdentity) + if (identityChanged) activation = Activation(normalizedIdentity) executor.activate(normalizedIdentity) if (identityChanged) { manualRequestSignatures.clear() diff --git a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt index d080b226c2..bd89682e41 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt @@ -354,6 +354,58 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { verify(sdk).processOutboundPrivateMessages(fixtures.counterpartyKey) } + @Test + fun `same identity activation keeps a queued manual acceptance valid`() = test { + records = listOf(receivedAsk()) + val waiting = CompletableDeferred() + val release = CompletableDeferred() + var accepted = 0 + whenever(sdk.acceptAllowance(any(), any(), any(), any())).doSuspendableAnswer { + waiting.complete(Unit) + release.await() + it.getArgument Unit>(3).invoke() + accepted += 1 + records.single() + } + sut.activate(identity) + val accepting = async { sut.accept(entryKey) } + waiting.await() + + sut.activate(identity) + release.complete(Unit) + + assertTrue(accepting.await().isSuccess) + assertEquals(1, accepted) + verify(sdk, times(1)).acceptAllowance(any(), any(), any(), any()) + verify(sdk).processOutboundPrivateMessages(fixtures.counterpartyKey) + } + + @Test + fun `same identity activation keeps a queued offer acceptance valid`() = test { + records = listOf(receivedProposal()) + val waiting = CompletableDeferred() + val release = CompletableDeferred() + var accepted = 0 + whenever(sdk.acceptAllowance(any(), any(), any(), any())).doSuspendableAnswer { + waiting.complete(Unit) + release.await() + it.getArgument Unit>(3).invoke() + accepted += 1 + records.single() + } + sut.activate(identity) + val accepting = async { sut.acceptOffersFromAllowers() } + waiting.await() + + sut.activate(identity) + release.complete(Unit) + + assertEquals(listOf(fixtures.counterpartyKey), accepting.await().map { it.counterparty }) + assertEquals(1, accepted) + verify(sdk, times(1)).acceptAllowance(any(), any(), any(), any()) + verify(sdk).processOutboundPrivateMessages(fixtures.counterpartyKey) + } + @Test fun `paused repository does not accept a queued offer`() = test { for (reactivate in listOf(false, true)) { diff --git a/changelog.d/next/1686.fixed.md b/changelog.d/next/1686.fixed.md index 95cf1e5b08..c42042a9a7 100644 --- a/changelog.d/next/1686.fixed.md +++ b/changelog.d/next/1686.fixed.md @@ -1 +1 @@ -Wallet restore finishes without optional profile refresh waits and retries missing profiles after reconnecting, while complete backups reject incomplete identity data and queued allowance offers respect disabled allowances. +Wallet restore finishes without optional profile refresh waits and retries missing profiles after reconnecting, while complete backups reject incomplete identity data and queued allowance acceptance survives contact sync but respects disabled allowances. From 1b1426fbebeccd616c29311fa5bf652089727a84 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 1 Nov 2026 22:32:12 +0100 Subject: [PATCH 29/61] fix: preserve pending profile setup and revoke stale activation --- .../repositories/PaykitAllowanceRepo.kt | 30 ++++++++--- .../java/to/bitkit/repositories/PubkyRepo.kt | 6 ++- .../to/bitkit/services/PaykitSdkService.kt | 3 +- .../java/to/bitkit/viewmodels/AppViewModel.kt | 5 +- .../repositories/PaykitAllowanceRepoTest.kt | 50 +++++++++++++++++ .../to/bitkit/repositories/PubkyRepoTest.kt | 33 ++++++++++++ .../bitkit/services/PaykitSdkServiceTest.kt | 23 ++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 54 ++++++++++++++++++- changelog.d/next/1686.fixed.md | 2 +- 9 files changed, 192 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt index 80c5b0311a..87872e8d4a 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt @@ -105,6 +105,8 @@ class PaykitAllowanceRepo @Inject constructor( private val scope = appScope(ioDispatcher, TAG) private val refreshMutex = Mutex() private val publishLock = Any() + private val activationLock = Any() + private var activationRevision = Any() private val isProcessingRequests = AtomicBoolean(false) private val isAcceptingOffers = AtomicBoolean(false) private val updates = MutableStateFlow(0) @@ -181,16 +183,22 @@ class PaykitAllowanceRepo @Inject constructor( // region Lifecycle - suspend fun activate(identity: String?) { + suspend fun activate(identity: String?, canActivate: suspend () -> Boolean = { true }) { val normalizedIdentity = identity?.let(PubkyPublicKeyFormat::normalized) if (normalizedIdentity == null) { deactivate() return } + val revision = synchronized(activationLock) { activationRevision } withContext(ioDispatcher) { - val identityChanged = activeIdentity != normalizedIdentity - if (identityChanged) activation = Activation(normalizedIdentity) - executor.activate(normalizedIdentity) + if (!canActivate()) return@withContext + val identityChanged = synchronized(activationLock) { + if (activationRevision !== revision) return@withContext + val changed = activeIdentity != normalizedIdentity + if (changed) activation = Activation(normalizedIdentity) + executor.activate(normalizedIdentity) + changed + } if (identityChanged) { manualRequestSignatures.clear() _offersToAnnounce.update { emptyList() } @@ -202,8 +210,11 @@ class PaykitAllowanceRepo @Inject constructor( } fun deactivate() { - executor.activate(null) - clear() + synchronized(activationLock) { + activationRevision = Any() + executor.activate(null) + clear() + } } /** @@ -211,8 +222,11 @@ class PaykitAllowanceRepo @Inject constructor( * the executor settle attempts left open before allowances were turned off; null keeps its current one. */ suspend fun pause(identity: String? = null) { - executor.stopAdmitting() - clear() + synchronized(activationLock) { + activationRevision = Any() + executor.stopAdmitting() + clear() + } val normalizedIdentity = identity?.let(PubkyPublicKeyFormat::normalized) ?: return withContext(ioDispatcher) { executor.pause(normalizedIdentity) } } diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index e722c3dd25..0de7df3737 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -399,7 +399,11 @@ class PubkyRepo @Inject constructor( loadIdentityData() } else { currentSignIn()?.takeIf { _profile.value == null }?.let { signIn -> - scope.launch { loadProfile(signIn, onlyIfMissing = true) } + scope.launch { + if (!settingsStore.isPubkyProfileSetupPending.first()) { + loadProfile(signIn, onlyIfMissing = true) + } + } } } restored diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt index 3ac3016d1a..b7581de454 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt @@ -1325,8 +1325,7 @@ class PaykitSdkService @Inject constructor( ): AllowanceRecord { isSetup.await() return operationLock.withLock(Priority.Interactive) { - withStateRevisionTracking { handle -> - admit() + withStateRevisionTracking(beforeOperation = admit) { handle -> completeSdkCall { handle.acceptAllowance(counterparty, allowanceId, expectedProposalStreamItemId) } } } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 95bcf05879..965e6d7f15 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -991,7 +991,10 @@ class AppViewModel @Inject constructor( isPaymentRequestIdentityActivating = true val requestRefresh = try { paykitPaymentRequestRepo.activate(state.publicKey) - if (state.areAllowancesEnabled) paykitAllowanceRepo.activate(state.publicKey) + if (!isStillCurrent()) return + if (state.areAllowancesEnabled && areAllowancesEnabled()) { + paykitAllowanceRepo.activate(state.publicKey) { areAllowancesEnabled() && isStillCurrent() } + } // Allowances may have turned off while this activated, before the activation took effect. if (!state.areAllowancesEnabled || !areAllowancesEnabled()) paykitAllowanceRepo.pause(state.publicKey) if (!pubkyRepo.isCurrent(signIn)) return diff --git a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt index bd89682e41..1c90c987ab 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceRepoTest.kt @@ -10,10 +10,12 @@ import com.synonym.paykit.OutboundPrivateSendReport import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.update +import kotlinx.coroutines.test.StandardTestDispatcher import org.junit.After import org.junit.Assume.assumeTrue import org.junit.Before @@ -117,6 +119,54 @@ class PaykitAllowanceRepoTest : BaseUnitTest() { // region Entries + @Test + fun `pause revokes an activation queued on the dispatcher`() = test { + val queued = PaykitAllowanceRepo( + ioDispatcher = StandardTestDispatcher(testScheduler), + paykitSdkService = sdk, + executor = executor, + lightningRepo = lightningRepo, + activityRepo = activityRepo, + clock = clock, + ) + val activation = async(start = CoroutineStart.UNDISPATCHED) { queued.activate(identity) } + + queued.pause() + activation.await() + + verify(executor, never()).activate(identity) + } + + @Test + fun `pause revokes activation while its caller admission is suspended`() = test { + val admissionStarted = CompletableDeferred() + val finishAdmission = CompletableDeferred() + val activation = async { + sut.activate(identity) { + admissionStarted.complete(Unit) + finishAdmission.await() + true + } + } + admissionStarted.await() + sut.pause() + finishAdmission.complete(Unit) + activation.await() + + verify(executor, never()).activate(identity) + sut.activate(identity) + verify(executor).activate(identity) + } + + @Test + fun `rejected activation does not recover or refresh allowances`() = test { + sut.activate(identity) { false } + + verify(executor, never()).activate(identity) + verify(executor, never()).recover(any()) + verify(sdk, never()).listAllowances(any()) + } + @Test fun `entries list one grant per contact with the grant's limits`() = test { records = listOf( diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 81a7f15999..3ebe00ec95 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -2461,6 +2461,39 @@ class PubkyRepoTest : BaseUnitTest() { verify(pubkyService).resolveContactProfile(VALID_SELF_KEY, true) } + @Test + fun `reconnect skips expected missing profile until local setup completes`() = test { + sut.awaitInitialization() + whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn("restored_session") + whenever(pubkyService.importSession("restored_session")).thenReturn(VALID_SELF_KEY) + whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).thenAnswer { + throw PaykitException.Transport("transport_error", "offline") + } + assertTrue(sut.restoreSessionIfNeeded()) + val originalSignIn = assertNotNull(sut.currentSignIn()) + profileSetupPending.value = true + clearInvocations(pubkyService) + + repeat(3) { + assertFalse(sut.restoreSessionIfNeeded()) + yield() + advanceUntilIdle() + } + + assertTrue(sut.isCurrent(originalSignIn)) + verify(pubkyService, never()).resolveContactProfile(VALID_SELF_KEY, true) + verify(pubkyService, never()).importSession(any()) + profileSetupPending.value = false + doSuspendableAnswer { + createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile(name = "Completed")) + }.whenever(pubkyService).resolveContactProfile(VALID_SELF_KEY, true) + assertFalse(sut.restoreSessionIfNeeded()) + yield() + advanceUntilIdle() + assertEquals("Completed", sut.profile.value?.name) + verify(pubkyService).resolveContactProfile(VALID_SELF_KEY, true) + } + @Test fun `active identity retries its missing profile on reconnect without delaying wallet maintenance`() = test { sut.awaitInitialization() diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt index 2c3cc12ac6..7251792372 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt @@ -1804,6 +1804,29 @@ class PaykitSdkServiceTest { verify(sdk, never()).processOutboundPrivateMessages(any()) } + @Test + fun `rejected allowance admission preserves cached backup and version`() = runTest { + val sdk = mock() + whenever(sdk.stateRevision()).thenReturn("state") + whenever(sdk.observedBackupStateRevision()).thenReturn(ObservedBackupStateRevision("state", "backup")) + whenever { sdk.backupStateRevision() }.thenReturn("backup") + whenever { sdk.processPendingPrivateMessages() }.thenReturn(emptyList()) + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + service.processPendingPrivateMessages() + val originalVersion = service.backupStateVersion.value + val failure = AppError("Admission revoked") + + val thrown = assertFailsWith { + service.acceptAllowance(RING_PUBKY, "allowance", 1uL) { throw failure } + } + + assertSame(failure, thrown) + verify(sdk, never()).acceptAllowance(any(), any(), any()) + assertEquals(originalVersion, service.backupStateVersion.value) + service.processPendingPrivateMessages() + verify(sdk, times(1)).backupStateRevision() + } + @Test fun `cancelling active acceptance waits for its durable call and preserves backup notification`() = runTest { val sdk = mock() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 89de855cf8..6d62184ce3 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -326,6 +326,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } private val isRecoveryMode = MutableStateFlow(false) private val isPaykitEnabled = MutableStateFlow(false) + private val areAllowancesEnabled = MutableStateFlow(true) private val walletState = MutableStateFlow(WalletState()) private val nodeEventUpdates = MutableSharedFlow() private val pubkyPublicKey = MutableStateFlow(null) @@ -904,7 +905,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { private fun stubSettingsStore() { whenever(settingsStore.data).thenReturn(settingsData) whenever(settingsStore.isPaykitEnabled).thenReturn(isPaykitEnabled) - whenever(settingsStore.areAllowancesEnabled).thenReturn(flowOf(true)) + whenever(settingsStore.areAllowancesEnabled).thenReturn(areAllowancesEnabled) whenever { settingsStore.update(any()) }.thenAnswer { val transform = it.getArgument<(SettingsData) -> SettingsData>(0) settingsData.value = transform(settingsData.value) @@ -3274,6 +3275,57 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals("PaymentRequestUnavailableToast", terminalToast.testTag) } + @Test + fun `contact activation cannot reopen allowances after switching off`() = test { + val activationStarted = CompletableDeferred() + val finishActivation = CompletableDeferred() + whenever(paykitPaymentRequestRepo.activate(testPublicKey)).doSuspendableAnswer { + activationStarted.complete(Unit) + finishActivation.await() + } + enablePaykitUi() + pubkyPublicKey.value = testPublicKey + activationStarted.await() + + areAllowancesEnabled.value = false + runCurrent() + verify(paykitAllowanceRepo).pause() + clearInvocations(paykitAllowanceRepo) + + finishActivation.complete(Unit) + runCurrent() + + verify(paykitAllowanceRepo, never()).activate(anyOrNull(), any()) + } + + @Test + fun `allowance admission rechecks deletion after the settings read`() = test { + val settingsReadStarted = CompletableDeferred() + val finishSettingsRead = CompletableDeferred() + var admitted: Boolean? = null + whenever { paykitAllowanceRepo.activate(anyOrNull(), any()) }.doSuspendableAnswer { + val admission = it.getArgument Boolean>(1) + whenever(settingsStore.areAllowancesEnabled).thenReturn( + flow { + settingsReadStarted.complete(Unit) + finishSettingsRead.await() + emit(true) + } + ) + admitted = admission() + } + pubkyPublicKey.value = testPublicKey + isPaykitEnabled.value = true + pubkyContactsLoadVersion.value = 1L + runCurrent() + settingsReadStarted.await() + isProfileDeletionInProgress.value = true + finishSettingsRead.complete(Unit) + runCurrent() + + assertEquals(false, admitted) + } + @Test fun `latest identity activation blocks retries from the previous payment request queue`() = test { val request = paymentRequest() diff --git a/changelog.d/next/1686.fixed.md b/changelog.d/next/1686.fixed.md index c42042a9a7..23f68f489c 100644 --- a/changelog.d/next/1686.fixed.md +++ b/changelog.d/next/1686.fixed.md @@ -1 +1 @@ -Wallet restore finishes without optional profile refresh waits and retries missing profiles after reconnecting, while complete backups reject incomplete identity data and queued allowance acceptance survives contact sync but respects disabled allowances. +Wallet restore finishes without optional profile refresh waits and retries missing profiles after reconnecting without reloading profiles still being set up, while complete backups reject incomplete identity data and queued allowance acceptance survives contact sync but respects disabled allowances and profile removal. From 181d664c38a40df156cad4388168b5ab2df132c4 Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 2 Nov 2026 00:04:31 +0100 Subject: [PATCH 30/61] fix: resume allowances after a paused activation --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 18 +++++- .../viewmodels/AppViewModelSendFlowTest.kt | 55 +++++++++++++++++++ changelog.d/next/1686.fixed.md | 2 +- journeys/allowances/allowances-turned-off.xml | 4 +- 4 files changed, 74 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 965e6d7f15..ed33346ba1 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -576,6 +576,7 @@ class AppViewModel @Inject constructor( private var isCompletingRestoreHold = false private var addressValidationJob: Job? = null private var lastPrivatePaykitContactKeys: Set = emptySet() + private val allowancePauseRevision = MutableStateFlow(0L) private val isPaykitEnabled = settingsStore.isPaykitEnabled .map { PaykitFeatureFlags.isUiEnabled(it) } .stateIn(viewModelScope, SharingStarted.Eagerly, false) @@ -932,15 +933,20 @@ class AppViewModel @Inject constructor( combine( settingsStore.isPaykitEnabled.map { PaykitFeatureFlags.isUiEnabled(it) }, settingsStore.areAllowancesEnabled, - ) { isPaykitEnabled, areAllowancesEnabled -> isPaykitEnabled to areAllowancesEnabled }, + allowancePauseRevision, + ) { isPaykitEnabled, areAllowancesEnabled, pauseRevision -> + Triple(isPaykitEnabled, areAllowancesEnabled, pauseRevision) + }, privatePaykitRepo.isProfileDeletionInProgress, - ) { publicKey, contacts, contactsLoadVersion, (isPaykitEnabled, areAllowancesEnabled), deleting -> + ) { publicKey, contacts, contactsLoadVersion, allowanceSettings, deleting -> + val (isPaykitEnabled, areAllowancesEnabled, pauseRevision) = allowanceSettings PaykitContactSyncState( publicKey = publicKey, contactKeys = contacts.map { it.publicKey }.toSet(), contactsLoaded = contactsLoadVersion > 0L, isPaykitEnabled = isPaykitEnabled, areAllowancesEnabled = areAllowancesEnabled, + allowancePauseRevision = pauseRevision, ).takeUnless { deleting } } .distinctUntilChanged() @@ -952,7 +958,11 @@ class AppViewModel @Inject constructor( settingsStore.areAllowancesEnabled .distinctUntilChanged() .filter { !it } - .collect { paykitAllowanceRepo.pause() } + .collect { + paykitAllowanceRepo.pause() + // Off/on can coalesce while contact sync waits; revoked activation still needs a fresh sync. + allowancePauseRevision.update { it + 1 } + } } } @@ -1019,6 +1029,7 @@ class AppViewModel @Inject constructor( private fun isCurrentPaykitContactSync(state: PaykitContactSyncState, signIn: PubkySignIn): Boolean = pubkyRepo.isCurrent(signIn) && isPaykitEnabled.value && !privatePaykitRepo.isProfileDeletionInProgress.value && + state.allowancePauseRevision == allowancePauseRevision.value && (pubkyRepo.contactsLoadVersion.value > 0L) == state.contactsLoaded && pubkyRepo.contacts.value.map { it.publicKey }.toSet() == state.contactKeys @@ -9054,6 +9065,7 @@ private data class PaykitContactSyncState( val contactsLoaded: Boolean, val isPaykitEnabled: Boolean, val areAllowancesEnabled: Boolean, + val allowancePauseRevision: Long, ) sealed class SendEffect { diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 6d62184ce3..c57be8d4c0 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -138,6 +138,7 @@ import to.bitkit.models.PaykitAmount import to.bitkit.models.PaykitAsset import to.bitkit.models.PaykitRequestPricing import to.bitkit.models.PubkyProfile +import to.bitkit.models.PubkyPublicKeyFormat import to.bitkit.models.SamRockPaymentMethod import to.bitkit.models.SamRockSetupRequest import to.bitkit.models.SendFailureDetails @@ -170,6 +171,8 @@ import to.bitkit.repositories.OnchainSendEvidence import to.bitkit.repositories.OnchainSendNotDispatchedError import to.bitkit.repositories.OnchainSendOutcome import to.bitkit.repositories.PaykitAllowanceEvent +import to.bitkit.repositories.PaykitAllowanceExecutor +import to.bitkit.repositories.PaykitAllowanceLocalState import to.bitkit.repositories.PaykitAllowanceRepo import to.bitkit.repositories.PaykitBillingPeriod import to.bitkit.repositories.PaykitOnchainPaymentProofResolution @@ -3298,6 +3301,58 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(paykitAllowanceRepo, never()).activate(anyOrNull(), any()) } + @Test + fun `off on during allowance admission activates the latest enabled state`() = test { + val sdk = mock() + val executor = mock() + whenever(executor.events).thenReturn(MutableSharedFlow()) + whenever(executor.localState(any())).thenReturn(PaykitAllowanceLocalState()) + whenever(sdk.listAllowances(any())).thenReturn(emptyList()) + val realAllowances = PaykitAllowanceRepo( + ioDispatcher = testDispatcher, + paykitSdkService = sdk, + executor = executor, + lightningRepo = lightningRepo, + activityRepo = activityRepo, + clock = Clock.System, + ) + val activationStarted = CompletableDeferred() + val finishActivation = CompletableDeferred() + var holdNextAdmission = true + whenever { paykitAllowanceRepo.activate(anyOrNull(), any()) }.doSuspendableAnswer { + val identity = it.getArgument(0) + val admission = it.getArgument Boolean>(1) + realAllowances.activate(identity) { + if (holdNextAdmission) { + holdNextAdmission = false + activationStarted.complete(Unit) + finishActivation.await() + } + admission() + } + } + whenever { paykitAllowanceRepo.pause(anyOrNull()) }.doSuspendableAnswer { + realAllowances.pause(it.getArgument(0)) + } + enablePaykitUi() + pubkyPublicKey.value = testPublicKey + activationStarted.await() + + areAllowancesEnabled.value = false + runCurrent() + verify(executor).stopAdmitting() + areAllowancesEnabled.value = true + runCurrent() + verify(executor, never()).activate(any()) + + finishActivation.complete(Unit) + runCurrent() + + val identity = requireNotNull(PubkyPublicKeyFormat.normalized(testPublicKey)) + verify(executor).activate(identity) + verify(executor).recover(identity) + } + @Test fun `allowance admission rechecks deletion after the settings read`() = test { val settingsReadStarted = CompletableDeferred() diff --git a/changelog.d/next/1686.fixed.md b/changelog.d/next/1686.fixed.md index 23f68f489c..7a9d63b22e 100644 --- a/changelog.d/next/1686.fixed.md +++ b/changelog.d/next/1686.fixed.md @@ -1 +1 @@ -Wallet restore finishes without optional profile refresh waits and retries missing profiles after reconnecting without reloading profiles still being set up, while complete backups reject incomplete identity data and queued allowance acceptance survives contact sync but respects disabled allowances and profile removal. +Wallet restore finishes without optional profile refresh waits, missing profiles retry after reconnecting without interrupting active setup, incomplete identity backups remain blocked, and allowances resume safely after re-enabling without reviving cancelled work. diff --git a/journeys/allowances/allowances-turned-off.xml b/journeys/allowances/allowances-turned-off.xml index 59af61c2e7..12b8acabc7 100644 --- a/journeys/allowances/allowances-turned-off.xml +++ b/journeys/allowances/allowances-turned-off.xml @@ -2,7 +2,9 @@ Allowances can be turned off from Dev Settings. With them off the Subscriptions screen shows only the Overview and Payments tabs, and a request covered by an Active allowance is not paid - automatically: it opens as an ordinary Payment Request. Turning them back on shows the tab again. + automatically: it opens as an ordinary Payment Request. Turning them back on restores both the tab + and its Active allowance row. On Android, repeat the off/on sequence while contact loading is + delayed, then let it finish: the latest enabled state must restore the row without restarting the app. Launch the E2E Bitkit app on both instances with an Active allowance, per set-and-accept.xml From b6751e22956653c4f2a80112143880b47298e30d Mon Sep 17 00:00:00 2001 From: benk10 Date: Sat, 31 Oct 2026 00:34:36 +0200 Subject: [PATCH 31/61] test: report Pubky alias state on routing failures --- .../to/bitkit/build/PubkyAuthManifestTest.kt | 62 +++++++++++++++---- 1 file changed, 50 insertions(+), 12 deletions(-) diff --git a/app/src/test/java/to/bitkit/build/PubkyAuthManifestTest.kt b/app/src/test/java/to/bitkit/build/PubkyAuthManifestTest.kt index 8354250793..9029439678 100644 --- a/app/src/test/java/to/bitkit/build/PubkyAuthManifestTest.kt +++ b/app/src/test/java/to/bitkit/build/PubkyAuthManifestTest.kt @@ -74,18 +74,25 @@ class PubkyAuthManifestTest { ) val allUrls = signupUrls + authUrls + unrelatedUrls - assertRoutes(packageManager, application.packageName, allUrls, null) + assertRoutes(packageManager, application.packageName, allUrls, null, "initial defaults") packageManager.setComponentEnabledSetting( signupAlias, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP, ) - assertRoutes(packageManager, application.packageName, signupUrls + authUrls.last(), signupAlias) + assertRoutes( + packageManager, + application.packageName, + signupUrls + authUrls.last(), + signupAlias, + "signup enabled", + ) assertRoutes( packageManager, application.packageName, authUrls.dropLast(1) + unrelatedUrls, null, + "signup enabled", ) packageManager.setComponentEnabledSetting( @@ -98,15 +105,15 @@ class PubkyAuthManifestTest { PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP, ) - assertRoutes(packageManager, application.packageName, authUrls, authAlias) - assertRoutes(packageManager, application.packageName, signupUrls + unrelatedUrls, null) + assertRoutes(packageManager, application.packageName, authUrls, authAlias, "authorization enabled") + assertRoutes(packageManager, application.packageName, signupUrls + unrelatedUrls, null, "authorization enabled") packageManager.setComponentEnabledSetting( authAlias, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP, ) - assertRoutes(packageManager, application.packageName, allUrls, null) + assertRoutes(packageManager, application.packageName, allUrls, null, "both explicitly disabled") } private fun assertRoutes( @@ -114,19 +121,50 @@ class PubkyAuthManifestTest { packageName: String, urls: List, alias: ComponentName?, + phase: String, ) { urls.forEach { val intent = Intent(Intent.ACTION_VIEW, it.toUri()) .addCategory(Intent.CATEGORY_BROWSABLE) .setPackage(packageName) val resolved = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) - if (alias == null) { - assertTrue(resolved.isEmpty(), it) - } else { - val activity = resolved.single().activityInfo - assertEquals(alias.className, activity.name, it) - assertEquals("to.bitkit.ui.MainActivity", activity.targetActivity) - assertTrue(activity.exported) + fun diagnostics() = buildString { + append("phase=$phase url=$it package=$packageName expected=${alias?.className}") + listOf("to.bitkit.ui.MainActivityPubkySignup", "to.bitkit.ui.MainActivityPubkyAuth").forEach { name -> + val component = ComponentName(packageName, name) + append("; alias=$name override=${packageManager.getComponentEnabledSetting(component)}") + runCatching { + packageManager.getActivityInfo( + component, + PackageManager.ComponentInfoFlags.of(PackageManager.MATCH_DISABLED_COMPONENTS.toLong()), + ) + }.onSuccess { info -> + append(" enabled=${info.enabled} exported=${info.exported} target=${info.targetActivity}") + }.onFailure { error -> + append(" activityInfoError=${error.javaClass.simpleName}") + } + } + resolved.forEach { result -> + val info = result.activityInfo + append("; resolved=${info.packageName}/${info.name} target=${info.targetActivity}") + append(" enabled=${info.enabled} exported=${info.exported} match=${result.match}") + } + } + try { + if (alias == null) { + assertTrue(resolved.isEmpty(), it) + } else { + assertEquals(1, resolved.size, it) + val activity = resolved.single().activityInfo + assertEquals(alias.className, activity.name, it) + assertEquals("to.bitkit.ui.MainActivity", activity.targetActivity) + assertTrue(activity.exported) + } + } catch (error: AssertionError) { + val message = runCatching { diagnostics() }.getOrElse { diagnosticError -> + "phase=$phase url=$it diagnosticsUnavailable=${diagnosticError.javaClass.simpleName}" + } + throw AssertionError(message, error) } } } From 581fed71da6127737a2f9b734f58a7941c95325c Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 2 Nov 2026 02:37:47 +0100 Subject: [PATCH 32/61] fix: preserve cleanup and local pin recovery --- .../to/bitkit/data/ProfileRemovalStore.kt | 2 ++ .../to/bitkit/ui/components/AuthCheckView.kt | 3 +- .../recovery/WalletResetRecoveryScreen.kt | 3 ++ .../to/bitkit/usecases/WipeWalletUseCase.kt | 6 ++-- .../bitkit/usecases/WipeWalletUseCaseTest.kt | 35 ++++++++++++++++++- changelog.d/next/1693.fixed.md | 2 +- journeys/security/README.md | 13 +++++++ .../security/wallet-reset-recovery-pin.xml | 16 +++++++++ 8 files changed, 74 insertions(+), 6 deletions(-) create mode 100644 journeys/security/wallet-reset-recovery-pin.xml diff --git a/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt b/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt index 5ce56c1694..0532199073 100644 --- a/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt +++ b/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt @@ -105,6 +105,8 @@ class ProfileRemovalStore internal constructor(private val store: DataStore Unit)? = null, onBack: (() -> Unit)? = null, onValidatePin: ((String) -> Boolean)? = null, + onClickForgotPin: (() -> Unit)? = null, ) { val isBiometricsEnabled by settingsViewModel.isBiometricEnabled.collectAsStateWithLifecycle() val attemptsRemaining by appViewModel.pinAttemptsRemaining.collectAsStateWithLifecycle() @@ -64,7 +65,7 @@ fun AuthCheckView( validatePin = onValidatePin ?: appViewModel::validatePin, onSuccess = onSuccess, onBack = onBack, - onClickForgotPin = { appViewModel.setShowForgotPin(true) }, + onClickForgotPin = onClickForgotPin ?: { appViewModel.setShowForgotPin(true) }, ) } diff --git a/app/src/main/java/to/bitkit/ui/screens/recovery/WalletResetRecoveryScreen.kt b/app/src/main/java/to/bitkit/ui/screens/recovery/WalletResetRecoveryScreen.kt index e426f632e6..f2c64a04f7 100644 --- a/app/src/main/java/to/bitkit/ui/screens/recovery/WalletResetRecoveryScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/recovery/WalletResetRecoveryScreen.kt @@ -5,6 +5,7 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.key @@ -60,6 +61,7 @@ fun WalletResetRecoveryScreen( appViewModel.recoveryPinRequired } val pinEnabled by recoveryPinRequired.collectAsStateWithLifecycle(initialValue = null) + LaunchedEffect(appViewModel) { appViewModel.setShowForgotPin(false) } WalletResetRecoveryFlow( recovery = walletState.walletResetRecovery, busy = finishing || wiping, @@ -80,6 +82,7 @@ fun WalletResetRecoveryScreen( onSuccess = onSuccess, onBack = onBack, onValidatePin = appViewModel::validateRecoveryPin, + onClickForgotPin = onBack, ) }, phrase = { onBack -> ScopedRecoveryMnemonic(onBack) }, diff --git a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt index def335997c..f50fe525a2 100644 --- a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt @@ -83,13 +83,13 @@ class WipeWalletUseCase @Inject constructor( contactPaymentSettingsRepo.get().withWalletWipe(pubkyRepo::withWalletWipeAdmission) { paykitSdkService.withWalletWipe { expectedPendingAttemptId?.let { profileRemovalStore.requirePendingWalletReset(it) } - val pending = profileRemovalStore.pendingAttempt() - val attemptId = pending ?: UUID.randomUUID().toString() + val pending = profileRemovalStore.pendingState() + val attemptId = pending.attemptId ?: UUID.randomUUID().toString() profileRemovalStore.withAccess(attemptId, ProfileRemovalScope.WALLET_WIPE) { privatePaykitRepo.get().withProfileDeletionPaused { pause -> stopNode().getOrThrow() profileRemovalStore.begin(attemptId) - if (pending == null) cleanupRemote() + if (pending.scope != ProfileRemovalScope.WALLET_WIPE) cleanupRemote() wipeLocal(walletIndex, pause) { credentialsMayBeErased = true }.getOrThrow() profileRemovalStore.complete(attemptId) resetWalletState() diff --git a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt index 4ced0a39ea..df957ce380 100644 --- a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt @@ -55,6 +55,7 @@ import to.bitkit.data.SettingsStore import to.bitkit.data.WalletResetRecovery import to.bitkit.data.WidgetsStore import to.bitkit.data.keychain.Keychain +import to.bitkit.data.profileRemovalCorruptionHandler import to.bitkit.data.sharedpubky.SharedPubkyClient import to.bitkit.models.NodeLifecycleState import to.bitkit.repositories.ActivityRepo @@ -385,7 +386,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { @Test fun `pending restart wipe skips remote cleanup and only clears marker after local acknowledgement`() = test { val id = UUID.randomUUID().toString() - profileRemovalStore.withAccess(id) { profileRemovalStore.begin(id) } + profileRemovalStore.withAccess(id, ProfileRemovalScope.WALLET_WIPE) { profileRemovalStore.begin(id) } whenever { privatePaykitRepo.finishProfileRemoval(any()) }.doSuspendableAnswer { assertEquals(id, profileRemovalStore.pendingAttempt()) verify(keychain).wipe() @@ -398,6 +399,38 @@ class WipeWalletUseCaseTest : BaseUnitTest() { verify(privatePaykitRepo, never()).closeAndClear() } + @Test + fun `explicit reset from corrupt marker attempts endpoint cleanup before erasing credentials`() = test { + val file = folder.newFile("corrupt-removal.json").also { it.writeText("broken") } + val storage = DataStoreFactory.create( + serializer = ProfileRemovalSerializer, + corruptionHandler = profileRemovalCorruptionHandler(), + scope = backgroundScope, + produceFile = { file }, + ) + val removalStore = ProfileRemovalStore(storage) + val recovery = assertIs(removalStore.walletResetRecovery.first()) + whenever { privatePaykitRepo.removePublishedEndpointsForCleanup(any()) }.doSuspendableAnswer { + assertEquals(recovery.attemptId, removalStore.pendingAttempt()) + assertEquals(ProfileRemovalScope.WALLET_WIPE, storage.data.first().scope) + Result.success(Unit) + } + + val result = localWipe(removalStore).invoke( + resetWalletState = {}, + onSuccess = {}, + expectedPendingAttemptId = recovery.attemptId, + ) + + assertTrue(result.isSuccess) + inOrder(privatePaykitRepo, pubkyRepo, keychain) { + verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any()) + verify(pubkyRepo).removeBitkitPaymentEndpoints() + verify(keychain).wipe() + } + assertNull(removalStore.pendingAttempt()) + } + @Test fun `private persistence failure retains marker and suppresses completion callbacks`() = test { whenever { diff --git a/changelog.d/next/1693.fixed.md b/changelog.d/next/1693.fixed.md index 736100c1d5..44a4674a92 100644 --- a/changelog.d/next/1693.fixed.md +++ b/changelog.d/next/1693.fixed.md @@ -1 +1 @@ -Keep interrupted profile removal recoverable with confirmed retries while the original sign-in remains valid or a separately confirmed local Disconnect, require acknowledged endpoint cleanup even when sharing is off, preserve cleanup progress, replacement identities and incoming payment details, and wait for running payment updates before removing local data, and keep interrupted wallet resets blocked until a newly confirmed local cleanup finishes, distinguish unreadable reset state from an interrupted reset, retain authenticated read-only seed access, and show progress without a second reset action while cleanup is running. +Keep interrupted profile removal recoverable with confirmed retries or local Disconnect, preserve cleanup progress and payment details, and make wallet-reset recovery distinguish unreadable state, attempt endpoint cleanup before a fresh reset, retain authenticated read-only seed access and local forgotten-PIN navigation, and prevent duplicate actions while cleanup is running. diff --git a/journeys/security/README.md b/journeys/security/README.md index 9b8be02a9e..2aa480f082 100644 --- a/journeys/security/README.md +++ b/journeys/security/README.md @@ -3,3 +3,16 @@ `wallet-wipe-new-profile.xml` shares its action text with iOS. Android titles the Profile Error toast "Failed to create profile". Capture a screenshot as profile creation completes to check that this toast is absent, because `android layout` does not expose toasts. + +`wallet-reset-recovery-pin.xml` covers Android's restricted reset-recovery route using an already +prepared, unfunded wallet with a PIN and unreadable reset marker. It does not reset the wallet or +display its seed. Forgot PIN returns to the recovery overview and revokes the pending read-only +authorization; it must not queue the ordinary wallet's Forgot PIN sheet. A previous queued sheet +is cleared when recovery opens. Preparing the marker and checking the shared sheet state require +an isolated fixture beyond the standard journey capabilities. This route is Android-specific; +iOS profile-removal recovery is a separate flow. + +For an explicitly authorized reset in a separate disposable fixture, an unreadable marker must +attempt private and public endpoint cleanup before erasing credentials. A known interrupted +wallet wipe resumes local cleanup without automatically replaying remote operations. Capture the +marker scope and redacted operation order; component tests do not establish this network journey. diff --git a/journeys/security/wallet-reset-recovery-pin.xml b/journeys/security/wallet-reset-recovery-pin.xml new file mode 100644 index 0000000000..795a64f22d --- /dev/null +++ b/journeys/security/wallet-reset-recovery-pin.xml @@ -0,0 +1,16 @@ + + + Android-specific restricted recovery route. Use a prepared disposable, unfunded wallet with + a known PIN and an unreadable reset marker; preparation requires a controlled storage fixture. + Do not reset the wallet or enter its correct PIN in this journey. No seed display is needed. + iOS profile-removal recovery is separate from this Android wallet-reset route. + + + Open the app and verify the unreadable recovery overview, with no ordinary wallet controls + Tap Show Seed Phrase and verify the PIN prompt appears without displaying any seed + Enter one incorrect PIN and verify the prompt remains with an attempts-remaining link + Tap the attempts-remaining link and verify the recovery overview appears without a Forgot PIN sheet or reset confirmation + Tap Show Seed Phrase again and verify a fresh PIN prompt appears + Go back without entering a PIN, restart the app, and verify recovery remains pending without a queued Forgot PIN sheet + + From 595c3642f1fbb91c52dca0206ee9f8b28082eb64 Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 2 Nov 2026 05:58:38 +0100 Subject: [PATCH 33/61] fix: resume migration after cleanup state recovery --- .../java/to/bitkit/ui/RootDestinationTest.kt | 20 ++ .../main/java/to/bitkit/ui/MainActivity.kt | 4 + .../to/bitkit/viewmodels/WalletViewModel.kt | 102 ++++++---- .../java/to/bitkit/ui/WalletViewModelTest.kt | 181 ++++++++++++++++-- changelog.d/next/1693.fixed.md | 2 +- journeys/security/README.md | 9 + 6 files changed, 264 insertions(+), 54 deletions(-) diff --git a/app/src/androidTest/java/to/bitkit/ui/RootDestinationTest.kt b/app/src/androidTest/java/to/bitkit/ui/RootDestinationTest.kt index f565f997f3..eda2ede3b6 100644 --- a/app/src/androidTest/java/to/bitkit/ui/RootDestinationTest.kt +++ b/app/src/androidTest/java/to/bitkit/ui/RootDestinationTest.kt @@ -19,6 +19,7 @@ class RootDestinationTest { private fun setContent( isCriticalUpdateRequired: Boolean = false, isShowingMigrationLoading: Boolean = false, + isCheckingRNMigration: Boolean = false, walletExists: Boolean = true, isRecoveryMode: Boolean = false, walletResetRecovery: WalletResetRecovery = WalletResetRecovery.Clear, @@ -27,6 +28,7 @@ class RootDestinationTest { RootDestination( isCriticalUpdateRequired = isCriticalUpdateRequired, isShowingMigrationLoading = isShowingMigrationLoading, + isCheckingRNMigration = isCheckingRNMigration, walletExists = walletExists, isRecoveryMode = isRecoveryMode, walletResetRecovery = walletResetRecovery, @@ -46,6 +48,24 @@ class RootDestinationTest { .forEach { composeTestRule.onNodeWithTag(it).assertDoesNotExist() } } + @Test + fun migrationAdmissionPrecedesOnboarding() { + setContent(walletExists = false, isCheckingRNMigration = true) + assertOnly(TAG_MIGRATION) + } + + @Test + fun recoveryModeCannotBypassMigrationAdmission() { + setContent(walletExists = false, isRecoveryMode = true, isCheckingRNMigration = true) + assertOnly(TAG_MIGRATION) + } + + @Test + fun unreadableCleanupKeepsItsRetryAheadOfMigrationAdmission() { + setContent(isCheckingRNMigration = true, walletResetRecovery = WalletResetRecovery.Unavailable) + assertOnly(TAG_RESET) + } + @Test fun pendingResetPrecedesOnboardingAndRecoveryMode() { setContent(walletExists = false, isRecoveryMode = true, walletResetRecovery = WalletResetRecovery.Pending("test")) diff --git a/app/src/main/java/to/bitkit/ui/MainActivity.kt b/app/src/main/java/to/bitkit/ui/MainActivity.kt index b88b48c695..79e87a219d 100644 --- a/app/src/main/java/to/bitkit/ui/MainActivity.kt +++ b/app/src/main/java/to/bitkit/ui/MainActivity.kt @@ -137,6 +137,7 @@ class MainActivity : FragmentActivity() { val walletExists = walletViewModel.walletExists val walletState by walletViewModel.walletState.collectAsStateWithLifecycle() val walletResetRecovery = walletState.walletResetRecovery + val isCheckingRNMigration by walletViewModel.isCheckingRNMigration.collectAsStateWithLifecycle() val isShowingMigrationLoading by walletViewModel.isShowingMigrationLoading.collectAsStateWithLifecycle() val restoreState by walletViewModel.restoreState.collectAsStateWithLifecycle() val isCriticalUpdateRequired by appViewModel.isCriticalUpdateRequired.collectAsStateWithLifecycle() @@ -166,6 +167,7 @@ class MainActivity : FragmentActivity() { RootDestination( isCriticalUpdateRequired = isCriticalUpdateRequired, isShowingMigrationLoading = isShowingMigrationLoading, + isCheckingRNMigration = isCheckingRNMigration, walletExists = walletExists, isRecoveryMode = isRecoveryMode, walletResetRecovery = walletResetRecovery, @@ -406,6 +408,7 @@ class MainActivity : FragmentActivity() { fun RootDestination( isCriticalUpdateRequired: Boolean, isShowingMigrationLoading: Boolean, + isCheckingRNMigration: Boolean, walletExists: Boolean, isRecoveryMode: Boolean, criticalUpdate: @Composable () -> Unit, @@ -418,6 +421,7 @@ fun RootDestination( when { isCriticalUpdateRequired -> criticalUpdate() walletResetRecovery != WalletResetRecovery.Clear -> resetRecovery() + isCheckingRNMigration -> migrationLoading() isShowingMigrationLoading && !isRecoveryMode -> migrationLoading() !walletExists && !isRecoveryMode -> onboarding() else -> wallet() diff --git a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index e1b5fc5f30..f524cc3eef 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -27,6 +27,7 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.supervisorScope import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withTimeoutOrNull import org.lightningdevkit.ldknode.ChannelDataMigration import org.lightningdevkit.ldknode.PeerDetails @@ -112,6 +113,10 @@ class WalletViewModel @Inject constructor( val isRecoveryMode = lightningRepo.isRecoveryMode + private val rnMigrationMutex = Mutex() + private val _isCheckingRNMigration = MutableStateFlow(true) + val isCheckingRNMigration = _isCheckingRNMigration.asStateFlow() + val isShowingMigrationLoading: StateFlow = migrationService.isShowingMigrationLoading val isRestoringFromRNRemoteBackup: StateFlow = migrationService.isRestoringFromRNRemoteBackup val isWiping: StateFlow = backupRepo.isWiping @@ -348,7 +353,9 @@ class WalletViewModel @Inject constructor( private fun observeNetworkState() = viewModelScope.launch(bgDispatcher) { connectivityRepo.isOnline.collect { state -> - if (state == ConnectivityState.CONNECTED && pendingWalletStart) { + if (state == ConnectivityState.CONNECTED && _isCheckingRNMigration.value) { + checkAndPerformRNMigration() + } else if (state == ConnectivityState.CONNECTED && pendingWalletStart) { pendingWalletStart = false val isChecked = migrationService.isMigrationChecked() if (!isChecked && migrationService.hasRNWalletData()) { @@ -368,28 +375,38 @@ class WalletViewModel @Inject constructor( } private fun checkAndPerformRNMigration() = viewModelScope.launch(bgDispatcher) { - if (walletRepo.checkWalletAvailable().isFailure) return@launch - val isChecked = migrationService.isMigrationChecked() - if (isChecked) { - loadCacheIfWalletExists() - return@launch - } + val startMigratedWallet = runSuspendCatching { + rnMigrationMutex.withLock { checkAndMigrateRNWallet() } + }.onFailure { + Logger.warn("RN migration admission is unavailable", it, context = TAG) + }.getOrDefault(false) + if (!startMigratedWallet) return@launch + runSuspendCatching { + if (!isNetworkConnected()) { + Logger.warn("Network offline, dismissing loader and skipping wallet start", context = TAG) + migrationService.setShowingMigrationLoading(false) + pendingWalletStart = true + return@runSuspendCatching + } + startNode(0) + }.onFailure { handleRNMigrationFailure(it) } + } - val hasNative = migrationService.hasNativeWalletData() - if (hasNative) { - migrationService.markMigrationChecked() + private suspend fun checkAndMigrateRNWallet(): Boolean { + if (!_isCheckingRNMigration.value || walletRepo.checkWalletAvailable().isFailure) return false + if (migrationService.isMigrationChecked()) { loadCacheIfWalletExists() - return@launch + _isCheckingRNMigration.update { false } + return false } - - val hasRN = migrationService.hasRNWalletData() - if (!hasRN) { + if (migrationService.hasNativeWalletData() || !migrationService.hasRNWalletData()) { migrationService.markMigrationChecked() loadCacheIfWalletExists() - return@launch + _isCheckingRNMigration.update { false } + return false } - - runSuspendCatching { + var migrationStarted = false + return runSuspendCatching { connectionRecovery.withIdentityChange( isStillNeeded = { walletRepo.checkWalletAvailable().getOrThrow() @@ -398,6 +415,7 @@ class WalletViewModel @Inject constructor( }, ) { walletRepo.checkWalletAvailable().getOrThrow() + migrationStarted = true migrationService.setShowingMigrationLoading(true) Logger.info("RN wallet data found, starting migration...", context = TAG) migrationService.migrateFromReactNative() @@ -405,29 +423,29 @@ class WalletViewModel @Inject constructor( walletRepo.setWalletExistsState() walletExists = walletRepo.walletExists() loadCacheIfWalletExists() - if (walletExists) { - // Re-check network before starting wallet (like iOS) - if (!isNetworkConnected()) { - Logger.warn("Network offline, dismissing loader and skipping wallet start", context = TAG) - migrationService.setShowingMigrationLoading(false) - pendingWalletStart = true - return@runSuspendCatching - } - startNode(0) + _isCheckingRNMigration.update { false } + if (!walletExists) migrationService.setShowingMigrationLoading(false) + walletExists + }.onFailure { + if (migrationStarted) { + handleRNMigrationFailure(it) } else { - migrationService.setShowingMigrationLoading(false) + Logger.warn("RN migration admission is unavailable", it, context = TAG) } - }.onFailure { - if (walletRepo.checkWalletAvailable().isFailure) return@onFailure - Logger.error("RN migration failed", it, context = TAG) - migrationService.markMigrationChecked() - migrationService.setShowingMigrationLoading(false) - ToastEventBus.send( - type = Toast.ToastType.ERROR, - title = "Migration Failed", - description = "Please restore your wallet manually using your recovery phrase" - ) - } + }.getOrDefault(false) + } + + private suspend fun handleRNMigrationFailure(error: Throwable) { + if (walletRepo.checkWalletAvailable().isFailure) return + Logger.error("RN migration failed", error, context = TAG) + migrationService.markMigrationChecked() + migrationService.setShowingMigrationLoading(false) + _isCheckingRNMigration.update { false } + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = "Migration Failed", + description = "Please restore your wallet manually using your recovery phrase" + ) } private fun loadCacheIfWalletExists() { @@ -440,6 +458,7 @@ class WalletViewModel @Inject constructor( walletState.collect { walletExists = it.walletExists if (it.walletResetRecovery != WalletResetRecovery.Clear) return@collect + if (_isCheckingRNMigration.value) checkAndPerformRNMigration() if (!it.walletExists) { appliedConnection = null _connectionStartupError.update { null } @@ -1006,7 +1025,10 @@ class WalletViewModel @Inject constructor( } } - fun refreshWalletResetRecovery() = walletRepo.refreshWalletResetRecovery() + fun refreshWalletResetRecovery() { + walletRepo.refreshWalletResetRecovery() + if (_isCheckingRNMigration.value) checkAndPerformRNMigration() + } fun finishPendingWalletReset(attemptId: String) = viewModelScope.launch { if (isWiping.value || !_isFinishingWalletReset.compareAndSet(false, true)) return@launch @@ -1018,6 +1040,7 @@ class WalletViewModel @Inject constructor( } suspend fun createWallet(bip39Passphrase: String?) { + if (_isCheckingRNMigration.value) return walletRepo.checkWalletAvailable().getOrElse { ToastEventBus.send(it) return @@ -1037,6 +1060,7 @@ class WalletViewModel @Inject constructor( } suspend fun restoreWallet(mnemonic: String, bip39Passphrase: String?) { + if (_isCheckingRNMigration.value) return walletRepo.checkWalletAvailable().getOrElse { ToastEventBus.send(it) return diff --git a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt index 4e91b6ed94..aa8cc4bdef 100644 --- a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt @@ -35,6 +35,7 @@ import org.mockito.kotlin.whenever import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.data.WalletConnectionRecovery +import to.bitkit.data.WalletResetRecovery import to.bitkit.data.keychain.Keychain import to.bitkit.data.keychain.hasPendingWalletRestore import to.bitkit.ext.of @@ -115,20 +116,172 @@ class WalletViewModelTest : BaseUnitTest() { whenever { lightningRepo.getFeeRateForSpeed(any(), anyOrNull()) }.thenReturn(Result.success(1uL)) connectionRecovery = connectionRecoveryFixture(settingsStore, recoveryKeychain) { currentBinding } - sut = WalletViewModel( - context = context, - bgDispatcher = testDispatcher, - walletRepo = walletRepo, - lightningRepo = lightningRepo, - settingsStore = settingsStore, - backupRepo = backupRepo, - blocktankRepo = blocktankRepo, - pubkyRepo = pubkyRepo, - migrationService = migrationService, - connectivityRepo = connectivityRepo, - boltzService = boltzService, - connectionRecovery = connectionRecovery, - ) + sut = createViewModel() + } + + private fun createViewModel() = WalletViewModel( + context = context, + bgDispatcher = testDispatcher, + walletRepo = walletRepo, + lightningRepo = lightningRepo, + settingsStore = settingsStore, + backupRepo = backupRepo, + blocktankRepo = blocktankRepo, + pubkyRepo = pubkyRepo, + migrationService = migrationService, + connectivityRepo = connectivityRepo, + boltzService = boltzService, + connectionRecovery = connectionRecovery, + ) + + @Test + fun `clear cleanup state resumes deferred rn migration`() = test { + walletState.value = WalletState(walletResetRecovery = WalletResetRecovery.Unavailable) + whenever(walletRepo.checkWalletAvailable()).thenReturn(Result.failure(AppError("temporarily unreadable"))) + whenever(migrationService.isMigrationChecked()).thenReturn(false) + whenever(migrationService.hasRNWalletData()).thenReturn(true) + createViewModel() + advanceUntilIdle() + verify(migrationService, never()).migrateFromReactNative() + + whenever(walletRepo.checkWalletAvailable()).thenReturn(Result.success(Unit)) + walletState.value = WalletState(walletResetRecovery = WalletResetRecovery.Clear) + advanceUntilIdle() + + verify(migrationService).migrateFromReactNative() + } + + @Test + fun `read retry resumes deferred rn migration without a state emission`() = test { + whenever(walletRepo.checkWalletAvailable()).thenReturn(Result.failure(AppError("temporarily unreadable"))) + whenever(migrationService.isMigrationChecked()).thenReturn(false) + whenever(migrationService.hasRNWalletData()).thenReturn(true) + val recovering = createViewModel() + advanceUntilIdle() + verify(migrationService, never()).migrateFromReactNative() + + whenever(walletRepo.checkWalletAvailable()).thenReturn(Result.success(Unit)) + recovering.refreshWalletResetRecovery() + advanceUntilIdle() + + verify(migrationService).migrateFromReactNative() + } + + @Test + fun `reconnect resumes deferred migration once and blocks replacement while held`() = test { + whenever(walletRepo.checkWalletAvailable()).thenReturn(Result.failure(AppError("temporarily unreadable"))) + whenever(migrationService.isMigrationChecked()).thenReturn(false) + whenever(migrationService.hasRNWalletData()).thenReturn(true) + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever(migrationService.migrateFromReactNative()).doSuspendableAnswer { + entered.complete(Unit) + release.await() + } + val recovering = createViewModel() + advanceUntilIdle() + assertTrue(recovering.isCheckingRNMigration.value) + whenever(walletRepo.checkWalletAvailable()).thenReturn(Result.success(Unit)) + isOnline.value = ConnectivityState.DISCONNECTED + runCurrent() + isOnline.value = ConnectivityState.CONNECTED + entered.await() + recovering.refreshWalletResetRecovery() + walletState.value = WalletState(walletResetRecovery = WalletResetRecovery.Unavailable) + walletState.value = WalletState(walletResetRecovery = WalletResetRecovery.Clear) + recovering.createWallet(null) + recovering.restoreWallet("replacement", null) + assertTrue(recovering.isCheckingRNMigration.value) + verify(walletRepo, never()).createWallet(anyOrNull()) + verify(walletRepo, never()).restoreWallet(any(), anyOrNull()) + verify(backupRepo, never()).setRestorePending(true) + release.complete(Unit) + advanceUntilIdle() + verify(migrationService).migrateFromReactNative() + assertFalse(recovering.isCheckingRNMigration.value) + recovering.refreshWalletResetRecovery() + advanceUntilIdle() + verify(migrationService).migrateFromReactNative() + } + + @Test + fun `unavailable migration metadata does not classify rn data as absent`() = test { + var unreadable = true + whenever(migrationService.isMigrationChecked()).doSuspendableAnswer { + check(!unreadable) { "metadata unreadable" } + false + } + val recovering = createViewModel() + advanceUntilIdle() + assertTrue(recovering.isCheckingRNMigration.value) + verify(migrationService, never()).markMigrationChecked() + unreadable = false + whenever(migrationService.hasRNWalletData()).thenReturn(true) + recovering.refreshWalletResetRecovery() + advanceUntilIdle() + verify(migrationService).migrateFromReactNative() + assertFalse(recovering.isCheckingRNMigration.value) + } + + @Test + fun `unavailable cleanup keeps retries from migrating or exposing onboarding`() = test { + whenever(walletRepo.checkWalletAvailable()).thenReturn(Result.failure(AppError("reset pending"))) + val recovering = createViewModel() + recovering.refreshWalletResetRecovery() + isOnline.value = ConnectivityState.DISCONNECTED + runCurrent() + isOnline.value = ConnectivityState.CONNECTED + advanceUntilIdle() + assertTrue(recovering.isCheckingRNMigration.value) + verify(migrationService, never()).migrateFromReactNative() + verify(migrationService, never()).markMigrationChecked() + } + + @Test + fun `fresh installation completes migration classification without importing`() = test { + whenever(migrationService.isMigrationChecked()).thenReturn(false) + whenever(migrationService.hasRNWalletData()).thenReturn(false) + val recovering = createViewModel() + advanceUntilIdle() + assertFalse(recovering.isCheckingRNMigration.value) + verify(migrationService).markMigrationChecked() + verify(migrationService, never()).migrateFromReactNative() + } + + @Test + fun `failed inner cleanup admission retains migration for explicit retry`() = test { + var checks = 0 + whenever(migrationService.isMigrationChecked()).doSuspendableAnswer { + checks += 1 + if (checks >= 2) { + whenever(walletRepo.checkWalletAvailable()).thenReturn(Result.failure(AppError("read failed"))) + } + false + } + whenever(migrationService.hasRNWalletData()).thenReturn(true) + val recovering = createViewModel() + advanceUntilIdle() + assertTrue(recovering.isCheckingRNMigration.value) + verify(migrationService, never()).migrateFromReactNative() + verify(migrationService, never()).markMigrationChecked() + + whenever(migrationService.isMigrationChecked()).thenReturn(false) + whenever(walletRepo.checkWalletAvailable()).thenReturn(Result.success(Unit)) + recovering.refreshWalletResetRecovery() + advanceUntilIdle() + verify(migrationService).migrateFromReactNative() + assertFalse(recovering.isCheckingRNMigration.value) + } + + @Test + fun `native wallet completes migration classification without importing rn data`() = test { + whenever(migrationService.isMigrationChecked()).thenReturn(false) + whenever(migrationService.hasNativeWalletData()).thenReturn(true) + val recovering = createViewModel() + advanceUntilIdle() + assertFalse(recovering.isCheckingRNMigration.value) + verify(migrationService).markMigrationChecked() + verify(migrationService, never()).migrateFromReactNative() } @Test diff --git a/changelog.d/next/1693.fixed.md b/changelog.d/next/1693.fixed.md index 44a4674a92..7b8213c52f 100644 --- a/changelog.d/next/1693.fixed.md +++ b/changelog.d/next/1693.fixed.md @@ -1 +1 @@ -Keep interrupted profile removal recoverable with confirmed retries or local Disconnect, preserve cleanup progress and payment details, and make wallet-reset recovery distinguish unreadable state, attempt endpoint cleanup before a fresh reset, retain authenticated read-only seed access and local forgotten-PIN navigation, and prevent duplicate actions while cleanup is running. +Keep interrupted profile removal recoverable with confirmed retries or local Disconnect, preserve cleanup progress and payment details, and make wallet-reset recovery distinguish unreadable state, attempt endpoint cleanup before a fresh reset, retain authenticated read-only seed access and local forgotten-PIN navigation, and prevent duplicate actions while cleanup is running, resume deferred React Native migration after cleanup-state recovery, and keep onboarding closed until migration admission finishes. diff --git a/journeys/security/README.md b/journeys/security/README.md index 2aa480f082..72421d36f1 100644 --- a/journeys/security/README.md +++ b/journeys/security/README.md @@ -16,3 +16,12 @@ For an explicitly authorized reset in a separate disposable fixture, an unreadab attempt private and public endpoint cleanup before erasing credentials. A known interrupted wallet wipe resumes local cleanup without automatically replaying remote operations. Capture the marker scope and redacted operation order; component tests do not establish this network journey. + +React Native migration after cleanup-state recovery needs a prepared, unfunded RN-only +installation with no native mnemonic and no completed migration marker. Hold the initial +cleanup-state read unavailable, then release it and use Retry. Recovery must precede onboarding; +automatic Clear or a reconnect must resume the same migration check without a second importer. +Keep a local migration suspended while retrying and verify no new-wallet or restore action can +run. A still-unavailable cleanup read must retain recovery. These storage and migration holds +require a controlled fixture; ViewModel and installed root-routing tests cover the admission +boundaries but do not establish a complete RN data migration or authenticated app journey. From 78f7209f98c16858987567a726bd7571d36fde8f Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 2 Nov 2026 06:47:26 +0100 Subject: [PATCH 34/61] fix: offer retry for unavailable migration status --- .../java/to/bitkit/ui/RootDestinationTest.kt | 90 +++++++++++++++---- .../main/java/to/bitkit/ui/MainActivity.kt | 9 ++ .../ui/screens/MigrationRecoveryScreen.kt | 40 +++++++++ .../to/bitkit/viewmodels/WalletViewModel.kt | 16 ++-- app/src/main/res/values-ar/strings.xml | 1 + app/src/main/res/values-b+es+419/strings.xml | 1 + app/src/main/res/values-ca/strings.xml | 1 + app/src/main/res/values-cs/strings.xml | 1 + app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-el/strings.xml | 1 + app/src/main/res/values-es-rES/strings.xml | 1 + app/src/main/res/values-es/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-it/strings.xml | 1 + app/src/main/res/values-nl/strings.xml | 1 + app/src/main/res/values-pl/strings.xml | 1 + app/src/main/res/values-pt-rBR/strings.xml | 1 + app/src/main/res/values-pt/strings.xml | 1 + app/src/main/res/values-ru/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + .../java/to/bitkit/ui/WalletViewModelTest.kt | 44 +++++++++ changelog.d/next/1693.fixed.md | 2 +- docs/screens-map.md | 1 + journeys/security/README.md | 6 ++ 24 files changed, 202 insertions(+), 22 deletions(-) create mode 100644 app/src/main/java/to/bitkit/ui/screens/MigrationRecoveryScreen.kt diff --git a/app/src/androidTest/java/to/bitkit/ui/RootDestinationTest.kt b/app/src/androidTest/java/to/bitkit/ui/RootDestinationTest.kt index eda2ede3b6..e14fee0ea0 100644 --- a/app/src/androidTest/java/to/bitkit/ui/RootDestinationTest.kt +++ b/app/src/androidTest/java/to/bitkit/ui/RootDestinationTest.kt @@ -1,14 +1,19 @@ package to.bitkit.ui import androidx.compose.material3.Text +import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick import org.junit.Rule import org.junit.Test +import kotlin.test.assertEquals import to.bitkit.data.WalletResetRecovery import to.bitkit.test.annotations.ComposeUi +import to.bitkit.ui.screens.MigrationRecoveryScreen +import to.bitkit.ui.theme.AppThemeSurface @ComposeUi class RootDestinationTest { @@ -20,30 +25,35 @@ class RootDestinationTest { isCriticalUpdateRequired: Boolean = false, isShowingMigrationLoading: Boolean = false, isCheckingRNMigration: Boolean = false, + isRNMigrationUnavailable: Boolean = false, walletExists: Boolean = true, isRecoveryMode: Boolean = false, walletResetRecovery: WalletResetRecovery = WalletResetRecovery.Clear, ) { composeTestRule.setContent { - RootDestination( - isCriticalUpdateRequired = isCriticalUpdateRequired, - isShowingMigrationLoading = isShowingMigrationLoading, - isCheckingRNMigration = isCheckingRNMigration, - walletExists = walletExists, - isRecoveryMode = isRecoveryMode, - walletResetRecovery = walletResetRecovery, - resetRecovery = { Text(text = "reset", modifier = Modifier.testTag(TAG_RESET)) }, - criticalUpdate = { Text(text = "critical", modifier = Modifier.testTag(TAG_CRITICAL)) }, - migrationLoading = { Text(text = "migration", modifier = Modifier.testTag(TAG_MIGRATION)) }, - onboarding = { Text(text = "onboarding", modifier = Modifier.testTag(TAG_ONBOARDING)) }, - wallet = { Text(text = "wallet", modifier = Modifier.testTag(TAG_WALLET)) }, - ) + AppThemeSurface { + RootDestination( + isCriticalUpdateRequired = isCriticalUpdateRequired, + isShowingMigrationLoading = isShowingMigrationLoading, + isCheckingRNMigration = isCheckingRNMigration, + isRNMigrationUnavailable = isRNMigrationUnavailable, + walletExists = walletExists, + isRecoveryMode = isRecoveryMode, + walletResetRecovery = walletResetRecovery, + resetRecovery = { Text(text = "reset", modifier = Modifier.testTag(TAG_RESET)) }, + criticalUpdate = { Text(text = "critical", modifier = Modifier.testTag(TAG_CRITICAL)) }, + migrationLoading = { Text(text = "migration", modifier = Modifier.testTag(TAG_MIGRATION)) }, + migrationRecovery = { MigrationRecoveryScreen(onRetry = {}) }, + onboarding = { Text(text = "onboarding", modifier = Modifier.testTag(TAG_ONBOARDING)) }, + wallet = { Text(text = "wallet", modifier = Modifier.testTag(TAG_WALLET)) }, + ) + } } } private fun assertOnly(tag: String) { composeTestRule.onNodeWithTag(tag).assertExists() - listOf(TAG_CRITICAL, TAG_MIGRATION, TAG_ONBOARDING, TAG_WALLET, TAG_RESET) + listOf(TAG_CRITICAL, TAG_MIGRATION, TAG_MIGRATION_ERROR, TAG_ONBOARDING, TAG_WALLET, TAG_RESET) .filterNot { it == tag } .forEach { composeTestRule.onNodeWithTag(it).assertDoesNotExist() } } @@ -62,10 +72,59 @@ class RootDestinationTest { @Test fun unreadableCleanupKeepsItsRetryAheadOfMigrationAdmission() { - setContent(isCheckingRNMigration = true, walletResetRecovery = WalletResetRecovery.Unavailable) + setContent( + isCheckingRNMigration = true, + isRNMigrationUnavailable = true, + walletResetRecovery = WalletResetRecovery.Unavailable, + ) assertOnly(TAG_RESET) } + @Test + fun unavailableMigrationOffersRetryBeforeWalletAndRecoveryMode() { + val unavailable = mutableStateOf(true) + val checking = mutableStateOf(true) + var retries = 0 + composeTestRule.setContent { + AppThemeSurface { + RootDestination( + isCriticalUpdateRequired = false, + isShowingMigrationLoading = false, + isCheckingRNMigration = checking.value, + isRNMigrationUnavailable = unavailable.value, + walletExists = true, + isRecoveryMode = true, + walletResetRecovery = WalletResetRecovery.Clear, + resetRecovery = { Text("reset", Modifier.testTag(TAG_RESET)) }, + criticalUpdate = { Text("critical", Modifier.testTag(TAG_CRITICAL)) }, + migrationLoading = { Text("migration", Modifier.testTag(TAG_MIGRATION)) }, + migrationRecovery = { + MigrationRecoveryScreen(onRetry = { + retries++ + unavailable.value = false + }) + }, + onboarding = { Text("onboarding", Modifier.testTag(TAG_ONBOARDING)) }, + wallet = { Text("wallet", Modifier.testTag(TAG_WALLET)) }, + ) + } + } + assertOnly(TAG_MIGRATION_ERROR) + composeTestRule.onNodeWithTag("MigrationReadRetry").performClick() + assertOnly(TAG_MIGRATION) + composeTestRule.runOnIdle { + assertEquals(1, retries) + checking.value = false + } + assertOnly(TAG_WALLET) + } + + @Test + fun unavailableMigrationPrecedesFreshOnboarding() { + setContent(walletExists = false, isCheckingRNMigration = true, isRNMigrationUnavailable = true) + assertOnly(TAG_MIGRATION_ERROR) + } + @Test fun pendingResetPrecedesOnboardingAndRecoveryMode() { setContent(walletExists = false, isRecoveryMode = true, walletResetRecovery = WalletResetRecovery.Pending("test")) @@ -156,6 +215,7 @@ class RootDestinationTest { private const val TAG_CRITICAL = "TestCriticalUpdate" private const val TAG_MIGRATION = "TestMigrationLoading" +private const val TAG_MIGRATION_ERROR = "MigrationRecovery" private const val TAG_ONBOARDING = "TestOnboarding" private const val TAG_WALLET = "TestWallet" diff --git a/app/src/main/java/to/bitkit/ui/MainActivity.kt b/app/src/main/java/to/bitkit/ui/MainActivity.kt index 79e87a219d..0076a102bb 100644 --- a/app/src/main/java/to/bitkit/ui/MainActivity.kt +++ b/app/src/main/java/to/bitkit/ui/MainActivity.kt @@ -65,6 +65,7 @@ import to.bitkit.ui.onboarding.TermsOfUseScreen import to.bitkit.ui.onboarding.WarningMultipleDevicesScreen import to.bitkit.ui.screens.CriticalUpdateScreen import to.bitkit.ui.screens.MigrationLoadingScreen +import to.bitkit.ui.screens.MigrationRecoveryScreen import to.bitkit.ui.screens.SplashScreen import to.bitkit.ui.screens.recovery.WalletResetRecoveryScreen import to.bitkit.ui.sheets.ForgotPinSheet @@ -138,6 +139,7 @@ class MainActivity : FragmentActivity() { val walletState by walletViewModel.walletState.collectAsStateWithLifecycle() val walletResetRecovery = walletState.walletResetRecovery val isCheckingRNMigration by walletViewModel.isCheckingRNMigration.collectAsStateWithLifecycle() + val isRNMigrationUnavailable by walletViewModel.isRNMigrationUnavailable.collectAsStateWithLifecycle() val isShowingMigrationLoading by walletViewModel.isShowingMigrationLoading.collectAsStateWithLifecycle() val restoreState by walletViewModel.restoreState.collectAsStateWithLifecycle() val isCriticalUpdateRequired by appViewModel.isCriticalUpdateRequired.collectAsStateWithLifecycle() @@ -168,6 +170,7 @@ class MainActivity : FragmentActivity() { isCriticalUpdateRequired = isCriticalUpdateRequired, isShowingMigrationLoading = isShowingMigrationLoading, isCheckingRNMigration = isCheckingRNMigration, + isRNMigrationUnavailable = isRNMigrationUnavailable, walletExists = walletExists, isRecoveryMode = isRecoveryMode, walletResetRecovery = walletResetRecovery, @@ -190,6 +193,9 @@ class MainActivity : FragmentActivity() { CriticalUpdateScreen() }, migrationLoading = { MigrationLoadingScreen(isVisible = true) }, + migrationRecovery = { + MigrationRecoveryScreen(onRetry = walletViewModel::refreshWalletResetRecovery) + }, onboarding = { CompositionLocalProvider(LocalAppViewModel provides appViewModel) { OnboardingNav( @@ -409,10 +415,12 @@ fun RootDestination( isCriticalUpdateRequired: Boolean, isShowingMigrationLoading: Boolean, isCheckingRNMigration: Boolean, + isRNMigrationUnavailable: Boolean, walletExists: Boolean, isRecoveryMode: Boolean, criticalUpdate: @Composable () -> Unit, migrationLoading: @Composable () -> Unit, + migrationRecovery: @Composable () -> Unit, onboarding: @Composable () -> Unit, wallet: @Composable () -> Unit, walletResetRecovery: WalletResetRecovery, @@ -421,6 +429,7 @@ fun RootDestination( when { isCriticalUpdateRequired -> criticalUpdate() walletResetRecovery != WalletResetRecovery.Clear -> resetRecovery() + isRNMigrationUnavailable -> migrationRecovery() isCheckingRNMigration -> migrationLoading() isShowingMigrationLoading && !isRecoveryMode -> migrationLoading() !walletExists && !isRecoveryMode -> onboarding() diff --git a/app/src/main/java/to/bitkit/ui/screens/MigrationRecoveryScreen.kt b/app/src/main/java/to/bitkit/ui/screens/MigrationRecoveryScreen.kt new file mode 100644 index 0000000000..c355f8436c --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/screens/MigrationRecoveryScreen.kt @@ -0,0 +1,40 @@ +package to.bitkit.ui.screens + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import to.bitkit.R +import to.bitkit.ui.components.BodyM +import to.bitkit.ui.components.PrimaryButton +import to.bitkit.ui.components.VerticalSpacer +import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.shared.util.screen +import to.bitkit.ui.theme.AppThemeSurface + +@Composable +fun MigrationRecoveryScreen(onRetry: () -> Unit, modifier: Modifier = Modifier) { + BackHandler {} + Column(modifier = modifier.screen().padding(horizontal = 16.dp).testTag("MigrationRecovery")) { + AppTopBar(titleText = stringResource(R.string.migration__nav_title), onBackClick = null) + VerticalSpacer(16.dp) + BodyM(text = stringResource(R.string.migration__status_error)) + VerticalSpacer(32.dp) + PrimaryButton( + text = stringResource(R.string.common__retry), + onClick = onRetry, + modifier = Modifier.testTag("MigrationReadRetry") + ) + } +} + +@Preview(showSystemUi = true) +@Composable +private fun Preview() { + AppThemeSurface { MigrationRecoveryScreen(onRetry = {}) } +} diff --git a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index f524cc3eef..156ce5f7c8 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -116,6 +116,8 @@ class WalletViewModel @Inject constructor( private val rnMigrationMutex = Mutex() private val _isCheckingRNMigration = MutableStateFlow(true) val isCheckingRNMigration = _isCheckingRNMigration.asStateFlow() + private val _isRNMigrationUnavailable = MutableStateFlow(false) + val isRNMigrationUnavailable = _isRNMigrationUnavailable.asStateFlow() val isShowingMigrationLoading: StateFlow = migrationService.isShowingMigrationLoading val isRestoringFromRNRemoteBackup: StateFlow = migrationService.isRestoringFromRNRemoteBackup @@ -375,11 +377,13 @@ class WalletViewModel @Inject constructor( } private fun checkAndPerformRNMigration() = viewModelScope.launch(bgDispatcher) { - val startMigratedWallet = runSuspendCatching { - rnMigrationMutex.withLock { checkAndMigrateRNWallet() } - }.onFailure { - Logger.warn("RN migration admission is unavailable", it, context = TAG) - }.getOrDefault(false) + val startMigratedWallet = rnMigrationMutex.withLock { + _isRNMigrationUnavailable.update { false } + runSuspendCatching { checkAndMigrateRNWallet() }.onFailure { + _isRNMigrationUnavailable.update { _isCheckingRNMigration.value } + Logger.warn("Failed to check RN migration admission", it, context = TAG) + }.getOrDefault(false) + } if (!startMigratedWallet) return@launch runSuspendCatching { if (!isNetworkConnected()) { @@ -430,7 +434,7 @@ class WalletViewModel @Inject constructor( if (migrationStarted) { handleRNMigrationFailure(it) } else { - Logger.warn("RN migration admission is unavailable", it, context = TAG) + throw it } }.getOrDefault(false) } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index d1645d5e4b..13281a56d3 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -238,6 +238,7 @@ تفعيل\nLightning\n<accent>المدفوعات</accent> يرجى الانتظار أثناء ترحيل بيانات محفظتك القديمة إلى إصدار Bitkit الجديد. عادةً ما يستغرق هذا أقل من دقيقة. ترحيل المحفظة + حالة ترحيل المحفظة غير متاحة. أعد المحاولة قبل المتابعة. جارٍ ترحيل\n<accent>المحفظة</accent> قناة الإشعارات لخدمة عقدة Lightning في المقدمة إشعار عقدة Lightning diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 048859df7a..32777012b0 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -245,6 +245,7 @@ Habilitar\nLightning\n<accent>pagos</accent> Por favor espera mientras se migran los datos de tu billetera anterior a esta nueva versión de Bitkit. Esto normalmente tarda menos de un minuto. Migración de billetera + El estado de migración de la billetera no está disponible. Reinténtalo antes de continuar. MIGRANDO\n<accent>BILLETERA</accent> Canal de notificación para el servicio en segundo plano del nodo Lightning Notificación del nodo Lightning diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 4888b4c8e6..88aceaebc1 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -242,6 +242,7 @@ Habilitar\nLightning\n<accent>pagaments</accent> Si us plau, espera mentre les dades de la teva antiga cartera es migren a aquesta nova versió de Bitkit. Normalment triga menys d\'un minut. Migració de cartera + L’estat de la migració de la cartera no està disponible. Torna-ho a provar abans de continuar. MIGRANT\n<accent>CARTERA</accent> Canal de notificació per al servei en primer pla del node Lightning Notificació del node Lightning diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index d8d37ea560..aa719e2f7c 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -245,6 +245,7 @@ Povolit\nLightning\n<accent>platby</accent> Počkejte prosím, než budou vaše stará data peněženky migrována do této nové verze Bitkit. Obvykle to trvá méně než minutu. Migrace peněženky + Stav migrace peněženky není dostupný. Před pokračováním to zkuste znovu. MIGRACE\nPENĚŽENKY Notifikační kanál pro službu Lightning uzlu na pozadí Notifikace Lightning uzlu diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 3be56d3ab3..70906e8e93 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -245,6 +245,7 @@ Lightning\n<accent>Zahlungen</accent>\naktivieren Bitte warte, während deine alten Wallet-Daten auf diese neue Bitkit-Version migriert werden. Das dauert normalerweise weniger als eine Minute. Wallet-Migration + Der Status der Wallet-Migration ist nicht verfügbar. Versuche es erneut, bevor du fortfährst. WALLET\n<accent>MIGRATION</accent> Benachrichtigungskanal für den Lightning-Node-Vordergrunddienst Lightning-Node-Benachrichtigung diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 66bc76c697..4edcde47a7 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -238,6 +238,7 @@ Ενεργοποίηση\nLightning\n<accent>πληρωμών</accent> Περίμενε όσο τα παλιά δεδομένα του πορτοφολιού μεταφέρονται σε αυτή τη νέα έκδοση του Bitkit. Αυτό συνήθως διαρκεί λιγότερο από ένα λεπτό. Μετάβαση πορτοφολιού + Η κατάσταση μεταφοράς του πορτοφολιού δεν είναι διαθέσιμη. Δοκιμάστε ξανά πριν συνεχίσετε. ΜΕΤΑΒΑΣΗ\n<accent>ΠΟΡΤΟΦΟΛΙΟΥ</accent> Κανάλι ειδοποιήσεων για υπηρεσία προσκηνίου κόμβου Lightning Ειδοποίηση κόμβου Lightning diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 9bb4adea63..c209879282 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -244,6 +244,7 @@ Habilitar\nLightning\n<accent>pagos</accent> Por favor espera mientras se migran los datos de tu antiguo monedero a esta nueva versión de Bitkit. Esto suele tardar menos de un minuto. Migración del monedero + El estado de migración del monedero no está disponible. Reinténtalo antes de continuar. MIGRANDO\n<accent>MONEDERO</accent> Canal de notificación para el servicio en primer plano del nodo Lightning Notificación del nodo Lightning diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 0cf00c5719..b64f1c97a1 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -242,6 +242,7 @@ Habilitar\nLightning\n<accent>pagos</accent> Por favor espera mientras los datos de tu antiguo monedero migran a esta nueva versión de Bitkit. Esto normalmente tarda menos de un minuto. Migración del Monedero + El estado de migración de la billetera no está disponible. Reinténtalo antes de continuar. MIGRANDO\n<accent>MONEDERO</accent> Canal de notificaciones para el servicio en segundo plano del nodo Lightning Notificación del nodo Lightning diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 3b53769707..bc9fb4acdb 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -244,6 +244,7 @@ Activer les\n<accent>paiements</accent>\nLightning Veuillez patienter pendant la migration de vos anciennes données vers cette nouvelle version de Bitkit. Cela prend généralement moins d\'une minute. Migration du portefeuille + Le statut de migration du portefeuille est indisponible. Réessayez avant de continuer. MIGRATION\n<accent>DU PORTEFEUILLE</accent> Canal de notification pour le service de nœud Lightning en arrière-plan Notification du nœud Lightning diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index f7896e44f2..2606da8ad4 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -243,6 +243,7 @@ Abilita\nLightning\n<accent>pagamenti</accent> Attendi mentre i dati del tuo vecchio wallet migrano a questa nuova versione di Bitkit. Questo di solito richiede meno di un minuto. Migrazione Wallet + Lo stato della migrazione del portafoglio non è disponibile. Riprova prima di continuare. MIGRAZIONE\n<accent>WALLET</accent> Canale di notifica per il servizio in primo piano del nodo Lightning Notifica nodo Lightning diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 4ece64952d..b9918e4308 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -242,6 +242,7 @@ Lightning\n<accent>betalingen</accent>\ninschakelen Even geduld terwijl je oude wallet-gegevens migreren naar deze nieuwe Bitkit-versie. Dit duurt meestal minder dan een minuut. Wallet-migratie + De migratiestatus van de wallet is niet beschikbaar. Probeer het opnieuw voordat je doorgaat. WALLET\n<accent>MIGREREN</accent> Notificatiekanaal voor Lightning node voorgrondservice Lightning node notificatie diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 6161341fbc..cde4b83b80 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -246,6 +246,7 @@ Włącz\nLightning\n<accent>płatności</accent> Proszę czekać, trwa migracja danych starego portfela do nowej wersji Bitkit. Zwykle trwa to mniej niż minutę. Migracja portfela + Status migracji portfela jest niedostępny. Spróbuj ponownie przed kontynuowaniem. MIGRACJA\n<accent>PORTFELA</accent> Kanał powiadomień dla usługi Lightning w tle Powiadomienie węzła Lightning diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index de8ca1b469..b16aec7ca5 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -246,6 +246,7 @@ Ativar\nLightning\n<accent>pagamentos</accent> Aguarde enquanto os dados da sua carteira antiga são migrados para esta nova versão da Bitkit. Isso geralmente leva menos de um minuto. Migração da Carteira + O status da migração da carteira está indisponível. Tente novamente antes de continuar. MIGRANDO\n<accent>CARTEIRA</accent> Canal de notificação para serviço em primeiro plano do nó Lightning Notificação do nó Lightning diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 36c59e8cad..d35b297f66 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -239,6 +239,7 @@ Ativar\nLightning\n<accent>pagamentos</accent> Por favor aguarde enquanto seus dados da carteira antiga migram para esta nova versão da Bitkit. Isso geralmente leva menos de um minuto. Migração da Carteira + O estado da migração da carteira está indisponível. Tenta novamente antes de continuar. MIGRANDO\n<accent>CARTEIRA</accent> Canal de notificação para o serviço em primeiro plano do nó Lightning Notificação do nó Lightning diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index aac23a4681..c40276c7ea 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -254,6 +254,7 @@ Включить\nLightning\n<accent>платежи</accent> Пожалуйста, подождите, пока данные вашего старого кошелька переносятся в эту новую версию Bitkit. Обычно это занимает меньше минуты. Миграция кошелька + Статус переноса кошелька недоступен. Повторите попытку, прежде чем продолжить. МИГРАЦИЯ <accent>КОШЕЛЬКА</accent> Канал уведомлений для фоновой службы Lightning ноды diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 6e6dbaf343..00184c3afa 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -405,6 +405,7 @@ Wallet Migration Please ensure you have a stable internet connection. Data may show incorrectly while trying to connect. Network Issues Detected + Wallet migration status is unavailable. Retry before continuing. MIGRATING\n<accent>WALLET</accent> Notification channel for Lightning node foreground service Lightning node notification diff --git a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt index aa8cc4bdef..a387886a61 100644 --- a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt @@ -24,6 +24,7 @@ import org.lightningdevkit.ldknode.PeerDetails import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.clearInvocations import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq import org.mockito.kotlin.inOrder @@ -214,6 +215,7 @@ class WalletViewModelTest : BaseUnitTest() { val recovering = createViewModel() advanceUntilIdle() assertTrue(recovering.isCheckingRNMigration.value) + assertTrue(recovering.isRNMigrationUnavailable.value) verify(migrationService, never()).markMigrationChecked() unreadable = false whenever(migrationService.hasRNWalletData()).thenReturn(true) @@ -221,6 +223,48 @@ class WalletViewModelTest : BaseUnitTest() { advanceUntilIdle() verify(migrationService).migrateFromReactNative() assertFalse(recovering.isCheckingRNMigration.value) + assertFalse(recovering.isRNMigrationUnavailable.value) + } + + @Test + fun `native migration status write failure offers retry without replacing the wallet`() = test { + whenever(walletRepo.walletExists()).thenReturn(true) + walletState.value = WalletState(walletExists = true) + whenever(migrationService.isMigrationChecked()).thenReturn(false) + whenever(migrationService.hasNativeWalletData()).thenReturn(true) + var unwritable = true + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever(migrationService.markMigrationChecked()).doSuspendableAnswer { + check(!unwritable) { "metadata write failed" } + entered.complete(Unit) + release.await() + } + val recovering = createViewModel() + advanceUntilIdle() + assertTrue(recovering.walletExists) + assertTrue(recovering.isCheckingRNMigration.value) + assertTrue(recovering.isRNMigrationUnavailable.value) + recovering.createWallet(null) + recovering.restoreWallet("replacement", null) + verify(walletRepo, never()).createWallet(anyOrNull()) + verify(walletRepo, never()).restoreWallet(any(), anyOrNull()) + verify(migrationService, never()).migrateFromReactNative() + + unwritable = false + clearInvocations(migrationService) + recovering.refreshWalletResetRecovery() + entered.await() + recovering.refreshWalletResetRecovery() + assertTrue(recovering.isCheckingRNMigration.value) + assertFalse(recovering.isRNMigrationUnavailable.value) + release.complete(Unit) + advanceUntilIdle() + assertTrue(recovering.walletExists) + assertFalse(recovering.isCheckingRNMigration.value) + assertFalse(recovering.isRNMigrationUnavailable.value) + verify(migrationService).markMigrationChecked() + verify(migrationService, never()).migrateFromReactNative() } @Test diff --git a/changelog.d/next/1693.fixed.md b/changelog.d/next/1693.fixed.md index 7b8213c52f..b4898cdacd 100644 --- a/changelog.d/next/1693.fixed.md +++ b/changelog.d/next/1693.fixed.md @@ -1 +1 @@ -Keep interrupted profile removal recoverable with confirmed retries or local Disconnect, preserve cleanup progress and payment details, and make wallet-reset recovery distinguish unreadable state, attempt endpoint cleanup before a fresh reset, retain authenticated read-only seed access and local forgotten-PIN navigation, and prevent duplicate actions while cleanup is running, resume deferred React Native migration after cleanup-state recovery, and keep onboarding closed until migration admission finishes. +Keep interrupted profile removal recoverable with confirmed retries or local Disconnect, preserve cleanup progress and payment details, and make wallet-reset recovery distinguish unreadable state, attempt endpoint cleanup before a fresh reset, retain authenticated read-only seed access and local forgotten-PIN navigation, and prevent duplicate actions while cleanup is running, resume deferred React Native migration after cleanup-state recovery, offer Retry when migration status is unavailable, and keep onboarding closed until migration admission finishes. diff --git a/docs/screens-map.md b/docs/screens-map.md index 318c7c7af4..dacd56ce71 100644 --- a/docs/screens-map.md +++ b/docs/screens-map.md @@ -45,6 +45,7 @@ Frame names are stable across handoff iterations; node ids are not, so the map l | - | - | | CriticalUpdateScreen.kt | Update › Forced update | | MigrationLoadingScreen.kt | Update › Forced migration | +| MigrationRecoveryScreen.kt | `todo` | | SplashScreen.kt | New user › Splash and loading screen | ## ui/screens/common diff --git a/journeys/security/README.md b/journeys/security/README.md index 72421d36f1..ddb7b1a76c 100644 --- a/journeys/security/README.md +++ b/journeys/security/README.md @@ -25,3 +25,9 @@ Keep a local migration suspended while retrying and verify no new-wallet or rest run. A still-unavailable cleanup read must retain recovery. These storage and migration holds require a controlled fixture; ViewModel and installed root-routing tests cover the admission boundaries but do not establish a complete RN data migration or authenticated app journey. + +An unreadable migration-status store must show Wallet Migration with Retry, including for an +existing native wallet. Hold either the migration-status read or its completion write; Retry +must remain reachable without changing connectivity, while onboarding and wallet replacement +stay blocked. After releasing the fault, Retry must complete classification once and open the +existing wallet. Cleanup recovery takes precedence if its state also becomes unavailable. From 8727da02549c3a885fbb48b500747b3401d3d649 Mon Sep 17 00:00:00 2001 From: benk10 Date: Tue, 3 Nov 2026 10:04:39 -0500 Subject: [PATCH 35/61] fix: initialize cold explicit backup retries --- .../java/to/bitkit/repositories/BackupRepo.kt | 26 ++- .../to/bitkit/repositories/BackupRepoTest.kt | 201 ++++++++++++++++++ changelog.d/next/1689.fixed.md | 2 +- 3 files changed, 219 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 91f431d868..93ce34c15d 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -12,6 +12,7 @@ import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.async import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.coroutineScope @@ -720,7 +721,13 @@ class BackupRepo @Inject constructor( BackupCategory.WALLET -> uploadWalletBackup() BackupCategory.USDT_RECOVERY -> uploadUsdtRecoveryBackup(usdtSnapshot) else -> runSuspendCatching { - vssBackupClient.putObject(key = category.name, data = getBackupDataBytes(category)).getOrThrow() + val data = getBackupDataBytes(category) + val setup = vssBackupClient.setup() + currentCoroutineContext().ensureActive() + setup.onFailure { + if (it is TimeoutCancellationException) throw BackupClientSetupTimeout(it) + }.getOrThrow() + vssBackupClient.putObject(key = category.name, data = data).getOrThrow() } } return upload @@ -905,22 +912,20 @@ class BackupRepo @Inject constructor( BackupCategory.METADATA -> getMetadataBackupDataBytes() BackupCategory.BLOCKTANK -> { - val blocktankState = blocktankRepo.blocktankState.first() - val payload = BlocktankBackupV1( createdAt = currentTimeMillis(), - orders = blocktankState.orders, - cjitEntries = blocktankState.cjitEntries, - info = blocktankState.info, + orders = coreService.blocktank.orders(refresh = false), + cjitEntries = coreService.blocktank.cjitEntries(refresh = false), + info = coreService.blocktank.info(refresh = false), ) json.encodeToString(payload).toByteArray() } BackupCategory.ACTIVITY -> { - val activities = activityRepo.getActivities().getOrDefault(emptyList()) - val closedChannels = activityRepo.getClosedChannels().getOrDefault(emptyList()) - val activityTags = activityRepo.getAllActivitiesTags().getOrDefault(emptyList()) + val activities = activityRepo.getActivities().getOrThrow() + val closedChannels = activityRepo.getClosedChannels().getOrThrow() + val activityTags = activityRepo.getAllActivitiesTags().getOrThrow() val payload = ActivityBackupV1( createdAt = currentTimeMillis(), @@ -1557,6 +1562,8 @@ class BackupRepo @Inject constructor( internal class WalletBackupSnapshotChanged : AppError("Private payment state changed during wallet snapshot") +private class BackupClientSetupTimeout(cause: Throwable) : AppError("Backup client setup timed out", cause) + private class PublicAddressRestoreFailed(cause: Throwable) : AppError( "Failed to retain public address exclusion during restore", cause, @@ -1590,6 +1597,7 @@ private data class RestoredCoreBackup( ) internal fun Throwable.isTemporaryBackupFailure(): Boolean = isPaykitTemporarilyUnavailable() || when (this) { + is BackupClientSetupTimeout, is VssException.ConnectionException, is VssException.NetworkException, is VssException.StoreException, diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index c81709c8fd..d60eaea0b7 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -27,6 +27,7 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.currentTime @@ -83,6 +84,7 @@ import to.bitkit.di.json import to.bitkit.models.ActivityBackupV1 import to.bitkit.models.BackupCategory import to.bitkit.models.BackupItemStatus +import to.bitkit.models.BlocktankBackupV1 import to.bitkit.models.KnownDevice import to.bitkit.models.MetadataBackupV1 import to.bitkit.models.PaykitAllowanceStateBackup @@ -98,6 +100,7 @@ import to.bitkit.models.WatchOnlyAccountRecord import to.bitkit.models.WatchOnlyAccountSetupState import to.bitkit.models.WidgetsBackupV1 import to.bitkit.services.AddressDerivationInfo +import to.bitkit.services.BlocktankService import to.bitkit.services.LightningService import to.bitkit.services.PaykitSdkOperationLock import to.bitkit.services.PaykitSdkService @@ -138,6 +141,7 @@ class BackupRepoTest : BaseUnitTest() { private val blocktankRepo = mock() private val activityRepo = mock() private val coreService = mock() + private val blocktankService = mock() private val lightningRepo = mock() private val pubkyRepo = mock() private val paykitSdkService = mock() @@ -169,6 +173,10 @@ class BackupRepoTest : BaseUnitTest() { @Before fun setUp() = test { + whenever(coreService.blocktank).thenReturn(blocktankService) + whenever { blocktankService.orders(refresh = false) }.thenReturn(emptyList()) + whenever { blocktankService.cjitEntries(refresh = false) }.thenReturn(emptyList()) + whenever { blocktankService.info(refresh = false) }.thenReturn(null) whenever(coreService.validateBitcoinAddress(any())).thenAnswer { com.synonym.bitkitcore.ValidationResult( address = it.getArgument(0), @@ -240,6 +248,199 @@ class BackupRepoTest : BaseUnitTest() { sut = createSut() } + @Test + fun `cold explicit settings backup initializes its client without observation`() = test { + val ready = CompletableDeferred() + whenever { vssBackupClient.setup(any()) }.doSuspendableAnswer { + ready.complete(Unit) + Result.success(Unit) + } + whenever { vssBackupClient.putObject(eq(BackupCategory.SETTINGS.name), any()) }.doSuspendableAnswer { + ready.await() + Result.success(VssItem(BackupCategory.SETTINGS.name, byteArrayOf(), 1)) + } + val backup = async { sut.triggerBackup(BackupCategory.SETTINGS) } + try { + runCurrent() + assertTrue(backup.isCompleted) + backup.await().getOrThrow() + verify(vssBackupClient, never()).setupWithRetry(any(), any(), any()) + verify(vssBackupClientLdk, never()).setup() + } finally { + backup.cancelAndJoin() + sut.reset() + } + } + + @Test + fun `cold explicit settings setup failure keeps its retry without observation`() = test { + val error = VssException.ConnectionException("unavailable") + val statuses = MutableStateFlow(mapOf(BackupCategory.SETTINGS to BackupItemStatus(required = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + whenever { vssBackupClient.setup(any()) } + .thenReturn(Result.failure(error)) + .thenReturn(Result.success(Unit)) + try { + assertEquals(error, sut.triggerBackup(BackupCategory.SETTINGS).exceptionOrNull()) + verify(vssBackupClient, never()).putObject(any(), any()) + assertTrue(statuses.value.getValue(BackupCategory.SETTINGS).isRequired) + advanceTimeBy(15_000) + runCurrent() + verify(vssBackupClient, times(2)).setup(any()) + verify(vssBackupClient).putObject(eq(BackupCategory.SETTINGS.name), any()) + assertFalse(statuses.value.getValue(BackupCategory.SETTINGS).isRequired) + } finally { + sut.reset() + } + } + + @Test + fun `cold explicit setup timeout keeps its retry without observation`() = test { + sut = createSut(dispatcher = StandardTestDispatcher(testScheduler)) + var setupAttempts = 0 + val statuses = MutableStateFlow(mapOf(BackupCategory.SETTINGS to BackupItemStatus(required = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + whenever { vssBackupClient.setup(any()) }.doSuspendableAnswer { + setupAttempts += 1 + if (setupAttempts == 1) runCatching { withTimeout(1) { awaitCancellation() } } else Result.success(Unit) + } + try { + val result = sut.triggerBackup(BackupCategory.SETTINGS) + assertTrue(result.exceptionOrNull()?.isTemporaryBackupFailure() == true, result.toString()) + verify(vssBackupClient, never()).putObject(any(), any()) + assertTrue(statuses.value.getValue(BackupCategory.SETTINGS).isRequired) + runCurrent() + advanceTimeBy(10_000) + runCurrent() + verify(vssBackupClient, never()).putObject(any(), any()) + advanceTimeBy(5_000) + runCurrent() + verify(vssBackupClient, times(2)).setup(any()) + verify(vssBackupClient).putObject(eq(BackupCategory.SETTINGS.name), any()) + assertFalse(statuses.value.getValue(BackupCategory.SETTINGS).isRequired) + } finally { + sut.reset() + } + } + + @Test + fun `reset drains cold explicit setup before resetting clients`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever { vssBackupClient.setup(any()) }.doSuspendableAnswer { + entered.complete(Unit) + withContext(NonCancellable) { release.await() } + Result.success(Unit) + } + val backup = async { sut.triggerBackup(BackupCategory.SETTINGS) } + try { + runCurrent() + assertTrue(entered.isCompleted) + val reset = async { sut.reset() } + runCurrent() + assertFalse(reset.isCompleted) + verify(vssBackupClient, never()).reset() + release.complete(Unit) + reset.await() + assertTrue(backup.await().isFailure) + verify(vssBackupClient, never()).putObject(any(), any()) + verify(vssBackupClient).reset() + } finally { + release.complete(Unit) + backup.cancelAndJoin() + sut.reset() + } + } + + @Test + fun `caller cancellation drains cold explicit setup without upload`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever { vssBackupClient.setup(any()) }.doSuspendableAnswer { + entered.complete(Unit) + withContext(NonCancellable) { release.await() } + Result.success(Unit) + } + val backup = async { sut.triggerBackup(BackupCategory.SETTINGS) } + try { + runCurrent() + assertTrue(entered.isCompleted) + backup.cancel() + runCurrent() + assertFalse(backup.isCompleted) + release.complete(Unit) + backup.join() + assertTrue(backup.isCancelled) + verify(vssBackupClient, never()).putObject(any(), any()) + } finally { + release.complete(Unit) + backup.cancelAndJoin() + sut.reset() + } + } + + @Test + fun `cold blocktank backup captures persisted orders before state refresh`() = test { + val order = previewBtOrder() + whenever(blocktankRepo.blocktankState).thenReturn(MutableStateFlow(BlocktankState())) + whenever { blocktankService.orders(refresh = false) }.thenReturn(listOf(order)) + + sut.triggerBackup(BackupCategory.BLOCKTANK).getOrThrow() + + val payload = argumentCaptor() + verify(vssBackupClient).putObject(eq(BackupCategory.BLOCKTANK.name), payload.capture()) + val backup = json.decodeFromString(payload.firstValue.decodeToString()) + assertEquals(listOf(order), backup.orders) + assertTrue(backup.cjitEntries.isEmpty()) + assertNull(backup.info) + verify(blocktankService).orders(refresh = false) + verify(blocktankService).cjitEntries(refresh = false) + verify(blocktankService).info(refresh = false) + } + + @Test + fun `cold blocktank backup refuses every unreadable cache before setup`() = test { + val error = AppError("Core cache is unavailable") + var unreadable = -1 + whenever { blocktankService.orders(refresh = false) }.doSuspendableAnswer { + if (unreadable == 0) throw error + emptyList() + } + whenever { blocktankService.cjitEntries(refresh = false) }.doSuspendableAnswer { + if (unreadable == 1) throw error + emptyList() + } + whenever { blocktankService.info(refresh = false) }.doSuspendableAnswer { + if (unreadable == 2) throw error + null + } + repeat(3) { unavailable -> + unreadable = unavailable + assertEquals(error, sut.triggerBackup(BackupCategory.BLOCKTANK).exceptionOrNull()) + } + verify(vssBackupClient, never()).setup(any()) + verify(vssBackupClient, never()).putObject(any(), any()) + } + + @Test + fun `cold activity backup refuses every unavailable component before setup`() = test { + val error = AppError("Core is unavailable") + repeat(3) { unavailable -> + whenever { activityRepo.getActivities() }.thenReturn( + if (unavailable == 0) Result.failure(error) else Result.success(emptyList()) + ) + whenever { activityRepo.getClosedChannels() }.thenReturn( + if (unavailable == 1) Result.failure(error) else Result.success(emptyList()) + ) + whenever { activityRepo.getAllActivitiesTags() }.thenReturn( + if (unavailable == 2) Result.failure(error) else Result.success(emptyList()) + ) + assertEquals(error, sut.triggerBackup(BackupCategory.ACTIVITY).exceptionOrNull()) + } + verify(vssBackupClient, never()).setup(any()) + verify(vssBackupClient, never()).putObject(any(), any()) + } + @Test fun `metadata backup preserves complete data when identity records cannot be read`() = test { stubMetadataBackupReads() diff --git a/changelog.d/next/1689.fixed.md b/changelog.d/next/1689.fixed.md index 8e1c25855d..1131f5353f 100644 --- a/changelog.d/next/1689.fixed.md +++ b/changelog.d/next/1689.fixed.md @@ -1 +1 @@ -Keep interrupted backups within their wallet lifecycle, retry newer pending data after failures, and let explicit recovery acknowledgements proceed without the background delay. +Keep interrupted backups within their wallet lifecycle, retry newer pending data after failures, and let explicit backups recover without waiting for the Lightning node or background delay. From 3b3b22620cf934d84a113259826bffd53ea812dd Mon Sep 17 00:00:00 2001 From: benk10 Date: Tue, 3 Nov 2026 14:40:40 -0500 Subject: [PATCH 36/61] fix: keep unreadable recovery retry available with PIN access --- .../ui/screens/recovery/WalletResetRecoveryTest.kt | 9 ++++++++- .../ui/screens/recovery/WalletResetRecoveryScreen.kt | 8 ++++++-- changelog.d/next/1693.fixed.md | 2 +- journeys/security/wallet-reset-recovery-pin.xml | 1 + 4 files changed, 16 insertions(+), 4 deletions(-) diff --git a/app/src/androidTest/java/to/bitkit/ui/screens/recovery/WalletResetRecoveryTest.kt b/app/src/androidTest/java/to/bitkit/ui/screens/recovery/WalletResetRecoveryTest.kt index 480a42b945..12a1189647 100644 --- a/app/src/androidTest/java/to/bitkit/ui/screens/recovery/WalletResetRecoveryTest.kt +++ b/app/src/androidTest/java/to/bitkit/ui/screens/recovery/WalletResetRecoveryTest.kt @@ -88,15 +88,22 @@ class WalletResetRecoveryTest { @Test fun unknownMarkerOffersPhraseWithoutAdmittingReset() { var shown = 0 + var reads = 0 val finished = mutableListOf() rule.setContent { AppThemeSurface { WalletResetRecoveryContent( - WalletResetRecovery.Unreadable("unknown"), false, {}, finished::add, + WalletResetRecovery.Unreadable("unknown"), false, { reads++ }, finished::add, onShowPhrase = { shown++ }, canShowPhrase = true, ) } } + rule.onNodeWithTag("WalletResetReadRetry").performClick() + rule.runOnIdle { + assertEquals(1, reads) + assertEquals(0, shown) + assertEquals(emptyList(), finished) + } rule.onNodeWithTag("WalletResetShowPhrase").performClick() rule.runOnIdle { assertEquals(1, shown) diff --git a/app/src/main/java/to/bitkit/ui/screens/recovery/WalletResetRecoveryScreen.kt b/app/src/main/java/to/bitkit/ui/screens/recovery/WalletResetRecoveryScreen.kt index f2c64a04f7..241fd37264 100644 --- a/app/src/main/java/to/bitkit/ui/screens/recovery/WalletResetRecoveryScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/recovery/WalletResetRecoveryScreen.kt @@ -241,9 +241,13 @@ internal fun WalletResetRecoveryContent( modifier = Modifier.testTag("WalletResetFinish") ) } - if (!busy && attemptId != null && !canShowPhrase) { + if (!busy && attemptId != null && (!canShowPhrase || recovery is WalletResetRecovery.Unreadable)) { VerticalSpacer(16.dp) - SecondaryButton(text = stringResource(R.string.common__retry), onClick = onRetry) + SecondaryButton( + text = stringResource(R.string.common__retry), + onClick = onRetry, + testTag = "WalletResetReadRetry", + ) } if (recovery != WalletResetRecovery.Loading && recovery != WalletResetRecovery.Clear) { VerticalSpacer(16.dp) diff --git a/changelog.d/next/1693.fixed.md b/changelog.d/next/1693.fixed.md index b4898cdacd..cadaa459b2 100644 --- a/changelog.d/next/1693.fixed.md +++ b/changelog.d/next/1693.fixed.md @@ -1 +1 @@ -Keep interrupted profile removal recoverable with confirmed retries or local Disconnect, preserve cleanup progress and payment details, and make wallet-reset recovery distinguish unreadable state, attempt endpoint cleanup before a fresh reset, retain authenticated read-only seed access and local forgotten-PIN navigation, and prevent duplicate actions while cleanup is running, resume deferred React Native migration after cleanup-state recovery, offer Retry when migration status is unavailable, and keep onboarding closed until migration admission finishes. +Keep interrupted profile removal recoverable with confirmed retries or local Disconnect, preserve cleanup progress and payment details, and make wallet-reset recovery distinguish unreadable state, attempt endpoint cleanup before a fresh reset, retain authenticated read-only seed access and local forgotten-PIN navigation, keep Retry available for unreadable reset state even when phrase access is available, and prevent duplicate actions while cleanup is running, resume deferred React Native migration after cleanup-state recovery, offer Retry when migration status is unavailable, and keep onboarding closed until migration admission finishes. diff --git a/journeys/security/wallet-reset-recovery-pin.xml b/journeys/security/wallet-reset-recovery-pin.xml index 795a64f22d..50e00f4ec6 100644 --- a/journeys/security/wallet-reset-recovery-pin.xml +++ b/journeys/security/wallet-reset-recovery-pin.xml @@ -7,6 +7,7 @@ Open the app and verify the unreadable recovery overview, with no ordinary wallet controls + Verify Retry remains available beside Show Seed Phrase, tap Retry while the marker is still unreadable, and verify the overview remains without opening the PIN prompt or starting a reset Tap Show Seed Phrase and verify the PIN prompt appears without displaying any seed Enter one incorrect PIN and verify the prompt remains with an attempts-remaining link Tap the attempts-remaining link and verify the recovery overview appears without a Forgot PIN sheet or reset confirmation From e7fb0ac37beae6c3f8e9a58f0f5691ece312f03c Mon Sep 17 00:00:00 2001 From: benk10 Date: Tue, 3 Nov 2026 17:12:50 -0500 Subject: [PATCH 37/61] fix: retry backup authentication transport failures --- .../java/to/bitkit/repositories/BackupRepo.kt | 10 ++- .../to/bitkit/repositories/BackupRepoTest.kt | 80 +++++++++++++++++++ 2 files changed, 87 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 93ce34c15d..3b8302bf9a 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1603,13 +1603,17 @@ internal fun Throwable.isTemporaryBackupFailure(): Boolean = isPaykitTemporarily is VssException.StoreException, is VssException.PutException, -> true - is VssException.UnknownException -> isVssRequestSendFailure(errorDetails) + is VssException.UnknownException -> isVssRequestSendFailure(errorDetails, "/putObjects") + is VssException.AuthException -> isVssRequestSendFailure( + errorDetails.removePrefix("error performing external request: "), + ) else -> false } -private fun isVssRequestSendFailure(details: String): Boolean { +private fun isVssRequestSendFailure(details: String, pathSuffix: String? = null): Boolean { val prefix = "error sending request for url (" if (!details.startsWith(prefix) || !details.endsWith(")")) return false val url = runCatching { URI(details.removePrefix(prefix).dropLast(1)) }.getOrNull() ?: return false - return url.scheme in setOf("http", "https") && !url.host.isNullOrEmpty() && url.path.endsWith("/putObjects") + return url.scheme in setOf("http", "https") && !url.host.isNullOrEmpty() && + (pathSuffix == null || url.path.endsWith(pathSuffix)) } diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index d60eaea0b7..37506d58df 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -2173,6 +2173,86 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `released VSS auth transport failure is temporary without retrying authorization failures`() { + for (prefix in listOf("", "error performing external request: ")) { + for (url in listOf("http://127.0.0.1:1/lnurl_auth/auth", "https://auth.example.com/signed?k1=fixture")) { + assertTrue( + VssException.AuthException( + "${prefix}error sending request for url ($url)" + ).isTemporaryBackupFailure() + ) + } + } + listOf( + "authorization was refused: LNURL Auth failed", + "invalid data: invalid JWT", + "HTTP status client error (401 Unauthorized)", + "error performing external request: error decoding response body", + "prefix error sending request for url (https://auth.example.com/auth)", + "error performing external request: prefix error sending request for url (https://auth.example.com/auth)", + "error sending request for url (file://auth.example.com/auth)", + "error sending request for url (https:///auth)", + "error sending request for url (not a URL)", + "error sending request for url (https://auth.example.com/auth) suffix", + ).forEach { assertFalse(VssException.AuthException(it).isTemporaryBackupFailure(), it) } + assertFalse( + VssException.UnknownException( + "error sending request for url (https://auth.example.com/auth)" + ).isTemporaryBackupFailure() + ) + } + + @Test + fun `cold explicit auth transport failure retries without observation or another request`() = test { + val category = BackupCategory.SETTINGS + val error = VssException.AuthException( + "error performing external request: error sending request for url (http://127.0.0.1:1/lnurl_auth/auth)", + ) + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + whenever(vssBackupClient.putObject(eq(category.name), any())) + .thenReturn(Result.failure(error)) + .thenReturn(Result.success(VssItem(category.name, byteArrayOf(), 1))) + try { + assertEquals(error, sut.triggerBackup(category).exceptionOrNull()) + assertTrue(statuses.value.getValue(category).isRequired) + assertFalse(statuses.value.getValue(category).running) + advanceTimeBy(10_000) + runCurrent() + verify(vssBackupClient, times(1)).putObject(eq(category.name), any()) + advanceTimeBy(5_000) + runCurrent() + verify(vssBackupClient, times(2)).setup(any()) + verify(vssBackupClient, times(2)).putObject(eq(category.name), any()) + assertFalse(statuses.value.getValue(category).isRequired) + advanceTimeBy(600_000) + runCurrent() + verify(vssBackupClient, times(2)).putObject(eq(category.name), any()) + } finally { + sut.reset() + } + } + + @Test + fun `cold explicit authorization denial stays pending without automatic retry`() = test { + val category = BackupCategory.SETTINGS + val error = VssException.AuthException("authorization was refused: LNURL Auth failed") + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + whenever(vssBackupClient.putObject(eq(category.name), any())).thenReturn(Result.failure(error)) + try { + assertEquals(error, sut.triggerBackup(category).exceptionOrNull()) + advanceTimeBy(600_000) + runCurrent() + verify(vssBackupClient, times(1)).putObject(eq(category.name), any()) + assertTrue(statuses.value.getValue(category).isRequired) + assertFalse(statuses.value.getValue(category).running) + } finally { + sut.reset() + } + } + @Test fun `released VSS connection failure is temporary without broad unknown retry`() { assertTrue( From 4056d2c0036e5a4e51698e26b3d1615825dd77f5 Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 05:47:55 -0500 Subject: [PATCH 38/61] fix: keep VSS operations with their original wallet --- .../bitkit/data/WalletConnectionRecovery.kt | 4 +- .../to/bitkit/data/backup/VssBackupClient.kt | 139 +++-- .../bitkit/data/backup/VssBackupClientLdk.kt | 75 +-- .../data/backup/VssClientCoordinator.kt | 158 ++++++ .../java/to/bitkit/repositories/BackupRepo.kt | 214 ++++---- .../to/bitkit/repositories/LightningRepo.kt | 478 +++++++++--------- .../to/bitkit/viewmodels/BackupsViewModel.kt | 9 +- .../data/WalletConnectionRecoveryTest.kt | 47 +- .../data/backup/VssBackupClientLdkTest.kt | 38 +- .../bitkit/data/backup/VssBackupClientTest.kt | 53 +- .../data/backup/VssClientCoordinatorTest.kt | 188 +++++++ .../to/bitkit/repositories/BackupRepoTest.kt | 65 ++- .../bitkit/repositories/LightningRepoTest.kt | 64 ++- .../bitkit/test/ConnectionRecoveryFixture.kt | 4 +- changelog.d/next/1686.fixed.md | 2 +- 15 files changed, 1069 insertions(+), 469 deletions(-) create mode 100644 app/src/main/java/to/bitkit/data/backup/VssClientCoordinator.kt create mode 100644 app/src/test/java/to/bitkit/data/backup/VssClientCoordinatorTest.kt diff --git a/app/src/main/java/to/bitkit/data/WalletConnectionRecovery.kt b/app/src/main/java/to/bitkit/data/WalletConnectionRecovery.kt index e1c70bbffb..fdecbf8854 100644 --- a/app/src/main/java/to/bitkit/data/WalletConnectionRecovery.kt +++ b/app/src/main/java/to/bitkit/data/WalletConnectionRecovery.kt @@ -12,6 +12,7 @@ import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json +import to.bitkit.data.backup.VssClientCoordinator import to.bitkit.data.backup.VssStoreIdProvider import to.bitkit.data.keychain.Keychain import to.bitkit.data.keychain.hasPendingWalletRestore @@ -30,6 +31,7 @@ class WalletConnectionRecovery @Inject constructor( private val db: AppDb, private val storeIdProvider: VssStoreIdProvider, private val settingsStore: SettingsStore, + private val vssClients: VssClientCoordinator, ) { companion object { internal const val KEY = "WALLET_CONNECTION_RECOVERY" @@ -130,7 +132,7 @@ class WalletConnectionRecovery @Inject constructor( currentCoroutineContext().ensureActive() beginWipe() currentCoroutineContext().ensureActive() - block() + vssClients.withSuspendedClients { block() } } finally { storeIdProvider.clearCache() endWipe() diff --git a/app/src/main/java/to/bitkit/data/backup/VssBackupClient.kt b/app/src/main/java/to/bitkit/data/backup/VssBackupClient.kt index eef9af0b15..728b112e41 100644 --- a/app/src/main/java/to/bitkit/data/backup/VssBackupClient.kt +++ b/app/src/main/java/to/bitkit/data/backup/VssBackupClient.kt @@ -3,24 +3,27 @@ package to.bitkit.data.backup import com.synonym.vssclient.KeyVersion import com.synonym.vssclient.VssItem import com.synonym.vssclient.vssDelete +import com.synonym.vssclient.vssDeriveStoreId import com.synonym.vssclient.vssGet import com.synonym.vssclient.vssListKeys import com.synonym.vssclient.vssNewClientWithLnurlAuth import com.synonym.vssclient.vssStore -import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout import to.bitkit.data.keychain.Keychain import to.bitkit.di.IoDispatcher import to.bitkit.env.Env +import to.bitkit.ext.runSuspendCatching import to.bitkit.utils.Logger import to.bitkit.utils.ServiceError import javax.inject.Inject import javax.inject.Singleton +import kotlin.coroutines.cancellation.CancellationException import kotlin.time.Duration.Companion.seconds class MnemonicNotAvailableException : Exception("Mnemonic not available") @@ -28,19 +31,12 @@ class MnemonicNotAvailableException : Exception("Mnemonic not available") @Singleton class VssBackupClient @Inject constructor( @IoDispatcher private val ioDispatcher: CoroutineDispatcher, - private val vssStoreIdProvider: VssStoreIdProvider, + private val coordinator: VssClientCoordinator, private val keychain: Keychain, ) { - @Volatile - private var isSetup = CompletableDeferred() - private val setupMutex = Mutex() - suspend fun setup(walletIndex: Int = 0): Result = withContext(ioDispatcher) { - setupMutex.withLock { - val gate = isSetup - runCatching { - if (gate.isCompleted && !gate.isCancelled) return@runCatching - + runCatching { + coordinator.setup(VssClientCoordinator.Domain.APP) { val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) ?: throw MnemonicNotAvailableException() @@ -48,13 +44,13 @@ class VssBackupClient @Inject constructor( Logger.debug("VSS client setting up…", context = TAG) val vssUrl = Env.vssServerUrl val lnurlAuthServerUrl = Env.lnurlAuthServerUrl - val vssStoreId = vssStoreIdProvider.getVssStoreId(walletIndex) Logger.verbose("Building VSS client with vssUrl: '$vssUrl'", context = TAG) Logger.verbose("Building VSS client with lnurlAuthServerUrl: '$lnurlAuthServerUrl'", context = TAG) if (lnurlAuthServerUrl.isBlank()) { throw ServiceError.VssAuthRequired() } val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) + val vssStoreId = vssDeriveStoreId(Env.vssStoreIdPrefix, mnemonic, passphrase) vssNewClientWithLnurlAuth( baseUrl = vssUrl, @@ -63,14 +59,13 @@ class VssBackupClient @Inject constructor( passphrase = passphrase, lnurlAuthServerUrl = lnurlAuthServerUrl, ) - gate.complete(Unit) - Logger.info("VSS client setup with server: '$vssUrl'", context = TAG) + Logger.info("VSS client setup for wallet[$walletIndex] with server: '$vssUrl'", context = TAG) } - }.onFailure { - gate.completeExceptionally(it) - if (isSetup === gate) isSetup = CompletableDeferred() - Logger.error("VSS client setup error", it, context = TAG) } + }.onFailure { + currentCoroutineContext().ensureActive() + if (it is CancellationException && it !is TimeoutCancellationException) throw it + Logger.error("VSS client setup error", it, context = TAG) } } @@ -85,49 +80,43 @@ class VssBackupClient @Inject constructor( baseDelayMs: Long = 1000L, logger: SetupRetryLogger.() -> Unit, ): Result = withContext(ioDispatcher) { - val log = SetupRetryLogger().apply(logger) - var attempt = 0 - while (attempt < maxAttempts) { - val result = setup() - if (result.isSuccess) { - log.onSuccess(attempt + 1) - return@withContext Result.success(Unit) - } - val exception = result.exceptionOrNull() - if (exception != null && exception !is MnemonicNotAvailableException) { - return@withContext result - } - attempt++ - if (attempt < maxAttempts) { - val delayMs = baseDelayMs * attempt - log.onRetry(attempt, maxAttempts, delayMs) - delay(delayMs) + coordinator.withWallet { + val log = SetupRetryLogger().apply(logger) + var attempt = 0 + while (attempt < maxAttempts) { + val result = setup() + if (result.isSuccess) { + log.onSuccess(attempt + 1) + return@withWallet Result.success(Unit) + } + val exception = result.exceptionOrNull() + if (exception != null && exception !is MnemonicNotAvailableException) { + return@withWallet result + } + attempt++ + if (attempt < maxAttempts) { + val delayMs = baseDelayMs * attempt + log.onRetry(attempt, maxAttempts, delayMs) + delay(delayMs) + } } + log.onExhausted(maxAttempts) + Result.failure(MnemonicNotAvailableException()) } - log.onExhausted(maxAttempts) - Result.failure(MnemonicNotAvailableException()) - } - - fun reset() { - synchronized(this) { - isSetup.cancel() - isSetup = CompletableDeferred() - } - vssStoreIdProvider.clearCache() - Logger.debug("VSS client reset", context = TAG) } suspend fun putObject( key: String, data: ByteArray, ): Result = withContext(ioDispatcher) { - isSetup.await() Logger.verbose("VSS 'putObject' call for '$key'", context = TAG) - runCatching { - vssStore( - key = key, - value = data, - ) + runSuspendCatching { + coordinator.withClient(VssClientCoordinator.Domain.APP) { + vssStore( + key = key, + value = data, + ) + } }.onSuccess { Logger.verbose("VSS 'putObject' success for '$key' at version: '${it.version}'", context = TAG) }.onFailure { @@ -136,12 +125,13 @@ class VssBackupClient @Inject constructor( } suspend fun getObject(key: String): Result = withContext(ioDispatcher) { - isSetup.await() Logger.verbose("VSS 'getObject' call for '$key'", context = TAG) - runCatching { - vssGet( - key = key, - ) + runSuspendCatching { + coordinator.withClient(VssClientCoordinator.Domain.APP) { + vssGet( + key = key, + ) + } }.onSuccess { if (it == null) { Logger.verbose("VSS 'getObject' success null for '$key'", context = TAG) @@ -154,10 +144,11 @@ class VssBackupClient @Inject constructor( } suspend fun listKeys(prefix: String? = null): Result> = withContext(ioDispatcher) { - isSetup.await() Logger.verbose("VSS 'listKeys' call with prefix: '$prefix'", context = TAG) - runCatching { - vssListKeys(prefix = prefix) + runSuspendCatching { + coordinator.withClient(VssClientCoordinator.Domain.APP) { + vssListKeys(prefix = prefix) + } }.onSuccess { Logger.verbose("VSS 'listKeys' success - found ${it.size} key(s)", context = TAG) }.onFailure { @@ -166,10 +157,11 @@ class VssBackupClient @Inject constructor( } suspend fun deleteObject(key: String): Result = withContext(ioDispatcher) { - isSetup.await() Logger.verbose("VSS 'deleteObject' call for '$key'", context = TAG) - runCatching { - vssDelete(key = key) + runSuspendCatching { + coordinator.withClient(VssClientCoordinator.Domain.APP) { + vssDelete(key = key) + } }.onSuccess { wasDeleted -> if (wasDeleted) { Logger.verbose("VSS 'deleteObject' success for '$key' - key was deleted", context = TAG) @@ -182,16 +174,17 @@ class VssBackupClient @Inject constructor( } suspend fun deleteAllKeys(): Result = withContext(ioDispatcher) { - isSetup.await() Logger.verbose("VSS 'deleteAllKeys' call", context = TAG) - runCatching { - val keys = vssListKeys(prefix = null) - var deletedCount = 0 - for (keyVersion in keys) { - val wasDeleted = vssDelete(key = keyVersion.key) - if (wasDeleted) deletedCount++ + runSuspendCatching { + coordinator.withClient(VssClientCoordinator.Domain.APP) { + val keys = vssListKeys(prefix = null) + var deletedCount = 0 + for (keyVersion in keys) { + val wasDeleted = vssDelete(key = keyVersion.key) + if (wasDeleted) deletedCount++ + } + deletedCount } - deletedCount }.onSuccess { Logger.verbose("VSS 'deleteAllKeys' success - deleted $it key(s)", context = TAG) }.onFailure { diff --git a/app/src/main/java/to/bitkit/data/backup/VssBackupClientLdk.kt b/app/src/main/java/to/bitkit/data/backup/VssBackupClientLdk.kt index 7842dbf194..bd5fe8766e 100644 --- a/app/src/main/java/to/bitkit/data/backup/VssBackupClientLdk.kt +++ b/app/src/main/java/to/bitkit/data/backup/VssBackupClientLdk.kt @@ -3,29 +3,32 @@ package to.bitkit.data.backup import com.synonym.vssclient.KeyVersion import com.synonym.vssclient.LdkNamespace import com.synonym.vssclient.VssItem +import com.synonym.vssclient.vssDeriveStoreId import com.synonym.vssclient.vssLdkDelete import com.synonym.vssclient.vssLdkGet import com.synonym.vssclient.vssLdkListKeys import com.synonym.vssclient.vssNewLdkClientWithLnurlAuth -import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout import to.bitkit.data.keychain.Keychain import to.bitkit.di.IoDispatcher import to.bitkit.env.Env +import to.bitkit.ext.runSuspendCatching import to.bitkit.utils.Logger import to.bitkit.utils.ServiceError import javax.inject.Inject import javax.inject.Singleton +import kotlin.coroutines.cancellation.CancellationException import kotlin.time.Duration.Companion.seconds @Singleton class VssBackupClientLdk @Inject constructor( @IoDispatcher private val ioDispatcher: CoroutineDispatcher, - private val vssStoreIdProvider: VssStoreIdProvider, + private val coordinator: VssClientCoordinator, private val keychain: Keychain, ) { companion object { @@ -38,16 +41,9 @@ class VssBackupClientLdk @Inject constructor( ) } - @Volatile - private var isSetup = CompletableDeferred() - private val setupMutex = Mutex() - suspend fun setup(walletIndex: Int = 0): Result = withContext(ioDispatcher) { - setupMutex.withLock { - val gate = isSetup - runCatching { - if (gate.isCompleted && !gate.isCancelled) return@runCatching - + runCatching { + coordinator.setup(VssClientCoordinator.Domain.LDK) { val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) ?: throw MnemonicNotAvailableException() @@ -58,38 +54,30 @@ class VssBackupClientLdk @Inject constructor( val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) vssNewLdkClientWithLnurlAuth( baseUrl = Env.vssServerUrl, - storeId = vssStoreIdProvider.getVssStoreId(walletIndex), + storeId = vssDeriveStoreId(Env.vssStoreIdPrefix, mnemonic, passphrase), mnemonic = mnemonic, passphrase = passphrase, lnurlAuthServerUrl = Env.lnurlAuthServerUrl, ) - gate.complete(Unit) - Logger.info("VSS LDK client setup", context = TAG) + Logger.info("VSS LDK client setup for wallet[$walletIndex]", context = TAG) } - }.onFailure { - gate.completeExceptionally(it) - if (isSetup === gate) isSetup = CompletableDeferred() - Logger.error("VSS LDK client setup error", it, context = TAG) } + }.onFailure { + currentCoroutineContext().ensureActive() + if (it is CancellationException && it !is TimeoutCancellationException) throw it + Logger.error("VSS LDK client setup error", it, context = TAG) } } - fun reset() { - synchronized(this) { - isSetup.cancel() - isSetup = CompletableDeferred() - } - Logger.debug("VSS LDK client reset", context = TAG) - } - suspend fun getObject( key: String, namespace: LdkNamespace = LdkNamespace.Default, ): Result = withContext(ioDispatcher) { - isSetup.await() Logger.verbose("VSS LDK 'getObject' call for '$key'", context = TAG) - runCatching { - vssLdkGet(key = key, namespace = namespace) + runSuspendCatching { + coordinator.withClient(VssClientCoordinator.Domain.LDK) { + vssLdkGet(key = key, namespace = namespace) + } }.onSuccess { if (it == null) { Logger.verbose("VSS LDK 'getObject' success null for '$key'", context = TAG) @@ -105,10 +93,11 @@ class VssBackupClientLdk @Inject constructor( key: String, namespace: LdkNamespace = LdkNamespace.Default, ): Result = withContext(ioDispatcher) { - isSetup.await() Logger.verbose("VSS LDK 'deleteObject' call for '$key'", context = TAG) - runCatching { - vssLdkDelete(key = key, namespace = namespace) + runSuspendCatching { + coordinator.withClient(VssClientCoordinator.Domain.LDK) { + vssLdkDelete(key = key, namespace = namespace) + } }.onSuccess { wasDeleted -> if (wasDeleted) { Logger.verbose("VSS LDK 'deleteObject' success for '$key' - key was deleted", context = TAG) @@ -120,11 +109,23 @@ class VssBackupClientLdk @Inject constructor( } } + suspend fun deleteObjects(keys: List, walletIndex: Int = 0): Result = withContext(ioDispatcher) { + runSuspendCatching { + coordinator.withWallet { + setup(walletIndex).getOrThrow() + coordinator.withClient(VssClientCoordinator.Domain.LDK) { + keys.forEach { vssLdkDelete(key = it, namespace = LdkNamespace.Default) } + } + } + } + } + suspend fun listAllKeysTagged(): Result>> = withContext(ioDispatcher) { - isSetup.await() Logger.verbose("VSS LDK 'listAllKeysTagged' call", context = TAG) - runCatching { - NAMESPACES.flatMap { ns -> vssLdkListKeys(namespace = ns).map { ns to it } } + runSuspendCatching { + coordinator.withClient(VssClientCoordinator.Domain.LDK) { + NAMESPACES.flatMap { ns -> vssLdkListKeys(namespace = ns).map { ns to it } } + } }.onSuccess { Logger.verbose("VSS LDK 'listAllKeysTagged' success - found ${it.size} key(s)", context = TAG) }.onFailure { diff --git a/app/src/main/java/to/bitkit/data/backup/VssClientCoordinator.kt b/app/src/main/java/to/bitkit/data/backup/VssClientCoordinator.kt new file mode 100644 index 0000000000..e7768e136c --- /dev/null +++ b/app/src/main/java/to/bitkit/data/backup/VssClientCoordinator.kt @@ -0,0 +1,158 @@ +package to.bitkit.data.backup + +import com.synonym.vssclient.vssShutdownClient +import com.synonym.vssclient.vssShutdownLdkClient +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.joinAll +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.coroutines.AbstractCoroutineContextElement +import kotlin.coroutines.CoroutineContext +import kotlin.coroutines.cancellation.CancellationException + +/** Owns the two standalone native slots; the running Lightning node has a separate lifetime. */ +@Singleton +class VssClientCoordinator @Inject constructor() { + enum class Domain { APP, LDK } + + class Owner internal constructor(internal val generation: Long) + + private class Admission(val coordinator: VssClientCoordinator, val owner: Owner) : + AbstractCoroutineContextElement(Key) { + companion object Key : CoroutineContext.Key + } + + private class Client { + val setupMutex = Mutex() + var ready = CompletableDeferred() + var attempted = false + } + + private val lock = Any() + private val transitionMutex = Mutex() + private var generation = 0L + private var suspended = false + private val jobs = mutableSetOf() + private val clients = Domain.entries.associateWith { Client() } + private val _owners = MutableStateFlow(Owner(generation)) + val owners = _owners.asStateFlow() + + fun captureOwner(): Owner = synchronized(lock) { + if (suspended) throw CancellationException("VSS clients are suspended") + Owner(generation) + } + + private fun checkOwner(owner: Owner) = synchronized(lock) { + if (suspended || owner.generation != generation) { + throw CancellationException("VSS wallet owner changed") + } + } + + /** Retain admission across payload capture, retries, compound requests and their local tails. */ + suspend fun withWallet(owner: Owner? = null, block: suspend () -> T): T = coroutineScope { + val inherited = currentCoroutineContext()[Admission]?.takeIf { it.coordinator === this@VssClientCoordinator } + val original = owner ?: inherited?.owner ?: captureOwner() + val job = checkNotNull(currentCoroutineContext()[Job]) + synchronized(lock) { + checkOwner(original) + jobs.add(job) + } + try { + withContext(Admission(this@VssClientCoordinator, original)) { + val result = runCatching { block() } + currentCoroutineContext().ensureActive() + checkOwner(original) + result.getOrThrow() + } + } finally { + synchronized(lock) { jobs.remove(job) } + } + } + + suspend fun setup(domain: Domain, block: suspend () -> Unit) = withWallet { + val client = clients.getValue(domain) + client.setupMutex.withLock { + currentCoroutineContext().ensureActive() + val gate = synchronized(lock) { client.ready } + if (gate.isCompleted && !gate.isCancelled) return@withLock + try { + synchronized(lock) { client.attempted = true } + block() + currentCoroutineContext().ensureActive() + gate.complete(Unit) + } catch (error: Throwable) { + gate.completeExceptionally(error) + synchronized(lock) { + if (client.ready === gate) client.ready = CompletableDeferred() + } + throw error + } + } + } + + suspend fun withClient(domain: Domain, block: suspend () -> T): T = withWallet { + val gate = synchronized(lock) { clients.getValue(domain).ready } + gate.await() + currentCoroutineContext().ensureActive() + block() + } + + /** Close admission before credentials change, including cleanup when the caller is cancelled. */ + suspend fun withSuspendedClients( + shutdown: (Domain) -> Unit = { + when (it) { + Domain.APP -> vssShutdownClient() + Domain.LDK -> vssShutdownLdkClient() + } + }, + block: suspend () -> T, + ): T { + check(currentCoroutineContext()[Admission]?.coordinator !== this) { + "Cannot replace a wallet inside an admitted VSS operation" + } + val original = captureOwner() + return transitionMutex.withLock { + val pending = synchronized(lock) { + checkOwner(original) + suspended = true + _owners.update { null } + generation += 1 + clients.values.forEach { it.ready.cancel() } + jobs.toList() + } + var shutdownComplete = false + try { + withContext(NonCancellable) { + pending.forEach { it.cancel(CancellationException("VSS wallet retired")) } + pending.joinAll() + clients.forEach { (domain, client) -> if (client.attempted) shutdown(domain) } + shutdownComplete = true + } + currentCoroutineContext().ensureActive() + block() + } finally { + synchronized(lock) { + if (shutdownComplete) { + clients.values.forEach { + it.ready = CompletableDeferred() + it.attempted = false + } + suspended = false + _owners.update { Owner(generation) } + } + } + } + } + } +} diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index f09a091bf1..ee050e3dca 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -5,6 +5,8 @@ import com.synonym.bitkitcore.UsdtException import com.synonym.vssclient.VssException import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable @@ -16,6 +18,7 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.drop @@ -47,6 +50,7 @@ import to.bitkit.data.WidgetsStore import to.bitkit.data.backup.UsdtRecoveryBackupStore import to.bitkit.data.backup.VssBackupClient import to.bitkit.data.backup.VssBackupClientLdk +import to.bitkit.data.backup.VssClientCoordinator import to.bitkit.data.backup.VssStoreIdProvider import to.bitkit.data.entities.TransferEntity import to.bitkit.data.hwWalletNames @@ -114,6 +118,7 @@ class BackupRepo @Inject constructor( @IoDispatcher private val ioDispatcher: CoroutineDispatcher, private val cacheStore: CacheStore, private val vssBackupClient: VssBackupClient, + private val vssClients: VssClientCoordinator, private val vssBackupClientLdk: VssBackupClientLdk, private val settingsStore: SettingsStore, private val widgetsStore: WidgetsStore, @@ -149,16 +154,21 @@ class BackupRepo @Inject constructor( private val usdtRecoveryBackup = UsdtRecoveryBackupStore(vssBackupClient) private val scope = appScope(ioDispatcher, TAG) - private val backupJobs = mutableMapOf() + private val backupJobs = ConcurrentHashMap.newKeySet() + private val backupJobLock = Any() + private val pendingBackups = ConcurrentHashMap() private val statusObserverJobs = mutableListOf() private val dataListenerJobs = mutableListOf() private var periodicCheckJob: Job? = null + private var setupJob: Job? = null + private var setupGeneration: Long? = null private val runningBackups = ConcurrentHashMap.newKeySet() // Tracks active jobs since app start private val failedBackupRequired = ConcurrentHashMap() private val temporaryFailureRetries = ConcurrentHashMap() private val temporaryFailureSince = ConcurrentHashMap() + @Volatile private var isObserving = false private var lastNotificationTime = 0L @@ -172,8 +182,6 @@ class BackupRepo @Inject constructor( fun reset() { stopObservingBackups() - vssBackupClient.reset() - vssBackupClientLdk.reset() } fun setWiping(isWiping: Boolean) = _isWiping.update { isWiping } @@ -224,26 +232,41 @@ class BackupRepo @Inject constructor( isObserving = true Logger.debug("Start observing backup statuses and data store changes", context = TAG) - scope.launch { - vssBackupClient.setupWithRetry { - onSuccess = { attempt -> - Logger.debug("VSS client setup succeeded on attempt $attempt", context = TAG) - } - onRetry = { attempt, maxAttempts, delayMs -> - Logger.debug( - "VSS client setup deferred, retrying in ${delayMs}ms (attempt $attempt/$maxAttempts)", - context = TAG, - ) - } - onExhausted = { maxAttempts -> - Logger.warn("VSS client setup failed after $maxAttempts attempts", context = TAG) + setupJob = scope.launch { + vssClients.owners.collectLatest { owner -> + if (owner == null) return@collectLatest + vssClients.withWallet(owner) { + if (setupGeneration != null && setupGeneration != owner.generation) { + failedBackupRequired.clear() + temporaryFailureRetries.clear() + temporaryFailureSince.clear() + } + setupGeneration = owner.generation + vssBackupClient.setupWithRetry { + onSuccess = { attempt -> + Logger.debug("VSS client setup succeeded on attempt $attempt", context = TAG) + } + onRetry = { attempt, maxAttempts, delayMs -> + Logger.debug( + "VSS client setup deferred, retrying in ${delayMs}ms (attempt $attempt/$maxAttempts)", + context = TAG, + ) + } + onExhausted = { maxAttempts -> + Logger.warn("VSS client setup failed after $maxAttempts attempts", context = TAG) + } + }.onSuccess { + vssBackupClientLdk.setup() + _isWiping.first { !it } + cacheStore.backupStatuses.first().forEach { (category, status) -> + if (status.shouldBackup(category)) scheduleBackup(category) + } + } } - }.onSuccess { - scope.launch { vssBackupClientLdk.setup() } } } - scope.launch { + launchForWallet { BackupCategory.entries.forEach { category -> if (category !in runningBackups) { cacheStore.updateBackupStatus(category) { status -> @@ -266,11 +289,18 @@ class BackupRepo @Inject constructor( fun stopObservingBackups() { if (!isObserving) return - isObserving = false + val pendingJobs = synchronized(backupJobLock) { + isObserving = false + backupJobs.toList().also { + backupJobs.clear() + pendingBackups.clear() + } + } + setupJob?.cancel() + setupJob = null // Cancel all backup jobs - backupJobs.values.forEach { it.cancel() } - backupJobs.clear() + pendingJobs.forEach { it.cancel() } // Cancel backup status observer jobs statusObserverJobs.forEach { it.cancel() } @@ -472,8 +502,13 @@ class BackupRepo @Inject constructor( } } + private fun launchForWallet(block: suspend CoroutineScope.() -> Unit): Job { + val owner = runCatching { vssClients.captureOwner() }.getOrNull() ?: return Job().apply { cancel() } + return scope.launch { vssClients.withWallet(owner) { block() } } + } + private fun markBackupRequired(category: BackupCategory) { - scope.launch { + launchForWallet { failedBackupRequired -= category cacheStore.updateBackupStatus(category) { it.copy(required = maxOf(currentTimeMillis(), it.required + 1, it.synced + 1)) @@ -482,50 +517,45 @@ class BackupRepo @Inject constructor( } } - private fun scheduleBackup(category: BackupCategory) { - backupJobs[category]?.cancel() - - Logger.verbose("Scheduling backup for: '$category'", context = TAG) - - backupJobs[category] = scope.launch { - runningBackups += category - cacheStore.updateBackupStatus(category) { - it.copy(running = true) - } - - delay(BACKUP_DEBOUNCE) - if (category == BackupCategory.WALLET) paykitSdkService.isPaymentSubmissionActive.first { !it } - - val status = cacheStore.backupStatuses.first()[category] ?: BackupItemStatus() - if (status.isRequired && !shouldSkipBackup(category)) { - triggerBackup(category) - } else { - Logger.debug("Backup no longer needed for: '$category'", context = TAG) - runningBackups -= category - cacheStore.updateBackupStatus(category) { - it.copy(running = false) - } + private fun scheduleBackup( + category: BackupCategory, + expectedOwner: VssClientCoordinator.Owner? = null, + requireObservation: Boolean = true, + ) { + val owner = expectedOwner ?: runCatching { vssClients.captureOwner() }.getOrNull() ?: return + val job = synchronized(backupJobLock) { + if (requireObservation && !isObserving) return + var reserved = false + pendingBackups.compute(category) { _, previous -> + previous?.takeIf { it.generation >= owner.generation } ?: owner.also { reserved = true } } - }.also { job -> - job.invokeOnCompletion { exception -> - if (exception != null) { - Logger.debug("Backup job cancelled for: '$category'", context = TAG) - scope.launch { - runningBackups -= category - cacheStore.updateBackupStatus(category) { - it.copy(running = false) - } + if (!reserved) return + Logger.debug("Scheduling backup for: '$category'", context = TAG) + scope.launch(start = CoroutineStart.LAZY) { + try { + vssClients.withWallet(owner) { + delay(BACKUP_DEBOUNCE) + if (category == BackupCategory.WALLET) paykitSdkService.isPaymentSubmissionActive.first { !it } + pendingBackups.remove(category, owner) + val status = cacheStore.backupStatuses.first()[category] ?: BackupItemStatus() + if (status.shouldBackup(category)) triggerBackup(category) } + } finally { + pendingBackups.remove(category, owner) } + }.also { scheduled -> + backupJobs.add(scheduled) + scheduled.invokeOnCompletion { backupJobs.remove(scheduled) } } } + job.start() } private fun checkForFailedBackups() { val currentTime = currentTimeMillis() // find if there are any backup categories that have been failing for more than 30 minutes - scope.launch { + launchForWallet { val backupStatuses = cacheStore.backupStatuses.first() val hasFailedBackups = BackupCategory.entries.any { category -> val status = backupStatuses[category] ?: BackupItemStatus() @@ -548,7 +578,7 @@ class BackupRepo @Inject constructor( lastNotificationTime = currentTime - scope.launch { + launchForWallet { ToastEventBus.send( type = Toast.ToastType.ERROR, title = context.getString(R.string.settings__backup__failed_title), @@ -560,10 +590,12 @@ class BackupRepo @Inject constructor( } suspend fun triggerBackup(category: BackupCategory): Result = withContext(ioDispatcher) { - if (category == BackupCategory.WALLET || category == BackupCategory.METADATA) { - walletBackupMutex.withLock { performBackup(category) } - } else { - performBackup(category) + vssClients.withWallet { + if (category == BackupCategory.WALLET || category == BackupCategory.METADATA) { + walletBackupMutex.withLock { performBackup(category) } + } else { + performBackup(category) + } } } @@ -621,15 +653,20 @@ class BackupRepo @Inject constructor( suspend fun persistWalletBackup(): Result = withContext(ioDispatcher) { - walletBackupMutex.withLock { uploadWalletBackup() } - }.onFailure { markBackupRequired(BackupCategory.WALLET) } - - suspend fun persistUsdtRecoveryBackup(snapshot: String): Result = runSuspendCatching { - cacheStore.updateBackupStatus(BackupCategory.USDT_RECOVERY) { - it.copy(required = maxOf(currentTimeMillis(), it.required + 1, it.synced + 1)) + vssClients.withWallet { + walletBackupMutex.withLock { uploadWalletBackup() } + .onFailure { markBackupRequired(BackupCategory.WALLET) } + } } - uploadUsdtRecoveryBackup(snapshot).getOrThrow() - }.onFailure { markBackupRequired(BackupCategory.USDT_RECOVERY) } + + suspend fun persistUsdtRecoveryBackup(snapshot: String): Result = vssClients.withWallet { + runSuspendCatching { + cacheStore.updateBackupStatus(BackupCategory.USDT_RECOVERY) { + it.copy(required = maxOf(currentTimeMillis(), it.required + 1, it.synced + 1)) + } + uploadUsdtRecoveryBackup(snapshot).getOrThrow() + }.onFailure { markBackupRequired(BackupCategory.USDT_RECOVERY) } + } private suspend fun uploadUsdtRecoveryBackup(snapshot: String? = null): Result = withContext(ioDispatcher) { runSuspendCatching { @@ -691,10 +728,10 @@ class BackupRepo @Inject constructor( val retryDelay = (TEMPORARY_FAILURE_RETRY_DELAY * (1 shl (attempt - 1).coerceAtMost(MAX_RETRY_SHIFT))) .coerceAtMost(TEMPORARY_FAILURE_RETRY_MAX_DELAY) Logger.warn("Retrying backup for: '$category' in '$retryDelay'", e, context = TAG) - scope.launch { + launchForWallet { delay(retryDelay) - if (!failedBackupRequired.remove(category, backupRequired) || !isObserving) return@launch - val status = cacheStore.backupStatuses.first()[category] ?: return@launch + if (!failedBackupRequired.remove(category, backupRequired) || !isObserving) return@launchForWallet + val status = cacheStore.backupStatuses.first()[category] ?: return@launchForWallet if (status.shouldBackup(category)) scheduleBackup(category) } } @@ -1212,21 +1249,23 @@ class BackupRepo @Inject constructor( } suspend fun getLatestBackupTime(): ULong? = withContext(ioDispatcher) { - runCatching { - withTimeout(VSS_TIMESTAMP_TIMEOUT) { - vssBackupClient.setup().getOrThrow() - coroutineScope { - BackupCategory.entries - .filter { it != BackupCategory.LIGHTNING_CONNECTIONS && it != BackupCategory.USDT_RECOVERY } - .map { category -> async { getRemoteBackupTimestamp(category) } } - .mapNotNull { it.await() } - .filter { it > 0uL } - .maxOrNull() + vssClients.withWallet { + runCatching { + withTimeout(VSS_TIMESTAMP_TIMEOUT) { + vssBackupClient.setup().getOrThrow() + coroutineScope { + BackupCategory.entries + .filter { it != BackupCategory.LIGHTNING_CONNECTIONS && it != BackupCategory.USDT_RECOVERY } + .map { category -> async { getRemoteBackupTimestamp(category) } } + .mapNotNull { it.await() } + .filter { it > 0uL } + .maxOrNull() + } } - } - }.onFailure { e -> - Logger.warn("Failed to get VSS backup timestamp: $e", context = TAG) - }.getOrNull() + }.onFailure { e -> + Logger.warn("Failed to get VSS backup timestamp: $e", context = TAG) + }.getOrNull() + } } private suspend fun getRemoteBackupTimestamp(category: BackupCategory): ULong? { @@ -1243,11 +1282,12 @@ class BackupRepo @Inject constructor( } fun scheduleFullBackup() { + val owner = runCatching { vssClients.captureOwner() }.getOrNull() ?: return Logger.debug("Scheduling backups for all categories", context = TAG) BackupCategory.entries .filter { it != BackupCategory.LIGHTNING_CONNECTIONS } .forEach { - scheduleBackup(it) + scheduleBackup(it, expectedOwner = owner, requireObservation = false) } } diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 46d9fc0edd..2d4d34eba1 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -64,6 +64,7 @@ import to.bitkit.data.CacheStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.data.backup.VssBackupClientLdk +import to.bitkit.data.backup.VssClientCoordinator import to.bitkit.data.keychain.Keychain import to.bitkit.data.keychain.requireWalletRestoreComplete import to.bitkit.di.BgDispatcher @@ -128,6 +129,7 @@ class LightningRepo @Inject constructor( private val onchainSendAttemptStore: OnchainSendAttemptStore, private val connectivityRepo: ConnectivityRepo, private val vssBackupClientLdk: VssBackupClientLdk, + private val vssClients: VssClientCoordinator, private val urlValidator: UrlValidator, private val electrumProbeService: ElectrumProbeService, ) : OnchainReleasing { @@ -353,153 +355,159 @@ class LightningRepo @Inject constructor( shouldValidateGraph: Boolean = true, shouldRetryYieldToStop: Boolean = false, shouldCancelPendingStop: Boolean = true, - ): Result = withContext(bgDispatcher) { - if (_isRecoveryMode.value) { - return@withContext Result.failure(RecoveryModeError()) - } + ): Result = vssClients.withWallet { + withContext(bgDispatcher) { + if (_isRecoveryMode.value) { + return@withContext Result.failure(RecoveryModeError()) + } - if (shouldCancelPendingStop) cancelPendingStop() + if (shouldCancelPendingStop) cancelPendingStop() - eventHandler?.let { _eventHandlers.add(it) } + eventHandler?.let { _eventHandlers.add(it) } - // Track retry state outside mutex to avoid deadlock (Mutex is non-reentrant) - var shouldRetryStart = false - var shouldRestartForGraphReset = false - var initialLifecycleState: NodeLifecycleState + // Track retry state outside mutex to avoid deadlock (Mutex is non-reentrant) + var shouldRetryStart = false + var shouldRestartForGraphReset = false + var initialLifecycleState: NodeLifecycleState - val result = lifecycleMutex.withLock { - if (isWiping) return@withLock Result.failure(WipeInProgressError()) - initialLifecycleState = _lightningState.value.nodeLifecycleState - if (initialLifecycleState.isRunningOrStarting()) { - return@withLock skipStartForRunningNode( - lifecycleState = initialLifecycleState, - customServerUrl = customServerUrl, - customRgsServerUrl = customRgsServerUrl, - ) - } + val result = lifecycleMutex.withLock { + if (isWiping) return@withLock Result.failure(WipeInProgressError()) + initialLifecycleState = _lightningState.value.nodeLifecycleState + if (initialLifecycleState.isRunningOrStarting()) { + return@withLock skipStartForRunningNode( + lifecycleState = initialLifecycleState, + customServerUrl = customServerUrl, + customRgsServerUrl = customRgsServerUrl, + ) + } - runCatching { - _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Starting) } - - // Setup if needed - if (lightningService.node == null) { - val setupResult = - setup(walletIndex, customServerUrl, customRgsServerUrl, channelMigration) - if (setupResult.isFailure) { - _lightningState.update { - it.copy( - nodeLifecycleState = NodeLifecycleState.ErrorStarting( - setupResult.exceptionOrNull() ?: NodeSetupError() + runCatching { + _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Starting) } + + // Setup if needed + if (lightningService.node == null) { + val setupResult = + setup(walletIndex, customServerUrl, customRgsServerUrl, channelMigration) + if (setupResult.isFailure) { + _lightningState.update { + it.copy( + nodeLifecycleState = NodeLifecycleState.ErrorStarting( + setupResult.exceptionOrNull() ?: NodeSetupError() + ) ) - ) + } + return@withLock setupResult } - return@withLock setupResult } - } - if (lightningService.status?.isRunning == true) { - Logger.info("LDK node already running", context = TAG) - runSuspendCatching { lightningService.reconcileWatchOnlyAccounts() } - .onFailure { - Logger.warn("Failed to reconcile Paykit Server accounts during startup", it, context = TAG) - } - return@withLock adoptRunningNode() - } + if (lightningService.status?.isRunning == true) { + Logger.info("LDK node already running", context = TAG) + runSuspendCatching { lightningService.reconcileWatchOnlyAccounts() } + .onFailure { + Logger.warn( + "Failed to reconcile Paykit Server accounts during startup", + it, + context = TAG, + ) + } + return@withLock adoptRunningNode() + } - lightningService.start(timeout, ::onEvent) + lightningService.start(timeout, ::onEvent) - _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) } + _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) } - // Initial state sync - syncState() - logNodeSupportSummary("node started") - refreshChannelCache() + // Initial state sync + syncState() + logNodeSupportSummary("node started") + refreshChannelCache() - if (shouldValidateGraph && !lightningService.aresRequiredPeersInNetworkGraph()) { - Logger.warn("Network graph is stale, resetting and restarting...", context = TAG) + if (shouldValidateGraph && !lightningService.aresRequiredPeersInNetworkGraph()) { + Logger.warn("Network graph is stale, resetting and restarting...", context = TAG) - lightningService.stop() - clearNetworkGraph(walletIndex) + lightningService.stop() + clearNetworkGraph(walletIndex) - _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Stopped) } - shouldRestartForGraphReset = true - return@withLock Result.success(Unit) - } + _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Stopped) } + shouldRestartForGraphReset = true + return@withLock Result.success(Unit) + } - // Post-startup tasks (non-blocking) - disconnectIdlePeers().onFailure { - Logger.error("Failed to disconnect idle peers", it, context = TAG) - } - logNodeSupportSummary("idle peers disconnected") + // Post-startup tasks (non-blocking) + disconnectIdlePeers().onFailure { + Logger.error("Failed to disconnect idle peers", it, context = TAG) + } + logNodeSupportSummary("idle peers disconnected") - sync().onFailure { e -> - Logger.warn("Initial sync failed, event-driven sync will retry", e, context = TAG) - } - Result.success(Unit) - }.getOrElse { e -> - if (e is CancellationException) { - withContext(NonCancellable) { reconcileCancelledStart(initialLifecycleState) } - throw e - } + sync().onFailure { e -> + Logger.warn("Initial sync failed, event-driven sync will retry", e, context = TAG) + } + Result.success(Unit) + }.getOrElse { e -> + if (e is CancellationException) { + withContext(NonCancellable) { reconcileCancelledStart(initialLifecycleState) } + throw e + } - val currentState = _lightningState.value.nodeLifecycleState - if (currentState.isRunning()) { - Logger.warn("Start error but node is $currentState, skipping retry", e, context = TAG) - return@withLock Result.success(Unit) - } + val currentState = _lightningState.value.nodeLifecycleState + if (currentState.isRunning()) { + Logger.warn("Start error but node is $currentState, skipping retry", e, context = TAG) + return@withLock Result.success(Unit) + } + + if (lightningService.status?.isRunning == true) { + Logger.warn("Start error but LDK node is running, adopting it", e, context = TAG) + return@withLock adoptRunningNode() + } - if (lightningService.status?.isRunning == true) { - Logger.warn("Start error but LDK node is running, adopting it", e, context = TAG) - return@withLock adoptRunningNode() + if (shouldRetry) { + Logger.warn("Start error, will retry...", e, context = TAG) + _lightningState.update { it.copy(nodeLifecycleState = initialLifecycleState) } + shouldRetryStart = true + Result.failure(e) + } else { + _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.ErrorStarting(e)) } + Result.failure(e) + } } + } - if (shouldRetry) { - Logger.warn("Start error, will retry...", e, context = TAG) - _lightningState.update { it.copy(nodeLifecycleState = initialLifecycleState) } - shouldRetryStart = true - Result.failure(e) - } else { - _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.ErrorStarting(e)) } - Result.failure(e) + // Retry OUTSIDE the mutex to avoid deadlock (Kotlin Mutex is non-reentrant) + if (shouldRetryStart) { + delay(2.seconds) + // A stop requested after this start began wins over the retry; a foreground start cancels it + if (shouldRetryYieldToStop && pendingStopJob.get() != null) { + Logger.info("Skipped start retry because a stop was requested", context = TAG) + return@withContext Result.failure(NodeStartYieldedToStopError(result.exceptionOrNull())) } + return@withContext startNode( + walletIndex = walletIndex, + timeout = timeout, + shouldRetry = false, + customServerUrl = customServerUrl, + customRgsServerUrl = customRgsServerUrl, + channelMigration = channelMigration, + shouldValidateGraph = shouldValidateGraph, + shouldCancelPendingStop = !shouldRetryYieldToStop, + ) } - } - // Retry OUTSIDE the mutex to avoid deadlock (Kotlin Mutex is non-reentrant) - if (shouldRetryStart) { - delay(2.seconds) - // A stop requested after this start began wins over the retry; a foreground start cancels it - if (shouldRetryYieldToStop && pendingStopJob.get() != null) { - Logger.info("Skipped start retry because a stop was requested", context = TAG) - return@withContext Result.failure(NodeStartYieldedToStopError(result.exceptionOrNull())) + // Restart after graph reset OUTSIDE the mutex to avoid deadlock + if (shouldRestartForGraphReset) { + return@withContext start( + walletIndex = walletIndex, + timeout = timeout, + shouldRetry = shouldRetry, + customServerUrl = customServerUrl, + customRgsServerUrl = customRgsServerUrl, + eventHandler = eventHandler, + channelMigration = channelMigration, + shouldValidateGraph = false, // Prevent infinite loop + ) } - return@withContext startNode( - walletIndex = walletIndex, - timeout = timeout, - shouldRetry = false, - customServerUrl = customServerUrl, - customRgsServerUrl = customRgsServerUrl, - channelMigration = channelMigration, - shouldValidateGraph = shouldValidateGraph, - shouldCancelPendingStop = !shouldRetryYieldToStop, - ) - } - // Restart after graph reset OUTSIDE the mutex to avoid deadlock - if (shouldRestartForGraphReset) { - return@withContext start( - walletIndex = walletIndex, - timeout = timeout, - shouldRetry = shouldRetry, - customServerUrl = customServerUrl, - customRgsServerUrl = customRgsServerUrl, - eventHandler = eventHandler, - channelMigration = channelMigration, - shouldValidateGraph = false, // Prevent infinite loop - ) + result } - - result } private suspend fun adoptRunningNode(): Result { @@ -729,14 +737,16 @@ class LightningRepo @Inject constructor( } } - suspend fun resetNetworkGraph(walletIndex: Int = 0): Result = withContext(bgDispatcher) { - Logger.warn("Resetting network graph (manual)", context = TAG) - runCatching { - if (lightningService.node != null) { - lightningService.stop() + suspend fun resetNetworkGraph(walletIndex: Int = 0): Result = vssClients.withWallet { + withContext(bgDispatcher) { + Logger.warn("Resetting network graph (manual)", context = TAG) + runSuspendCatching { + if (lightningService.node != null) { + lightningService.stop() + } + // Propagate VSS failures: a manual reset that leaves the graph in VSS is ineffective. + clearNetworkGraph(walletIndex).getOrThrow() } - // Propagate VSS failures: a manual reset that leaves the graph in VSS is ineffective. - clearNetworkGraph(walletIndex).getOrThrow() } } @@ -749,8 +759,7 @@ class LightningRepo @Inject constructor( } return runSuspendCatching { - vssBackupClientLdk.setup(walletIndex).getOrThrow() - vssBackupClientLdk.deleteObject("network_graph").getOrThrow() + vssBackupClientLdk.deleteObjects(listOf("network_graph"), walletIndex).getOrThrow() Logger.info("Cleared network graph from VSS", context = TAG) }.onFailure { Logger.warn("Failed to clear network graph from VSS", it, context = TAG) @@ -2451,100 +2460,110 @@ class LightningRepo @Inject constructor( * so callers can require any scores sync timestamp to be strictly newer to prove a post-reset download. */ @OptIn(ExperimentalTime::class) - suspend fun resetPathfindingScores(walletIndex: Int = 0): Result = withContext(bgDispatcher) { - Logger.info("Resetting pathfinding scores", context = TAG) - - waitForNodeToStop().onFailure { return@withContext Result.failure(it) } - stop().onFailure { - Logger.error("Failed to stop node during pathfinding scores reset", it, context = TAG) - return@withContext Result.failure(it) - } + suspend fun resetPathfindingScores(walletIndex: Int = 0): Result = vssClients.withWallet { + withContext(bgDispatcher) { + Logger.info("Resetting pathfinding scores", context = TAG) - runCatching { - val lifecycleState = _lightningState.value.nodeLifecycleState - check(lifecycleState == NodeLifecycleState.Stopped) { - "Node lifecycle changed to '$lifecycleState' during pathfinding scores reset" + waitForNodeToStop().onFailure { return@withContext Result.failure(it) } + stop().onFailure { + Logger.error("Failed to stop node during pathfinding scores reset", it, context = TAG) + return@withContext Result.failure(it) } - // Gate the destructive VSS deletes on the previous node's release, so the old node cannot - // re-persist scores over the delete while it is still draining. - lightningService.awaitNodeRelease() - vssBackupClientLdk.setup(walletIndex).getOrThrow() - vssBackupClientLdk.deleteObject(VSS_KEY_SCORER).getOrThrow() - vssBackupClientLdk.deleteObject(VSS_KEY_EXTERNAL_SCORES_CACHE).getOrThrow() - }.onFailure { - Logger.error("Failed to delete pathfinding scores from VSS", it, context = TAG) - start(walletIndex = walletIndex, shouldRetry = false, shouldValidateGraph = false).onFailure { startError -> - Logger.error("Failed to restart node after pathfinding scores reset failure", startError, context = TAG) + + runSuspendCatching { + val lifecycleState = _lightningState.value.nodeLifecycleState + check(lifecycleState == NodeLifecycleState.Stopped) { + "Node lifecycle changed to '$lifecycleState' during pathfinding scores reset" + } + // Gate the destructive VSS deletes on the previous node's release, so the old node cannot + // re-persist scores over the delete while it is still draining. + lightningService.awaitNodeRelease() + vssBackupClientLdk.deleteObjects( + listOf(VSS_KEY_SCORER, VSS_KEY_EXTERNAL_SCORES_CACHE), + walletIndex, + ).getOrThrow() + }.onFailure { + Logger.error("Failed to delete pathfinding scores from VSS", it, context = TAG) + start(walletIndex = walletIndex, shouldRetry = false, shouldValidateGraph = false) + .onFailure { startError -> + Logger.error( + "Failed to restart node after pathfinding scores reset failure", + startError, + context = TAG, + ) + } + return@withContext Result.failure(it) } - return@withContext Result.failure(it) - } - val resetAtSecs = nowMillis() / 1000 + val resetAtSecs = nowMillis() / 1000 - start(walletIndex = walletIndex, shouldRetry = false, shouldValidateGraph = false) - .map { resetAtSecs } - .onSuccess { - Logger.info("Pathfinding scores reset at '$resetAtSecs'", context = TAG) - } + start(walletIndex = walletIndex, shouldRetry = false, shouldValidateGraph = false) + .map { resetAtSecs } + .onSuccess { + Logger.info("Pathfinding scores reset at '$resetAtSecs'", context = TAG) + } + } } - suspend fun resetPaymentRoutingCachesAndWait(walletIndex: Int = 0): Result = withContext(bgDispatcher) { - val refreshStartedAtMs = nowMillis() - val refreshStartedAtSecs = (refreshStartedAtMs / 1000).toULong() - val requiresRgsRefresh = Env.network != Network.REGTEST && - !settingsStore.data.first().rgsServerUrl.isNullOrEmpty() - val requiresScorerRefresh = Env.ldkScorerUrl != null - val resetErrors = mutableListOf() + suspend fun resetPaymentRoutingCachesAndWait(walletIndex: Int = 0): Result = vssClients.withWallet { + withContext(bgDispatcher) { + val refreshStartedAtMs = nowMillis() + val refreshStartedAtSecs = (refreshStartedAtMs / 1000).toULong() + val requiresRgsRefresh = Env.network != Network.REGTEST && + !settingsStore.data.first().rgsServerUrl.isNullOrEmpty() + val requiresScorerRefresh = Env.ldkScorerUrl != null + val resetErrors = mutableListOf() - Logger.info( - "Started payment routing refresh rgs='$requiresRgsRefresh' scorer='$requiresScorerRefresh'", - context = TAG, - ) + Logger.info( + "Started payment routing refresh rgs='$requiresRgsRefresh' scorer='$requiresScorerRefresh'", + context = TAG, + ) - val resetResult = withContext(NonCancellable) reset@{ - stop().onFailure { - start( - walletIndex = walletIndex, - shouldRetry = false, - shouldValidateGraph = false, - ).onFailure { startError -> - Logger.error( - "Failed to restart node after payment routing refresh stop failure", - startError, - context = TAG, - ) + val resetResult = withContext(NonCancellable) reset@{ + stop().onFailure { + start( + walletIndex = walletIndex, + shouldRetry = false, + shouldValidateGraph = false, + ).onFailure { startError -> + Logger.error( + "Failed to restart node after payment routing refresh stop failure", + startError, + context = TAG, + ) + } + return@reset Result.failure(it) } - return@reset Result.failure(it) - } - clearNetworkGraph(walletIndex).onFailure { - resetErrors.add(it) - } + clearNetworkGraph(walletIndex).onFailure { + resetErrors.add(it) + } - resetPathfindingScores(walletIndex).onFailure { - resetErrors.add(it) - } + resetPathfindingScores(walletIndex).onFailure { + resetErrors.add(it) + } - resetErrors.firstOrNull()?.let { - Result.failure(it) - } ?: Result.success(Unit) - } - resetResult.onFailure { - return@withContext Result.failure(it) - } + resetErrors.firstOrNull()?.let { + Result.failure(it) + } ?: Result.success(Unit) + } + resetResult.onFailure { + return@withContext Result.failure(it) + } - val result = waitForPaymentRoutingDataRefresh( - walletIndex = walletIndex, - refreshStartedAtMs = refreshStartedAtMs, - refreshStartedAtSecs = refreshStartedAtSecs, - requiresRgsRefresh = requiresRgsRefresh, - requiresScorerRefresh = requiresScorerRefresh, - ) - result.onSuccess { - Logger.info( - "Finished payment routing refresh elapsedMs='${nowMillis() - refreshStartedAtMs}'", - context = TAG, + val result = waitForPaymentRoutingDataRefresh( + walletIndex = walletIndex, + refreshStartedAtMs = refreshStartedAtMs, + refreshStartedAtSecs = refreshStartedAtSecs, + requiresRgsRefresh = requiresRgsRefresh, + requiresScorerRefresh = requiresScorerRefresh, ) + result.onSuccess { + Logger.info( + "Finished payment routing refresh elapsedMs='${nowMillis() - refreshStartedAtMs}'", + context = TAG, + ) + } } } @@ -2605,30 +2624,35 @@ class LightningRepo @Inject constructor( * The caller still awaits the [Result], so a live caller keeps reporting the outcome; a cancelled * one only loses the reporting, never the restart. */ - suspend fun restartNodeDetached(): Result = scope.async { restartNode() }.await() + suspend fun restartNodeDetached(): Result { + val owner = vssClients.captureOwner() + return scope.async { vssClients.withWallet(owner) { restartNode() } }.await() + } suspend fun restartNode( channelMigration: ChannelDataMigration? = null, walletIndex: Int = 0, - ): Result = withContext(bgDispatcher) { - Logger.info("Restarting node", context = TAG) - stop().onFailure { - Logger.error("Failed to stop node during restart", it, context = TAG) - return@withContext Result.failure(it) - } - startNode( - walletIndex = walletIndex, - channelMigration = channelMigration, - shouldRetryYieldToStop = true - ).onFailure { - if (it is NodeStartYieldedToStopError) { - Logger.info("Deferred node restart to a requested stop", context = TAG) - } else { - Logger.error("Failed to start node during restart", it, context = TAG) + ): Result = vssClients.withWallet { + withContext(bgDispatcher) { + Logger.info("Restarting node", context = TAG) + stop().onFailure { + Logger.error("Failed to stop node during restart", it, context = TAG) + return@withContext Result.failure(it) + } + startNode( + walletIndex = walletIndex, + channelMigration = channelMigration, + shouldRetryYieldToStop = true + ).onFailure { + if (it is NodeStartYieldedToStopError) { + Logger.info("Deferred node restart to a requested stop", context = TAG) + } else { + Logger.error("Failed to start node during restart", it, context = TAG) + } + return@withContext Result.failure(it) + }.onSuccess { + Logger.info("Node restarted successfully", context = TAG) } - return@withContext Result.failure(it) - }.onSuccess { - Logger.info("Node restarted successfully", context = TAG) } } diff --git a/app/src/main/java/to/bitkit/viewmodels/BackupsViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/BackupsViewModel.kt index 350c2c716b..01d68197f7 100644 --- a/app/src/main/java/to/bitkit/viewmodels/BackupsViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/BackupsViewModel.kt @@ -13,6 +13,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import to.bitkit.data.CacheStore +import to.bitkit.data.backup.VssClientCoordinator import to.bitkit.models.BackupCategory import to.bitkit.models.BackupItemStatus import to.bitkit.models.NodeLifecycleState @@ -25,6 +26,7 @@ class BackupsViewModel @Inject constructor( private val cacheStore: CacheStore, private val backupRepo: BackupRepo, private val lightningRepo: LightningRepo, + private val vssClients: VssClientCoordinator, ) : ViewModel() { private val _uiState = MutableStateFlow(BackupStatusUiState()) @@ -63,9 +65,12 @@ class BackupsViewModel @Inject constructor( } fun retryBackup(category: BackupCategory) { + val owner = runCatching { vssClients.captureOwner() }.getOrNull() ?: return viewModelScope.launch { - delay(500) // small delay for UX feedback - backupRepo.triggerBackup(category) + vssClients.withWallet(owner) { + delay(500) // small delay for UX feedback + backupRepo.triggerBackup(category) + } } } } diff --git a/app/src/test/java/to/bitkit/data/WalletConnectionRecoveryTest.kt b/app/src/test/java/to/bitkit/data/WalletConnectionRecoveryTest.kt index 5324176595..ef5943b176 100644 --- a/app/src/test/java/to/bitkit/data/WalletConnectionRecoveryTest.kt +++ b/app/src/test/java/to/bitkit/data/WalletConnectionRecoveryTest.kt @@ -5,12 +5,15 @@ import android.content.Context import androidx.test.core.app.ApplicationProvider import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.withContext import org.junit.After import org.junit.Before import org.junit.Test @@ -22,6 +25,7 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config +import to.bitkit.data.backup.VssClientCoordinator import to.bitkit.data.backup.VssStoreIdProvider import to.bitkit.data.entities.ConfigEntity import to.bitkit.data.keychain.Keychain @@ -45,6 +49,7 @@ class WalletConnectionRecoveryTest : BaseUnitTest() { private val keychain = mock() private val db = mock() private val binding = mock() + private val vssClients = VssClientCoordinator() private val config = MutableStateFlow(listOf(ConfigEntity())) private var record: String? = null private var pending = false @@ -82,7 +87,47 @@ class WalletConnectionRecoveryTest : BaseUnitTest() { @After fun tearDown() = runBlocking { settings.reset() } - private fun instance(store: SettingsStore = settings) = WalletConnectionRecovery(keychain, db, binding, store) + private fun instance(store: SettingsStore = settings) = WalletConnectionRecovery( + keychain, + db, + binding, + store, + vssClients, + ) + + @Test + fun `identity change waits for VSS cleanup and keeps admission closed through credentials`() = test { + val cleanup = CompletableDeferred() + var changed = false + var drained = false + val old = launch { + vssClients.withWallet { + try { + awaitCancellation() + } finally { + withContext(NonCancellable) { + cleanup.await() + drained = true + } + } + } + } + runCurrent() + val transition = launch { + sut.withIdentityChange { + assertTrue(drained) + assertFailsWith { vssClients.withWallet {} } + changed = true + } + } + runCurrent() + assertFalse(changed) + cleanup.complete(Unit) + transition.join() + assertTrue(changed) + old.join() + vssClients.withWallet {} + } @Test fun `queued wallet generation is revoked during same seed replacement`() = test { diff --git a/app/src/test/java/to/bitkit/data/backup/VssBackupClientLdkTest.kt b/app/src/test/java/to/bitkit/data/backup/VssBackupClientLdkTest.kt index f80e27d0b0..6b8c919349 100644 --- a/app/src/test/java/to/bitkit/data/backup/VssBackupClientLdkTest.kt +++ b/app/src/test/java/to/bitkit/data/backup/VssBackupClientLdkTest.kt @@ -1,14 +1,16 @@ package to.bitkit.data.backup +import com.synonym.vssclient.vssDeriveStoreId import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import org.mockito.Mockito.mockStatic -import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import to.bitkit.data.keychain.Keychain +import to.bitkit.env.Env import to.bitkit.test.BaseUnitTest +import kotlin.test.assertEquals import kotlin.test.assertIs import kotlin.test.assertNull import kotlin.test.assertTrue @@ -17,27 +19,55 @@ class VssBackupClientLdkTest : BaseUnitTest() { private lateinit var sut: VssBackupClientLdk - private val vssStoreIdProvider = mock() private val keychain = mock() @Before fun setUp() = runBlocking { sut = VssBackupClientLdk( ioDispatcher = testDispatcher, - vssStoreIdProvider = vssStoreIdProvider, + coordinator = VssClientCoordinator(), keychain = keychain, ) } + @Test + fun `setup derives store id from the same captured credentials as the signer`() = test { + whenever(keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(TEST_MNEMONIC) + whenever(keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name)).thenReturn("test-passphrase") + var setupArguments: List? = null + var deriveArguments: List? = null + mockStatic(Class.forName(VSS_FFI_CLASS)) { invocation -> + when (invocation.method.name) { + "vssDeriveStoreId" -> { + deriveArguments = invocation.arguments.toList() + "captured-store" + } + "vssNewLdkClientWithLnurlAuth" -> { + setupArguments = invocation.arguments.take(5) + null + } + else -> null + } + }.use { + assertTrue(sut.setup().isSuccess) + assertEquals(listOf(Env.vssStoreIdPrefix, TEST_MNEMONIC, "test-passphrase"), deriveArguments) + assertEquals( + listOf(Env.vssServerUrl, "captured-store", TEST_MNEMONIC, "test-passphrase", Env.lnurlAuthServerUrl), + setupArguments, + ) + } + } + @Test fun `setup succeeding after a failure leaves the client usable`() = test { whenever(keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(null) assertIs(sut.setup().exceptionOrNull()) whenever(keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(TEST_MNEMONIC) - whenever(vssStoreIdProvider.getVssStoreId(any())).thenReturn("test-store-id") mockStatic(Class.forName(VSS_FFI_CLASS)).use { + whenever(vssDeriveStoreId(Env.vssStoreIdPrefix, TEST_MNEMONIC, null)) + .thenReturn("captured-store") assertTrue(sut.setup().isSuccess) val result = sut.getObject("key") diff --git a/app/src/test/java/to/bitkit/data/backup/VssBackupClientTest.kt b/app/src/test/java/to/bitkit/data/backup/VssBackupClientTest.kt index 1ab0912034..abb2309777 100644 --- a/app/src/test/java/to/bitkit/data/backup/VssBackupClientTest.kt +++ b/app/src/test/java/to/bitkit/data/backup/VssBackupClientTest.kt @@ -1,6 +1,7 @@ package to.bitkit.data.backup import com.synonym.vssclient.VssItem +import com.synonym.vssclient.vssDeriveStoreId import com.synonym.vssclient.vssStore import kotlinx.coroutines.runBlocking import org.junit.Before @@ -8,10 +9,9 @@ import org.junit.Test import org.mockito.Mockito.mockStatic import org.mockito.kotlin.any import org.mockito.kotlin.mock -import org.mockito.kotlin.never -import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.data.keychain.Keychain +import to.bitkit.env.Env import to.bitkit.test.BaseUnitTest import kotlin.test.assertEquals import kotlin.test.assertIs @@ -22,14 +22,13 @@ class VssBackupClientTest : BaseUnitTest() { private lateinit var sut: VssBackupClient - private val vssStoreIdProvider = mock() private val keychain = mock() @Before fun setUp() = runBlocking { sut = VssBackupClient( ioDispatcher = testDispatcher, - vssStoreIdProvider = vssStoreIdProvider, + coordinator = VssClientCoordinator(), keychain = keychain, ) } @@ -45,23 +44,31 @@ class VssBackupClientTest : BaseUnitTest() { } @Test - fun `setup does not call vssStoreIdProvider when mnemonic is not available`() = test { - whenever(keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(null) - - sut.setup() - - verify(vssStoreIdProvider, never()).getVssStoreId(any()) - } - - @Test - fun `setup checks mnemonic before proceeding with vss initialization`() = test { + fun `setup derives store id from the same captured credentials as the signer`() = test { whenever(keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(TEST_MNEMONIC) - whenever(vssStoreIdProvider.getVssStoreId(any())).thenReturn("test-store-id") - - // Setup will fail on native VSS calls, but we verify we passed the mnemonic check - runCatching { sut.setup() } - - verify(vssStoreIdProvider).getVssStoreId(any()) + whenever(keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name)).thenReturn("test-passphrase") + var setupArguments: List? = null + var deriveArguments: List? = null + mockStatic(Class.forName(VSS_FFI_CLASS)) { invocation -> + when (invocation.method.name) { + "vssDeriveStoreId" -> { + deriveArguments = invocation.arguments.toList() + "captured-store" + } + "vssNewClientWithLnurlAuth" -> { + setupArguments = invocation.arguments.take(5) + null + } + else -> null + } + }.use { + assertTrue(sut.setup().isSuccess) + assertEquals(listOf(Env.vssStoreIdPrefix, TEST_MNEMONIC, "test-passphrase"), deriveArguments) + assertEquals( + listOf(Env.vssServerUrl, "captured-store", TEST_MNEMONIC, "test-passphrase", Env.lnurlAuthServerUrl), + setupArguments, + ) + } } @Test @@ -80,9 +87,10 @@ class VssBackupClientTest : BaseUnitTest() { assertIs(sut.setup().exceptionOrNull()) whenever(keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(TEST_MNEMONIC) - whenever(vssStoreIdProvider.getVssStoreId(any())).thenReturn("test-store-id") mockStatic(Class.forName(VSS_FFI_CLASS)).use { + whenever(vssDeriveStoreId(Env.vssStoreIdPrefix, TEST_MNEMONIC, null)) + .thenReturn("captured-store") assertTrue(sut.setup().isSuccess) val result = sut.getObject("METADATA") @@ -97,9 +105,10 @@ class VssBackupClientTest : BaseUnitTest() { whenever(keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)) .thenReturn(null) .thenReturn(TEST_MNEMONIC) - whenever(vssStoreIdProvider.getVssStoreId(any())).thenReturn("test-store-id") mockStatic(Class.forName(VSS_FFI_CLASS)).use { + whenever(vssDeriveStoreId(Env.vssStoreIdPrefix, TEST_MNEMONIC, null)) + .thenReturn("captured-store") assertTrue(sut.setupWithRetry(baseDelayMs = 0L) {}.isSuccess) val item = VssItem("METADATA", byteArrayOf(), 1L) diff --git a/app/src/test/java/to/bitkit/data/backup/VssClientCoordinatorTest.kt b/app/src/test/java/to/bitkit/data/backup/VssClientCoordinatorTest.kt new file mode 100644 index 0000000000..437d300ea7 --- /dev/null +++ b/app/src/test/java/to/bitkit/data/backup/VssClientCoordinatorTest.kt @@ -0,0 +1,188 @@ +package to.bitkit.data.backup + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.withContext +import org.junit.Test +import to.bitkit.test.BaseUnitTest +import to.bitkit.utils.AppError +import kotlin.coroutines.cancellation.CancellationException +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +@OptIn(ExperimentalCoroutinesApi::class) +class VssClientCoordinatorTest : BaseUnitTest() { + private val sut = VssClientCoordinator() + + @Test + fun `retirement waits for cancelled setup cleanup before shutdown and replacement`() = test { + val cleanup = CompletableDeferred() + var shutdown = false + val old = launch { + sut.setup(VssClientCoordinator.Domain.APP) { + try { + awaitCancellation() + } finally { + withContext(NonCancellable) { cleanup.await() } + } + } + } + runCurrent() + val transition = launch { sut.withSuspendedClients({ shutdown = true }) {} } + runCurrent() + assertFalse(shutdown) + assertFalse(transition.isCompleted) + assertFailsWith { sut.withWallet {} } + cleanup.complete(Unit) + transition.join() + assertTrue(old.isCancelled) + assertTrue(shutdown) + sut.setup(VssClientCoordinator.Domain.APP) {} + assertEquals("replacement", sut.withClient(VssClientCoordinator.Domain.APP) { "replacement" }) + } + + @Test + fun `both domains and local result tails finish before credential change`() = test { + VssClientCoordinator.Domain.entries.forEach { sut.setup(it) {} } + val release = CompletableDeferred() + val finished = mutableSetOf() + val shutdown = mutableSetOf() + VssClientCoordinator.Domain.entries.forEach { domain -> + launch { + sut.withClient(domain) { + try { + awaitCancellation() + } finally { + withContext(NonCancellable) { + release.await() + finished.add(domain) + } + } + } + } + } + runCurrent() + val transition = launch { + sut.withSuspendedClients({ shutdown.add(it) }) { + assertEquals(VssClientCoordinator.Domain.entries.toSet(), finished) + assertEquals(finished, shutdown) + assertFailsWith { sut.captureOwner() } + } + } + runCurrent() + assertTrue(shutdown.isEmpty()) + release.complete(Unit) + transition.join() + } + + @Test + fun `old payload and compound followup cannot enter replacement client`() = test { + sut.setup(VssClientCoordinator.Domain.APP) {} + val owner = sut.captureOwner() + var calls = 0 + val followup = CompletableDeferred() + val original = launch { + sut.withWallet(owner) { + sut.withClient(VssClientCoordinator.Domain.APP) { calls++ } + followup.await() + sut.withClient(VssClientCoordinator.Domain.APP) { calls++ } + } + } + runCurrent() + sut.withSuspendedClients({}) {} + assertTrue(original.isCancelled) + sut.setup(VssClientCoordinator.Domain.APP) {} + assertFailsWith { sut.withWallet(owner) { calls++ } } + assertEquals(1, calls) + } + + @Test + fun `cancelled retirement still drains and reopens without changing credentials`() = test { + val cleanup = CompletableDeferred() + var changed = false + launch { + sut.withWallet { + try { + awaitCancellation() + } finally { + withContext(NonCancellable) { cleanup.await() } + } + } + } + runCurrent() + val transition = launch { sut.withSuspendedClients({}) { changed = true } } + runCurrent() + transition.cancel() + assertFailsWith { sut.captureOwner() } + cleanup.complete(Unit) + transition.join() + assertFalse(changed) + sut.withWallet {} + } + + @Test + fun `credential failure reopens uninitialized slots and invalidates previous owner`() = test { + val original = sut.captureOwner() + assertFailsWith { sut.withSuspendedClients({}) { throw FixtureFailure() } } + assertFailsWith { sut.withWallet(original) {} } + var initialized = false + sut.setup(VssClientCoordinator.Domain.APP) { initialized = true } + assertTrue(initialized) + } + + @Test + fun `setup waiters share successful setup and calls can overlap`() = test { + val setupRelease = CompletableDeferred() + var setups = 0 + val first = launch { + sut.setup(VssClientCoordinator.Domain.APP) { + setups++ + setupRelease.await() + } + } + val second = launch { sut.setup(VssClientCoordinator.Domain.APP) { setups++ } } + runCurrent() + setupRelease.complete(Unit) + first.join() + second.join() + assertEquals(1, setups) + val release = CompletableDeferred() + var entered = 0 + val calls = List(2) { + async { + sut.withClient(VssClientCoordinator.Domain.APP) { + entered++ + release.await() + } + } + } + runCurrent() + assertEquals(2, entered) + release.complete(Unit) + calls.forEach { it.await() } + } + + @Test + fun `retirement wakes calls waiting for explicit setup`() = test { + val waiting = launch { sut.withClient(VssClientCoordinator.Domain.APP) { error("Not initialized") } } + runCurrent() + sut.withSuspendedClients({}) {} + assertTrue(waiting.isCancelled) + } + + @Test + fun `shutdown failure leaves admission closed`() = test { + sut.setup(VssClientCoordinator.Domain.APP) {} + assertFailsWith { sut.withSuspendedClients({ throw FixtureFailure() }) {} } + assertFailsWith { sut.withWallet {} } + } + + private class FixtureFailure : AppError("fixture failure") +} diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index b0591370db..1570a36cce 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -65,6 +65,7 @@ import to.bitkit.data.backup.UsdtRecoveryBackupStore import to.bitkit.data.backup.UsdtRecoveryBackupV1 import to.bitkit.data.backup.VssBackupClient import to.bitkit.data.backup.VssBackupClientLdk +import to.bitkit.data.backup.VssClientCoordinator import to.bitkit.data.dao.TransferDao import to.bitkit.data.entities.TransferEntity import to.bitkit.data.keychain.Keychain @@ -115,6 +116,7 @@ class BackupRepoTest : BaseUnitTest() { private val context = mock() private val cacheStore = mock() private val vssBackupClient = mock() + private val vssClients = VssClientCoordinator() private val vssBackupClientLdk = mock() private val settingsStore = mock() private val widgetsStore = mock() @@ -177,6 +179,7 @@ class BackupRepoTest : BaseUnitTest() { whenever { cacheStore.updateBackupStatus(any(), any()) }.thenReturn(Unit) whenever { cacheStore.update(any()) }.thenReturn(Unit) whenever(cacheStore.data).thenReturn(cacheData) + whenever(cacheStore.backupStatuses).thenReturn(cacheData.map { it.backupStatuses }) whenever(settingsStore.data).thenReturn(settingsData) whenever { settingsStore.update(any()) }.thenReturn(Unit) whenever(widgetsStore.data).thenReturn(widgetsData) @@ -222,6 +225,65 @@ class BackupRepoTest : BaseUnitTest() { sut = createSut() } + @Test + fun `explicit first wallet backup does not wait for node observers`() = test { + val statuses = MutableStateFlow(mapOf(BackupCategory.WALLET to BackupItemStatus(required = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + sut.scheduleFullBackup() + advanceTimeBy(5_000) + runCurrent() + verify(vssBackupClient).setup() + verify(vssBackupClient, times(1)).putObject(eq(BackupCategory.WALLET.name), any()) + verify(vssBackupClient, never()).setupWithRetry(any(), any(), any()) + } + + @Test + fun `observer bootstrap requeues a required backup after a failed identity transition`() = test { + val statuses = MutableStateFlow(mapOf(BackupCategory.SETTINGS to BackupItemStatus(required = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + try { + sut.startObservingBackups() + runCurrent() + verify(vssBackupClient, times(1)).setupWithRetry(any(), any(), any()) + val recovery = connectionRecoveryFixture(settingsStore, keychain, vssClients) + assertFailsWith { + recovery.withIdentityChange { throw BackupRepoTestError("credentials unchanged") } + } + runCurrent() + verify(vssBackupClient, times(2)).setupWithRetry(any(), any(), any()) + verify(vssBackupClientLdk, times(2)).setup() + advanceTimeBy(5_000) + runCurrent() + verify(vssBackupClient, times(1)).putObject(eq(BackupCategory.SETTINGS.name), any()) + } finally { + sut.stopObservingBackups() + } + } + + @Test + fun `backup failure status drains before replacement credentials`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + var replaced = false + var crossed = false + whenever(cacheStore.updateBackupStatus(eq(BackupCategory.WALLET), any())).doSuspendableAnswer { + entered.complete(Unit) + release.await() + crossed = replaced + Unit + } + whenever(pubkyRepo.hasIdentityForBackup()).thenReturn(true) + assertTrue(sut.persistWalletBackup().isFailure) + entered.await() + val recovery = connectionRecoveryFixture(settingsStore, keychain, vssClients) + recovery.withIdentityChange { replaced = true } + release.complete(Unit) + runCurrent() + assertTrue(replaced) + assertFalse(crossed) + } + @Test fun `metadata backup preserves complete data when identity records cannot be read`() = test { stubMetadataBackupReads() @@ -3066,6 +3128,7 @@ class BackupRepoTest : BaseUnitTest() { ioDispatcher = ioDispatcher, cacheStore = cacheStore, vssBackupClient = vssBackupClient, + vssClients = vssClients, vssBackupClientLdk = vssBackupClientLdk, settingsStore = settingsStore, widgetsStore = widgetsStore, @@ -3094,7 +3157,7 @@ class BackupRepoTest : BaseUnitTest() { lightningService = lightningService, clock = clock, db = db, - connectionRecovery = connectionRecoveryFixture(settingsStore, keychain), + connectionRecovery = connectionRecoveryFixture(settingsStore, keychain, vssClients), ) private class BackupRepoTestError(message: String) : AppError(message) diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 18c097ea37..c4aab73634 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -68,6 +68,7 @@ import to.bitkit.data.CacheStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.data.backup.VssBackupClientLdk +import to.bitkit.data.backup.VssClientCoordinator import to.bitkit.data.keychain.Keychain import to.bitkit.data.keychain.WalletBackupRestorePendingError import to.bitkit.ext.createChannelDetails @@ -132,6 +133,7 @@ class LightningRepoTest : BaseUnitTest() { private val lnurlService = mock() private val connectivityRepo = mock() private val vssBackupClientLdk = mock() + private val vssClients = VssClientCoordinator() private val electrumProbeService = mock() private val urlValidator = UrlValidator { Result.success(Unit) } private val probePaymentA = "probe-payment-a" @@ -161,7 +163,7 @@ class LightningRepoTest : BaseUnitTest() { preActivityMetadataRepo = preActivityMetadataRepo, onchainSendAttemptStore = onchainSendAttemptStore, connectivityRepo = connectivityRepo, - vssBackupClientLdk = vssBackupClientLdk, + vssBackupClientLdk = vssBackupClientLdk, vssClients = vssClients, urlValidator = urlValidator, electrumProbeService = electrumProbeService, ) @@ -1034,23 +1036,61 @@ class LightningRepoTest : BaseUnitTest() { assertEquals(NodeLifecycleState.Stopped, sut.lightningState.value.nodeLifecycleState) } + @Test + fun `detached restart drains its old stop without starting replacement wallet`() = test { + startNodeForTesting() + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever(lightningService.stop()).doSuspendableAnswer { + entered.complete(Unit) + release.await() + } + val restart = launch { sut.restartNodeDetached() } + entered.await() + var replaced = false + val recovery = connectionRecoveryFixture(settingsStore, vssClients = vssClients) + val transition = launch { recovery.withIdentityChange { replaced = true } } + runCurrent() + assertFalse(replaced) + release.complete(Unit) + transition.join() + restart.join() + assertTrue(replaced) + assertTrue(restart.isCancelled) + verify(lightningService, times(1)).start(anyOrNull(), any()) + verify(vssBackupClientLdk, never()).deleteObjects(any(), any()) + } + + @Test + fun `manual graph reset cannot delete after wallet identity replacement`() = test { + val entered = CompletableDeferred() + whenever(lightningService.resetNetworkGraph(any())).doSuspendableAnswer { + entered.complete(Unit) + awaitCancellation() + } + val reset = launch { sut.resetNetworkGraph() } + entered.await() + val recovery = connectionRecoveryFixture(settingsStore, vssClients = vssClients) + recovery.withIdentityChange {} + reset.join() + assertTrue(reset.isCancelled) + verify(vssBackupClientLdk, never()).deleteObjects(any(), any()) + } + @Test fun `resetNetworkGraph clears local cache and VSS copy`() = test { - whenever(vssBackupClientLdk.setup(any())).thenReturn(Result.success(Unit)) - whenever(vssBackupClientLdk.deleteObject(any(), any())).thenReturn(Result.success(true)) + whenever(vssBackupClientLdk.deleteObjects(any(), any())).thenReturn(Result.success(Unit)) val result = sut.resetNetworkGraph() assertTrue(result.isSuccess) verify(lightningService).resetNetworkGraph(0) - verify(vssBackupClientLdk).setup(0) - verify(vssBackupClientLdk).deleteObject(eq("network_graph"), any()) + verify(vssBackupClientLdk).deleteObjects(listOf("network_graph"), 0) } @Test fun `resetNetworkGraph fails when VSS delete fails`() = test { - whenever(vssBackupClientLdk.setup(any())).thenReturn(Result.success(Unit)) - whenever(vssBackupClientLdk.deleteObject(any(), any())) + whenever(vssBackupClientLdk.deleteObjects(any(), any())) .thenReturn(Result.failure(RuntimeException("vss unavailable"))) val result = sut.resetNetworkGraph() @@ -2082,7 +2122,7 @@ class LightningRepoTest : BaseUnitTest() { preActivityMetadataRepo = preActivityMetadataRepo, onchainSendAttemptStore = store, connectivityRepo = connectivityRepo, - vssBackupClientLdk = vssBackupClientLdk, + vssBackupClientLdk = vssBackupClientLdk, vssClients = vssClients, urlValidator = urlValidator, electrumProbeService = electrumProbeService, ) @@ -2508,7 +2548,7 @@ class LightningRepoTest : BaseUnitTest() { keychain = keychain, lnurlService = lnurlService, cacheStore = cacheStore, preActivityMetadataRepo = preActivityMetadataRepo, onchainSendAttemptStore = store, connectivityRepo = connectivityRepo, - vssBackupClientLdk = vssBackupClientLdk, urlValidator = urlValidator, + vssBackupClientLdk = vssBackupClientLdk, vssClients = vssClients, urlValidator = urlValidator, electrumProbeService = electrumProbeService, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) @@ -2578,7 +2618,7 @@ class LightningRepoTest : BaseUnitTest() { keychain = keychain, lnurlService = lnurlService, cacheStore = cacheStore, preActivityMetadataRepo = preActivityMetadataRepo, onchainSendAttemptStore = store, connectivityRepo = connectivityRepo, - vssBackupClientLdk = vssBackupClientLdk, urlValidator = urlValidator, + vssBackupClientLdk = vssBackupClientLdk, vssClients = vssClients, urlValidator = urlValidator, electrumProbeService = electrumProbeService, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) @@ -2659,7 +2699,7 @@ class LightningRepoTest : BaseUnitTest() { keychain = keychain, lnurlService = lnurlService, cacheStore = cacheStore, preActivityMetadataRepo = preActivityMetadataRepo, onchainSendAttemptStore = store, connectivityRepo = connectivityRepo, - vssBackupClientLdk = vssBackupClientLdk, urlValidator = urlValidator, + vssBackupClientLdk = vssBackupClientLdk, vssClients = vssClients, urlValidator = urlValidator, electrumProbeService = electrumProbeService, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) @@ -3137,7 +3177,7 @@ class LightningRepoTest : BaseUnitTest() { preActivityMetadataRepo = preActivityMetadataRepo, onchainSendAttemptStore = onchainSendAttemptStore, connectivityRepo = connectivityRepo, - vssBackupClientLdk = vssBackupClientLdk, + vssBackupClientLdk = vssBackupClientLdk, vssClients = vssClients, urlValidator = failingValidator, electrumProbeService = electrumProbeService, ) diff --git a/app/src/test/java/to/bitkit/test/ConnectionRecoveryFixture.kt b/app/src/test/java/to/bitkit/test/ConnectionRecoveryFixture.kt index 5f8ccf5859..373b2ef185 100644 --- a/app/src/test/java/to/bitkit/test/ConnectionRecoveryFixture.kt +++ b/app/src/test/java/to/bitkit/test/ConnectionRecoveryFixture.kt @@ -7,6 +7,7 @@ import org.mockito.kotlin.whenever import to.bitkit.data.AppDb import to.bitkit.data.SettingsStore import to.bitkit.data.WalletConnectionRecovery +import to.bitkit.data.backup.VssClientCoordinator import to.bitkit.data.backup.VssStoreIdProvider import to.bitkit.data.entities.ConfigEntity import to.bitkit.data.keychain.Keychain @@ -14,6 +15,7 @@ import to.bitkit.data.keychain.Keychain fun connectionRecoveryFixture( settings: SettingsStore, keychain: Keychain = mock(), + vssClients: VssClientCoordinator = VssClientCoordinator(), currentBinding: () -> String = { "test-wallet-binding" }, ): WalletConnectionRecovery { val db = mock() @@ -21,5 +23,5 @@ fun connectionRecoveryFixture( whenever(db.configDao().getAll()).thenReturn(MutableStateFlow(listOf(ConfigEntity()))) val binding = mock() whenever(binding.getBackupWalletBinding(any())).thenAnswer { currentBinding() } - return WalletConnectionRecovery(keychain, db, binding, settings) + return WalletConnectionRecovery(keychain, db, binding, settings, vssClients) } diff --git a/changelog.d/next/1686.fixed.md b/changelog.d/next/1686.fixed.md index 7a9d63b22e..280e800320 100644 --- a/changelog.d/next/1686.fixed.md +++ b/changelog.d/next/1686.fixed.md @@ -1 +1 @@ -Wallet restore finishes without optional profile refresh waits, missing profiles retry after reconnecting without interrupting active setup, incomplete identity backups remain blocked, and allowances resume safely after re-enabling without reviving cancelled work. +Wallet restore finishes without optional profile refresh waits, missing profiles retry after reconnecting without interrupting active setup, incomplete identity backups remain blocked, and allowances resume safely after re-enabling without reviving cancelled work, while backup uploads, retries and routing resets stay with their original wallet during identity changes. From b93444c35968be6d827a00a20132f6a14a947ffd Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 09:19:12 -0500 Subject: [PATCH 39/61] fix: keep queued backups marked as running --- .../java/to/bitkit/repositories/BackupRepo.kt | 40 ++++++--- .../to/bitkit/repositories/BackupRepoTest.kt | 84 ++++++++++++++++++- changelog.d/next/1686.fixed.md | 2 +- journeys/README.md | 1 + journeys/backup/scheduled-backup-status.xml | 16 ++++ 5 files changed, 128 insertions(+), 15 deletions(-) create mode 100644 journeys/backup/scheduled-backup-status.xml diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index ee050e3dca..cc93471e30 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -268,14 +268,12 @@ class BackupRepo @Inject constructor( launchForWallet { BackupCategory.entries.forEach { category -> - if (category !in runningBackups) { - cacheStore.updateBackupStatus(category) { status -> - if (status.running) { - Logger.debug("Clearing stale running flag for: '$category'", context = TAG) - status.copy(running = false) - } else { - status - } + cacheStore.updateBackupStatus(category) { status -> + if (status.running && category !in runningBackups && !pendingBackups.containsKey(category)) { + Logger.debug("Clearing stale running flag for: '$category'", context = TAG) + status.copy(running = false) + } else { + status } } } @@ -534,11 +532,27 @@ class BackupRepo @Inject constructor( scope.launch(start = CoroutineStart.LAZY) { try { vssClients.withWallet(owner) { - delay(BACKUP_DEBOUNCE) - if (category == BackupCategory.WALLET) paykitSdkService.isPaymentSubmissionActive.first { !it } - pendingBackups.remove(category, owner) - val status = cacheStore.backupStatuses.first()[category] ?: BackupItemStatus() - if (status.shouldBackup(category)) triggerBackup(category) + try { + cacheStore.updateBackupStatus(category) { it.copy(running = true) } + delay(BACKUP_DEBOUNCE) + if (category == BackupCategory.WALLET) { + paykitSdkService.isPaymentSubmissionActive.first { !it } + } + pendingBackups.remove(category, owner) + val status = cacheStore.backupStatuses.first()[category] ?: BackupItemStatus() + if (status.copy(running = category in runningBackups).shouldBackup(category)) { + triggerBackup(category) + } + } finally { + withContext(NonCancellable) { + pendingBackups.remove(category, owner) + cacheStore.updateBackupStatus(category) { + it.copy( + running = category in runningBackups || pendingBackups.containsKey(category) + ) + } + } + } } } finally { pendingBackups.remove(category, owner) diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 1570a36cce..8b41369ed4 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -246,9 +246,13 @@ class BackupRepoTest : BaseUnitTest() { sut.startObservingBackups() runCurrent() verify(vssBackupClient, times(1)).setupWithRetry(any(), any(), any()) + assertTrue(statuses.value.getValue(BackupCategory.SETTINGS).running) val recovery = connectionRecoveryFixture(settingsStore, keychain, vssClients) assertFailsWith { - recovery.withIdentityChange { throw BackupRepoTestError("credentials unchanged") } + recovery.withIdentityChange { + assertFalse(statuses.value.getValue(BackupCategory.SETTINGS).running) + throw BackupRepoTestError("credentials unchanged") + } } runCurrent() verify(vssBackupClient, times(2)).setupWithRetry(any(), any(), any()) @@ -387,6 +391,7 @@ class BackupRepoTest : BaseUnitTest() { runCurrent() assertTrue(statuses.value.getValue(BackupCategory.WALLET).isRequired) + assertTrue(statuses.value.getValue(BackupCategory.WALLET).running) verify(privatePaykitRepo, never()).backupSnapshot() verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) @@ -2031,6 +2036,83 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `scheduled backup stays running until completion or observation stops`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + try { + sut.startObservingBackups() + runCurrent() + assertTrue(statuses.value.getValue(category).running) + advanceTimeBy(4_999) + runCurrent() + assertTrue(statuses.value.getValue(category).running) + verify(vssBackupClient, never()).putObject(eq(category.name), any()) + + sut.stopObservingBackups() + runCurrent() + assertFalse(statuses.value.getValue(category).running) + assertTrue(statuses.value.getValue(category).isRequired) + + sut.startObservingBackups() + runCurrent() + assertTrue(statuses.value.getValue(category).running) + advanceTimeBy(5_000) + runCurrent() + verify(vssBackupClient).putObject(eq(category.name), any()) + assertFalse(statuses.value.getValue(category).running) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + sut.stopObservingBackups() + } + } + + @Test + fun `delayed startup cleanup preserves a newly scheduled backup status`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000))) + val finishSetup = CompletableDeferred() + val finishCleanup = CompletableDeferred() + var cleanupEntered = false + whenever(vssBackupClient.setupWithRetry(any(), any(), any())).doSuspendableAnswer { + finishSetup.await() + Result.success(Unit) + } + whenever(cacheStore.backupStatuses).thenReturn(statuses) + whenever(cacheStore.updateBackupStatus(any(), any())).doSuspendableAnswer { + val updatedCategory = it.getArgument(0) + val transform = it.getArgument<(BackupItemStatus) -> BackupItemStatus>(1) + if (updatedCategory == category && !cleanupEntered) { + cleanupEntered = true + finishCleanup.await() + } + statuses.update { current -> + current + (updatedCategory to transform(current[updatedCategory] ?: BackupItemStatus())) + } + } + stubBackupObservers() + try { + sut.startObservingBackups() + runCurrent() + assertTrue(cleanupEntered) + assertTrue(statuses.value.getValue(category).running) + + finishCleanup.complete(Unit) + runCurrent() + assertTrue(statuses.value.getValue(category).running) + advanceTimeBy(5_000) + runCurrent() + verify(vssBackupClient).putObject(eq(category.name), any()) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + finishCleanup.complete(Unit) + finishSetup.complete(Unit) + sut.stopObservingBackups() + } + } + @Test fun `start observing backs up stale required status after clearing running flag`() = test { val backupStatuses = MutableStateFlow( diff --git a/changelog.d/next/1686.fixed.md b/changelog.d/next/1686.fixed.md index 280e800320..5857ddcd17 100644 --- a/changelog.d/next/1686.fixed.md +++ b/changelog.d/next/1686.fixed.md @@ -1 +1 @@ -Wallet restore finishes without optional profile refresh waits, missing profiles retry after reconnecting without interrupting active setup, incomplete identity backups remain blocked, and allowances resume safely after re-enabling without reviving cancelled work, while backup uploads, retries and routing resets stay with their original wallet during identity changes. +Wallet restore finishes without optional profile refresh waits, missing profiles retry after reconnecting without interrupting active setup, incomplete identity backups remain blocked, and allowances resume safely after re-enabling without reviving cancelled work, while backup uploads, retries and routing resets stay with their original wallet during identity changes, and scheduled backups stay marked as running until they finish or stop. diff --git a/journeys/README.md b/journeys/README.md index 5770c36ac8..cc9f3e3023 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -171,6 +171,7 @@ Known differences in the corpus, as of the iOS port (synonymdev/bitkit-ios#691): | `send/prepared-fee-recovery.md` | Same four manual fault cases and file on both platforms; the recipe records original-send versus replacement fee retention and iOS Max/identity-flow adaptations. These faults are not journey capabilities. | | `settings/electrum-server-error-toasts.xml` | not ported — iOS still shows one generic message for every manual Electrum connect failure | | `onchain-receive/*` | port pending in synonymdev/bitkit-ios#588, which wires `onchainTransactionConfirmed` into the same received-sheet flow but carries no `journeys/` files. Two adaptations when it lands: iOS suppresses replayed historical receives with a `pendingRestoreActivitySeen` flag cleared by the first post-restore on-chain sync, not the one-hour block-timestamp guard used here, so a stale-confirmation step has to drive a restore instead of a clock; and iOS has no foreground-service path, so `confirmed-only-background-notification.xml` has no counterpart | +| `backup/scheduled-backup-status.xml` | Android-only status regression in the VSS ownership scheduler; iOS #1121 changed VSS admission without changing backup scheduling or its running flag. | | `backup/show-mnemonic-long-words.xml` | not ported — the long-word fit is an Android-only change (synonymdev/bitkit-android#633); whether iOS wraps long words at larger text sizes is unchecked | | `security/forgot-pin-nav-bar-inset.xml` | not ported — Android-only fix (synonymdev/bitkit-android#1572): the Android sheet host adds no navigation-bar inset, so each sheet screen pads itself. iOS sheets keep their content inside the bottom safe area | | `deeplinks/pubky-contact.xml` | ported — same contact routing and unlock behavior | diff --git a/journeys/backup/scheduled-backup-status.xml b/journeys/backup/scheduled-backup-status.xml new file mode 100644 index 0000000000..a9eb251f13 --- /dev/null +++ b/journeys/backup/scheduled-backup-status.xml @@ -0,0 +1,16 @@ + + + On an unfunded disposable dev wallet with working staging VSS and Electrum, verify + that a queued backup shows Running during its five-second debounce and becomes + Latest Backup after acknowledgement. Start at Home in English. No profile, + payment, recovery-phrase access or wallet reset is required. Android-only regression: + the iOS VSS ownership change did not alter backup scheduling or its running status. + + + Open Settings, select the General tab, and open Local Currency (testTag "CurrenciesSettings") + Choose a different local currency, then immediately open bitkit://screen/backup-settings + Verify that the Settings row shows Running and does not show Retry while its backup is queued + Wait for the Settings row to show Latest Backup after the VSS acknowledgement + Verify that Settings has no Failed Backup message or Retry button + + From a2c58f2427635719b63263b9441b8d22a7b6c858 Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 10:38:10 -0500 Subject: [PATCH 40/61] fix: clear status for unadmitted backups --- .../java/to/bitkit/repositories/BackupRepo.kt | 22 +++-- .../to/bitkit/repositories/BackupRepoTest.kt | 81 +++++++++++++++++++ 2 files changed, 96 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index cc93471e30..ae971375ff 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -156,7 +156,12 @@ class BackupRepo @Inject constructor( private val backupJobs = ConcurrentHashMap.newKeySet() private val backupJobLock = Any() - private val pendingBackups = ConcurrentHashMap() + private val pendingBackups = ConcurrentHashMap() + private class PendingBackup(val owner: VssClientCoordinator.Owner) { + @Volatile + var admitted = false + } + private val statusObserverJobs = mutableListOf() private val dataListenerJobs = mutableListOf() private var periodicCheckJob: Job? = null @@ -269,7 +274,7 @@ class BackupRepo @Inject constructor( launchForWallet { BackupCategory.entries.forEach { category -> cacheStore.updateBackupStatus(category) { status -> - if (status.running && category !in runningBackups && !pendingBackups.containsKey(category)) { + if (status.running && category !in runningBackups && pendingBackups[category]?.admitted != true) { Logger.debug("Clearing stale running flag for: '$category'", context = TAG) status.copy(running = false) } else { @@ -523,39 +528,42 @@ class BackupRepo @Inject constructor( val owner = expectedOwner ?: runCatching { vssClients.captureOwner() }.getOrNull() ?: return val job = synchronized(backupJobLock) { if (requireObservation && !isObserving) return + val pending = PendingBackup(owner) var reserved = false pendingBackups.compute(category) { _, previous -> - previous?.takeIf { it.generation >= owner.generation } ?: owner.also { reserved = true } + previous?.takeIf { it.owner.generation >= owner.generation } ?: pending.also { reserved = true } } if (!reserved) return Logger.debug("Scheduling backup for: '$category'", context = TAG) scope.launch(start = CoroutineStart.LAZY) { try { vssClients.withWallet(owner) { + pending.admitted = true try { cacheStore.updateBackupStatus(category) { it.copy(running = true) } delay(BACKUP_DEBOUNCE) if (category == BackupCategory.WALLET) { paykitSdkService.isPaymentSubmissionActive.first { !it } } - pendingBackups.remove(category, owner) + pendingBackups.remove(category, pending) val status = cacheStore.backupStatuses.first()[category] ?: BackupItemStatus() if (status.copy(running = category in runningBackups).shouldBackup(category)) { triggerBackup(category) } } finally { withContext(NonCancellable) { - pendingBackups.remove(category, owner) + pendingBackups.remove(category, pending) cacheStore.updateBackupStatus(category) { it.copy( - running = category in runningBackups || pendingBackups.containsKey(category) + running = category in runningBackups || + pendingBackups[category]?.admitted == true ) } } } } } finally { - pendingBackups.remove(category, owner) + pendingBackups.remove(category, pending) } }.also { scheduled -> backupJobs.add(scheduled) diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 8b41369ed4..42d4eeb1b5 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -7,8 +7,11 @@ import com.synonym.paykit.PaykitException import com.synonym.vssclient.VssItem import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Delay import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.InternalCoroutinesApi import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation @@ -20,6 +23,7 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.currentTime import kotlinx.coroutines.test.runCurrent @@ -98,6 +102,7 @@ import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import javax.inject.Provider +import kotlin.coroutines.CoroutineContext import kotlin.coroutines.cancellation.CancellationException import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -265,6 +270,82 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `retired replacement reservation cannot leave a cancelled backup running`() = test { + for (retireBeforeCleanup in listOf(true, false)) { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + val finishCleanup = CompletableDeferred() + var holdCleanup = false + var cleanupEntered = false + var holdDispatch = false + val queued = mutableListOf>() + val delegate = StandardTestDispatcher(testScheduler) + + @OptIn(InternalCoroutinesApi::class) + val dispatcher = object : CoroutineDispatcher(), Delay by (delegate as Delay) { + override fun dispatch(context: CoroutineContext, block: Runnable) { + if (holdDispatch) queued += context to block else delegate.dispatch(context, block) + } + } + sut = createSut(ioDispatcher = dispatcher) + whenever(cacheStore.updateBackupStatus(any(), any())).doSuspendableAnswer { + val target = it.getArgument(0) + val transform = it.getArgument<(BackupItemStatus) -> BackupItemStatus>(1) + if (target == category && holdCleanup && !cleanupEntered) { + cleanupEntered = true + finishCleanup.await() + } + statuses.update { it + (target to transform(it[target] ?: BackupItemStatus())) } + } + try { + sut.startObservingBackups() + runCurrent() + assertTrue(statuses.value.getValue(category).running) + holdCleanup = true + sut.stopObservingBackups() + runCurrent() + assertTrue(cleanupEntered) + + holdDispatch = true + sut.scheduleFullBackup() + holdDispatch = false + assertTrue(queued.isNotEmpty()) + if (retireBeforeCleanup) { + val retiring = launch(start = CoroutineStart.UNDISPATCHED) { + vssClients.withSuspendedClients(shutdown = {}) { + assertFalse(statuses.value.getValue(category).running) + } + } + assertNull(vssClients.owners.value) + finishCleanup.complete(Unit) + runCurrent() + retiring.join() + } else { + finishCleanup.complete(Unit) + runCurrent() + vssClients.withSuspendedClients(shutdown = {}) { + assertFalse(statuses.value.getValue(category).running) + } + } + queued.forEach { (context, block) -> delegate.dispatch(context, block) } + queued.clear() + runCurrent() + + assertFalse(statuses.value.getValue(category).running) + assertTrue(statuses.value.getValue(category).isRequired) + verify(vssBackupClient, never()).putObject(eq(category.name), any()) + } finally { + holdDispatch = false + finishCleanup.complete(Unit) + queued.forEach { (context, block) -> delegate.dispatch(context, block) } + sut.reset() + } + } + } + @Test fun `backup failure status drains before replacement credentials`() = test { val entered = CompletableDeferred() From 8ceaca25550291d6975291e2ca2309bfb5a81356 Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 4 Nov 2026 12:19:59 -0500 Subject: [PATCH 41/61] fix: recheck subscriptions before profile deletion --- .../to/bitkit/services/PaykitSdkService.kt | 12 ++-- .../to/bitkit/repositories/PubkyRepoTest.kt | 17 +++++ .../bitkit/services/PaykitSdkServiceTest.kt | 70 +++++++++++++++++++ changelog.d/next/1690.fixed.md | 2 +- 4 files changed, 96 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt index 98c40d3759..5392ef9a66 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt @@ -654,6 +654,7 @@ class PaykitSdkService @Inject constructor( isSetup.await() operationLock.withLock { withPaykitKey { handle -> + requireNoActiveSubscriptions(handle) val publicKey = requireNotNull(completeSdkCall { handle.identityStatus() }?.publicKey) val current = handle.fetchPaykitProfile(publicKey) completeSdkCall { @@ -772,14 +773,17 @@ class PaykitSdkService @Inject constructor( isSetup.await() operationLock.withLock { withStateRevisionTracking { handle -> - val now = nowMillis() - val requests = completeSdkCall { handle.paymentRequests() } - val subscriptions = requests.filter { it.hasActiveSubscription(now) } - requireNoProfileSubscriptions(subscriptions) + requireNoActiveSubscriptions(handle) } } } + private suspend fun requireNoActiveSubscriptions(handle: PaykitSdk) { + val now = nowMillis() + val subscriptions = completeSdkCall { handle.paymentRequests() }.filter { it.hasActiveSubscription(now) } + requireNoProfileSubscriptions(subscriptions) + } + private fun PaymentRequestRecord.hasActiveSubscription(now: Long): Boolean { val endsAt = subscriptionEndsAtMillis() return state == PaymentRequestLifecycleState.ACTIVE_RECURRING && (endsAt == null || endsAt > now) diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 1ff7dafd1c..c114ebd03c 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -1393,6 +1393,23 @@ class PubkyRepoTest : BaseUnitTest() { verify(pubkyService, never()).signOut() } + @Test + fun `subscription refusal at profile deletion preserves the session without contacts`() = test { + authenticateForTesting() + whenever(pubkyService.contactRecords()).thenReturn(emptyList()) + val expected = PubkyContactError.ActiveProfileSubscriptions(null) + whenever(pubkyService.deletePaykitProfile()) + .thenAnswer { throw IllegalStateException("Service operation failed", expected) } + clearInvocations(pubkyStore, settingsStore) + + assertSame(expected, sut.deleteProfile().exceptionOrNull()) + + verify(pubkyService, never()).removeContactsForProfile(any()) + verify(pubkyService, never()).signOut() + verify(pubkyStore, never()).update(any()) + verify(settingsStore, never()).update(any()) + } + @Test fun `partial contact cleanup preserves retained contacts and stops profile deletion`() = test { authenticateForTesting() diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt index 70bf7e46be..ce8f847205 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt @@ -15,6 +15,7 @@ import com.synonym.paykit.PaykitAppCapabilities import com.synonym.paykit.PaykitAppRegistry import com.synonym.paykit.PaykitException import com.synonym.paykit.PaykitIdentitySecretKey +import com.synonym.paykit.PaykitProfileRecord import com.synonym.paykit.PaykitSdk import com.synonym.paykit.PaykitStateObservation import com.synonym.paykit.PaymentPayload @@ -2538,6 +2539,72 @@ class PaykitSdkServiceTest { } } + @Test + fun `profile deletion rejects a subscription received after preflight`() = runTest { + for (role in listOf(PaymentRequestLocalRole.PAYER, PaymentRequestLocalRole.PAYEE)) { + val sdk = mock() + val request = mock { + on { localRole } doReturn role + on { state } doReturn PaymentRequestLifecycleState.ACTIVE_RECURRING + } + val profile = mock { on { revision } doReturn "original" } + whenever(sdk.identityStatus()) + .thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + whenever(sdk.fetchPaykitProfile(RING_PUBKY)).thenReturn(profile) + val checking = CompletableDeferred() + val finishCheck = CompletableDeferred() + var requests = emptyList() + whenever(sdk.paymentRequests()).doSuspendableAnswer { + if (!checking.isCompleted) { + checking.complete(Unit) + finishCheck.await() + } + requests + } + whenever(sdk.receivePrivateMessagesFromLinkedPeers()).thenAnswer { + requests = listOf(request) + emptyList() + } + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + val preflight = async { service.checkProfileDeletionAllowed() } + checking.await() + val receive = async { service.receivePrivateMessagesFromLinkedPeers(Priority.Background) } + runCurrent() + val deletion = async { runSuspendCatching { service.deletePaykitProfile() } } + runCurrent() + finishCheck.complete(Unit) + preflight.await() + receive.await() + + assertIs(deletion.await().exceptionOrNull()) + verify(sdk, never()).deletePaykitProfile(any()) + verify(sdk, never()).fetchPaykitProfile(any()) + } + } + + @Test + fun `profile deletion permits no active subscription`() = runTest { + for (ended in listOf(false, true)) { + val sdk = mock() + val recurrence = mock { on { endsAt } doReturn "2000-01-01T00:00:00Z" } + val terms = mock { on { this.recurrence } doReturn recurrence } + val request = mock { + on { state } doReturn PaymentRequestLifecycleState.ACTIVE_RECURRING + on { this.terms } doReturn terms + } + whenever(sdk.paymentRequests()).thenReturn(if (ended) listOf(request) else emptyList()) + whenever(sdk.identityStatus()) + .thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + val profile = mock { on { revision } doReturn "original" } + whenever(sdk.fetchPaykitProfile(RING_PUBKY)).thenReturn(profile) + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + + service.deletePaykitProfile() + + verify(sdk).deletePaykitProfile("original") + } + } + @Test fun `profile removal fails closed when subscriptions cannot be read`() = runTest { val sdk = mock() @@ -2546,6 +2613,7 @@ class PaykitSdkServiceTest { val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } assertSame(error, assertFailsWith { service.checkProfileDeletionAllowed() }) + assertSame(error, assertFailsWith { service.deletePaykitProfile() }) assertSame( error, assertFailsWith { @@ -2553,6 +2621,8 @@ class PaykitSdkServiceTest { } ) verify(sdk, never()).removeContactsAndBlockPeers(any()) + verify(sdk, never()).deletePaykitProfile(any()) + verify(sdk, never()).fetchPaykitProfile(any()) } @Test diff --git a/changelog.d/next/1690.fixed.md b/changelog.d/next/1690.fixed.md index 1ff078f5b7..2cae693deb 100644 --- a/changelog.d/next/1690.fixed.md +++ b/changelog.d/next/1690.fixed.md @@ -1 +1 @@ -Preserve profile data when cleanup is incomplete and explain when active subscriptions prevent removal. Show a known expiry instead of asking users to cancel fixed-term subscriptions. +Preserve profile data when cleanup is incomplete or active subscriptions prevent removal, and show a known expiry instead of asking users to cancel fixed-term subscriptions. From be4e1ba8743762dc25e383fbeb90d49d9a2a9581 Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 9 Nov 2026 08:47:09 -0500 Subject: [PATCH 42/61] fix: retry wallet and USDT recovery uploads after VSS setup times out --- .../data/backup/UsdtRecoveryBackupStore.kt | 2 +- .../to/bitkit/data/backup/VssBackupClient.kt | 12 +++++++ .../java/to/bitkit/repositories/BackupRepo.kt | 13 +++---- .../to/bitkit/repositories/BackupRepoTest.kt | 34 ++++++++++++++++--- 4 files changed, 46 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/backup/UsdtRecoveryBackupStore.kt b/app/src/main/java/to/bitkit/data/backup/UsdtRecoveryBackupStore.kt index 335429403a..4364ebe12c 100644 --- a/app/src/main/java/to/bitkit/data/backup/UsdtRecoveryBackupStore.kt +++ b/app/src/main/java/to/bitkit/data/backup/UsdtRecoveryBackupStore.kt @@ -28,7 +28,7 @@ class UsdtRecoveryBackupStore( ) { constructor(client: VssBackupClient) : this( put = { key, data -> - client.setup().getOrThrow() + client.ensureSetupForUpload() client.putObject(key, data).getOrThrow() }, keys = { diff --git a/app/src/main/java/to/bitkit/data/backup/VssBackupClient.kt b/app/src/main/java/to/bitkit/data/backup/VssBackupClient.kt index 728b112e41..aaa1677680 100644 --- a/app/src/main/java/to/bitkit/data/backup/VssBackupClient.kt +++ b/app/src/main/java/to/bitkit/data/backup/VssBackupClient.kt @@ -19,6 +19,7 @@ import to.bitkit.data.keychain.Keychain import to.bitkit.di.IoDispatcher import to.bitkit.env.Env import to.bitkit.ext.runSuspendCatching +import to.bitkit.utils.AppError import to.bitkit.utils.Logger import to.bitkit.utils.ServiceError import javax.inject.Inject @@ -28,6 +29,17 @@ import kotlin.time.Duration.Companion.seconds class MnemonicNotAvailableException : Exception("Mnemonic not available") +internal class BackupClientSetupTimeout(cause: TimeoutCancellationException) : + AppError("Backup client setup timed out", cause) + +internal suspend fun VssBackupClient.ensureSetupForUpload() { + val result = setup() + currentCoroutineContext().ensureActive() + val error = result.exceptionOrNull() + if (error is TimeoutCancellationException) throw BackupClientSetupTimeout(error) + result.getOrThrow() +} + @Singleton class VssBackupClient @Inject constructor( @IoDispatcher private val ioDispatcher: CoroutineDispatcher, diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index addebf9588..f51579f8ca 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -12,7 +12,6 @@ import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin @@ -56,11 +55,13 @@ import to.bitkit.data.SettingsStore import to.bitkit.data.WalletConnectionRecovery import to.bitkit.data.WatchOnlyAccountStore import to.bitkit.data.WidgetsStore +import to.bitkit.data.backup.BackupClientSetupTimeout import to.bitkit.data.backup.UsdtRecoveryBackupStore import to.bitkit.data.backup.VssBackupClient import to.bitkit.data.backup.VssBackupClientLdk import to.bitkit.data.backup.VssClientCoordinator import to.bitkit.data.backup.VssStoreIdProvider +import to.bitkit.data.backup.ensureSetupForUpload import to.bitkit.data.entities.TransferEntity import to.bitkit.data.hwWalletNames import to.bitkit.data.keychain.Keychain @@ -830,11 +831,7 @@ class BackupRepo @Inject constructor( BackupCategory.USDT_RECOVERY -> uploadUsdtRecoveryBackup(usdtSnapshot) else -> runSuspendCatching { val data = getBackupDataBytes(category) - val setup = vssBackupClient.setup() - currentCoroutineContext().ensureActive() - setup.onFailure { - if (it is TimeoutCancellationException) throw BackupClientSetupTimeout(it) - }.getOrThrow() + vssBackupClient.ensureSetupForUpload() vssBackupClient.putObject(key = category.name, data = data).getOrThrow() } } @@ -938,7 +935,7 @@ class BackupRepo @Inject constructor( private suspend fun uploadWalletBackup(): Result = withContext(ioDispatcher) { runSuspendCatching { if (shouldSkipBackup()) throw UsdtException.BackupUnavailable() - vssBackupClient.setup().getOrThrow() + vssBackupClient.ensureSetupForUpload() val data = getWalletBackupDataBytes() if (shouldSkipBackup()) throw UsdtException.BackupUnavailable() vssBackupClient.putObject(key = BackupCategory.WALLET.name, data = data).getOrThrow() @@ -1699,8 +1696,6 @@ class BackupRepo @Inject constructor( internal class WalletBackupSnapshotChanged : AppError("Private payment state changed during wallet snapshot") -private class BackupClientSetupTimeout(cause: Throwable) : AppError("Backup client setup timed out", cause) - private class PublicAddressRestoreFailed(cause: Throwable) : AppError( "Failed to retain public address exclusion during restore", cause, diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 32a1f94fa0..606be3c97f 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -610,30 +610,54 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `wallet upload retries after a client setup timeout`() = test { + assertSetupTimeoutRetries(BackupCategory.WALLET) { sut.triggerBackup(BackupCategory.WALLET) } + verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), any()) + } + + @Test + fun `USDT recovery upload retries the pending snapshot after a client setup timeout`() = test { + whenever { usdtRepo.backupSnapshot() }.thenReturn("pending-snapshot") + assertSetupTimeoutRetries(BackupCategory.USDT_RECOVERY) { sut.persistUsdtRecoveryBackup("pending-snapshot") } + val payload = argumentCaptor() + verify(vssBackupClient).putObject(argThat { startsWith(UsdtRecoveryBackupStore.PREFIX) }, payload.capture()) + val backup = json.decodeFromString(payload.firstValue.decodeToString()) + assertEquals("pending-snapshot", backup.usdtWallet) + } + @Test fun `cold explicit setup timeout keeps its retry without observation`() = test { + assertSetupTimeoutRetries(BackupCategory.SETTINGS) { sut.triggerBackup(BackupCategory.SETTINGS) } + verify(vssBackupClient).putObject(eq(BackupCategory.SETTINGS.name), any()) + } + + private suspend fun TestScope.assertSetupTimeoutRetries( + category: BackupCategory, + upload: suspend () -> Result, + ) { sut = createSut(dispatcher = StandardTestDispatcher(testScheduler)) var setupAttempts = 0 - val statuses = MutableStateFlow(mapOf(BackupCategory.SETTINGS to BackupItemStatus(required = 1_000))) + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000))) stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} whenever { vssBackupClient.setup(any()) }.doSuspendableAnswer { setupAttempts += 1 if (setupAttempts == 1) runCatching { withTimeout(1) { awaitCancellation() } } else Result.success(Unit) } try { - val result = sut.triggerBackup(BackupCategory.SETTINGS) + val result = upload() assertTrue(result.exceptionOrNull()?.isTemporaryBackupFailure() == true, result.toString()) verify(vssBackupClient, never()).putObject(any(), any()) - assertTrue(statuses.value.getValue(BackupCategory.SETTINGS).isRequired) + assertTrue(statuses.value.getValue(category).isRequired) runCurrent() advanceTimeBy(10_000) runCurrent() verify(vssBackupClient, never()).putObject(any(), any()) + verify(vssBackupClient, times(1)).setup(any()) advanceTimeBy(5_000) runCurrent() verify(vssBackupClient, times(2)).setup(any()) - verify(vssBackupClient).putObject(eq(BackupCategory.SETTINGS.name), any()) - assertFalse(statuses.value.getValue(BackupCategory.SETTINGS).isRequired) + assertFalse(statuses.value.getValue(category).isRequired) } finally { sut.reset() } From acdd99c30f1d58022e92bfeb19ce86bd7c515f64 Mon Sep 17 00:00:00 2001 From: benk10 Date: Wed, 11 Nov 2026 12:41:27 -0500 Subject: [PATCH 43/61] fix: resume spark backups after restore --- .../java/to/bitkit/repositories/BackupRepo.kt | 25 ++++-- .../to/bitkit/repositories/BackupRepoTest.kt | 76 +++++++++++++++++++ changelog.d/next/1686.fixed.md | 2 +- 3 files changed, 95 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 79b862a768..f337368e7f 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -374,18 +374,23 @@ class BackupRepo @Inject constructor( // Observe backup status changes for each category BackupCategory.entries.forEach { category -> val job = scope.launch { - cacheStore.backupStatuses + val statuses = cacheStore.backupStatuses .map { statuses -> statuses[category] ?: BackupItemStatus() } .distinctUntilChanged { old, new -> old.synced == new.synced && old.required == new.required && old.running == new.running } - .collect { status -> - if (status.shouldBackup(category)) { - scheduleBackup(category) - } + val resumableStatuses = if (category == BackupCategory.SPARK_EXIT) { + statuses.combine(restoreInProgress) { status, _ -> status } + } else { + statuses + } + resumableStatuses.collect { status -> + if (status.shouldBackup(category)) { + scheduleBackup(category) } + } } statusObserverJobs.add(job) } @@ -518,13 +523,19 @@ class BackupRepo @Inject constructor( // payment and sync traffic does not re-upload the whole metadata envelope. dataListenerJobs.add(observeBackupChanges(activityRepo.activityTagsChanged, BackupCategory.METADATA)) - // Replay unrecorded Spark changes when wallet admission reopens, including after a failed identity change. + // Replay unrecorded Spark changes when wallet admission or the restore gate reopens. dataListenerJobs.add( scope.launch { vssClients.owners.collectLatest { owner -> if (owner == null) return@collectLatest vssClients.withWallet(owner) { - combine(sparkRepo.state, sparkRepo.exitStateGeneration, ::Pair).collect { (state, generation) -> + combine( + sparkRepo.state, + sparkRepo.exitStateGeneration, + restoreInProgress + ) { state, generation, _ -> + state to generation + }.collect { (state, generation) -> val ready = state.isReady && state.hasSynced if (!ready) hasBackedUpSparkConnection = false val connectionNeedsBackup = ready && !hasBackedUpSparkConnection diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 5fd21a38eb..4196f5f12e 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -576,6 +576,82 @@ class BackupRepoTest : BaseUnitTest() { assertSparkBackupSurvivesOwnerRetirement(initiallyReady = false) } + @Test + fun `spark exit backup resumes when the pending restore clears`() = test { + assertSparkBackupResumesAfterRestore(expires = false) + } + + @Test + fun `spark exit backup resumes when the pending restore expires`() = test { + assertSparkBackupResumesAfterRestore(expires = true) + } + + @Test + fun `spark exit backup resumes when another restore interrupts its debounce`() = test { + assertSparkBackupResumesAfterRestore(expires = false, interruptDebounce = true) + } + + private suspend fun TestScope.assertSparkBackupResumesAfterRestore( + expires: Boolean, + interruptDebounce: Boolean = false, + ) { + val category = BackupCategory.SPARK_EXIT + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(synced = 1, required = 1))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + val sparkState = MutableStateFlow(SparkState()) + whenever(sparkRepo.state).thenReturn(sparkState) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "state")) + ) + try { + sut.setRestorePending(true) + sut.startObservingBackups() + runCurrent() + sparkState.update { SparkState(isSupported = true, isReady = true, hasSynced = true) } + exitStateGeneration.update { 1L } + runCurrent() + advanceTimeBy(61_000) + runCurrent() + assertFalse(statuses.value.getValue(category).isRequired) + verify(vssBackupClient, never()).putObject(eq(category.name), any()) + + if (expires) { + whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(RESTORE_GATE_EXPIRED_AT)) + advanceTimeBy(RESTORE_GATE_EXPIRED_AT) + } else { + sut.setRestorePending(false) + } + runCurrent() + if (interruptDebounce) { + assertTrue(statuses.value.getValue(category).isRequired) + sut.setRestorePending(true) + runCurrent() + advanceTimeBy(61_000) + runCurrent() + assertTrue(statuses.value.getValue(category).isRequired) + assertFalse(statuses.value.getValue(category).running) + verify(vssBackupClient, never()).putObject(eq(category.name), any()) + sut.setRestorePending(false) + runCurrent() + } + advanceTimeBy(61_000) + runCurrent() + verify(vssBackupClient).putObject(eq(category.name), any()) + assertFalse(statuses.value.getValue(category).isRequired) + + sut.setRestorePending(true) + runCurrent() + sut.setRestorePending(false) + runCurrent() + advanceTimeBy(61_000) + runCurrent() + verify(vssBackupClient, times(1)).putObject(eq(category.name), any()) + } finally { + sut.stopObservingBackups() + } + } + @Test fun `spark exit generation survives a cancelled required-status write`() = test { assertSparkBackupSurvivesOwnerRetirement(initiallyReady = true) diff --git a/changelog.d/next/1686.fixed.md b/changelog.d/next/1686.fixed.md index 5857ddcd17..c399fcae29 100644 --- a/changelog.d/next/1686.fixed.md +++ b/changelog.d/next/1686.fixed.md @@ -1 +1 @@ -Wallet restore finishes without optional profile refresh waits, missing profiles retry after reconnecting without interrupting active setup, incomplete identity backups remain blocked, and allowances resume safely after re-enabling without reviving cancelled work, while backup uploads, retries and routing resets stay with their original wallet during identity changes, and scheduled backups stay marked as running until they finish or stop. +Wallet restore finishes without optional profile refresh waits, missing profiles retry after reconnecting without interrupting active setup, incomplete identity backups remain blocked, and allowances resume safely after re-enabling without reviving cancelled work, while backup uploads, retries and routing resets stay with their original wallet during identity changes, scheduled backups stay marked as running until they finish or stop, and pending Spark changes back up when restore finishes. From ff9275d6d29a2c8fbb9d235931c6149638b26589 Mon Sep 17 00:00:00 2001 From: benk10 Date: Thu, 12 Nov 2026 01:21:22 -0500 Subject: [PATCH 44/61] fix: keep spark balances and payment results current --- .../java/to/bitkit/models/BalanceState.kt | 3 + .../java/to/bitkit/repositories/WalletRepo.kt | 169 ++++++++--- .../java/to/bitkit/ui/sheets/SendSheet.kt | 12 +- .../usecases/DeriveBalanceStateUseCase.kt | 18 +- .../to/bitkit/viewmodels/WalletViewModel.kt | 2 +- .../bitkit/repositories/LightningRepoTest.kt | 3 +- .../to/bitkit/repositories/WalletRepoTest.kt | 282 +++++++++++++++++- .../java/to/bitkit/ui/WalletViewModelTest.kt | 22 ++ .../ui/sheets/SendSheetNavigationTest.kt | 38 +++ changelog.d/next/1686.fixed.md | 2 +- 10 files changed, 502 insertions(+), 49 deletions(-) diff --git a/app/src/main/java/to/bitkit/models/BalanceState.kt b/app/src/main/java/to/bitkit/models/BalanceState.kt index 7618389b57..8161394b3f 100644 --- a/app/src/main/java/to/bitkit/models/BalanceState.kt +++ b/app/src/main/java/to/bitkit/models/BalanceState.kt @@ -14,6 +14,9 @@ data class BalanceState( val balanceInTransferToSavings: ULong = 0uL, val balanceInTransferToSpending: ULong = 0uL, val hardwareWallets: List = emptyList(), + /** Spark amounts included in the totals; null in caches whose rail split is unknown. */ + val sparkBalanceSats: ULong? = null, + val sparkPendingDepositSats: ULong? = null, ) { val totalSats get() = totalOnchainSats diff --git a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt index 71d527ef98..b0ec9351ae 100644 --- a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt @@ -12,7 +12,10 @@ import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.distinctUntilChanged @@ -30,9 +33,11 @@ import org.lightningdevkit.ldknode.ChannelDetails import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.WordCount import to.bitkit.async.appScope +import to.bitkit.data.AppCacheData import to.bitkit.data.CacheStore import to.bitkit.data.SettingsStore import to.bitkit.data.WalletConnectionRecovery +import to.bitkit.data.backup.VssClientCoordinator import to.bitkit.data.keychain.Keychain import to.bitkit.di.BgDispatcher import to.bitkit.env.Env @@ -47,6 +52,7 @@ import to.bitkit.models.BalanceState import to.bitkit.models.DEFAULT_ADDRESS_TYPE_STRING import to.bitkit.models.ReceiveLiquidityDecision import to.bitkit.models.WalletScope +import to.bitkit.models.safe import to.bitkit.models.toAccountDerivationPath import to.bitkit.models.toBalance import to.bitkit.models.toDerivationPath @@ -82,6 +88,7 @@ class WalletRepo @Inject constructor( private val connectionRecovery: WalletConnectionRecovery, private val sparkRepo: SparkRepo, private val backupRepo: BackupRepo, + private val vssClients: VssClientCoordinator, ) { private val repoScope = appScope(bgDispatcher, TAG) @@ -90,6 +97,8 @@ class WalletRepo @Inject constructor( private val _balanceState = MutableStateFlow(BalanceState()) val balanceState = _balanceState.asStateFlow() + private val balanceMutex = Mutex() + private var hasLiveBalance = false private var eventSyncJob: Job? = null private val receiveStateMutex = Mutex() @@ -136,9 +145,9 @@ class WalletRepo @Inject constructor( } repoScope.launch { // The read balance too, as sends use it: it can come back to the shown one while that stays the same. - sparkRepo.state.map { Triple(it.balanceSats, it.shownBalanceSats, it.pendingDepositSats) } + sparkRepo.state.map { it.isReady to Triple(it.balanceSats, it.shownBalanceSats, it.pendingDepositSats) } .distinctUntilChanged().collect { - if (walletExists()) syncBalances() + if (walletExists()) coroutineScope { launch { syncBalances() } } } } } @@ -203,32 +212,34 @@ class WalletRepo @Inject constructor( } fun loadFromCache() { + val owner = vssClients.captureOwner() changePendingReceiveCacheLoads(1) repoScope.launch { - receiveStateMutex.withLock { - var cacheData = cacheStore.data.first() - cacheData.balance?.let { balance -> _balanceState.update { balance } } - val unavailable = runSuspendCatching { - privatePaykitAddressReservationRepo.isUnavailableForReusableReceive(cacheData.onchainAddress) - }.getOrElse { - receiveCacheValidationFailed = true - Logger.warn("Failed to validate cached receive address", it, context = TAG) - return@withLock - } - if (unavailable) { - cacheData = cacheData.invalidateReceiveOnchainAddress() - cacheStore.update { it.invalidateReceiveOnchainAddress() } - } - committedReceiveBip21 = cacheData.bip21 - _walletState.update { - it.copy( - onchainAddress = cacheData.onchainAddress, - bolt11 = cacheData.bolt11, - bip21 = cacheData.bip21, - ) + vssClients.withWallet(owner) { + receiveStateMutex.withLock { + var cacheData = loadBalanceCache() + val unavailable = runSuspendCatching { + privatePaykitAddressReservationRepo.isUnavailableForReusableReceive(cacheData.onchainAddress) + }.getOrElse { + receiveCacheValidationFailed = true + Logger.warn("Failed to validate cached receive address", it, context = TAG) + return@withLock + } + if (unavailable) { + cacheData = cacheData.invalidateReceiveOnchainAddress() + cacheStore.update { it.invalidateReceiveOnchainAddress() } + } + committedReceiveBip21 = cacheData.bip21 + _walletState.update { + it.copy( + onchainAddress = cacheData.onchainAddress, + bolt11 = cacheData.bolt11, + bip21 = cacheData.bip21, + ) + } + synchronized(receiveUpdateStatusLock) { updateReceivePendingState() } + receiveCacheValidationFailed = false } - synchronized(receiveUpdateStatusLock) { updateReceivePendingState() } - receiveCacheValidationFailed = false } }.invokeOnCompletion { changePendingReceiveCacheLoads(-1) } } @@ -438,23 +449,110 @@ class WalletRepo @Inject constructor( /** Re-derives the Spending limit from the published channels, without the balances call of [syncBalances]. */ fun refreshMaxSendLightning() { - val state = lightningRepo.lightningState.value - if (!state.nodeLifecycleState.isRunning()) return - val maxSendSats = maxOf(state.channels.totalNextOutboundHtlcLimitSats(), sparkRepo.state.value.sendableSats) - _balanceState.update { it.copy(maxSendLightningSats = maxSendSats) } + _balanceState.update { + val state = lightningRepo.lightningState.value + if (!state.nodeLifecycleState.isRunning()) return@update it + it.copy( + maxSendLightningSats = maxOf( + state.channels.totalNextOutboundHtlcLimitSats(), + sparkRepo.state.value.sendableSats, + ), + ) + } } suspend fun syncBalances() { - deriveBalanceStateUseCase().onSuccess { balanceState -> - runCatching { cacheStore.cacheBalance(balanceState) } - _balanceState.update { balanceState } - }.onFailure { - if (it !is CancellationException) { - Logger.warn("Could not sync balances", it, context = TAG) + vssClients.withWallet { + balanceMutex.withLock { + val result = deriveBalanceStateUseCase() + val balance = result.getOrElse { + if (it is CancellationException) throw it + if (it is NodeNotRunningError) { + updateSparkBalance(_balanceState.value)?.let { updated -> return@getOrElse updated } + } + Logger.warn("Could not sync balances", it, context = TAG) + return@withLock + } + val channels = lightningRepo.lightningState.value.channels + val hasAggregate = result.isSuccess || + (balance.sparkBalanceSats != null && balance.sparkPendingDepositSats != null) + if (hasAggregate) cacheBalance(balance) + publishBalance(balance, channels) + hasLiveBalance = hasLiveBalance || hasAggregate + } + } + } + + private fun updateSparkBalance(balance: BalanceState): BalanceState? { + val spark = sparkRepo.state.value + if (!spark.isReady) return null + val included = balance.sparkBalanceSats + val pending = balance.sparkPendingDepositSats + if (included == null || pending == null) { + return balance.copy(maxSendLightningSats = spark.sendableSats) + } + return balance.copy( + totalLightningSats = (balance.totalLightningSats.safe() - included.safe()).safe() + + spark.shownBalanceSats.safe(), + balanceInTransferToSpending = (balance.balanceInTransferToSpending.safe() - pending.safe()).safe() + + spark.pendingDepositSats.safe(), + maxSendLightningSats = spark.sendableSats, + sparkBalanceSats = spark.shownBalanceSats, + sparkPendingDepositSats = spark.pendingDepositSats, + ) + } + + private suspend fun loadBalanceCache(): AppCacheData = balanceMutex.withLock { + val hardware = hwWalletRepo.wallets.value + val channels = lightningRepo.lightningState.value.channels + cacheStore.data.first().also { data -> + val balance = if (hasLiveBalance) _balanceState.value else data.balance + balance?.let { + val updated = if (lightningRepo.lightningState.value.nodeLifecycleState.isRunning()) { + it + } else { + updateSparkBalance(it) ?: it + } + if (updated != it) cacheBalance(updated) + publishBalance( + updated, + if (hasLiveBalance) channels else null, + refreshHardware = hwWalletRepo.wallets.value !== hardware, + ) } } } + private suspend fun cacheBalance(balance: BalanceState) { + runSuspendCatching { cacheStore.cacheBalance(balance) } + } + + private suspend fun publishBalance( + balance: BalanceState, + previousChannels: List?, + refreshHardware: Boolean = true, + ) { + currentCoroutineContext().ensureActive() + _balanceState.update { + val node = lightningRepo.lightningState.value + val spark = sparkRepo.state.value + val maxSend = when { + !node.nodeLifecycleState.isRunning() && spark.isReady -> spark.sendableSats + node.nodeLifecycleState.isRunning() && node.channels != previousChannels -> + maxOf(node.channels.totalNextOutboundHtlcLimitSats(), spark.sendableSats) + else -> balance.maxSendLightningSats + } + balance.copy( + maxSendLightningSats = maxSend, + hardwareWallets = if (refreshHardware) { + hwWalletRepo.wallets.value.map { it.toBalance() } + } else { + balance.hardwareWallets + }, + ) + } + } + /** Coalesces event syncs, then runs [onActivitiesSynced] only after a successful fresh activity sync. */ fun debounceSyncByEvent(onActivitiesSynced: suspend () -> Unit = {}) { eventSyncJob?.cancel() @@ -712,6 +810,7 @@ class WalletRepo @Inject constructor( fun resetState() { _walletState.update { WalletState() } _balanceState.update { BalanceState() } + hasLiveBalance = false } fun getOnchainAddress(): String = _walletState.value.onchainAddress diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index fd2c3a9df8..67b76cbad8 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -134,7 +134,14 @@ internal fun waitsForNode( hasAnyChannels: Boolean, hasUsableChannels: Boolean, sparkCanPay: Boolean, + destination: NavDestination? = null, ): Boolean { + if (destination?.hasRoute() == true || + destination?.hasRoute() == true || + destination?.hasRoute() == true + ) { + return false + } if (sparkCanPay) return false if (!isNodeRunning) return true return hasAnyChannels && !hasUsableChannels @@ -174,6 +181,8 @@ fun SendSheet( preparingRequest: PaykitPaymentRequest? = null, ) { val context = LocalContext.current + val navController = rememberNavController() + val entry by navController.currentBackStackEntryAsState() val connectivityState by appViewModel.isOnline.collectAsStateWithLifecycle() val isOffline by remember { derivedStateOf { connectivityState != ConnectivityState.CONNECTED } } val lightningState by walletViewModel.lightningState.collectAsStateWithLifecycle() @@ -193,6 +202,7 @@ fun SendSheet( hasAnyChannels = hasAnyChannels, hasUsableChannels = lightningState.channels.any { it.isUsable }, sparkCanPay = sparkCanPay, + destination = entry?.destination, ) } @@ -230,8 +240,6 @@ fun SendSheet( .imePadding() .testTag("SendSheet"), ) { - val navController = rememberNavController() - val entry by navController.currentBackStackEntryAsState() val reviewing = entry?.destination?.isPaymentReview() == true LaunchedEffect(reviewing, lifecycle, appViewModel) { if (!reviewing) return@LaunchedEffect diff --git a/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt b/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt index eab2df0941..a6913210e7 100644 --- a/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt @@ -13,6 +13,7 @@ import to.bitkit.di.BgDispatcher import to.bitkit.env.Defaults import to.bitkit.ext.amountSats import to.bitkit.ext.channelId +import to.bitkit.ext.runSuspendCatching import to.bitkit.ext.totalNextOutboundHtlcLimitSats import to.bitkit.models.BalanceState import to.bitkit.models.TransferType @@ -37,7 +38,7 @@ class DeriveBalanceStateUseCase @Inject constructor( private val sparkRepo: SparkRepo, ) { suspend operator fun invoke(): Result = withContext(bgDispatcher) { - runCatching { + runSuspendCatching { val balanceDetails = lightningRepo.getBalancesAsync().getOrThrow() val channels = lightningRepo.getChannels().orEmpty() val activeTransfers = transferRepo.activeTransfers.first() @@ -52,9 +53,10 @@ class DeriveBalanceStateUseCase @Inject constructor( val channelFundableBalance = getMaxChannelFundableAmount(lightningRepo.getChannelFundableBalance()) val afterPendingChannels = balanceDetails.totalLightningBalanceSats.safe() - pendingChannelsSats.safe() val afterClosingChannels = afterPendingChannels.safe() - toSavingsAmount.safe() - val sparkSats = sparkRepo.state.value.shownBalanceSats val afterLingeringCoopClose = afterClosingChannels.safe() - lingeringCoopCloseSats.safe() - val totalLightningSats = afterLingeringCoopClose.safe() + sparkSats.safe() + val maxSendOnchainSats = getMaxSendAmount(balanceDetails) + val spark = sparkRepo.state.value + val totalLightningSats = afterLingeringCoopClose.safe() + spark.shownBalanceSats.safe() val balanceState = BalanceState( totalOnchainSats = totalOnchainSats, @@ -63,13 +65,15 @@ class DeriveBalanceStateUseCase @Inject constructor( // A payment goes over one rail, so the larger of the two balances caps it; Spark keeps its fee. maxSendLightningSats = maxOf( lightningRepo.getChannels().totalNextOutboundHtlcLimitSats(), - sparkRepo.state.value.sendableSats, + spark.sendableSats, ), - maxSendOnchainSats = getMaxSendAmount(balanceDetails), + maxSendOnchainSats = maxSendOnchainSats, balanceInTransferToSavings = toSavingsAmount.safe() - coopCloseSavingsSats.safe(), balanceInTransferToSpending = pendingChannelsSats.safe() + - sparkRepo.state.value.pendingDepositSats.safe(), + spark.pendingDepositSats.safe(), hardwareWallets = hwWalletRepo.wallets.value.map { it.toBalance() }, + sparkBalanceSats = spark.shownBalanceSats, + sparkPendingDepositSats = spark.pendingDepositSats, ) val height = lightningRepo.lightningState.value.block()?.height @@ -77,7 +81,7 @@ class DeriveBalanceStateUseCase @Inject constructor( Logger.verbose("Balances in ldk-node at block height=$height: ${jsonLogOf(balanceDetails)}", context = TAG) Logger.verbose("Balances in state at block height=$height: ${jsonLogOf(balanceState)}", context = TAG) - return@runCatching balanceState + return@runSuspendCatching balanceState } } diff --git a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index 8aac98f10e..5a08f7f254 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -855,7 +855,7 @@ class WalletViewModel @Inject constructor( boltzService.events.collect { event -> if (event is BoltzSwapEvent.Claimed) { Logger.info("Savings swap claimed: ${event.swapId}", context = TAG) - walletRepo.syncBalances() + coroutineScope { launch { walletRepo.syncBalances() } } } } } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 72ccb0b518..84ecc43036 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -317,9 +317,10 @@ class LightningRepoTest : BaseUnitTest() { transferRepo = mock(), activityRepo = mock(), hwWalletRepo = hardware, - connectionRecovery = connectionRecoveryFixture(settingsStore), + connectionRecovery = connectionRecoveryFixture(settingsStore, vssClients = vssClients), sparkRepo = sparkRepo, backupRepo = mock { on { restoreInProgress } doReturn MutableStateFlow(false) }, + vssClients = vssClients, ) } diff --git a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt index 8af155152b..328210e614 100644 --- a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt @@ -27,6 +27,7 @@ import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.UnconfinedTestDispatcher import org.junit.Before import org.junit.Test +import org.lightningdevkit.ldknode.BalanceDetails import org.lightningdevkit.ldknode.ChannelDetails import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.Network @@ -51,7 +52,9 @@ import to.bitkit.data.PrivatePaykitReservationStore import to.bitkit.data.PrivatePaykitStoredAssignmentData import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore +import to.bitkit.data.backup.VssClientCoordinator import to.bitkit.data.keychain.Keychain +import to.bitkit.di.json import to.bitkit.models.BalanceState import to.bitkit.models.NodeLifecycleState import to.bitkit.services.AddressDerivationInfo @@ -94,7 +97,8 @@ class WalletRepoTest : BaseUnitTest() { private val activityRepo = mock() private val hwWalletRepo = mock() private val backupRepo = mock() - private val connectionRecovery = connectionRecoveryFixture(settingsStore) + private val vssClients = VssClientCoordinator() + private val connectionRecovery = connectionRecoveryFixture(settingsStore, vssClients = vssClients) companion object Fixtures { const val ACTIVITY_TAG = "testTag" @@ -180,6 +184,7 @@ class WalletRepoTest : BaseUnitTest() { dispatcher: CoroutineDispatcher = testDispatcher, reservationRepo: PrivatePaykitAddressReservationRepo = privatePaykitAddressReservationRepo, spark: SparkRepo = sparkRepo, + balances: DeriveBalanceStateUseCase = deriveBalanceStateUseCase, ) = WalletRepo( bgDispatcher = dispatcher, keychain = keychain, @@ -188,7 +193,7 @@ class WalletRepoTest : BaseUnitTest() { lightningRepo = lightningRepo, cacheStore = cacheStore, preActivityMetadataRepo = preActivityMetadataRepo, - deriveBalanceStateUseCase = deriveBalanceStateUseCase, + deriveBalanceStateUseCase = balances, wipeWalletUseCase = wipeWalletUseCase, privatePaykitAddressReservationRepo = reservationRepo, transferRepo = transferRepo, @@ -197,6 +202,7 @@ class WalletRepoTest : BaseUnitTest() { connectionRecovery = connectionRecovery, sparkRepo = spark, backupRepo = backupRepo, + vssClients = vssClients, ) private fun lightningInvoice(bolt11: String, isExpired: Boolean = false) = LightningInvoice( @@ -276,6 +282,278 @@ class WalletRepoTest : BaseUnitTest() { verify(deriveBalanceStateUseCase).invoke() } + @Test + fun `Spark balance changes update spending while the node is stopped`() = test { + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) + val nodeState = MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Running)) + whenever(lightningRepo.lightningState).thenReturn(nodeState) + whenever(lightningRepo.getBalancesAsync()).thenReturn( + Result.success( + BalanceDetails( + totalOnchainBalanceSats = 50_000uL, + spendableOnchainBalanceSats = 0uL, + totalAnchorChannelsReserveSats = 0uL, + totalLightningBalanceSats = 20_000uL, + lightningBalances = emptyList(), + pendingBalancesFromChannelClosures = emptyList(), + ), + ), + ) + whenever(lightningRepo.getChannels()).thenReturn(emptyList()) + whenever(lightningRepo.getChannelFundableBalance()).thenReturn(0uL) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(emptyList())) + val sparkState = + MutableStateFlow(SparkState(isReady = true, balanceSats = 99_865uL, pendingDepositSats = 600uL)) + val spark = sparkRepoWith(sparkState) + val balances = DeriveBalanceStateUseCase( + bgDispatcher = testDispatcher, + lightningRepo = lightningRepo, + transferRepo = transferRepo, + settingsStore = settingsStore, + hwWalletRepo = hwWalletRepo, + sparkRepo = spark, + ) + sut = createSut(spark = spark, balances = balances) + testScheduler.runCurrent() + assertEquals(119_865uL, sut.balanceState.value.totalLightningSats) + + nodeState.value = LightningState(nodeLifecycleState = NodeLifecycleState.Stopped) + whenever(lightningRepo.getBalancesAsync()).thenReturn( + Result.failure(NodeNotRunningError("getBalancesAsync", NodeLifecycleState.Stopped)), + ) + for (remaining in listOf(98_659uL, 97_653uL, 0uL)) { + sparkState.update { it.copy(balanceSats = remaining, pendingDepositSats = 100uL) } + testScheduler.runCurrent() + + assertEquals(20_000uL + remaining, sut.balanceState.value.totalLightningSats) + assertEquals(50_000uL, sut.balanceState.value.totalOnchainSats) + assertEquals(100uL, sut.balanceState.value.balanceInTransferToSpending) + assertEquals(SparkFees.sendableSats(remaining), sut.balanceState.value.maxSendLightningSats) + verify(cacheStore).cacheBalance(sut.balanceState.value) + } + sparkState.update { it.copy(keptBalanceSats = 97_653uL) } + testScheduler.runCurrent() + assertEquals(117_653uL, sut.balanceState.value.totalLightningSats) + assertEquals(0uL, sut.balanceState.value.maxSendLightningSats) + } + + @Test + fun `cached Spark contribution updates only after Spark is ready and never guesses a legacy split`() = test { + val known = BalanceState( + totalOnchainSats = 50_000uL, + totalLightningSats = 120_000uL, + balanceInTransferToSpending = 3_000uL, + sparkBalanceSats = 100_000uL, + sparkPendingDepositSats = 1_000uL, + ) + val legacy = json.decodeFromString("""{"totalLightningSats":120000}""") + assertEquals(null, legacy.sparkBalanceSats) + val restored = json.decodeFromString(json.encodeToString(known)) + assertEquals(known, restored) + val state = MutableStateFlow(SparkState()) + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) + whenever(deriveBalanceStateUseCase.invoke()).thenReturn( + Result.failure(NodeNotRunningError("getBalancesAsync", NodeLifecycleState.Stopped)), + ) + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(balance = restored))) + sut = createSut(spark = sparkRepoWith(state)) + sut.loadFromCache() + testScheduler.runCurrent() + assertEquals(known, sut.balanceState.value) + + state.update { it.copy(isReady = true) } + testScheduler.runCurrent() + assertEquals(20_000uL, sut.balanceState.value.totalLightningSats) + assertEquals(2_000uL, sut.balanceState.value.balanceInTransferToSpending) + assertEquals(50_000uL, sut.balanceState.value.totalOnchainSats) + + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(balance = legacy))) + val legacyState = MutableStateFlow(SparkState(isReady = true)) + sut = createSut(spark = sparkRepoWith(legacyState)) + sut.loadFromCache() + testScheduler.runCurrent() + assertEquals(legacy, sut.balanceState.value) + legacyState.update { it.copy(balanceSats = 5_000uL) } + testScheduler.runCurrent() + assertEquals(legacy.copy(maxSendLightningSats = SparkFees.sendableSats(5_000uL)), sut.balanceState.value) + } + + @Test + fun `balance writes and cache hydration cannot overtake a pending update`() = test { + var cached = AppCacheData() + whenever(cacheStore.data).thenReturn(flow { emit(cached) }) + val first = BalanceState(totalLightningSats = 120_000uL) + val latest = BalanceState(totalLightningSats = 20_000uL) + whenever(deriveBalanceStateUseCase.invoke()).thenReturn(Result.success(first), Result.success(latest)) + val held = CompletableDeferred() + val release = CompletableDeferred() + whenever(cacheStore.cacheBalance(any())).doSuspendableAnswer { + val balance = it.getArgument(0) + if (balance == first) { + held.complete(Unit) + release.await() + } + cached = cached.copy(balance = balance) + } + val older = launch { sut.syncBalances() } + held.await() + val newer = launch { sut.syncBalances() } + sut.loadFromCache() + testScheduler.runCurrent() + assertEquals(null, cached.balance) + release.complete(Unit) + older.join() + newer.join() + testScheduler.runCurrent() + + assertEquals(latest, cached.balance) + assertEquals(latest, sut.balanceState.value) + } + + @Test + fun `failed cache write keeps the latest visible balance during hydration`() = test { + val latest = BalanceState(totalLightningSats = 20_000uL) + whenever(deriveBalanceStateUseCase.invoke()).thenReturn(Result.success(latest)) + whenever(cacheStore.cacheBalance(any())).doSuspendableAnswer { throw IOException("cache unavailable") } + whenever(cacheStore.data).thenReturn( + flowOf(AppCacheData(balance = BalanceState(totalLightningSats = 120_000uL))), + ) + + sut.syncBalances() + sut.loadFromCache() + testScheduler.runCurrent() + + assertEquals(latest, sut.balanceState.value) + } + + @Test + fun `wallet retirement drains balance writes and leaves Spark observation available for the next wallet`() = test { + val state = MutableStateFlow(SparkState(isReady = true, balanceSats = 50_000uL)) + val held = CompletableDeferred() + val release = CompletableDeferred() + var cached: BalanceState? = null + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) + whenever(deriveBalanceStateUseCase.invoke()).thenReturn( + Result.success(BalanceState(totalLightningSats = 50_000uL)), + ) + whenever(cacheStore.cacheBalance(any())).doSuspendableAnswer { + held.complete(Unit) + release.await() + cached = it.getArgument(0) + } + sut = createSut(spark = sparkRepoWith(state)) + held.await() + vssClients.withSuspendedClients(shutdown = {}) { + sut.resetState() + cached = null + } + release.complete(Unit) + testScheduler.runCurrent() + assertEquals(BalanceState(), sut.balanceState.value) + assertEquals(null, cached) + + val next = BalanceState( + totalLightningSats = 10_000uL, + maxSendLightningSats = SparkFees.sendableSats(10_000uL), + ) + whenever(deriveBalanceStateUseCase.invoke()).thenReturn(Result.success(next)) + state.update { it.copy(balanceSats = 10_000uL) } + testScheduler.runCurrent() + assertEquals(next, sut.balanceState.value) + assertEquals(next, cached) + } + + @Test + fun `balance publication preserves native limits and later channel refreshes`() = test { + val node = MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Running)) + whenever(lightningRepo.lightningState).thenReturn(node) + var cached = AppCacheData() + whenever(cacheStore.data).thenReturn(flow { emit(cached) }) + whenever(cacheStore.cacheBalance(any())).doSuspendableAnswer { + cached = cached.copy(balance = it.getArgument(0)) + } + val fresh = BalanceState(totalLightningSats = 20_000uL, maxSendLightningSats = 5_000uL) + val published = mock { + on { isChannelReady } doReturn true + on { isUsable } doReturn true + on { nextOutboundHtlcLimitMsat } doReturn 2_000_000uL + } + whenever(deriveBalanceStateUseCase.invoke()).doSuspendableAnswer { + node.update { it.copy(channels = listOf(published).toImmutableList()) } + Result.success(fresh) + } + sut.syncBalances() + assertEquals(5_000uL, sut.balanceState.value.maxSendLightningSats) + sut.loadFromCache() + testScheduler.runCurrent() + assertEquals(5_000uL, sut.balanceState.value.maxSendLightningSats) + + val held = CompletableDeferred() + val release = CompletableDeferred() + whenever(cacheStore.cacheBalance(any())).doSuspendableAnswer { + held.complete(Unit) + release.await() + } + val sync = launch { sut.syncBalances() } + held.await() + val recovered = mock { + on { isChannelReady } doReturn true + on { isUsable } doReturn true + on { nextOutboundHtlcLimitMsat } doReturn 7_000_000uL + } + node.update { it.copy(channels = listOf(recovered).toImmutableList()) } + sut.refreshMaxSendLightning() + assertEquals(7_000uL, sut.balanceState.value.maxSendLightningSats) + release.complete(Unit) + sync.join() + assertEquals(7_000uL, sut.balanceState.value.maxSendLightningSats) + assertEquals(20_000uL, sut.balanceState.value.totalLightningSats) + sut.loadFromCache() + testScheduler.runCurrent() + assertEquals(7_000uL, sut.balanceState.value.maxSendLightningSats) + } + + @Test + fun `Spark readiness before cache hydration preserves stored wallet totals`() = test { + var cached = AppCacheData( + balance = BalanceState( + totalOnchainSats = 50_000uL, + totalLightningSats = 120_000uL, + sparkBalanceSats = 100_000uL, + sparkPendingDepositSats = 0uL, + ), + ) + val original = cached + whenever(cacheStore.data).thenReturn(flow { emit(cached) }) + whenever(cacheStore.cacheBalance(any())).doSuspendableAnswer { + cached = cached.copy(balance = it.getArgument(0)) + } + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) + whenever(deriveBalanceStateUseCase.invoke()).thenReturn( + Result.failure(NodeNotRunningError("getBalancesAsync", NodeLifecycleState.Stopped)), + ) + val state = MutableStateFlow(SparkState(isReady = true, balanceSats = 5_000uL)) + sut = createSut(spark = sparkRepoWith(state)) + testScheduler.runCurrent() + assertEquals(original, cached) + assertEquals(SparkFees.sendableSats(5_000uL), sut.balanceState.value.maxSendLightningSats) + + sut.loadFromCache() + testScheduler.runCurrent() + assertEquals(25_000uL, sut.balanceState.value.totalLightningSats) + assertEquals(50_000uL, sut.balanceState.value.totalOnchainSats) + assertEquals(sut.balanceState.value, cached.balance) + } + + @Test + fun `balance refresh can run inside a recovery startup session`() = test { + val owner = connectionRecovery.captureOwner() + connectionRecovery.withOperation(owner) { + connectionRecovery.withStartup(owner) { sut.syncBalances() } + } + verify(cacheStore).cacheBalance(BalanceState()) + } + private fun sparkRepoWith(state: MutableStateFlow): SparkRepo = mock { on { this.state } doReturn state on { nodeEvents } doReturn MutableSharedFlow() diff --git a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt index 54e34fe9cb..976068872a 100644 --- a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt @@ -2,6 +2,7 @@ package to.bitkit.ui import android.content.Context import app.cash.turbine.test +import com.synonym.bitkitcore.BoltzSwapEvent import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.NonCancellable @@ -143,6 +144,27 @@ class WalletViewModelTest : BaseUnitTest() { verify(boltzService).startUpdates(anyOrNull(), any(), anyOrNull()) } + @Test + fun `swap balance observation survives a retired wallet refresh`() = test { + val events = MutableSharedFlow() + whenever(boltzService.events).thenReturn(events) + whenever(boltzService.isSwapSupported).thenReturn(true) + whenever(boltzService.isSwapEnabled()).thenReturn(true) + var refreshes = 0 + whenever(walletRepo.syncBalances()).doSuspendableAnswer { + if (++refreshes == 1) throw CancellationException("Wallet retired") + } + sut.ensureSwapUpdatesRunning() + runCurrent() + + events.emit(BoltzSwapEvent.Claimed(swapId = "first", txid = "first-transaction")) + runCurrent() + events.emit(BoltzSwapEvent.Claimed(swapId = "second", txid = "second-transaction")) + runCurrent() + + assertEquals(2, refreshes) + } + @Test fun `ensureSwapUpdatesRunning should do nothing when swaps are unsupported`() = test { whenever(boltzService.isSwapSupported).thenReturn(false) diff --git a/app/src/test/java/to/bitkit/ui/sheets/SendSheetNavigationTest.kt b/app/src/test/java/to/bitkit/ui/sheets/SendSheetNavigationTest.kt index eb65547d98..89c4b9630d 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/SendSheetNavigationTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/SendSheetNavigationTest.kt @@ -11,7 +11,9 @@ import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config +import to.bitkit.repositories.SparkState import to.bitkit.ui.navigateTo +import to.bitkit.viewmodels.SendMethod import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue @@ -19,6 +21,42 @@ import kotlin.test.assertTrue @Config(sdk = [34]) @RunWith(RobolectricTestRunner::class) class SendSheetNavigationTest { + @Test + fun `payment results stay visible after a stopped-node Spark payment reduces the balance`() { + val navController = NavHostController(ApplicationProvider.getApplicationContext()).apply { + navigatorProvider.addNavigator(ComposeNavigator()) + graph = createGraph(startDestination = SendRoute.Confirm) { + composable {} + composable {} + composable {} + composable {} + } + } + var spark = SparkState(isSupported = true, isReady = true, balanceSats = 100_000uL) + fun waiting() = waitsForNode( + isNodeRunning = false, + hasAnyChannels = true, + hasUsableChannels = false, + sparkCanPay = sparkCanPayInvoice(SendMethod.LIGHTNING, 60_000uL, spark), + destination = navController.currentDestination, + ) + + assertFalse(waiting()) + spark = spark.copy(balanceSats = 39_758uL) + assertTrue(waiting()) + val results = listOf( + SendRoute.Pending(paymentHash = "payment", amount = 60_000, walletId = "wallet0"), + SendRoute.Success, + SendRoute.Error(), + ) + for (result in results) { + navController.navigateTo(result) + assertFalse(waiting()) + assertTrue(navController.popBackStack()) + assertTrue(waiting()) + } + } + @Test fun `recovery pin holds review only until returning to pending`() { val pending = SendRoute.Pending(paymentHash = "payment", amount = 1000, walletId = "wallet0") diff --git a/changelog.d/next/1686.fixed.md b/changelog.d/next/1686.fixed.md index c399fcae29..39dfb3bdc8 100644 --- a/changelog.d/next/1686.fixed.md +++ b/changelog.d/next/1686.fixed.md @@ -1 +1 @@ -Wallet restore finishes without optional profile refresh waits, missing profiles retry after reconnecting without interrupting active setup, incomplete identity backups remain blocked, and allowances resume safely after re-enabling without reviving cancelled work, while backup uploads, retries and routing resets stay with their original wallet during identity changes, scheduled backups stay marked as running until they finish or stop, and pending Spark changes back up when restore finishes. +Wallet restore finishes without optional profile refresh waits, missing profiles retry after reconnecting without interrupting active setup, incomplete identity backups remain blocked, and allowances resume safely after re-enabling without reviving cancelled work, while backup uploads, retries and routing resets stay with their original wallet during identity changes, scheduled backups stay marked as running until they finish or stop, and pending Spark changes back up when restore finishes, and Spending reflects Spark balance changes and payment results remain visible while the Lightning node is stopped. From 89f3bc6bff5c5d68d14559a860b408b006c315ce Mon Sep 17 00:00:00 2001 From: benk10 Date: Thu, 12 Nov 2026 02:35:03 -0500 Subject: [PATCH 45/61] fix: load cached wallet data during node startup --- .../java/to/bitkit/repositories/WalletRepo.kt | 29 +++++++----- .../to/bitkit/repositories/WalletRepoTest.kt | 47 +++++++++++++++++++ changelog.d/next/1686.fixed.md | 2 +- 3 files changed, 64 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt index b0ec9351ae..ce8475f5a9 100644 --- a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt @@ -97,6 +97,7 @@ class WalletRepo @Inject constructor( private val _balanceState = MutableStateFlow(BalanceState()) val balanceState = _balanceState.asStateFlow() + private val balanceSyncMutex = Mutex() private val balanceMutex = Mutex() private var hasLiveBalance = false @@ -463,22 +464,24 @@ class WalletRepo @Inject constructor( suspend fun syncBalances() { vssClients.withWallet { - balanceMutex.withLock { + balanceSyncMutex.withLock { val result = deriveBalanceStateUseCase() - val balance = result.getOrElse { - if (it is CancellationException) throw it - if (it is NodeNotRunningError) { - updateSparkBalance(_balanceState.value)?.let { updated -> return@getOrElse updated } + val channels = lightningRepo.lightningState.value.channels + balanceMutex.withLock publish@{ + val balance = result.getOrElse { + if (it is CancellationException) throw it + if (it is NodeNotRunningError) { + updateSparkBalance(_balanceState.value)?.let { updated -> return@getOrElse updated } + } + Logger.warn("Could not sync balances", it, context = TAG) + return@publish } - Logger.warn("Could not sync balances", it, context = TAG) - return@withLock + val hasAggregate = result.isSuccess || + (balance.sparkBalanceSats != null && balance.sparkPendingDepositSats != null) + if (hasAggregate) cacheBalance(balance) + publishBalance(balance, channels) + hasLiveBalance = hasLiveBalance || hasAggregate } - val channels = lightningRepo.lightningState.value.channels - val hasAggregate = result.isSuccess || - (balance.sparkBalanceSats != null && balance.sparkPendingDepositSats != null) - if (hasAggregate) cacheBalance(balance) - publishBalance(balance, channels) - hasLiveBalance = hasLiveBalance || hasAggregate } } } diff --git a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt index 328210e614..01f3a0ec79 100644 --- a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt @@ -378,6 +378,53 @@ class WalletRepoTest : BaseUnitTest() { assertEquals(legacy.copy(maxSendLightningSats = SparkFees.sendableSats(5_000uL)), sut.balanceState.value) } + @Test + fun `cached wallet data loads during serialized balance reads`() = test { + val node = MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Starting)) + whenever(lightningRepo.lightningState).thenReturn(node) + val cached = AppCacheData( + balance = BalanceState(totalOnchainSats = 50_000uL), + onchainAddress = ADDRESS, + bolt11 = INVOICE, + bip21 = "bitcoin:$ADDRESS?lightning=$INVOICE", + ) + whenever(cacheStore.data).thenReturn(flowOf(cached)) + val reading = CompletableDeferred() + val release = CompletableDeferred() + val fresh = BalanceState(totalOnchainSats = 60_000uL) + val latest = BalanceState(totalOnchainSats = 70_000uL) + var reads = 0 + whenever(deriveBalanceStateUseCase.invoke()).doSuspendableAnswer { + if (reads++ == 0) { + reading.complete(Unit) + release.await() + Result.success(fresh) + } else { + Result.success(latest) + } + } + + val sync = launch { sut.syncBalances() } + reading.await() + sut.loadFromCache() + testScheduler.runCurrent() + try { + assertEquals(cached.balance, sut.balanceState.value) + assertEquals(cached.onchainAddress, sut.walletState.value.onchainAddress) + assertEquals(cached.bolt11, sut.walletState.value.bolt11) + assertEquals(cached.bip21, sut.walletState.value.bip21) + assertFalse(sut.walletState.value.isReceiveInvoiceUpdating) + launch { sut.syncBalances() } + testScheduler.runCurrent() + } finally { + release.complete(Unit) + sync.join() + } + testScheduler.runCurrent() + assertEquals(latest, sut.balanceState.value) + verify(cacheStore).cacheBalance(latest) + } + @Test fun `balance writes and cache hydration cannot overtake a pending update`() = test { var cached = AppCacheData() diff --git a/changelog.d/next/1686.fixed.md b/changelog.d/next/1686.fixed.md index 39dfb3bdc8..0bf584b967 100644 --- a/changelog.d/next/1686.fixed.md +++ b/changelog.d/next/1686.fixed.md @@ -1 +1 @@ -Wallet restore finishes without optional profile refresh waits, missing profiles retry after reconnecting without interrupting active setup, incomplete identity backups remain blocked, and allowances resume safely after re-enabling without reviving cancelled work, while backup uploads, retries and routing resets stay with their original wallet during identity changes, scheduled backups stay marked as running until they finish or stop, and pending Spark changes back up when restore finishes, and Spending reflects Spark balance changes and payment results remain visible while the Lightning node is stopped. +Wallet restore finishes without optional profile refresh waits, missing profiles retry after reconnecting without interrupting active setup, incomplete identity backups remain blocked, and allowances resume safely after re-enabling without reviving cancelled work, while backup uploads, retries and routing resets stay with their original wallet during identity changes, scheduled backups stay marked as running until they finish or stop, and pending Spark changes back up when restore finishes, cached balances remain visible during node startup, and Spending reflects Spark balance changes and payment results remain visible while the Lightning node is stopped. From 9330e2462c42a375018af97f93ac6ae053e88793 Mon Sep 17 00:00:00 2001 From: benk10 Date: Fri, 13 Nov 2026 08:23:59 -0500 Subject: [PATCH 46/61] fix: retry consumed backup marks after storage failures --- .../java/to/bitkit/repositories/BackupRepo.kt | 74 +++++++- .../to/bitkit/repositories/BackupRepoTest.kt | 163 ++++++++++++++++++ 2 files changed, 229 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index ba835fee4e..d3620f1c30 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -201,12 +201,23 @@ class BackupRepo @Inject constructor( private val runningBackups = ConcurrentHashMap.newKeySet() // Tracks active jobs since app start private val failedBackupRequired = ConcurrentHashMap() + private val pendingRequiredMarks = mutableMapOf() + private var requiredMarkVersion = 0L private val temporaryFailureRetries = ConcurrentHashMap() private val temporaryFailureSince = ConcurrentHashMap() private var lastNotificationTime = 0L private class BackupOwner(val generation: Long, val native: VssClientCoordinator.Owner) + private data class RequiredBackupKey( + val generation: Long, + val nativeGeneration: Long, + val category: BackupCategory, + ) { + fun belongsTo(owner: BackupOwner) = + generation == owner.generation && nativeGeneration == owner.native.generation + } + private class PendingBackup(val owner: BackupOwner, val job: Job) { var admitted = false } @@ -263,7 +274,15 @@ class BackupRepo @Inject constructor( try { pending?.cancel() pending?.join() - synchronized(lifecycleLock) { generation += 1 } + synchronized(lifecycleLock) { + if (pendingRequiredMarks.keys.any { + it.generation == generation && it.nativeGeneration == nativeGeneration + } + ) { + throw BackupStatusWritePending() + } + generation += 1 + } synchronized(lifecycleLock) { backupJobs.clear() explicitBackups.clear() @@ -357,6 +376,8 @@ class BackupRepo @Inject constructor( startDataStoreListeners(owner) previous.joinAll() currentCoroutineContext().ensureActive() + flushRequiredMarks(original) + currentCoroutineContext().ensureActive() owner.ready.complete(Unit) startObservation(owner) // Keep every listener and its non-cancellable tail inside the native drain. @@ -597,6 +618,7 @@ class BackupRepo @Inject constructor( } runSuspendCatching { updateBackupRequired(BackupCategory.SPARK_EXIT, owner.generation) } .onSuccess { + if (!it) return@onSuccess hasBackedUpSparkConnection = ready markedSparkExitGeneration = maxOf(markedSparkExitGeneration, generation) } @@ -633,13 +655,43 @@ class BackupRepo @Inject constructor( owner.scope.launch { while (currentCoroutineContext().isActive) { delay(BACKUP_CHECK_INTERVAL) + flushRequiredMarks(owner.generation) checkForFailedBackups(owner) } } } - private suspend fun markBackupRequired(owner: Observation, category: BackupCategory) = - markBackupRequired(category, owner.generation) + private suspend fun markBackupRequired(owner: Observation, category: BackupCategory) { + val original = owner.generation + val key = RequiredBackupKey(original.generation, original.native.generation, category) + val version = synchronized(lifecycleLock) { + if (!ownsState(original)) return + requiredMarkVersion += 1 + requiredMarkVersion.also { pendingRequiredMarks[key] = it } + } + writeRequiredMark(key, version, original) + } + + private suspend fun flushRequiredMarks(owner: BackupOwner) { + val pending = synchronized(lifecycleLock) { + pendingRequiredMarks.filterKeys { it.belongsTo(owner) } + } + pending.forEach { (key, version) -> + currentCoroutineContext().ensureActive() + writeRequiredMark(key, version, owner) + } + } + + private suspend fun writeRequiredMark(key: RequiredBackupKey, version: Long, owner: BackupOwner) = + withContext(NonCancellable) { + runSuspendCatching { + if (updateBackupRequired(key.category, owner)) { + synchronized(lifecycleLock) { + if (pendingRequiredMarks[key] == version) pendingRequiredMarks.remove(key) + } + } + }.onFailure { Logger.error("Failed to retain backup required for '${key.category}'", it, context = TAG) } + } private suspend fun markBackupRequired(category: BackupCategory, expectedGeneration: BackupOwner) = withContext(NonCancellable) { @@ -647,27 +699,31 @@ class BackupRepo @Inject constructor( updateBackupRequired(category, expectedGeneration) } - private suspend fun updateBackupRequired(category: BackupCategory, expectedGeneration: BackupOwner) { - updateBackupStatus(category, expectedGeneration) { + private suspend fun updateBackupRequired(category: BackupCategory, expectedGeneration: BackupOwner): Boolean { + val updated = updateBackupStatus(category, expectedGeneration) { failedBackupRequired -= category it.copy(required = maxOf(currentTimeMillis(), it.required + 1, it.synced + 1)) } - Logger.verbose("Marked backup required for: '$category'", context = TAG) + if (updated) Logger.verbose("Marked backup required for: '$category'", context = TAG) + return updated } private suspend fun updateBackupStatus( category: BackupCategory, expectedGeneration: BackupOwner, transform: (BackupItemStatus) -> BackupItemStatus, - ) { + ): Boolean { + var updated = false cacheStore.update { data -> synchronized(lifecycleLock) { // Reset drains admitted writers before advancing the generation or clearing clients. - if (!ownsState(expectedGeneration)) return@update data + updated = ownsState(expectedGeneration) + if (!updated) return@update data val status = data.backupStatuses[category] ?: BackupItemStatus() data.copy(backupStatuses = data.backupStatuses + (category to transform(status))) } } + return updated } private fun scheduleBackup( @@ -1932,6 +1988,8 @@ internal class WalletBackupSnapshotChanged : AppError("Private payment state cha internal class SparkExitBackupDeferred : AppError("Spark has not connected and synced yet") +internal class BackupStatusWritePending : AppError("Backup changes could not be recorded") + private class PublicAddressRestoreFailed(cause: Throwable) : AppError( "Failed to retain public address exclusion during restore", cause, diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index c1fba60d78..e32d36a257 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -138,6 +138,7 @@ import kotlin.test.assertIs import kotlin.test.assertNotEquals import kotlin.test.assertNotNull import kotlin.test.assertNull +import kotlin.test.assertSame import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Duration.Companion.minutes @@ -349,6 +350,168 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `failed required mark retries without another change and keeps observing`() = test { + assertFailedRequiredMarkRecovers(restart = false) + } + + @Test + fun `failed required mark survives observation restart without another change`() = test { + assertFailedRequiredMarkRecovers(restart = true) + } + + private suspend fun TestScope.assertFailedRequiredMarkRecovers(restart: Boolean) { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000, synced = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + sut.startObservingBackups() + runCurrent() + var failedWrites = 0 + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + val current = AppCacheData(backupStatuses = statuses.value) + val updated = transform(current) + if (failedWrites == 0 && updated.backupStatuses.getValue(category).required > + current.backupStatuses.getValue(category).required + ) { + failedWrites++ + throw IOException("required mark could not be stored") + } + statuses.update { updated.backupStatuses } + } + try { + settingsData.update { it.copy(selectedCurrency = "EUR") } + runCurrent() + assertEquals(1, failedWrites) + assertFalse(statuses.value.getValue(category).isRequired) + if (restart) { + sut.stopObservingBackups() + runCurrent() + sut.startObservingBackups() + } + advanceTimeBy(65_000) + runCurrent() + val payload = argumentCaptor() + verify(vssBackupClient, times(1)).putObject(eq(category.name), payload.capture()) + assertTrue(payload.lastValue.decodeToString().contains("EUR")) + assertFalse(statuses.value.getValue(category).isRequired) + + settingsData.update { it.copy(selectedCurrency = "GBP") } + advanceTimeBy(5_000) + runCurrent() + verify(vssBackupClient, times(2)).putObject(eq(category.name), payload.capture()) + assertTrue(payload.lastValue.decodeToString().contains("GBP")) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + sut.reset() + } + } + + @Test + fun `failed required mark refuses reset until storage recovers`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000, synced = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + sut.startObservingBackups() + runCurrent() + val original = vssClients.owners.value + var failRequiredWrite = true + var failedWrites = 0 + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + val current = AppCacheData(backupStatuses = statuses.value) + val updated = transform(current) + if (failRequiredWrite && updated.backupStatuses.getValue(category).required > + current.backupStatuses.getValue(category).required + ) { + failedWrites++ + throw IOException("required mark could not be stored") + } + statuses.update { updated.backupStatuses } + } + try { + settingsData.update { it.copy(selectedCurrency = "EUR") } + advanceTimeBy(65_000) + runCurrent() + assertEquals(2, failedWrites) + assertFailsWith { sut.reset() } + assertSame(original, vssClients.owners.value) + verify(vssBackupClient, never()).putObject(eq(category.name), any()) + + failRequiredWrite = false + sut.startObservingBackups() + advanceTimeBy(5_000) + runCurrent() + val payload = argumentCaptor() + verify(vssBackupClient).putObject(eq(category.name), payload.capture()) + assertTrue(payload.lastValue.decodeToString().contains("EUR")) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + failRequiredWrite = false + sut.startObservingBackups() + advanceTimeBy(65_000) + runCurrent() + sut.reset() + } + } + + @Test + fun `older required mark completion retains a newer failed write`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000, synced = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + sut.startObservingBackups() + runCurrent() + val oldWriteCommitted = CompletableDeferred() + val releaseOldWrite = CompletableDeferred() + var requiredWrites = 0 + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + val current = AppCacheData(backupStatuses = statuses.value) + val updated = transform(current) + val isRequiredWrite = updated.backupStatuses.getValue(category).required > + current.backupStatuses.getValue(category).required + if (isRequiredWrite) requiredWrites++ + if (isRequiredWrite && requiredWrites == 2) { + throw IOException("newer required mark could not be stored") + } + statuses.update { updated.backupStatuses } + if (isRequiredWrite && requiredWrites == 1) { + oldWriteCommitted.complete(Unit) + releaseOldWrite.await() + } + } + try { + settingsData.update { it.copy(selectedCurrency = "EUR") } + advanceTimeBy(5_000) + runCurrent() + assertTrue(oldWriteCommitted.isCompleted) + val payload = argumentCaptor() + verify(vssBackupClient).putObject(eq(category.name), payload.capture()) + assertFalse(statuses.value.getValue(category).isRequired) + + sut.stopObservingBackups() + sut.startObservingBackups() + runCurrent() + settingsData.update { it.copy(selectedCurrency = "GBP") } + runCurrent() + assertEquals(2, requiredWrites) + assertFalse(statuses.value.getValue(category).isRequired) + releaseOldWrite.complete(Unit) + advanceTimeBy(5_000) + runCurrent() + verify(vssBackupClient, times(2)).putObject(eq(category.name), payload.capture()) + assertTrue(payload.lastValue.decodeToString().contains("GBP")) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + releaseOldWrite.complete(Unit) + sut.reset() + } + } + @Test fun `explicit coalesced request survives observer cancellation before dispatch`() = test { val category = BackupCategory.SETTINGS From 7fac7ab29d3fd57800f36a3b401f048f002112e6 Mon Sep 17 00:00:00 2001 From: benk10 Date: Fri, 13 Nov 2026 14:17:50 -0500 Subject: [PATCH 47/61] fix: retain backup marks before wallet retirement --- .../bitkit/data/WalletConnectionRecovery.kt | 3 + .../java/to/bitkit/repositories/BackupRepo.kt | 11 ++ .../to/bitkit/usecases/WipeWalletUseCase.kt | 9 +- .../data/WalletConnectionRecoveryTest.kt | 25 +++++ .../to/bitkit/repositories/BackupRepoTest.kt | 100 +++++++++++++----- 5 files changed, 117 insertions(+), 31 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/WalletConnectionRecovery.kt b/app/src/main/java/to/bitkit/data/WalletConnectionRecovery.kt index fdecbf8854..c9b61b7630 100644 --- a/app/src/main/java/to/bitkit/data/WalletConnectionRecovery.kt +++ b/app/src/main/java/to/bitkit/data/WalletConnectionRecovery.kt @@ -122,6 +122,7 @@ class WalletConnectionRecovery @Inject constructor( /** Drains original owners before credentials, settings or the SDK wipe barrier can change. */ suspend fun withIdentityChange( isStillNeeded: suspend () -> Boolean = { true }, + beforeClientsSuspend: suspend () -> Unit = {}, block: suspend () -> T, ): T { val capturedGeneration = admittedGeneration() @@ -132,6 +133,8 @@ class WalletConnectionRecovery @Inject constructor( currentCoroutineContext().ensureActive() beginWipe() currentCoroutineContext().ensureActive() + beforeClientsSuspend() + currentCoroutineContext().ensureActive() vssClients.withSuspendedClients { block() } } finally { storeIdProvider.clearCache() diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index d3620f1c30..26eb96e778 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -274,6 +274,17 @@ class BackupRepo @Inject constructor( try { pending?.cancel() pending?.join() + val requiredOwner = synchronized(lifecycleLock) { + pendingRequiredMarks.keys.firstOrNull { + it.generation == generation && it.nativeGeneration == nativeGeneration + } + } + if (requiredOwner != null) { + val native = vssClients.captureOwner() + if (native.generation == requiredOwner.nativeGeneration) { + flushRequiredMarks(BackupOwner(requiredOwner.generation, native)) + } + } synchronized(lifecycleLock) { if (pendingRequiredMarks.keys.any { it.generation == generation && it.nativeGeneration == nativeGeneration diff --git a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt index 684585d997..1a6edc8fed 100644 --- a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt @@ -65,9 +65,9 @@ class WipeWalletUseCase @Inject constructor( lightningRepo.setWiping(true) val result = try { runSuspendCatching { - connectionRecovery.withIdentityChange { + connectionRecovery.withIdentityChange(beforeClientsSuspend = { backupRepo.reset() }) { paykitSdkService.withWalletWipe { - stopNode().getOrThrow() + lightningRepo.stop().getOrThrow() cleanupRemote() wipeLocal(walletIndex, resetWalletState).getOrThrow() onSuccess() @@ -87,11 +87,6 @@ class WipeWalletUseCase @Inject constructor( } } - private suspend fun stopNode(): Result { - backupRepo.reset() - return lightningRepo.stop() - } - private suspend fun cleanupRemote() { step("remove Paykit published endpoints") { privatePaykitRepo.get().removePublishedEndpointsForCleanup(TAG) } step("remove Bitkit payment endpoints") { pubkyRepo.removeBitkitPaymentEndpoints() } diff --git a/app/src/test/java/to/bitkit/data/WalletConnectionRecoveryTest.kt b/app/src/test/java/to/bitkit/data/WalletConnectionRecoveryTest.kt index ef5943b176..87d6ec3a8b 100644 --- a/app/src/test/java/to/bitkit/data/WalletConnectionRecoveryTest.kt +++ b/app/src/test/java/to/bitkit/data/WalletConnectionRecoveryTest.kt @@ -452,6 +452,31 @@ class WalletConnectionRecoveryTest : BaseUnitTest() { assertTrue(result.exceptionOrNull() is CancellationException) } + @Test + fun `cancellation during local drain preserves native owner and skips identity change`() = test { + val original = vssClients.owners.value + val draining = CompletableDeferred() + val release = CompletableDeferred() + var replaced = false + val replacement = launch { + sut.withIdentityChange(beforeClientsSuspend = { + withContext(NonCancellable) { + draining.complete(Unit) + release.await() + } + }) { replaced = true } + } + draining.await() + replacement.cancel() + runCurrent() + assertFalse(replacement.isCompleted) + release.complete(Unit) + replacement.join() + assertFalse(replaced) + assertEquals(original, vssClients.owners.value) + vssClients.withWallet { } + } + @Test fun `rejected conditional migration preserves the current wallet admission`() = test { val owner = sut.captureOwner() diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index e32d36a257..4e812ee9fe 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -98,6 +98,7 @@ import to.bitkit.models.BackupItemStatus import to.bitkit.models.BlocktankBackupV1 import to.bitkit.models.KnownDevice import to.bitkit.models.MetadataBackupV1 +import to.bitkit.models.NodeLifecycleState import to.bitkit.models.PaykitAllowanceStateBackup import to.bitkit.models.PaykitPaymentStateBackup import to.bitkit.models.PaykitUsdtStateBackup @@ -120,6 +121,7 @@ import to.bitkit.services.PaykitSdkService import to.bitkit.services.UsdtService import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture +import to.bitkit.usecases.WipeWalletUseCase import to.bitkit.utils.AppError import java.io.File import java.io.IOException @@ -409,7 +411,16 @@ class BackupRepoTest : BaseUnitTest() { } @Test - fun `failed required mark refuses reset until storage recovers`() = test { + fun `aborted wipe retains the failed mark for the running wallet`() = test { + assertFailedMarkSurvivesWipe(nodeRunning = true) + } + + @Test + fun `stopped wallet retries a failed mark before another wipe`() = test { + assertFailedMarkSurvivesWipe(nodeRunning = false) + } + + private suspend fun TestScope.assertFailedMarkSurvivesWipe(nodeRunning: Boolean) { val category = BackupCategory.SETTINGS val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000, synced = 1_000))) stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} @@ -418,7 +429,6 @@ class BackupRepoTest : BaseUnitTest() { runCurrent() val original = vssClients.owners.value var failRequiredWrite = true - var failedWrites = 0 whenever { cacheStore.update(any()) }.doSuspendableAnswer { val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) val current = AppCacheData(backupStatuses = statuses.value) @@ -426,34 +436,76 @@ class BackupRepoTest : BaseUnitTest() { if (failRequiredWrite && updated.backupStatuses.getValue(category).required > current.backupStatuses.getValue(category).required ) { - failedWrites++ throw IOException("required mark could not be stored") } statuses.update { updated.backupStatuses } } + val stopRefused = BackupRepoTestError("stop refused before local deletion") + whenever { lightningRepo.stop() }.thenReturn(Result.failure(stopRefused)) + whenever(lightningRepo.lightningState).thenReturn( + MutableStateFlow( + LightningState( + nodeLifecycleState = if (nodeRunning) NodeLifecycleState.Running else NodeLifecycleState.Stopped, + ), + ), + ) + val wipe = WipeWalletUseCase( + backupRepo = sut, + keychain = keychain, + coreService = coreService, + db = db, + settingsStore = settingsStore, + cacheStore = cacheStore, + watchOnlyAccountRepo = watchOnlyAccountRepo, + widgetsStore = widgetsStore, + blocktankRepo = mock(), + activityRepo = activityRepo, + hwWalletRepo = mock(), + lightningRepo = lightningRepo, + pubkyRepo = pubkyRepo, + privatePaykitRepo = Provider { privatePaykitRepo }, + privatePaykitAddressReservationRepo = privatePaykitAddressReservationRepo, + firebaseMessaging = mock(), + migrationService = mock(), + paykitSdkService = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { mock() }, + usdtRepo = usdtRepo, + paykitUsdtPaymentRepo = paykitUsdtPaymentRepo, + connectionRecovery = connectionRecoveryFixture(settingsStore, keychain, vssClients), + ) try { settingsData.update { it.copy(selectedCurrency = "EUR") } - advanceTimeBy(65_000) runCurrent() - assertEquals(2, failedWrites) - assertFailsWith { sut.reset() } - assertSame(original, vssClients.owners.value) - verify(vssBackupClient, never()).putObject(eq(category.name), any()) - - failRequiredWrite = false - sut.startObservingBackups() - advanceTimeBy(5_000) + if (!nodeRunning) { + sut.stopObservingBackups() + runCurrent() + } + val result = wipe(resetWalletState = { error("must retain wallet") }, onSuccess = {}) + assertIs(result.exceptionOrNull()) + verify(lightningRepo, never()).stop() + verify(keychain, never()).wipe() + verify(settingsStore, never()).reset() runCurrent() - val payload = argumentCaptor() - verify(vssBackupClient).putObject(eq(category.name), payload.capture()) - assertTrue(payload.lastValue.decodeToString().contains("EUR")) - assertFalse(statuses.value.getValue(category).isRequired) + failRequiredWrite = false + if (nodeRunning) { + advanceTimeBy(65_000) + runCurrent() + val payload = argumentCaptor() + verify(vssBackupClient, times(1)).putObject(eq(category.name), payload.capture()) + assertTrue(payload.lastValue.decodeToString().contains("EUR")) + assertFalse(statuses.value.getValue(category).isRequired) + assertSame(original, vssClients.owners.value) + } else { + val retried = wipe(resetWalletState = { error("must retain wallet") }, onSuccess = {}) + assertSame(stopRefused, retried.exceptionOrNull()) + assertTrue(statuses.value.getValue(category).isRequired) + verify(lightningRepo).stop() + verify(vssBackupClient, never()).putObject(eq(category.name), any()) + } + verify(keychain, never()).wipe() + verify(settingsStore, never()).reset() } finally { failRequiredWrite = false - sut.startObservingBackups() - advanceTimeBy(65_000) - runCurrent() - sut.reset() + sut.stopObservingBackups() } } @@ -4476,10 +4528,10 @@ class BackupRepoTest : BaseUnitTest() { exportQueued.await() val wipe = async { sut.setWiping(true) - connectionRecoveryFixture(settingsStore, keychain, vssClients).withIdentityChange { - sdkLock.withWalletWipe { - sut.reset() - } + connectionRecoveryFixture(settingsStore, keychain, vssClients).withIdentityChange( + beforeClientsSuspend = { sut.reset() }, + ) { + sdkLock.withWalletWipe { } } } runCurrent() From 78d65feaeaf59fb8a0fa4f4d8d24a6c490119397 Mon Sep 17 00:00:00 2001 From: benk10 Date: Fri, 13 Nov 2026 19:23:54 -0500 Subject: [PATCH 48/61] fix: resume backups after cancelled wallet wipe --- .../to/bitkit/usecases/WipeWalletUseCase.kt | 6 +- .../to/bitkit/repositories/BackupRepoTest.kt | 110 ++++++++++++++---- 2 files changed, 90 insertions(+), 26 deletions(-) diff --git a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt index 1a6edc8fed..16d23b9c76 100644 --- a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt @@ -77,13 +77,13 @@ class WipeWalletUseCase @Inject constructor( } finally { lightningRepo.setWiping(false) backupRepo.setWiping(false) + if (lightningRepo.lightningState.value.nodeLifecycleState.isRunning()) { + backupRepo.startObservingBackups() + } wipeMutex.unlock() } return result.onFailure { Logger.error("Failed to wipe wallet", it, context = TAG) - if (lightningRepo.lightningState.value.nodeLifecycleState.isRunning()) { - backupRepo.startObservingBackups() - } } } diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 4e812ee9fe..783654c83d 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -449,29 +449,7 @@ class BackupRepoTest : BaseUnitTest() { ), ), ) - val wipe = WipeWalletUseCase( - backupRepo = sut, - keychain = keychain, - coreService = coreService, - db = db, - settingsStore = settingsStore, - cacheStore = cacheStore, - watchOnlyAccountRepo = watchOnlyAccountRepo, - widgetsStore = widgetsStore, - blocktankRepo = mock(), - activityRepo = activityRepo, - hwWalletRepo = mock(), - lightningRepo = lightningRepo, - pubkyRepo = pubkyRepo, - privatePaykitRepo = Provider { privatePaykitRepo }, - privatePaykitAddressReservationRepo = privatePaykitAddressReservationRepo, - firebaseMessaging = mock(), - migrationService = mock(), - paykitSdkService = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { mock() }, - usdtRepo = usdtRepo, - paykitUsdtPaymentRepo = paykitUsdtPaymentRepo, - connectionRecovery = connectionRecoveryFixture(settingsStore, keychain, vssClients), - ) + val wipe = createWipeUseCase() try { settingsData.update { it.copy(selectedCurrency = "EUR") } runCurrent() @@ -509,6 +487,92 @@ class BackupRepoTest : BaseUnitTest() { } } + private fun createWipeUseCase() = WipeWalletUseCase( + backupRepo = sut, + keychain = keychain, + coreService = coreService, + db = db, + settingsStore = settingsStore, + cacheStore = cacheStore, + watchOnlyAccountRepo = watchOnlyAccountRepo, + widgetsStore = widgetsStore, + blocktankRepo = mock(), + activityRepo = activityRepo, + hwWalletRepo = mock(), + lightningRepo = lightningRepo, + pubkyRepo = pubkyRepo, + privatePaykitRepo = Provider { privatePaykitRepo }, + privatePaykitAddressReservationRepo = privatePaykitAddressReservationRepo, + firebaseMessaging = mock(), + migrationService = mock(), + paykitSdkService = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { mock() }, + usdtRepo = usdtRepo, + paykitUsdtPaymentRepo = paykitUsdtPaymentRepo, + connectionRecovery = connectionRecoveryFixture(settingsStore, keychain, vssClients), + ) + + @Test + fun `cancelled wipe drain resumes automatic backups for the retained wallet`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000, synced = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + whenever(lightningRepo.lightningState).thenReturn( + MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Running)), + ) + sut.startObservingBackups() + runCurrent() + val original = vssClients.owners.value + val committed = CompletableDeferred() + val release = CompletableDeferred() + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + val current = AppCacheData(backupStatuses = statuses.value) + val updated = transform(current) + statuses.update { updated.backupStatuses } + if (!committed.isCompleted && updated.backupStatuses.getValue(category).required > + current.backupStatuses.getValue(category).required + ) { + committed.complete(Unit) + release.await() + } + } + settingsData.update { it.copy(selectedCurrency = "EUR") } + advanceTimeBy(5_000) + runCurrent() + assertTrue(committed.isCompleted) + assertFalse(statuses.value.getValue(category).isRequired) + val payload = argumentCaptor() + verify(vssBackupClient).putObject(eq(category.name), payload.capture()) + assertTrue(payload.lastValue.decodeToString().contains("EUR")) + val wipe = async { createWipeUseCase()(resetWalletState = { error("must retain wallet") }, onSuccess = {}) } + try { + runCurrent() + wipe.cancel() + runCurrent() + assertFalse(wipe.isCompleted) + release.complete(Unit) + wipe.join() + assertTrue(wipe.isCancelled) + runCurrent() + assertSame(original, vssClients.owners.value) + verify(lightningRepo, never()).stop() + verify(keychain, never()).wipe() + verify(settingsStore, never()).reset() + assertFalse(sut.isWiping.value) + settingsData.update { it.copy(selectedCurrency = "GBP") } + advanceTimeBy(65_000) + runCurrent() + verify(vssBackupClient, times(2)).putObject(eq(category.name), payload.capture()) + assertTrue(payload.lastValue.decodeToString().contains("GBP")) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + release.complete(Unit) + wipe.cancelAndJoin() + sut.reset() + } + } + @Test fun `older required mark completion retains a newer failed write`() = test { val category = BackupCategory.SETTINGS From 3c2682acd0632ef56f649e12e663e7230fcf8f4a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 03:44:06 +0100 Subject: [PATCH 49/61] fix: reconcile stack tests and wipe order with master Drain profile removal before the identity change, so backup reset follows removal and still precedes VSS client suspension. Align the stack's tests with master's APIs and max-send rule. Verified: just test (unit suite), just lint --- .../bitkit/repositories/PublicPaykitRepo.kt | 4 ++- .../to/bitkit/services/PaykitSdkService.kt | 10 +++++-- .../to/bitkit/usecases/WipeWalletUseCase.kt | 24 ++++++++--------- .../to/bitkit/repositories/BackupRepoTest.kt | 27 ++++++++++++++++--- .../ContactPaymentSettingsRepoTest.kt | 2 +- .../bitkit/repositories/LightningRepoTest.kt | 2 ++ .../to/bitkit/repositories/PubkyRepoTest.kt | 20 -------------- .../repositories/PublicPaykitRepoTest.kt | 2 +- .../to/bitkit/repositories/WalletRepoTest.kt | 5 +++- .../bitkit/services/ActivityServiceRbfTest.kt | 2 +- .../bitkit/usecases/WipeWalletUseCaseTest.kt | 2 +- .../viewmodels/AppViewModelSendFlowTest.kt | 1 + 12 files changed, 58 insertions(+), 43 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PublicPaykitRepo.kt b/app/src/main/java/to/bitkit/repositories/PublicPaykitRepo.kt index e5aa0adbef..29ec24e70d 100644 --- a/app/src/main/java/to/bitkit/repositories/PublicPaykitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PublicPaykitRepo.kt @@ -387,7 +387,9 @@ class PublicPaykitRepo @Inject constructor( desired, beforePublish = { markPublicationPending(ownsPublication) }, acknowledge = { current -> - acknowledgePublishedEndpoints(desired, signIn.publicKey) { current() && ownsPublication() } + acknowledgePublishedEndpoints(desired, signIn.publicKey) { + current() && ownsPublication() + } }, canPublish = { isAutomaticPublicationAllowed(ownsPublication) }, refresh = refresh, diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt index 753e9025c2..7a86b78f89 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt @@ -1220,7 +1220,7 @@ class PaykitSdkService @Inject constructor( endpoints: List, onAcknowledged: () -> Unit, canPublish: suspend () -> Boolean, - ): EndpointSyncReport? = syncPublicEndpointsWithEpoch(endpoints, canPublish, reusable = null, onAcknowledged)?.report + ): EndpointSyncReport? = syncPublicEndpoints(endpoints, canPublish, reusable = null, onAcknowledged)?.report internal fun publicEndpointSyncEpoch(): Long = publicEndpointEpoch.get() @@ -1228,7 +1228,13 @@ class PaykitSdkService @Inject constructor( endpoints: List, canPublish: suspend () -> Boolean, reusable: PublicEndpointSync?, - onAcknowledged: () -> Unit = {}, + ): PublicEndpointSync? = syncPublicEndpoints(endpoints, canPublish, reusable, onAcknowledged = {}) + + private suspend fun syncPublicEndpoints( + endpoints: List, + canPublish: suspend () -> Boolean, + reusable: PublicEndpointSync?, + onAcknowledged: () -> Unit, ): PublicEndpointSync? { isSetup.await() val priority = if (endpoints.isEmpty()) { diff --git a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt index 3321f513ed..1702de847b 100644 --- a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt @@ -80,18 +80,18 @@ class WipeWalletUseCase @Inject constructor( var credentialsMayBeErased = false val result = try { runSuspendCatching { - connectionRecovery.withIdentityChange( - isStillNeeded = { - expectedPendingAttemptId?.let { profileRemovalStore.requirePendingWalletReset(it) } - backupRepo.setWiping(true) - lightningRepo.setWiping(true) - wipeAdmitted = true - true - }, - beforeClientsSuspend = { backupRepo.reset() }, - ) { - expectedPendingAttemptId?.let { profileRemovalStore.requirePendingWalletReset(it) } - contactPaymentSettingsRepo.get().withWalletWipe(pubkyRepo::withWalletWipeAdmission) { + // Drain profile removal first: backup reset must follow it and still precede VSS client suspension. + contactPaymentSettingsRepo.get().withWalletWipe(pubkyRepo::withWalletWipeAdmission) { + connectionRecovery.withIdentityChange( + isStillNeeded = { + expectedPendingAttemptId?.let { profileRemovalStore.requirePendingWalletReset(it) } + backupRepo.setWiping(true) + lightningRepo.setWiping(true) + wipeAdmitted = true + true + }, + beforeClientsSuspend = { backupRepo.reset() }, + ) { paykitSdkService.withWalletWipe { expectedPendingAttemptId?.let { profileRemovalStore.requirePendingWalletReset(it) } val pending = profileRemovalStore.pendingState() diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 214e6ba0b1..55216b27b2 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -122,8 +122,8 @@ import to.bitkit.services.BlocktankService import to.bitkit.services.LightningService import to.bitkit.services.PaykitSdkOperationLock import to.bitkit.services.PaykitSdkService -import to.bitkit.services.UsdtService import to.bitkit.services.SparkError +import to.bitkit.services.UsdtService import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture import to.bitkit.usecases.WipeWalletUseCase @@ -505,7 +505,23 @@ class BackupRepoTest : BaseUnitTest() { } } - private fun createWipeUseCase() = WipeWalletUseCase( + private suspend fun createWipeUseCase(): WipeWalletUseCase { + val sharing = mock() + whenever { sharing.withWalletWipe(any(), any()) }.doSuspendableAnswer { + it.getArgument Unit) -> Unit>(0)(it.getArgument(1)) + } + whenever { privatePaykitRepo.withProfileDeletionPaused(any()) }.doSuspendableAnswer { + it.getArgument Unit>(0) + .invoke(PrivatePaykitRepo.ProfileDeletionPause()) + } + whenever { privatePaykitRepo.finishProfileRemoval(any()) }.thenReturn(Result.success(Unit)) + whenever { pubkyRepo.withWalletWipeAdmission(any()) }.doSuspendableAnswer { + it.getArgument Unit>(0).invoke() + } + return createWipeUseCase(sharing) + } + + private fun createWipeUseCase(sharing: ContactPaymentSettingsRepo) = WipeWalletUseCase( backupRepo = sut, keychain = keychain, coreService = coreService, @@ -527,7 +543,12 @@ class BackupRepoTest : BaseUnitTest() { paykitSdkService = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { mock() }, usdtRepo = usdtRepo, paykitUsdtPaymentRepo = paykitUsdtPaymentRepo, + paykitReceiptRepo = mock(), + profileRemovalStore = ProfileRemovalStore.inMemoryForTesting(), + contactPaymentSettingsRepo = Provider { sharing }, connectionRecovery = connectionRecoveryFixture(settingsStore, keychain, vssClients), + wakeRepo = mock(), + moveToSparkManager = Provider { mock() }, ) @Test @@ -6698,7 +6719,6 @@ class BackupRepoTest : BaseUnitTest() { Result.success(Unit) } } -} @Test fun `legacy USDT restore gate precedes malformed connection correction`() = test { @@ -6750,3 +6770,4 @@ class BackupRepoTest : BaseUnitTest() { connectionRecovery = connectionRecoveryFixture(settingsStore, keychain, vssClients), vssClients = vssClients, ) +} diff --git a/app/src/test/java/to/bitkit/repositories/ContactPaymentSettingsRepoTest.kt b/app/src/test/java/to/bitkit/repositories/ContactPaymentSettingsRepoTest.kt index 16fd3bb725..9235604cd8 100644 --- a/app/src/test/java/to/bitkit/repositories/ContactPaymentSettingsRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/ContactPaymentSettingsRepoTest.kt @@ -132,7 +132,7 @@ class ContactPaymentSettingsRepoTest : BaseUnitTest() { val publication = CompletableDeferred() val enteredRemoval = CompletableDeferred() val finishRemoval = CompletableDeferred() - whenever(publicPaykitRepo.syncPaykitApp(isNull(), canSync = any())).doSuspendableAnswer { + whenever(publicPaykitRepo.syncPaykitApp(isNull(), eq(Priority.Background), any())).doSuspendableAnswer { publication.await() Result.failure(IllegalStateException("Uncertain publication")) } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 6c7dd43cbd..d7d60e6c54 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -4016,9 +4016,11 @@ class LightningRepoTest : BaseUnitTest() { onchainSendAttemptStore = store, connectivityRepo = connectivityRepo, vssBackupClientLdk = vssBackupClientLdk, + vssClients = vssClients, urlValidator = urlValidator, electrumProbeService = electrumProbeService, sparkRepo = sparkRepo, + profileRemovalStore = profileRemovalStore, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) val activityService = mock() diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 53da9ac91a..ac404ac1e4 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -1951,26 +1951,6 @@ class PubkyRepoTest : BaseUnitTest() { verify(pubkyService, never()).signOut() } - @Test - fun `pubky app deletion does not renew the session or replay an identity error`() = test { - val secretKey = "local_secret" - authenticateForTesting(publicKey = VALID_SELF_KEY) - whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(secretKey) - whenever(pubkyService.publicKeyFromSecret(secretKey)).thenReturn(VALID_SELF_KEY.removePrefix("pubky")) - val identityError = PaykitException.Identity("identity_error", "Missing capabilities") - whenever(pubkyService.deletePubkyProfile("revision-Test", VALID_SELF_KEY)) - .thenAnswer { throw identityError } - .thenReturn(Unit) - - val result = sut.deleteProfile() - - assertSame(identityError, result.exceptionOrNull()) - verify(pubkyService).deletePubkyProfile("revision-Test", VALID_SELF_KEY) - verify(pubkyService, never()).signIn(any()) - verify(pubkyService, never()).deletePaykitProfile() - verify(pubkyService, never()).signOut() - } - @Test fun `deleteProfile is not followed by a profile copy write from a load under way`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) diff --git a/app/src/test/java/to/bitkit/repositories/PublicPaykitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PublicPaykitRepoTest.kt index ea08128a15..c3f2816175 100644 --- a/app/src/test/java/to/bitkit/repositories/PublicPaykitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PublicPaykitRepoTest.kt @@ -731,7 +731,7 @@ class PublicPaykitRepoTest : BaseUnitTest() { it.getArgument Unit>(2)(true) }.whenever(addressReservationRepo).withPublicAddressMatch(any(), any(), any()) - val paid = async { sut.refreshPublishedBolt11ForPayment("010203") } + val paid = async { sut.refreshPublishedBolt11ForPayment("010203", admitPublication = { it() }) } entered.await() val refresh = async { sut.syncCurrentPublishedEndpoints() } assertFalse(refresh.isCompleted) diff --git a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt index d598f0d249..006129a45c 100644 --- a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt @@ -428,7 +428,10 @@ class WalletRepoTest : BaseUnitTest() { testScheduler.runCurrent() assertEquals(60_000uL, sut.balanceState.value.totalLightningSats) - assertEquals(55_000uL, sut.balanceState.value.maxSendLightningSats) + assertEquals( + MoveToSparkMath.maxSendSats(listOf(recovered), sparkState.value), + sut.balanceState.value.maxSendLightningSats, + ) } @Test diff --git a/app/src/test/java/to/bitkit/services/ActivityServiceRbfTest.kt b/app/src/test/java/to/bitkit/services/ActivityServiceRbfTest.kt index 62680ee579..611ca44a63 100644 --- a/app/src/test/java/to/bitkit/services/ActivityServiceRbfTest.kt +++ b/app/src/test/java/to/bitkit/services/ActivityServiceRbfTest.kt @@ -39,8 +39,8 @@ import to.bitkit.repositories.PaykitReceivedPaymentContacts import to.bitkit.repositories.PrivatePaykitAddressReservationRepo import to.bitkit.repositories.PrivatePaykitContactResolver import to.bitkit.test.BaseUnitTest -import to.bitkit.utils.RbfOriginalConfirmed import to.bitkit.test.connectionRecoveryFixture +import to.bitkit.utils.RbfOriginalConfirmed import javax.inject.Provider import kotlin.test.assertEquals import kotlin.test.assertFailsWith diff --git a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt index 7c843cf9f9..63e5e4c88e 100644 --- a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt @@ -80,10 +80,10 @@ import to.bitkit.services.PaykitSdkService import to.bitkit.services.PubkyService import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture +import to.bitkit.ui.settings.lightning.MoveToSparkManager import java.io.IOException import java.io.OutputStream import java.util.UUID -import to.bitkit.ui.settings.lightning.MoveToSparkManager import javax.inject.Provider import kotlin.test.assertEquals import kotlin.test.assertFailsWith diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index dbf2bbf6d4..af0120d8e0 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -3575,6 +3575,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { lightningRepo = lightningRepo, activityRepo = activityRepo, clock = Clock.System, + backupRepo = { backupRepo }, ) val activationStarted = CompletableDeferred() val finishActivation = CompletableDeferred() From 438a1619fd58a535b9226161a8e0c3771a5acb34 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Sun, 29 Nov 2026 19:46:03 +0100 Subject: [PATCH 50/61] fix: keep spark out of a wallet a pending reset holds LightningRepo.start launched Spark and registered the caller's event handler before the lifecycle lock checked the pending wallet reset, so a retained or unreadable reset marker still let Spark connect and sync into that wallet. Both now wait for wallet admission, and the lock's refusal checks move into startRefusal. Verified: testDevDebugUnitTest (extended pending-wipe test fails on the previous LightningRepo, passes here) and just lint --- .../to/bitkit/repositories/LightningRepo.kt | 33 ++++++++++++------- .../bitkit/repositories/LightningRepoTest.kt | 2 ++ changelog.d/next/1688.fixed.md | 1 - changelog.d/next/1689.fixed.md | 1 - changelog.d/next/1690.fixed.md | 1 - changelog.d/next/1693.fixed.md | 1 - 6 files changed, 23 insertions(+), 16 deletions(-) delete mode 100644 changelog.d/next/1688.fixed.md delete mode 100644 changelog.d/next/1689.fixed.md delete mode 100644 changelog.d/next/1690.fixed.md delete mode 100644 changelog.d/next/1693.fixed.md diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 274aa3d465..56ef749b2a 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -438,10 +438,12 @@ class LightningRepo @Inject constructor( val stopRequestsAtStart = stopRequestsSeen ?: stopRequestCount.get() val isConfigChange = customServerUrl != null || customRgsServerUrl != null - // Spark needs no node, so it starts alongside it and stays up while the node stops in background. - if (!isWiping) scope.launch { sparkRepo.start(walletIndex) } - - eventHandler?.let { _eventHandlers.add(it) } + // Spark needs no node, so it starts alongside it and stays up while the node stops in background. Neither + // Spark nor the caller's handler joins a wallet that a pending reset keeps out. + if (!isWiping && walletAdmissionError() == null) { + scope.launch { sparkRepo.start(walletIndex) } + eventHandler?.let { _eventHandlers.add(it) } + } // Track retry state outside mutex to avoid deadlock (Mutex is non-reentrant) var shouldRetryStart = false @@ -449,14 +451,7 @@ class LightningRepo @Inject constructor( var initialLifecycleState: NodeLifecycleState val result = lifecycleMutex.withLock { - if (isWiping) return@withLock Result.failure(WipeInProgressError()) - // A stop that ran since the caller checked wins, including one that found the node already stopped. - if (stopRequestsSeen != null && stopRequestCount.get() != stopRequestsSeen) { - Logger.info("Skipped start because a stop was requested", context = TAG) - return@withLock Result.failure(NodeStartYieldedToStopError(null)) - } - runSuspendCatching { profileRemovalStore.requireWalletAvailable() } - .exceptionOrNull()?.let { return@withLock Result.failure(it) } + startRefusal(stopRequestsSeen)?.let { return@withLock Result.failure(it) } initialLifecycleState = _lightningState.value.nodeLifecycleState if (initialLifecycleState.isRunningOrStarting()) { return@withLock skipStartForRunningNode( @@ -634,6 +629,20 @@ class LightningRepo @Inject constructor( } } + /** Why a start must not run once it holds the lifecycle lock, or null when it may. */ + private suspend fun startRefusal(stopRequestsSeen: Long?): Throwable? { + if (isWiping) return WipeInProgressError() + // A stop that ran since the caller checked wins, including one that found the node already stopped. + if (stopRequestsSeen != null && stopRequestCount.get() != stopRequestsSeen) { + Logger.info("Skipped start because a stop was requested", context = TAG) + return NodeStartYieldedToStopError(null) + } + return walletAdmissionError() + } + + private suspend fun walletAdmissionError(): Throwable? = + runSuspendCatching { profileRemovalStore.requireWalletAvailable() }.exceptionOrNull() + private suspend fun releaseUnsavedConfigNode() { runSuspendCatching { lightningService.stop() } .onFailure { Logger.warn("Failed to release node built with an unsaved config", it, context = TAG) } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index f7716e2d6d..e405556d48 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -499,9 +499,11 @@ class LightningRepoTest : BaseUnitTest() { profileRemovalStore.begin(attempt) } val result = sut.start() + testScheduler.runCurrent() assertIs(result.exceptionOrNull()) verify(lightningService, never()).setup(any(), anyOrNull(), anyOrNull(), anyOrNull()) verify(lightningService, never()).start(anyOrNull(), any()) + verify(sparkRepo, never()).start(any()) assertEquals(attempt, profileRemovalStore.pendingAttempt()) } diff --git a/changelog.d/next/1688.fixed.md b/changelog.d/next/1688.fixed.md deleted file mode 100644 index fb97b9ecd4..0000000000 --- a/changelog.d/next/1688.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/1689.fixed.md b/changelog.d/next/1689.fixed.md deleted file mode 100644 index ce494b30fa..0000000000 --- a/changelog.d/next/1689.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Keep interrupted backups within their wallet lifecycle, retry newer pending data after failures, and let explicit backups recover without waiting for the Lightning node or background delay, while preventing retired requests from acting on a replacement wallet. diff --git a/changelog.d/next/1690.fixed.md b/changelog.d/next/1690.fixed.md deleted file mode 100644 index 2cae693deb..0000000000 --- a/changelog.d/next/1690.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Preserve profile data when cleanup is incomplete or active subscriptions prevent removal, and show a known expiry instead of asking users to cancel fixed-term subscriptions. diff --git a/changelog.d/next/1693.fixed.md b/changelog.d/next/1693.fixed.md deleted file mode 100644 index 284a7d1139..0000000000 --- a/changelog.d/next/1693.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Keep interrupted profile removal recoverable with confirmed retries or local Disconnect, preserve cleanup progress and payment details, and make wallet-reset recovery distinguish unreadable state, attempt endpoint cleanup before a fresh reset, retain authenticated read-only seed access and local forgotten-PIN navigation, keep Retry available for unreadable reset state even when phrase access is available, and prevent duplicate actions while cleanup is running, resume deferred React Native migration after cleanup-state recovery, offer Retry when migration status is unavailable, and keep onboarding closed until migration admission finishes, and keep erased or unreadable wallet credentials from reopening the wallet during reset completion. From c8c3402a547e6ea1ccb8b1816f8482a9d1a9f3b1 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Sun, 29 Nov 2026 19:46:04 +0100 Subject: [PATCH 51/61] fix: let a wallet change cancel on-chain receipt handlers quietly The on-chain receive and confirmation handlers wrapped their receipt work in runCatching, so a wallet change that cancelled them was logged as an error. They now use runSuspendCatching, as the replacement handler does. Verified: testDevDebugUnitTest and just lint --- app/src/main/java/to/bitkit/services/CoreService.kt | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/services/CoreService.kt b/app/src/main/java/to/bitkit/services/CoreService.kt index 8a9cb0b83d..1c044c6bed 100644 --- a/app/src/main/java/to/bitkit/services/CoreService.kt +++ b/app/src/main/java/to/bitkit/services/CoreService.kt @@ -1682,21 +1682,21 @@ class ActivityService( withReceiptOperation { receipt -> ServiceQueue.CORE.background { receipt.requireCurrent() - runCatching { + runSuspendCatching { val coreDetails = mapToCoreTransactionDetails(txid, details) invalidatePaykitContactBackfill() receipt.commit { upsertTransactionDetails(listOf(coreDetails)) } val payments = lightningService.listPayments() ?: run { Logger.warn("No payments available for transaction $txid", context = TAG) - return@background + return@runSuspendCatching } val payment = payments.firstOrNull { payment -> (payment.kind as? PaymentKind.Onchain)?.txid == txid } ?: run { Logger.warn("Payment not found for transaction $txid", context = TAG) - return@background + return@runSuspendCatching } processOnchainPayment( @@ -1717,21 +1717,21 @@ class ActivityService( withReceiptOperation { receipt -> ServiceQueue.CORE.background { receipt.requireCurrent() - runCatching { + runSuspendCatching { val coreDetails = mapToCoreTransactionDetails(txid, details) invalidatePaykitContactBackfill() receipt.commit { upsertTransactionDetails(listOf(coreDetails)) } val payments = lightningService.listPayments() ?: run { Logger.warn("No payments available for transaction $txid", context = TAG) - return@background + return@runSuspendCatching } val payment = payments.firstOrNull { payment -> (payment.kind as? PaymentKind.Onchain)?.txid == txid } ?: run { Logger.warn("Payment not found for transaction $txid", context = TAG) - return@background + return@runSuspendCatching } processOnchainPayment( From 89e28e434116de707e85d89bfbd9928a4ec7b719 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Sun, 29 Nov 2026 19:46:04 +0100 Subject: [PATCH 52/61] chore: merge this pr's changelog fragments into one Verified: none (changelog text only) --- changelog.d/next/1686.fixed.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog.d/next/1686.fixed.md b/changelog.d/next/1686.fixed.md index 2304d8787b..2d8b7e152e 100644 --- a/changelog.d/next/1686.fixed.md +++ b/changelog.d/next/1686.fixed.md @@ -1 +1 @@ -Wallet restore finishes without optional profile refresh waits, missing profiles retry after reconnecting without interrupting active setup, incomplete identity backups remain blocked, and allowances resume safely after re-enabling without reviving cancelled work, while backup uploads, retries and routing resets stay with their original wallet during identity changes, scheduled backups stay marked as running until they finish or stop, and pending Spark changes back up when restore finishes, cached balances remain visible during node startup, and Spending reflects Spark balance changes and payment results remain visible while the Lightning node is stopped or its startup times out, including after a finished Spark exit. +Wallet restore no longer waits for optional profile data, pending backups stay with their wallet and survive connection failures and wallet resets, interrupted profile removal and wallet reset can be retried or completed locally, and incomplete profile deletion keeps profile data without repeating cleanup. From a78b5562e7d50cc6d655f54bb8e2ced8b10e574a Mon Sep 17 00:00:00 2001 From: ovitrif Date: Sun, 29 Nov 2026 19:58:30 +0100 Subject: [PATCH 53/61] fix: start spark only once the lifecycle lock admits the wallet Checking admission before the lock left a window in which a reset that began meanwhile still let Spark start; Spark and the caller's handler now start right after the lock's refusal checks pass. Verified: testDevDebugUnitTest and just lint --- .../to/bitkit/repositories/LightningRepo.kt | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 56ef749b2a..24c92c1edd 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -438,13 +438,6 @@ class LightningRepo @Inject constructor( val stopRequestsAtStart = stopRequestsSeen ?: stopRequestCount.get() val isConfigChange = customServerUrl != null || customRgsServerUrl != null - // Spark needs no node, so it starts alongside it and stays up while the node stops in background. Neither - // Spark nor the caller's handler joins a wallet that a pending reset keeps out. - if (!isWiping && walletAdmissionError() == null) { - scope.launch { sparkRepo.start(walletIndex) } - eventHandler?.let { _eventHandlers.add(it) } - } - // Track retry state outside mutex to avoid deadlock (Mutex is non-reentrant) var shouldRetryStart = false var shouldRestartForGraphReset = false @@ -452,6 +445,10 @@ class LightningRepo @Inject constructor( val result = lifecycleMutex.withLock { startRefusal(stopRequestsSeen)?.let { return@withLock Result.failure(it) } + // Spark needs no node, so it starts alongside it and stays up while the node stops in background. + // Neither Spark nor the caller's handler joins a wallet that a pending reset keeps out. + scope.launch { sparkRepo.start(walletIndex) } + eventHandler?.let { _eventHandlers.add(it) } initialLifecycleState = _lightningState.value.nodeLifecycleState if (initialLifecycleState.isRunningOrStarting()) { return@withLock skipStartForRunningNode( @@ -629,7 +626,6 @@ class LightningRepo @Inject constructor( } } - /** Why a start must not run once it holds the lifecycle lock, or null when it may. */ private suspend fun startRefusal(stopRequestsSeen: Long?): Throwable? { if (isWiping) return WipeInProgressError() // A stop that ran since the caller checked wins, including one that found the node already stopped. @@ -637,12 +633,9 @@ class LightningRepo @Inject constructor( Logger.info("Skipped start because a stop was requested", context = TAG) return NodeStartYieldedToStopError(null) } - return walletAdmissionError() + return runSuspendCatching { profileRemovalStore.requireWalletAvailable() }.exceptionOrNull() } - private suspend fun walletAdmissionError(): Throwable? = - runSuspendCatching { profileRemovalStore.requireWalletAvailable() }.exceptionOrNull() - private suspend fun releaseUnsavedConfigNode() { runSuspendCatching { lightningService.stop() } .onFailure { Logger.warn("Failed to release node built with an unsaved config", it, context = TAG) } From 5c7df26f25e200f10fbb619a34956e6929c018fa Mon Sep 17 00:00:00 2001 From: ovitrif Date: Sun, 29 Nov 2026 19:58:31 +0100 Subject: [PATCH 54/61] chore: say pending backups retry after connection failures A wallet reset retires pending backups on Android, so the fragment no longer says they survive it. Verified: none (changelog text only) --- changelog.d/next/1686.fixed.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog.d/next/1686.fixed.md b/changelog.d/next/1686.fixed.md index 2d8b7e152e..8612b615a1 100644 --- a/changelog.d/next/1686.fixed.md +++ b/changelog.d/next/1686.fixed.md @@ -1 +1 @@ -Wallet restore no longer waits for optional profile data, pending backups stay with their wallet and survive connection failures and wallet resets, interrupted profile removal and wallet reset can be retried or completed locally, and incomplete profile deletion keeps profile data without repeating cleanup. +Wallet restore no longer waits for optional profile data, pending backups stay with their wallet and retry after connection failures, interrupted profile removal and wallet reset can be retried or completed locally, and incomplete profile deletion keeps profile data without repeating cleanup. From 02945587c1873d6775b3ec9335956524dbc02ac8 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Wed, 2 Dec 2026 20:38:26 +0100 Subject: [PATCH 55/61] fix: keep payment alerts and reset progress while work drains The caller's event handler joins before the lifecycle lock again and leaves if the start is refused or cancelled before admission, so it sees events while another start holds the lock. The wipe sets its flags before draining identity work, so Reset shows progress and starts are refused meanwhile. Verified: just test, just lint --- .../to/bitkit/repositories/LightningRepo.kt | 237 +++++++++--------- .../to/bitkit/usecases/WipeWalletUseCase.kt | 7 +- .../bitkit/repositories/LightningRepoTest.kt | 45 ++++ .../bitkit/usecases/WipeWalletUseCaseTest.kt | 20 ++ 4 files changed, 192 insertions(+), 117 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index fd785135e2..1ec0241b32 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -484,142 +484,151 @@ class LightningRepo @Inject constructor( var shouldRestartForGraphReset = false var initialLifecycleState: NodeLifecycleState - val result = lifecycleMutex.withLock { - startRefusal(stopRequestsSeen)?.let { return@withLock Result.failure(it) } - // Spark needs no node, so it starts alongside it and stays up while the node stops in background. - // Neither Spark nor the caller's handler joins a wallet that a pending reset keeps out. - scope.launch { sparkRepo.start(walletIndex) } - eventHandler?.let { _eventHandlers.add(it) } - dropStoppedNode() - initialLifecycleState = _lightningState.value.nodeLifecycleState - if (initialLifecycleState.isRunningOrStarting()) { - return@withLock skipStartForRunningNode( - lifecycleState = initialLifecycleState, - customServerUrl = customServerUrl, - customRgsServerUrl = customRgsServerUrl, - ) - } + // The caller's handler joins before the lock, so it sees events while another start holds it, + // and leaves again if this start is refused or cancelled before admission. + val handlerAdded = eventHandler?.let { _eventHandlers.add(it) } == true + var handlerAdmitted = false + val result = try { + lifecycleMutex.withLock { + startRefusal(stopRequestsSeen)?.let { return@withLock Result.failure(it) } + handlerAdmitted = true + // Spark needs no node, so it starts alongside it and stays up while the node stops in background. + // Spark does not join a wallet that a pending reset keeps out. + scope.launch { sparkRepo.start(walletIndex) } + dropStoppedNode() + initialLifecycleState = _lightningState.value.nodeLifecycleState + if (initialLifecycleState.isRunningOrStarting()) { + return@withLock skipStartForRunningNode( + lifecycleState = initialLifecycleState, + customServerUrl = customServerUrl, + customRgsServerUrl = customRgsServerUrl, + ) + } - // A changed config starts only a node it built itself, never a handle another start left behind. - if (isConfigChange && lightningService.node != null) { - releaseUnsavedConfigNode() - if (lightningService.node != null) return@withLock Result.failure(NodeConfigNotAppliedError()) - } + // A changed config starts only a node it built itself, never a handle another start left behind. + if (isConfigChange && lightningService.node != null) { + releaseUnsavedConfigNode() + if (lightningService.node != null) return@withLock Result.failure(NodeConfigNotAppliedError()) + } - runCatching { - _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Starting) } - - // Setup if needed - if (lightningService.node == null) { - val setupResult = - setup(walletIndex, customServerUrl, customRgsServerUrl, channelMigration) - if (setupResult.isFailure) { - _lightningState.update { - it.copy( - nodeLifecycleState = NodeLifecycleState.ErrorStarting( - setupResult.exceptionOrNull() ?: NodeSetupError() + runCatching { + _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Starting) } + + // Setup if needed + if (lightningService.node == null) { + val setupResult = + setup(walletIndex, customServerUrl, customRgsServerUrl, channelMigration) + if (setupResult.isFailure) { + _lightningState.update { + it.copy( + nodeLifecycleState = NodeLifecycleState.ErrorStarting( + setupResult.exceptionOrNull() ?: NodeSetupError() + ) ) - ) + } + return@withLock setupResult } - return@withLock setupResult } - } - // A stop requested during a server change's or recovery's build wins. A foreground start can cancel - // that stop before it runs, so release the built node here, or that start would reuse it. An - // ordinary start, which cancels pending stops, is not held back by one. - val yieldsToStop = isConfigChange || !shouldCancelPendingStop - if (yieldsToStop && stopRequestsSeen != null && stopRequestCount.get() != stopRequestsSeen) { - Logger.info("Skipped start because a stop was requested during setup", context = TAG) - releaseUnsavedConfigNode() - _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Stopped) } - return@withLock Result.failure(NodeStartYieldedToStopError(null)) - } + // A stop requested during a server change's or recovery's build wins. A foreground start can + // cancel that stop before it runs, so release the built node here, or that start would reuse + // it. An ordinary start, which cancels pending stops, is not held back by one. + val yieldsToStop = isConfigChange || !shouldCancelPendingStop + if (yieldsToStop && stopRequestsSeen != null && stopRequestCount.get() != stopRequestsSeen) { + Logger.info("Skipped start because a stop was requested during setup", context = TAG) + releaseUnsavedConfigNode() + _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Stopped) } + return@withLock Result.failure(NodeStartYieldedToStopError(null)) + } - if (lightningService.status?.isRunning == true) { - Logger.info("LDK node already running", context = TAG) - runSuspendCatching { lightningService.reconcileWatchOnlyAccounts() } - .onFailure { - Logger.warn( - "Failed to reconcile Paykit Server accounts during startup", - it, - context = TAG, - ) - } - return@withLock adoptRunningNode() - } + if (lightningService.status?.isRunning == true) { + Logger.info("LDK node already running", context = TAG) + runSuspendCatching { lightningService.reconcileWatchOnlyAccounts() } + .onFailure { + Logger.warn( + "Failed to reconcile Paykit Server accounts during startup", + it, + context = TAG, + ) + } + return@withLock adoptRunningNode() + } - lightningService.start(timeout, ::onEvent) + lightningService.start(timeout, ::onEvent) - _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) } - listPaymentsKeepingSendHashes() + _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) } + listPaymentsKeepingSendHashes() - // Initial state sync - syncState() - logNodeSupportSummary("node started") - refreshChannelCache() + // Initial state sync + syncState() + logNodeSupportSummary("node started") + refreshChannelCache() - if (shouldValidateGraph && !lightningService.aresRequiredPeersInNetworkGraph()) { - Logger.warn("Network graph is stale, resetting and restarting...", context = TAG) + if (shouldValidateGraph && !lightningService.aresRequiredPeersInNetworkGraph()) { + Logger.warn("Network graph is stale, resetting and restarting...", context = TAG) - lightningService.stop() - clearNetworkGraph(walletIndex) + lightningService.stop() + clearNetworkGraph(walletIndex) - _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Stopped) } - shouldRestartForGraphReset = true - return@withLock Result.success(Unit) - } + _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Stopped) } + shouldRestartForGraphReset = true + return@withLock Result.success(Unit) + } - // Post-startup tasks (non-blocking) - disconnectIdlePeers().onFailure { - Logger.error("Failed to disconnect idle peers", it, context = TAG) - } - logNodeSupportSummary("idle peers disconnected") - // Detached, so an unreachable Blocktank never delays the start - scope.launch { connectMovedPeers() } + // Post-startup tasks (non-blocking) + disconnectIdlePeers().onFailure { + Logger.error("Failed to disconnect idle peers", it, context = TAG) + } + logNodeSupportSummary("idle peers disconnected") + // Detached, so an unreachable Blocktank never delays the start + scope.launch { connectMovedPeers() } - sync().onFailure { e -> - Logger.warn("Initial sync failed, event-driven sync will retry", e, context = TAG) - } - Result.success(Unit) - }.getOrElse { e -> - if (e is CancellationException) { - withContext(NonCancellable) { - if (isConfigChange) { - // The change was never saved, so neither keep nor adopt a node built with its server. - stopLocked() - Logger.info("Released the node of a cancelled config change", context = TAG) - } else { - reconcileCancelledStart(initialLifecycleState) + sync().onFailure { e -> + Logger.warn("Initial sync failed, event-driven sync will retry", e, context = TAG) + } + Result.success(Unit) + }.getOrElse { e -> + if (e is CancellationException) { + withContext(NonCancellable) { + if (isConfigChange) { + // The change was never saved, so neither keep nor adopt a node built with + // its server. + stopLocked() + Logger.info("Released the node of a cancelled config change", context = TAG) + } else { + reconcileCancelledStart(initialLifecycleState) + } } + throw e } - throw e - } - val currentState = _lightningState.value.nodeLifecycleState - if (currentState.isRunning()) { - Logger.warn("Start error but node is $currentState, skipping retry", e, context = TAG) - return@withLock Result.success(Unit) - } + val currentState = _lightningState.value.nodeLifecycleState + if (currentState.isRunning()) { + Logger.warn("Start error but node is $currentState, skipping retry", e, context = TAG) + return@withLock Result.success(Unit) + } - if (lightningService.status?.isRunning == true) { - Logger.warn("Start error but LDK node is running, adopting it", e, context = TAG) - return@withLock adoptRunningNode() - } + if (lightningService.status?.isRunning == true) { + Logger.warn("Start error but LDK node is running, adopting it", e, context = TAG) + return@withLock adoptRunningNode() + } - if (shouldRetry) { - Logger.warn("Start error, will retry...", e, context = TAG) - _lightningState.update { it.copy(nodeLifecycleState = initialLifecycleState) } - shouldRetryStart = true - Result.failure(e) - } else { - // A node built with a changed server must not outlive its failed start: the next start would - // reuse it although the change was never saved. - if (isConfigChange) releaseUnsavedConfigNode() - _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.ErrorStarting(e)) } - Result.failure(e) + if (shouldRetry) { + Logger.warn("Start error, will retry...", e, context = TAG) + _lightningState.update { it.copy(nodeLifecycleState = initialLifecycleState) } + shouldRetryStart = true + Result.failure(e) + } else { + // A node built with a changed server must not outlive its failed start: the next start + // would reuse it although the change was never saved. + if (isConfigChange) releaseUnsavedConfigNode() + _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.ErrorStarting(e)) } + Result.failure(e) + } } } + } finally { + if (handlerAdded && !handlerAdmitted) _eventHandlers.remove(eventHandler) } // Retry OUTSIDE the mutex to avoid deadlock (Kotlin Mutex is non-reentrant) diff --git a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt index 13cb00bcf5..de27185620 100644 --- a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt @@ -78,14 +78,15 @@ class WipeWalletUseCase @Inject constructor( var credentialsMayBeErased = false val result = try { runSuspendCatching { + expectedPendingAttemptId?.let { profileRemovalStore.requirePendingWalletReset(it) } + backupRepo.setWiping(true) + lightningRepo.setWiping(true) + wipeAdmitted = true // Drain profile removal first: backup reset must follow it and still precede VSS client suspension. contactPaymentSettingsRepo.get().withWalletWipe(pubkyRepo::withWalletWipeAdmission) { connectionRecovery.withIdentityChange( isStillNeeded = { expectedPendingAttemptId?.let { profileRemovalStore.requirePendingWalletReset(it) } - backupRepo.setWiping(true) - lightningRepo.setWiping(true) - wipeAdmitted = true true }, beforeClientsSuspend = { backupRepo.reset() }, diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 7fe094845c..58d0b31180 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -346,6 +346,20 @@ class LightningRepoTest : BaseUnitTest() { assertFalse(dispatched) } + @Test + fun `a refused start leaves the caller handler out of later events`() = test { + val received = mutableListOf() + val serviceHandler: NodeEventHandler = { received.add(it) } + sut.setWiping(true) + assertTrue(sut.start(eventHandler = serviceHandler).isFailure) + sut.setWiping(false) + + val nodeListener = startNodeAndCaptureEvents() + nodeListener(Event.PaymentSuccessful("payment", "hash", "preimage", 10uL)) + + assertTrue(received.isEmpty()) + } + private suspend fun startNodeAndCaptureEvents(): NodeEventHandler { var capturedHandler: NodeEventHandler? = null whenever { lightningService.start(anyOrNull(), any()) }.thenAnswer { @@ -391,6 +405,37 @@ class LightningRepoTest : BaseUnitTest() { ) } + @Test + fun `caller handler receives events emitted while another start holds the lifecycle lock`() = test { + sut.setInitNodeLifecycleState() + whenever(lightningService.node).thenReturn(mock()) + whenever(lightningService.sync()).thenReturn(Unit) + val blocktank = mock() + whenever(coreService.blocktank).thenReturn(blocktank) + whenever(blocktank.info(any())).thenReturn(null) + var nodeListener: NodeEventHandler? = null + val startGate = CompletableDeferred() + whenever(lightningService.start(anyOrNull(), any())).doSuspendableAnswer { + @Suppress("UNCHECKED_CAST") + nodeListener = it.arguments[1] as NodeEventHandler + startGate.await() + } + val received = mutableListOf() + val serviceHandler: NodeEventHandler = { received.add(it) } + + val foregroundStart = async { sut.start() } + testScheduler.runCurrent() + val serviceStart = async { sut.start(eventHandler = serviceHandler) } + testScheduler.runCurrent() + val event = Event.PaymentSuccessful("payment", "hash", "preimage", 10uL) + requireNotNull(nodeListener).invoke(event) + startGate.complete(Unit) + assertTrue(foregroundStart.await().isSuccess) + assertTrue(serviceStart.await().isSuccess) + + assertEquals(listOf(event), received) + } + @Test fun `produced lightning settlement survives a captured unpublished receive cache snapshot`() = test { val eventHandler = startNodeAndCaptureEvents() diff --git a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt index 7858f02d0c..d5c5a473e7 100644 --- a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt @@ -592,6 +592,26 @@ class WipeWalletUseCaseTest : BaseUnitTest() { verify(lightningRepo).stop() } + @Test + fun `invoke should report wiping while profile identity work drains`() = runTest { + val drained = CompletableDeferred() + whenever { pubkyRepo.withWalletWipeAdmission(any()) }.doSuspendableAnswer { + drained.await() + it.getArgument Unit>(0).invoke() + } + val job = launch { sut.invoke(resetWalletState = {}, onSuccess = {}) } + runCurrent() + + val wipingWhileDraining = runCatching { + verify(backupRepo).setWiping(true) + verify(lightningRepo).setWiping(true) + }.isSuccess + drained.complete(Unit) + job.join() + + assertTrue(wipingWhileDraining, "isWiping stayed false while the wipe waited for identity work") + } + @Test fun `invoke should fail without wiping and restart observers when node stop fails while running`() = runTest { whenever(lightningRepo.lightningState) From 198f3e3c45429c585af6c6199a01e5005ab1b56c Mon Sep 17 00:00:00 2001 From: ovitrif Date: Thu, 3 Dec 2026 00:48:48 +0100 Subject: [PATCH 56/61] fix: let reset interrupt a stalled session restore A wipe now cancels an admitted session restore, the startup one included, instead of draining it, as master's Paykit wipe barrier interrupted it, so Reset no longer waits out restore and re-sign-in retries against an unreachable homeserver. The restore's caller sees the existing busy outcome. Other identity transitions are still drained. Verified: just test, just lint --- .../repositories/PubkyIdentityOperations.kt | 30 +++++--- .../java/to/bitkit/repositories/PubkyRepo.kt | 12 ++-- .../PubkyIdentityOperationsTest.kt | 72 +++++++++++++++++++ 3 files changed, 101 insertions(+), 13 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkyIdentityOperations.kt b/app/src/main/java/to/bitkit/repositories/PubkyIdentityOperations.kt index 961f1d03db..172858d3d3 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyIdentityOperations.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyIdentityOperations.kt @@ -3,10 +3,13 @@ package to.bitkit.repositories import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Job import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.isActive import kotlinx.coroutines.withContext import to.bitkit.utils.AppError import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.CoroutineContext +import kotlin.coroutines.cancellation.CancellationException /** Admission covers local completion and rollback as well as the native session change. */ internal class PubkyIdentityOperations( @@ -19,18 +22,24 @@ internal class PubkyIdentityOperations( private var wiping = false private var wipeOperation: Operation? = null - suspend fun transition(block: suspend () -> T): T { + /** A wipe cancels a retryable [cancelOnWipe] transition (a restore); its caller sees [PubkyIdentityBusy]. */ + suspend fun transition(cancelOnWipe: Boolean = false, block: suspend () -> T): T { currentCoroutineContext()[Operation]?.takeIf { it.owner === this }?.let { check(synchronized(lock) { it in active }) { "Pubky operation has already finished" } return block() } val operation = synchronized(lock) { if (wiping || removal != null) throw PubkyIdentityBusy - Operation(this).also(active::add) + Operation(this, cancelOnWipe).also(active::add) } - return run(operation) { - beforeTransition() - block() + return try { + run(operation) { + beforeTransition() + block() + } + } catch (e: CancellationException) { + if (operation.isCancelled && currentCoroutineContext().isActive) throw PubkyIdentityBusy + throw e } } @@ -64,10 +73,10 @@ internal class PubkyIdentityOperations( val (draining, cancelled) = synchronized(lock) { if (wiping) throw PubkyIdentityBusy wiping = true - active.toList() to removal + active.toList() to (active.filter { it.cancelOnWipe } + listOfNotNull(removal)) } // Revoke and drain before the SDK barrier; no monitor or session mutex is held while awaiting cleanup. - cancelled?.cancel() + cancelled.forEach { it.cancel() } try { beforeWipeDrain() draining.forEach { it.drained.await() } @@ -90,6 +99,7 @@ internal class PubkyIdentityOperations( try { return withContext(operation) { operation.bind(requireNotNull(currentCoroutineContext()[Job])) + currentCoroutineContext().ensureActive() block() } } finally { @@ -101,13 +111,17 @@ internal class PubkyIdentityOperations( } } - private class Operation(val owner: PubkyIdentityOperations) : AbstractCoroutineContextElement(Key) { + private class Operation( + val owner: PubkyIdentityOperations, + val cancelOnWipe: Boolean = false, + ) : AbstractCoroutineContextElement(Key) { companion object Key : CoroutineContext.Key private val lock = Any() private var job: Job? = null private var cancelled = false val drained = CompletableDeferred() + val isCancelled get() = synchronized(lock) { cancelled } fun bind(job: Job) { val cancelNow = synchronized(lock) { diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 079b4f47e5..bca9ce2950 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -493,8 +493,10 @@ class PubkyRepo @Inject constructor( } } - private suspend fun identityTransition(operation: suspend () -> Result): Result = - runSuspendCatching { identityOperations.transition { operation().getOrThrow() } } + private suspend fun identityTransition( + cancelOnWipe: Boolean = false, + operation: suspend () -> Result, + ): Result = runSuspendCatching { identityOperations.transition(cancelOnWipe) { operation().getOrThrow() } } fun profileOwner(): PubkyProfileOwner { val revision = storedIdentityRevision.get() @@ -587,7 +589,7 @@ class PubkyRepo @Inject constructor( } private suspend fun initializeForRevision(expectedRevision: Long? = null): Result = - identityTransition { initializeForRevisionAdmitted(expectedRevision) } + identityTransition(cancelOnWipe = true) { initializeForRevisionAdmitted(expectedRevision) } private suspend fun initializeForRevisionAdmitted( expectedRevision: Long? = null, @@ -610,7 +612,7 @@ class PubkyRepo @Inject constructor( } suspend fun restoreSessionIfNeeded(): Boolean = try { - identityOperations.transition { restoreSessionIfNeededAdmitted() } + identityOperations.transition(cancelOnWipe = true) { restoreSessionIfNeededAdmitted() } } catch (_: PubkyIdentityBusy) { false } catch (_: ProfileRemovalPending) { @@ -681,7 +683,7 @@ class PubkyRepo @Inject constructor( } private suspend fun restoreSession(expectedGeneration: Long? = null): Boolean = try { - identityOperations.transition { restoreSessionAdmitted(expectedGeneration) } + identityOperations.transition(cancelOnWipe = true) { restoreSessionAdmitted(expectedGeneration) } } catch (_: PubkyIdentityBusy) { false } catch (_: ProfileRemovalPending) { diff --git a/app/src/test/java/to/bitkit/repositories/PubkyIdentityOperationsTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyIdentityOperationsTest.kt index 8fd7ee3c23..1591b49f68 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyIdentityOperationsTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyIdentityOperationsTest.kt @@ -1,5 +1,6 @@ package to.bitkit.repositories +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.NonCancellable @@ -10,10 +11,12 @@ import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import org.junit.Test +import to.bitkit.ext.runSuspendCatching import kotlin.coroutines.CoroutineContext import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse +import kotlin.test.assertIs import kotlin.test.assertTrue @OptIn(ExperimentalCoroutinesApi::class) @@ -125,6 +128,75 @@ class PubkyIdentityOperationsTest { } } + @Test + fun `wipe cancels an admitted session restore and its caller sees busy`() = runTest { + val operations = PubkyIdentityOperations() + var outcome: Result? = null + val restore = launch { + outcome = runSuspendCatching { operations.transition(cancelOnWipe = true) { awaitCancellation() } } + } + runCurrent() + var wiped = false + val wipe = launch { operations.wipe { wiped = true } } + runCurrent() + restore.join() + wipe.join() + + assertTrue(wiped) + assertTrue(outcome?.exceptionOrNull() is PubkyIdentityBusy) + } + + @Test + fun `wipe still drains an ordinary transition next to a cancelled restore`() = runTest { + val operations = PubkyIdentityOperations() + val save = CompletableDeferred() + var saved = false + var outcome: Result? = null + val restore = launch { + outcome = runSuspendCatching { operations.transition(cancelOnWipe = true) { awaitCancellation() } } + } + val transition = launch { + operations.transition { + save.await() + saved = true + } + } + runCurrent() + val wipe = launch { operations.wipe { assertTrue(saved) } } + try { + runCurrent() + assertTrue(restore.isCompleted) + assertIs(outcome?.exceptionOrNull()) + assertFalse(wipe.isCompleted) + save.complete(Unit) + transition.join() + wipe.join() + } finally { + save.complete(Unit) + transition.cancel() + wipe.cancel() + } + } + + @Test + fun `a restore cancelled by its own caller stays cancelled`() = runTest { + val operations = PubkyIdentityOperations() + var error: Throwable? = null + val restore = launch { + try { + operations.transition(cancelOnWipe = true) { awaitCancellation() } + } catch (e: Throwable) { + error = e + throw e + } + } + runCurrent() + restore.cancel() + restore.join() + + assertIs(error) + } + @Test fun `ended context cannot authorize later work and nested wipe cannot self-deadlock`() = runTest { val operations = PubkyIdentityOperations() From 94c7e21d838db67bf441721bc172c8fea5394940 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Thu, 3 Dec 2026 08:08:02 +0100 Subject: [PATCH 57/61] fix: retry the session restore when reset fails Verified: just compile, just test, just lint --- .../repositories/PubkyIdentityOperations.kt | 11 +++- .../java/to/bitkit/repositories/PubkyRepo.kt | 34 ++++++++---- .../PubkyIdentityOperationsTest.kt | 52 +++++++++++++++++++ 3 files changed, 85 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkyIdentityOperations.kt b/app/src/main/java/to/bitkit/repositories/PubkyIdentityOperations.kt index 172858d3d3..4d044c197f 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyIdentityOperations.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyIdentityOperations.kt @@ -15,12 +15,14 @@ import kotlin.coroutines.cancellation.CancellationException internal class PubkyIdentityOperations( private val beforeTransition: suspend () -> Unit = {}, private val beforeWipeDrain: () -> Unit = {}, + private val afterInterruptedRestore: () -> Unit = {}, ) { private val lock = Any() private val active = mutableSetOf() private var removal: Operation? = null private var wiping = false private var wipeOperation: Operation? = null + private var restoreRefused = false /** A wipe cancels a retryable [cancelOnWipe] transition (a restore); its caller sees [PubkyIdentityBusy]. */ suspend fun transition(cancelOnWipe: Boolean = false, block: suspend () -> T): T { @@ -29,6 +31,7 @@ internal class PubkyIdentityOperations( return block() } val operation = synchronized(lock) { + if (wiping && cancelOnWipe) restoreRefused = true if (wiping || removal != null) throw PubkyIdentityBusy Operation(this, cancelOnWipe).also(active::add) } @@ -68,6 +71,7 @@ internal class PubkyIdentityOperations( } } + /** A wipe that fails after cancelling or refusing a restore calls [afterInterruptedRestore] to run it again. */ suspend fun wipe(block: suspend () -> T): T { check(currentCoroutineContext()[Operation]?.owner !== this) { "Pubky operation cannot start a wallet wipe" } val (draining, cancelled) = synchronized(lock) { @@ -77,6 +81,7 @@ internal class PubkyIdentityOperations( } // Revoke and drain before the SDK barrier; no monitor or session mutex is held while awaiting cleanup. cancelled.forEach { it.cancel() } + var wiped = false try { beforeWipeDrain() draining.forEach { it.drained.await() } @@ -86,12 +91,14 @@ internal class PubkyIdentityOperations( wipeOperation = it } } - return run(operation, block) + return run(operation, block).also { wiped = true } } finally { - synchronized(lock) { + val restoreInterrupted = synchronized(lock) { wiping = false wipeOperation = null + (restoreRefused || cancelled.any { it.cancelOnWipe }).also { restoreRefused = false } } + if (!wiped && restoreInterrupted) afterInterruptedRestore() } } diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index bca9ce2950..6b201b7ed0 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -29,6 +29,7 @@ import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow @@ -245,8 +246,11 @@ class PubkyRepo @Inject constructor( private val scope = appScope(ioDispatcher, TAG) private val serviceInitializeMutex = Mutex() private val initializeMutex = Mutex() - private val identityOperations = - PubkyIdentityOperations(::requireNoPendingRemoval, pubkyService::revokeProfileLogout) + private val identityOperations = PubkyIdentityOperations( + beforeTransition = ::requireNoPendingRemoval, + beforeWipeDrain = pubkyService::revokeProfileLogout, + afterInterruptedRestore = { scope.launch { resumeInterruptedRestore() } }, + ) private val deferredRestoreMutex = Mutex() private var deferredRestoreGeneration: Long? = null private val completedRestoreVersion = AtomicLong() @@ -478,6 +482,8 @@ class PubkyRepo @Inject constructor( init { scope.launch { initialize() }.invokeOnCompletion { + // A wipe can cancel startup before the restore clears this flag itself. + _isRestoringSession.update { false } initializationReady.complete(Unit) } } @@ -636,6 +642,11 @@ class PubkyRepo @Inject constructor( restored } + private suspend fun resumeInterruptedRestore() { + if (!restoreSessionIfNeeded() && _publicKey.value != null) loadIdentityData() + checkAdoptedSource() + } + /** Retries a temporarily unavailable saved session while the caller remains active. */ suspend fun retryDeferredSessionRestoration() = withContext(ioDispatcher) { deferredRestoreMutex.withLock { @@ -788,14 +799,17 @@ class PubkyRepo @Inject constructor( withContext(ioDispatcher) { serviceInitializeMutex.withLock { if (isServiceInitialized) return@withLock null - val importedSession = if (savedSessionSecret.isNullOrEmpty()) { - pubkyService.initialize() - null - } else { - pubkyService.initializeAndImportSession(savedSessionSecret) - } - isServiceInitialized = true - importedSession + // The native call is not interruptible, so record it even when a wipe cancels the restore. + withContext(NonCancellable) { + val importedSession = if (savedSessionSecret.isNullOrEmpty()) { + pubkyService.initialize() + null + } else { + pubkyService.initializeAndImportSession(savedSessionSecret) + } + isServiceInitialized = true + importedSession + }.also { currentCoroutineContext().ensureActive() } } } diff --git a/app/src/test/java/to/bitkit/repositories/PubkyIdentityOperationsTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyIdentityOperationsTest.kt index 1591b49f68..2158136cca 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyIdentityOperationsTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyIdentityOperationsTest.kt @@ -178,6 +178,58 @@ class PubkyIdentityOperationsTest { } } + @Test + fun `a failed wipe that cancelled a restore lets the restore run again`() = runTest { + var retries = 0 + val operations = PubkyIdentityOperations(afterInterruptedRestore = { retries++ }) + val restore = launch { + runSuspendCatching { operations.transition(cancelOnWipe = true) { awaitCancellation() } } + } + runCurrent() + val wipe = runSuspendCatching { operations.wipe { error("stop failed") } } + restore.join() + + assertIs(wipe.exceptionOrNull()) + assertEquals(1, retries) + assertEquals(Unit, operations.transition(cancelOnWipe = true) {}) + } + + @Test + fun `a failed wipe retries a restore it refused while wiping`() = runTest { + var retries = 0 + val operations = PubkyIdentityOperations(afterInterruptedRestore = { retries++ }) + val stop = CompletableDeferred() + val wipe = launch { + runSuspendCatching { + operations.wipe { + stop.await() + error("stop failed") + } + } + } + runCurrent() + assertFailsWith { operations.transition(cancelOnWipe = true) {} } + stop.complete(Unit) + wipe.join() + + assertEquals(1, retries) + } + + @Test + fun `a wipe retries no restore when it completes or cancelled none`() = runTest { + var retries = 0 + val operations = PubkyIdentityOperations(afterInterruptedRestore = { retries++ }) + val restore = launch { + runSuspendCatching { operations.transition(cancelOnWipe = true) { awaitCancellation() } } + } + runCurrent() + operations.wipe {} + restore.join() + runSuspendCatching { operations.wipe { error("stop failed") } } + + assertEquals(0, retries) + } + @Test fun `a restore cancelled by its own caller stays cancelled`() = runTest { val operations = PubkyIdentityOperations() From f166072cd639fd7deff4d5d15d11ad8ced824adf Mon Sep 17 00:00:00 2001 From: ovitrif Date: Thu, 3 Dec 2026 10:26:17 +0100 Subject: [PATCH 58/61] fix: keep resumed restores out of pending teardown Verified: just compile, just test, just lint --- .../java/to/bitkit/repositories/PubkyRepo.kt | 11 +++- .../to/bitkit/repositories/PubkyRepoTest.kt | 63 +++++++++++++++++++ 2 files changed, 71 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 6b201b7ed0..066f5916b0 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -483,7 +483,7 @@ class PubkyRepo @Inject constructor( init { scope.launch { initialize() }.invokeOnCompletion { // A wipe can cancel startup before the restore clears this flag itself. - _isRestoringSession.update { false } + if (!initializationReady.isCompleted) _isRestoringSession.update { false } initializationReady.complete(Unit) } } @@ -643,8 +643,13 @@ class PubkyRepo @Inject constructor( } private suspend fun resumeInterruptedRestore() { - if (!restoreSessionIfNeeded() && _publicKey.value != null) loadIdentityData() - checkAdoptedSource() + runSuspendCatching { + identityOperations.transition(cancelOnWipe = true) { + if (requiresProfileRecovery()) return@transition + if (!restoreSessionIfNeededAdmitted() && _publicKey.value != null) loadIdentityData() + checkAdoptedSourceAdmitted() + } + } } /** Retries a temporarily unavailable saved session while the caller remains active. */ diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 69ca18cad2..3e8f704313 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -359,6 +359,69 @@ class PubkyRepoTest : BaseUnitTest() { verify(pubkyService).forgetLocalProfileAccess() } + @Test + fun `failed wipe after pending removal does not resume identity loads`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + advanceUntilIdle() + val id = UUID.randomUUID().toString() + val wipeEntered = CompletableDeferred() + val failWipe = CompletableDeferred() + val wipe = async { + runSuspendCatching { + sut.withWalletWipeAdmission { + wipeEntered.complete(Unit) + failWipe.await() + profileRemovalStore.withAccess(id) { profileRemovalStore.begin(id) } + error("wipeStorage failed") + } + } + } + wipeEntered.await() + assertFalse(sut.restoreSessionIfNeeded()) + clearInvocations(pubkyService) + failWipe.complete(Unit) + assertTrue(wipe.await().isFailure) + advanceUntilIdle() + assertTrue(sut.requiresProfileRecovery()) + verify(pubkyService, never()).fetchPaykitProfile(any()) + verify(pubkyService, never()).fetchPubkyProfileWithRevision(any()) + verify(pubkyService, never()).observedContactRecords(any()) + } + + @Test + fun `startup tail does not clear a later restore in flight`() = test { + advanceUntilIdle() + stubAdoptedRingSource() + whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn("saved_session") + whenever(sharedPubkyClient.ringCredential(any())).thenReturn(Result.failure(TestAppError("Unavailable"))) + val ringCheck = CompletableDeferred() + whenever { sharedPubkyClient.listRingIdentities() }.doSuspendableAnswer { + ringCheck.await() + Result.success(persistentListOf(VALID_SELF_KEY.removePrefix("pubky"))) + } + val retryImport = CompletableDeferred() + var imports = 0 + whenever { pubkyService.importSession("saved_session") }.doSuspendableAnswer { + if (imports++ == 0) throw TestAppError("Offline") + retryImport.await() + VALID_SELF_KEY + } + val restarted = createSut() + restarted.awaitInitialization() + runCurrent() + assertFalse(restarted.isRestoringSession.value) + + val retry = async { restarted.restoreSessionIfNeeded() } + runCurrent() + assertTrue(restarted.isRestoringSession.value, "retry restore should be in flight") + ringCheck.complete(Unit) + runCurrent() + assertTrue(restarted.isRestoringSession.value, "startup completion cleared the in-flight restore flag") + retryImport.complete(Unit) + retry.await() + assertFalse(restarted.isRestoringSession.value) + } + private val pubkyService = mock() private val keychain = mock() private val sharedPubkyClient = mock() From d22508b31c09bf0a6ea11207d4229c0f2dd45d38 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Thu, 3 Dec 2026 12:23:43 +0100 Subject: [PATCH 59/61] fix: stop queued paykit work from delaying reset Verified: just compile, just test, just lint --- .../java/to/bitkit/repositories/PubkyRepo.kt | 5 ++++- .../bitkit/services/PaykitSdkOperationLock.kt | 16 +++++++++++++++- .../to/bitkit/services/PaykitSdkService.kt | 6 ++++++ .../java/to/bitkit/services/PubkyService.kt | 2 ++ .../services/PaykitSdkOperationLockTest.kt | 19 +++++++++++++++++++ 5 files changed, 46 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 066f5916b0..0d3175e23f 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -85,6 +85,7 @@ import to.bitkit.services.PaykitProfileLogout import to.bitkit.services.PaykitReadLane import to.bitkit.services.PaykitReadTimeoutError import to.bitkit.services.PubkyService +import to.bitkit.services.isWalletWipeInProgress import to.bitkit.utils.AppError import to.bitkit.utils.Logger import java.io.ByteArrayOutputStream @@ -248,7 +249,7 @@ class PubkyRepo @Inject constructor( private val initializeMutex = Mutex() private val identityOperations = PubkyIdentityOperations( beforeTransition = ::requireNoPendingRemoval, - beforeWipeDrain = pubkyService::revokeProfileLogout, + beforeWipeDrain = pubkyService::beginWalletWipe, afterInterruptedRestore = { scope.launch { resumeInterruptedRestore() } }, ) private val deferredRestoreMutex = Mutex() @@ -1034,6 +1035,7 @@ class PubkyRepo @Inject constructor( var completed = false try { runSuspendCatching { pubkyService.signIn(secretKeyHex) }.getOrElse { + if (it.isWalletWipeInProgress()) throw it val hasIdentityRecord = runSuspendCatching { pubkyService.hasIdentityRecord(publicKey) } .onFailure { Logger.warn("Failed to check ring identity record", it, context = TAG) } .getOrNull() @@ -1339,6 +1341,7 @@ class PubkyRepo @Inject constructor( runSuspendCatching { pubkyService.signUp(secretKeyHex, signupDetails.first, signupDetails.second) }.getOrElse { + if (it.isWalletWipeInProgress()) throw it Logger.warn("Retrying sign in after sign up failed", it, context = TAG) pubkyService.signIn(secretKeyHex) } diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkOperationLock.kt b/app/src/main/java/to/bitkit/services/PaykitSdkOperationLock.kt index b97d98d5d8..cb454ace3e 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkOperationLock.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkOperationLock.kt @@ -10,6 +10,12 @@ import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.CoroutineContext import kotlin.coroutines.cancellation.CancellationException +private const val WALLET_WIPE_IN_PROGRESS = "wallet_wipe_in_progress" + +/** A wallet wipe refused this SDK call; callers must not fall back to another native call. */ +internal fun Throwable.isWalletWipeInProgress() = + this is PaykitException.Storage && code == WALLET_WIPE_IN_PROGRESS + internal class PaykitSdkOperationLock( private val checkRecoveryAccess: suspend () -> Unit = {}, ) { @@ -161,6 +167,14 @@ internal class PaykitSdkOperationLock( } } + /** + * Fails callers admitted so far once they reach the lock, so wipe drains never wait on their queued native calls. + * Admission stays open; [withWalletWipe] still takes the barrier later. + */ + fun revokeAdmittedOperations() { + synchronized(stateLock) { if (!isWiping) generation++ } + } + suspend fun withWalletWipe(operation: suspend () -> T): T { check(currentCoroutineContext()[ProfileRemoval] == null) { "Profile removal cannot start a wallet wipe" } val removal = synchronized(stateLock) { @@ -245,7 +259,7 @@ internal class PaykitSdkOperationLock( } private fun wipeError() = PaykitException.Storage( - code = "wallet_wipe_in_progress", + code = WALLET_WIPE_IN_PROGRESS, context = "Paykit operation interrupted by wallet wipe", ) diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt index 7a86b78f89..d96435dc0c 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt @@ -2133,6 +2133,12 @@ class PaykitSdkService @Inject constructor( } } + /** Wipe admission: revoke the captured logout and fail SDK work admitted before the wipe. */ + internal fun beginWalletWipe() { + revokeProfileLogout() + operationLock.revokeAdmittedOperations() + } + suspend fun withWalletWipe(operation: suspend () -> T): T { revokeProfileLogout() // Drain setup before closing admission, so cleanup cannot await setup queued behind its own barrier. diff --git a/app/src/main/java/to/bitkit/services/PubkyService.kt b/app/src/main/java/to/bitkit/services/PubkyService.kt index b3df230b47..2aac52a985 100644 --- a/app/src/main/java/to/bitkit/services/PubkyService.kt +++ b/app/src/main/java/to/bitkit/services/PubkyService.kt @@ -99,6 +99,8 @@ class PubkyService @Inject constructor( internal fun revokeProfileLogout() = paykitSdkService.revokeProfileLogout() + internal fun beginWalletWipe() = paykitSdkService.beginWalletWipe() + internal suspend fun requireWalletWipe() = paykitSdkService.requireWalletWipe() suspend fun clearSessionAccess() = ServiceQueue.PUBKY.background { diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkOperationLockTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkOperationLockTest.kt index e68e3ec801..16f3d3e5f4 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkOperationLockTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkOperationLockTest.kt @@ -412,6 +412,25 @@ class PaykitSdkOperationLockTest { assertEquals("fresh", lock.withoutLock { "fresh" }) } + @Test + fun `revoked admission fails queued work at the lock and admits later work`() = runTest { + val lock = PaykitSdkOperationLock() + val holder = CompletableDeferred() + val active = launch { lock.withLock { holder.await() } } + runCurrent() + var ran = false + val queued = async { assertFailsWith { lock.withLock { ran = true } } } + runCurrent() + + lock.revokeAdmittedOperations() + holder.complete(Unit) + active.join() + + assertTrue(queued.await().isWalletWipeInProgress()) + assertFalse(ran) + assertEquals(1, lock.withLock { 1 }) + } + @Test fun `cancelled queued operation never executes`() = runTest { val lock = PaykitSdkOperationLock() From e53c2a7e384e0e67afbddc5a47955dd88e157af5 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Thu, 3 Dec 2026 13:35:27 +0100 Subject: [PATCH 60/61] fix: detect wipe refusals through wrapped errors Verified: just compile, just test, just lint --- .../to/bitkit/services/PaykitSdkOperationLock.kt | 4 ++-- .../java/to/bitkit/repositories/PubkyRepoTest.kt | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkOperationLock.kt b/app/src/main/java/to/bitkit/services/PaykitSdkOperationLock.kt index cb454ace3e..d22734c61a 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkOperationLock.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkOperationLock.kt @@ -12,9 +12,9 @@ import kotlin.coroutines.cancellation.CancellationException private const val WALLET_WIPE_IN_PROGRESS = "wallet_wipe_in_progress" -/** A wallet wipe refused this SDK call; callers must not fall back to another native call. */ +/** A wallet wipe refused this SDK call, also through `ServiceQueue`'s [to.bitkit.utils.AppError] wrapping. */ internal fun Throwable.isWalletWipeInProgress() = - this is PaykitException.Storage && code == WALLET_WIPE_IN_PROGRESS + generateSequence(this) { it.cause }.any { it is PaykitException.Storage && it.code == WALLET_WIPE_IN_PROGRESS } internal class PaykitSdkOperationLock( private val checkRecoveryAccess: suspend () -> Unit = {}, diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 3e8f704313..c396bc07a3 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -107,6 +107,7 @@ import to.bitkit.services.PaykitReadLane import to.bitkit.services.PaykitSdkService import to.bitkit.services.PubkyRingAuthTimeoutError import to.bitkit.services.PubkyService +import to.bitkit.services.isWalletWipeInProgress import to.bitkit.test.BaseUnitTest import to.bitkit.test.forEachCase import to.bitkit.usecases.ProfileRemovalCoordinator @@ -1260,6 +1261,21 @@ class PubkyRepoTest : BaseUnitTest() { verifyBlocking(pubkyService) { signIn("secret") } } + @Test + fun `createIdentity stops without signing in when a wallet wipe refuses sign up`() = test { + val httpClient = identityHttpClient() + sut = createSut(httpClient) + stubSignupKeys() + val wipe = PaykitException.Storage("wallet_wipe_in_progress", "Paykit operation interrupted by wallet wipe") + whenever(pubkyService.signUp("secret", "test-homeserver", "test-code")).thenAnswer { throw AppError(wipe) } + + val result = sut.createIdentity("Test", "", emptyList(), emptyList(), null) + httpClient.close() + + assertTrue(result.exceptionOrNull()?.isWalletWipeInProgress() == true) + verifyBlocking(pubkyService, never()) { signIn(any()) } + } + @Test fun `createIdentity reports a transport failure without signing up again`() = test { val httpClient = identityHttpClient() From 84599e3d7891db7426076cf9d840cab8680d0580 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Thu, 3 Dec 2026 19:33:18 +0100 Subject: [PATCH 61/61] fix: release unwritten removal sessions and fail vss timeouts A profile removal whose durable marker never lands, by write failure or cancellation, now releases its session so Delete and Sign out can run again. The marker is read after any in-flight write settles. An LDK VSS setup timeout during deleteObjects is now a failed Result, so network graph and pathfinding score resets report it and restart paths run. Verified: just compile, just test, just lint --- .../to/bitkit/data/ProfileRemovalStore.kt | 3 + .../bitkit/data/backup/VssBackupClientLdk.kt | 4 +- .../usecases/ProfileRemovalCoordinator.kt | 12 +++- .../usecases/ProfileRemovalCoordinatorTest.kt | 56 ++++++++++++++++++- 4 files changed, 71 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt b/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt index 0532199073..d7c4b6ffa6 100644 --- a/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt +++ b/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt @@ -105,6 +105,9 @@ class ProfileRemovalStore internal constructor(private val store: DataStore, walletIndex: Int = 0): Result = withContext(ioDispatcher) { runSuspendCatching { coordinator.withWallet { - setup(walletIndex).getOrThrow() + setup(walletIndex).onFailure { + if (it is TimeoutCancellationException) throw BackupClientSetupTimeout(it) + }.getOrThrow() coordinator.withClient(VssClientCoordinator.Domain.LDK) { keys.forEach { vssLdkDelete(key = it, namespace = LdkNamespace.Default) } } diff --git a/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt b/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt index b74f620c49..3ddc33cbbd 100644 --- a/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt +++ b/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt @@ -312,7 +312,17 @@ class ProfileRemovalCoordinator @Inject constructor( } removalMayHaveStarted = true intent?.started?.set(true) - removalStore.begin(confirmation.attemptId) + // Cancellation is caught to roll back too, and getOrThrow rethrows it. + runCatching { removalStore.begin(confirmation.attemptId) }.onFailure { + // An unwritten marker means nothing durable or remote started: release the session. + val pending = withContext(NonCancellable) { + runCatching { removalStore.settledAttempt() } + } + if (pending.isSuccess && pending.getOrNull() == null) { + intent?.started?.set(false) + removalMayHaveStarted = false + } + }.getOrThrow() if (!confirmation.localOnly) { val original = checkNotNull(intent) { "An original live logout is required" } withContext(original.logout) { diff --git a/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt b/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt index 15f58f6f95..509e978f39 100644 --- a/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt +++ b/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt @@ -10,6 +10,7 @@ import com.synonym.paykit.PubkyGrantLogoutReceipt import com.synonym.paykit.PublicationStatus import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first @@ -497,13 +498,15 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { override suspend fun updateData( transform: suspend (ProfileRemovalState) -> ProfileRemovalState ): ProfileRemovalState { + val next = transform(data.value) + if (next == data.value) return next writes++ throw failure } }) val confirmation = sut.prepareLocalDisconnect(original).getOrThrow() - val result = assertIs(sut.remove(confirmation).exceptionOrNull()) - assertSame(failure, result.cause) + assertEquals(failure.message, assertIs(sut.remove(confirmation).exceptionOrNull()).message) + assertNull(sut.failureFor(confirmation)) assertEquals(1, writes) assertNull(store.pendingAttempt()) assertTrue(events.isEmpty()) @@ -811,6 +814,55 @@ class ProfileRemovalCoordinatorTest : BaseUnitTest() { assertTrue(events.isEmpty()) } + @Test + fun `failed durable begin releases the deletion session for a fresh confirmation`() = test { + val failure = IOException("pending marker not acknowledged") + store = ProfileRemovalStore(object : DataStore { + override val data = MutableStateFlow(ProfileRemovalState()) + override suspend fun updateData( + transform: suspend (ProfileRemovalState) -> ProfileRemovalState + ): ProfileRemovalState { + val next = transform(data.value) + if (next == data.value) return next + throw failure + } + }) + val confirmation = sut.prepareDeletion(original).getOrThrow() + + assertEquals(failure.message, assertIs(sut.remove(confirmation).exceptionOrNull()).message) + + assertNull(sut.failureFor(confirmation)) + assertFalse(logouts.single().isCurrent()) + verify(privateRepo, never()).removePublishedEndpointsForProfileRemoval(any()) + assertTrue(sut.prepareDeletion(original).isSuccess) + assertTrue(logouts.last().isCurrent()) + } + + @Test + fun `cancelled durable begin releases the deletion session`() = test { + val writing = CompletableDeferred() + store = ProfileRemovalStore(object : DataStore { + override val data = MutableStateFlow(ProfileRemovalState()) + override suspend fun updateData( + transform: suspend (ProfileRemovalState) -> ProfileRemovalState + ): ProfileRemovalState { + val next = transform(data.value) + if (next == data.value) return next + writing.complete(Unit) + awaitCancellation() + } + }) + val confirmation = sut.prepareDeletion(original).getOrThrow() + val removal = async { sut.remove(confirmation) } + writing.await() + + removal.cancelAndJoin() + + assertNull(sut.failureFor(confirmation)) + assertFalse(logouts.single().isCurrent()) + assertTrue(sut.prepareDeletion(original).isSuccess) + } + @Test fun `changed snapshot fails before durable marker and destructive work`() = test { whenever { pubky.validateProfileDeletion(deletion) }.thenAnswer { error("profile revision changed") }