diff --git a/app/src/androidTest/java/to/bitkit/ui/RootDestinationTest.kt b/app/src/androidTest/java/to/bitkit/ui/RootDestinationTest.kt index 4bfda7e9c2..e14fee0ea0 100644 --- a/app/src/androidTest/java/to/bitkit/ui/RootDestinationTest.kt +++ b/app/src/androidTest/java/to/bitkit/ui/RootDestinationTest.kt @@ -1,13 +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 { @@ -18,30 +24,131 @@ class RootDestinationTest { private fun setContent( 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, - walletExists = walletExists, - isRecoveryMode = isRecoveryMode, - 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) + listOf(TAG_CRITICAL, TAG_MIGRATION, TAG_MIGRATION_ERROR, TAG_ONBOARDING, TAG_WALLET, TAG_RESET) .filterNot { it == tag } .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, + 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")) + assertOnly(TAG_RESET) + } + + @Test + fun unreadableResetStateBlocksOrdinaryWallet() { + setContent(walletResetRecovery = WalletResetRecovery.Unavailable) + assertOnly(TAG_RESET) + } + + @Test + fun corruptedResetStateDoesNotOpenWalletOrOnboarding() { + setContent(walletExists = false, isRecoveryMode = true, walletResetRecovery = WalletResetRecovery.Unreadable("test")) + assertOnly(TAG_RESET) + } + + @Test + fun loadingResetStateBlocksOnboarding() { + setContent(walletExists = false, walletResetRecovery = WalletResetRecovery.Loading) + assertOnly(TAG_RESET) + } + @Test fun whenCriticalUpdateRequiredDuringMigration_shouldShowCriticalUpdateOnly() { setContent(isCriticalUpdateRequired = true, isShowingMigrationLoading = true) @@ -108,5 +215,8 @@ 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" + +private const val TAG_RESET = "TestWalletReset" 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..506ee64ee1 --- /dev/null +++ b/app/src/androidTest/java/to/bitkit/ui/screens/profile/ProfileRecoveryContentTest.kt @@ -0,0 +1,139 @@ +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.espresso.Espresso.pressBackUnconditionally +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 + var back = 0 + compose.setContent { + AppThemeSurface { + CompositionLocalProvider(LocalInspectionMode provides true) { + ProfileContent( + uiState = state, + onBackClick = { back++ }, + 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__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() + 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() + compose.onNodeWithTag("NavigationBack").performClick() + compose.onNodeWithTag("HeaderMenu").assertDoesNotExist() + pressBackUnconditionally() + compose.onNodeWithTag("ProfileRecoveryDisconnect").assertIsDisplayed() + compose.runOnIdle { assertEquals(0, back) } + } + + @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, + onLocalDisconnect = { error("Fresh local disconnect is not part of this recovery scenario") }, + onDismissAddLinkSheet = {}, onSaveLink = { _, _ -> }, onDismissAddTagSheet = {}, onSaveTag = {}, + ) + } + } + } + } +} 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 new file mode 100644 index 0000000000..12a1189647 --- /dev/null +++ b/app/src/androidTest/java/to/bitkit/ui/screens/recovery/WalletResetRecoveryTest.kt @@ -0,0 +1,213 @@ +package to.bitkit.ui.screens.recovery + +import android.os.SystemClock +import androidx.compose.material3.Text +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LifecycleRegistry +import androidx.lifecycle.compose.LocalLifecycleOwner +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.performClick +import org.junit.Rule +import org.junit.Test +import to.bitkit.data.WalletResetRecovery +import to.bitkit.test.annotations.ComposeUi +import to.bitkit.ui.theme.AppThemeSurface +import kotlin.test.assertEquals + +@ComposeUi +class WalletResetRecoveryTest { + @get:Rule + val rule = createComposeRule() + + @Test + fun resetRequiresFreshConfirmationAndCancelDoesNothing() { + val finished = mutableListOf() + rule.setContent { + AppThemeSurface { + WalletResetRecoveryContent(WalletResetRecovery.Pending("original"), false, {}, finished::add) + } + } + rule.onNodeWithTag("WalletResetFinish").performClick() + rule.runOnIdle { assertEquals(emptyList(), finished) } + rule.onNodeWithTag("DialogCancel").performClick() + rule.runOnIdle { assertEquals(emptyList(), finished) } + val dismissedAt = SystemClock.uptimeMillis() + rule.waitUntil(1_000) { SystemClock.uptimeMillis() - dismissedAt >= 600 } + rule.onNodeWithTag("WalletResetFinish").performClick() + rule.onNodeWithTag("DialogConfirm").performClick() + rule.runOnIdle { assertEquals(listOf("original"), finished) } + } + + @Test + fun changedAttemptDiscardsTheOldConfirmation() { + val recovery = mutableStateOf(WalletResetRecovery.Pending("old")) + val finished = mutableListOf() + rule.setContent { + AppThemeSurface { WalletResetRecoveryContent(recovery.value, false, {}, finished::add) } + } + rule.onNodeWithTag("WalletResetFinish").performClick() + rule.runOnIdle { recovery.value = WalletResetRecovery.Pending("new") } + rule.onNodeWithTag("DialogConfirm").assertDoesNotExist() + rule.runOnIdle { assertEquals(emptyList(), finished) } + } + + @Test + fun activeWipeShowsOnlyProgressUntilUnwind() { + val recovery = mutableStateOf(WalletResetRecovery.Unavailable) + val busy = mutableStateOf(true) + var reads = 0 + val finished = mutableListOf() + rule.setContent { + AppThemeSurface { WalletResetRecoveryContent(recovery.value, busy.value, { reads++ }, finished::add) } + } + rule.onNodeWithTag("WalletResetFinish").assertDoesNotExist() + rule.onNodeWithTag("WalletResetProgress").assertExists() + rule.onNodeWithTag("WalletResetReadRetry").assertDoesNotExist() + rule.onNodeWithTag("WalletResetShowPhrase").assertIsNotEnabled() + rule.runOnIdle { busy.value = false } + rule.onNodeWithTag("WalletResetReadRetry").performClick() + rule.runOnIdle { + assertEquals(1, reads) + assertEquals(emptyList(), finished) + recovery.value = WalletResetRecovery.Pending("pending") + busy.value = true + } + rule.onNodeWithTag("WalletResetFinish").assertDoesNotExist() + rule.onNodeWithTag("WalletResetProgress").assertExists() + rule.runOnIdle { assertEquals(emptyList(), finished) } + } + + @Test + fun unknownMarkerOffersPhraseWithoutAdmittingReset() { + var shown = 0 + var reads = 0 + val finished = mutableListOf() + rule.setContent { + AppThemeSurface { + WalletResetRecoveryContent( + 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) + assertEquals(emptyList(), finished) + } + rule.onNodeWithTag("WalletResetFinish").performClick() + rule.onNodeWithTag("DialogCancel").performClick() + rule.runOnIdle { assertEquals(emptyList(), finished) } + } + + @Test + fun phraseGrantIsRevokedByBackgroundAndLateAuthCannotReturn() { + val lifecycle = object : LifecycleOwner { + override val lifecycle = LifecycleRegistry.createUnsafe(this).apply { + currentState = Lifecycle.State.RESUMED + } + } + val pinRequired = mutableStateOf(null) + var authenticate: (() -> Unit)? = null + var phraseEntries = 0 + var phraseDisposals = 0 + rule.setContent { + CompositionLocalProvider(LocalLifecycleOwner provides lifecycle) { + AppThemeSurface { + WalletResetRecoveryFlow( + recovery = WalletResetRecovery.Unreadable("original"), busy = false, + pinEnabled = pinRequired.value, isCurrent = { true }, onRetry = {}, onFinish = {}, + authentication = { success, _ -> + authenticate = success + Text("auth", Modifier.testTag("RecoveryAuth")) + }, + phrase = { + DisposableEffect(Unit) { + phraseEntries++ + onDispose { phraseDisposals++ } + } + Text("read-only placeholder", Modifier.testTag("RecoveryPhrase")) + }, + ) + } + } + } + rule.onNodeWithTag("WalletResetShowPhrase").assertIsNotEnabled() + rule.runOnIdle { pinRequired.value = true } + rule.onNodeWithTag("WalletResetShowPhrase").performClick() + rule.onNodeWithTag("RecoveryAuth").assertExists() + rule.onNodeWithTag("RecoveryPhrase").assertDoesNotExist() + rule.runOnIdle { requireNotNull(authenticate).invoke() } + rule.onNodeWithTag("RecoveryPhrase").assertExists() + rule.runOnIdle { lifecycle.lifecycle.currentState = Lifecycle.State.CREATED } + rule.onNodeWithTag("RecoveryPhrase").assertDoesNotExist() + rule.runOnIdle { + assertEquals(1, phraseEntries) + assertEquals(1, phraseDisposals) + lifecycle.lifecycle.currentState = Lifecycle.State.RESUMED + requireNotNull(authenticate).invoke() + } + rule.onNodeWithTag("RecoveryPhrase").assertDoesNotExist() + } + + @Test + fun rawAdmissionAndAttemptChangesRejectQueuedPhraseComposition() { + val recovery = mutableStateOf(WalletResetRecovery.Unreadable("original")) + val busy = mutableStateOf(false) + var admitted = true + var authenticate: (() -> Unit)? = null + var phraseEntries = 0 + rule.setContent { + AppThemeSurface { + WalletResetRecoveryFlow( + recovery = recovery.value, busy = busy.value, pinEnabled = true, + isCurrent = { admitted }, onRetry = {}, onFinish = {}, + authentication = { success, _ -> + authenticate = success + Text("auth", Modifier.testTag("RecoveryAuth")) + }, + phrase = { + DisposableEffect(Unit) { phraseEntries++; onDispose {} } + Text("read-only placeholder", Modifier.testTag("RecoveryPhrase")) + }, + ) + } + } + rule.onNodeWithTag("WalletResetShowPhrase").performClick() + rule.onNodeWithTag("RecoveryAuth").assertExists() + val oldAuth = requireNotNull(authenticate) + rule.runOnIdle { + oldAuth() + admitted = false + } + rule.onNodeWithTag("RecoveryPhrase").assertDoesNotExist() + rule.runOnIdle { + assertEquals(0, phraseEntries) + recovery.value = WalletResetRecovery.Unreadable("replacement") + admitted = true + } + rule.runOnIdle { oldAuth() } + rule.onNodeWithTag("RecoveryPhrase").assertDoesNotExist() + rule.onNodeWithTag("WalletResetShowPhrase").performClick() + rule.onNodeWithTag("RecoveryAuth").assertExists() + rule.runOnIdle { busy.value = true } + rule.runOnIdle { requireNotNull(authenticate).invoke() } + rule.onNodeWithTag("RecoveryPhrase").assertDoesNotExist() + rule.onNodeWithTag("WalletResetProgress").assertExists() + rule.runOnIdle { assertEquals(0, phraseEntries) } + } +} diff --git a/app/src/main/java/to/bitkit/data/PrivatePaykitStores.kt b/app/src/main/java/to/bitkit/data/PrivatePaykitStores.kt index ab7cd6f545..0bb2d8eaf1 100644 --- a/app/src/main/java/to/bitkit/data/PrivatePaykitStores.kt +++ b/app/src/main/java/to/bitkit/data/PrivatePaykitStores.kt @@ -12,6 +12,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.serialization.Serializable +import kotlinx.serialization.Transient import to.bitkit.di.json import to.bitkit.models.PubkyPublicKeyFormat import to.bitkit.utils.Logger @@ -138,6 +139,7 @@ data class PrivatePaykitCacheData( val contacts: Map = emptyMap(), val cleanupPending: Boolean = false, val deletedContactCleanupPendingPublicKeys: Set = emptySet(), + @Transient internal val receiptSourceReadable: Boolean = true, ) @Serializable @@ -172,6 +174,7 @@ data class PrivatePaykitReservationData( val publicAssignments: Map = emptyMap(), val quarantinedPublicAddresses: Set = emptySet(), val restoredReservedReceiveIndexCeilingsByAddressType: Map = emptyMap(), + @Transient internal val receiptSourceReadable: Boolean = true, ) @Serializable @@ -181,7 +184,7 @@ data class PrivatePaykitStoredAssignmentData( val address: String = "", ) -private object PrivatePaykitCacheSerializer : Serializer { +internal object PrivatePaykitCacheSerializer : Serializer { private const val TAG = "PrivatePaykitCacheSerializer" override val defaultValue: PrivatePaykitCacheData = PrivatePaykitCacheData() @@ -191,15 +194,16 @@ private object PrivatePaykitCacheSerializer : Serializer json.decodeFromString(input.readBytes().decodeToString()) }.getOrElse { Logger.error("Failed to deserialize PrivatePaykitCacheData", it, context = TAG) - defaultValue + defaultValue.copy(receiptSourceReadable = false) } override suspend fun writeTo(t: PrivatePaykitCacheData, output: OutputStream) { + check(t.receiptSourceReadable) { "Cannot persist an incomplete invoice cache" } output.write(json.encodeToString(t).encodeToByteArray()) } } -private object PrivatePaykitReservationSerializer : Serializer { +internal object PrivatePaykitReservationSerializer : Serializer { private const val TAG = "PrivatePaykitReservationSerializer" override val defaultValue: PrivatePaykitReservationData = PrivatePaykitReservationData() @@ -209,10 +213,11 @@ private object PrivatePaykitReservationSerializer : Serializer(input.readBytes().decodeToString()) }.getOrElse { Logger.error("Failed to deserialize PrivatePaykitReservationData", it, context = TAG) - defaultValue + defaultValue.copy(receiptSourceReadable = false) } override suspend fun writeTo(t: PrivatePaykitReservationData, output: OutputStream) { + check(t.receiptSourceReadable) { "Cannot persist an incomplete reservation ledger" } output.write(json.encodeToString(t).encodeToByteArray()) } } 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..d7c4b6ffa6 --- /dev/null +++ b/app/src/main/java/to/bitkit/data/ProfileRemovalStore.kt @@ -0,0 +1,314 @@ +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.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.ext.runSuspendCatching +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) + private val receiptSnapshotMutex = Mutex() + internal val generation: Long get() = observationRevision.value + + @OptIn(ExperimentalCoroutinesApi::class) + private val observedState: Flow = observationRevision.flatMapLatest { + store.data.map { it } + .retryWhen { _, attempt -> + 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 + } + + val walletResetRecovery: Flow = observedState.map { + when { + it == null -> WalletResetRecovery.Unavailable + it.attemptId == null || it.scope == ProfileRemovalScope.PROFILE -> WalletResetRecovery.Clear + it.scope == ProfileRemovalScope.WALLET_WIPE -> WalletResetRecovery.Pending(it.attemptId) + else -> WalletResetRecovery.Unreadable(it.attemptId) + } + } + + fun refreshWalletResetRecovery() = observationRevision.update { it + 1 } + + internal suspend fun requirePendingWalletReset(attemptId: String) { + val state = store.data.first() + if (state.attemptId != attemptId || state.scope == ProfileRemovalScope.PROFILE) { + throw ProfileRemovalPending() + } + } + + internal suspend fun pendingAttempt(): String? = store.data.first().attemptId + + /** Reads the marker after any in-flight write lands, which a cancelled writer cannot wait for itself. */ + internal suspend fun settledAttempt(): String? = store.updateData { it }.attemptId + + internal suspend fun pendingState(): ProfileRemovalState = store.data.first() + + internal suspend fun requireWalletAvailable() { + val state = store.data.first() + if (state.attemptId != null && state.scope != ProfileRemovalScope.PROFILE) { + throw ProfileRemovalPending() + } + } + + internal suspend fun requireNoPending() { + if (pendingAttempt() != null) throw ProfileRemovalPending() + } + + internal suspend fun requireAccess() { + val state = store.data.first() + val pending = state.attemptId ?: return + val access = currentCoroutineContext()[Access] + if (access?.store !== this || access.attemptId != pending || !access.active.get() || + state.scope != access.scope + ) { + throw ProfileRemovalPending() + } + access.job.ensureActive() + } + + /** Only for local completion after acknowledged credential teardown, while outer removal ownership is retained. */ + internal suspend fun requireCompletionAccess() { + val state = store.data.first() + val pending = state.attemptId ?: return + val access = currentCoroutineContext()[Access] + if (access?.store !== this || access.attemptId != pending || !access.active.get() || + state.scope != access.scope + ) { + throw ProfileRemovalPending() + } + } + + internal suspend fun withAccess( + attemptId: String, + scope: ProfileRemovalScope = ProfileRemovalScope.PROFILE, + operation: suspend () -> T, + ): T { + require(UUID.fromString(attemptId).toString() == attemptId) { "Invalid profile removal attempt" } + val state = store.data.first() + val pending = state.attemptId + check(pending == null || pending == attemptId) { "Another profile removal needs local recovery" } + check(pending == null || state.scope == scope || scope == ProfileRemovalScope.WALLET_WIPE) { + "Wallet cleanup must complete before profile recovery" + } + val access = Access(this, attemptId, scope, 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" } + check( + it.attemptId == null || it.scope == access.scope || + access.scope == ProfileRemovalScope.WALLET_WIPE + ) { "Wallet cleanup cannot become profile cleanup" } + it.copy(attemptId = attemptId, scope = access.scope) + } + 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 && it.scope == access.scope) { "Profile removal attempt changed" } + ProfileRemovalState() + } + observationRevision.update { it + 1 } + } + + /** Copy local associations only; never hold this gate over SDK, Core or address derivation. */ + internal suspend fun withReceiptSnapshot(read: suspend () -> T): T = receiptSnapshotMutex.withLock { + val state = readReceiptState() + if (state.localCleanupStarted) throw ReceiptAssociationsUnavailable() + val snapshot = read() + check(readReceiptState() == state) { "Receipt source changed while being copied" } + snapshot + } + + private suspend fun readReceiptState(): ProfileRemovalState { + val state = runSuspendCatching { store.data.first() }.getOrElse { throw ProfileRemovalPending(it) } + if (state.attemptId != null && state.scope != ProfileRemovalScope.PROFILE) throw ProfileRemovalPending() + return state + } + + internal suspend fun requireReceiptAccountingAccess() { readReceiptState() } + + /** A failed local clear remains unavailable after restart; admitted snapshots keep their own lifetime. */ + internal suspend fun withReceiptCleanup(clear: suspend () -> T): T = receiptSnapshotMutex.withLock { + armReceiptCleanup() + clear() + } + + internal suspend fun beginLocalCleanup() = receiptSnapshotMutex.withLock { armReceiptCleanup() } + + private suspend fun armReceiptCleanup() { + requireCompletionAccess() + store.updateData { state -> + check(state.attemptId != null) { "Durable cleanup admission is required" } + state.copy(localCleanupStarted = true) + } + observationRevision.update { it + 1 } + } + + private class Access( + val store: ProfileRemovalStore, + val attemptId: String, + val scope: ProfileRemovalScope, + val job: Job, + ) : AbstractCoroutineContextElement(Key) { + companion object Key : CoroutineContext.Key + val active = AtomicBoolean(true) + } +} + +sealed interface WalletResetRecovery { + data object Loading : WalletResetRecovery + data object Unavailable : WalletResetRecovery + data object Clear : WalletResetRecovery + data class Pending(val attemptId: String) : WalletResetRecovery + data class Unreadable(val attemptId: String) : WalletResetRecovery +} + +@Serializable +internal data class ProfileRemovalState( + val version: Int = 1, + val attemptId: String? = null, + val scope: ProfileRemovalScope? = null, + val localCleanupStarted: Boolean = false, +) + +@Serializable +internal enum class ProfileRemovalScope { PROFILE, WALLET_WIPE } + +/** 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() + } + } + envelope["scope"]?.let { scope -> + if (scope is JsonPrimitive && scope.content != "null" && + ProfileRemovalScope.entries.none { it.name == scope.content } + ) { + throw UnsupportedProfileRemovalFormat() + } + } + json.decodeFromJsonElement(envelope).also { + require(it.attemptId == null || UUID.fromString(it.attemptId).toString() == it.attemptId) { + "Invalid profile removal attempt" + } + require(it.attemptId != null || (it.scope == null && !it.localCleanupStarted)) { + "Cleanup state requires a pending 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(cause: Throwable? = null) : AppError( + "Local recovery is pending. Open the profile for recovery options.", + cause, +) + +internal class ReceiptAssociationsUnavailable : AppError("Receipt associations are being cleared") diff --git a/app/src/main/java/to/bitkit/data/WalletConnectionRecovery.kt b/app/src/main/java/to/bitkit/data/WalletConnectionRecovery.kt index bfba18514a..4e46386577 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 @@ -21,6 +22,8 @@ import to.bitkit.utils.AppError import java.util.UUID import javax.inject.Inject import javax.inject.Singleton +import kotlin.coroutines.AbstractCoroutineContextElement +import kotlin.coroutines.CoroutineContext import kotlin.coroutines.cancellation.CancellationException /** Local connection choices made while recovering a wallet, never included in a remote backup. */ @@ -30,6 +33,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" @@ -87,9 +91,29 @@ class WalletConnectionRecovery @Inject constructor( suspend fun withStartup(owner: Owner, block: suspend (Session) -> T): T = withAdmission(owner, startupMutex, block) + /** Historical receipt work drains with its wallet without serializing behind restoration. */ + internal suspend fun withReceiptOperation(block: suspend (Session) -> T): T { + check(currentCoroutineContext()[ReceiptOperation] == null) { "Receipt operation is already admitted" } + val owner = captureRuntimeOwner() + return withAdmission(owner, mutex = null) { session -> + // Identity changes drain this admission before changing credentials. Validate the indexed + // namespace once; individual receipts only need the captured generation and caller's Job. + storeIdProvider.getBackupWalletBinding(owner.walletIndex) + // ServiceQueue replaces the caller's Job. Keep admission until its actual worker returns. + withContext(NonCancellable + ReceiptOperation()) { + session.requireCurrent() + block(session) + } + } + } + + private class ReceiptOperation : AbstractCoroutineContextElement(Key) { + companion object Key : CoroutineContext.Key + } + private suspend fun withAdmission( owner: Owner, - mutex: Mutex, + mutex: Mutex?, block: suspend (Session) -> T, ): T = coroutineScope { val job = checkNotNull(currentCoroutineContext()[Job]) @@ -99,7 +123,7 @@ class WalletConnectionRecovery @Inject constructor( jobs.add(job) } try { - mutex.withLock { + val admitted: suspend () -> T = { checkOwner(owner) val session = Session(owner, job) try { @@ -108,6 +132,7 @@ class WalletConnectionRecovery @Inject constructor( session.active = false } } + if (mutex == null) admitted() else mutex.withLock { admitted() } } finally { synchronized(stateLock) { jobs.remove(job) } } @@ -120,8 +145,10 @@ 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 { + check(currentCoroutineContext()[ReceiptOperation] == null) { "Wallet replacement cannot drain itself" } val capturedGeneration = admittedGeneration() return lifecycleMutex.withLock { checkGeneration(capturedGeneration) @@ -130,7 +157,9 @@ class WalletConnectionRecovery @Inject constructor( currentCoroutineContext().ensureActive() beginWipe() currentCoroutineContext().ensureActive() - block() + beforeClientsSuspend() + currentCoroutineContext().ensureActive() + vssClients.withSuspendedClients { block() } } finally { storeIdProvider.clearCache() endWipe() @@ -165,6 +194,23 @@ class WalletConnectionRecovery @Inject constructor( checkOwner(owner) } + internal fun requireCurrent() { + job.ensureActive() + check(active) { "Receipt operation ended" } + checkGeneration(owner.generation) + } + + internal val receiptGeneration: Long get() = owner.generation + + /** Final receipt writes run on Core after all suspending lookups have completed. */ + internal fun commitReceiptState(block: () -> T): T = synchronized(stateLock) { + job.ensureActive() + check(active) { "Receipt operation ended" } + checkAdmission() + if (owner.generation != generation) throw CancellationException("Receipt wallet changed") + block() + } + /** Publish local UI state only while this original owner still holds admission. */ internal suspend fun commitCurrentState(block: () -> T): T { checkCurrent() 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 0a1038dee3..f9c605f248 100644 --- a/app/src/main/java/to/bitkit/data/backup/VssBackupClient.kt +++ b/app/src/main/java/to/bitkit/data/backup/VssBackupClient.kt @@ -3,44 +3,52 @@ 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.AppError 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") +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, - 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 +56,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, @@ -64,14 +72,13 @@ class VssBackupClient @Inject constructor( lnurlAuthServerUrl = lnurlAuthServerUrl, keyDomain = Env.lnurlAuthKeyDomain, ) - 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) } } @@ -86,49 +93,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 { @@ -137,12 +138,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) @@ -155,10 +157,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 { @@ -167,10 +170,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) @@ -183,16 +187,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 a2fccdf9d7..cc3a0a0883 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,39 +54,31 @@ 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, keyDomain = Env.lnurlAuthKeyDomain, ) - 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) @@ -106,10 +94,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) @@ -121,11 +110,25 @@ class VssBackupClientLdk @Inject constructor( } } + suspend fun deleteObjects(keys: List, walletIndex: Int = 0): Result = withContext(ioDispatcher) { + runSuspendCatching { + coordinator.withWallet { + setup(walletIndex).onFailure { + if (it is TimeoutCancellationException) throw BackupClientSetupTimeout(it) + }.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/data/keychain/Keychain.kt b/app/src/main/java/to/bitkit/data/keychain/Keychain.kt index b84d76390e..fa371e7d52 100644 --- a/app/src/main/java/to/bitkit/data/keychain/Keychain.kt +++ b/app/src/main/java/to/bitkit/data/keychain/Keychain.kt @@ -45,6 +45,28 @@ class Keychain @Inject constructor( @Suppress("MemberNameEqualsClassName") private val keychain = context.keychainDataStore + private val profileCredentials by lazy { + ProfileCredentialStore( + keychain, + walletIndex = { db.configDao().getAll().first().firstOrNull()?.walletIndex ?: 0 }, + decrypt = { keyStore.decrypt(it.fromBase64()) }, + ) + } + + internal suspend fun captureProfileCredentials(requireCurrent: () -> Unit): ProfileCredentials = + profileCredentials.capture(requireCurrent) + + 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) + private val loadDiagnosticsEmitted: MutableSet = Collections.newSetFromMap(ConcurrentHashMap()) diff --git a/app/src/main/java/to/bitkit/data/keychain/ProfileCredentials.kt b/app/src/main/java/to/bitkit/data/keychain/ProfileCredentials.kt new file mode 100644 index 0000000000..7d86ce8ac6 --- /dev/null +++ b/app/src/main/java/to/bitkit/data/keychain/ProfileCredentials.kt @@ -0,0 +1,159 @@ +package to.bitkit.data.keychain + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.stringPreferencesKey +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.first +import to.bitkit.utils.AppError +import java.security.MessageDigest +import java.util.concurrent.atomic.AtomicReference + +/** A local erase target; it conveys neither remote authority nor acknowledged logout. */ +internal class ProfileCredentials internal constructor( + internal val store: ProfileCredentialStore, + internal val walletIndex: Long, + private val values: Map, ByteArray?>, +) { + private enum class Invalidation { UNREADABLE, CHANGED } + + private val invalidation = AtomicReference(null) + + internal fun requireCurrent() { + if (invalidation.get() != null) throw ProfileCredentialsChanged() + } + + internal fun requireLocalErase() { + if (invalidation.get() == Invalidation.CHANGED) throw ProfileCredentialsChanged() + } + + internal fun invalidate() { + invalidation.set(Invalidation.CHANGED) + } + + 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. */ +internal class ProfileCredentialStore( + private val store: DataStore, + private val walletIndex: suspend () -> Long, + private val decrypt: (String) -> ByteArray, +) { + suspend fun capture(requireCurrent: () -> Unit): ProfileCredentials { + requireCurrent() + val index = walletIndex() + val values = read(store.data.first(), index) + requireCurrent() + if (walletIndex() != index) throw ProfileCredentialsChanged() + return ProfileCredentials(this, index, values) + } + + 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() + if (localOnly) target.requireLocalErase() else target.requireCurrent() + var validationStarted = false + try { + store.edit { preferences -> + validationStarted = true + validateOwnedCredentials(target, requireCurrent, localOnly) { + preferences + } + keys(target.walletIndex).forEach(preferences::remove) + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + 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) { + validateAdmission(target, requireCurrent) + if (target.store !== this) throw ProfileCredentialsChanged() + validateOwnedCredentials(target, requireCurrent) { store.data.first() } + } + + private suspend fun validateOwnedCredentials( + target: ProfileCredentials, + requireCurrent: () -> Unit, + localOnly: Boolean = false, + values: suspend () -> Preferences, + ) { + 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() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + target.invalidate() + throw e + } + } + + 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) } + + private fun keys(index: Long): List> = listOf( + Keychain.Key.PAYKIT_SESSION, + Keychain.Key.PUBKY_SECRET_KEY, + Keychain.Key.SHARED_PUBKY_SOURCE, + ).map { stringPreferencesKey("${it.name}_$index") } +} + +internal class ProfileCredentialsChanged : AppError("The profile credentials changed before local cleanup") 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/ActivityRepo.kt b/app/src/main/java/to/bitkit/repositories/ActivityRepo.kt index 95d5baa5c1..44747d4654 100644 --- a/app/src/main/java/to/bitkit/repositories/ActivityRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/ActivityRepo.kt @@ -137,8 +137,7 @@ class ActivityRepo @Inject constructor( var cancellation: CancellationException? = null val result = try { runSuspendCatching { - val payments = lightningRepo.getPayments().getOrThrow() - syncLdkNodePayments(payments).getOrThrow() + syncLdkNodePayments().getOrThrow() boostPendingActivities() transferRepo.syncTransferStates().getOrThrow() getAllAvailableTags().getOrNull() @@ -164,10 +163,12 @@ class ActivityRepo @Inject constructor( /** * Syncs `ldk-node` [PaymentDetails] list to `bitkit-core` [Activity] items. */ - suspend fun syncLdkNodePayments(payments: List): Result = withContext(bgDispatcher) { - runCatching { - val channelIdsByTxId = findChannelsForPayments(payments) - coreService.activity.syncLdkNodePaymentsToActivities(payments, channelIdsByTxId = channelIdsByTxId) + suspend fun syncLdkNodePayments(): Result = withContext(bgDispatcher) { + runSuspendCatching { + coreService.activity.syncLdkNodePaymentsToActivities( + payments = { lightningRepo.getPayments().getOrThrow() }, + channelIdsByTxId = ::findChannelsForPayments, + ) notifyActivitiesChanged() }.onFailure { Logger.error("Error syncing LDK payments:", it, context = TAG) @@ -589,9 +590,7 @@ class ActivityRepo @Inject constructor( ): Result = withContext(ioDispatcher) { runCatching { if (syncLdkPayments) { - lightningRepo.getPayments().onSuccess { - syncLdkNodePayments(it).getOrThrow() - }.getOrThrow() + syncLdkNodePayments().getOrThrow() } val normalizedKey = PubkyPublicKeyFormat.normalized(contactPublicKey) ?: contactPublicKey @@ -625,9 +624,7 @@ class ActivityRepo @Inject constructor( ): Result = withContext(ioDispatcher) { runCatching { if (syncLdkPayments) { - lightningRepo.getPayments().onSuccess { - syncLdkNodePayments(it).getOrThrow() - }.getOrThrow() + syncLdkNodePayments().getOrThrow() } val activity = findActivityForPaymentId(forPaymentId, syncLdkPayments, walletId) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index de3c8df76d..b6c9b14c60 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -2,33 +2,42 @@ 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.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation +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 import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.drop -import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.transformLatest import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive +import kotlinx.coroutines.joinAll import kotlinx.coroutines.launch +import kotlinx.coroutines.supervisorScope import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext @@ -51,10 +60,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 @@ -95,13 +107,13 @@ import to.bitkit.utils.Logger import to.bitkit.utils.NetworkValidationHelper import to.bitkit.utils.jsonLogOf import java.io.File +import java.net.URI import java.security.MessageDigest import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.atomic.AtomicLong -import java.util.concurrent.atomic.AtomicReference 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.milliseconds import kotlin.time.Duration.Companion.minutes @@ -160,26 +172,68 @@ class BackupRepo @Inject constructor( private val clock: Clock, private val db: AppDb, private val connectionRecovery: WalletConnectionRecovery, + private val vssClients: VssClientCoordinator, ) { private val walletBackupMutex = Mutex() private val usdtBackupMutex = Mutex() - private val activityBackupMutex = Mutex() private val usdtRecoveryBackup = UsdtRecoveryBackupStore(vssBackupClient) private val scope = appScope(ioDispatcher, TAG) - private val backupJobs = mutableMapOf() - private val statusObserverJobs = mutableListOf() - private val dataListenerJobs = mutableListOf() - private var periodicCheckJob: Job? = null + 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 var observationController: CoroutineScope? = null + private var nativeGeneration: Long? = null + private val retiringObservations = mutableSetOf() + private val backupJobs = mutableMapOf() + private val explicitBackups = mutableMapOf() + private val categoryMutexes = BackupCategory.entries.associateWith { Mutex() } + + private class ActivityUploadCache { + var ownerGeneration: Long? = null + var digest: ByteArray? = null + } + + // ACTIVITY's category mutex serializes uploads. Swapping the cache detaches any outstanding ACK. + @Volatile + private var activityUploadCache = ActivityUploadCache() 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 isObserving = false 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 + } + + private class Observation(val scope: CoroutineScope, val generation: BackupOwner) { + val ready = CompletableDeferred() + } + + private fun newBackupScope(parent: CoroutineScope) = + CoroutineScope(parent.coroutineContext + SupervisorJob(parent.coroutineContext[Job])) + /** Spark's current connection was backed up once ready, so a restart of the observers doesn't upload it again. */ @Volatile private var hasBackedUpSparkConnection = false @@ -188,9 +242,6 @@ class BackupRepo @Inject constructor( @Volatile private var markedSparkExitGeneration = 0L - private val uploadedActivityDigest = AtomicReference(null) - private val activityDigestEpoch = AtomicLong(0) - private val _isRestoring = MutableStateFlow(false) val isRestoring: StateFlow = _isRestoring.asStateFlow() @@ -215,11 +266,54 @@ class BackupRepo @Inject constructor( } .distinctUntilChanged() - fun reset() { - stopObservingBackups() - clearUploadedActivityDigest() - vssBackupClient.reset() - vssBackupClientLdk.reset() + suspend fun reset() = withContext(ioDispatcher) { + resetMutex.withLock { + val pending = synchronized(lifecycleLock) { + resetting = true + activityUploadCache = ActivityUploadCache() + observation = null + observationController = null + pendingScope.coroutineContext[Job] + } + withContext(NonCancellable) { + 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 + } + ) { + throw BackupStatusWritePending() + } + generation += 1 + } + synchronized(lifecycleLock) { + backupJobs.clear() + explicitBackups.clear() + failedBackupRequired.clear() + temporaryFailureRetries.clear() + temporaryFailureSince.clear() + } + } finally { + synchronized(lifecycleLock) { + pendingScope = newBackupScope(scope) + resetting = false + } + } + } + } } fun setWiping(isWiping: Boolean) { @@ -267,16 +361,78 @@ 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 (observationController != null || resetting || _isWiping.value) return + val previous = retiringObservations.toList() + val controller = newBackupScope(pendingScope) + observationController = controller + val parent = checkNotNull(controller.coroutineContext[Job]) + retiringObservations.add(parent) + parent.invokeOnCompletion { synchronized(lifecycleLock) { retiringObservations.remove(parent) } } + controller.launch(start = CoroutineStart.LAZY) { + combine(vssClients.owners, isWiping) { native, wiping -> native.takeUnless { wiping } } + .collectLatest { native -> + if (native == null) return@collectLatest + try { + vssClients.withWallet(native) { + supervisorScope { + val original = synchronized(lifecycleLock) { BackupOwner(generation, native) } + adoptOwner(original) + val owner = Observation(this, original) + synchronized(lifecycleLock) { + if (observationController !== controller) { + throw CancellationException( + "Backup observation stopped" + ) + } + observation = owner + } + try { + // Record consumed changes during ordinary stop cleanup, before uploads resume. + 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. + awaitCancellation() + } finally { + synchronized(lifecycleLock) { + if (observation === owner) observation = null + } + } + } + } + } catch (_: CancellationException) { + currentCoroutineContext().ensureActive() + // Native retirement cancels only this generation; the controller awaits reopening. + } + } + } } + startup.start() + } - isObserving = true - Logger.debug("Start observing backup statuses and data store changes", context = TAG) + private fun adoptOwner(owner: BackupOwner) = synchronized(lifecycleLock) { + check(generation == owner.generation && !resetting) + if (nativeGeneration != owner.native.generation) { + // Admission guarantees the previous owner's native work and local tails have drained. + nativeGeneration = owner.native.generation + explicitBackups.entries.removeAll { it.value != owner.native.generation } + failedBackupRequired.clear() + temporaryFailureRetries.clear() + temporaryFailureSince.clear() + } + } - scope.launch { + private fun ownsState(owner: BackupOwner) = + generation == owner.generation && nativeGeneration == owner.native.generation + + private fun startObservation(owner: Observation) { + Logger.debug("Start observing backup statuses and data store changes", context = TAG) + owner.scope.launch { vssBackupClient.setupWithRetry { onSuccess = { attempt -> Logger.debug("VSS client setup succeeded on attempt $attempt", context = TAG) @@ -291,234 +447,205 @@ 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) { - Logger.debug("Clearing stale running flag for: '$category'", context = TAG) - status.copy(running = false) - } else { - status - } + updateBackupStatus(category, owner.generation) { status -> + if (status.running && category !in runningBackups && backupJobs[category]?.admitted != true) { + Logger.debug("Clearing stale running flag for: '$category'", context = TAG) + status.copy(running = false) + } else { + status } } } } - startBackupStatusObservers() - startDataStoreListeners() - startPeriodicBackupFailureCheck() + startBackupStatusObservers(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) { + observationController?.coroutineContext?.get(Job).also { + observationController = null + 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 { - cacheStore.backupStatuses + owner.scope.launch { + 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, 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, - ) - ) - dataListenerJobs.add( - observeBackupChanges( - usdtRepo.get().state.map { it.transfers }.distinctUntilChanged(), - BackupCategory.WALLET, - ) + 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(paykitPresentationStore.backupStateVersion, BackupCategory.WALLET)) - dataListenerJobs.add(observeBackupChanges(paykitAllowanceStore.backupStateVersion, BackupCategory.WALLET)) - dataListenerJobs.add( - observeBackupChanges(paykitOutboundDeliveryStore.backupStateVersion, BackupCategory.WALLET) + observeBackupChanges( + owner, + usdtRepo.get().state.map { it.transfers }.distinctUntilChanged(), + BackupCategory.WALLET, ) - dataListenerJobs.add( - observeBackupChanges( - privatePaykitAddressReservationRepo.get().backupStateVersion, - BackupCategory.WALLET, - ) + observeBackupChanges(owner, paykitPresentationStore.backupStateVersion, BackupCategory.WALLET) + observeBackupChanges(owner, paykitAllowanceStore.backupStateVersion, BackupCategory.WALLET) + observeBackupChanges(owner, paykitOutboundDeliveryStore.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)) - dataListenerJobs.add(observeBackupChanges(SparkExitEarlierAddressStore.writes, BackupCategory.METADATA)) - - // SPARK_EXIT - back up once per Spark connection when it is ready and synced, even if observing starts after - // that, and again whenever Spark announces its unilateral exit data changed - dataListenerJobs.add( - scope.launch { - val isReady = sparkRepo.state.map { it.isReady && it.hasSynced }.distinctUntilChanged() - .onEach { if (!it) hasBackedUpSparkConnection = false } - .filter { it } - isReady.collect { - if (hasBackedUpSparkConnection || shouldSkipBackup()) return@collect - hasBackedUpSparkConnection = true - markBackupRequired(BackupCategory.SPARK_EXIT) - } - } - ) - // The generation replays on each start, so exit data that changed while nothing observed is backed up then. - dataListenerJobs.add( - scope.launch { - sparkRepo.exitStateGeneration.collect { generation -> - if (generation <= markedSparkExitGeneration || shouldSkipBackup()) return@collect - markedSparkExitGeneration = generation - markBackupRequired(BackupCategory.SPARK_EXIT) + observeBackupChanges(owner, activityRepo.activityTagsChanged, BackupCategory.METADATA) + observeBackupChanges(owner, SparkExitEarlierAddressStore.writes, BackupCategory.METADATA) + + // Replay unrecorded Spark changes when the admitted observation or restore gate reopens. + owner.scope.launch { + 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 + if ((!connectionNeedsBackup && generation <= markedSparkExitGeneration) || shouldSkipBackup()) { + return@collect } + runSuspendCatching { updateBackupRequired(BackupCategory.SPARK_EXIT, owner.generation) } + .onSuccess { + if (!it) return@onSuccess + hasBackedUpSparkConnection = ready + markedSparkExitGeneration = maxOf(markedSparkExitGeneration, generation) + } + .onFailure { Logger.error("Failed to mark Spark exit backup required", it, context = TAG) } } - ) + } // 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 { @@ -526,87 +653,251 @@ 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() + flushRequiredMarks(owner.generation) + checkForFailedBackups(owner) } } } - private fun markBackupRequired(category: BackupCategory) { - scope.launch { - failedBackupRequired -= category - cacheStore.updateBackupStatus(category) { - it.copy(required = maxOf(currentTimeMillis(), it.required + 1, it.synced + 1)) - } - Logger.verbose("Marked backup required for: '$category'", context = TAG) + 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 fun scheduleBackup(category: BackupCategory, skipUnchangedActivity: Boolean = true) { - backupJobs[category]?.cancel() + 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) + } + } - Logger.verbose("Scheduling backup for: '$category'", context = TAG) + 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) } + } - backupJobs[category] = scope.launch { - runningBackups += category - cacheStore.updateBackupStatus(category) { - it.copy(running = true) - } + private suspend fun markBackupRequired(category: BackupCategory, expectedGeneration: BackupOwner) = + withContext(NonCancellable) { + // A consumed change must remain pending even if observation stops before the cache write. + updateBackupRequired(category, expectedGeneration) + } - delay(if (category == BackupCategory.SPARK_EXIT) SPARK_EXIT_BACKUP_DEBOUNCE else BACKUP_DEBOUNCE) - if (category == BackupCategory.WALLET) paykitSdkService.isPaymentSubmissionActive.first { !it } + 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)) + } + if (updated) Logger.verbose("Marked backup required for: '$category'", context = TAG) + return updated + } - val status = cacheStore.backupStatuses.first()[category] ?: BackupItemStatus() - if (status.isRequired && !shouldSkipBackup(category)) { - triggerBackup(category, skipUnchangedActivity) - } else { - Logger.debug("Backup no longer needed for: '$category'", context = TAG) - runningBackups -= category - cacheStore.updateBackupStatus(category) { - it.copy(running = false) - } + 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. + 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( + category: BackupCategory, + owner: Observation? = null, + requestedGeneration: BackupOwner? = null, + ) { + val expectedGeneration = owner?.generation ?: requestedGeneration ?: return + val job = synchronized(lifecycleLock) { + if (expectedGeneration.native.generation != vssClients.owners.value?.generation || + resetting || _isWiping.value || (owner != null && observation !== owner) || + (requestedGeneration != null && requestedGeneration.generation != 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) + if (owner == null) explicitBackups[category] = expectedGeneration.native.generation + val existing = backupJobs[category] + if (existing?.owner?.native?.generation == expectedGeneration.native.generation && + !existing.job.isCompleted && !existing.job.isCancelled + ) { + return + } + val jobScope = owner?.scope ?: pendingScope + jobScope.launch(start = CoroutineStart.LAZY) { + val scheduledJob = currentCoroutineContext()[Job] + vssClients.withWallet(expectedGeneration.native) { + adoptOwner(expectedGeneration) + if (owner == null) { + synchronized( + lifecycleLock + ) { explicitBackups[category] = expectedGeneration.native.generation } + } + try { + synchronized(lifecycleLock) { + backupJobs[category]?.takeIf { it.job === scheduledJob }?.admitted = true + } + updateBackupStatus(category, expectedGeneration) { it.copy(running = true) } + owner?.ready?.await() + // Coalescing pending work must not delay an explicit recovery acknowledgement. + val debounce = if (category == BackupCategory.SPARK_EXIT) { + SPARK_EXIT_BACKUP_DEBOUNCE + } else { + BACKUP_DEBOUNCE + } + delay(debounce) + categoryMutexes.getValue(category).withLock { + runningBackups += category + try { + updateBackupStatus(category, expectedGeneration) { it.copy(running = true) } + if (category == BackupCategory.WALLET) { + paykitSdkService.isPaymentSubmissionActive.first { !it } + } + val status = cacheStore.backupStatuses.first()[category] ?: BackupItemStatus() + if (status.isRequired && !shouldSkipBackup(category) && + failedBackupRequired[category] != status.required + ) { + if (performBackup(category, expectedGeneration).getOrNull() == false) { + finishUnchangedActivity(expectedGeneration, scheduledJob) + } + } + } finally { + finishBackup(category, expectedGeneration) + } + } + } finally { + synchronized(lifecycleLock) { + if (backupJobs[category]?.job === scheduledJob) backupJobs.remove(category) + } + withContext(NonCancellable) { + updateBackupStatus(category, expectedGeneration) { + it.copy(running = category in runningBackups || backupJobs[category]?.admitted == true) + } + schedulePendingBackup(category, expectedGeneration, owner) } } } + }.also { backupJobs[category] = PendingBackup(expectedGeneration, it) } + } + job.invokeOnCompletion { resumeUnstartedBackup(category, expectedGeneration, job) } + job.start() + } + + private fun resumeUnstartedBackup(category: BackupCategory, original: BackupOwner, completed: Job) { + val followup = synchronized(lifecycleLock) { + // Entered jobs remove their reservation before their normal pending handoff. + if (backupJobs[category]?.job !== completed) return + backupJobs.remove(category) + if (resetting || _isWiping.value || !ownsState(original) || + vssClients.owners.value?.generation != original.native.generation || + explicitBackups[category] != original.native.generation + ) { + return + } + pendingScope.launch(start = CoroutineStart.LAZY) { + vssClients.withWallet(original.native) { + schedulePendingBackup(category, original) + } } } + followup.start() } - private fun checkForFailedBackups() { + private suspend fun finishUnchangedActivity(owner: BackupOwner, job: Job?) = withContext(NonCancellable) { + val category = BackupCategory.ACTIVITY + // The skip has been published. Retire its reservation atomically with checking for a joined full request. + val force = synchronized(lifecycleLock) { + if (backupJobs[category]?.job === job) backupJobs.remove(category) + explicitBackups[category] == owner.native.generation + } + if (force) { + updateBackupStatus(category, owner) { + explicitBackups[category] = owner.native.generation + if (it.isRequired) it else it.copy(required = maxOf(currentTimeMillis(), it.synced + 1)) + } + } + } + + private suspend fun schedulePendingBackup( + category: BackupCategory, + expectedGeneration: BackupOwner, + previousOwner: Observation? = null, + ) { + var status = BackupItemStatus() + updateBackupStatus(category, expectedGeneration) { + status = it + if (!it.isRequired) explicitBackups -= category + it + } + val nextOwner = synchronized(lifecycleLock) { + if (resetting || !ownsState(expectedGeneration)) return + if (!status.shouldBackup(category)) return + if (category in explicitBackups) { + null + } else { + val owner = observation?.takeIf { previousOwner == null || previousOwner === it } ?: return + if (!owner.scope.isActive) return + owner + } + } + scheduleBackup(category, nextOwner, expectedGeneration) + } + + private suspend fun finishBackup(category: BackupCategory, expectedGeneration: BackupOwner) = 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() @@ -618,18 +909,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), @@ -640,76 +931,129 @@ class BackupRepo @Inject constructor( } } - suspend fun triggerBackup(category: BackupCategory): Result = triggerBackup(category, false) + suspend fun triggerBackup(category: BackupCategory): Result = performExplicitBackup(category) - private suspend fun triggerBackup( + private suspend fun performExplicitBackup( category: BackupCategory, - skipUnchangedActivity: Boolean, - ): Result = withContext(ioDispatcher) { + 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 || !ownsState(expectedGeneration) }) { + return@withLock Result.failure(UsdtException.BackupUnavailable()) + } + runningBackups += category + try { + performBackup( + category, + expectedGeneration, + usdtSnapshot, + explicitAttempt = true, + reservedRequired = reservedRequired, + ).map { } + } finally { + finishBackup(category, expectedGeneration) + withContext(NonCancellable) { + schedulePendingBackup(category, expectedGeneration) + } + } + } + } + + private suspend fun performBackup( + category: BackupCategory, + expectedGeneration: BackupOwner, + usdtSnapshot: String? = null, + explicitAttempt: Boolean = false, + reservedRequired: Long? = null, + ): Result = if (category == BackupCategory.WALLET || category == BackupCategory.METADATA) { - walletBackupMutex.withLock { performBackup(category, skipUnchangedActivity) } + walletBackupMutex.withLock { + performSerializedBackup(category, expectedGeneration, usdtSnapshot, explicitAttempt, reservedRequired) + } } else { - performBackup(category, skipUnchangedActivity) + performSerializedBackup(category, expectedGeneration, usdtSnapshot, explicitAttempt, reservedRequired) } - } - private suspend fun performBackup(category: BackupCategory, skipUnchangedActivity: Boolean): Result { + private suspend fun performSerializedBackup( + category: BackupCategory, + expectedGeneration: BackupOwner, + usdtSnapshot: String?, + explicitAttempt: Boolean, + reservedRequired: Long?, + ): Result { 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) + var backupRequired = reservedRequired ?: currentTimeMillis() + updateBackupStatus(category, expectedGeneration) { + if (reservedRequired == null) { + val required = if (explicitAttempt) it.required + 1 else it.required + backupRequired = maxOf(backupRequired, required, it.synced + 1) } - - val upload = when (category) { - BackupCategory.WALLET -> uploadWalletBackup().map { true } - BackupCategory.USDT_RECOVERY -> uploadUsdtRecoveryBackup().map { true } - BackupCategory.SPARK_EXIT -> uploadSparkExitBackup().map { true } - BackupCategory.ACTIVITY -> uploadActivityBackup(skipUnchangedActivity) - else -> runSuspendCatching { - vssBackupClient.putObject(key = category.name, data = getBackupDataBytes(category)).getOrThrow() - true - } + if ((failedBackupRequired[category] ?: 0) <= backupRequired) failedBackupRequired -= category + it.copy(running = true, required = maxOf(it.required, backupRequired)) + } + if (synchronized(lifecycleLock) { resetting || !ownsState(expectedGeneration) }) { + return Result.failure(UsdtException.BackupUnavailable()) + } + val upload = when (category) { + BackupCategory.WALLET -> uploadWalletBackup().map { true } + BackupCategory.USDT_RECOVERY -> uploadUsdtRecoveryBackup(usdtSnapshot).map { true } + BackupCategory.SPARK_EXIT -> uploadSparkExitBackup().map { true } + BackupCategory.ACTIVITY -> uploadActivityBackup(expectedGeneration, explicitAttempt) + else -> runSuspendCatching { + val data = getBackupDataBytes(category) + vssBackupClient.ensureSetupForUpload() + vssBackupClient.putObject(key = category.name, data = data).getOrThrow() + true } - return upload - .onSuccess { uploaded -> - withContext(NonCancellable) { - cacheStore.updateBackupStatus(category) { - it.copy(running = false, synced = backupRequired) + } + return upload + .onSuccess { uploaded -> + withContext(NonCancellable) { + updateBackupStatus(category, expectedGeneration) { + // A known full request must remain durably pending until the upload succeeds. + if (!uploaded && explicitBackups[category] == expectedGeneration.native.generation) { + return@updateBackupStatus it.copy(running = false) + } + if ((failedBackupRequired[category] ?: 0) <= backupRequired) { + failedBackupRequired -= category + temporaryFailureRetries -= category + temporaryFailureSince -= category + } + if (uploaded && it.required <= backupRequired) { + explicitBackups -= category + } else if (explicitAttempt) { + explicitBackups[category] = expectedGeneration.native.generation } - if (category == BackupCategory.WALLET) { + it.copy(running = false, synced = maxOf(it.synced, backupRequired)) + } + if (category == BackupCategory.WALLET) { + updateBackupStatus(BackupCategory.METADATA, expectedGeneration) { failedBackupRequired -= BackupCategory.METADATA - cacheStore.updateBackupStatus(BackupCategory.METADATA) { - if (it.isRequired) { - it.copy(required = maxOf(currentTimeMillis(), it.required + 1, it.synced + 1)) - } else { - it - } + if (it.isRequired) { + it.copy(required = maxOf(currentTimeMillis(), it.required + 1, it.synced + 1)) + } else { + it } } - runningBackups -= category - failedBackupRequired -= category - temporaryFailureRetries -= category - temporaryFailureSince -= category - } - if (uploaded) { - Logger.info("Backup succeeded for: '$category'", context = TAG) - } else { - Logger.debug("Skipped backup for: '$category', payload unchanged", context = TAG) } } - .onFailure { markBackupFailed(category, backupRequired, it) } - .map {} - } finally { - if (runningBackups.remove(category)) { - withContext(NonCancellable) { - cacheStore.updateBackupStatus(category) { it.copy(running = false) } + if (uploaded) { + Logger.info("Backup succeeded for: '$category'", context = TAG) + } else { + Logger.debug("Skipped backup for: '$category', payload unchanged", context = TAG) } } - } + .onFailure { markBackupFailed(category, backupRequired, expectedGeneration, it, explicitAttempt) } } /** @@ -720,13 +1064,17 @@ class BackupRepo @Inject constructor( private suspend fun uploadSparkExitBackup(): Result = runSuspendCatching { val staged = sparkRepo.importStagedExitState() if (staged is StagedExitImport.Rejected) { + vssBackupClient.ensureSetupForUpload() setAsideRejectedExitBackup(rejectedStagedExitCopy(staged)) sparkRepo.discardStagedExitState(staged.exitState) } // Dropping a rejected staged copy asks for the stored backup to be merged again, until a merge succeeds. if (!sparkRepo.hasMergedRemoteExitState) { sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred() + vssBackupClient.ensureSetupForUpload() mergeStoredExitBackup() + } else { + vssBackupClient.ensureSetupForUpload() } val backup = sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred() vssBackupClient.putObject( @@ -785,17 +1133,45 @@ class BackupRepo @Inject constructor( Logger.warn("Set Spark exit data Spark can't import aside as '$key'", context = TAG) } - suspend fun persistWalletBackup(): Result = - withContext(ioDispatcher) { - walletBackupMutex.withLock { uploadWalletBackup() } - }.onFailure { markBackupRequired(BackupCategory.WALLET) } + suspend fun persistWalletBackup(): Result = withBackupOperation { expectedGeneration -> + walletBackupMutex.withLock { 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 = + performExplicitBackup(BackupCategory.USDT_RECOVERY, snapshot) + + private suspend fun withBackupOperation( + operation: suspend (BackupOwner) -> Result, + ): Result { + val native = try { + vssClients.captureOwner() + } catch (e: CancellationException) { + currentCoroutineContext().ensureActive() + return Result.failure(UsdtException.BackupUnavailable().apply { initCause(e) }) } - uploadUsdtRecoveryBackup(snapshot).getOrThrow() - }.onFailure { markBackupRequired(BackupCategory.USDT_RECOVERY) } + return withContext(ioDispatcher) { + val callerContext = currentCoroutineContext().minusKey(Job) + val task = synchronized(lifecycleLock) { + if (resetting || _isWiping.value) return@withContext Result.failure(UsdtException.BackupUnavailable()) + val original = BackupOwner(generation, native) + pendingScope.async(context = callerContext, start = CoroutineStart.LAZY) { + vssClients.withWallet(native) { + adoptOwner(original) + operation(original) + } + } + } + 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 { @@ -824,47 +1200,79 @@ 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() }.map { } } - private suspend fun markBackupFailed(category: BackupCategory, backupRequired: Long, e: Throwable) { + private suspend fun markBackupFailed( + category: BackupCategory, + backupRequired: Long, + expectedGeneration: BackupOwner, + e: Throwable, + explicitAttempt: Boolean, + ) { + val temporary = e.isTemporaryBackupFailure() withContext(NonCancellable) { - cacheStore.updateBackupStatus(category) { + updateBackupStatus(category, expectedGeneration) { + if (temporary && explicitAttempt) explicitBackups[category] = expectedGeneration.native.generation + 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) } - runningBackups -= category } when { e is WalletBackupSnapshotChanged -> Logger.debug("Deferred changing backup snapshot for: '$category'", context = TAG) e is SparkExitBackupDeferred -> Logger.debug("Deferred backup until Spark syncs for: '$category'", context = TAG) - e.isTemporaryBackupFailure() -> retryAfterTemporaryFailure(category, backupRequired, e) + temporary -> 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: BackupOwner, + e: Throwable, + ) { + val job = synchronized(lifecycleLock) { + if (resetting || !ownsState(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))) + .coerceAtMost(TEMPORARY_FAILURE_RETRY_MAX_DELAY) + Logger.warn("Retrying backup for: '$category' in '$retryDelay'", e, context = TAG) + pendingScope.launch(start = CoroutineStart.LAZY) { + delay(retryDelay) + vssClients.withWallet(expectedGeneration.native) { + synchronized(lifecycleLock) { + if (resetting || !ownsState(expectedGeneration)) return@withWallet + val failed = failedBackupRequired[category] + if (failed == backupRequired) { + failedBackupRequired.remove(category, backupRequired) + } else if (failed != null || category !in explicitBackups) { + return@withWallet + } + } + schedulePendingBackup(category, expectedGeneration) + } + } } + job.start() } private suspend fun getBackupDataBytes(category: BackupCategory): ByteArray = when (category) { @@ -891,13 +1299,11 @@ 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() @@ -913,36 +1319,34 @@ class BackupRepo @Inject constructor( } } - private suspend fun getActivityBackupPayload(): ActivityBackupV1 = ActivityBackupV1( + private suspend fun getActivityBackupPayload() = ActivityBackupV1( createdAt = currentTimeMillis(), - activities = activityRepo.getActivities().getOrDefault(emptyList()), - activityTags = activityRepo.getAllActivitiesTags().getOrDefault(emptyList()), - closedChannels = activityRepo.getClosedChannels().getOrDefault(emptyList()), + activities = activityRepo.getActivities().getOrThrow(), + activityTags = activityRepo.getAllActivitiesTags().getOrThrow(), + closedChannels = activityRepo.getClosedChannels().getOrThrow(), ) - private suspend fun uploadActivityBackup(skipIfUnchanged: Boolean): Result = runSuspendCatching { - activityBackupMutex.withLock { uploadActivityBackupLocked(skipIfUnchanged) } - } - - private suspend fun uploadActivityBackupLocked(skipIfUnchanged: Boolean): Boolean { + private suspend fun uploadActivityBackup(owner: BackupOwner, explicitAttempt: Boolean) = runSuspendCatching { + val category = BackupCategory.ACTIVITY + val cache = activityUploadCache val payload = getActivityBackupPayload() val digest = MessageDigest.getInstance("SHA-256") .digest(json.encodeToString(payload.copy(createdAt = 0)).toByteArray()) - if (skipIfUnchanged && digest.contentEquals(uploadedActivityDigest.get())) return false - - val epoch = activityDigestEpoch.get() - uploadedActivityDigest.set(null) - vssBackupClient.putObject( - key = BackupCategory.ACTIVITY.name, - data = json.encodeToString(payload).toByteArray(), - ).getOrThrow() - if (activityDigestEpoch.get() == epoch) uploadedActivityDigest.set(digest) - return true - } + val force = explicitAttempt || synchronized(lifecycleLock) { + explicitBackups[category] == owner.native.generation + } + if (!force && cache === activityUploadCache && cache.ownerGeneration == owner.native.generation && + digest.contentEquals(cache.digest) + ) { + return@runSuspendCatching false + } - private fun clearUploadedActivityDigest() { - activityDigestEpoch.incrementAndGet() - uploadedActivityDigest.set(null) + vssBackupClient.ensureSetupForUpload() + cache.digest = null // A failed PUT may already have changed the remote value. + vssBackupClient.putObject(key = category.name, data = json.encodeToString(payload).toByteArray()).getOrThrow() + cache.ownerGeneration = owner.native.generation + cache.digest = digest + true } private suspend fun getMetadataBackupDataBytes(): ByteArray = withContext(ioDispatcher) { @@ -966,8 +1370,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(), @@ -1031,6 +1435,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() @@ -1118,7 +1525,7 @@ class BackupRepo @Inject constructor( Logger.debug("Full restore starting", context = TAG) _isRestoring.update { true } - clearUploadedActivityDigest() + activityUploadCache = ActivityUploadCache() // Mutated only by the sequential restore steps below, inside this single coroutine. val categoriesNeedingRewrite = mutableSetOf() @@ -1475,21 +1882,26 @@ class BackupRepo @Inject constructor( wire.validateProofs(proofs, WalletScope.default) } - suspend fun getLatestBackupTime(): ULong? = withContext(ioDispatcher) { - runCatching { - withTimeout(VSS_TIMESTAMP_TIMEOUT) { - vssBackupClient.setup().getOrThrow() - coroutineScope { - LATEST_BACKUP_TIME_CATEGORIES - .map { category -> async { getRemoteBackupTimestamp(category) } } - .mapNotNull { it.await() } - .filter { it > 0uL } - .maxOrNull() - } + suspend fun getLatestBackupTime(): ULong? { + val original = vssClients.captureOwner() + return withContext(ioDispatcher) { + vssClients.withWallet(original) { + runCatching { + withTimeout(VSS_TIMESTAMP_TIMEOUT) { + vssBackupClient.setup().getOrThrow() + coroutineScope { + LATEST_BACKUP_TIME_CATEGORIES + .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? { @@ -1507,10 +1919,16 @@ class BackupRepo @Inject constructor( fun scheduleFullBackup() { Logger.debug("Scheduling backups for all categories", context = TAG) + val native = try { + vssClients.captureOwner() + } catch (_: CancellationException) { + return + } + val requestedGeneration = synchronized(lifecycleLock) { BackupOwner(generation, native) } BackupCategory.entries .filter { it != BackupCategory.LIGHTNING_CONNECTIONS } .forEach { - scheduleBackup(it, skipUnchangedActivity = false) + scheduleBackup(it, requestedGeneration = requestedGeneration) } } @@ -1668,6 +2086,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") + internal class SparkExitBackupChanged : AppError("Stored Spark exit backup kept changing while it was merged") private class PublicAddressRestoreFailed(cause: Throwable) : AppError( @@ -1702,13 +2122,30 @@ private data class RestoredCoreBackup( val complete: Boolean = true, ) -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 BackupClientSetupTimeout, + is VssException.ConnectionException, + is VssException.NetworkException, + is VssException.StoreException, + is VssException.PutException, + -> true + is VssException.UnknownException -> isVssRequestSendFailure(errorDetails, "/putObjects") + is VssException.AuthException -> isVssRequestSendFailure( + errorDetails.removePrefix("error performing external request: "), + ) + else -> false + } + +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() && + (pathSuffix == null || url.path.endsWith(pathSuffix)) } /** diff --git a/app/src/main/java/to/bitkit/repositories/ContactPaymentSettingsRepo.kt b/app/src/main/java/to/bitkit/repositories/ContactPaymentSettingsRepo.kt index a4a8e6155d..7538f2e670 100644 --- a/app/src/main/java/to/bitkit/repositories/ContactPaymentSettingsRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/ContactPaymentSettingsRepo.kt @@ -20,6 +20,8 @@ import to.bitkit.ext.runSuspendCatching import to.bitkit.flags.PaykitFeatureFlags import to.bitkit.services.PaykitSdkOperationLock.Priority import to.bitkit.utils.Logger +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicLong import javax.inject.Inject import javax.inject.Singleton @@ -34,6 +36,56 @@ 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 (PubkySignIn?) -> Result, + ): Result = runSuspendCatching { + val epoch = sharingEpoch.get() + val signIn = pubkyRepo.currentSignIn() + check(!removalPending.get() && !wipePending.get()) { "Profile removal is in progress" } + withContext(ioDispatcher) { + sharingMutex.withLock { + check( + !removalPending.get() && !wipePending.get() && epoch == sharingEpoch.get() && + (if (signIn == null) pubkyRepo.currentSignIn() == null else pubkyRepo.isCurrent(signIn)) + ) { "Profile sharing state changed" } + operation(signIn).getOrThrow() + } + } + } + private val scope = appScope(ioDispatcher, TAG) private var newProfileJob: Job? = null @@ -48,7 +100,9 @@ class ContactPaymentSettingsRepo @Inject constructor( fun enableForNewProfile() { if (newProfileJob?.isActive == true) return newProfileJob = scope.launch { - sharingMutex.withLock { if (isPaykitUiEnabled()) enableBothForNewProfile() } + sharingMutex.withLock { + if (!removalPending.get() && !wipePending.get() && isPaykitUiEnabled()) enableBothForNewProfile() + } } } @@ -129,52 +183,49 @@ class ContactPaymentSettingsRepo @Inject constructor( }.onFailure(error::addSuppressed) } - suspend fun setPublicEnabled(isEnabled: Boolean): Result = withContext(ioDispatcher) { - sharingMutex.withLock { - if (isEnabled && !isPaykitUiEnabled()) return@withLock Result.failure(PublicPaykitError.PaykitDisabled) - val signIn = pubkyRepo.currentSignIn() - val previous = settingsStore.data.first() - val canPublish = { - signIn != null && pubkyRepo.isCurrent(signIn) && !privatePaykitRepo.isProfileDeletionInProgress.value - } - val canUpdateSettings = { - if (signIn == null) { - !isEnabled && pubkyRepo.currentSignIn() == null && - !privatePaykitRepo.isProfileDeletionInProgress.value - } else { - canPublish() - } + suspend fun setPublicEnabled(isEnabled: Boolean): Result = changeSharing { signIn -> + if (isEnabled && !isPaykitUiEnabled()) return@changeSharing Result.failure(PublicPaykitError.PaykitDisabled) + val previous = settingsStore.data.first() + val canPublish = { + signIn != null && pubkyRepo.isCurrent(signIn) && !privatePaykitRepo.isProfileDeletionInProgress.value + } + val canUpdateSettings = { + if (signIn == null) { + !isEnabled && pubkyRepo.currentSignIn() == null && + !privatePaykitRepo.isProfileDeletionInProgress.value + } else { + canPublish() } - var enabledPersisted = false - var completed = false - try { - runSuspendCatching { - currentCoroutineContext().ensureActive() - if (!canUpdateSettings()) throw PublicPaykitError.SessionNotActive - withContext(NonCancellable) { - settingsStore.update { - if (!canUpdateSettings()) throw PublicPaykitError.SessionNotActive - it.copy( - hasConfirmedPublicPaykitEndpoints = isEnabled, - sharesPublicPaykitEndpoints = isEnabled, - publicPaykitCleanupPending = true, - ) - } - enabledPersisted = isEnabled - } - currentCoroutineContext().ensureActive() - if (isEnabled) { - publicPaykitRepo.syncPublishedEndpoints(true, Priority.Background, canPublish).getOrThrow() - } else { - publicPaykitRepo.syncPublishedEndpoints(false, Priority.Interactive, canPublish).getOrThrow() + } + var enabledPersisted = false + var completed = false + try { + runSuspendCatching { + currentCoroutineContext().ensureActive() + if (!canUpdateSettings()) throw PublicPaykitError.SessionNotActive + withContext(NonCancellable) { + settingsStore.update { + if (!canUpdateSettings()) throw PublicPaykitError.SessionNotActive + it.copy( + hasConfirmedPublicPaykitEndpoints = isEnabled, + sharesPublicPaykitEndpoints = isEnabled, + publicPaykitCleanupPending = true, + ) } - }.onFailure { - if (enabledPersisted) rollbackPublicEnabled(previous, canPublish, it) - }.also { completed = true } - } finally { - if (enabledPersisted && !completed) { - withContext(NonCancellable) { restorePublicSettings(previous, canPublish) } + enabledPersisted = isEnabled + } + currentCoroutineContext().ensureActive() + if (isEnabled) { + publicPaykitRepo.syncPublishedEndpoints(true, Priority.Background, canPublish).getOrThrow() + } else { + publicPaykitRepo.syncPublishedEndpoints(false, Priority.Interactive, canPublish).getOrThrow() } + }.onFailure { + if (enabledPersisted) rollbackPublicEnabled(previous, canPublish, it) + }.also { completed = true } + } finally { + if (enabledPersisted && !completed) { + withContext(NonCancellable) { restorePublicSettings(previous, canPublish) } } } } @@ -209,53 +260,73 @@ class ContactPaymentSettingsRepo @Inject constructor( }.onFailure(error::addSuppressed) } - suspend fun setEnabled(isEnabled: Boolean): Result = withContext(ioDispatcher) { - sharingMutex.withLock { - if (isEnabled && !isPaykitUiEnabled()) return@withLock Result.failure(PublicPaykitError.PaykitDisabled) - val contacts = pubkyRepo.contacts.value.map { it.publicKey } - if (isEnabled) enable(contacts) else disable(contacts) - } + suspend fun setEnabled(isEnabled: Boolean): Result = changeSharing { signIn -> + if (isEnabled && !isPaykitUiEnabled()) return@changeSharing Result.failure(PublicPaykitError.PaykitDisabled) + val contacts = pubkyRepo.contacts.value.map { it.publicKey } + if (isEnabled) enable(contacts, signIn) else disable(contacts, signIn) } - suspend fun reconcilePendingEndpoints(reconcile: suspend () -> Unit) = withContext(ioDispatcher) { - if (!sharingMutex.tryLock()) return@withContext - try { - reconcile() - } finally { - sharingMutex.unlock() + suspend fun reconcilePendingEndpoints(waitForTurn: Boolean = false, reconcile: suspend () -> Unit) { + val epoch = sharingEpoch.get() + if (removalPending.get() || wipePending.get()) return + withContext(ioDispatcher) { + if (removalPending.get() || wipePending.get() || epoch != sharingEpoch.get()) return@withContext + if (waitForTurn) { + sharingMutex.lock() + } else if (!sharingMutex.tryLock()) { + return@withContext + } + try { + if (!removalPending.get() && !wipePending.get() && epoch == sharingEpoch.get()) reconcile() + } finally { + sharingMutex.unlock() + } } } - suspend fun disablePaykit(): Result = withContext(ioDispatcher) { - sharingMutex.withLock { - runSuspendCatching { - val previous = settingsStore.data.first() - val hadPublicState = previous.hasPublicPaykitPublicationState() - settingsStore.update { it.paykitDisabled(markPublicCleanupPending = hadPublicState) } - val contacts = pubkyRepo.contacts.value.map { it.publicKey } - val privateCleanup = privatePaykitRepo.disableSharingAndPruneUnsavedContactState(contacts) - val publicCleanup = when { - hadPublicState -> publicPaykitRepo.syncPublishedEndpoints( - publish = false, - appSyncPriority = Priority.Interactive, - ) - previous.sharesPrivatePaykitEndpoints -> publicPaykitRepo.syncPaykitApp( - privateSharingEnabled = false, - ) - else -> Result.success(Unit) - } - settingsStore.update { it.copy(publicPaykitCleanupPending = publicCleanup.isFailure) } - publicCleanup.exceptionOrNull()?.let { error -> - privateCleanup.exceptionOrNull()?.let(error::addSuppressed) - throw error - } - privateCleanup.getOrThrow() + suspend fun disablePaykit(): Result = changeSharing { signIn -> + val canSync = { + signIn != null && pubkyRepo.isCurrent(signIn) && !privatePaykitRepo.isProfileDeletionInProgress.value + } + val canUpdateSettings = { + !privatePaykitRepo.isProfileDeletionInProgress.value && + (if (signIn == null) pubkyRepo.currentSignIn() == null else canSync()) + } + runSuspendCatching { + val previous = settingsStore.data.first() + val hadPublicState = previous.hasPublicPaykitPublicationState() + val needsAppCleanup = hadPublicState || previous.sharesPrivatePaykitEndpoints + settingsStore.update { + if (!canUpdateSettings()) throw PublicPaykitError.SessionNotActive + it.paykitDisabled(markPublicCleanupPending = needsAppCleanup) } + val contacts = pubkyRepo.contacts.value.map { it.publicKey } + val privateCleanup = privatePaykitRepo.disableSharingAndPruneUnsavedContactState(contacts, canSync) + val publicCleanup = when { + hadPublicState -> publicPaykitRepo.syncPublishedEndpoints( + publish = false, + appSyncPriority = Priority.Interactive, + isStillCurrent = canSync, + ) + previous.sharesPrivatePaykitEndpoints -> publicPaykitRepo.syncPaykitApp( + privateSharingEnabled = false, + canSync = canSync, + ) + else -> Result.success(Unit) + } + settingsStore.update { + if (!canUpdateSettings()) throw PublicPaykitError.SessionNotActive + it.copy(publicPaykitCleanupPending = publicCleanup.isFailure || signIn == null && needsAppCleanup) + } + publicCleanup.exceptionOrNull()?.let { error -> + privateCleanup.exceptionOrNull()?.let(error::addSuppressed) + throw error + } + privateCleanup.getOrThrow() } } - private suspend fun enable(contacts: List): Result { - val signIn = pubkyRepo.currentSignIn() + private suspend fun enable(contacts: List, signIn: PubkySignIn?): Result { val canSync = { signIn != null && pubkyRepo.isCurrent(signIn) && !privatePaykitRepo.isProfileDeletionInProgress.value } @@ -316,8 +387,7 @@ class ContactPaymentSettingsRepo @Inject constructor( } } - private suspend fun disable(contacts: List): Result { - val signIn = pubkyRepo.currentSignIn() + private suspend fun disable(contacts: List, signIn: PubkySignIn?): Result { val canSync = { signIn != null && pubkyRepo.isCurrent(signIn) && !privatePaykitRepo.isProfileDeletionInProgress.value } diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index aa4408f4f9..1ec0241b32 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -21,7 +21,9 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async 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.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow @@ -69,9 +71,11 @@ import org.lightningdevkit.ldknode.SpendableUtxo import org.lightningdevkit.ldknode.Txid import to.bitkit.async.appScope import to.bitkit.data.CacheStore +import to.bitkit.data.ProfileRemovalStore 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 @@ -145,8 +149,10 @@ 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, + private val profileRemovalStore: ProfileRemovalStore, private val sparkRepo: SparkRepo, ) : OnchainReleasing { private val _lightningState = MutableStateFlow(LightningState()) @@ -463,197 +469,206 @@ class LightningRepo @Inject constructor( shouldRetryYieldToStop: Boolean = false, shouldCancelPendingStop: Boolean = true, stopRequestsSeen: Long? = null, - ): Result = withContext(bgDispatcher) { - if (_isRecoveryMode.value) { - return@withContext Result.failure(RecoveryModeError()) - } - - if (shouldCancelPendingStop) cancelPendingStop() - 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) } + ): Result = vssClients.withWallet { + withContext(bgDispatcher) { + if (_isRecoveryMode.value) { + return@withContext Result.failure(RecoveryModeError()) + } + + if (shouldCancelPendingStop) cancelPendingStop() + val stopRequestsAtStart = stopRequestsSeen ?: stopRequestCount.get() + val isConfigChange = customServerUrl != null || customRgsServerUrl != null + + // Track retry state outside mutex to avoid deadlock (Mutex is non-reentrant) + var shouldRetryStart = false + var shouldRestartForGraphReset = false + var initialLifecycleState: NodeLifecycleState + + // 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, + ) + } - // Track retry state outside mutex to avoid deadlock (Mutex is non-reentrant) - var shouldRetryStart = false - var shouldRestartForGraphReset = false - var initialLifecycleState: NodeLifecycleState + // 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()) + } - 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)) - } - dropStoppedNode() - 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() + ) + ) + } + return@withLock setupResult + } + } - // 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 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)) + } - 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() - ) - ) + 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() } - 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)) - } + lightningService.start(timeout, ::onEvent) - 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() - } + _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) } + listPaymentsKeepingSendHashes() - lightningService.start(timeout, ::onEvent) + // Initial state sync + syncState() + logNodeSupportSummary("node started") + refreshChannelCache() - _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) } - listPaymentsKeepingSendHashes() + if (shouldValidateGraph && !lightningService.aresRequiredPeersInNetworkGraph()) { + Logger.warn("Network graph is stale, resetting and restarting...", context = TAG) - // Initial state sync - syncState() - logNodeSupportSummary("node started") - refreshChannelCache() + lightningService.stop() + clearNetworkGraph(walletIndex) - if (shouldValidateGraph && !lightningService.aresRequiredPeersInNetworkGraph()) { - Logger.warn("Network graph is stale, resetting and restarting...", context = TAG) + _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Stopped) } + shouldRestartForGraphReset = true + return@withLock Result.success(Unit) + } - lightningService.stop() - clearNetworkGraph(walletIndex) + // 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() } - _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Stopped) } - shouldRestartForGraphReset = true - return@withLock Result.success(Unit) - } + 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 + } - // 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() } + 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) + } - 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) + 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 { - reconcileCancelledStart(initialLifecycleState) + // 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) } } - 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) - } - - if (lightningService.status?.isRunning == true) { - Logger.warn("Start error but LDK node is running, adopting it", e, context = TAG) - return@withLock adoptRunningNode() } + } finally { + if (handlerAdded && !handlerAdmitted) _eventHandlers.remove(eventHandler) + } - 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) + // 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 startNode( + walletIndex = walletIndex, + timeout = timeout, + shouldRetry = shouldRetry, + customServerUrl = customServerUrl, + customRgsServerUrl = customRgsServerUrl, + eventHandler = eventHandler, + channelMigration = channelMigration, + shouldValidateGraph = false, // Prevent infinite loop + shouldCancelPendingStop = shouldCancelPendingStop, + stopRequestsSeen = stopRequestsAtStart, + ) } - 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 startNode( - walletIndex = walletIndex, - timeout = timeout, - shouldRetry = shouldRetry, - customServerUrl = customServerUrl, - customRgsServerUrl = customRgsServerUrl, - eventHandler = eventHandler, - channelMigration = channelMigration, - shouldValidateGraph = false, // Prevent infinite loop - shouldCancelPendingStop = shouldCancelPendingStop, - stopRequestsSeen = stopRequestsAtStart, - ) + result } - - result } // A node that panicked stopped itself and refuses to start again, so drop it and build a new one. @@ -669,6 +684,16 @@ class LightningRepo @Inject constructor( } } + 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 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) } @@ -750,8 +775,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 -> { @@ -918,14 +951,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() } } @@ -938,8 +973,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) @@ -3471,100 +3505,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) + suspend fun resetPathfindingScores(walletIndex: Int = 0): Result = vssClients.withWallet { + 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) - } + 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) + } - runCatching { - 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.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, + ) + } } } @@ -3625,31 +3669,36 @@ 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) { - whileStartPending { - 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) { + whileStartPending { + 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/repositories/PaykitPaymentRequestRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentRequestRepo.kt index 4ab3db8576..fbdf9fab37 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentRequestRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentRequestRepo.kt @@ -433,6 +433,11 @@ class PaykitPaymentRequestRepo @Inject constructor( internal val receivedPaymentContactsGeneration: Long get() = stateGeneration.get() + internal fun invalidateReceivedPaymentContacts() { + stateGeneration.incrementAndGet() + receivedContacts = null + } + private data class ReceivedContactsSnapshot( val generation: Long, val identity: String, diff --git a/app/src/main/java/to/bitkit/repositories/PrivatePaykitAddressReservationRepo.kt b/app/src/main/java/to/bitkit/repositories/PrivatePaykitAddressReservationRepo.kt index 84e4b9ec0d..97382fe291 100644 --- a/app/src/main/java/to/bitkit/repositories/PrivatePaykitAddressReservationRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PrivatePaykitAddressReservationRepo.kt @@ -308,6 +308,36 @@ class PrivatePaykitAddressReservationRepo @Inject constructor( }?.first } + internal suspend fun receiptAssignments(): ReceiptAssignments = locked { ledger -> + check(ledger.receiptSourceReadable) { "Receipt reservation source is unavailable" } + check(ledger.version == 1) { "Receipt reservation format is unsupported" } + val assignments = ( + ledger.contactAssignments.map { it.key to it.value } + + ledger.contactAssignmentHistory.flatMap { (publicKey, assignments) -> + assignments.map { publicKey to it } + } + ).distinct() + ReceiptAssignments(assignments, attributionVersion) + } + + internal data class ReceiptAssignments( + val assignments: List>, + val revision: Long, + ) + + internal suspend fun contactsForReceipt( + address: String, + assignments: List>, + ): List { + val addressType = address.addressTypeFromAddress() ?: return emptyList() + return assignments.mapNotNull { (publicKey, assignment) -> + publicKey.takeIf { + assignment.addressType == addressType && + (assignment.address == address || resolvedAddress(assignment).getOrThrow() == address) + } + } + } + suspend fun currentContactPublicKeyForReservedAddress(address: String): String? = withContext(ioDispatcher) { if (address.isBlank()) return@withContext null val addressType = address.addressTypeFromAddress() ?: return@withContext null @@ -397,8 +427,9 @@ class PrivatePaykitAddressReservationRepo @Inject constructor( suspend fun clear() = withContext(ioDispatcher) { locked { - ledger = PrivatePaykitReservationData() + ledger = null reservationStore.reset() + ledger = PrivatePaykitReservationData() notifyBackupStateChanged() } } @@ -441,10 +472,15 @@ class PrivatePaykitAddressReservationRepo @Inject constructor( current.contactAssignmentHistory + (assignmentKey to history) }, ) - persist(next) - ledger = 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 47c01cdf88..d2d0e617bd 100644 --- a/app/src/main/java/to/bitkit/repositories/PrivatePaykitContactResolver.kt +++ b/app/src/main/java/to/bitkit/repositories/PrivatePaykitContactResolver.kt @@ -4,8 +4,14 @@ import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.first import kotlinx.coroutines.withContext import to.bitkit.data.PrivatePaykitCacheStore +import to.bitkit.data.PrivatePaykitStoredAssignmentData +import to.bitkit.data.ProfileRemovalPending +import to.bitkit.data.ProfileRemovalStore +import to.bitkit.data.WalletConnectionRecovery import to.bitkit.di.IoDispatcher +import to.bitkit.ext.runSuspendCatching import to.bitkit.models.PubkyPublicKeyFormat +import java.util.concurrent.atomic.AtomicBoolean import javax.inject.Inject import javax.inject.Provider import javax.inject.Singleton @@ -16,7 +22,129 @@ class PrivatePaykitContactResolver @Inject constructor( private val cacheStore: PrivatePaykitCacheStore, private val addressReservationRepo: Provider, private val paymentRequestRepo: Provider, + private val profileRemovalStore: ProfileRemovalStore, + private val connectionRecovery: Provider, ) { + /** Local receipt associations belong to the wallet that admitted the incoming synchronization. */ + internal suspend fun withReceiptOperation(block: suspend (Receipt) -> T): T = + connectionRecovery.get().withReceiptOperation { session -> + session.requireCurrent() + val snapshot = runSuspendCatching { + profileRemovalStore.withReceiptSnapshot { + val cache = cacheStore.data.first() + check(cache.receiptSourceReadable) { "Receipt invoice source is unavailable" } + val shared = receivedPaymentContacts + val requestGeneration = receivedPaymentContactsGeneration + val reserved = addressReservationRepo.get().receiptAssignments() + check( + cacheStore.data.first() == cache && receivedPaymentContacts === shared && + reservationVersion == reserved.revision && + receivedPaymentContactsGeneration == requestGeneration + ) { "Receipt associations changed during capture" } + val invoiceContacts = mutableMapOf>() + cache.contacts.forEach { (key, value) -> + (value.receivedInvoicePaymentHashes + listOfNotNull(value.localInvoice?.paymentHash)) + .forEach { hash -> invoiceContacts.getOrPut(hash) { mutableSetOf() }.add(key) } + } + ReceiptSnapshot( + session.receiptGeneration, + invoiceContacts.mapValues { it.value.toSet() }, + shared, + reserved.assignments, + requestGeneration, + reserved.revision + ) + } + }.getOrElse { + if (it is ProfileRemovalPending) throw it + null + } + profileRemovalStore.requireReceiptAccountingAccess() + session.requireCurrent() + block(Receipt(session, snapshot)) + } + + internal inner class Receipt internal constructor( + private val session: WalletConnectionRecovery.Session, + /** Null is unavailable association evidence, never a complete empty source or completed backfill. */ + val snapshot: ReceiptSnapshot?, + ) { + private val lookupFailed = AtomicBoolean(false) + val associationsComplete: Boolean get() = snapshot != null && !lookupFailed.get() + + fun requireCurrent() = session.requireCurrent() + + private suspend fun lookupAssociations(block: suspend () -> T): T? { + val result = runSuspendCatching { block() } + requireCurrent() + if (result.isFailure) lookupFailed.set(true) + return result.getOrNull() + } + + fun commit(block: () -> T): T = session.commitReceiptState(block) + + fun contactForInvoice(paymentHash: String): String? { + requireCurrent() + val source = snapshot ?: return null + if (paymentHash.isBlank()) return null + return (source.invoiceContacts[paymentHash].orEmpty() + source.requests.contactsForPaymentHash(paymentHash)) + .mapNotNull(PubkyPublicKeyFormat::normalized).distinct().singleOrNull() + } + + suspend fun contactForAddresses(receivingAddress: String?, addresses: Collection): String? { + requireCurrent() + val source = snapshot ?: return null + if (receivingAddress.isNullOrBlank() || receivingAddress !in addresses) return null + val reserved = lookupAssociations { + addresses.distinct().associateWith { + addressReservationRepo.get().contactsForReceipt(it, source.assignments) + } + } ?: return null + val receivingContacts = reserved[receivingAddress].orEmpty() + + source.requests.contactsForAddresses(listOf(receivingAddress)) + val contact = receivingContacts.mapNotNull(PubkyPublicKeyFormat::normalized).distinct().singleOrNull() + ?: return null + return contact.takeIf { + (reserved.values.flatten() + source.requests.contactsForAddresses(addresses)) + .mapNotNull(PubkyPublicKeyFormat::normalized).distinct().singleOrNull() == contact + } + } + + suspend fun isReservedReceiveAddress(address: String): Boolean { + requireCurrent() + return lookupAssociations { + val source = snapshot + if (source == null) { + addressReservationRepo.get().isUnavailableForReusableReceive(address) + } else { + addressReservationRepo.get().contactsForReceipt(address, source.assignments).isNotEmpty() + } + } ?: false + } + } + + internal data class ReceiptSnapshot( + val walletGeneration: Long, + val invoiceContacts: Map>, + val requests: PaykitReceivedPaymentContacts, + val assignments: List>, + val requestGeneration: Long, + val reservationRevision: Long, + ) + + 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 +156,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 +165,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 +182,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 +194,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 30ff485c57..c438661a7b 100644 --- a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt @@ -18,6 +18,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 @@ -42,6 +43,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 @@ -89,6 +91,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" @@ -129,10 +132,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 @@ -223,6 +228,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() @@ -310,12 +325,12 @@ class PrivatePaykitRepo @Inject constructor( return admittedPriority } - 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 } ) @@ -350,7 +365,7 @@ class PrivatePaykitRepo @Inject constructor( } }.onFailure { if (it == PaykitPaymentRequestError.OperationInProgress) { - if (generation == preparationGeneration && !isDeletingProfile) { + if (generation == preparationGeneration && !isDeletingProfile()) { pendingPreparationKeys.addAll(keys.intersect(knownSavedContactKeys)) activePreparationKeys = emptySet() delay(privateMessageDrainRetryDelays.first()) @@ -376,13 +391,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 + } + } + + internal suspend fun endProfileDeletion(pause: ProfileDeletionPause) = withContext(serializedDispatcher) { + profileDeletionPauses.remove(pause) + _isProfileDeletionInProgress.value = recoveryPending || profileDeletionPauses.isNotEmpty() } - suspend fun endProfileDeletion() = withContext(serializedDispatcher) { - _isProfileDeletionInProgress.update { false } + internal suspend fun withProfileDeletionPaused( + operation: suspend (ProfileDeletionPause) -> T, + ): T { + val pause = beginProfileDeletion() + try { + return operation(pause) + } finally { + withContext(NonCancellable) { endProfileDeletion(pause) } + } } suspend fun refreshSavedContactEndpoints( @@ -394,7 +434,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( @@ -431,7 +471,8 @@ class PrivatePaykitRepo @Inject constructor( ): Result = withContext(serializedDispatcher) { runContactSync { checkPaykitContactSync(isStillCurrent) - if (isDeletingProfile) return@runContactSync + if (isDeletingProfile()) return@runContactSync + profileRemovalStore.requireNoPending() val settings = settingsStore.data.first() val hasDisabledPublications = !settings.sharesPrivatePaykitEndpoints && hasPublishedPrivateEndpoints() val cleanupPending = isContactSharingCleanupPending() @@ -479,7 +520,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) @@ -489,7 +530,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) } } @@ -528,10 +569,28 @@ class PrivatePaykitRepo @Inject constructor( suspend fun removePublishedEndpointsForCleanup( context: String, deferAppSync: Boolean, + ): Result = removePublishedEndpointsForCleanup(context, deferAppSync, requireAcknowledgement = false) + + suspend fun removePublishedEndpointsForProfileRemoval(onAcknowledged: () -> Unit = {}): Result = + removePublishedEndpointsForCleanup( + "profile removal", + deferAppSync = true, + requireAcknowledgement = true, + onAcknowledged = onAcknowledged, + ) + + private suspend fun removePublishedEndpointsForCleanup( + context: String, + deferAppSync: Boolean, + requireAcknowledgement: Boolean, + onAcknowledged: (() -> Unit)? = null, ): Result = withContext(serializedDispatcher) { runSuspendCatching { updateContactSharingCleanupPending(true) - removePublishedEndpoints().getOrThrow() + removePublishedEndpoints( + requireAcknowledgement = requireAcknowledgement, + onAcknowledged = onAcknowledged, + ).getOrThrow() if (!deferAppSync) { syncPaykitAppAfterCleanup().getOrThrow() updateContactSharingCleanupPending(false) @@ -544,21 +603,53 @@ 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" } + profileRemovalStore.withReceiptCleanup { + paymentRequestRepo.invalidateReceivedPaymentContacts() + clearLocalPaymentState() + } + notifyBackupStateChanged() + } + } + } + + /** 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() + unavailableLinkRetryAt.clear() + state = PrivatePaykitState() + cacheStore.reset() + addressReservationRepo.clearContactAssignments(excludingPublicKeys = emptySet()) + } + /** * Opens a payment to the saved contact [publicKey]. A contact with a private payment path is only paid * privately: when that path is not ready yet the result is [PublicPaykitPaymentResult.PrivateLinkPending], never @@ -867,18 +958,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) @@ -904,6 +999,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 @@ -1163,7 +1259,7 @@ class PrivatePaykitRepo @Inject constructor( if (paykitSdkService.identityStatus(Priority.Interactive)?.publicKey == null) return null val normalizedKey = normalizedPublicKey(publicKey) ?: return null paykitSdkService.contactRecord(normalizedKey) ?: return null - if (!isDeletingProfile) rememberSavedContacts(listOf(normalizedKey), replacing = false) + if (!isDeletingProfile()) rememberSavedContacts(listOf(normalizedKey), replacing = false) return normalizedKey } @@ -1317,7 +1413,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 } @@ -1451,9 +1547,9 @@ class PrivatePaykitRepo @Inject constructor( generation: Int, priority: Priority = Priority.Ordered, ) { - if (isDeletingProfile || generation != preparationGeneration) return + if (isDeletingProfile() || generation != preparationGeneration) return if (isContactSharingCleanupPending() || !hasPrivatePaymentAccessForCurrentProfile(priority)) return - if (isDeletingProfile || generation != preparationGeneration) return + if (isDeletingProfile() || generation != preparationGeneration) return drainAndSchedulePrivateLinkRetries(reason, publicKeys.distinct(), generation, priority) } @@ -1465,12 +1561,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) } } @@ -1660,7 +1756,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 @@ -2056,11 +2152,19 @@ class PrivatePaykitRepo @Inject constructor( persistState(markWalletBackup = true) } - private suspend fun removePublishedEndpoints(isStillCurrent: (() -> Boolean)? = null): Result = + private suspend fun removePublishedEndpoints( + isStillCurrent: (() -> Boolean)? = null, + requireAcknowledgement: Boolean = false, + onAcknowledged: (() -> Unit)? = null, + ): Result = withContext(serializedDispatcher) { runSuspendCatching { publicationMutex.withLock { - removePublishedEndpointsLocked(isStillCurrent = isStillCurrent).getOrThrow() + removePublishedEndpointsLocked( + isStillCurrent = isStillCurrent, + requireAcknowledgement = requireAcknowledgement, + onAcknowledged = onAcknowledged, + ).getOrThrow() } } } @@ -2078,36 +2182,56 @@ class PrivatePaykitRepo @Inject constructor( private suspend fun removePublishedEndpointsLocked( publicKeys: Collection? = null, isStillCurrent: (() -> Boolean)? = null, + requireAcknowledgement: Boolean = false, + onAcknowledged: (() -> Unit)? = null, ): 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 + if (normalizedKeys.isEmpty()) { + if (requireAcknowledgement) onAcknowledged?.invoke() + return@runSuspendCatching + } ensureState() checkPaykitContactSync(isStillCurrent) val cleanupStateByPublicKey = normalizedKeys.associateWith(::publishedEndpointCleanupState) - val preparation = clearPrivatePaymentLists(normalizedKeys, linkedPublicKeys, isStillCurrent) + val preparation = clearPrivatePaymentLists( + normalizedKeys, + linkedPublicKeys, + isStillCurrent, + requireAcknowledgement, + onAcknowledged, + ) 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 @@ -2182,15 +2306,29 @@ class PrivatePaykitRepo @Inject constructor( publicKeys: Collection, linkedPublicKeys: Set, isStillCurrent: (() -> Boolean)? = null, + requireAcknowledgement: Boolean = false, + onAcknowledged: (() -> Unit)? = null, ): PrivateEndpointCleanupPreparation { val cleanupKeys = publicKeys.filter { it in linkedPublicKeys || state?.contacts?.get(it)?.hasPublishedPrivatePaymentList == true } - if (cleanupKeys.isEmpty()) return PrivateEndpointCleanupPreparation(emptyList(), emptySet(), null) + if (cleanupKeys.isEmpty()) { + if (requireAcknowledgement) onAcknowledged?.invoke() + return PrivateEndpointCleanupPreparation(emptyList(), emptySet(), null) + } return runSuspendCatching { - val report = paykitSdkService.clearPrivatePaymentLists(cleanupKeys, isStillCurrent) - ?: return@runSuspendCatching PrivateEndpointCleanupPreparation(emptyList(), emptySet(), null) + val report = paykitSdkService.clearPrivatePaymentLists(cleanupKeys, isStillCurrent) { + if (requireAcknowledgement && hasAcknowledgedWithdrawals(it, cleanupKeys)) onAcknowledged?.invoke() + } + 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 } + @@ -2209,6 +2347,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, @@ -2372,24 +2524,29 @@ 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, priority: Priority = Priority.Ordered, ): 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(priority) } - return hasAccess && !isDeletingProfile + return hasAccess && !isDeletingProfile() } private suspend fun hasPrivatePaymentAccessForCurrentProfile(priority: Priority): Boolean = runSuspendCatching { @@ -2558,8 +2715,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( @@ -2567,6 +2728,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..4d044c197f --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/PubkyIdentityOperations.kt @@ -0,0 +1,151 @@ +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( + 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 { + 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 && cancelOnWipe) restoreRefused = true + if (wiping || removal != null) throw PubkyIdentityBusy + Operation(this, cancelOnWipe).also(active::add) + } + return try { + run(operation) { + beforeTransition() + block() + } + } catch (e: CancellationException) { + if (operation.isCancelled && currentCoroutineContext().isActive) throw PubkyIdentityBusy + throw e + } + } + + 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" + } + } + + /** 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) { + if (wiping) throw PubkyIdentityBusy + wiping = true + 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.forEach { it.cancel() } + var wiped = false + try { + beforeWipeDrain() + draining.forEach { it.drained.await() } + val operation = synchronized(lock) { + Operation(this).also { + active.add(it) + wipeOperation = it + } + } + return run(operation, block).also { wiped = true } + } finally { + val restoreInterrupted = synchronized(lock) { + wiping = false + wipeOperation = null + (restoreRefused || cancelled.any { it.cancelOnWipe }).also { restoreRefused = false } + } + if (!wiped && restoreInterrupted) afterInterruptedRestore() + } + } + + private suspend fun run(operation: Operation, block: suspend () -> T): T { + try { + return withContext(operation) { + operation.bind(requireNotNull(currentCoroutineContext()[Job])) + currentCoroutineContext().ensureActive() + block() + } + } finally { + synchronized(lock) { + active.remove(operation) + if (removal === operation) removal = null + } + operation.drained.complete(Unit) + } + } + + 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) { + 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 2afb33859b..e6f8620f61 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 @@ -47,13 +48,13 @@ import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import to.bitkit.async.appScope import to.bitkit.data.PUBKY_IMAGE_MAX_BYTES +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 @@ -80,12 +81,16 @@ import to.bitkit.models.isSocialV1WebUri import to.bitkit.models.singleLine import to.bitkit.models.takeCodePoints import to.bitkit.models.toPubkyAppLinkUrl +import to.bitkit.services.PaykitProfileDeletionSnapshot +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 +import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicLong import javax.inject.Inject @@ -103,6 +108,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") } @@ -115,6 +121,22 @@ 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, + val deletePubkyProfile: Boolean, + val pubkyProfileRevision: String?, +) { + val pubkyProfileAcknowledged = AtomicBoolean(false) +} + private fun Throwable.hasCause(error: AppError): Boolean = generateSequence(this) { it.cause }.any { it == error } @@ -171,6 +193,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) @@ -186,6 +211,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" @@ -221,6 +247,11 @@ class PubkyRepo @Inject constructor( private val scope = appScope(ioDispatcher, TAG) private val serviceInitializeMutex = Mutex() private val initializeMutex = Mutex() + private val identityOperations = PubkyIdentityOperations( + beforeTransition = ::requireNoPendingRemoval, + beforeWipeDrain = pubkyService::beginWalletWipe, + afterInterruptedRestore = { scope.launch { resumeInterruptedRestore() } }, + ) private val deferredRestoreMutex = Mutex() private var deferredRestoreGeneration: Long? = null private val completedRestoreVersion = AtomicLong() @@ -347,12 +378,24 @@ 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) + + val profileRecoveryCanDisconnect: StateFlow = profileRemovalStore.localDisconnectAvailable + .stateIn(scope, SharingStarted.Eagerly, false) + + 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) @@ -435,13 +478,90 @@ class PubkyRepo @Inject constructor( } private val initializationReady = CompletableDeferred() + private val restoreInitializationLock = Any() + private var restoreInitialization: Pair? = null init { scope.launch { initialize() }.invokeOnCompletion { + // A wipe can cancel startup before the restore clears this flag itself. + if (!initializationReady.isCompleted) _isRestoringSession.update { false } initializationReady.complete(Unit) } } + 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.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) + } + } + + private suspend fun identityTransition( + cancelOnWipe: Boolean = false, + operation: suspend () -> Result, + ): Result = runSuspendCatching { identityOperations.transition(cancelOnWipe) { 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) + + internal suspend fun captureProfileLogout(owner: PubkyProfileOwner): Result = + runSuspendCatching { + var captured: PaykitProfileLogout? = null + try { + performProfileRemoval(owner) { + val publicKey = checkNotNull(owner.signIn).publicKey + captured = pubkyService.captureProfileLogout(publicKey) { isProfileOwnerCurrent(owner) } + }.getOrThrow() + check(isProfileOwnerCurrent(owner)) { "The profile identity changed" } + checkNotNull(captured) + } catch (error: Throwable) { + captured?.revoke() + throw error + } + } + // region Initialization suspend fun awaitInitialization() = withContext(ioDispatcher) { @@ -449,22 +569,90 @@ 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() = 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 = + identityTransition(cancelOnWipe = true) { initializeForRevisionAdmitted(expectedRevision) } + + private suspend fun initializeForRevisionAdmitted( + expectedRevision: Long? = null, + ): Result = withContext(ioDispatcher) { + val (restored, revision) = initializeMutex.withLock { + if (expectedRevision != null && expectedRevision != storedIdentityRevision.get()) { + return@withContext Result.success(Unit) + } + 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() + if (revision != storedIdentityRevision.get()) return@withContext Result.success(Unit) checkAdoptedSource() } - suspend fun restoreSessionIfNeeded() = withContext(ioDispatcher) { + suspend fun restoreSessionIfNeeded(): Boolean = try { + identityOperations.transition(cancelOnWipe = true) { restoreSessionIfNeededAdmitted() } + } catch (_: PubkyIdentityBusy) { + false + } catch (_: ProfileRemovalPending) { + false + } + + private suspend fun restoreSessionIfNeededAdmitted() = withContext(ioDispatcher) { awaitInitialization() val restored = restoreSession() - if (restored) loadIdentityData() + if (restored) { + loadIdentityData() + } else { + currentSignIn()?.takeIf { _profile.value == null }?.let { signIn -> + scope.launch { + if (!settingsStore.isPubkyProfileSetupPending.first()) { + loadProfile(signIn, onlyIfMissing = true) + } + } + } + } restored } + private suspend fun resumeInterruptedRestore() { + 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. */ suspend fun retryDeferredSessionRestoration() = withContext(ioDispatcher) { deferredRestoreMutex.withLock { @@ -489,6 +677,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() @@ -510,7 +699,15 @@ class PubkyRepo @Inject constructor( } } - private suspend fun restoreSession(expectedGeneration: Long? = null): Boolean { + private suspend fun restoreSession(expectedGeneration: Long? = null): Boolean = try { + identityOperations.transition(cancelOnWipe = true) { 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 && @@ -608,14 +805,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() } } } @@ -706,7 +906,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) } @@ -746,6 +949,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 { @@ -826,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() @@ -872,6 +1082,21 @@ class PubkyRepo @Inject constructor( } } + internal suspend fun removeBitkitPaymentEndpointsForRemoval( + endpointsAcknowledged: Boolean, + appAcknowledged: Boolean, + onEndpointsAcknowledged: () -> Unit, + onAppAcknowledged: () -> Unit, + ): Result = runSuspendCatching { + identityOperations.requireRemoval() + pubkyService.removeBitkitPaymentEndpointsForRemoval( + endpointsAcknowledged, + appAcknowledged, + onEndpointsAcknowledged, + onAppAcknowledged, + ) + } + suspend fun currentPublicKey(): Result = withContext(ioDispatcher) { runSuspendCatching { pubkyService.currentPublicKey()?.ensurePubkyPrefix() @@ -912,9 +1137,14 @@ class PubkyRepo @Inject constructor( suspend fun loadProfile() { val signIn = currentSignIn() ?: return loadReadOnlyProfile() + loadProfile(signIn) + } + + private suspend fun loadProfile(signIn: PubkySignIn, onlyIfMissing: Boolean = false) { val version = completedProfileLoadVersion.get() loadProfileMutex.withLock { if (!isCurrent(signIn)) return + if (onlyIfMissing && _profile.value != null) return val writeGeneration = profileWriteGeneration.get() if (completedProfileLoadVersion.get() != version && completedProfileSignInGeneration == signIn.generation && completedProfileWriteGeneration == writeGeneration @@ -927,36 +1157,39 @@ class PubkyRepo @Inject constructor( try { runSuspendCatching { withContext(ioDispatcher) { - loadOwnProfile(signIn.publicKey) ?: throw PubkyProfileNotFoundError() + loadOwnProfile(signIn) ?: throw PubkyProfileNotFoundError() } }.onSuccess { loaded -> - val installed = synchronized(profileStateLock) { - if (!isCurrentLoad()) return@synchronized false - ownProfileRevision = loaded.revision - tagsReadEpoch.incrementAndGet() - tagsUnavailable = loaded.tagsUnread - _profile.value = loaded.profile - true + val installed = initializeMutex.withLock { + synchronized(profileStateLock) { + if (!isCurrentLoad()) return@synchronized false + ownProfileRevision = loaded.revision + tagsReadEpoch.incrementAndGet() + tagsUnavailable = loaded.tagsUnread + _profile.value = loaded.profile + true + }.also { if (it) invalidateReadOnlyProfile() } } if (!installed) { Logger.debug("Skipped stale profile load for '${redacted(signIn.publicKey)}'", context = TAG) return@onSuccess } - invalidateReadOnlyProfile() cacheMetadata(loaded.profile, isCurrentLoad) }.onFailure { Logger.error("Failed to load profile", it, context = TAG) // A profile deleted on pubky.app is set up again rather than left unreachable. if (it is PubkyProfileNotFoundError) { - val cleared = synchronized(profileStateLock) { - if (!isCurrentLoad()) return@synchronized false - ownProfileRevision = null - tagsUnavailable = false - tagsReadEpoch.incrementAndGet() - _profile.value = null - true + initializeMutex.withLock { + val cleared = synchronized(profileStateLock) { + if (!isCurrentLoad()) return@synchronized false + ownProfileRevision = null + tagsUnavailable = false + tagsReadEpoch.incrementAndGet() + _profile.value = null + true + } + if (cleared) settingsStore.setPubkyProfileSetupPending(true) } - if (cleared) settingsStore.setPubkyProfileSetupPending(true) } } completedProfileSignInGeneration = signIn.generation @@ -1046,6 +1279,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) { @@ -1105,6 +1347,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) } @@ -1121,12 +1364,19 @@ class PubkyRepo @Inject constructor( ): SavedProfile { // A restore saves against the pubky.app profile its form was filled from; without one it creates the profile. val restore = restoreBase?.takeIf { it.publicKey == publicKey } - val imageUrl = avatarBytes?.let { uploadAvatar(it, publicKey).getOrNull() } ?: restore?.profile?.imageUrl + val imageUrl = avatarBytes?.let { uploadAvatarLocked(it, publicKey).getOrNull() } ?: restore?.profile?.imageUrl val base = restore?.profile?.takeIf { restore.revision != null } val saved = runSuspendCatching { writeProfile( - publicKey, name, bio, links, tags, imageUrl, base, + publicKey, + name, + bio, + links, + tags, + imageUrl, + base, expectedRevision = restore?.revision, + signIn = null, tagsUnread = restore?.tagsUnread == true, ) }.getOrElse { @@ -1176,14 +1426,27 @@ class PubkyRepo @Inject constructor( return clearedLocalState } - suspend fun uploadAvatar(imageBytes: ByteArray, publicKey: String? = null): Result = runSuspendCatching { + suspend fun uploadAvatar(imageBytes: ByteArray, publicKey: String? = null): Result = identityTransition { + val owner = profileOwner() + withContext(ioDispatcher) { + initializeMutex.withLock { + check(isProfileOwnerCurrent(owner)) { "Profile identity changed before avatar upload" } + uploadAvatarLocked(imageBytes, publicKey) + } + } + } + + private suspend fun uploadAvatarLocked( + imageBytes: ByteArray, + publicKey: String?, + ): Result = runSuspendCatching { withContext(ioDispatcher) { requireNotNull(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)) { "No session available" } val identity = requireNotNull(publicKey ?: _publicKey.value) { "No public key available" } val compressed = compressAvatar(imageBytes) - withPubkyAppScope { pubkyService.uploadPubkyAppAvatar(compressed, "image/jpeg", identity) } + withPubkyAppScopeLocked(identity) { pubkyService.uploadPubkyAppAvatar(compressed, "image/jpeg", identity) } } } @@ -1207,6 +1470,15 @@ class PubkyRepo @Inject constructor( tags: List, imageUrl: String?, editBase: ProfileEditBase, + ): Result = identityTransition { saveProfileAdmitted(name, bio, links, tags, imageUrl, editBase) } + + private suspend fun saveProfileAdmitted( + name: String, + bio: String, + links: List, + tags: List, + imageUrl: String?, + editBase: ProfileEditBase, ): Result = runSuspendCatching { withContext(ioDispatcher) { requireNotNull(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)) { @@ -1224,6 +1496,7 @@ class PubkyRepo @Inject constructor( imageUrl, base = editBase.profile.takeIf { editBase.revision != null }, expectedRevision = editBase.revision, + signIn = signIn, tagsUnread = editBase.tagsUnread, ) }.getOrElse { @@ -1240,79 +1513,103 @@ 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)) { - "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) } + val deletePubkyProfile = !isRingAdoptedIdentity() + val pubkyRevision = if (deletePubkyProfile) { + pubkyService.fetchPubkyProfileWithRevision(signIn.publicKey)?.revision + } else { + null } - clearSessionContactProfiles() - deleteAllContacts() - profileWriteMutex.withLock { - profileDeletionGeneration.incrementAndGet() - try { - if (!isRingAdoptedIdentity()) deletePubkyAppProfile() - runSuspendCatching { - pubkyService.deletePaykitProfile() - }.getOrElse { - if (!it.isMissingPubkyData()) { - throw it + check(isProfileOwnerCurrent(owner) && revision == profileWriteGeneration.get()) { + "Profile changed; review it before removing it" + } + PubkyProfileDeletion(owner, revision, snapshot, deletePubkyProfile, pubkyRevision) + }.recoverCatching { + generateSequence(it) { error -> error.cause } + .filterIsInstance() + .firstOrNull()?.let { error -> throw error } + if (it.hasCause(PubkyContactError.ActiveSubscription)) throw PubkyContactError.ActiveSubscription + throw it + } + + internal suspend fun validateProfileDeletion(deletion: PubkyProfileDeletion) { + identityOperations.requireRemoval() + check(isProfileOwnerCurrent(deletion.owner) && deletion.profileWriteRevision == profileWriteGeneration.get()) { + "Profile changed; review it before removing it" + } + check(deletion.deletePubkyProfile == !isRingAdoptedIdentity()) { "Profile ownership changed" } + if (deletion.deletePubkyProfile) { + val revision = pubkyService.fetchPubkyProfileWithRevision(deletion.snapshot.publicKey)?.revision + check(revision == if (deletion.pubkyProfileAcknowledged.get()) null else deletion.pubkyProfileRevision) { + "Profile changed; review it before removing it" + } + } + runSuspendCatching { pubkyService.validateProfileDeletion(deletion.snapshot) }.recoverCatching { + generateSequence(it) { error -> error.cause } + .filterIsInstance() + .firstOrNull()?.let { error -> throw error } + if (it.hasCause(PubkyContactError.ActiveSubscription)) throw PubkyContactError.ActiveSubscription + throw it + }.getOrThrow() + } + + internal suspend fun deleteProfile( + deletion: PubkyProfileDeletion, + onAcknowledged: () -> Unit = {}, + ): Result = runSuspendCatching { + identityOperations.requireRemoval() + check(isProfileOwnerCurrent(deletion.owner)) { "Profile removal identity changed" } + clearSessionContactProfiles() + deleteContacts(deletion.snapshot.contacts) + profileWriteMutex.withLock { + profileDeletionGeneration.incrementAndGet() + try { + if (deletion.deletePubkyProfile && !deletion.pubkyProfileAcknowledged.get()) { + val revision = deletion.pubkyProfileRevision + if (revision == null) { + check(pubkyService.fetchPubkyProfileWithRevision(deletion.snapshot.publicKey) == null) { + "Profile changed; review it before removing it" + } + deletion.pubkyProfileAcknowledged.set(true) + } else { + pubkyService.deletePubkyProfile(revision, deletion.snapshot.publicKey) { + deletion.pubkyProfileAcknowledged.set(true) } - Logger.info("Continuing sign out, bitkit profile storage already missing", context = TAG) } - } finally { - profileDeletionGeneration.incrementAndGet() + ownProfileRevision = null } + pubkyService.deletePaykitProfile(deletion.snapshot, onAcknowledged) + } finally { + profileDeletionGeneration.incrementAndGet() } - profileWriteGeneration.incrementAndGet() - } - settingsStore.update { it.paykitDisabled(markPublicCleanupPending = it.hasPaykitState()) } - signOut().getOrThrow() - } - - private suspend fun deletePubkyAppProfile() { - val publicKey = _publicKey.value ?: return - val known = ownProfileRevision - val revision = known ?: pubkyService.fetchPubkyProfileWithRevision(publicKey)?.revision ?: return - runSuspendCatching { withPubkyAppScope { pubkyService.deletePubkyProfile(revision, publicKey) } }.getOrElse { - if (known == null || !it.isConcurrentUpdate()) throw it - val current = pubkyService.fetchPubkyProfileWithRevision(publicKey)?.revision - if (current != null) withPubkyAppScope { pubkyService.deletePubkyProfile(current, publicKey) } } - ownProfileRevision = null + profileWriteGeneration.incrementAndGet() + }.recoverCatching { + generateSequence(it) { error -> error.cause } + .filterIsInstance() + .firstOrNull()?.let { error -> throw error } + if (it.hasCause(PubkyContactError.ActiveSubscription)) throw PubkyContactError.ActiveSubscription + throw it } - 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()) } + private suspend fun deleteContacts(records: List) { + if (records.isEmpty()) return + val keys = records.map { it.publicKey.ensurePubkyPrefix() }.toSet() + val removedKeys = pubkyService.removeContactsForProfile(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) } @@ -1325,12 +1622,24 @@ class PubkyRepo @Inject constructor( imageUrl: String?, base: PubkyProfile?, expectedRevision: String?, + signIn: PubkySignIn?, tagsUnread: Boolean = false, ): SavedProfile { profileSaveEpoch.incrementAndGet() profileSavesRunning.incrementAndGet() try { - return writeProfileOnce(publicKey, name, bio, links, tags, imageUrl, base, expectedRevision, tagsUnread) + return writeProfileOnce( + publicKey, + name, + bio, + links, + tags, + imageUrl, + base, + expectedRevision, + signIn, + tagsUnread, + ) } finally { profileSavesRunning.decrementAndGet() profileSaveEpoch.incrementAndGet() @@ -1346,6 +1655,7 @@ class PubkyRepo @Inject constructor( imageUrl: String?, base: PubkyProfile?, expectedRevision: String?, + signIn: PubkySignIn?, tagsUnread: Boolean, ): SavedProfile { val generation = profileDeletionGeneration.get() @@ -1376,9 +1686,7 @@ class PubkyRepo @Inject constructor( links = links.takeIf { base == null || it != base.links } ?.map { SdkPubkyProfileLink(title = it.label, url = it.url) }, ) - val snapshot = profileWrite(generation) { - withPubkyAppScope { pubkyService.publishPubkyProfile(update, expectedRevision, publicKey) } - } + val snapshot = publishProfileSnapshot(signIn, generation, publicKey, update, expectedRevision) ownProfileRevision = snapshot.revision val baseTags = base?.tags.orEmpty() val stored = storedCopy(publicKey, copyUnread) @@ -1392,11 +1700,7 @@ class PubkyRepo @Inject constructor( else -> null } val avatarPending = pendingAvatar != null || keepPending - pubkyStore.update { - val keys = it.pubkyAppAvatarPending - val pending = if (avatarPending) keys + publicKey else keys - publicKey - it.copy(pubkyAppProfileOwners = it.pubkyAppProfileOwners + publicKey, pubkyAppAvatarPending = pending) - } + updateProfileOwnership(signIn, publicKey, avatarPending) val keptTags = stored?.let { copy -> copy.tags?.let { it + tags.filterNot { tag -> tag in it } } ?: tags } val profile = PubkyProfile.fromPubkyProfile(publicKey, snapshot.profile).let { it.copy(tags = keptTags ?: baseTags, imageUrl = pendingAvatar ?: it.imageUrl) @@ -1450,6 +1754,32 @@ class PubkyRepo @Inject constructor( } } + private suspend fun publishProfileSnapshot( + signIn: PubkySignIn?, + generation: Long, + publicKey: String, + update: PubkyProfileUpdate, + expectedRevision: String?, + ): PubkyProfileSnapshot { + val publish = suspend { + withPubkyAppScopeLocked(publicKey) { pubkyService.publishPubkyProfile(update, expectedRevision, publicKey) } + } + return if (signIn == null) { + profileWrite(generation, publish) + } else { + profileWrite(signIn, generation, publish) + } + } + + private suspend fun updateProfileOwnership(signIn: PubkySignIn?, publicKey: String, avatarPending: Boolean) { + pubkyStore.update { + if (signIn != null && !isCurrent(signIn)) return@update it + val keys = it.pubkyAppAvatarPending + val pending = if (avatarPending) keys + publicKey else keys - publicKey + it.copy(pubkyAppProfileOwners = it.pubkyAppProfileOwners + publicKey, pubkyAppAvatarPending = pending) + } + } + /** * What a save keeps from the Paykit copy after the last load could not read it, as the form then lacked its tags * and the avatar still to move: empty when that load read it, null while it still cannot be read. @@ -1474,18 +1804,21 @@ class PubkyRepo @Inject constructor( .take(PUBKY_APP_LINKS_MAX_COUNT), ) - private suspend fun loadOwnProfile(publicKey: String): LoadedProfile? { + private suspend fun loadOwnProfile(signIn: PubkySignIn): LoadedProfile? { + val publicKey = signIn.publicKey val generation = profileDeletionGeneration.get() val saveEpoch = profileSaveEpoch.get() val paykitRead = runSuspendCatching { pubkyService.fetchPaykitProfile(publicKey) } .onFailure { Logger.warn("Failed to read Bitkit profile copy", it, context = TAG) } + initializeMutex.withLock { requireCurrent(signIn) } val paykitData = paykitRead.getOrNull()?.let { PubkyProfileData.fromPaykitProfile(it.profile) } val fetched = readRetryingOnce(publicKey) { pubkyService.fetchPubkyProfileWithRevision(publicKey) } if (fetched == null) paykitRead.getOrThrow() val stored = pubkyStore.data.first() + requireCurrent(signIn) val hadPubkyAppProfile = publicKey in stored.pubkyAppProfileOwners val migrating = fetched == null && !hadPubkyAppProfile - var snapshot = fetched ?: paykitData?.takeIf { migrating }?.let { migrateToPubkyApp(publicKey, it, generation) } + var snapshot = fetched ?: paykitData?.takeIf { migrating }?.let { migrateToPubkyApp(signIn, it, generation) } // While the move cannot finish, the Bitkit profile is shown and the next save creates the pubky.app profile. snapshot ?: return paykitData?.takeIf { migrating }?.let { LoadedProfile(it.toPubkyProfile(publicKey), revision = null, tagsUnread = false) @@ -1496,32 +1829,36 @@ class PubkyRepo @Inject constructor( if (retryingAvatar && avatarMoveSettled) { // An avatar set on pubky.app meanwhile wins, and only an avatar on Paykit storage is moved. An unread copy // settles nothing, so the move is retried on a later load. - pubkyStore.update { it.copy(pubkyAppAvatarPending = it.pubkyAppAvatarPending - publicKey) } + pubkyStore.update { + if (isCurrent(signIn)) it.copy(pubkyAppAvatarPending = it.pubkyAppAvatarPending - publicKey) else it + } } if (pendingAvatar == null || avatarMoveSettled) retryingAvatar = false if (retryingAvatar) { - snapshot = moveAvatar(publicKey, checkNotNull(pendingAvatar), snapshot, generation) ?: snapshot + snapshot = moveAvatar(signIn, checkNotNull(pendingAvatar), snapshot, generation) ?: snapshot } if (!hadPubkyAppProfile) { - pubkyStore.update { it.copy(pubkyAppProfileOwners = it.pubkyAppProfileOwners + publicKey) } + pubkyStore.update { + if (isCurrent(signIn)) it.copy(pubkyAppProfileOwners = it.pubkyAppProfileOwners + publicKey) else it + } } - if (snapshot !== fetched) ownProfileRevision = snapshot.revision val avatarPending = pendingAvatar != null && snapshot.profile.image == null && (migrating || retryingAvatar) val profile = PubkyProfile.fromPubkyProfile(publicKey, snapshot.profile).let { it.copy(tags = paykitData?.tags.orEmpty(), imageUrl = if (avatarPending) pendingAvatar else it.imageUrl) } if (!avatarPending && paykitData != null && paykitData != profile.toProfileData()) { - publishPaykitProfileCopy(publicKey, profile, generation, saveEpoch) + publishPaykitProfileCopy(signIn, profile, generation, saveEpoch) } return LoadedProfile(profile, snapshot.revision, tagsUnread = paykitRead.isFailure) } private suspend fun migrateToPubkyApp( - publicKey: String, + signIn: PubkySignIn, data: PubkyProfileData, generation: Long, ): PubkyProfileSnapshot? = runSuspendCatching { + val publicKey = signIn.publicKey val fitted = fitted(data.name, data.bio, data.links.map { PubkyProfileLink(it.label, it.url) }) // An avatar already on pubky.app is kept as is; one on Paykit storage is moved below. val keptImage = data.image?.takeIf { it.isPubkyAppFile() } @@ -1535,22 +1872,25 @@ class PubkyRepo @Inject constructor( // Recorded before the profile is created without it, so an app stopped before the move still retries it. // A failed create keeps it too: the create may have landed, and the next load or save handles either case. if (image != null) { - pubkyStore.update { it.copy(pubkyAppAvatarPending = it.pubkyAppAvatarPending + publicKey) } + pubkyStore.update { + if (isCurrent(signIn)) it.copy(pubkyAppAvatarPending = it.pubkyAppAvatarPending + publicKey) else it + } } - val snapshot = profileWrite(generation) { - withPubkyAppScope { pubkyService.publishPubkyProfile(update, null, publicKey) } + val snapshot = profileWrite(signIn, generation) { + withPubkyAppScopeLocked(publicKey) { pubkyService.publishPubkyProfile(update, null, publicKey) } } Logger.info("Moved Bitkit profile to pubky.app", context = TAG) image ?: return@runSuspendCatching snapshot - moveAvatar(publicKey, image, snapshot, generation) ?: snapshot + moveAvatar(signIn, image, snapshot, generation) ?: snapshot }.onFailure { Logger.warn("Failed to move Bitkit profile to pubky.app", it, context = TAG) }.getOrNull() private suspend fun moveAvatar( - publicKey: String, + signIn: PubkySignIn, uri: String, snapshot: PubkyProfileSnapshot, generation: Long, ): PubkyProfileSnapshot? = runSuspendCatching { + val publicKey = signIn.publicKey val bytes = pubkyService.fetchFile(uri, PUBKY_IMAGE_MAX_BYTES) val contentType = when (uri.substringAfterLast('.').lowercase()) { "png" -> "image/png" @@ -1558,9 +1898,11 @@ class PubkyRepo @Inject constructor( "gif" -> "image/gif" else -> "image/jpeg" } - profileWrite(generation) { - val image = withPubkyAppScope { pubkyService.uploadPubkyAppAvatar(bytes, contentType, publicKey) } - withPubkyAppScope { + profileWrite(signIn, generation) { + val image = withPubkyAppScopeLocked( + publicKey + ) { pubkyService.uploadPubkyAppAvatar(bytes, contentType, publicKey) } + withPubkyAppScopeLocked(publicKey) { pubkyService.publishPubkyProfile( PubkyProfileUpdate(null, null, image, null), snapshot.revision, @@ -1569,10 +1911,14 @@ class PubkyRepo @Inject constructor( } } }.onSuccess { - pubkyStore.update { it.copy(pubkyAppAvatarPending = it.pubkyAppAvatarPending - publicKey) } + pubkyStore.update { + if (isCurrent(signIn)) it.copy(pubkyAppAvatarPending = it.pubkyAppAvatarPending - signIn.publicKey) else it + } }.onFailure { Logger.warn("Failed to move avatar to pubky.app", it, context = TAG) - pubkyStore.update { it.copy(pubkyAppAvatarPending = it.pubkyAppAvatarPending + publicKey) } + pubkyStore.update { + if (isCurrent(signIn)) it.copy(pubkyAppAvatarPending = it.pubkyAppAvatarPending + signIn.publicKey) else it + } }.getOrNull() private fun Throwable.isConcurrentUpdate() = @@ -1585,30 +1931,37 @@ class PubkyRepo @Inject constructor( codePointCount(0, length) <= PUBKY_APP_LINK_URL_MAX_LENGTH private suspend fun publishPaykitProfileCopy( - publicKey: String, + signIn: PubkySignIn, profile: PubkyProfile, generation: Long, saveEpoch: Long, ) { runSuspendCatching { - profileWrite(generation) { + profileWrite(signIn, generation) { // Checked under the write lock, so a save that starts after it writes its copy after this one. if (profileSavesRunning.get() != 0 || profileSaveEpoch.get() != saveEpoch) return@profileWrite - pubkyService.publishPaykitProfile(profile.toProfileData().toPaykitProfile(), publicKey) + pubkyService.publishPaykitProfile(profile.toProfileData().toPaykitProfile(), signIn.publicKey) } }.onFailure { Logger.warn("Failed to update Bitkit profile copy", it, context = TAG) } } + private suspend fun profileWrite(signIn: PubkySignIn, generation: Long, block: suspend () -> T): T = + initializeMutex.withLock { + requireCurrent(signIn) + profileWrite(generation, block) + } + /** Runs a write of a load or save that started at [generation], refused once a profile deletion began since. */ private suspend fun profileWrite(generation: Long, block: suspend () -> T): T = profileWriteMutex.withLock { check(profileDeletionGeneration.get() == generation) { "The profile was deleted since this write began" } block() } - private suspend fun withPubkyAppScope(block: suspend () -> T): T = runSuspendCatching { block() }.getOrElse { - if (!it.isPaykitIdentityError() || !refreshSessionIfPossible().getOrDefault(false)) throw it - block() - } + private suspend fun withPubkyAppScopeLocked(publicKey: String, block: suspend () -> T): T = + runSuspendCatching { block() }.getOrElse { + if (!it.isPaykitIdentityError() || !refreshSessionIfPossibleLocked(publicKey).getOrDefault(false)) throw it + block() + } private fun compressAvatar(imageBytes: ByteArray): ByteArray { val original = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) ?: return imageBytes @@ -2018,8 +2371,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) { @@ -2058,6 +2412,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) { validatedExpectedSigner(authUrl) @@ -2089,7 +2451,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" } @@ -2150,6 +2515,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()) { @@ -2164,6 +2536,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( @@ -2232,7 +2611,9 @@ class PubkyRepo @Inject constructor( withContext(ioDispatcher) { when (awaitIdentityReady()) { PubkyIdentityReadiness.Missing -> null - PubkyIdentityReadiness.Unavailable -> throw PubkyIdentityUnavailableError + PubkyIdentityReadiness.Unavailable, + PubkyIdentityReadiness.RecoveryRequired, + -> throw PubkyIdentityUnavailableError PubkyIdentityReadiness.Ready -> { val publicKey = _publicKey.value ?: throw PubkyIdentityUnavailableError publicKey.takeIf { hasWakeKeyFor(it) }?.let(::pubkyWakeIdentity) @@ -2291,7 +2672,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() @@ -2342,16 +2728,24 @@ class PubkyRepo @Inject constructor( } } - suspend fun refreshSessionIfPossible(): Result = runSuspendCatching { + private suspend fun refreshSessionIfPossibleLocked( + expectedPublicKey: String, + ): Result = runSuspendCatching { withContext(ioDispatcher) { - val storedSecretKeyHex = activeSecretKeyHex() ?: return@withContext false - + val storedSecretKeyHex = activeSecretKeyHexLocked(profileOwner(), clearInvalidKey = true) + ?: return@withContext false + check( + PubkyPublicKeyFormat.matches(pubkyService.publicKeyFromSecret(storedSecretKeyHex), expectedPublicKey) + ) { + "Profile credential does not match the intended identity" + } pubkyService.signIn(storedSecretKeyHex) val publicKey = pubkyService.publicKeyFromSecret(storedSecretKeyHex).ensurePubkyPrefix() - + check(PubkyPublicKeyFormat.matches(publicKey, expectedPublicKey)) { + "Refreshed profile identity does not match the intended identity" + } notifyBackupStateChanged() continueSignIn(publicKey) - true } } @@ -2360,44 +2754,60 @@ 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) } + internal suspend fun validateProfileLogout(logout: PaykitProfileLogout) { + identityOperations.requireRemoval() + pubkyService.validateProfileLogout(logout) + } - 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 - } + internal suspend fun executeProfileLogout(logout: PaykitProfileLogout) { + identityOperations.requireRemoval() + pubkyService.executeProfileLogout(logout) + } - clearLocalState(publicPaykitCleanupPending = endpointCleanupResult.isFailure && hadPaykitState) - result - } + /** No native initialization or remote mutation; callers retain admission through private completion. */ + internal suspend fun finishProfileRemovalLocally() { + identityOperations.requireRemoval() + pubkyService.forgetLocalProfileAccess() + 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) } + internal suspend fun finishProfileRemovalLocally(logout: PaykitProfileLogout, localOnly: Boolean) { + identityOperations.requireRemoval() + pubkyService.eraseProfileLogoutCredentials(logout, localOnly) + 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() + pubkyService.requireWalletWipe() + clearProfileMetadataAfterCredentialTeardown() + } + + 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 { @@ -2640,34 +3050,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, "") @@ -2680,9 +3094,22 @@ 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 { + activeSecretKeyHexLocked(owner, clearInvalidKey) + } + } + + private suspend fun activeSecretKeyHexLocked(owner: PubkyProfileOwner, clearInvalidKey: Boolean): String? { + if (!isProfileOwnerCurrent(owner)) return null + val publicKey = owner.signIn?.publicKey + ?: return keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name) + return managedSecretKeyFor(publicKey, clearInvalidKey) } private suspend fun deriveLocalSecretKeyFromWalletSeed(): String = withContext(ioDispatcher) { @@ -2721,6 +3148,7 @@ class PubkyRepo @Inject constructor( } private fun startSignIn(publicKey: String, restoringStoredIdentity: Boolean = false) { + pubkyService.revokeProfileLogout() // First, so the sign-in it replaces has ended before the key is published, even when it is the same identity. signInGeneration.incrementAndGet() if (!restoringStoredIdentity) storedIdentityRevision.incrementAndGet() @@ -2743,6 +3171,7 @@ class PubkyRepo @Inject constructor( clearRestorationFailure: Boolean = true, preserveStoredIdentity: Boolean = false, ) = withContext(ioDispatcher) { + pubkyService.revokeProfileLogout() // First, so work of the ending sign-in stops before the store reset below, and cannot write after it. signInGeneration.incrementAndGet() if (!preserveStoredIdentity) { @@ -2834,21 +3263,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/main/java/to/bitkit/repositories/PublicPaykitRepo.kt b/app/src/main/java/to/bitkit/repositories/PublicPaykitRepo.kt index 4643b7e6a7..2aa3564096 100644 --- a/app/src/main/java/to/bitkit/repositories/PublicPaykitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PublicPaykitRepo.kt @@ -365,30 +365,41 @@ class PublicPaykitRepo @Inject constructor( paymentHash: String, canPublish: () -> Boolean = { true }, isStillCurrent: () -> Boolean = { true }, - ): Result = withContext(ioDispatcher) { - runSuspendCatching { - val signIn = pubkyRepo.currentSignIn() ?: return@runSuspendCatching - val ownsInvoice = { pubkyRepo.isCurrent(signIn) && isStillCurrent() } - val ownsPublication = { ownsInvoice() && canPublish() } - if (!ownsInvoice()) return@runSuspendCatching - val settings = settingsStore.data.first() - if (!settings.sharesPublicPaykitEndpoints) return@runSuspendCatching - if (settings.publicPaykitBolt11PaymentHash != paymentHash) return@runSuspendCatching - val refresh = EndpointRefresh(signIn, lastAcknowledgedPublication.get(), reuseMatching = false) - - clearPublicBolt11Metadata(publicationPending = true, canClear = { ownsInvoice() }) - if (!isAutomaticPublicationAllowed(ownsPublication)) return@runSuspendCatching - val desired = buildWalletEndpoints(signIn.publicKey, ownsPublication, refresh = true) - applyPublishedEndpoints( - desired, - beforePublish = { markPublicationPending(ownsPublication) }, - acknowledge = { current -> - acknowledgePublishedEndpoints(desired, signIn.publicKey) { current() && ownsPublication() } - }, - canPublish = { isAutomaticPublicationAllowed(ownsPublication) }, - refresh = refresh, - ) - Unit + admitPublication: suspend (suspend () -> Unit) -> Unit, + ): Result { + val signIn = pubkyRepo.currentSignIn() ?: return Result.success(Unit) + return withContext(ioDispatcher) { + runSuspendCatching { + val ownsInvoice = { pubkyRepo.isCurrent(signIn) && isStillCurrent() } + val ownsPublication = { ownsInvoice() && canPublish() } + if (!ownsInvoice()) return@runSuspendCatching + val settings = settingsStore.data.first() + if (!settings.sharesPublicPaykitEndpoints) return@runSuspendCatching + if (settings.publicPaykitBolt11PaymentHash != paymentHash) return@runSuspendCatching + val refresh = EndpointRefresh(signIn, lastAcknowledgedPublication.get(), reuseMatching = false) + + // Keep the paid invoice invalidated even when preparation must wait for teardown or sharing. + clearPublicBolt11Metadata( + publicationPending = true, + canClear = { ownsInvoice() && it.publicPaykitBolt11PaymentHash == paymentHash }, + ) + admitPublication { + if (isAutomaticPublicationAllowed(ownsPublication)) { + val desired = buildWalletEndpoints(signIn.publicKey, ownsPublication, refresh = true) + applyPublishedEndpoints( + desired, + beforePublish = { markPublicationPending(ownsPublication) }, + acknowledge = { current -> + acknowledgePublishedEndpoints(desired, signIn.publicKey) { + current() && ownsPublication() + } + }, + canPublish = { isAutomaticPublicationAllowed(ownsPublication) }, + refresh = refresh, + ) + } + } + } } } diff --git a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt index 72f5b9125a..77fd6a0461 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.combine @@ -31,9 +34,13 @@ 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.ProfileRemovalStore import to.bitkit.data.SettingsStore import to.bitkit.data.WalletConnectionRecovery +import to.bitkit.data.WalletResetRecovery +import to.bitkit.data.backup.VssClientCoordinator import to.bitkit.data.keychain.Keychain import to.bitkit.di.BgDispatcher import to.bitkit.env.Env @@ -48,13 +55,13 @@ 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 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 @@ -81,18 +88,25 @@ class WalletRepo @Inject constructor( private val activityRepo: ActivityRepo, private val hwWalletRepo: HwWalletRepo, private val connectionRecovery: WalletConnectionRecovery, + private val profileRemovalStore: ProfileRemovalStore, private val sparkRepo: SparkRepo, private val sparkExitRepo: SparkExitRepo, private val backupRepo: BackupRepo, + private val vssClients: VssClientCoordinator, private val invoiceParser: QuickPayInvoiceParser, ) { private val repoScope = appScope(bgDispatcher, TAG) - private val _walletState = MutableStateFlow(WalletState(walletExists = walletExists())) + private val _walletState = MutableStateFlow( + WalletState(walletExists = walletExists(), walletResetRecovery = WalletResetRecovery.Loading) + ) val walletState = _walletState.asStateFlow() private val _balanceState = MutableStateFlow(BalanceState()) val balanceState = _balanceState.asStateFlow() + private val balanceSyncMutex = Mutex() + private val balanceMutex = Mutex() + private var hasLiveBalance = false private var eventSyncJob: Job? = null private val receiveStateMutex = Mutex() @@ -104,6 +118,22 @@ class WalletRepo @Inject constructor( private var committedReceiveBip21 = "" init { + repoScope.launch { + profileRemovalStore.walletResetRecovery.collect { recovery -> + runSuspendCatching { + _walletState.update { + it.copy( + walletExists = + if (recovery == WalletResetRecovery.Clear) walletExists() else it.walletExists, + walletResetRecovery = recovery, + ) + } + }.onFailure { + _walletState.update { it.copy(walletResetRecovery = WalletResetRecovery.Unavailable) } + Logger.warn("Failed to refresh wallet existence for reset recovery", it, context = TAG) + } + } + } repoScope.launch { lightningRepo.nodeEventUpdates.collect { update -> if (!walletExists()) return@collect @@ -141,14 +171,16 @@ class WalletRepo @Inject constructor( // The read balance too, as sends use it: it can come back to the shown one while that stays the same. An // exit's start or end changes what Spending counts with no balance change. val spark = sparkRepo.state - .map { listOf(it.balanceSats, it.shownBalanceSats, it.pendingDepositSats) to it.isExiting } + .map { + (it.isReady to it.isExiting) to listOf(it.balanceSats, it.shownBalanceSats, it.pendingDepositSats) + } .distinctUntilChanged() // Funding reaching the exit changes what it brings to savings with no Spark balance change. val exit = sparkExitRepo.state .map { Triple(it.inTransferSats, it.outsideExitSats, it.record?.transferId) } .distinctUntilChanged() combine(spark, exit) { _, _ -> }.collect { - if (walletExists()) syncBalances() + if (walletExists()) coroutineScope { launch { syncBalances() } } } } } @@ -213,36 +245,38 @@ 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 - val paymentHash = cacheData.bolt11PaymentHash.ifEmpty { - cacheData.bolt11.takeIf { it.isNotEmpty() }?.let { invoiceParser.parse(it) }.orEmpty() - } - _walletState.update { - it.copy( - onchainAddress = cacheData.onchainAddress, - bolt11 = cacheData.bolt11, - bolt11PaymentHash = paymentHash, - 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 + val paymentHash = cacheData.bolt11PaymentHash.ifEmpty { + cacheData.bolt11.takeIf { it.isNotEmpty() }?.let { invoiceParser.parse(it) }.orEmpty() + } + _walletState.update { + it.copy( + onchainAddress = cacheData.onchainAddress, + bolt11 = cacheData.bolt11, + bolt11PaymentHash = paymentHash, + bip21 = cacheData.bip21, + ) + } + synchronized(receiveUpdateStatusLock) { updateReceivePendingState() } + receiveCacheValidationFailed = false } - synchronized(receiveUpdateStatusLock) { updateReceivePendingState() } - receiveCacheValidationFailed = false } }.invokeOnCompletion { changePendingReceiveCacheLoads(-1) } } @@ -453,20 +487,109 @@ 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 + val maxSendSats = maxOf(state.channels.totalNextOutboundHtlcLimitSats(), sparkRepo.state.value.sendableSats) + it.copy(maxSendLightningSats = maxSendSats) + } } 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 { + balanceSyncMutex.withLock { + val result = deriveBalanceStateUseCase() + val channels = lightningRepo.lightningState.value.channels + balanceMutex.withLock publish@{ + val balance = result.getOrElse { + if (it is CancellationException) throw it + if (it is NodeNotRunningError || it is NodeRunTimeoutError) { + updateSparkBalance(_balanceState.value)?.let { updated -> return@getOrElse updated } + } + Logger.warn("Could not sync balances", it, context = TAG) + return@publish + } + val hasAggregate = result.isSuccess || + (balance.sparkBalanceSats != null && balance.sparkPendingDepositSats != null) + if (hasAggregate) cacheBalance(balance) + publishBalance(balance, channels.takeIf { result.isSuccess }) + 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 || spark.isExiting || sparkExitRepo.state.value.isExiting) { + return balance.copy( + maxSendLightningSats = spark.sendableSats, + sparkBalanceSats = null, + sparkPendingDepositSats = null, + ) + } + 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 + }, + ) } } @@ -673,9 +796,13 @@ class WalletRepo @Inject constructor( } suspend fun createWallet(bip39Passphrase: String?): Result = withContext(bgDispatcher) { - lightningRepo.setRecoveryMode(enabled = false) runSuspendCatching { - connectionRecovery.withIdentityChange { + connectionRecovery.withIdentityChange(isStillNeeded = { + profileRemovalStore.requireWalletAvailable() + true + }) { + profileRemovalStore.requireWalletAvailable() + lightningRepo.setRecoveryMode(enabled = false) val mnemonic = generateEntropyMnemonic() keychain.saveString(Keychain.Key.BIP39_MNEMONIC.name, mnemonic) if (bip39Passphrase != null) { @@ -695,9 +822,13 @@ class WalletRepo @Inject constructor( } suspend fun restoreWallet(mnemonic: String, bip39Passphrase: String?): Result = withContext(bgDispatcher) { - lightningRepo.setRecoveryMode(enabled = false) runSuspendCatching { - connectionRecovery.withIdentityChange { + connectionRecovery.withIdentityChange(isStillNeeded = { + profileRemovalStore.requireWalletAvailable() + true + }) { + profileRemovalStore.requireWalletAvailable() + lightningRepo.setRecoveryMode(enabled = false) keychain.saveString(Keychain.Key.BIP39_MNEMONIC.name, mnemonic) if (bip39Passphrase != null) { keychain.saveString(Keychain.Key.BIP39_PASSPHRASE.name, bip39Passphrase) @@ -715,19 +846,33 @@ 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() - } + suspend fun checkWalletAvailable(): Result = withContext(bgDispatcher) { + runSuspendCatching { profileRemovalStore.requireWalletAvailable() } } + fun refreshWalletResetRecovery() = profileRemovalStore.refreshWalletResetRecovery() + + suspend fun wipeWallet(walletIndex: Int = 0, expectedPendingAttemptId: String? = null): Result = + withContext(bgDispatcher) { + try { + wipeWalletUseCase( + walletIndex = walletIndex, + resetWalletState = ::resetState, + onSuccess = {}, + expectedPendingAttemptId = expectedPendingAttemptId, + ) + } finally { + runCatching { setWalletExistsState() } + .onFailure { Logger.warn("Failed to refresh wallet existence after wipe", it, context = TAG) } + } + } + fun resetState() { - _walletState.update { WalletState() } + _walletState.update { + WalletState(walletExists = it.walletExists, walletResetRecovery = it.walletResetRecovery) + } _balanceState.update { BalanceState() } + hasLiveBalance = false } fun getOnchainAddress(): String = _walletState.value.onchainAddress @@ -1096,6 +1241,7 @@ data class WalletState( val bip21Description: String = "", val selectedTags: ImmutableList = persistentListOf(), val walletExists: Boolean = false, + val walletResetRecovery: WalletResetRecovery = WalletResetRecovery.Clear, ) enum class SyncSource { AUTO, MANUAL } diff --git a/app/src/main/java/to/bitkit/services/CoreService.kt b/app/src/main/java/to/bitkit/services/CoreService.kt index 80c8607082..e5ea6e8f00 100644 --- a/app/src/main/java/to/bitkit/services/CoreService.kt +++ b/app/src/main/java/to/bitkit/services/CoreService.kt @@ -67,6 +67,7 @@ import com.synonym.bitkitcore.wipeAllDatabases import io.ktor.client.request.get import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.first @@ -99,7 +100,6 @@ import to.bitkit.models.msatFloorOf import to.bitkit.models.toAddressType import to.bitkit.models.toCoreNetwork import to.bitkit.models.toSettingsString -import to.bitkit.repositories.PaykitReceivedPaymentContacts import to.bitkit.repositories.PrivatePaykitContactResolver import to.bitkit.utils.AppError import to.bitkit.utils.Logger @@ -378,12 +378,14 @@ class ActivityService( private var lastPaykitContactBackfill: PaykitContactBackfillState? = null private data class PaykitContactBackfillState( - val contacts: PaykitReceivedPaymentContacts, - val generation: Long, + val associations: PrivatePaykitContactResolver.ReceiptSnapshot, val activityRevision: Long, - val reservationVersion: Long, ) + private suspend fun withReceiptOperation( + block: suspend (PrivatePaykitContactResolver.Receipt) -> T, + ): T = privatePaykitContactResolver.get().withReceiptOperation(block) + internal suspend fun invalidatePaykitContactBackfill() = ServiceQueue.CORE.background { paykitActivityRevision++ } @@ -629,89 +631,83 @@ class ActivityService( updateActivity(activityId = id, activity = activity) } - suspend fun backfillPaykitContacts(): Boolean = ServiceQueue.CORE.background { - val resolver = privatePaykitContactResolver.get() - val contacts = resolver.receivedPaymentContacts - if (contacts === PaykitReceivedPaymentContacts.Empty) { - lastPaykitContactBackfill = null - return@background false - } - val snapshot = PaykitContactBackfillState( - contacts = contacts, - generation = resolver.receivedPaymentContactsGeneration, - activityRevision = paykitActivityRevision, - reservationVersion = resolver.reservationVersion, - ) - if (snapshot == lastPaykitContactBackfill) return@background false - val activities = getActivities( - walletId = null, - filter = ActivityFilter.ALL, - txType = PaymentType.RECEIVED, - tags = null, - search = null, - minDate = null, - maxDate = null, - limit = null, - sortDirection = null, - ) - var changed = false - var complete = true - for (activity in activities) { - if (!isCurrentPaykitContactBackfill(resolver, snapshot)) return@background changed - if (cacheStore.data.first().isContactDetached(activity.rawId(), activity.walletId())) continue - val (updated, hydrated) = attributedPaykitActivity(activity, contacts) - complete = complete && hydrated - if (!isCurrentPaykitContactBackfill(resolver, snapshot)) return@background changed - if (updated != null && !cacheStore.data.first().isContactDetached(activity.rawId(), activity.walletId())) { - if (!isCurrentPaykitContactBackfill(resolver, snapshot)) return@background changed - updateActivity(activityId = activity.rawId(), activity = updated) - changed = true + suspend fun backfillPaykitContacts(): Boolean = withReceiptOperation { receipt -> + ServiceQueue.CORE.background { + receipt.requireCurrent() + val associations = receipt.snapshot ?: return@background false + val snapshot = PaykitContactBackfillState(associations, paykitActivityRevision) + if (snapshot == lastPaykitContactBackfill) return@background false + val activities = getActivities( + walletId = null, + filter = ActivityFilter.ALL, + txType = PaymentType.RECEIVED, + tags = null, + search = null, + minDate = null, + maxDate = null, + limit = null, + sortDirection = null, + ) + var changed = false + var complete = true + for (activity in activities) { + val (contact, hydrated) = receivedPaykitContact(activity, receipt) + complete = complete && hydrated + receipt.requireCurrent() + val cache = cacheStore.data.first() + receipt.commit { + val latest = getActivityById(walletId = activity.walletId(), activityId = activity.rawId()) + if (latest != activity) { + complete = false + } else if (contact != null && !cache.isContactDetached(activity.rawId(), activity.walletId()) && + !cache.isActivityDeleted(activity.rawId(), activity.walletId()) + ) { + val updated = when (activity) { + is Activity.Lightning -> Activity.Lightning(activity.v1.copy(contact = contact)) + is Activity.Onchain -> Activity.Onchain(activity.v1.copy(contact = contact)) + } + updateActivity(activityId = activity.rawId(), activity = updated) + changed = true + } + } } + receipt.commit { + if (complete && receipt.associationsComplete && paykitActivityRevision == snapshot.activityRevision) { + lastPaykitContactBackfill = snapshot + } + } + changed } - if (complete && isCurrentPaykitContactBackfill(resolver, snapshot)) { - lastPaykitContactBackfill = snapshot - } - changed } - private fun isCurrentPaykitContactBackfill( - resolver: PrivatePaykitContactResolver, - snapshot: PaykitContactBackfillState, - ): Boolean = resolver.receivedPaymentContacts === snapshot.contacts && - resolver.receivedPaymentContactsGeneration == snapshot.generation && - paykitActivityRevision == snapshot.activityRevision && - resolver.reservationVersion == snapshot.reservationVersion - - private suspend fun attributedPaykitActivity( + private suspend fun receivedPaykitContact( activity: Activity, - contacts: PaykitReceivedPaymentContacts, - ): Pair = when (activity) { + receipt: PrivatePaykitContactResolver.Receipt, + ): Pair = when (activity) { is Activity.Lightning -> { - val contact = receivedPaykitContact(activity.v1, contacts) - contact?.let { Activity.Lightning(activity.v1.copy(contact = it)) } to true + val row = activity.v1 + if (row.contact != null || row.txType != PaymentType.RECEIVED || row.status == PaymentState.FAILED) { + null to true + } else { + receipt.contactForInvoice(row.id) to true + } } is Activity.Onchain -> { - val (contact, hydrated) = receivedPaykitContact(activity.v1) - contact?.let { Activity.Onchain(activity.v1.copy(contact = it)) } to hydrated + val row = activity.v1 + if (row.contact != null || row.txType != PaymentType.RECEIVED) { + null to true + } else { + val details = getBitkitCoreTransactionDetails(walletId = row.walletId, txId = row.txId) + val addresses = details?.outputs?.mapNotNull { it.scriptpubkeyAddress }.orEmpty() + if (row.address !in addresses) { + null to false + } else { + receipt.contactForAddresses(row.address, addresses) to true + } + } } } - private fun receivedPaykitContact(row: LightningActivity, contacts: PaykitReceivedPaymentContacts): String? { - if (row.contact != null || row.txType != PaymentType.RECEIVED || row.status == PaymentState.FAILED) return null - return contacts.contactsForPaymentHash(row.id).singleOrNull() - } - - private suspend fun receivedPaykitContact(row: OnchainActivity): Pair { - if (row.contact != null || row.txType != PaymentType.RECEIVED) return null to true - val details = getBitkitCoreTransactionDetails(walletId = row.walletId, txId = row.txId) - val addresses = details?.outputs?.mapNotNull { it.scriptpubkeyAddress }.orEmpty() - if (row.address !in addresses) return null to false - return privatePaykitContactResolver.get().contactPublicKeyForPrivateOnchainAddresses( - receivingAddress = row.address, - addresses = addresses, - ) to true - } - suspend fun delete(id: String, walletId: String = defaultWalletId): Boolean = ServiceQueue.CORE.background { invalidatePaykitContactBackfill() deleteActivityById(walletId = walletId, activityId = id) @@ -821,49 +817,61 @@ class ActivityService( com.synonym.bitkitcore.migrateBackupPreActivityMetadataJson(json) } - suspend fun handlePaymentEvent(paymentHash: String) = ServiceQueue.CORE.background { - val payments = lightningService.listPayments() ?: run { - Logger.warn("No payments available for hash $paymentHash", context = TAG) - return@background + suspend fun handlePaymentEvent(paymentHash: String) = withReceiptOperation { receipt -> + ServiceQueue.CORE.background { + receipt.requireCurrent() + val payments = lightningService.listPayments() ?: run { + Logger.warn("No payments available for hash $paymentHash", context = TAG) + return@background + } + receipt.requireCurrent() + val payment = payments.firstOrNull { it.id == paymentHash } + if (payment != null) { + processSinglePayment(payment, false, emptyMap(), receipt) + } else { + syncReceiptPayments(payments, false, emptyMap(), receipt) + } } + } - val payment = payments.firstOrNull { it.id == paymentHash } - if (payment != null) { - // Lightning payments don't need channel IDs, only onchain payments do - val channelIdsByTxId = emptyMap() - processSinglePayment(payment, forceUpdate = false, channelIdsByTxId = channelIdsByTxId) - } else { - Logger.info("Payment not found for hash $paymentHash - syncing all payments", context = TAG) - // For full sync, we need channel IDs for onchain payments - // This will be handled by ActivityRepo.syncLdkNodePayments which calls findChannelsForPayments - syncLdkNodePaymentsToActivities(payments, channelIdsByTxId = emptyMap()) + /** Capture wallet admission before obtaining the owner-specific payment list. */ + suspend fun syncLdkNodePaymentsToActivities( + payments: suspend () -> List, + forceUpdate: Boolean = false, + channelIdsByTxId: suspend (List) -> Map = { emptyMap() }, + ) = withReceiptOperation { receipt -> + val capturedPayments = payments() + receipt.requireCurrent() + val channels = channelIdsByTxId(capturedPayments) + receipt.requireCurrent() + ServiceQueue.CORE.background { + syncReceiptPayments(capturedPayments, forceUpdate, channels, receipt) } } - suspend fun syncLdkNodePaymentsToActivities( + private suspend fun syncReceiptPayments( payments: List, - forceUpdate: Boolean = false, - channelIdsByTxId: Map = emptyMap(), - ) = ServiceQueue.CORE.background { + forceUpdate: Boolean, + channelIdsByTxId: Map, + receipt: PrivatePaykitContactResolver.Receipt, + ) = coroutineScope { val allResults = mutableListOf>() - payments.chunked(CHUNK_SIZE).forEach { chunk -> + receipt.requireCurrent() val results = chunk.map { payment -> async { - runCatching { - processSinglePayment(payment, forceUpdate, channelIdsByTxId) + runSuspendCatching { + processSinglePayment(payment, forceUpdate, channelIdsByTxId, receipt) payment.id }.onFailure { e -> Logger.error("Error syncing payment with id: ${payment.id}:", e, context = TAG) } } }.awaitAll() - allResults.addAll(results) } - + receipt.requireCurrent() val (successful, failed) = allResults.partition { it.isSuccess } - Logger.info("Synced ${successful.size} payments successfully, ${failed.size} failed", context = TAG) } @@ -871,7 +879,9 @@ class ActivityService( payment: PaymentDetails, forceUpdate: Boolean, channelIdsByTxId: Map, + receipt: PrivatePaykitContactResolver.Receipt, ) { + receipt.requireCurrent() val state = when (payment.status) { PaymentStatus.FAILED -> PaymentState.FAILED PaymentStatus.PENDING -> PaymentState.PENDING @@ -886,11 +896,12 @@ class ActivityService( payment = payment, forceUpdate = forceUpdate, channelId = channelId, + receipt = receipt, ) } is PaymentKind.Bolt11 -> { - processBolt11(kind = kind, payment = payment, state = state) + processBolt11(kind = kind, payment = payment, state = state, receipt = receipt) } else -> Unit // Handle spontaneous payments if needed @@ -901,6 +912,7 @@ class ActivityService( kind: PaymentKind.Bolt11, payment: PaymentDetails, state: PaymentState, + receipt: PrivatePaykitContactResolver.Receipt, ) { // Skip pending inbound payments, just means an invoice was created if ( @@ -913,73 +925,58 @@ class ActivityService( val pendingMessage = payment.id.takeIf { payment.direction == PaymentDirection.OUTBOUND } ?.let { cacheStore.data.first().pendingLightningMessages[it] } - val existingActivity = getActivityById(walletId = defaultWalletId, activityId = payment.id) - // Another attempt of the same invoice, or an older snapshot read before the success was saved, never undoes - // that success. - if (existingActivity is Activity.Lightning && existingActivity.v1.status == PaymentState.SUCCEEDED && - state != PaymentState.SUCCEEDED - ) { - return - } - // A Spark retry of the invoice stays pending until Spark settles it; the channel's failure can't end it. - // Spark records the hash before it sends and drops it only once it reports the send failed or unknown. - if (existingActivity is Activity.Lightning && existingActivity.v1.status == PaymentState.PENDING && - state == PaymentState.FAILED && payment.id.lowercase() in cacheStore.data.first().sparkSendHashes - ) { - return + val resolvedContact = if (payment.direction == PaymentDirection.INBOUND && state != PaymentState.FAILED) { + receipt.contactForInvoice(payment.id) + } else { + null } - if (existingActivity is Activity.Lightning) { - val statusChanging = existingActivity.v1.status != state - val needsPrivateContactAttribution = existingActivity.v1.contact == null && - payment.direction == PaymentDirection.INBOUND - if ((existingActivity.v1.updatedAt ?: 0u) > payment.latestUpdateTimestamp && - !statusChanging && - !needsPrivateContactAttribution + receipt.requireCurrent() + val cache = cacheStore.data.first() + val applied = receipt.commit { + if (cache.isActivityDeleted(payment.id, defaultWalletId)) return@commit false + val existing = getActivityById(walletId = defaultWalletId, activityId = payment.id) as? Activity.Lightning + // A pending or failed update cannot undo success or end a pending Spark retry. + if (existing?.v1?.status == PaymentState.SUCCEEDED && state != PaymentState.SUCCEEDED) return@commit false + if (existing?.v1?.status == PaymentState.PENDING && state == PaymentState.FAILED && + payment.id.lowercase() in cache.sparkSendHashes ) { - return + return@commit false } - } - - val contact = existingActivity - ?.takeIf { it is Activity.Lightning } - ?.let { (it as Activity.Lightning).v1.contact } - ?: payment.takeUnless { - it.status == PaymentStatus.FAILED || cacheStore.data.first().isContactDetached(it.id, defaultWalletId) - }?.let { - privatePaykitContactPublicKeyForReceivedInvoicePaymentHash(it.id, it.direction) + val contact = existing?.v1?.contact ?: resolvedContact.takeUnless { + cache.isContactDetached(payment.id, defaultWalletId) } - - val ln = if (existingActivity is Activity.Lightning) { - existingActivity.v1.withPaymentUpdate( - payment = payment, - kind = kind, - state = state, - contact = contact, - ) - } else { - LightningActivity.create( - id = payment.id, - txType = payment.direction.toPaymentType(), - status = state, - value = payment.amountSats ?: 0u, - invoice = kind.bolt11 ?: "Loading...", - timestamp = payment.latestUpdateTimestamp, - fee = msatFloorOf(payment.feePaidMsat ?: 0u), - message = kind.description.orEmpty(), - preimage = kind.preimage, - contact = contact, - seenAt = null, - ) - }.withPendingMessage(pendingMessage = pendingMessage, description = kind.description) - - if (existingActivity != Activity.Lightning(ln)) invalidatePaykitContactBackfill() - if (getActivityById(walletId = defaultWalletId, activityId = payment.id) != null) { - updateActivity(activityId = payment.id, activity = Activity.Lightning(ln)) - } else { - upsertActivity(Activity.Lightning(ln)) + if (existing != null && (existing.v1.updatedAt ?: 0u) > payment.latestUpdateTimestamp && + existing.v1.status == state && !(existing.v1.contact == null && contact != null) + ) { + return@commit false + } + val ln = if (existing != null) { + existing.v1.withPaymentUpdate(payment, kind, state, contact) + } else { + LightningActivity.create( + id = payment.id, + txType = payment.direction.toPaymentType(), + status = state, + value = payment.amountSats ?: 0u, + invoice = kind.bolt11 ?: "Loading...", + timestamp = payment.latestUpdateTimestamp, + fee = msatFloorOf(payment.feePaidMsat ?: 0u), + message = kind.description.orEmpty(), + preimage = kind.preimage, + contact = contact, + seenAt = null, + ) + }.withPendingMessage(pendingMessage = pendingMessage, description = kind.description) + if (existing != Activity.Lightning(ln)) paykitActivityRevision++ + if (existing != null) { + updateActivity(activityId = payment.id, activity = Activity.Lightning(ln)) + } else { + upsertActivity(Activity.Lightning(ln)) + } + true } - if (pendingMessage != null) cacheStore.removePendingLightningMessage(payment.id) + if (applied && pendingMessage != null) cacheStore.removePendingLightningMessage(payment.id) } /** @@ -1038,6 +1035,7 @@ class ActivityService( kind: PaymentKind.Onchain, payment: PaymentDetails, details: BitkitCoreTransactionDetails?, + receipt: PrivatePaykitContactResolver.Receipt, ): String? { if (payment.direction != PaymentDirection.INBOUND) return null @@ -1059,13 +1057,16 @@ class ActivityService( currentWalletAddress = currentWalletAddress, selectedAddressType = selectedAddressType, ) - ?: findPrivateReservedAddress(details) + ?: findPrivateReservedAddress(details, receipt) } - private suspend fun findPrivateReservedAddress(details: BitkitCoreTransactionDetails): String? { + private suspend fun findPrivateReservedAddress( + details: BitkitCoreTransactionDetails, + receipt: PrivatePaykitContactResolver.Receipt, + ): String? { for (output in details.outputs) { val address = output.scriptpubkeyAddress ?: continue - if (privatePaykitContactResolver.get().contactPublicKeyForReservedAddress(address) != null) return address + if (receipt.isReservedReceiveAddress(address)) return address } return null } @@ -1363,7 +1364,9 @@ class ActivityService( forceUpdate: Boolean, channelId: String? = null, transactionDetails: BitkitCoreTransactionDetails? = null, + receipt: PrivatePaykitContactResolver.Receipt, ) { + receipt.requireCurrent() val timestamp = payment.latestUpdateTimestamp val confirmationData = getConfirmationStatus(kind, timestamp) @@ -1383,7 +1386,7 @@ class ActivityService( val details = transactionDetails ?: payment.takeIf { it.direction == PaymentDirection.INBOUND } ?.let { fetchTransactionDetails(kind.txid) } - val resolvedAddress = resolveAddressForInboundPayment(kind, payment, details) + val resolvedAddress = resolveAddressForInboundPayment(kind, payment, details, receipt) val resolvedContact = if ( payment.direction == PaymentDirection.INBOUND && payment.status != PaymentStatus.FAILED && !details?.outputs.isNullOrEmpty() @@ -1398,7 +1401,7 @@ class ActivityService( ) { null } else { - privatePaykitContactResolver.get().contactPublicKeyForPrivateOnchainAddresses( + receipt.contactForAddresses( receivingAddress = resolvedAddress, addresses = details.outputs.mapNotNull { it.scriptpubkeyAddress }, ) @@ -1407,67 +1410,62 @@ class ActivityService( null } + receipt.requireCurrent() val cache = cacheStore.data.first() - val existingActivity = getActivityById(walletId = defaultWalletId, activityId = payment.id) - ?: getActivityByTxId(walletId = defaultWalletId, txId = kind.txid)?.let { Activity.Onchain(it) } - val existingOnchainActivity = existingActivity as? Activity.Onchain - if (existingOnchainActivity != null && - (existingOnchainActivity.v1.updatedAt ?: 0u) > payment.latestUpdateTimestamp && - !(existingOnchainActivity.v1.contact == null && payment.direction == PaymentDirection.INBOUND) - ) { - return - } - val activityId = existingOnchainActivity?.v1?.id ?: payment.id - val contact = existingOnchainActivity?.v1?.contact ?: resolvedContact.takeUnless { - cache.isContactDetached(activityId, defaultWalletId) - } - - val ldkValue = payment.amountSats ?: 0u - val onChain = if (existingOnchainActivity != null) { - buildUpdatedOnchainActivity( - existingActivity = existingOnchainActivity, - confirmationData = confirmationData, - ldkValue = ldkValue, - ldkFeeMsat = payment.feePaidMsat ?: 0u, - resolvedAddress = resolvedAddress, - contact = contact, - channelId = resolvedChannelId, - ) - } else { - buildNewOnchainActivity( - payment = payment, - kind = kind, - confirmationData = confirmationData, - resolvedAddress = resolvedAddress, - contact = contact, - channelId = resolvedChannelId, - ) - } + receipt.commit { + val existingActivity = getActivityById(walletId = defaultWalletId, activityId = payment.id) + ?: getActivityByTxId(walletId = defaultWalletId, txId = kind.txid)?.let { Activity.Onchain(it) } + val existingOnchainActivity = existingActivity as? Activity.Onchain + if (existingOnchainActivity != null && + (existingOnchainActivity.v1.updatedAt ?: 0u) > payment.latestUpdateTimestamp && + !(existingOnchainActivity.v1.contact == null && payment.direction == PaymentDirection.INBOUND) + ) { + return@commit + } + val activityId = existingOnchainActivity?.v1?.id ?: payment.id + val contact = existingOnchainActivity?.v1?.contact ?: resolvedContact.takeUnless { + cache.isContactDetached(activityId, defaultWalletId) + } - if (cache.isActivityDeleted(onChain.id, onChain.walletId) && !forceUpdate) { - Logger.verbose("Activity ${onChain.id} was already deleted, skipping", context = TAG) - return - } + val ldkValue = payment.amountSats ?: 0u + val onChain = if (existingOnchainActivity != null) { + buildUpdatedOnchainActivity( + existingActivity = existingOnchainActivity, + confirmationData = confirmationData, + ldkValue = ldkValue, + ldkFeeMsat = payment.feePaidMsat ?: 0u, + resolvedAddress = resolvedAddress, + contact = contact, + channelId = resolvedChannelId, + ) + } else { + buildNewOnchainActivity( + payment = payment, + kind = kind, + confirmationData = confirmationData, + resolvedAddress = resolvedAddress, + contact = contact, + channelId = resolvedChannelId, + ) + } - if (existingActivity != Activity.Onchain(onChain)) paykitActivityRevision++ - if (existingActivity is Activity.Onchain) { - upsertOnchainActivityPreservingFeeRate(onChain) - } else { - upsertActivity(Activity.Onchain(onChain)) + if (cache.isActivityDeleted(onChain.id, onChain.walletId) && !forceUpdate) { + Logger.verbose("Activity ${onChain.id} was already deleted, skipping", context = TAG) + return@commit + } + + if (existingActivity != Activity.Onchain(onChain)) paykitActivityRevision++ + if (existingActivity is Activity.Onchain) { + upsertOnchainActivityPreservingFeeRate(onChain) + } else { + upsertActivity(Activity.Onchain(onChain)) + } } } private fun PaymentDirection.toPaymentType(): PaymentType = if (this == PaymentDirection.OUTBOUND) PaymentType.SENT else PaymentType.RECEIVED - private suspend fun privatePaykitContactPublicKeyForReceivedInvoicePaymentHash( - paymentHash: String, - direction: PaymentDirection, - ): String? { - if (direction != PaymentDirection.INBOUND) return null - return privatePaykitContactResolver.get().contactPublicKeyForPrivateInvoicePaymentHash(paymentHash) - } - // MARK: - Test Data Generation (regtest only) suspend fun generateRandomTestData(count: Int = 100) { @@ -1652,129 +1650,146 @@ class ActivityService( check(restored.fee == fee && restored.feeRate == feeRate) } - suspend fun handleOnchainTransactionReceived(txid: String, details: TransactionDetails) { - ServiceQueue.CORE.background { - runCatching { - val coreDetails = mapToCoreTransactionDetails(txid, details) - invalidatePaykitContactBackfill() - upsertTransactionDetails(listOf(coreDetails)) + suspend fun handleOnchainTransactionReceived(txid: String, details: TransactionDetails) = + withReceiptOperation { receipt -> + ServiceQueue.CORE.background { + receipt.requireCurrent() + 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 - } + val payments = lightningService.listPayments() ?: run { + Logger.warn("No payments available for transaction $txid", context = TAG) + 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 - } + val payment = payments.firstOrNull { payment -> + (payment.kind as? PaymentKind.Onchain)?.txid == txid + } ?: run { + Logger.warn("Payment not found for transaction $txid", context = TAG) + return@runSuspendCatching + } - processOnchainPayment( - kind = payment.kind as PaymentKind.Onchain, - payment = payment, - forceUpdate = false, - channelId = null, - transactionDetails = coreDetails, - ) - }.onFailure { e -> - Logger.error("Error handling onchain transaction received for $txid", e, context = TAG) + processOnchainPayment( + kind = payment.kind as PaymentKind.Onchain, + payment = payment, + forceUpdate = false, + channelId = null, + transactionDetails = coreDetails, + receipt = receipt, + ) + }.onFailure { e -> + Logger.error("Error handling onchain transaction received for $txid", e, context = TAG) + } } } - } - suspend fun handleOnchainTransactionConfirmed(txid: String, details: TransactionDetails) { - ServiceQueue.CORE.background { - runCatching { - val coreDetails = mapToCoreTransactionDetails(txid, details) - invalidatePaykitContactBackfill() - upsertTransactionDetails(listOf(coreDetails)) + suspend fun handleOnchainTransactionConfirmed(txid: String, details: TransactionDetails) = + withReceiptOperation { receipt -> + ServiceQueue.CORE.background { + receipt.requireCurrent() + 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 - } + val payments = lightningService.listPayments() ?: run { + Logger.warn("No payments available for transaction $txid", context = TAG) + 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 - } + val payment = payments.firstOrNull { payment -> + (payment.kind as? PaymentKind.Onchain)?.txid == txid + } ?: run { + Logger.warn("Payment not found for transaction $txid", context = TAG) + return@runSuspendCatching + } - processOnchainPayment( - kind = payment.kind as PaymentKind.Onchain, - payment = payment, - forceUpdate = false, - channelId = null, - transactionDetails = coreDetails, - ) - }.onFailure { e -> - Logger.error("Error handling onchain transaction confirmed for $txid", e, context = TAG) + processOnchainPayment( + kind = payment.kind as PaymentKind.Onchain, + payment = payment, + forceUpdate = false, + channelId = null, + transactionDetails = coreDetails, + receipt = receipt, + ) + }.onFailure { e -> + Logger.error("Error handling onchain transaction confirmed for $txid", e, context = TAG) + } } } - } suspend fun publishRbfBoost(originalTxId: String, replacementTxId: String): Activity.Onchain = - ServiceQueue.CORE.background { - require(originalTxId.isNotBlank() && replacementTxId.isNotBlank() && originalTxId != replacementTxId) { - "RBF must replace the original transaction" - } - val initialOriginal = checkNotNull(getActivityByTxId(defaultWalletId, originalTxId)) { - "RBF original is not available" - } - if (initialOriginal.confirmed) throw RbfOriginalConfirmed() - if (getOrCreateReplacementActivity(replacementTxId) == null) { - // RBF returns after broadcast, before wallet sync discovers the new payment. - lightningService.sync() - checkNotNull(getOrCreateReplacementActivity(replacementTxId)) { "RBF replacement is not available" } + withReceiptOperation { receipt -> + ServiceQueue.CORE.background { + receipt.requireCurrent() + require(originalTxId.isNotBlank() && replacementTxId.isNotBlank() && originalTxId != replacementTxId) { + "RBF must replace the original transaction" + } + val initialOriginal = checkNotNull(getActivityByTxId(defaultWalletId, originalTxId)) { + "RBF original is not available" + } + if (initialOriginal.confirmed) throw RbfOriginalConfirmed() + if (getOrCreateReplacementActivity(replacementTxId, receipt) == null) { + // RBF returns after broadcast, before wallet sync discovers the new payment. + lightningService.sync() + receipt.requireCurrent() + checkNotNull(getOrCreateReplacementActivity(replacementTxId, receipt)) { + "RBF replacement is not available" + } + } + val cache = cacheStore.data.first() + receipt.commit { + val original = checkNotNull(getActivityByTxId(defaultWalletId, originalTxId)) + if (original.confirmed) throw RbfOriginalConfirmed() + val replacement = checkNotNull(getActivityByTxId(defaultWalletId, replacementTxId)) + check(original.txType == PaymentType.SENT && replacement.txType == PaymentType.SENT) + check(!cache.isActivityDeleted(original.id, defaultWalletId)) + check(!cache.isActivityDeleted(replacement.id, defaultWalletId)) + val updated = updateReplacementActivity( + originalTxId, + replacementTxId, + replacement, + original, + cache.isContactDetached(replacement.id, defaultWalletId), + ) + markReplacedActivity(originalTxId, original, listOf(replacementTxId)) + updated + } } - val cache = cacheStore.data.first() - val original = checkNotNull(getActivityByTxId(defaultWalletId, originalTxId)) - if (original.confirmed) throw RbfOriginalConfirmed() - val replacement = checkNotNull(getActivityByTxId(defaultWalletId, replacementTxId)) - check(original.txType == PaymentType.SENT && replacement.txType == PaymentType.SENT) - check(!cache.isActivityDeleted(original.id, defaultWalletId)) - check(!cache.isActivityDeleted(replacement.id, defaultWalletId)) - val updated = updateReplacementActivity( - originalTxId, - replacementTxId, - replacement, - original, - cache.isContactDetached(replacement.id, defaultWalletId), - ) - markReplacedActivity(originalTxId, original, listOf(replacementTxId)) - updated } - suspend fun handleOnchainTransactionReplaced(txid: String, conflicts: List) { - ServiceQueue.CORE.background { - runSuspendCatching { - markReplacedActivity(txid, getActivityByTxId(defaultWalletId, txid), conflicts) - for (conflictTxid in conflicts) { - runSuspendCatching { - getOrCreateReplacementActivity(conflictTxid) ?: return@runSuspendCatching - val cache = cacheStore.data.first() - val replacedActivity = getActivityByTxId(defaultWalletId, txid) - val replacement = getActivityByTxId(defaultWalletId, conflictTxid) - ?: return@runSuspendCatching - updateReplacementActivity( - txid, - conflictTxid, - replacement, - replacedActivity, - cache.isContactDetached(replacement.id, defaultWalletId), - ) - }.onFailure { - Logger.error("Failed to handle replacement '$conflictTxid' for '$txid'", it, context = TAG) + suspend fun handleOnchainTransactionReplaced(txid: String, conflicts: List) = + withReceiptOperation { receipt -> + ServiceQueue.CORE.background { + receipt.requireCurrent() + runSuspendCatching { + receipt.commit { markReplacedActivity(txid, getActivityByTxId(defaultWalletId, txid), conflicts) } + for (conflictTxid in conflicts) { + runSuspendCatching { + getOrCreateReplacementActivity(conflictTxid, receipt) ?: return@runSuspendCatching + val cache = cacheStore.data.first() + receipt.commit { + val replacedActivity = getActivityByTxId(defaultWalletId, txid) + val replacement = getActivityByTxId(defaultWalletId, conflictTxid) ?: return@commit + updateReplacementActivity( + txid, + conflictTxid, + replacement, + replacedActivity, + cache.isContactDetached(replacement.id, defaultWalletId), + ) + } + }.onFailure { + Logger.error("Failed to handle replacement '$conflictTxid' for '$txid'", it, context = TAG) + } } + }.onFailure { + Logger.error("Failed to handle replacement for '$txid'", it, context = TAG) } - }.onFailure { - Logger.error("Failed to handle replacement for '$txid'", it, context = TAG) } } - } private fun markReplacedActivity( txid: String, @@ -1805,7 +1820,11 @@ class ActivityService( } } - private suspend fun getOrCreateReplacementActivity(conflictTxid: String): OnchainActivity? { + private suspend fun getOrCreateReplacementActivity( + conflictTxid: String, + receipt: PrivatePaykitContactResolver.Receipt, + ): OnchainActivity? { + receipt.requireCurrent() getActivityByTxId(defaultWalletId, conflictTxid)?.let { return it } val payment = lightningService.listPayments()?.firstOrNull { (it.kind as? PaymentKind.Onchain)?.txid == conflictTxid @@ -1815,6 +1834,7 @@ class ActivityService( payment = payment, forceUpdate = false, channelId = null, + receipt = receipt, ) return getActivityByTxId(defaultWalletId, conflictTxid) } diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt index f83c2fd50e..ae2d7abd0a 100644 --- a/app/src/main/java/to/bitkit/services/LightningService.kt +++ b/app/src/main/java/to/bitkit/services/LightningService.kt @@ -740,7 +740,9 @@ class LightningService internal constructor( if (node != null) throw ServiceError.NodeStillRunning() awaitNodeRelease() Logger.warn("Wiping LDK storage…", context = TAG) - Path(Env.ldkStoragePath(walletIndex)).toFile().deleteRecursively() + if (!Path(Env.ldkStoragePath(walletIndex)).toFile().deleteRecursively()) { + throw WalletStorageDeleteError() + } Logger.info("LDK storage wiped", context = TAG) } @@ -1801,6 +1803,8 @@ data class NetworkGraphInfo( class NetworkGraphCacheDeleteError : AppError("Failed to delete network graph cache") +class WalletStorageDeleteError : AppError("Failed to delete wallet node storage") + /** Exact signed transaction inputs/prevouts, never an estimate or a backend-absence inference. */ internal fun exactOriginalSendFee( details: TransactionDetails, diff --git a/app/src/main/java/to/bitkit/services/PaykitProfileLogout.kt b/app/src/main/java/to/bitkit/services/PaykitProfileLogout.kt new file mode 100644 index 0000000000..0855d4e91f --- /dev/null +++ b/app/src/main/java/to/bitkit/services/PaykitProfileLogout.kt @@ -0,0 +1,51 @@ +package to.bitkit.services + +import com.synonym.paykit.PubkyGrantLogout +import com.synonym.paykit.PubkyGrantLogoutReceipt +import to.bitkit.data.keychain.ProfileCredentials +import java.util.concurrent.atomic.AtomicBoolean +import kotlin.coroutines.AbstractCoroutineContextElement +import kotlin.coroutines.CoroutineContext + +/** A live original-grant handle. A persisted removal UUID can never reconstruct it. */ +internal class PaykitProfileLogout( + internal val native: PubkyGrantLogout, + internal val credentials: ProfileCredentials, + private val validateOriginalSigner: () -> Unit = {}, + private val isOriginalLifecycle: () -> Boolean, +) : AbstractCoroutineContextElement(Key) { + companion object Key : CoroutineContext.Key + + val binding: PubkyGrantLogoutReceipt = native.binding() + private val admitted = AtomicBoolean(true) + private val remoteAcknowledged = AtomicBoolean(false) + internal val credentialsErased = AtomicBoolean(false) + + fun requireCurrent() { + check(admitted.get() && isOriginalLifecycle()) { "The original profile logout is no longer available" } + } + + fun isCurrent(): Boolean = admitted.get() && isOriginalLifecycle() + + fun validateSigner() = validateOriginalSigner() + + fun requireOriginalCredentials() { + check(isOriginalLifecycle()) { "The original profile credentials are no longer current" } + } + + fun revoke() { + admitted.set(false) + native.revokeAdmission() + } + + fun retainAcknowledgement(receipt: PubkyGrantLogoutReceipt) { + check(receipt == binding) { "The logout acknowledgement belongs to another grant" } + remoteAcknowledged.set(true) + } + + /** Inspect after native execution has drained, including when caller cancellation hid its return. */ + fun reconcileAcknowledgement(): Boolean { + native.acknowledged()?.let(::retainAcknowledgement) + return remoteAcknowledged.get() + } +} diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkOperationLock.kt b/app/src/main/java/to/bitkit/services/PaykitSdkOperationLock.kt index ea3483bc12..d22734c61a 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,15 @@ import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.CoroutineContext import kotlin.coroutines.cancellation.CancellationException -internal class PaykitSdkOperationLock { +private const val WALLET_WIPE_IN_PROGRESS = "wallet_wipe_in_progress" + +/** A wallet wipe refused this SDK call, also through `ServiceQueue`'s [to.bitkit.utils.AppError] wrapping. */ +internal fun Throwable.isWalletWipeInProgress() = + generateSequence(this) { it.cause }.any { it is PaykitException.Storage && it.code == WALLET_WIPE_IN_PROGRESS } + +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 +37,121 @@ 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) + currentCoroutineContext()[PaykitProfileLogout]?.requireCurrent() + } + acquire(priority, admittedGeneration) return try { currentCoroutineContext().ensureActive() checkAdmitted(admittedGeneration) + if (!allowPublicReadInitialization) { + checkRecoveryAccess() + checkProfileRemoval(removal) + currentCoroutineContext()[PaykitProfileLogout]?.requireCurrent() + 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) + currentCoroutineContext()[PaykitProfileLogout]?.requireCurrent() + } + + /** Disabled sharing still needs an acknowledged withdrawal during this exact removal. */ + internal suspend fun ownsProfileRemoval(): Boolean { + if (currentCoroutineContext()[ProfileRemoval] == null) return false + requireProfileRemoval() + return true + } + + suspend fun checkProfileRemoval() { + if (!ownsWipe()) { + checkRecoveryAccess() + checkProfileRemoval(currentCoroutineContext()[ProfileRemoval]) + currentCoroutineContext()[PaykitProfileLogout]?.requireCurrent() + } + } + + 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 @@ -57,13 +167,26 @@ 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 { - 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 +198,11 @@ 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(::checkAdmitted) if (!isLocked) { isLocked = true return @@ -133,12 +259,56 @@ 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", ) + 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 2db5d7a36e..d96435dc0c 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt @@ -117,6 +117,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 @@ -268,8 +269,15 @@ 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 profileLogoutLock = Any() + private var capturedProfileLogout: PaykitProfileLogout? = null + private val sessionProvider = PaykitSdkSessionProvider( + keychain, + sharedPubky, + onAccessReplaced = ::revokeProfileLogout + ) private val paymentAdapter = PaykitSdkPaymentAdapter() private val pubkyClientConfig by lazy { paykitPubkyClientConfig() } private var bootstrapFactory = { @@ -287,13 +295,14 @@ 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 publicEndpointEpoch = AtomicLong() 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 @@ -329,8 +338,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) { @@ -344,6 +354,150 @@ 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() + } + } + } + + internal suspend fun captureProfileLogout( + publicKey: String, + isOwnerCurrent: () -> Boolean, + ): PaykitProfileLogout { + operationLock.requireProfileRemoval() + return operationLock.withLock { + val existing = checkNotNull(sdk) { "An original live profile session is required" } + val generation = runtimeGeneration + val requireOriginal = { + check(isOwnerCurrent() && runtimeGeneration == generation && sdk === existing) { + "The profile identity changed" + } + } + requireOriginal() + check(synchronized(profileLogoutLock) { capturedProfileLogout?.isCurrent() != true }) { + "A profile removal confirmation is already active" + } + val target = keychain.captureProfileCredentials(requireOriginal) + val validateSigner = sessionProvider.captureOriginalSigner(publicKey) + var captured: PaykitProfileLogout? = null + try { + completeSdkCall { + val native = existing.captureGrantLogout(publicKey) + captured = PaykitProfileLogout(native, target, validateSigner) { + isOwnerCurrent() && runtimeGeneration == generation && sdk === existing + } + } + requireOriginal() + val logout = checkNotNull(captured) + validateOriginalProfileCredentials(logout) + check(PubkyPublicKeyFormat.matches(logout.binding.publicKey, publicKey)) { + "The captured logout belongs to another profile" + } + synchronized(profileLogoutLock) { capturedProfileLogout = logout } + logout + } catch (error: Throwable) { + captured?.revoke() + throw error + } + } + } + + internal fun revokeProfileLogout() { + val previous = synchronized(profileLogoutLock) { + capturedProfileLogout.also { capturedProfileLogout = null } + } + previous?.revoke() + } + + internal suspend fun executeProfileLogout(logout: PaykitProfileLogout) { + operationLock.requireProfileRemoval() + logout.requireCurrent() + if (logout.reconcileAcknowledgement()) return + try { + withContext(NonCancellable) { + operationLock.requireProfileRemoval() + validateOriginalProfileCredentials(logout) + logout.native.prepareAttempt().use { attempt -> + operationLock.requireProfileRemoval() + validateOriginalProfileCredentials(logout) + logout.retainAcknowledgement(attempt.execute()) + } + } + } finally { + logout.reconcileAcknowledgement() + } + } + + internal suspend fun validateProfileLogout(logout: PaykitProfileLogout) { + operationLock.requireProfileRemoval() + operationLock.withLock { validateOriginalProfileCredentials(logout) } + } + + private suspend fun validateOriginalProfileCredentials(logout: PaykitProfileLogout) { + logout.requireCurrent() + try { + keychain.validateProfileCredentials(logout.credentials, logout::requireCurrent) + logout.validateSigner() + } catch (error: CancellationException) { + throw error + } catch (error: Throwable) { + // Once an incompatible or unreadable bundle is observed, restoring its bytes cannot revive authority. + logout.revoke() + throw error + } + operationLock.requireProfileRemoval() + } + + internal suspend fun eraseProfileLogoutCredentials(logout: PaykitProfileLogout, localOnly: Boolean) { + operationLock.requireProfileRemoval() + check(localOnly || logout.reconcileAcknowledgement()) { "The original grant logout is not acknowledged" } + if (logout.credentialsErased.get()) return + operationLock.withLock { + logout.requireOriginalCredentials() + withContext(NonCancellable) { + if (localOnly) { + keychain.eraseProfileCredentialsAfterLocalConfirmation( + logout.credentials, + logout::requireOriginalCredentials, + ) + } else { + keychain.eraseProfileCredentials(logout.credentials, logout::requireOriginalCredentials) + } + logout.credentialsErased.set(true) + sessionProvider.clearLiveSessionAccess() + resetRuntime() + notifyBackupStateChanged() + } + } + } + fun setPaymentSubmissionActive(active: Boolean) { _isPaymentSubmissionActive.update { active } } @@ -364,17 +518,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) @@ -410,6 +570,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() @@ -420,12 +582,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 @@ -437,6 +603,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 @@ -456,8 +625,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? { @@ -643,7 +820,7 @@ class PaykitSdkService @Inject constructor( withPaykitKey { handle -> val publicKey = requireNotNull(completeSdkCall { handle.identityStatus() }?.publicKey) requireProfileIdentity(publicKey, expectedIdentity) - val current = handle.fetchPaykitProfile(publicKey) + val current = completeSdkCall { handle.fetchPaykitProfile(publicKey) } completeSdkCall { handle.publishPaykitProfile(profile, current?.revision).also { notifyBackupStateChanged() } } @@ -667,12 +844,72 @@ 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" } + requireNoActiveSubscriptions(handle) + 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" } + requireNoActiveSubscriptions(handle) + 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, onAcknowledged: () -> Unit = {}) { + isSetup.await() + operationLock.withLock { + withPaykitKey { handle -> + val identity = completeSdkCall { handle.identityStatus() }?.publicKey + check(PubkyPublicKeyFormat.matches(identity, snapshot.publicKey)) { "Profile removal identity changed" } + requireNoActiveSubscriptions(handle) + if (snapshot.profileRevision == null) { + check(completeSdkCall { handle.fetchPaykitProfile(snapshot.publicKey) } == null) { + "Profile changed; review it before removing it" + } + onAcknowledged() + } else { + completeSdkCall { + handle.deletePaykitProfile(snapshot.profileRevision) + onAcknowledged() + notifyBackupStateChanged() + } + } + } + } + } + suspend fun deletePaykitProfile() { isSetup.await() operationLock.withLock { withPaykitKey { handle -> + requireNoActiveSubscriptions(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() @@ -702,11 +939,19 @@ class PaykitSdkService @Inject constructor( } } - suspend fun deletePubkyProfile(expectedRevision: String, expectedIdentity: String) { + suspend fun deletePubkyProfile( + expectedRevision: String, + expectedIdentity: String, + onAcknowledged: () -> Unit = {}, + ) { isSetup.await() operationLock.withLock { requireProfileIdentity(currentIdentity(), expectedIdentity) - completeSdkCall { handle().deletePubkyProfile(expectedRevision) } + requireNoActiveSubscriptions(handle()) + completeSdkCall { + handle().deletePubkyProfile(expectedRevision) + onAcknowledged() + } } } @@ -825,6 +1070,37 @@ class PaykitSdkService @Inject constructor( return imported } + suspend fun checkProfileDeletionAllowed() { + isSetup.await() + operationLock.withLock { + withStateRevisionTracking { handle -> + 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) + } + + 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 { @@ -834,12 +1110,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 { @@ -859,18 +1130,29 @@ class PaykitSdkService @Inject constructor( } } - suspend fun removeContacts(publicKeys: List): List { - if (publicKeys.isEmpty()) return emptyList() + 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() && !requireAll) 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) requireNoProfileSubscriptions(subscriptions) + 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) } @@ -897,6 +1179,13 @@ class PaykitSdkService @Inject constructor( privatePaymentsEnabled: Boolean?, priority: Priority, canSync: suspend () -> Boolean, + ): Boolean = syncPaykitApp(privatePaymentsEnabled, priority, canSync) {} + + internal suspend fun syncPaykitApp( + privatePaymentsEnabled: Boolean?, + priority: Priority, + canSync: suspend () -> Boolean, + onAcknowledged: () -> Unit, ): Boolean { isSetup.await() return operationLock.withLock(priority) { @@ -912,6 +1201,7 @@ class PaykitSdkService @Inject constructor( privatePayments = capabilities.privatePayments && privateSharing ), ) + onAcknowledged() } true } @@ -924,7 +1214,13 @@ class PaykitSdkService @Inject constructor( internal suspend fun syncPublicEndpoints( endpoints: List, canPublish: suspend () -> Boolean, - ): EndpointSyncReport? = syncPublicEndpointsWithEpoch(endpoints, canPublish, reusable = null)?.report + ): EndpointSyncReport? = syncPublicEndpoints(endpoints, {}, canPublish) + + internal suspend fun syncPublicEndpoints( + endpoints: List, + onAcknowledged: () -> Unit, + canPublish: suspend () -> Boolean, + ): EndpointSyncReport? = syncPublicEndpoints(endpoints, canPublish, reusable = null, onAcknowledged)?.report internal fun publicEndpointSyncEpoch(): Long = publicEndpointEpoch.get() @@ -932,6 +1228,13 @@ class PaykitSdkService @Inject constructor( endpoints: List, canPublish: suspend () -> Boolean, reusable: PublicEndpointSync?, + ): 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()) { @@ -950,7 +1253,11 @@ class PaykitSdkService @Inject constructor( // Direct withdrawals use this same lock. An uncertain write invalidates earlier success too. val epoch = publicEndpointEpoch.incrementAndGet() val report = completeSdkCall { - handle.syncPublicEndpointsWithReceivingDetails(endpoints.map { it.toPublicReceivingDetail() }) + handle.syncPublicEndpointsWithReceivingDetails( + endpoints.map { it.toPublicReceivingDetail() } + ).also { + if (it.failed.isEmpty()) onAcknowledged() + } } PublicEndpointSync(report, epoch) } @@ -1015,6 +1322,12 @@ class PaykitSdkService @Inject constructor( suspend fun clearPrivatePaymentLists( counterparties: List, isStillCurrent: (() -> Boolean)? = null, + ): PrivatePaymentListDeliveryReport? = clearPrivatePaymentLists(counterparties, isStillCurrent) {} + + suspend fun clearPrivatePaymentLists( + counterparties: List, + isStillCurrent: (() -> Boolean)?, + onDelivered: (PrivatePaymentListDeliveryReport) -> Unit, ): PrivatePaymentListDeliveryReport? { if (counterparties.isEmpty()) return null isSetup.await() @@ -1029,11 +1342,6 @@ class PaykitSdkService @Inject constructor( } }.map { PrivatePaymentListReservationUpdateInput(it, emptyList()) } 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" } - if (app?.capabilities?.privatePayments == false) return@withStateRevisionTracking null - } for (update in updates) { checkPaykitContactSync(isStillCurrent) if (peers.any { @@ -1053,7 +1361,7 @@ class PaykitSdkService @Inject constructor( handle.syncPrivatePaymentListsWithReservationsAndProcessOutbound( updates = updates, clearUnlistedLinkedPeers = false, - ) + ).also(onDelivered) } } } @@ -1795,6 +2103,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() { @@ -1811,17 +2133,31 @@ 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. 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) + runSuspendCatching { preparePublicProfileRecovery() } + .onFailure { Logger.warn("Failed to prepare public access before wallet wipe", it, context = TAG) } + } 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() + } } } } @@ -1834,22 +2170,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()) } @@ -1862,9 +2203,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) @@ -1883,6 +2225,7 @@ class PaykitSdkService @Inject constructor( private suspend fun activateBootstrapResult( result: PubkySessionBootstrapResult, ) { + revokeProfileLogout() persistSessionAccess(result.sessionAccess) sessionProvider.setLiveSessionAccess(result.sessionAccess) val previousOwner = pubkyStore.data.first().ownerPublicKey @@ -1891,6 +2234,7 @@ class PaykitSdkService @Inject constructor( } resetRuntime() refreshPaykitKey() + operationLock.checkProfileRemoval() val handle = handle() val identityStatus = completeSdkCall { handle.initialize() } if (result.sessionAccess.exportLocalSecretKey() != null) { @@ -1964,6 +2308,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) @@ -2028,6 +2373,8 @@ class PaykitSdkService @Inject constructor( private suspend fun completeSdkCall(operation: suspend () -> T): T { currentCoroutineContext().ensureActive() + operationLock.checkProfileRemoval() + currentCoroutineContext()[PaykitProfileLogout]?.let { validateOriginalProfileCredentials(it) } val result = withContext(NonCancellable) { runSuspendCatching { operation() } } .onFailure(::invalidatePaykitKeyIfNeeded) currentCoroutineContext().ensureActive() @@ -2061,7 +2408,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) @@ -2091,6 +2438,7 @@ class PaykitSdkService @Inject constructor( } private fun resetRuntime() { + revokeProfileLogout() runtimeGeneration++ publicEndpointEpoch.incrementAndGet() sdk = null @@ -2184,22 +2532,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() + } } } } @@ -2238,6 +2596,8 @@ internal fun validatedApprovalClientId(requestClientId: String, approvedClientId internal class PaykitSdkSessionProvider( private val keychain: Keychain, private val sharedPubky: SharedPubkyClient, + private val derivePublicKey: (String) -> String = PaykitSdkService::publicKeyFromSecret, + private val onAccessReplaced: () -> Unit = {}, ) : SdkPubkySessionProvider { private val lock = Any() private var paykitIdentitySecretKey: PaykitIdentitySecretKey? = null @@ -2245,11 +2605,13 @@ internal class PaykitSdkSessionProvider( private var isStoredSessionAccessSuspended = false fun setLiveSessionAccess(access: PubkySessionAccess) = synchronized(lock) { + onAccessReplaced() liveSessionAccess = access paykitIdentitySecretKey = access.exportPaykitIdentitySecretKey() } fun clearLiveSessionAccess() = synchronized(lock) { + onAccessReplaced() liveSessionAccess = null paykitIdentitySecretKey = null } @@ -2265,6 +2627,7 @@ internal class PaykitSdkSessionProvider( ?.takeIf { it.exportSessionSecret() == sessionSecret } ?.let { return@synchronized it } + onAccessReplaced() PubkySessionAccess( clientId = BitkitPaykitSdkConfig.clientId, sessionSecret = sessionSecret, @@ -2283,6 +2646,7 @@ internal class PaykitSdkSessionProvider( errorContext == STALE_SESSION_RESTORE_CONTEXT && hasSessionAccess() fun suspendStoredSessionAccess() = synchronized(lock) { + onAccessReplaced() liveSessionAccess = null isStoredSessionAccessSuspended = true } @@ -2307,6 +2671,39 @@ internal class PaykitSdkSessionProvider( ?.substringAfter(SharedPubkyContract.RING_SOURCE_PREFIX, "") ?.takeIf { it.isNotBlank() } + /** Validate the selected local identity without reconstructing or refreshing the retained live access. */ + fun captureOriginalSigner(expectedPublicKey: String): () -> Unit { + val managedKey = keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)?.takeIf { it.isNotBlank() } + if (managedKey != null) { + check(PubkyPublicKeyFormat.matches(derivePublicKey(managedKey), expectedPublicKey)) { + "The stored profile key belongs to another identity" + } + // The captured Bitkit credential bundle checks this key on every remote admission. + return {} + } + val source = keychain.loadString(Keychain.Key.SHARED_PUBKY_SOURCE.name)?.takeIf { it.isNotBlank() } + ?: return {} // A genuine live delegate can have no local identity root. + check(source.startsWith(SharedPubkyContract.RING_SOURCE_PREFIX)) { "The adopted profile source is unavailable" } + val owner = source.removePrefix(SharedPubkyContract.RING_SOURCE_PREFIX) + check( + PubkyPublicKeyFormat.matches(owner, expectedPublicKey) + ) { "The adopted profile belongs to another identity" } + val credential = checkNotNull( + sharedPubky.readCredential(owner) + ) { "The adopted profile credential is unavailable" } + check(PubkyPublicKeyFormat.matches(derivePublicKey(credential), expectedPublicKey)) { + "The adopted profile key belongs to another identity" + } + return { + val current = sharedPubky.readCredential(owner) + check( + current != null && java.security.MessageDigest.isEqual(credential.toByteArray(), current.toByteArray()) + ) { + "The adopted profile credential changed" + } + } + } + fun loadLocalSecretKey(): PubkyLocalSecretKey? { val secretKeyHex = keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name) ?.takeIf { it.isNotBlank() } @@ -2316,9 +2713,9 @@ internal class PaykitSdkSessionProvider( } fun setPaykitIdentitySecretKey(key: PaykitIdentitySecretKey) = synchronized(lock) { - if (paykitIdentitySecretKey?.keyGeneration() != key.keyGeneration()) { - liveSessionAccess = null - } + if (paykitIdentitySecretKey === key) return@synchronized + onAccessReplaced() + liveSessionAccess = liveSessionAccess?.withPaykitIdentitySecretKey(key) paykitIdentitySecretKey = key } } @@ -2397,5 +2794,12 @@ internal fun paykitStorageCallback(code: String, operation: () -> T): T = 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, +) + /** The signed-in identity changed before a profile write, so it wrote nothing. */ class PubkyProfileIdentityChangedError : AppError("Pubky identity changed before the profile write") diff --git a/app/src/main/java/to/bitkit/services/PubkyService.kt b/app/src/main/java/to/bitkit/services/PubkyService.kt index 2ad6b297ab..2aac52a985 100644 --- a/app/src/main/java/to/bitkit/services/PubkyService.kt +++ b/app/src/main/java/to/bitkit/services/PubkyService.kt @@ -34,6 +34,10 @@ class PubkyService @Inject constructor( internal val AUTHORIZATION_TIMEOUT = 30.seconds } + internal suspend fun preparePublicProfileRecovery() = ServiceQueue.PUBKY.background { + paykitSdkService.preparePublicProfileRecovery() + } + suspend fun initialize() = ServiceQueue.PUBKY.background { paykitSdkService.initialize() } @@ -59,10 +63,46 @@ 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.PUBKY.background { paykitSdkService.forgetSessionAccess() } + internal suspend fun forgetLocalProfileAccess() = ServiceQueue.PUBKY.background { + paykitSdkService.forgetLocalProfileAccess() + } + + internal suspend fun captureProfileLogout(publicKey: String, isOwnerCurrent: () -> Boolean): PaykitProfileLogout { + var captured: PaykitProfileLogout? = null + return try { + ServiceQueue.PUBKY.background { + paykitSdkService.captureProfileLogout(publicKey, isOwnerCurrent).also { captured = it } + } + } catch (error: Throwable) { + // Queue cancellation can hide the successful native capture from its original caller. + captured?.revoke() + throw error + } + } + + internal suspend fun executeProfileLogout(logout: PaykitProfileLogout) = + ServiceQueue.PUBKY.background { paykitSdkService.executeProfileLogout(logout) } + + internal suspend fun validateProfileLogout(logout: PaykitProfileLogout) = + ServiceQueue.PUBKY.background { paykitSdkService.validateProfileLogout(logout) } + + internal suspend fun eraseProfileLogoutCredentials(logout: PaykitProfileLogout, localOnly: Boolean) = + ServiceQueue.PUBKY.background { paykitSdkService.eraseProfileLogoutCredentials(logout, localOnly) } + + internal fun revokeProfileLogout() = paykitSdkService.revokeProfileLogout() + + internal fun beginWalletWipe() = paykitSdkService.beginWalletWipe() + + internal suspend fun requireWalletWipe() = paykitSdkService.requireWalletWipe() + suspend fun clearSessionAccess() = ServiceQueue.PUBKY.background { paykitSdkService.clearSessionAccess() } @@ -80,6 +120,32 @@ class PubkyService @Inject constructor( cleanupError?.let { throw it } } + internal suspend fun removeBitkitPaymentEndpointsForRemoval( + endpointsAcknowledged: Boolean, + appAcknowledged: Boolean, + onEndpointsAcknowledged: () -> Unit, + onAppAcknowledged: () -> Unit, + ): Unit = ServiceQueue.PUBKY.background { + val endpointError = runSuspendCatching { + if (!endpointsAcknowledged) { + val report = paykitSdkService.syncPublicEndpoints(emptyList(), onEndpointsAcknowledged) { true } + check(report != null && report.failed.isEmpty()) { "Failed to remove Paykit payment endpoints" } + } + }.exceptionOrNull() + val appError = runSuspendCatching { + if (!appAcknowledged) { + paykitSdkService.syncPaykitApp( + privatePaymentsEnabled = false, + priority = PaykitSdkOperationLock.Priority.Ordered, + canSync = { true }, + onAcknowledged = onAppAcknowledged, + ) + } + }.exceptionOrNull() + if (endpointError != null && appError != null) endpointError.addSuppressed(appError) + (endpointError ?: appError)?.let { throw it } + } + // endregion // region Key derivation @@ -227,6 +293,36 @@ class PubkyService @Inject constructor( paykitSdkService.uploadProfileAvatar(bytes, contentType) } + internal suspend fun captureProfileDeletion( + publicKey: String, + isStillCurrent: () -> Boolean, + ): PaykitProfileDeletionSnapshot = ServiceQueue.PUBKY.background { + paykitSdkService.captureProfileDeletion(publicKey, isStillCurrent) + } + + internal suspend fun validateProfileDeletion(snapshot: PaykitProfileDeletionSnapshot) = + ServiceQueue.PUBKY.background { + paykitSdkService.validateProfileDeletion(snapshot) + } + + internal suspend fun deletePaykitProfile(snapshot: PaykitProfileDeletionSnapshot) = + deletePaykitProfile(snapshot) {} + + internal suspend fun deletePaykitProfile( + snapshot: PaykitProfileDeletionSnapshot, + onAcknowledged: () -> Unit, + ) = ServiceQueue.PUBKY.background { + paykitSdkService.deletePaykitProfile(snapshot, onAcknowledged) + } + suspend fun checkProfileDeletionAllowed() = ServiceQueue.PUBKY.background { + paykitSdkService.checkProfileDeletionAllowed() + } + + suspend fun removeContactsForProfile(publicKeys: List): List = + ServiceQueue.PUBKY.background { + paykitSdkService.removeContactsForProfile(publicKeys) + } + suspend fun deletePaykitProfile() = ServiceQueue.PUBKY.background { paykitSdkService.deletePaykitProfile() } @@ -247,8 +343,12 @@ class PubkyService @Inject constructor( paykitSdkService.publishPubkyProfile(update, expectedRevision, expectedIdentity) } - suspend fun deletePubkyProfile(expectedRevision: String, expectedIdentity: String) = ServiceQueue.PUBKY.background { - paykitSdkService.deletePubkyProfile(expectedRevision, expectedIdentity) + suspend fun deletePubkyProfile( + expectedRevision: String, + expectedIdentity: String, + onAcknowledged: () -> Unit = {}, + ) = ServiceQueue.PUBKY.background { + paykitSdkService.deletePubkyProfile(expectedRevision, expectedIdentity, onAcknowledged) } suspend fun uploadPubkyAppAvatar(bytes: ByteArray, contentType: String, expectedIdentity: String): String = diff --git a/app/src/main/java/to/bitkit/ui/MainActivity.kt b/app/src/main/java/to/bitkit/ui/MainActivity.kt index 8779a86cd9..d627e3f4e5 100644 --- a/app/src/main/java/to/bitkit/ui/MainActivity.kt +++ b/app/src/main/java/to/bitkit/ui/MainActivity.kt @@ -48,6 +48,7 @@ import to.bitkit.R import to.bitkit.androidServices.LightningNodeService import to.bitkit.androidServices.LightningNodeService.Companion.ACTION_START_SERVICE import to.bitkit.androidServices.LightningNodeService.Companion.CHANNEL_ID_NODE +import to.bitkit.data.WalletResetRecovery import to.bitkit.models.NewTransactionSheetDetails import to.bitkit.models.SamRockSetupRequest import to.bitkit.nfc.NfcRepeatGuard @@ -67,7 +68,9 @@ 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 import to.bitkit.ui.sheets.NewTransactionSheet import to.bitkit.ui.theme.AppThemeSurface @@ -140,7 +143,11 @@ class MainActivity : FragmentActivity() { val isRecoveryMode by walletViewModel.isRecoveryMode.collectAsStateWithLifecycle() val notificationsGranted by settingsViewModel.notificationsGranted.collectAsStateWithLifecycle() val keepActive by settingsViewModel.keepBitkitActiveInBackground.collectAsStateWithLifecycle() - val walletExists = walletViewModel.walletExists + val walletState by walletViewModel.walletState.collectAsStateWithLifecycle() + val walletExists = walletState.walletExists + 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() @@ -157,9 +164,10 @@ class MainActivity : FragmentActivity() { notificationsGranted, keepActive, restoreState, + walletResetRecovery, ) { val canStartService = walletExists && notificationsGranted && keepActive && restoreState.isIdle() - if (canStartService && !isRecoveryMode) { + if (canStartService && !isRecoveryMode && walletResetRecovery == WalletResetRecovery.Clear) { tryStartForegroundService() } else { stopForegroundService() @@ -169,8 +177,12 @@ class MainActivity : FragmentActivity() { RootDestination( isCriticalUpdateRequired = isCriticalUpdateRequired, isShowingMigrationLoading = isShowingMigrationLoading, + isCheckingRNMigration = isCheckingRNMigration, + isRNMigrationUnavailable = isRNMigrationUnavailable, walletExists = walletExists, isRecoveryMode = isRecoveryMode, + walletResetRecovery = walletResetRecovery, + resetRecovery = { WalletResetRecoveryScreen(walletViewModel, appViewModel, settingsViewModel) }, criticalUpdate = { val lifecycle = LocalLifecycleOwner.current.lifecycle DisposableEffect(lifecycle, walletExists, isRecoveryMode, notificationsGranted, keepActive) { @@ -189,6 +201,9 @@ class MainActivity : FragmentActivity() { CriticalUpdateScreen() }, migrationLoading = { MigrationLoadingScreen(isVisible = true) }, + migrationRecovery = { + MigrationRecoveryScreen(onRetry = walletViewModel::refreshWalletResetRecovery) + }, onboarding = { CompositionLocalProvider(LocalAppViewModel provides appViewModel) { OnboardingNav( @@ -262,7 +277,9 @@ class MainActivity : FragmentActivity() { val transactionSheetDetails by appViewModel.transactionSheet.collectAsStateWithLifecycle() val hideBalance by settingsViewModel.hideBalance.collectAsStateWithLifecycle() - if (isAuthenticated && transactionSheetDetails != NewTransactionSheetDetails.EMPTY) { + if (isAuthenticated && walletResetRecovery == WalletResetRecovery.Clear && + transactionSheetDetails != NewTransactionSheetDetails.EMPTY + ) { NewTransactionSheet( appViewModel = appViewModel, bottomSheetOverlayState = bottomSheetOverlayState, @@ -428,15 +445,23 @@ class MainActivity : FragmentActivity() { 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, + resetRecovery: @Composable () -> Unit, ) { when { isCriticalUpdateRequired -> criticalUpdate() + walletResetRecovery != WalletResetRecovery.Clear -> resetRecovery() + isRNMigrationUnavailable -> migrationRecovery() + isCheckingRNMigration -> migrationLoading() isShowingMigrationLoading && !isRecoveryMode -> migrationLoading() !walletExists && !isRecoveryMode -> onboarding() else -> wallet() diff --git a/app/src/main/java/to/bitkit/ui/components/AuthCheckView.kt b/app/src/main/java/to/bitkit/ui/components/AuthCheckView.kt index 848ae94fa3..73fbef736c 100644 --- a/app/src/main/java/to/bitkit/ui/components/AuthCheckView.kt +++ b/app/src/main/java/to/bitkit/ui/components/AuthCheckView.kt @@ -49,6 +49,8 @@ fun AuthCheckView( requirePin: Boolean = false, onSuccess: (() -> Unit)? = null, onBack: (() -> Unit)? = null, + onValidatePin: ((String) -> Boolean)? = null, + onClickForgotPin: (() -> Unit)? = null, ) { val isBiometricsEnabled by settingsViewModel.isBiometricEnabled.collectAsStateWithLifecycle() val attemptsRemaining by appViewModel.pinAttemptsRemaining.collectAsStateWithLifecycle() @@ -60,10 +62,10 @@ fun AuthCheckView( attemptsRemaining = attemptsRemaining, requireBiometrics = requireBiometrics, requirePin = requirePin, - validatePin = appViewModel::validatePin, + 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/components/ProfileEditForm.kt b/app/src/main/java/to/bitkit/ui/components/ProfileEditForm.kt index 6a67454fd5..a9841d9218 100644 --- a/app/src/main/java/to/bitkit/ui/components/ProfileEditForm.kt +++ b/app/src/main/java/to/bitkit/ui/components/ProfileEditForm.kt @@ -95,6 +95,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) @@ -281,6 +282,7 @@ fun ProfileEditForm( } } + additionalActions() VerticalSpacer(footerHeight + 16.dp) } 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/ui/screens/profile/EditProfileScreen.kt b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt index be27899857..5d007d4621 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 @@ -35,10 +35,13 @@ import to.bitkit.models.PROFILE_LINKS_MAX_COUNT import to.bitkit.models.isValidProfileName 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.components.pubkyAppLinkErrorText import to.bitkit.ui.scaffold.AppAlertDialog import to.bitkit.ui.scaffold.AppTopBar @@ -59,14 +62,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, @@ -84,6 +85,7 @@ fun EditProfileScreen( onRetryDelete = viewModel::retryDeleteProfile, onDismissDeleteFailureDialog = viewModel::dismissDeleteFailureDialog, onDisconnectProfile = viewModel::disconnectProfile, + onLocalDisconnect = viewModel::showLocalDisconnectConfirmation, onDismissAddLinkSheet = viewModel::dismissAddLinkSheet, onSaveLink = viewModel::addLink, onDismissAddTagSheet = viewModel::dismissAddTagSheet, @@ -92,7 +94,7 @@ fun EditProfileScreen( } @Composable -private fun Content( +internal fun EditProfileContent( uiState: EditProfileUiState, onBackClick: () -> Unit, onNameChange: (String) -> Unit, @@ -110,6 +112,7 @@ private fun Content( onRetryDelete: () -> Unit, onDismissDeleteFailureDialog: () -> Unit, onDisconnectProfile: () -> Unit, + onLocalDisconnect: () -> Unit, onDismissAddLinkSheet: () -> Unit, onSaveLink: (String, String) -> Unit, onDismissAddTagSheet: () -> Unit, @@ -196,28 +199,65 @@ private fun Content( 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") + ) + } + }, ) } } 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, + confirmTestTag = if (uiState.isLocalDisconnect) "ProfileLocalDisconnectConfirm" else "DialogConfirm", ) } 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, @@ -280,7 +320,7 @@ private fun AvatarSection( @Composable private fun Preview() { AppThemeSurface { - Content( + EditProfileContent( uiState = EditProfileUiState( name = "Satoshi", bio = "Authored the Bitcoin white paper", @@ -303,6 +343,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 226709f9ab..b1fa83ec54 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 @@ -18,17 +18,15 @@ import kotlinx.collections.immutable.persistentSetOf import kotlinx.collections.immutable.toImmutableList import kotlinx.collections.immutable.toImmutableMap import kotlinx.collections.immutable.toImmutableSet -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.isPaykitNonWebProfileLinkRejected -import to.bitkit.ext.runSuspendCatching +import to.bitkit.ext.toLocalizedTimestamp import to.bitkit.models.PROFILE_NAME_MAX_LENGTH import to.bitkit.models.PubkyAppLinkError import to.bitkit.models.PubkyProfileLink @@ -38,13 +36,18 @@ import to.bitkit.models.pubkyAppLinkError import to.bitkit.models.singleLine import to.bitkit.models.takeCodePoints import to.bitkit.models.toPubkyAppLinkUrl -import to.bitkit.repositories.PrivatePaykitRepo import to.bitkit.repositories.ProfileEditBase +import to.bitkit.repositories.PubkyContactError import to.bitkit.repositories.PubkyProfileChangedError +import to.bitkit.repositories.PubkyProfileOwner import to.bitkit.repositories.PubkyProfileTagsNotSavedError 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.usecases.ProfileRemovalLocalOnly import to.bitkit.utils.Logger import javax.inject.Inject @@ -52,12 +55,16 @@ 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 var editBase = ProfileEditBase(profile = null, revision = null) private val _uiState = MutableStateFlow(EditProfileUiState()) @@ -77,6 +84,10 @@ class EditProfileViewModel @Inject constructor( val profile = editBase.profile 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( @@ -194,12 +205,54 @@ 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(screenOwner) { removalCoordinator.prepareDeletion(screenOwner) } + } } fun dismissDeleteDialog() { - _uiState.update { it.copy(showDeleteDialog = false) } + preparationRevision++ + removalCoordinator.discard(removalConfirmation) + removalConfirmation = null + _uiState.update { + it.copy( + showDeleteDialog = false, + showDeleteFailureDialog = removalFailure != null, + canReviewRemoval = removalFailure?.canReview == true, + ) + } + } + + private suspend fun prepareConfirmation( + owner: PubkyProfileOwner, + 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)) { + removalCoordinator.discard(confirmation) + return@onSuccess + } + removalConfirmation = confirmation + _uiState.update { + it.copy( + showDeleteDialog = true, + showDeleteFailureDialog = false, + isLocalDisconnect = confirmation.localOnly + ) + } + }.onFailure { error -> + if (revision != preparationRevision || !removalCoordinator.isCurrent(owner)) return@onFailure + _uiState.update { it.copy(canReviewRemoval = removalFailure?.canReview == true) } + showRemovalError(error) + } + } finally { + _uiState.update { it.copy(isPreparingRemoval = false) } + } } fun save() { @@ -258,80 +311,125 @@ 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() { + if (_uiState.value.isBusy) return + val failure = removalFailure ?: return viewModelScope.launch { - attemptDeleteProfile() + prepareConfirmation( + failure.confirmation.owner + ) { removalCoordinator.reviewAgain(failure) } } } fun dismissDeleteFailureDialog() { + preparationRevision++ + removalCoordinator.discard(removalConfirmation) + 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() - } - } - 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(failure.recoveryOwner) { removalCoordinator.prepareLocalDisconnect(failure) } + } + } + + fun showLocalDisconnectConfirmation() { + if (_uiState.value.isBusy || !_uiState.value.canDisconnectLocally) return + viewModelScope.launch { + prepareConfirmation(screenOwner) { removalCoordinator.prepareLocalDisconnect(screenOwner) } } } - private suspend fun attemptDeleteProfile() { + private suspend fun performRemoval(confirmation: ProfileRemovalConfirmation) { if (_uiState.value.isBusy) return _uiState.update { it.copy( showDeleteDialog = false, showDeleteFailureDialog = false, + canDisconnectLocally = false, isDeleting = true, ) } try { - privatePaykitRepo.beginProfileDeletion() - privatePaykitRepo.removePublishedEndpointsForCleanup(TAG, deferAppSync = true) - val result = pubkyRepo.deleteProfileWithSessionRetry() - if (result.isSuccess) { - privatePaykitRepo.closeAndClear() - 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) } + removalCoordinator.remove(confirmation).onSuccess { endedOwner -> + removalFailure = null + if (removalCoordinator.isCurrent(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 + if (removalFailure != null) { + _uiState.update { + it.copy( + showDeleteFailureDialog = true, + canReviewRemoval = requireNotNull(removalFailure).canReview, + ) + } + } else { + if (removalCoordinator.isCurrent(confirmation.owner)) showRemovalError(error) + } } } 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, + ) + } } } + + private suspend fun showRemovalError(error: Throwable) { + if (error is ProfileRemovalLocalOnly) _uiState.update { it.copy(canDisconnectLocally = true) } + if (error is PubkyContactError.ActiveProfileSubscriptions || error == PubkyContactError.ActiveSubscription) { + _uiState.update { it.copy(canDisconnectLocally = true) } + ToastEventBus.send( + Toast.ToastType.ERROR, + context.getString(R.string.profile__delete_error_title), + listOfNotNull( + context.getString(R.string.profile__delete_active_subscription), + (error as? PubkyContactError.ActiveProfileSubscriptions)?.endsAtMillis?.let { + context.getString(R.string.subscriptions__expires_date, it.toLocalizedTimestamp()) + }, + ).joinToString("\n"), + ) + } else { + ToastEventBus.send( + Toast.ToastType.ERROR, + context.getString(R.string.profile__disconnect_error), + error.message, + ) + } + } + + fun isRemovalCurrent(effect: EditProfileEffect.RemovalCompleted): Boolean = + removalCoordinator.isCurrent(effect.owner) + + override fun onCleared() { + removalCoordinator.discard(removalConfirmation) + } } @Stable @@ -352,12 +450,16 @@ data class EditProfileUiState( val isLoading: Boolean = false, val isSaving: Boolean = false, 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, val showAddLinkSheet: Boolean = false, val showAddTagSheet: Boolean = false, ) { - val isBusy: Boolean get() = isSaving || isDeleting + val isBusy: Boolean get() = isSaving || isDeleting || isPreparingRemoval /** * The links pubky.app would refuse, by index. A save sends the links only once they differ from the stored ones @@ -416,8 +518,7 @@ 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 } private fun Throwable.rejectedLink(links: List): ProfileEditLink? { 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 9999c40269..cf1d4926cb 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 @@ -93,12 +94,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, @@ -113,11 +114,12 @@ fun ProfileScreen( onDismissAddTagSheet = { viewModel.dismissAddTagSheet() }, onSaveTag = { viewModel.addTag(it) }, onDismissCopiedPopup = { viewModel.dismissCopiedPopup() }, + onClickRemoteRetry = { viewModel.showSignOutConfirmation(remoteRetry = true) }, ) } @Composable -private fun Content( +internal fun ProfileContent( uiState: ProfileUiState, onBackClick: () -> Unit, onClickEdit: () -> Unit, @@ -132,19 +134,55 @@ private fun Content( onDismissAddTagSheet: () -> Unit, onSaveTag: (String) -> Unit, onDismissCopiedPopup: () -> Unit, + onClickRemoteRetry: () -> 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, ) } when { + uiState.recoveryPending -> ScreenColumn { + topBar(Modifier) + VerticalSpacer(32.dp) + BodyM( + text = stringResource( + if (uiState.recoveryCanDisconnect) { + R.string.profile__cleanup_pending + } else { + R.string.profile__wallet_recovery_pending + }, + ), + ) + if (uiState.recoveryCanDisconnect) { + VerticalSpacer(24.dp) + if (uiState.recoveryCanRetry) { + PrimaryButton( + text = stringResource(R.string.common__retry), + onClick = onClickRemoteRetry, + enabled = !uiState.isSigningOut, + modifier = Modifier.testTag("ProfileRecoveryRetry"), + ) + VerticalSpacer(16.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, @@ -189,7 +227,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, @@ -557,7 +601,7 @@ private fun EmptyState( @Composable private fun PreviewCached() { AppThemeSurface { - Content( + ProfileContent( uiState = ProfileUiState( cachedProfile = PubkyCachedProfile( publicKey = "pk8e3qm5...gxag", @@ -587,7 +631,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 8b2d5b3592..05fcf22720 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,14 +69,35 @@ 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, pubkyRepo.restorationNeedsUpdate, ) { showSignOutDialog, isSigningOut, showAddTagSheet, copiedPublicKey, needsUpdate -> - ProfileControls(showSignOutDialog, isSigningOut, showAddTagSheet, copiedPublicKey, needsUpdate) + ProfileControls( + showSignOutDialog = showSignOutDialog, + isSigningOut = isSigningOut, + showAddTagSheet = showAddTagSheet, + copiedPublicKey = copiedPublicKey, + needsUpdate = needsUpdate, + ) + } + + private val controls = combine( + dialogControls, + pubkyRepo.profileRecoveryPending, + _localDisconnect, + pubkyRepo.profileRecoveryCanDisconnect, + removalCoordinator.retryOwner, + ) { controls, pending, localOnly, canDisconnect, retryOwner -> + controls.copy( + recoveryPending = pending, + localDisconnect = localOnly, + recoveryCanDisconnect = canDisconnect, + recoveryCanRetry = removalCoordinator.canRetry(retryOwner), + ) } init { @@ -93,7 +120,11 @@ class ProfileViewModel @Inject constructor( publicKey = pubkyRepo.publicKey.value, isLoading = pubkyRepo.isLoadingProfile.value || pubkyRepo.isRestoringSession.value || _isRefreshing.value, cachedProfile = pubkyRepo.cachedProfile.value, - controls = ProfileControls(needsUpdate = pubkyRepo.restorationNeedsUpdate.value), + controls = ProfileControls( + recoveryPending = pubkyRepo.profileRecoveryPending.value, + recoveryCanDisconnect = pubkyRepo.profileRecoveryCanDisconnect.value, + needsUpdate = pubkyRepo.restorationNeedsUpdate.value, + ), ), ) @@ -123,19 +154,54 @@ class ProfileViewModel @Inject constructor( profileLoadJob = viewModelScope.launch { _isRefreshing.update { true } try { - load() + if (pubkyRepo.profileRecoveryPending.first { it != null } == false) load() } finally { _isRefreshing.update { false } } } } - fun showSignOutConfirmation() { - _showSignOutDialog.update { true } + fun showSignOutConfirmation(remoteRetry: Boolean = false) { + 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 { + state.owner + } ?: return + val revision = ++preparationRevision + _isSigningOut.value = true + viewModelScope.launch { + try { + val failure = removalFailure + val result = if (remoteRetry) { + removalCoordinator.prepareRemoteRetry(owner) + } else if (failure != null) { + removalCoordinator.prepareLocalDisconnect(failure) + } else { + removalCoordinator.prepareSignOut(owner) + } + result.onSuccess { confirmation -> + if (revision != preparationRevision || !removalCoordinator.isCurrent(confirmation.owner)) { + removalCoordinator.discard(confirmation) + return@onSuccess + } + removalConfirmation = confirmation + _localDisconnect.value = confirmation.localOnly + _showSignOutDialog.value = true + }.onFailure { showRemovalError(it) } + } finally { + _isSigningOut.value = false + } + } } fun dismissSignOutDialog() { - _showSignOutDialog.update { false } + preparationRevision++ + removalCoordinator.discard(removalConfirmation) + removalConfirmation = null + _showSignOutDialog.value = false } fun showAddTagSheet() { @@ -158,35 +224,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)) @@ -209,18 +277,35 @@ 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, - needsUpdate = controls.needsUpdate, - ) + ): 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, + recoveryCanDisconnect = controls.recoveryCanDisconnect, + recoveryCanRetry = controls.recoveryCanRetry && removalCoordinator.canRetry(displayedOwner), + localDisconnect = controls.localDisconnect, + owner = displayedOwner, + showSignOutDialog = controls.showSignOutDialog, + isSigningOut = controls.isSigningOut, + showAddTagSheet = controls.showAddTagSheet, + copiedPublicKey = controls.copiedPublicKey, + needsUpdate = controls.needsUpdate, + ) + } private fun updateTags( transform: (List) -> List, @@ -228,6 +313,7 @@ class ProfileViewModel @Inject constructor( ) { viewModelScope.launch { tagUpdateMutex.withLock { + if (pubkyRepo.profileRecoveryPending.value != false) return@withLock val editBase = pubkyRepo.profileEditBase() val profile = editBase.profile ?: return@withLock val tags = transform(profile.tags) @@ -256,6 +342,10 @@ class ProfileViewModel @Inject constructor( } } } + + override fun onCleared() { + removalCoordinator.discard(removalConfirmation) + } } @Stable @@ -264,6 +354,11 @@ data class ProfileUiState( val cachedProfile: PubkyCachedProfile? = null, val publicKey: String? = null, val canEdit: Boolean = false, + val recoveryPending: Boolean = false, + val recoveryCanDisconnect: Boolean = false, + val recoveryCanRetry: Boolean = false, + val localDisconnect: Boolean = false, + val owner: PubkyProfileOwner? = null, val isLoading: Boolean = true, val showSignOutDialog: Boolean = false, val isSigningOut: Boolean = false, @@ -273,6 +368,10 @@ data class ProfileUiState( ) private data class ProfileControls( + val recoveryPending: Boolean? = null, + val recoveryCanDisconnect: Boolean = false, + val recoveryCanRetry: Boolean = false, + val localDisconnect: Boolean = false, val showSignOutDialog: Boolean = false, val isSigningOut: Boolean = false, val showAddTagSheet: Boolean = false, @@ -281,5 +380,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/ui/screens/recovery/WalletResetRecoveryScreen.kt b/app/src/main/java/to/bitkit/ui/screens/recovery/WalletResetRecoveryScreen.kt new file mode 100644 index 0000000000..241fd37264 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/screens/recovery/WalletResetRecoveryScreen.kt @@ -0,0 +1,283 @@ +package to.bitkit.ui.screens.recovery + +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.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +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 androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.HasDefaultViewModelProviderFactory +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.ViewModelStore +import androidx.lifecycle.ViewModelStoreOwner +import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.compose.currentStateAsState +import androidx.lifecycle.viewmodel.CreationExtras +import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner +import to.bitkit.R +import to.bitkit.data.WalletResetRecovery +import to.bitkit.ui.components.AuthCheckView +import to.bitkit.ui.components.BodyM +import to.bitkit.ui.components.PrimaryButton +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.shared.util.screen +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.viewmodels.AppViewModel +import to.bitkit.viewmodels.SettingsViewModel +import to.bitkit.viewmodels.WalletViewModel + +@Composable +fun WalletResetRecoveryScreen( + walletViewModel: WalletViewModel, + appViewModel: AppViewModel, + settingsViewModel: SettingsViewModel, + modifier: Modifier = Modifier, +) { + val walletState by walletViewModel.walletState.collectAsStateWithLifecycle() + val finishing by walletViewModel.isFinishingWalletReset.collectAsStateWithLifecycle() + val wiping by walletViewModel.isWiping.collectAsStateWithLifecycle() + var readRevision by remember { mutableIntStateOf(0) } + val recoveryPinRequired = remember(appViewModel, walletState.walletResetRecovery, readRevision) { + appViewModel.recoveryPinRequired + } + val pinEnabled by recoveryPinRequired.collectAsStateWithLifecycle(initialValue = null) + LaunchedEffect(appViewModel) { appViewModel.setShowForgotPin(false) } + WalletResetRecoveryFlow( + recovery = walletState.walletResetRecovery, + busy = finishing || wiping, + pinEnabled = pinEnabled, + isCurrent = { expected -> + walletViewModel.walletState.value.walletResetRecovery == expected && + !walletViewModel.isWiping.value && !walletViewModel.isFinishingWalletReset.value + }, + onRetry = { + readRevision++ + walletViewModel.refreshWalletResetRecovery() + }, + onFinish = { walletViewModel.finishPendingWalletReset(it) }, + authentication = { onSuccess, onBack -> + AuthCheckView( + appViewModel = appViewModel, + settingsViewModel = settingsViewModel, + onSuccess = onSuccess, + onBack = onBack, + onValidatePin = appViewModel::validateRecoveryPin, + onClickForgotPin = onBack, + ) + }, + phrase = { onBack -> ScopedRecoveryMnemonic(onBack) }, + modifier = modifier, + ) +} + +/** This read-only route never admits wallet operations or restores a saved authentication grant. */ +@Composable +internal fun WalletResetRecoveryFlow( + recovery: WalletResetRecovery, + busy: Boolean, + pinEnabled: Boolean?, + isCurrent: (WalletResetRecovery) -> Boolean, + onRetry: () -> Unit, + onFinish: (String) -> Unit, + authentication: @Composable (() -> Unit, () -> Unit) -> Unit, + phrase: @Composable (() -> Unit) -> Unit, + modifier: Modifier = Modifier, +) { + val currentAdmission by rememberUpdatedState(isCurrent) + key(recovery, busy, pinEnabled) { + val session = remember { RecoveryPhraseSession() } + val lifecycle = LocalLifecycleOwner.current.lifecycle + val lifecycleState by lifecycle.currentStateAsState() + DisposableEffect(session, lifecycle) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_STOP) session.revoke() + } + lifecycle.addObserver(observer) + onDispose { + session.close() + lifecycle.removeObserver(observer) + } + } + val available = !busy && pinEnabled != null && recovery != WalletResetRecovery.Loading && + recovery != WalletResetRecovery.Clear && lifecycleState.isAtLeast(Lifecycle.State.STARTED) && + currentAdmission(recovery) + SideEffect { if (!available) session.revoke() } + val mayContinue = { + available && currentAdmission(recovery) && lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED) + } + val phase = session.phase + when { + available && phase is RecoveryPhrasePhase.Authenticate -> { + BackHandler { session.revoke() } + authentication({ session.authorize(phase, mayContinue()) }, session::revoke) + } + available && phase == RecoveryPhrasePhase.Phrase -> { + BackHandler { session.revoke() } + phrase(session::revoke) + } + else -> WalletResetRecoveryContent( + recovery = recovery, + busy = busy, + onRetry = onRetry, + onFinish = onFinish, + onShowPhrase = { if (mayContinue()) session.begin(requireNotNull(pinEnabled)) }, + canShowPhrase = available, + modifier = modifier, + ) + } + } +} + +internal sealed interface RecoveryPhrasePhase { + data object Overview : RecoveryPhrasePhase + class Authenticate : RecoveryPhrasePhase + data object Phrase : RecoveryPhrasePhase +} + +internal class RecoveryPhraseSession { + var phase: RecoveryPhrasePhase by mutableStateOf(RecoveryPhrasePhase.Overview) + private set + private var active = true + + fun begin(pinEnabled: Boolean) { + if (active) phase = if (pinEnabled) RecoveryPhrasePhase.Authenticate() else RecoveryPhrasePhase.Phrase + } + + fun authorize(attempt: RecoveryPhrasePhase.Authenticate, admitted: Boolean) { + if (active && phase === attempt && admitted) phase = RecoveryPhrasePhase.Phrase + } + + fun revoke() { phase = RecoveryPhrasePhase.Overview } + + fun close() { + active = false + revoke() + } +} + +@Composable +private fun ScopedRecoveryMnemonic(onBack: () -> Unit) { + val parent = checkNotNull(LocalViewModelStoreOwner.current as? HasDefaultViewModelProviderFactory) + val owner = remember(parent) { RecoveryPhraseViewModelOwner(parent) } + DisposableEffect(owner) { onDispose { owner.viewModelStore.clear() } } + RecoveryMnemonicScreen(onBack, recoveryMnemonicViewModel = hiltViewModel(viewModelStoreOwner = owner)) +} + +private class RecoveryPhraseViewModelOwner( + private val parent: HasDefaultViewModelProviderFactory, +) : ViewModelStoreOwner, HasDefaultViewModelProviderFactory { + override val viewModelStore = ViewModelStore() + override val defaultViewModelProviderFactory: ViewModelProvider.Factory + get() = parent.defaultViewModelProviderFactory + override val defaultViewModelCreationExtras: CreationExtras get() = parent.defaultViewModelCreationExtras +} + +@Composable +internal fun WalletResetRecoveryContent( + recovery: WalletResetRecovery, + busy: Boolean, + onRetry: () -> Unit, + onFinish: (String) -> Unit, + modifier: Modifier = Modifier, + onShowPhrase: () -> Unit = {}, + canShowPhrase: Boolean = false, +) { + var showConfirmation by remember(recovery, busy) { mutableStateOf(false) } + val attemptId = when (recovery) { + is WalletResetRecovery.Pending -> recovery.attemptId + is WalletResetRecovery.Unreadable -> recovery.attemptId + else -> null + } + BackHandler {} + Column(modifier = modifier.screen().padding(horizontal = 16.dp).testTag("WalletResetRecovery")) { + AppTopBar(titleText = stringResource(R.string.security__recovery), onBackClick = null) + VerticalSpacer(16.dp) + if (!busy && recovery is WalletResetRecovery.Pending) { + BodyM(text = stringResource(R.string.security__reset_pending_text)) + } else if (!busy && + (recovery == WalletResetRecovery.Unavailable || recovery is WalletResetRecovery.Unreadable) + ) { + BodyM(text = stringResource(R.string.security__reset_read_error)) + } + VerticalSpacer(32.dp) + when { + busy || recovery == WalletResetRecovery.Loading -> PrimaryButton( + text = null, + isLoading = true, + enabled = false, + onClick = {}, + modifier = Modifier.testTag("WalletResetProgress"), + ) + recovery == WalletResetRecovery.Unavailable -> PrimaryButton( + text = stringResource(R.string.common__retry), + onClick = onRetry, + modifier = Modifier.testTag("WalletResetReadRetry") + ) + attemptId != null -> PrimaryButton( + text = stringResource(R.string.security__reset_button_reset), + isLoading = busy, + enabled = !busy, + onClick = { showConfirmation = true }, + modifier = Modifier.testTag("WalletResetFinish") + ) + } + if (!busy && attemptId != null && (!canShowPhrase || recovery is WalletResetRecovery.Unreadable)) { + VerticalSpacer(16.dp) + SecondaryButton( + text = stringResource(R.string.common__retry), + onClick = onRetry, + testTag = "WalletResetReadRetry", + ) + } + if (recovery != WalletResetRecovery.Loading && recovery != WalletResetRecovery.Clear) { + VerticalSpacer(16.dp) + SecondaryButton( + text = stringResource(R.string.security__display_seed), + enabled = canShowPhrase && !busy, + onClick = onShowPhrase, + testTag = "WalletResetShowPhrase", + ) + } + } + if (showConfirmation && attemptId != null && !busy) { + AppAlertDialog( + onDismissRequest = { showConfirmation = false }, + title = stringResource(R.string.security__reset_dialog_title), + text = stringResource(R.string.security__reset_dialog_desc), + confirmText = stringResource(R.string.security__reset_confirm), + onConfirm = { + showConfirmation = false + onFinish(attemptId) + }, + onDismiss = { showConfirmation = false }, + ) + } +} + +@Preview(showSystemUi = true) +@Composable +private fun Preview() { + AppThemeSurface { + WalletResetRecoveryContent(WalletResetRecovery.Pending("preview"), false, {}, {}) + } +} 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 4d2b495d8e..1be9ab4b06 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 @@ -183,6 +190,8 @@ fun SendSheet( onConfirmLockChange: (Boolean) -> Unit = {}, ) { 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() @@ -202,6 +211,7 @@ fun SendSheet( hasAnyChannels = hasAnyChannels, hasUsableChannels = lightningState.channels.any { it.isUsable }, sparkCanPay = sparkCanPay, + destination = entry?.destination, ) } @@ -239,8 +249,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 b3e4e3586e..c5eaea40fc 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 @@ -21,6 +22,7 @@ import to.bitkit.models.toBalance import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.SparkExitRepo +import to.bitkit.repositories.SparkExitState import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.TransferRepo import to.bitkit.utils.Logger @@ -39,7 +41,7 @@ class DeriveBalanceStateUseCase @Inject constructor( private val sparkExitRepo: SparkExitRepo, ) { suspend operator fun invoke(): Result = withContext(bgDispatcher) { - runCatching { + runSuspendCatching { val balanceDetails = lightningRepo.getBalancesAsync().getOrThrow() val channels = lightningRepo.getChannels().orEmpty() val activeTransfers = transferRepo.activeTransfers.first() @@ -54,11 +56,14 @@ class DeriveBalanceStateUseCase @Inject constructor( val channelFundableBalance = getMaxChannelFundableAmount(lightningRepo.getChannelFundableBalance()) val afterPendingChannels = balanceDetails.totalLightningBalanceSats.safe() - pendingChannelsSats.safe() val afterClosingChannels = afterPendingChannels.safe() - toSavingsAmount.safe() - // During an exit, Spark's value outside it stays on Spark. - val sparkSats = sparkRepo.state.value.shownSpendingSats.safe() + - (sparkExitRepo.state.value.outsideExitSats ?: 0uL).safe() - val sparkExitSats = getSparkExitSats(activeTransfers) val afterLingeringCoopClose = afterClosingChannels.safe() - lingeringCoopCloseSats.safe() + val maxSendOnchainSats = getMaxSendAmount(balanceDetails) + val spark = sparkRepo.state.value + val exit = sparkExitRepo.state.value + val sparkSats = spark.shownSpendingSats.safe() + (exit.outsideExitSats ?: 0uL).safe() + val sparkExitSats = getSparkExitSats(activeTransfers, exit) + val hasExit = spark.isExiting || exit.isExiting || + activeTransfers.any { it.type == TransferType.SPARK_EXIT } val totalLightningSats = afterLingeringCoopClose.safe() + sparkSats.safe() val balanceState = BalanceState( @@ -68,14 +73,16 @@ 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()).safe() + sparkExitSats.safe(), balanceInTransferToSpending = pendingChannelsSats.safe() + - sparkRepo.state.value.pendingDepositSats.safe(), + spark.pendingDepositSats.safe(), hardwareWallets = hwWalletRepo.wallets.value.map { it.toBalance() }, + sparkBalanceSats = sparkSats.takeUnless { hasExit }, + sparkPendingDepositSats = spark.pendingDepositSats.takeUnless { hasExit }, ) val height = lightningRepo.lightningState.value.block()?.height @@ -83,7 +90,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 } } @@ -128,8 +135,7 @@ class DeriveBalanceStateUseCase @Inject constructor( * A Spark emergency exit has no channel: what it still brings to savings is in transfer until the exit settles * it. The running exit's own transfer counts only that, not funding nobody paid or value savings already has. */ - private fun getSparkExitSats(transfers: List): ULong { - val exit = sparkExitRepo.state.value + private fun getSparkExitSats(transfers: List, exit: SparkExitState): ULong { return transfers .filter { it.type == TransferType.SPARK_EXIT } .fold(0uL) { sum, transfer -> 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..3ddc33cbbd --- /dev/null +++ b/app/src/main/java/to/bitkit/usecases/ProfileRemovalCoordinator.kt @@ -0,0 +1,437 @@ +package to.bitkit.usecases + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +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.services.PaykitProfileLogout +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 privateWithdrawalAcknowledged: Boolean = false, + internal val intent: ProfileRemovalIntent? = null, +) { + internal val used = AtomicBoolean(false) + internal val failure = AtomicReference(null) + + init { + intent?.let { + synchronized(it) { + check(!it.executing.get()) { "Profile removal is still in progress" } + it.confirmation.set(this) + } + } + } +} + +internal class ProfileRemovalIntent( + val owner: PubkyProfileOwner, + val attemptId: String, + val logout: PaykitProfileLogout, + val deletingProfile: Boolean, +) { + val confirmation = AtomicReference(null) + val started = AtomicBoolean(false) + val privateWithdrawal = AtomicBoolean(false) + val publicEndpoints = AtomicBoolean(false) + val privateSharingDisabled = AtomicBoolean(false) + val profileDeleted = AtomicBoolean(false) + 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( + cause: Throwable, + 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() { + 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) : + AppError("Remote profile removal is unavailable. Disconnect locally to remove access from this device.", cause) + +/** 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, +) { + private val retainedIntent = AtomicReference(null) + private val _retryOwner = MutableStateFlow(null) + val retryOwner = _retryOwner.asStateFlow() + + 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" } + val intent = captureIntent(owner, deletingProfile = true) + ProfileRemovalConfirmation(owner, intent.attemptId, deletion, localOnly = false, intent = intent) + } + + 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" } + if (pending != null || owner.signIn == null) { + val intent = retainedIntent.get()?.takeIf { it.attemptId == pending && isCurrent(it.owner) } + ProfileRemovalConfirmation( + owner, + pending ?: UUID.randomUUID().toString(), + deletion = null, + localOnly = true, + intent = intent, + ) + } else { + val intent = runSuspendCatching { captureIntent(owner) }.getOrElse { + if (it !is ProfileRemovalLocalOnly) throw it + null + } + ProfileRemovalConfirmation( + owner, + intent?.attemptId ?: UUID.randomUUID().toString(), + deletion = null, + localOnly = intent == null, + intent = intent, + ) + } + } + + private suspend fun captureIntent( + owner: PubkyProfileOwner, + deletingProfile: Boolean = false, + ): ProfileRemovalIntent { + retainedIntent.get()?.takeUnless { it.logout.isCurrent() }?.let { + retainedIntent.compareAndSet(it, null) + } + val logout = pubkyRepo.captureProfileLogout(owner).getOrElse { throw ProfileRemovalLocalOnly(it) } + return try { + check(isCurrent(owner)) { "The profile identity changed" } + removalStore.requireNoPending() + ProfileRemovalIntent(owner, UUID.randomUUID().toString(), logout, deletingProfile).also { + check(retainedIntent.compareAndSet(null, it)) { "A profile removal confirmation is already active" } + } + } catch (error: Throwable) { + logout.revoke() + throw error + } + } + + fun canRetry(owner: PubkyProfileOwner?): Boolean { + val intent = retainedIntent.get() ?: return false + return owner != null && isCurrent(owner) && isCurrent(intent.owner) && intent.canRetryRemoteWork && + intent.retryReady.get() && !intent.executing.get() && + intent.logout.isCurrent() && !intent.logout.reconcileAcknowledgement() + } + + /** A new confirmation may retry the same live grant; restart state alone cannot reach this path. */ + suspend fun prepareRemoteRetry(owner: PubkyProfileOwner): Result = runSuspendCatching { + check(canRetry(owner)) { "The original remote logout is no longer available" } + val intent = checkNotNull(retainedIntent.get()) + check(removalStore.pendingAttempt() == intent.attemptId) { "The pending profile cleanup changed" } + synchronized(intent) { + check(canRetry(owner)) { "The profile identity changed" } + ProfileRemovalConfirmation( + intent.owner, + intent.attemptId, + deletion = null, + localOnly = false, + intent = intent + ) + } + } + + fun discard(confirmation: ProfileRemovalConfirmation?) { + if (confirmation == null || confirmation.used.get()) return + val intent = confirmation.intent ?: return + if (intent.confirmation.get() !== confirmation || intent.started.get()) return + if (confirmation.failure.get() != null || confirmation.privateWithdrawalAcknowledged) return + if (retainedIntent.compareAndSet(intent, null)) { + intent.logout.revoke() + _retryOwner.update { null } + } + } + + /** Re-read the original identity's remote state, then require a new user confirmation. */ + suspend fun reviewAgain(failure: ProfileRemovalFailure): Result = runSuspendCatching { + check(failure.canReview) { "Finish disconnecting this profile locally" } + val previous = failure.confirmation + val intent = checkNotNull(previous.intent) { "The original removal session is no longer available" } + intent.logout.requireCurrent() + if (intent.logoutStarted.get()) { + check(canRetry(previous.owner) && removalStore.pendingAttempt() == intent.attemptId) { + "The original remote logout is no longer available" + } + return@runSuspendCatching ProfileRemovalConfirmation( + previous.owner, + previous.attemptId, + previous.deletion, + localOnly = false, + reviewCeiling = previous.reviewCeiling, + privateWithdrawalAcknowledged = true, + intent = intent, + ) + } + check(previous.deletion != null) { "Disconnect this profile locally to finish cleanup" } + var deletion: PubkyProfileDeletion? = null + pubkyRepo.performProfileRemoval(previous.owner, previous.attemptId) { + withContext(intent.logout) { + pubkyRepo.validateProfileLogout(intent.logout) + val fresh = pubkyRepo.prepareProfileDeletion(previous.owner).getOrThrow() + val prior = checkNotNull(previous.reviewCeiling.get()) + val confirmed = prior.snapshot + val remaining = fresh.snapshot + check(fresh.deletePubkyProfile == prior.deletePubkyProfile) { "Profile ownership changed" } + check( + fresh.pubkyProfileRevision == null || + ( + !prior.pubkyProfileAcknowledged.get() && + fresh.pubkyProfileRevision == prior.pubkyProfileRevision + ) + ) { "The profile changed after confirmation. Disconnect locally to finish cleanup." } + fresh.pubkyProfileAcknowledged.set(prior.pubkyProfileAcknowledged.get()) + 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, + privateWithdrawalAcknowledged = true, + intent = intent, + ) + } + + 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() + 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, + intent = failure.confirmation.intent, + ) + } + + suspend fun remove(confirmation: ProfileRemovalConfirmation): Result = runSuspendCatching { + check(confirmation.used.compareAndSet(false, true)) { "Review this profile removal before trying again" } + val intent = confirmation.intent + intent?.let { + synchronized(it) { + check(it.confirmation.get() === confirmation) { "This confirmation was replaced" } + check(it.executing.compareAndSet(false, true)) { "Profile removal is still in progress" } + it.retryReady.set(false) + } + } + _retryOwner.update { null } + try { + sharingRepo.withProfileRemoval { + pubkyRepo.performProfileRemoval(confirmation.owner, confirmation.attemptId) { + var localCompletionStarted = false + var privateWithdrawalAcknowledged = + intent?.privateWithdrawal?.get() == true || confirmation.privateWithdrawalAcknowledged + 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 -> + if (!confirmation.localOnly) { + withContext(checkNotNull(intent).logout) { + pubkyRepo.validateProfileLogout(intent.logout) + if (!intent.profileDeleted.get()) { + confirmation.deletion?.let { pubkyRepo.validateProfileDeletion(it) } + } + } + } else if (intent?.profileDeleted?.get() != true) { + confirmation.deletion?.let { pubkyRepo.validateProfileDeletion(it) } + } + removalMayHaveStarted = true + intent?.started?.set(true) + // 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) { + original.logout.requireCurrent() + if (!original.logoutStarted.get()) { + if (!privateWithdrawalAcknowledged) { + privatePaykitRepo.removePublishedEndpointsForProfileRemoval { + original.privateWithdrawal.set(true) + privateWithdrawalAcknowledged = true + }.getOrThrow() + } + pubkyRepo.removeBitkitPaymentEndpointsForRemoval( + original.publicEndpoints.get(), + original.privateSharingDisabled.get(), + { original.publicEndpoints.set(true) }, + { original.privateSharingDisabled.set(true) }, + ).getOrThrow() + if (!original.profileDeleted.get()) { + confirmation.deletion?.let { + pubkyRepo.deleteProfile( + it + ) { original.profileDeleted.set(true) }.getOrThrow() + } + } + check( + original.privateWithdrawal.get() && original.publicEndpoints.get() && + original.privateSharingDisabled.get() + ) { "Profile cleanup is not acknowledged" } + original.logoutStarted.set(true) + } + pubkyRepo.executeProfileLogout(original.logout) + } + } else { + intent?.logout?.revoke() + } + localCompletionStarted = true + removalStore.beginLocalCleanup() + if (intent == null) { + pubkyRepo.finishProfileRemovalLocally() + } else { + pubkyRepo.finishProfileRemovalLocally(intent.logout, confirmation.localOnly) + } + withContext(NonCancellable) { + privatePaykitRepo.finishProfileRemoval(pause).getOrThrow() + removalStore.complete(confirmation.attemptId) + privatePaykitRepo.notifyProfileRemovalCompleted(pause) + pubkyRepo.notifyProfileRemovalCompleted() + retainedIntent.compareAndSet(intent, null) + } + } + } catch (error: CancellationException) { + if (removalMayHaveStarted) { + captureFailure( + error, + confirmation, + localCompletionStarted, + privateWithdrawalAcknowledged + ) + } + throw error + } catch (error: Throwable) { + if (!removalMayHaveStarted) throw error + throw captureFailure(error, confirmation, localCompletionStarted, privateWithdrawalAcknowledged) + } + }.getOrThrow() + } + } finally { + intent?.let { + // Publish retry eligibility only after native work and every outer cleanup barrier have drained. + synchronized(it) { + it.executing.set(false) + if (!it.started.get() && retainedIntent.compareAndSet(it, null)) it.logout.revoke() + it.retryReady.set( + confirmation.failure.get() != null && it.canRetryRemoteWork && + it.logout.isCurrent() && !it.logout.reconcileAcknowledgement() + ) + } + if (canRetry(confirmation.owner)) _retryOwner.update { confirmation.owner } + } + } + }.onFailure { + val intent = confirmation.intent + if (intent != null && !intent.started.get() && intent.confirmation.get() === confirmation && + retainedIntent.compareAndSet(intent, null) + ) { + intent.logout.revoke() + _retryOwner.update { null } + } + } + + private fun captureFailure( + 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, + privateWithdrawalAcknowledged, + ) + confirmation.failure.set(failure) + return failure + } + + fun failureFor(confirmation: ProfileRemovalConfirmation): ProfileRemovalFailure? = confirmation.failure.get() + + fun isCurrent(owner: PubkyProfileOwner): Boolean = pubkyRepo.isProfileOwnerCurrent(owner) +} diff --git a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt index e238d7eee7..de27185620 100644 --- a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt @@ -4,6 +4,8 @@ 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.ProfileRemovalScope +import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.SettingsStore import to.bitkit.data.WalletConnectionRecovery import to.bitkit.data.WidgetsStore @@ -12,6 +14,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.PaykitReceiptRepo @@ -28,6 +31,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 @@ -55,6 +59,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 paykitReceiptRepo: PaykitReceiptRepo, private val connectionRecovery: WalletConnectionRecovery, private val wakeRepo: WakeRepo, @@ -65,69 +71,98 @@ class WipeWalletUseCase @Inject constructor( walletIndex: Int = 0, resetWalletState: () -> Unit, onSuccess: () -> Unit, + expectedPendingAttemptId: String? = null, ): Result { if (!wipeMutex.tryLock()) return Result.failure(WipeAlreadyInProgress()) - backupRepo.setWiping(true) - lightningRepo.setWiping(true) + var wipeAdmitted = false + var credentialsMayBeErased = false val result = try { runSuspendCatching { - connectionRecovery.withIdentityChange { - paykitSdkService.withWalletWipe { - stopNode().getOrThrow() - cleanupRemote() - wipeLocal(walletIndex, resetWalletState).getOrThrow() - onSuccess() + 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) } + true + }, + beforeClientsSuspend = { backupRepo.reset() }, + ) { + paykitSdkService.withWalletWipe { + expectedPendingAttemptId?.let { profileRemovalStore.requirePendingWalletReset(it) } + val pending = profileRemovalStore.pendingState() + val attemptId = pending.attemptId ?: UUID.randomUUID().toString() + profileRemovalStore.withAccess(attemptId, ProfileRemovalScope.WALLET_WIPE) { + privatePaykitRepo.get().withProfileDeletionPaused { pause -> + lightningRepo.stop().getOrThrow() + profileRemovalStore.begin(attemptId) + if (pending.scope != ProfileRemovalScope.WALLET_WIPE) cleanupRemote() + wipeLocal(walletIndex, pause) { credentialsMayBeErased = true }.getOrThrow() + profileRemovalStore.complete(attemptId) + resetWalletState() + onSuccess() + } + } + } } } + }.let { outcome -> + val error = outcome.exceptionOrNull() + if (error != null && credentialsMayBeErased) Result.failure(WipeIncomplete(error)) else outcome } } finally { - lightningRepo.setWiping(false) - backupRepo.setWiping(false) + if (wipeAdmitted) { + 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() - } } } - 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() } - step("close Paykit SDK") { privatePaykitRepo.get().closeAndClear() } step("unregister wake device") { wakeRepo.unregister() } } - private suspend fun wipeLocal(walletIndex: Int, resetWalletState: () -> Unit): Result { + private suspend fun wipeLocal( + walletIndex: Int, + pause: PrivatePaykitRepo.ProfileDeletionPause, + onCredentialWipe: () -> Unit, + ): Result { lightningRepo.wipeStorage(walletIndex).onFailure { return Result.failure(it) } pubkySwapsRouteRepo.resetForWipe() - 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() + migrationService.setNeedsPostMigrationSync(false) + migrationService.cleanupAfterMigration() + onCredentialWipe() + usdtRepo.wipe { keychain.wipe() }.getOrThrow() + paykitUsdtPaymentRepo.resetForWipe() step("reset Paykit receipts") { paykitReceiptRepo.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() step("delete FCM token") { firebaseMessaging.deleteToken() } - step("wipe core data") { coreService.wipeData() } - step("clear database") { db.clearAllTables() } - step("reset settings") { settingsStore.reset() } - step("reset cache") { cacheStore.reset() } - step("clear watch-only accounts") { watchOnlyAccountRepo.clear() } - step("reset widgets") { widgetsStore.reset() } + coreService.wipeData().getOrThrow() + db.clearAllTables() + settingsStore.reset() + cacheStore.reset() + watchOnlyAccountRepo.clear() + 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()) + migrationService.markMigrationChecked() + return Result.success(Unit) } private suspend fun step(name: String, block: suspend () -> Any?): Boolean = @@ -143,4 +178,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 bb6370fd50..38629832f7 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -71,6 +71,7 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.debounce @@ -79,6 +80,7 @@ import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.stateIn @@ -754,6 +756,7 @@ class AppViewModel @Inject constructor( /** [lockGeneration] when the scan now holding [scanMutex] started, or null outside a scan. */ private var scanLockGeneration: Long? = 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) @@ -1142,10 +1145,12 @@ class AppViewModel @Inject constructor( val restoredSignIn = signIn ?: pubkyRepo.currentSignIn() val admission = canPublish ?: publicPaykitPublicationAdmission(restoredSignIn) - publicPaykitRepo.syncCurrentPublishedEndpoints( - canPublish = admission, - ) - .onFailure { Logger.warn("Failed to refresh public Paykit endpoints", it, context = TAG) } + contactPaymentSettingsRepo.reconcilePendingEndpoints(waitForTurn = true) { + publicPaykitRepo.syncCurrentPublishedEndpoints( + canPublish = admission, + ) + .onFailure { Logger.warn("Failed to refresh public Paykit endpoints", it, context = TAG) } + } } private fun publicPaykitPublicationAdmission(signIn: PubkySignIn? = pubkyRepo.currentSignIn()): () -> Boolean { @@ -1163,15 +1168,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() @@ -1183,7 +1193,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 } + } } } @@ -1250,6 +1264,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 @@ -2974,7 +2989,7 @@ class AppViewModel @Inject constructor( return } - lightningRepo.getPayments().onSuccess { activityRepo.syncLdkNodePayments(it) } + activityRepo.syncLdkNodePayments() migrationService.reapplyMetadataAfterSync() activityRepo.syncActivities() walletRepo.syncBalances() @@ -3035,9 +3050,7 @@ class AppViewModel @Inject constructor( isCompletingMigration = true runCatching { - lightningRepo.getPayments().onSuccess { payments -> - activityRepo.syncLdkNodePayments(payments) - }.onFailure { e -> + activityRepo.syncLdkNodePayments().onFailure { e -> Logger.warn("Failed to get payments during migration: $e", e, context = TAG) } activityRepo.markAllUnseenActivitiesAsSeen() @@ -3062,9 +3075,7 @@ class AppViewModel @Inject constructor( } private suspend fun finishMigrationSuccessfully() { - lightningRepo.getPayments().onSuccess { payments -> - activityRepo.syncLdkNodePayments(payments) - } + activityRepo.syncLdkNodePayments() transferRepo.syncTransferStates() migrationService.reapplyMetadataAfterSync() @@ -3083,9 +3094,7 @@ class AppViewModel @Inject constructor( private suspend fun finishMigrationWithFallbackSync() { walletRepo.syncBalances() - lightningRepo.getPayments().onSuccess { payments -> - activityRepo.syncLdkNodePayments(payments) - } + activityRepo.syncLdkNodePayments() transferRepo.syncTransferStates() migrationService.reapplyMetadataAfterSync() @@ -3300,6 +3309,9 @@ class AppViewModel @Inject constructor( paymentHash, canPublish = publicPaykitPublicationAdmission(), isStillCurrent = isSessionCurrent, + admitPublication = { publication -> + contactPaymentSettingsRepo.reconcilePendingEndpoints(waitForTurn = true, reconcile = publication) + }, ).onFailure { Logger.warn("Failed to refresh public Paykit invoice for '$paymentHash'", it, context = TAG) } @@ -4139,7 +4151,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) { @@ -4168,19 +4180,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 @@ -9599,6 +9620,11 @@ class AppViewModel @Inject constructor( if (!canPresent()) return@launch // 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 @@ -9760,6 +9786,37 @@ class AppViewModel @Inject constructor( Logger.debug("Locked app on background", context = TAG) } + /** Cold recovery reads must not treat the ordinary UI's initial false as a loaded PIN policy. */ + val recoveryPinRequired + get() = flow { + emit(null) + settingsStore.data.collect { settings -> + emit(settings.isPinEnabled || keychain.loadString(Keychain.Key.PIN.name) != null) + } + }.catch { emit(null) } + + /** Recovery authentication cannot erase a wallet whose cleanup state is unknown. */ + @Synchronized + fun validateRecoveryPin(pin: String): Boolean = runCatching { + keychain.accessBlocking { + val stored = load(Keychain.Key.PIN.name)?.decodeToString() ?: return@accessBlocking false + val encodedAttempts = load(Keychain.Key.PIN_ATTEMPTS_REMAINING.name)?.decodeToString() + val remaining = if (encodedAttempts == null) { + Env.PIN_ATTEMPTS + } else { + encodedAttempts.toIntOrNull() ?: return@accessBlocking false + } + if (remaining !in 1..Env.PIN_ATTEMPTS) return@accessBlocking false + val valid = stored == pin + val next = if (valid) Env.PIN_ATTEMPTS else remaining - 1 + upsert(Keychain.Key.PIN_ATTEMPTS_REMAINING.name, next.toString().toByteArray()) + valid + } + }.getOrElse { + Logger.warn("Recovery authentication is unavailable", it, context = TAG) + false + } + fun validatePin(pin: String): Boolean { val storedPin = keychain.loadString(Keychain.Key.PIN.name) val isValid = storedPin == pin @@ -10831,6 +10888,7 @@ class AppViewModel @Inject constructor( } private suspend fun handlePubkyAuth(authUrl: String) { + if (pubkyRepo.requiresProfileRecovery()) return showPubkyIdentityUnavailableToast() val isSignup = PubkyAuthRequest.isSignupUrl(authUrl) val createsIdentity = isSignup && ( @@ -10839,12 +10897,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 } @@ -10871,10 +10931,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( @@ -11374,6 +11444,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/main/java/to/bitkit/viewmodels/BackupsViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/BackupsViewModel.kt index 672811b189..21b4362656 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 @@ -26,6 +27,7 @@ class BackupsViewModel @Inject constructor( private val cacheStore: CacheStore, private val backupRepo: BackupRepo, private val lightningRepo: LightningRepo, + private val vssClients: VssClientCoordinator, private val sparkRepo: SparkRepo, ) : ViewModel() { @@ -67,9 +69,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/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index 3a42deb6fd..5635e89ccc 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -25,6 +25,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 @@ -32,6 +33,7 @@ import to.bitkit.R import to.bitkit.data.ConnectionRecoveryOwnerChanged import to.bitkit.data.SettingsStore import to.bitkit.data.WalletConnectionRecovery +import to.bitkit.data.WalletResetRecovery import to.bitkit.di.BgDispatcher import to.bitkit.env.Env import to.bitkit.ext.nowTimestamp @@ -89,6 +91,8 @@ class WalletViewModel @Inject constructor( val lightningState = lightningRepo.lightningState val sparkState = sparkRepo.state val walletState = walletRepo.walletState + private val _isFinishingWalletReset = MutableStateFlow(false) + val isFinishingWalletReset = _isFinishingWalletReset.asStateFlow() val balanceState = walletRepo.balanceState @Volatile @@ -99,6 +103,12 @@ class WalletViewModel @Inject constructor( val isRecoveryMode = lightningRepo.isRecoveryMode + 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 val isWiping: StateFlow = backupRepo.isWiping @@ -335,7 +345,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()) { @@ -355,33 +367,49 @@ class WalletViewModel @Inject constructor( } private fun checkAndPerformRNMigration() = viewModelScope.launch(bgDispatcher) { - val isChecked = migrationService.isMigrationChecked() - if (isChecked) { - loadCacheIfWalletExists() - return@launch + 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()) { + 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() !migrationService.isMigrationChecked() && !migrationService.hasNativeWalletData() && migrationService.hasRNWalletData() }, ) { + walletRepo.checkWalletAvailable().getOrThrow() + migrationStarted = true migrationService.setShowingMigrationLoading(true) Logger.info("RN wallet data found, starting migration...", context = TAG) migrationService.migrateFromReactNative() @@ -389,28 +417,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) + throw it } - }.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() { @@ -422,6 +451,8 @@ class WalletViewModel @Inject constructor( private fun collectStates() = viewModelScope.launch { walletState.collect { walletExists = it.walletExists + if (it.walletResetRecovery != WalletResetRecovery.Clear) return@collect + if (_isCheckingRNMigration.value) checkAndPerformRNMigration() if (!it.walletExists) { appliedConnection = null _connectionStartupError.update { null } @@ -476,7 +507,7 @@ class WalletViewModel @Inject constructor( connectionSession = connectionSession, ) .getOrThrow() - .also { pubkyRepo.initialize() } + .also { pubkyRepo.scheduleInitializationAfterRestore() } } else { restoreFromMostRecentBackup(connectionSession) } @@ -520,7 +551,7 @@ class WalletViewModel @Inject constructor( .getOrThrow() } - pubkyRepo.initialize() + pubkyRepo.scheduleInitializationAfterRestore() return failedCategories } @@ -713,6 +744,7 @@ class WalletViewModel @Inject constructor( viewModelScope.launch(bgDispatcher) { isStarting = true try { + if (walletRepo.checkWalletAvailable().isFailure) return@launch if (!isNetworkConnected()) { Logger.warn("Network offline, skipping wallet start", context = TAG) pendingWalletStart = true @@ -971,7 +1003,26 @@ class WalletViewModel @Inject constructor( } } + fun refreshWalletResetRecovery() { + walletRepo.refreshWalletResetRecovery() + if (_isCheckingRNMigration.value) checkAndPerformRNMigration() + } + + fun finishPendingWalletReset(attemptId: String) = viewModelScope.launch { + if (isWiping.value || !_isFinishingWalletReset.compareAndSet(false, true)) return@launch + try { + walletRepo.wipeWallet(expectedPendingAttemptId = attemptId).onFailure { ToastEventBus.send(it) } + } finally { + _isFinishingWalletReset.update { false } + } + } + suspend fun createWallet(bip39Passphrase: String?) { + if (_isCheckingRNMigration.value) return + walletRepo.checkWalletAvailable().getOrElse { + ToastEventBus.send(it) + return + } setInitNodeLifecycleState() walletRepo.createWallet(bip39Passphrase) .onSuccess { @@ -987,6 +1038,11 @@ class WalletViewModel @Inject constructor( } suspend fun restoreWallet(mnemonic: String, bip39Passphrase: String?) { + if (_isCheckingRNMigration.value) return + walletRepo.checkWalletAvailable().getOrElse { + ToastEventBus.send(it) + return + } setInitNodeLifecycleState() _restoreState.update { RestoreState.InProgress.Wallet } // The node starts and syncs long before the backup is read, so ordinary uploads are held from diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index d4211b8b72..029a2f5a64 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -398,6 +398,7 @@ تفعيل\nLightning\n<accent>المدفوعات</accent> يرجى الانتظار أثناء ترحيل بيانات محفظتك القديمة إلى إصدار Bitkit الجديد. عادةً ما يستغرق هذا أقل من دقيقة. ترحيل المحفظة + حالة ترحيل المحفظة غير متاحة. أعد المحاولة قبل المتابعة. جارٍ ترحيل\n<accent>المحفظة</accent> قناة الإشعارات لخدمة عقدة Lightning في المقدمة إشعار عقدة Lightning @@ -562,11 +563,15 @@ إضافة علامة التفاصيل حسنًا + لم يكتمل تنظيف الملف الشخصي. افصل الاتصال محليًا لإزالة وصول هذا الجهاز دون إعادة محاولة الحذف عن بُعد. المُرحّل هذا الطلب موجّه إلى %1$s، وليس إلى pubky هذه المحفظة. إنشاء ملف شخصي + قد تكون بعض التغييرات قد اكتملت. راجع الحالة الحالية قبل التأكيد مجددًا، أو افصل الاتصال محليًا. + أزل وصول هذا الجهاز وأكمل التنظيف المحلي. لا يُجري هذا أي تغييرات إضافية على ملفك الشخصي أو اشتراكاتك أو صلاحيات وصولك على الخادم. الملف الشخصي حاول مرة أخرى + مراجعة اقتراحات يحتاج هذا الملف الشخصي إلى إصدار أحدث من Bitkit. حدّث التطبيق لاستخدامه. نسخ احتياطي @@ -653,6 +658,8 @@ هل أنت متأكد من رغبتك في إعادة تعيين محفظة Bitkit؟ هل لديك نسخة احتياطية من عبارة الاسترداد وبيانات المحفظة؟ إعادة تعيين Bitkit؟ نعم، أعد التعيين + لم تكتمل إعادة ضبط المحفظة السابقة. أكمل إعادة الضبط قبل إنشاء محفظة أو استعادتها. احتفظ بعبارة الاسترداد والنسخة الاحتياطية للمحفظة في مكان آمن. + تعذرت قراءة حالة استرداد المحفظة. أعد المحاولة قبل المتابعة. انسخ محفظتك احتياطيًا أولاً لتجنب فقدان أموالك وبيانات محفظتك. ستؤدي إعادة التعيين إلى الكتابة فوق إعداد Bitkit الحالي. إعادة التعيين والاستعادة لقد أعددت رمز PIN و {biometricsName} بنجاح لتحسين أمان المحفظة. @@ -1521,6 +1528,7 @@ جارٍ تحميل ملفك الشخصي… ادخل إلى\n<accent>ويب الحرية</accent> فشل إنشاء الملف الشخصي + تمنع الاشتراكات النشطة إزالة هذا الملف الشخصي. يؤدي حذف ملفك الشخصي إلى إزالته من Pubky. قد تحتفظ جهات الاتصال بمعلومات الملف الشخصي والدفع التي شاركتها معهم سابقًا. حذف الملف الشخصي؟ تعذر علينا حذف بيانات ملفك الشخصي. أعد المحاولة، أو افصل هذا الـ pubky عن Bitkit. @@ -1568,6 +1576,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 5886baec12..aac734a3d8 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -405,6 +405,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 @@ -574,11 +575,15 @@ Detalles Relay 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. Esta solicitud es para %1$s, no para el pubky de esta billetera. Crear perfil + Es posible que algunos cambios se hayan completado. Revisa el estado actual antes de confirmar de nuevo o desconéctate localmente. + 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 + Revisar Sugerencias Sugerencias para añadir Sí, desvincular @@ -674,6 +679,8 @@ Estás seguro de que quieres restablecer tu wallet de Bitkit? ¿Tienes una copia de tu frase de recuperación y los datos de tu billetera? ¿Resetear Bitkit? Sí, Restaurar + El restablecimiento anterior de la billetera no se completó. Complétalo antes de crear o restaurar una billetera. Guarda tu frase de recuperación y la copia de seguridad en un lugar seguro. + No se pudo leer el estado de recuperación de la billetera. Reinténtalo antes de continuar. Haz una copia de seguridad de tu wallet antes para evitar perder tus fondos y datos. Restablecer sobrescribirá tu configuración actual de Bitkit. Restablecer y resetear Ha configurado correctamente un código PIN y {biometricsName} para mejorar la seguridad de la billetera. @@ -1544,6 +1551,7 @@ Cargando su perfil… Entre a la\n<accent>web de la libertad</accent> No se pudo crear el 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. @@ -1582,6 +1590,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 2f02d5902d..abd439e7b9 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -402,6 +402,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 @@ -568,12 +569,16 @@ 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. Relé Aquesta sol·licitud és per a %1$s, no per al pubky d\'aquesta cartera. 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 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 + Revisa Suggeriments Sí, desvincula Això eliminarà les teves dades de Paykit i desvincularà aquest pubky de Bitkit. Continuarà disponible a Pubky Ring. @@ -668,6 +673,8 @@ Estàs segur que vols restablir la teva cartera Bitkit? Tens una còpia de seguretat de la teva frase de recuperació i les dades de la cartera? Reiniciar Bitkit? Sí, reinicia + El restabliment anterior de la cartera no es va completar. Completa el restabliment abans de crear o restaurar una cartera. Desa en un lloc segur la frase de recuperació i la còpia de seguretat. + No es pot llegir l’estat de recuperació de la cartera. Torna-ho a provar abans de continuar. Fes còpia de seguretat de la teva cartera primer per evitar la pèrdua dels teus fons i dades de la cartera. Restablir sobreescriurà la teva configuració actual de Bitkit. Restablir i restaurar Has configurat correctament un codi PIN i {biometricsName} per millorar la seguretat de la cartera. @@ -1540,6 +1547,7 @@ Carregant el teu perfil… Entra a la\n<accent>web de la llibertat</accent> No s\'ha pogut crear el 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. @@ -1579,6 +1587,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 b0d8bbd939..c91616024b 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -405,6 +405,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 @@ -574,11 +575,15 @@ Podrobnosti Relay 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í. Tento požadavek je určen pro %1$s, ne pro pubky této peněženky. 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 neprovedou žádné další změny vašeho profilu, předplatných ani přístupu na serveru. 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. @@ -673,6 +678,8 @@ Opravdu chcete resetovat svou peněženku Bitkit? Máte zálohu své fráze pro obnovení a dat peněženky? Resetovat Bitkit? Ano, resetovat + Předchozí reset peněženky nebyl dokončen. Před vytvořením nebo obnovením peněženky dokončete reset. Uchovejte obnovovací frázi a zálohu peněženky v bezpečí. + Stav obnovy peněženky nelze načíst. Před pokračováním to zkuste znovu. Nejprve si zálohujte peněženku, abyste se vyhnuli ztrátě finančních prostředků a dat peněženky. Resetováním se přepíše vaše aktuální nastavení Bitkitu. Resetovat a obnovit Úspěšně jste nastavili kód PIN a {biometricsName} abyste zvýšili bezpečnost peněženky. @@ -1543,6 +1550,7 @@ Načítání vašeho profilu… Vstupte do\n<accent>svobodného webu</accent> Profil se nepodařilo vytvořit + 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. @@ -1582,6 +1590,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 075d67f1ce..0d94a325bf 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -405,6 +405,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 @@ -555,11 +556,15 @@ Autorisieren Sie Relay 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. Diese Anfrage ist für %1$s bestimmt, nicht für den Pubky dieses Wallets. 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 werden keine weiteren Änderungen an deinem Profil, deinen Abonnements oder deinem Zugriff auf dem Server vorgenommen. 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. @@ -653,6 +658,8 @@ PIN-Code gesetzt. Möchtest du {biometricsName} anstelle deines PIN-Codes verwenden? Verwende {biometricsName} Telefoneinstellungen + Das vorherige Zurücksetzen der Wallet wurde nicht abgeschlossen. Schließe es ab, bevor du eine Wallet erstellst oder wiederherstellst. Bewahre deine Wiederherstellungsphrase und dein Wallet-Backup sicher auf. + Der Wiederherstellungsstatus der Wallet konnte nicht gelesen werden. Versuche es erneut, bevor du fortfährst. Wallet gesichert Du hast erfolgreich einen PIN-Code und {biometricsName} eingerichtet, um die Sicherheit deines Wallets zu verbessern. Du hast erfolgreich einen PIN-Code eingerichtet, um die Sicherheit deines Wallets zu verbessern. @@ -1539,6 +1546,7 @@ Dein Profil wird geladen… Betritt das\n<accent>freie Web</accent> Profil konnte nicht erstellt werden + 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. @@ -1578,6 +1586,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 4073ffa1a8..4ee2f1c5bd 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -398,6 +398,7 @@ Ενεργοποίηση\nLightning\n<accent>πληρωμών</accent> Περίμενε όσο τα παλιά δεδομένα του πορτοφολιού μεταφέρονται σε αυτή τη νέα έκδοση του Bitkit. Αυτό συνήθως διαρκεί λιγότερο από ένα λεπτό. Μετάβαση πορτοφολιού + Η κατάσταση μεταφοράς του πορτοφολιού δεν είναι διαθέσιμη. Δοκιμάστε ξανά πριν συνεχίσετε. ΜΕΤΑΒΑΣΗ\n<accent>ΠΟΡΤΟΦΟΛΙΟΥ</accent> Κανάλι ειδοποιήσεων για υπηρεσία προσκηνίου κόμβου Lightning Ειδοποίηση κόμβου Lightning @@ -562,11 +563,15 @@ Προσθήκη ετικέτας Λεπτομέρειες ΟΚ + Η εκκαθάριση του προφίλ δεν ολοκληρώθηκε. Αποσυνδεθείτε τοπικά για να καταργήσετε την πρόσβαση αυτής της συσκευής χωρίς νέα προσπάθεια απομακρυσμένης διαγραφής. Αναμεταδότης Αυτό το αίτημα προορίζεται για το %1$s, όχι για το pubky αυτού του πορτοφολιού. Δημιουργία προφίλ + Ορισμένες αλλαγές ενδέχεται να έχουν ολοκληρωθεί. Ελέγξτε την τρέχουσα κατάσταση πριν επιβεβαιώσετε ξανά ή αποσυνδεθείτε τοπικά. + Αφαιρέστε την πρόσβαση αυτής της συσκευής και ολοκληρώστε την τοπική εκκαθάριση. Αυτό δεν κάνει άλλες αλλαγές στο προφίλ, τις συνδρομές ή την πρόσβασή σας στον διακομιστή. Προφίλ Προσπαθήστε Ξανά + Έλεγχος Προτάσεις Αυτό το προφίλ χρειάζεται νεότερη έκδοση του Bitkit. Ενημέρωσε την εφαρμογή για να το χρησιμοποιήσεις. Αντίγραφο ασφαλείας @@ -653,6 +658,8 @@ Είσαι σίγουρος ότι θέλεις να επαναφέρεις το πορτοφόλι Bitkit; Έχεις αντίγραφο ασφαλείας της φράσης ανάκτησης και των δεδομένων του πορτοφολιού; Επαναφορά Bitkit; Ναι, Επαναφορά + Η προηγούμενη επαναφορά του πορτοφολιού δεν ολοκληρώθηκε. Ολοκλήρωσέ την πριν δημιουργήσεις ή ανακτήσεις πορτοφόλι. Φύλαξε με ασφάλεια τη φράση ανάκτησης και το αντίγραφο ασφαλείας. + Δεν ήταν δυνατή η ανάγνωση της κατάστασης ανάκτησης του πορτοφολιού. Δοκίμασε ξανά πριν συνεχίσεις. Δημιούργησε πρώτα αντίγραφο ασφαλείας του πορτοφολιού για να αποφύγεις την απώλεια κεφαλαίων και δεδομένων πορτοφολιού. Η επαναφορά θα αντικαταστήσει την τρέχουσα ρύθμιση του Bitkit. Επαναφορά και ανάκτηση Ρύθμισες επιτυχώς κωδικό PIN και {biometricsName} για να βελτιώσεις την ασφάλεια του πορτοφολιού. @@ -1523,6 +1530,7 @@ Φόρτωση του προφίλ σου… Μπες στον\n<accent>ελεύθερο ιστό</accent> Αποτυχία δημιουργίας προφίλ + Οι ενεργές συνδρομές εμποδίζουν την αφαίρεση αυτού του προφίλ. Η διαγραφή του προφίλ σου το αφαιρεί από το Pubky. Οι επαφές μπορεί να διατηρούν ακόμα πληροφορίες προφίλ και πληρωμών που τους κοινοποιήθηκαν παλαιότερα. Διαγραφή προφίλ; Δεν μπορέσαμε να διαγράψουμε τα δεδομένα του προφίλ σου. Δοκίμασε ξανά ή αποσύνδεσε αυτό το pubky από το Bitkit. @@ -1570,6 +1578,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 facf2ddcd8..d065cc6144 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -404,6 +404,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 @@ -570,12 +571,16 @@ 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. Relé Esta solicitud es para %1$s, no para el pubky de este monedero. Crear perfil + Es posible que algunos cambios se hayan completado. Revisa el estado actual antes de confirmar de nuevo o desconéctate localmente. + 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 + Revisar Sugerencias Sugerencias para añadir Sí, desvincular @@ -671,6 +676,8 @@ ¿Está seguro de que desea restablecer su monedero Bitkit? ¿Tiene una copia de seguridad de su frase de recuperación y de los datos de su monedero? ¿Restablecer Bitkit a los parámetros iniciales? Sí, restaurar + El restablecimiento anterior de la billetera no se completó. Complétalo antes de crear o restaurar una billetera. Guarda tu frase de recuperación y la copia de seguridad en un lugar seguro. + No se pudo leer el estado de recuperación de la billetera. Reinténtalo antes de continuar. Haga primero una copia de seguridad de su monedero para evitar la pérdida de sus fondos y datos de monedero. Al restablecer sobrescribirá su configuración actual de Bitkit. Restablecer y restaurar Has configurado correctamente un código PIN y {biometricsName} para mejorar la seguridad del monedero. @@ -1538,6 +1545,7 @@ Cargando tu perfil… Entra en la\n<accent>web libre</accent> No se pudo crear el 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. @@ -1576,6 +1584,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 2de124be68..40b10b6380 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -402,6 +402,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 @@ -567,12 +568,16 @@ 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. Relé Esta solicitud es para %1$s, no para el pubky de este monedero. Crear perfil + Es posible que algunos cambios se hayan completado. Revisa el estado actual antes de confirmar de nuevo o desconéctate localmente. + 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 + Revisar Sugerencias Sugerencias para añadir Sí, desvincular @@ -649,6 +654,8 @@ Confirma {biometricsName} Utilizar {biometricsName} Ajustes del teléfono + El restablecimiento anterior de la billetera no se completó. Complétalo antes de crear o restaurar una billetera. Guarda tu frase de recuperación y la copia de seguridad en un lugar seguro. + No se pudo leer el estado de recuperación de la billetera. Reinténtalo antes de continuar. Cartera asegurada Has configurado correctamente un código PIN y {biometricsName} para mejorar la seguridad de tu monedero. Ha configurado correctamente un código PIN para mejorar la seguridad de su monedero. @@ -1537,6 +1544,7 @@ Cargando su perfil… Entre en la\n<accent>web libre</accent> No se pudo crear el 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. @@ -1575,6 +1583,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 3ed2db3b43..811feecacb 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -404,6 +404,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 @@ -555,11 +556,15 @@ Détails Relais 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. Cette demande est destinée à %1$s, pas au pubky de ce portefeuille. 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 n’apporte aucune autre modification à votre profil, à vos abonnements ou à votre accès sur le serveur. 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. @@ -653,6 +658,8 @@ Code PIN défini. Vous souhaitez utiliser {biometricsName} au lieu de votre code PIN ? Utiliser {biometricsName} Réglages tél. + La réinitialisation précédente du portefeuille est inachevée. Termine-la avant de créer ou restaurer un portefeuille. Conserve ta phrase de récupération et ta sauvegarde en lieu sûr. + Impossible de lire l’état de récupération du portefeuille. Réessaie avant de continuer. Portefeuille sécurisé Vous avez configuré avec succès un code PIN et {biometricsName} pour améliorer la sécurité de votre portefeuille. Vous avez configuré avec succès un code PIN pour améliorer la sécurité de votre portefeuille. @@ -1538,6 +1545,7 @@ Chargement de votre profil… Entrez dans le\n<accent>web de la liberté</accent> Échec de la création du 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. @@ -1577,6 +1585,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 7ac3156ca1..5c12fa2aca 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -403,6 +403,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 @@ -569,12 +570,16 @@ 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. Relay Questa richiesta è per %1$s, non per il pubky di questo portafoglio. 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. Questa operazione non apporta ulteriori modifiche al profilo, agli abbonamenti o all’accesso sul server. Modifica Profilo Profilo Riprova + Verifica Consigli Suggerimenti Da Aggiungere Sì, Scollega @@ -670,6 +675,8 @@ Sei sicuro di voler resettare il tuo Wallet Bitkit? Hai un backup della recovery phrase e dei dati del wallet? Resettare Bitkit? Sì, resetta + Il ripristino precedente del portafoglio non è terminato. Completalo prima di creare o recuperare un portafoglio. Conserva al sicuro la frase di recupero e il backup del portafoglio. + Impossibile leggere lo stato di recupero del portafoglio. Riprova prima di continuare. Esegui prima un backup del wallet per evitare la perdita dei fondi e dei dati del wallet. Il reset sovrascriverà l\'attuale configurazione di Bitkit. Reset e Ripristino Hai impostato con successo un codice PIN e{biometricsName} per migliorare la sicurezza del portafoglio. @@ -1543,6 +1550,7 @@ Caricamento del profilo… Entra nel\n<accent>web della libertà</accent> Impossibile creare il 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. @@ -1581,6 +1589,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 2dbfafd3b6..bd7672c73c 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -402,6 +402,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 @@ -567,12 +568,16 @@ 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. Relay Dit verzoek is voor %1$s, niet voor de pubky van deze wallet. 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 de lokale opschoning. Dit brengt geen verdere wijzigingen aan in je profiel, abonnementen of toegang op de server. Profiel Bewerken Profiel Probeer opnieuw + Controleren Suggesties Suggesties Om Toe Te Voegen Ja, ontkoppelen @@ -668,6 +673,8 @@ Weet je zeker dat je je Bitkit-wallet wilt resetten? Heb je een backup van je herstelzin en wallet-gegevens? Bitkit resetten? Ja, resetten + De vorige walletreset is niet voltooid. Voltooi de reset voordat je een wallet aanmaakt of herstelt. Bewaar je herstelzin en walletback-up veilig. + De herstelstatus van de wallet kon niet worden gelezen. Probeer het opnieuw voordat je doorgaat. Maak eerst een back-up van je wallet om verlies van je geld en wallet-gegevens te voorkomen. Resetten overschrijft je huidige Bitkit-configuratie. Resetten en herstellen Je hebt succesvol een pincode en {biometricsName} ingesteld om de wallet-beveiliging te verbeteren. @@ -1539,6 +1546,7 @@ Uw profiel laden… Betreed het\n<accent>vrije web</accent> Profiel aanmaken mislukt + 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. @@ -1577,6 +1585,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 ae0410d716..9d5fbc776a 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -406,6 +406,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 @@ -555,11 +556,15 @@ Szczegóły Przekaźnik Autoryzuj + Czyszczenie profilu nie zostało ukończone. Odłącz się lokalnie, aby usunąć dostęp tego urządzenia bez ponawiania zdalnego usuwania. To żądanie jest przeznaczone dla %1$s, a nie dla pubky tego portfela. 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 zakończ lokalne czyszczenie. Nie wprowadzi to dalszych zmian w profilu, subskrypcjach ani dostępie na serwerze. Edytuj profil Profil Spróbuj ponownie + Sprawdź Sugestie Sugestie do dodania Tak, odłącz @@ -656,6 +661,8 @@ Kod PIN ustawiony. Czy chcesz używać {biometricsName} zamiast twojego PIN-u? Użyj {biometricsName} Ustawienia telefonu + Poprzednie resetowanie portfela nie zostało ukończone. Dokończ je przed utworzeniem lub przywróceniem portfela. Przechowuj frazę odzyskiwania i kopię zapasową portfela w bezpiecznym miejscu. + Nie udało się odczytać stanu odzyskiwania portfela. Spróbuj ponownie przed kontynuowaniem. Portfel zabezpieczony Pomyślnie ustawiono kod PIN i {biometricsName}, aby zwiększyć bezpieczeństwo portfela. Skutecznie ustawiono kod PIN zwiększając bezpieczeństwo portfela. @@ -1542,6 +1549,7 @@ Wczytywanie Twojego profilu… Wejdź do\n<accent>wolnej sieci</accent> Nie udało się utworzyć 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. @@ -1580,6 +1588,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 11c653b52f..8b978ad7f8 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -406,6 +406,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 @@ -575,11 +576,15 @@ Detalhes Relay Autorizar + A limpeza do perfil está incompleta. Desconecte-se localmente para remover o acesso deste dispositivo sem tentar novamente a exclusão remota. Esta solicitação é para %1$s, não para o pubky desta carteira. 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 faz outras alterações no seu perfil, nas assinaturas ou no acesso no servidor. Editar perfil Perfil Tente novamente + Revisar Sugestões Sugestões Para Adicionar Sim, Desvincular @@ -675,6 +680,8 @@ Você tem certeza de que deseja redefinir sua Bitkit? Você tem um backup de sua frase de recuperação e dos dados da carteira? Redefinir Bitkit? Sim, Redefinir + A redefinição anterior da carteira não foi concluída. Conclua-a antes de criar ou restaurar uma carteira. Guarde a frase de recuperação e o backup da carteira em um local seguro. + Não foi possível ler o estado de recuperação da carteira. Tente novamente antes de continuar. Faça o backup da sua carteira primeiro para evitar a perda de fundos e dados da carteira. A redefinição substituirá a configuração atual da Bitkit. Redefinir e Restaurar Você configurou com sucesso um código PIN e {biometricsName} para melhorar a segurança da sua carteira. @@ -1543,6 +1550,7 @@ Carregando seu perfil… Entre na\n<accent>web da liberdade</accent> Falha ao criar 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. @@ -1581,6 +1589,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 ce704355eb..ea9fc2a17d 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -399,6 +399,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 @@ -532,11 +533,15 @@ 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. Relay Este pedido destina-se a %1$s, não ao pubky desta carteira. Criar Perfil + Algumas alterações poderão ter sido concluídas. Reveja o estado atual antes de confirmar novamente ou desligue-se localmente. + 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 Sugestões Atualize a Bitkit para obter novos recursos e correções de bugs! Atualizar @@ -634,6 +639,8 @@ PIN configurado. Você gostaria de usar {biometricsName} em vez de seu código PIN? Usar {biometricsName} Configurações do Telefone + A reposição anterior da carteira não foi concluída. Conclui-a antes de criar ou restaurar uma carteira. Guarda a frase de recuperação e a cópia de segurança num local seguro. + Não foi possível ler o estado de recuperação da carteira. Tenta novamente antes de continuar. Carteira Protegida Você configurou com sucesso um código PIN e {biometricsName} para melhorar a segurança da sua carteira. Você configurou com êxito um código PIN para aumentar a segurança da sua carteira. @@ -1517,6 +1524,7 @@ A carregar o seu perfil… Entre na\n<accent>web da liberdade</accent> Falha ao criar 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. @@ -1564,6 +1572,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 e2ea71d006..e4b0961cae 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -414,6 +414,7 @@ Включить\nLightning\n<accent>платежи</accent> Пожалуйста, подождите, пока данные вашего старого кошелька переносятся в эту новую версию Bitkit. Обычно это занимает меньше минуты. Миграция кошелька + Статус переноса кошелька недоступен. Повторите попытку, прежде чем продолжить. МИГРАЦИЯ <accent>КОШЕЛЬКА</accent> Канал уведомлений для фоновой службы Lightning ноды @@ -586,11 +587,15 @@ Ок Ретранслятор Авторизовать + Очистка профиля не завершена. Отключитесь локально, чтобы убрать доступ этого устройства без повторной попытки удалённого удаления. Этот запрос предназначен для %1$s, а не для pubky этого кошелька. Создать Профиль + Некоторые изменения могли быть выполнены. Проверьте текущее состояние перед повторным подтверждением или отключитесь локально. + Удалите доступ этого устройства и завершите локальную очистку. Это не вносит дополнительных изменений в ваш профиль, подписки или доступ на сервере. Редактировать Профиль Профиль Попробовать снова + Проверить Рекомендации Рекомендации для добавления Да, Отвязать @@ -686,6 +691,8 @@ Вы уверены, что хотите сбросить настройки своего кошелька Bitkit? У вас есть резервная копия фразы восстановления и данных кошелька? Сбросить Bitkit? Да,\nСбросить + Предыдущий сброс кошелька не завершён. Завершите его перед созданием или восстановлением кошелька. Храните фразу восстановления и резервную копию кошелька в безопасном месте. + Не удалось прочитать состояние восстановления кошелька. Повторите попытку перед продолжением. Сначала сделайте резервную копию своего кошелька, чтобы избежать потери ваших средств и данных кошелька. Сброс перезапишет ваши текущие настройки Bitkit. Сбросить И Восстановить Вы успешно установили PIN-код и {biometricsName} для повышения безопасности кошелька. @@ -1557,6 +1564,7 @@ Загрузка вашего профиля… Войдите в\n<accent>свободный веб</accent> Не удалось создать профиль + Активные подписки не позволяют удалить этот профиль. Удаление профиля удалит его из Pubky. У контактов могут остаться данные профиля и платёжные данные, которыми вы делились ранее. Удалить Профиль? Не удалось удалить данные вашего профиля. Повторите попытку или отключите этот pubky от Bitkit. @@ -1595,6 +1603,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 c930a202b0..ae62d74677 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -570,6 +570,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 @@ -815,16 +816,20 @@ 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 + 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. 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 makes no further changes to your profile, subscriptions or access on the server. BIO Short note. Tell a bit about yourself. Your profile changed in pubky.app. Bitkit loaded the latest version, so make your edit again. @@ -853,6 +858,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. @@ -868,6 +874,7 @@ Unlink pubky Pubky unlinked This profile needs a newer version of Bitkit. Update the app to use it. + Wallet recovery is required before this profile can be disconnected. Check wallet recovery in Settings. Your Name Your Pubky Already signed in @@ -972,6 +979,8 @@ Could not reset the network graph. Please try again. Bitkit will restart in a few seconds to download a fresh network graph. Network Graph Reset + The previous wallet reset did not finish. Complete the reset before creating or restoring a wallet. Keep your recovery phrase and wallet backup safe. + Wallet recovery state could not be read. Retry before continuing. Back up your wallet first to avoid loss of your funds and wallet data. Resetting will overwrite your current Bitkit setup. Reset And Restore You have successfully set up a PIN code and {biometricsName} to improve wallet security. 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..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) } } } 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..63a27c0c06 --- /dev/null +++ b/app/src/test/java/to/bitkit/data/ProfileRemovalStoreTest.kt @@ -0,0 +1,386 @@ +package to.bitkit.data + +import androidx.datastore.core.CorruptionException +import androidx.datastore.core.DataStore +import androidx.datastore.core.DataStoreFactory +import kotlinx.coroutines.CompletableDeferred +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.first +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.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +@OptIn(ExperimentalCoroutinesApi::class) +class ProfileRemovalStoreTest { + @get:Rule + val folder = TemporaryFolder() + + @Test + fun `wallet reset admission distinguishes profile cleanup and survives datastore restart`() = runTest { + val file = folder.newFile("wallet-reset").also { it.delete() } + val owner = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler)) + val store = ProfileRemovalStore(DataStoreFactory.create(ProfileRemovalSerializer, scope = owner) { file }) + val id = UUID.randomUUID().toString() + store.withAccess(id) { store.begin(id) } + assertEquals(WalletResetRecovery.Clear, store.walletResetRecovery.first()) + store.requireWalletAvailable() + store.withAccess(id, ProfileRemovalScope.WALLET_WIPE) { store.begin(id) } + requireNotNull(owner.coroutineContext[Job]).cancelAndJoin() + val restarted = ProfileRemovalStore( + DataStoreFactory.create(ProfileRemovalSerializer, scope = backgroundScope) { file } + ) + assertEquals(WalletResetRecovery.Pending(id), restarted.walletResetRecovery.first()) + assertFailsWith { restarted.requireWalletAvailable() } + restarted.requirePendingWalletReset(id) + } + + @Test + fun `unreadable reset admission remains unavailable until an explicit read succeeds`() = runTest { + var readable = false + val store = ProfileRemovalStore(object : DataStore { + override val data = flow { + if (!readable) throw IOException("read refused") + emit(ProfileRemovalState()) + } + override suspend fun updateData(transform: suspend (ProfileRemovalState) -> ProfileRemovalState) = + error("Read retry cannot mutate recovery state") + }) + assertEquals(WalletResetRecovery.Unavailable, store.walletResetRecovery.first()) + assertFailsWith { store.requireWalletAvailable() } + readable = true + store.refreshWalletResetRecovery() + assertEquals(WalletResetRecovery.Clear, store.walletResetRecovery.first()) + } + + @Test + fun `pending profile permits a complete local receipt snapshot but pending wipe does not`() = runTest { + val store = ProfileRemovalStore.inMemoryForTesting() + 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()) + } + + @Test + fun `local cleanup waits for the whole snapshot and never exposes its partial clear`() = runTest { + val store = ProfileRemovalStore.inMemoryForTesting() + val id = UUID.randomUUID().toString() + store.withAccess(id) { store.begin(id) } + val copying = CompletableDeferred() + val releaseCopy = CompletableDeferred() + val source = mutableListOf("first", "second") + val snapshot = async { + store.withReceiptSnapshot { + val first = source.first() + copying.complete(Unit) + releaseCopy.await() + listOf(first, source.last()) + } + } + copying.await() + var cleared = false + val cleanup = launch { + store.withAccess(id) { + store.withReceiptCleanup { + source.clear() + cleared = true + } + } + } + runCurrent() + assertFalse(cleared) + releaseCopy.complete(Unit) + assertEquals(listOf("first", "second"), snapshot.await()) + cleanup.join() + assertTrue(cleared) + assertFailsWith { store.withReceiptSnapshot { source.toList() } } + store.withAccess(id) { store.complete(id) } + assertEquals(emptyList(), store.withReceiptSnapshot { source.toList() }) + } + + @Test + fun `partial local cleanup remains blocked after a real DataStore restart`() = runTest { + val file = folder.newFile("partial-removal").also { it.delete() } + val firstScope = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler)) + val first = ProfileRemovalStore(DataStoreFactory.create(ProfileRemovalSerializer, scope = firstScope) { file }) + val id = UUID.randomUUID().toString() + try { + first.withAccess(id) { + first.begin(id) + assertFailsWith { + first.withReceiptCleanup { throw IOException("private state unavailable") } + } + } + } finally { + requireNotNull(firstScope.coroutineContext[Job]).cancelAndJoin() + } + val second = + ProfileRemovalStore(DataStoreFactory.create(ProfileRemovalSerializer, scope = backgroundScope) { file }) + assertEquals(id, second.pendingAttempt()) + assertFailsWith { second.withReceiptSnapshot { error("partial state") } } + second.withAccess(id) { + second.withReceiptCleanup { } + second.complete(id) + } + assertEquals("complete", second.withReceiptSnapshot { "complete" }) + } + + @Test + fun `legacy marker and unavailable storage never become absent receipt associations`() = runTest { + val state = MutableStateFlow(ProfileRemovalState(attemptId = UUID.randomUUID().toString())) + var unavailable = false + val store = ProfileRemovalStore(object : DataStore { + override val data = flow { + if (unavailable) throw IOException("unavailable") + emit(state.value) + } + override suspend fun updateData(transform: suspend (ProfileRemovalState) -> ProfileRemovalState) = + 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") } + }.cause is IOException + ) + } + + @Test + fun `observation fails closed with backoff and restarts after explicit durable completion`() = runTest { + val id = UUID.randomUUID().toString() + val state = MutableStateFlow(ProfileRemovalState(attemptId = id, scope = ProfileRemovalScope.PROFILE)) + 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(1_750) + 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 `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() } + 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 { + assertEquals(WalletResetRecovery.Unreadable(it), first.walletResetRecovery.first()) + assertFailsWith { first.requireWalletAvailable() } + 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()) + assertEquals(WalletResetRecovery.Unreadable(recovered), second.walletResetRecovery.first()) + assertFailsWith { second.requireWalletAvailable() } + assertFalse(second.localDisconnectAvailable.first()) + assertFailsWith { second.requireReceiptAccountingAccess() } + assertFailsWith { second.withAccess(recovered) { second.complete(recovered) } } + second.withAccess(recovered, ProfileRemovalScope.WALLET_WIPE) { + second.begin(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(), + "{\"scope\":\"WALLET_WIPE\"}".toByteArray(), + "{\"attemptId\":null,\"localCleanupStarted\":true}".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/data/WalletConnectionRecoveryTest.kt b/app/src/test/java/to/bitkit/data/WalletConnectionRecoveryTest.kt index 29072d8671..8c0a7d97d0 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,8 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config +import to.bitkit.async.ServiceQueue +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 +50,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 +88,148 @@ 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 `receipt checks derive the wallet binding only once per admitted operation`() = test { + var derivations = 0 + whenever(binding.getBackupWalletBinding(0)).thenAnswer { + derivations += 1 + "original-wallet" + } + repeat(2) { operation -> + sut.withReceiptOperation { receipt -> + repeat(200) { receipt.requireCurrent() } + receipt.commitReceiptState { assertEquals(operation + 1, derivations) } + } + } + } + + @Test + fun `receipt admission rejects unavailable wallet credentials before entering Core work`() = test { + whenever(binding.getBackupWalletBinding(0)).thenAnswer { throw AppError("binding unavailable") } + var entered = false + assertFailsWith { sut.withReceiptOperation { entered = true } } + assertFalse(entered) + } + + @Test + fun `receipt work can complete while restoration holds the ordinary operation lock`() = test { + sut.withOperation(sut.captureOwner()) { + sut.withReceiptOperation { receipt -> + receipt.requireCurrent() + assertEquals("committed", receipt.commitReceiptState { "committed" }) + } + } + } + + @Test + fun `receipt scope rejects escaped writes and recursive replacement`() = test { + lateinit var escaped: WalletConnectionRecovery.Session + sut.withReceiptOperation { + escaped = it + assertFailsWith { sut.withIdentityChange { error("must not replace") } } + } + assertFailsWith { escaped.commitReceiptState { error("must not write") } } + } + + @Test + fun `cancelled original receipt cannot write through the Core replacement job`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + val attempted = CompletableDeferred() + var committed = false + val operation = launch { + sut.withReceiptOperation { receipt -> + ServiceQueue.CORE.background { + entered.complete(Unit) + release.await() + val failure = runCatching { receipt.commitReceiptState { committed = true } }.exceptionOrNull() + attempted.complete(failure is CancellationException) + } + } + } + entered.await() + operation.cancel() + runCurrent() + assertFalse(operation.isCompleted, "Admission must outlive the Core worker") + release.complete(Unit) + assertTrue(attempted.await()) + operation.join() + assertFalse(committed) + } + + @Test + fun `same seed replacement drains the actual Core receipt before any credential cleanup`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + val attempted = CompletableDeferred() + var committed = false + val operation = launch { + sut.withReceiptOperation { receipt -> + ServiceQueue.CORE.background { + entered.complete(Unit) + release.await() + val failure = runCatching { receipt.commitReceiptState { committed = true } }.exceptionOrNull() + attempted.complete(failure is CancellationException) + } + } + } + entered.await() + var replaced = false + val replacement = launch { sut.withIdentityChange { replaced = true } } + runCurrent() + assertFalse(replaced) + assertFalse(operation.isCompleted) + release.complete(Unit) + assertTrue(attempted.await()) + operation.join() + replacement.join() + assertTrue(replaced) + assertFalse(committed) + sut.withReceiptOperation { it.commitReceiptState { committed = true } } + assertTrue(committed) + } @Test fun `queued wallet generation is revoked during same seed replacement`() = test { @@ -422,6 +569,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/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/data/keychain/ProfileCredentialsTest.kt b/app/src/test/java/to/bitkit/data/keychain/ProfileCredentialsTest.kt new file mode 100644 index 0000000000..597cfc56bf --- /dev/null +++ b/app/src/test/java/to/bitkit/data/keychain/ProfileCredentialsTest.kt @@ -0,0 +1,463 @@ +package to.bitkit.data.keychain + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.mutablePreferencesOf +import androidx.datastore.preferences.core.stringPreferencesKey +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.runTest +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import to.bitkit.test.InMemoryDataStore +import java.io.IOException +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse + +@OptIn(ExperimentalCoroutinesApi::class) +class ProfileCredentialsTest { + @get:Rule + val folder = TemporaryFolder() + + private val session = stringPreferencesKey("PAYKIT_SESSION_0") + private val secret = stringPreferencesKey("PUBKY_SECRET_KEY_0") + private val sharedSource = stringPreferencesKey("SHARED_PUBKY_SOURCE_0") + private val mnemonic = stringPreferencesKey("BIP39_MNEMONIC_0") + private val otherWallet = stringPreferencesKey("PAYKIT_SESSION_1") + private var walletIndex = 0L + private var admitted = true + + private fun requireCurrent() = check(admitted) { "Original profile admission ended" } + + private fun credentials(store: DataStore) = ProfileCredentialStore( + store, + walletIndex = { walletIndex }, + decrypt = { value -> + if (value == "unreadable") throw IOException("Key unavailable") + value.substringAfter(':').toByteArray() + }, + ) + + private fun initial() = mutablePreferencesOf( + session to "first:session", + secret to "first:managed-key", + sharedSource to "first:ring-reference", + mnemonic to "unchanged-wallet", + 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 -> + listOf("replacement", null, "unreadable").forEach { replacement -> + val store = InMemoryDataStore(initial()) + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + store.edit { + if (replacement == null) it.remove(changed) else it[changed] = replacement + } + val before = store.data.first() + if (replacement == "unreadable") { + assertFailsWith { credentials.validate(target, ::requireCurrent) } + } else { + assertFailsWith { credentials.validate(target, ::requireCurrent) } + } + assertEquals(before, store.data.first()) + } + } + } + + @Test + fun `validation preserves equal reencrypted credentials but rejects store wallet or admission changes`() = runTest { + val store = InMemoryDataStore(initial()) + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + store.edit { it[session] = "different-iv:session" } + val before = store.data.first() + credentials.validate(target, ::requireCurrent) + assertFailsWith { credentials(store).validate(target, ::requireCurrent) } + walletIndex = 1 + assertFailsWith { credentials.validate(target, ::requireCurrent) } + walletIndex = 0 + admitted = false + assertFailsWith { credentials.validate(target, ::requireCurrent) } + assertEquals(before, store.data.first()) + } + + @Test + fun `observed invalid owned credentials cannot regain erase permission when restored`() = runTest { + listOf("replacement", "unreadable").forEach { replacement -> + val store = InMemoryDataStore(initial()) + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + store.edit { it[session] = replacement } + if (replacement == "unreadable") { + assertFailsWith { credentials.validate(target, ::requireCurrent) } + } else { + assertFailsWith { credentials.validate(target, ::requireCurrent) } + } + store.updateData { initial() } + assertFailsWith { credentials.erase(target, ::requireCurrent) } + assertEquals(initial(), store.data.first()) + } + } + + @Test + fun `observed erase mismatch or decryption failure cannot regain permission when restored`() = runTest { + listOf("replacement", "unreadable").forEach { replacement -> + val store = InMemoryDataStore(initial()) + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + store.edit { it[sharedSource] = replacement } + if (replacement == "unreadable") { + assertFailsWith { credentials.erase(target, ::requireCurrent) } + } else { + assertFailsWith { credentials.erase(target, ::requireCurrent) } + } + store.updateData { initial() } + assertFailsWith { credentials.erase(target, ::requireCurrent) } + assertEquals(initial(), store.data.first()) + } + } + + @Test + fun `cancelled owned credential read preserves permission for matching local retry`() = runTest { + val backing = InMemoryDataStore(initial()) + var cancelRead = false + val store = object : DataStore { + override val data = backing.data.map { + if (cancelRead) throw CancellationException("Caller cancelled") + it + } + + override suspend fun updateData(transform: suspend (Preferences) -> Preferences): Preferences = + backing.updateData(transform) + } + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + cancelRead = true + assertFailsWith { credentials.validate(target, ::requireCurrent) } + assertEquals(initial(), backing.data.first()) + cancelRead = false + credentials.erase(target, ::requireCurrent) + assertFalse(backing.data.first().contains(session)) + } + + @Test + fun `failed read before erase transform permanently retires original target`() = runTest { + val backing = InMemoryDataStore(initial()) + var refuseRead = true + val store = object : DataStore { + override val data = backing.data + override suspend fun updateData(transform: suspend (Preferences) -> Preferences): Preferences { + if (refuseRead) throw IOException("Preferences cannot be read") + return backing.updateData(transform) + } + } + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + assertFailsWith { credentials.erase(target, ::requireCurrent) } + assertEquals(initial(), backing.data.first()) + refuseRead = false + assertFailsWith { credentials.erase(target, ::requireCurrent) } + assertEquals(initial(), backing.data.first()) + } + + @Test + fun `cancelled erase before transform preserves matching target for retry`() = runTest { + val backing = InMemoryDataStore(initial()) + var cancelRead = true + val store = object : DataStore { + override val data = backing.data + override suspend fun updateData(transform: suspend (Preferences) -> Preferences): Preferences { + if (cancelRead) throw CancellationException("Caller cancelled before read") + return backing.updateData(transform) + } + } + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + assertFailsWith { credentials.erase(target, ::requireCurrent) } + assertEquals(initial(), backing.data.first()) + cancelRead = false + credentials.erase(target, ::requireCurrent) + assertFalse(backing.data.first().contains(session)) + } + + @Test + fun `erase commits all original profile entries together and survives restart`() = runTest { + val file = folder.root.resolve("keychain.preferences_pb") + val scope = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler)) + val store = PreferenceDataStoreFactory.create(scope = scope) { file } + try { + store.updateData { initial() } + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + credentials.erase(target, ::requireCurrent) + } finally { + requireNotNull(scope.coroutineContext[Job]).cancelAndJoin() + } + val reopened = PreferenceDataStoreFactory.create(scope = backgroundScope) { file } + assertEquals( + mutablePreferencesOf(mnemonic to "unchanged-wallet", otherWallet to "other-wallet-session").asMap(), + reopened.data.first().asMap(), + ) + } + + @Test + fun `changed or newly absent credentials refuse the entire erase`() = runTest { + listOf(session, secret, sharedSource).forEach { changed -> + listOf("replacement", null).forEach { replacement -> + val store = InMemoryDataStore(initial()) + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + store.edit { + if (replacement == null) it.remove(changed) else it[changed] = replacement + } + val before = store.data.first() + assertFailsWith { credentials.erase(target, ::requireCurrent) } + assertEquals(before, store.data.first()) + } + } + } + + @Test + fun `adding an originally absent managed key refuses erase`() = runTest { + val store = InMemoryDataStore(initial().also { it.remove(secret) }) + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + store.edit { it[secret] = "replacement" } + val before = store.data.first() + assertFailsWith { credentials.erase(target, ::requireCurrent) } + assertEquals(before, store.data.first()) + } + + @Test + fun `wallet replacement or ended lifecycle refuses erase even with equal values`() = runTest { + val store = InMemoryDataStore(initial()) + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + walletIndex = 1 + assertFailsWith { credentials.erase(target, ::requireCurrent) } + walletIndex = 0 + admitted = false + assertFailsWith { credentials.erase(target, ::requireCurrent) } + assertEquals(initial(), store.data.first()) + } + + @Test + fun `another credential store cannot use the target`() = runTest { + val store = InMemoryDataStore(initial()) + val target = credentials(store).capture(::requireCurrent) + assertFailsWith { credentials(store).erase(target, ::requireCurrent) } + assertEquals(initial(), store.data.first()) + } + + @Test + fun `re-encryption of the same bundle does not invalidate original credentials`() = runTest { + val store = InMemoryDataStore(initial()) + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + store.edit { + it[session] = "new-iv:session" + it[secret] = "new-iv:managed-key" + } + credentials.erase(target, ::requireCurrent) + assertFalse(store.data.first().contains(session)) + assertEquals("unchanged-wallet", store.data.first()[mnemonic]) + } + + @Test + fun `decryption failure never clears any entry`() = runTest { + val store = InMemoryDataStore(initial()) + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + store.edit { it[sharedSource] = "unreadable" } + val before = store.data.first() + assertFailsWith { credentials.erase(target, ::requireCurrent) } + assertFailsWith { credentials.capture(::requireCurrent) } + assertEquals(before, store.data.first()) + } + + @Test + fun `failed durable update retains the original bundle and permits a later local retry`() = runTest { + val backing = InMemoryDataStore(initial()) + var refuse = true + val store = object : DataStore { + override val data = backing.data + override suspend fun updateData(transform: suspend (Preferences) -> Preferences): Preferences = + backing.updateData { + val next = transform(it) + if (refuse) throw IOException("Storage unavailable") + next + } + } + val credentials = credentials(store) + val target = credentials.capture(::requireCurrent) + assertFailsWith { credentials.erase(target, ::requireCurrent) } + assertEquals(initial(), backing.data.first()) + refuse = false + credentials.erase(target, ::requireCurrent) + assertFalse(backing.data.first().contains(session)) + } +} diff --git a/app/src/test/java/to/bitkit/repositories/ActivityRepoTest.kt b/app/src/test/java/to/bitkit/repositories/ActivityRepoTest.kt index 7efd8ee3bd..0e4f8aa8ec 100644 --- a/app/src/test/java/to/bitkit/repositories/ActivityRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/ActivityRepoTest.kt @@ -148,6 +148,7 @@ class ActivityRepoTest : BaseUnitTest() { fun setUp() { whenever(cacheStore.data).thenReturn(flowOf(AppCacheData())) whenever(coreService.activity).thenReturn(mock()) + mockPaymentImport() whenever(clock.now()).thenReturn(Clock.System.now()) whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState())) whenever(blocktankRepo.blocktankState).thenReturn(MutableStateFlow(BlocktankState())) @@ -296,18 +297,27 @@ class ActivityRepoTest : BaseUnitTest() { ) } + private val importedPaymentLists = mutableListOf>() + + private fun mockPaymentImport() { + whenever { + coreService.activity.syncLdkNodePaymentsToActivities(any(), eq(false), any()) + }.doSuspendableAnswer { invocation -> + val fetch = invocation.getArgument List>(0) + val payments = fetch() + val channels = invocation.getArgument) -> Map>(2) + channels(payments) + importedPaymentLists.add(payments) + Unit + } + } + private fun setupSyncActivitiesMocks( cacheData: AppCacheData, ) { whenever(cacheStore.data).thenReturn(flowOf(cacheData)) whenever { lightningRepo.getPayments() }.thenReturn(Result.success(emptyList())) - whenever { - coreService.activity.syncLdkNodePaymentsToActivities( - any(), - eq(false), - any() - ) - }.thenReturn(Unit) + mockPaymentImport() whenever { transferRepo.syncTransferStates() }.thenReturn(Result.success(Unit)) whenever { coreService.activity.allPossibleTags() }.thenReturn(emptyList()) } @@ -416,7 +426,7 @@ class ActivityRepoTest : BaseUnitTest() { assertTrue(fresh.none { it.isCompleted }) paymentResponse.complete(Result.success(newPayments)) assertTrue(fresh.awaitAll().all { it.isSuccess }) - verify(coreService.activity).syncLdkNodePaymentsToActivities(eq(newPayments), eq(false), any()) + assertEquals(newPayments, importedPaymentLists.last()) verify(lightningRepo, times(2)).getPayments() assertFalse(sut.isSyncingLdkNodePayments.value) } @@ -445,11 +455,7 @@ class ActivityRepoTest : BaseUnitTest() { assertTrue(fresh.await().isSuccess) if (cancelOwner) assertTrue(owner.isCancelled) else assertTrue(owner.await().isFailure) verify(lightningRepo, times(2 * (index + 1))).getPayments() - verify(coreService.activity, times(index + 1)).syncLdkNodePaymentsToActivities( - eq(payments), - eq(false), - any(), - ) + assertEquals(index + 1, importedPaymentLists.count { it == payments }) assertFalse(sut.isSyncingLdkNodePayments.value) } } @@ -499,13 +505,7 @@ class ActivityRepoTest : BaseUnitTest() { whenever { coreService.activity.getActivity(any(), eq(WalletScope.default)) }.thenReturn(null) - whenever { - coreService.activity.syncLdkNodePaymentsToActivities( - any>(), - any(), - any>() - ) - }.thenReturn(Unit) + mockPaymentImport() whenever { transferRepo.syncTransferStates() }.thenReturn(Result.success(Unit)) whenever { coreService.activity.allPossibleTags() }.thenReturn(emptyList()) diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 069bb5f5d0..7f6855efd1 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -1,30 +1,46 @@ 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.VssException import com.synonym.vssclient.VssItem import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Delay import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.InternalCoroutinesApi +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.coroutineScope import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.test.StandardTestDispatcher +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 kotlinx.serialization.json.jsonPrimitive @@ -57,6 +73,7 @@ import to.bitkit.data.HwWalletStore import to.bitkit.data.PaykitOutboundDeliveryStore import to.bitkit.data.PrivatePaykitReservationData import to.bitkit.data.PrivatePaykitReservationStore +import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.data.SparkSendAttempt @@ -71,17 +88,21 @@ 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 +import to.bitkit.data.serializers.AppCacheSerializer import to.bitkit.data.withPublicSharingDisabledForRestore import to.bitkit.di.json import to.bitkit.env.Env 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.NodeLifecycleState import to.bitkit.models.PaykitAllowanceStateBackup import to.bitkit.models.PaykitPaymentStateBackup import to.bitkit.models.PaykitUsdtStateBackup @@ -97,19 +118,28 @@ 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 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 import to.bitkit.utils.AppError import to.bitkit.utils.jsonLogOf import java.io.File +import java.io.IOException +import java.nio.file.Files import java.security.MessageDigest +import java.util.UUID import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger import javax.inject.Provider +import kotlin.coroutines.CoroutineContext import kotlin.coroutines.cancellation.CancellationException import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -118,6 +148,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 @@ -133,6 +164,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() @@ -142,6 +174,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() @@ -176,6 +209,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), @@ -196,8 +233,12 @@ 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(cacheStore.backupStatuses).thenReturn(cacheData.map { it.backupStatuses }) whenever(settingsStore.data).thenReturn(settingsData) whenever { settingsStore.update(any()) }.thenReturn(Unit) whenever(widgetsStore.data).thenReturn(widgetsData) @@ -240,6 +281,7 @@ class BackupRepoTest : BaseUnitTest() { }.thenReturn(Result.success(Unit)) whenever { vssBackupClient.listKeys() }.thenReturn(Result.success(emptyList())) + whenever(pubkyRepo.hasIdentityForBackup()).thenReturn(false) whenever { sparkRepo.exitBackup() }.thenReturn(Result.success(null)) whenever { sparkRepo.restoreExitBackup(any(), any()) }.thenReturn(Result.success(Unit)) whenever { sparkRepo.mergeRemoteExitBackup(anyOrNull()) }.thenReturn(Result.success(Unit)) @@ -252,562 +294,1389 @@ class BackupRepoTest : BaseUnitTest() { } @Test - fun `the latest backup time skips the spark exit data`() { - assertFalse(BackupCategory.SPARK_EXIT in BackupRepo.LATEST_BACKUP_TIME_CATEGORIES) - assertTrue(BackupCategory.WALLET in BackupRepo.LATEST_BACKUP_TIME_CATEGORIES) + 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 `restore marker storage reads leave Main responsive`() = test { - val entered = CompletableDeferred() - val release = CountDownLatch(1) - val mainThread = Thread.currentThread() - whenever(keychain.exists(Keychain.Key.PAYKIT_PENDING_BACKUP_RESTORE.name)).thenAnswer { - entered.complete(Thread.currentThread()) - check(release.await(5, TimeUnit.SECONDS)) { "Marker read was not released" } - false - } - Executors.newSingleThreadExecutor().asCoroutineDispatcher().use { ioDispatcher -> - sut = createSut(ioDispatcher = ioDispatcher) - try { - val read = async(Dispatchers.Main) { sut.hasPendingWalletRestore() } - val storageThread = withContext(Dispatchers.Default) { - withTimeout(5.seconds) { entered.await() } - } - assertNotEquals(mainThread, storageThread) - assertTrue(async(Dispatchers.Main) { true }.await()) - assertFalse(read.isCompleted) - - release.countDown() + 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()) + } - assertFalse(read.await()) - } finally { - release.countDown() + @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()) + assertTrue(statuses.value.getValue(BackupCategory.SETTINGS).running) + val recovery = connectionRecoveryFixture(settingsStore, keychain, vssClients) + assertFailsWith { + recovery.withIdentityChange { + assertFalse(statuses.value.getValue(BackupCategory.SETTINGS).running) + 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 `spark exit backup uploads the exported state and restores it before the wallet`() = test { - val backup = SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "{\"pedigrees\":[]}") - whenever(sparkRepo.exitBackup()).thenReturn(Result.success(backup)) + fun `isolated cache failure preserves other listeners and owner rearm`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000, synced = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + var failNext = true + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + if (failNext) { + failNext = false + throw java.io.IOException("isolated cache read failure") + } + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + statuses.update { current -> transform(AppCacheData(backupStatuses = current)).backupStatuses } + } + try { + sut.startObservingBackups() + runCurrent() + settingsData.update { it.copy(selectedCurrency = "EUR") } + advanceTimeBy(5_000) + runCurrent() + verify(vssBackupClient, times(1)).putObject(eq(category.name), any()) + connectionRecoveryFixture(settingsStore, keychain, vssClients).withIdentityChange { } + runCurrent() + verify(vssBackupClient, times(2)).setupWithRetry(any(), any(), any()) + } finally { + sut.reset() + } + } - sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + @Test + fun `failed required mark retries without another change and keeps observing`() = test { + assertFailedRequiredMarkRecovers(restart = false) + } - val data = argumentCaptor() - verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), data.capture()) - whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( - Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = data.firstValue, version = 1)) - ) + @Test + fun `failed required mark survives observation restart without another change`() = test { + assertFailedRequiredMarkRecovers(restart = true) + } - sut.performFullRestoreFromLatestBackup().getOrThrow() + 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) - inOrder(sparkRepo, vssBackupClient) { - verify(sparkRepo).restoreExitBackup(backup, 0) - verify(vssBackupClient).getObject(BackupCategory.WALLET.name) + 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 `spark exit backup uploads when Spark was ready before observing started`() = test { - val statuses = MutableStateFlow(mapOf(BackupCategory.SPARK_EXIT to BackupItemStatus(synced = 1, required = 1))) + 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)) {} stubBackupObservers() - whenever(sparkRepo.state).thenReturn( - MutableStateFlow(SparkState(isSupported = true, isReady = true, hasSynced = true)) + sut.startObservingBackups() + runCurrent() + val original = vssClients.owners.value + var failRequiredWrite = true + 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 + ) { + 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 backup = SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "state") - whenever(sparkRepo.exitBackup()).thenReturn(Result.success(backup)) + val wipe = createWipeUseCase() try { - sut.startObservingBackups() + settingsData.update { it.copy(selectedCurrency = "EUR") } runCurrent() - advanceTimeBy(61_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() - - verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + 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.stopObservingBackups() } } + 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, + db = db, + settingsStore = settingsStore, + cacheStore = cacheStore, + watchOnlyAccountRepo = watchOnlyAccountRepo, + widgetsStore = widgetsStore, + blocktankRepo = mock(), + activityRepo = activityRepo, + hwWalletRepo = mock(), + lightningRepo = lightningRepo, + pubkyRepo = pubkyRepo, + pubkySwapsRouteRepo = mock(), + privatePaykitRepo = Provider { privatePaykitRepo }, + privatePaykitAddressReservationRepo = privatePaykitAddressReservationRepo, + firebaseMessaging = mock(), + migrationService = mock(), + 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(), + ) + @Test - fun `spark exit backup does not upload again when observing restarts on foreground`() = test { - val statuses = MutableStateFlow(mapOf(BackupCategory.SPARK_EXIT to BackupItemStatus(synced = 1, required = 1))) + 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(sparkRepo.state).thenReturn( - MutableStateFlow(SparkState(isSupported = true, isReady = true, hasSynced = true)) + whenever(lightningRepo.lightningState).thenReturn( + MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Running)), ) - val backup = SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "state") - whenever(sparkRepo.exitBackup()).thenReturn(Result.success(backup)) + 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 { - sut.startObservingBackups() runCurrent() - advanceTimeBy(61_000) + wipe.cancel() runCurrent() - sut.stopObservingBackups() - - sut.startObservingBackups() + assertFalse(wipe.isCompleted) + release.complete(Unit) + wipe.join() + assertTrue(wipe.isCancelled) runCurrent() - advanceTimeBy(61_000) + 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(1)).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + verify(vssBackupClient, times(2)).putObject(eq(category.name), payload.capture()) + assertTrue(payload.lastValue.decodeToString().contains("GBP")) + assertFalse(statuses.value.getValue(category).isRequired) } finally { - sut.stopObservingBackups() + release.complete(Unit) + wipe.cancelAndJoin() + sut.reset() } } @Test - fun `spark exit data that changed while observing was stopped uploads when observing restarts`() = test { - val statuses = MutableStateFlow(mapOf(BackupCategory.SPARK_EXIT to BackupItemStatus(synced = 1, required = 1))) + 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() - whenever(sparkRepo.state).thenReturn( - MutableStateFlow(SparkState(isSupported = true, isReady = true, hasSynced = true)) - ) - val backup = SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "state") - whenever(sparkRepo.exitBackup()).thenReturn(Result.success(backup)) - exitStateGeneration.value = 1L + 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 { - sut.startObservingBackups() - runCurrent() - advanceTimeBy(61_000) + settingsData.update { it.copy(selectedCurrency = "EUR") } + advanceTimeBy(5_000) runCurrent() - sut.stopObservingBackups() + assertTrue(oldWriteCommitted.isCompleted) + val payload = argumentCaptor() + verify(vssBackupClient).putObject(eq(category.name), payload.capture()) + assertFalse(statuses.value.getValue(category).isRequired) - exitStateGeneration.value = 2L + sut.stopObservingBackups() sut.startObservingBackups() runCurrent() - advanceTimeBy(61_000) + 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() + } + } - verify(vssBackupClient, times(2)).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + @Test + fun `explicit coalesced request survives observer cancellation before dispatch`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + var beforeDispatch: (() -> Unit)? = null + var intercepted = false + val delegate = StandardTestDispatcher(testScheduler) + + @OptIn(InternalCoroutinesApi::class) + val dispatcher = object : CoroutineDispatcher(), Delay by (delegate as Delay) { + override fun dispatch(context: CoroutineContext, block: Runnable) { + val hook = beforeDispatch + beforeDispatch = null + hook?.invoke() + delegate.dispatch(context, block) + } + } + sut = createSut(dispatcher = dispatcher) + whenever(cacheStore.backupStatuses).thenReturn( + flow { + if (!intercepted) { + beforeDispatch = { + intercepted = true + sut.scheduleFullBackup() + sut.stopObservingBackups() + } + } + emit(statuses.value) + beforeDispatch = null + awaitCancellation() + } + ) + try { + sut.startObservingBackups() + advanceTimeBy(5_000) + runCurrent() + assertTrue(intercepted) + verify(vssBackupClient, times(1)).putObject(eq(category.name), any()) + assertFalse(statuses.value.getValue(category).isRequired) } finally { - sut.stopObservingBackups() + beforeDispatch = null + sut.reset() } } @Test - fun `spark exit backup defers, without uploading, until Spark has connected and synced`() = test { - whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + 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(dispatcher = dispatcher) + whenever(cacheStore.update(any())).doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + if (holdCleanup && !cleanupEntered) { + cleanupEntered = true + finishCleanup.await() + } + statuses.update { transform(AppCacheData(backupStatuses = it)).backupStatuses } + } + 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() - assertIs(sut.triggerBackup(BackupCategory.SPARK_EXIT).exceptionOrNull()) + 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() + } + } + } - verify(vssBackupClient, never()).getObject(BackupCategory.SPARK_EXIT.name) - verify(vssBackupClient, never()).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + @Test + fun `retired queued full request cannot hide a new owner request`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + sut.scheduleFullBackup() + connectionRecoveryFixture(settingsStore, keychain, vssClients).withIdentityChange { } + sut.scheduleFullBackup() + advanceTimeBy(5_000) + runCurrent() + verify(vssBackupClient, times(1)).putObject(eq(category.name), any()) + assertFalse(statuses.value.getValue(category).isRequired) + sut.reset() } @Test - fun `first spark exit backup merges the stored one into Spark before replacing it`() = test { - val stored = SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "stored") - whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) - whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( - Result.success( - VssItem( - key = BackupCategory.SPARK_EXIT.name, - value = json.encodeToString(stored).toByteArray(), - version = 1, - ) - ) + fun `retired detached retry cannot upload for a replacement wallet`() = test { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(emptyMap()) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + whenever { vssBackupClient.putObject(eq(category.name), any()) }.thenReturn( + Result.failure(java.io.IOException("temporary transport failure")), ) - whenever(sparkRepo.exitBackup()).thenReturn( - Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "merged")) + assertTrue(sut.triggerBackup(category).isFailure) + connectionRecoveryFixture(settingsStore, keychain, vssClients).withIdentityChange { } + whenever { vssBackupClient.putObject(eq(category.name), any()) }.thenReturn( + Result.success(VssItem(key = category.name, value = byteArrayOf(), version = 1)), ) - - sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() - - inOrder(sparkRepo, vssBackupClient) { - verify(sparkRepo).mergeRemoteExitBackup(stored) - verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) - } + advanceTimeBy(120_000) + runCurrent() + verify(vssBackupClient, times(1)).putObject(eq(category.name), any()) + assertTrue(statuses.value.getValue(category).isRequired) + sut.triggerBackup(category).getOrThrow() + verify(vssBackupClient, times(2)).putObject(eq(category.name), any()) + assertFalse(statuses.value.getValue(category).isRequired) + sut.reset() } @Test - fun `stored spark exit data spark can't import is kept apart and the upload goes through`() = test { - val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "v9")) - .toByteArray() - whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) - whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) - .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) - whenever(sparkRepo.mergeRemoteExitBackup(anyOrNull())) - .thenReturn(Result.failure(SparkError.ExitStateUnimportable())) - whenever(sparkRepo.exitBackup()).thenReturn( - Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) - ) - - sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() - - inOrder(sparkRepo, vssBackupClient) { - verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) - verify(sparkRepo).skipUnimportableRemoteExitState("v9") - verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + fun `replacement waits for consumed settings write before restarting observation`() = 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 replaced = false + var crossed = false + var holdNext = true + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + if (holdNext) { + holdNext = false + entered.complete(Unit) + release.await() + crossed = replaced + } + statuses.update { current -> transform(AppCacheData(backupStatuses = current)).backupStatuses } + } + settingsData.update { it.copy(selectedCurrency = "EUR") } + entered.await() + val transition = async { + connectionRecoveryFixture(settingsStore, keychain, vssClients).withIdentityChange { replaced = true } + } + try { + runCurrent() + assertFalse(transition.isCompleted) + assertFalse(replaced) + release.complete(Unit) + transition.await() + runCurrent() + assertFalse(crossed) + assertTrue(statuses.value.getValue(category).isRequired) + advanceTimeBy(5_000) + runCurrent() + verify(vssBackupClient, times(1)).putObject(eq(category.name), any()) + verify(vssBackupClient, times(2)).setupWithRetry(any(), any(), any()) + } finally { + release.complete(Unit) + transition.join() + sut.reset() } } @Test - fun `stored spark exit data that doesn't parse is kept apart and the upload goes through`() = test { - val stored = "not exit data".toByteArray() - whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) - whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) - .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) - whenever(sparkRepo.exitBackup()).thenReturn( - Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) - ) - - sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + fun `retiring explicit payload drains before credential change without upload`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + var replaced = false + whenever { activityRepo.getActivities() }.doSuspendableAnswer { + entered.complete(Unit) + withContext(NonCancellable) { release.await() } + Result.success(emptyList()) + } + val manual = async { sut.triggerBackup(BackupCategory.ACTIVITY) } + entered.await() + val transition = async { + connectionRecoveryFixture(settingsStore, keychain, vssClients).withIdentityChange { replaced = true } + } + try { + runCurrent() + assertFalse(transition.isCompleted) + assertFalse(replaced) + release.complete(Unit) + transition.await() + assertTrue(manual.await().isFailure) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.ACTIVITY.name), any()) + } finally { + release.complete(Unit) + transition.join() + sut.reset() + } + } - verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) - verify(sparkRepo, never()).mergeRemoteExitBackup(anyOrNull()) - verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + @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 `a rejected spark exit copy already set aside is not uploaded again`() = test { - val stored = "not exit data".toByteArray() - stubUnreadableStoredExit(stored) - val key = BackupRepo.rejectedExitKey(stored) - whenever( - vssBackupClient.getObject(key) - ).thenReturn(Result.success(VssItem(key = key, value = stored, version = 1))) + 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() + } + } - sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + @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()) + } - verify(vssBackupClient, never()).putObject(argThat { startsWith(BackupRepo.SPARK_EXIT_REJECTED_KEY) }, any()) - verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.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 `each rejected spark exit copy goes under its own digest key and never the plain key`() = test { - val stored = "not exit data".toByteArray() - stubUnreadableStoredExit(stored) + 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()) + } - sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + private suspend fun TestScope.assertSetupTimeoutRetries( + category: BackupCategory, + upload: suspend () -> Result, + ) { + sut = createSut(dispatcher = StandardTestDispatcher(testScheduler)) + var setupAttempts = 0 + 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 = upload() + assertTrue(result.exceptionOrNull()?.isTemporaryBackupFailure() == true, result.toString()) + verify(vssBackupClient, never()).putObject(any(), any()) + 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()) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + sut.reset() + } + } - val digest = MessageDigest.getInstance("SHA-256").digest(stored).joinToString("") { "%02x".format(it) } - verify(vssBackupClient).putObject("${BackupRepo.SPARK_EXIT_REJECTED_KEY}_${digest.take(16)}", stored) - verify(vssBackupClient, never()).putObject(eq(BackupRepo.SPARK_EXIT_REJECTED_KEY), any()) + @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) + release.complete(Unit) + reset.await() + assertTrue(backup.await().isFailure) + verify(vssBackupClient, never()).putObject(any(), any()) + } finally { + release.complete(Unit) + backup.cancelAndJoin() + sut.reset() + } } - private suspend fun stubUnreadableStoredExit(stored: ByteArray) { - whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) - whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) - .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) - whenever(sparkRepo.exitBackup()).thenReturn( - Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) - ) + @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 `staged exit data spark rejects is set aside as the stored backup that holds it`() = test { - val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "v9")) - .toByteArray() - whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) - .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) - whenever(sparkRepo.importStagedExitState()).thenReturn(StagedExitImport.Rejected("v9", "regtest")) - whenever(sparkRepo.exitBackup()).thenReturn( - Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) - ) + 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.SPARK_EXIT).getOrThrow() + sut.triggerBackup(BackupCategory.BLOCKTANK).getOrThrow() - inOrder(sparkRepo, vssBackupClient) { - verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) - verify(sparkRepo).discardStagedExitState("v9") - verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + 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 `staged exit data spark rejects is set aside on its own once the stored backup moved on`() = test { - val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "newer")) - .toByteArray() - whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) - .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) - whenever(sparkRepo.importStagedExitState()).thenReturn(StagedExitImport.Rejected("v9", "regtest")) - whenever(sparkRepo.exitBackup()).thenReturn( - Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) - ) + 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()) + } - sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + @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()) - val kept = argumentCaptor() - verify( - vssBackupClient - ).putObject(argThat { startsWith("${BackupRepo.SPARK_EXIT_REJECTED_KEY}_") }, kept.capture()) - assertEquals( - SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "v9"), - json.decodeFromString(String(kept.firstValue)), - ) - verify(sparkRepo).discardStagedExitState("v9") - verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + stubMetadataBackupReads() + sut.triggerBackup(BackupCategory.METADATA).getOrThrow() + verify(vssBackupClient).putObject(eq(BackupCategory.METADATA.name), any()) } @Test - fun `staged exit data spark rejects merges the stored backup another device replaced before the upload`() = test { - val newer = SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "newer") - whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( - Result.success( - VssItem( - key = BackupCategory.SPARK_EXIT.name, - value = json.encodeToString(newer).toByteArray(), - version = 2 - ) - ) - ) - // A merge already ran in this session, before another device stored newer exit data. - mergeFlagFollowsDiscard(hasMerged = true) - whenever(sparkRepo.importStagedExitState()).thenReturn(StagedExitImport.Rejected("v9", "regtest")) - whenever(sparkRepo.exitBackup()).thenReturn( - Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) - ) - - sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + 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()) - inOrder(sparkRepo, vssBackupClient) { - verify(sparkRepo).mergeRemoteExitBackup(newer) - verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) - } + stubMetadataBackupReads() + sut.triggerBackup(BackupCategory.METADATA).getOrThrow() + verify(vssBackupClient).putObject(eq(BackupCategory.METADATA.name), any()) } @Test - fun `a rejected staged copy dropped before a failed merge still merges on the next upload`() = test { - val newer = SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "other device") - val stored = VssItem( - key = BackupCategory.SPARK_EXIT.name, - value = json.encodeToString(newer).toByteArray(), - version = 2 - ) - mergeFlagFollowsDiscard(hasMerged = true) - whenever(sparkRepo.importStagedExitState()) - .thenReturn(StagedExitImport.Rejected("v9", "regtest"), StagedExitImport.NothingStaged) - whenever(sparkRepo.exitBackup()).thenReturn( - Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) - ) - // The copy is set aside and dropped, then the read for the merge fails. - whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( - Result.success(stored), - Result.failure(IllegalStateException("offline")), - Result.success(stored), - ) - assertTrue(sut.triggerBackup(BackupCategory.SPARK_EXIT).isFailure) + 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()) - sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + 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) + } - inOrder(sparkRepo, vssBackupClient) { - verify(sparkRepo).mergeRemoteExitBackup(newer) - verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + @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 `stored exit data replaced while unreadable data was set aside is merged before the upload`() = test { - val unreadable = "not exit data".toByteArray() - val replaced = SparkExitBackupV1(createdAt = 600, network = "regtest", exitState = "other device") - whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) - whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( - Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = unreadable, version = 1)), - Result.success( - VssItem( - key = BackupCategory.SPARK_EXIT.name, - value = json.encodeToString(replaced).toByteArray(), - version = 2 - ) - ), - ) - whenever(sparkRepo.exitBackup()).thenReturn( - Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) - ) - - sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() - - inOrder(sparkRepo, vssBackupClient) { - verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(unreadable), unreadable) - verify(sparkRepo).mergeRemoteExitBackup(replaced) - verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) - } - verify(sparkRepo, never()).skipUnimportableRemoteExitState(anyOrNull()) + fun `the latest backup time skips the spark exit data`() { + assertFalse(BackupCategory.SPARK_EXIT in BackupRepo.LATEST_BACKUP_TIME_CATEGORIES) + assertTrue(BackupCategory.WALLET in BackupRepo.LATEST_BACKUP_TIME_CATEGORIES) } @Test - fun `a spark exit merge that fails for another reason still blocks the upload`() = test { - val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "v1")) - .toByteArray() - whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) - whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) - .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) - whenever(sparkRepo.mergeRemoteExitBackup(anyOrNull())).thenReturn(Result.failure(AppError("not connected"))) - whenever(sparkRepo.exitBackup()).thenReturn( - Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) - ) + fun `restore marker storage reads leave Main responsive`() = test { + val entered = CompletableDeferred() + val release = CountDownLatch(1) + val mainThread = Thread.currentThread() + whenever(keychain.exists(Keychain.Key.PAYKIT_PENDING_BACKUP_RESTORE.name)).thenAnswer { + entered.complete(Thread.currentThread()) + check(release.await(5, TimeUnit.SECONDS)) { "Marker read was not released" } + false + } + Executors.newSingleThreadExecutor().asCoroutineDispatcher().use { ioDispatcher -> + sut = createSut(dispatcher = ioDispatcher) + try { + val read = async(Dispatchers.Main) { sut.hasPendingWalletRestore() } + val storageThread = withContext(Dispatchers.Default) { + withTimeout(5.seconds) { entered.await() } + } + assertNotEquals(mainThread, storageThread) + assertTrue(async(Dispatchers.Main) { true }.await()) + assertFalse(read.isCompleted) - assertTrue(sut.triggerBackup(BackupCategory.SPARK_EXIT).isFailure) + release.countDown() - verify(vssBackupClient, never()).putObject(argThat { startsWith(BackupRepo.SPARK_EXIT_REJECTED_KEY) }, any()) - verify(vssBackupClient, never()).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + assertFalse(read.await()) + } finally { + release.countDown() + } + } } @Test - fun `spark exit backup never replaces a stored one it could not read`() = test { - whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) - whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) - .thenReturn(Result.failure(AppError("unreachable"))) - whenever(sparkRepo.exitBackup()).thenReturn( - Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) - ) - - assertTrue(sut.triggerBackup(BackupCategory.SPARK_EXIT).isFailure) + fun `spark exit backup uploads the exported state and restores it before the wallet`() = test { + val backup = SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "{\"pedigrees\":[]}") + whenever(sparkRepo.exitBackup()).thenReturn(Result.success(backup)) - verify(sparkRepo, never()).mergeRemoteExitBackup(anyOrNull()) - verify(vssBackupClient, never()).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) - } + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() - @Test - fun `a restore sets aside spark exit data it can't read and reports it not restored`() = test { - val stored = "not exit data".toByteArray() - whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) - .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + val data = argumentCaptor() + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), data.capture()) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( + Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = data.firstValue, version = 1)) + ) - val failed = sut.performFullRestoreFromLatestBackup().getOrThrow() + sut.performFullRestoreFromLatestBackup().getOrThrow() - assertTrue(BackupCategory.SPARK_EXIT in failed) - verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) - verify(sparkRepo, never()).restoreExitBackup(any(), any()) - verify(cacheStore, never()).updateBackupStatus(eq(BackupCategory.SPARK_EXIT), any()) + inOrder(sparkRepo, vssBackupClient) { + verify(sparkRepo).restoreExitBackup(backup, 0) + verify(vssBackupClient).getObject(BackupCategory.WALLET.name) + } } @Test - fun `a failed spark exit restore is reported as an incomplete restore`() = test { - whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) - .thenReturn(Result.failure(AppError("unreachable"))) - - val failed = sut.performFullRestoreFromLatestBackup().getOrThrow() + fun `spark exit backup uploads when Spark was ready before observing started`() = test { + val statuses = MutableStateFlow(mapOf(BackupCategory.SPARK_EXIT to BackupItemStatus(synced = 1, required = 1))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + whenever(sparkRepo.state).thenReturn( + MutableStateFlow(SparkState(isSupported = true, isReady = true, hasSynced = true)) + ) + val backup = SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "state") + whenever(sparkRepo.exitBackup()).thenReturn(Result.success(backup)) + try { + sut.startObservingBackups() + runCurrent() + advanceTimeBy(61_000) + runCurrent() - assertTrue(BackupCategory.SPARK_EXIT in failed) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } finally { + sut.stopObservingBackups() + } } @Test - fun `wallet backup waits for submission and includes the latest pending state`() = test { - val statuses = MutableStateFlow( - mapOf(BackupCategory.WALLET to BackupItemStatus(required = 1_000)), - ) - val allowClear = CompletableDeferred(Unit) - stubBackupStatuses(statuses, allowClear) {} + fun `spark exit backup does not upload again when observing restarts on foreground`() = test { + val statuses = MutableStateFlow(mapOf(BackupCategory.SPARK_EXIT to BackupItemStatus(synced = 1, required = 1))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} stubBackupObservers() - val proofVersion = MutableStateFlow(0L) - whenever(paykitPaymentProofStore.backupStateVersion).thenReturn(proofVersion) - paymentSubmissionActive.value = true + whenever(sparkRepo.state).thenReturn( + MutableStateFlow(SparkState(isSupported = true, isReady = true, hasSynced = true)) + ) + val backup = SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "state") + whenever(sparkRepo.exitBackup()).thenReturn(Result.success(backup)) try { sut.startObservingBackups() runCurrent() - advanceTimeBy(5_000) - runCurrent() - proofVersion.value++ - runCurrent() - proofVersion.value++ + advanceTimeBy(61_000) runCurrent() + sut.stopObservingBackups() - assertTrue(statuses.value.getValue(BackupCategory.WALLET).isRequired) - verify(privatePaykitRepo, never()).backupSnapshot() - verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) - - whenever(privatePaykitRepo.backupSnapshot()).thenReturn( - Result.success(PrivatePaykitBackupSnapshot("pending-write", 0)), - ) - paymentSubmissionActive.value = false + sut.startObservingBackups() + runCurrent() + advanceTimeBy(61_000) runCurrent() - val payload = argumentCaptor() - verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), payload.capture()) - assertEquals( - "pending-write", - json.decodeFromString(String(payload.firstValue)).paykitSdkBackupState, - ) - verify(paykitPaymentProofRepo).backupSnapshot() - verify(privatePaykitRepo).backupSnapshot() + verify(vssBackupClient, times(1)).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) } finally { sut.stopObservingBackups() } } @Test - fun `cancelled manual backup completes success and failure status writes`() = test { - for (uploadSucceeds in listOf(true, false)) { - val category = BackupCategory.SETTINGS - val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000))) - 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) { - statusWriteStarted.complete(Unit) - finishStatusWrite.await() - } - statuses.update { current -> current + (category to updated) } - } - val uploadResult = if (uploadSucceeds) { - Result.success(VssItem(key = category.name, value = byteArrayOf(), version = 1)) - } else { - Result.failure(BackupRepoTestError("upload failed")) - } - whenever(vssBackupClient.putObject(eq(category.name), any())).thenReturn(uploadResult) - - val backup = launch { sut.triggerBackup(category) } + fun `spark exit data that changed while observing was stopped uploads when observing restarts`() = test { + val statuses = MutableStateFlow(mapOf(BackupCategory.SPARK_EXIT to BackupItemStatus(synced = 1, required = 1))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + whenever(sparkRepo.state).thenReturn( + MutableStateFlow(SparkState(isSupported = true, isReady = true, hasSynced = true)) + ) + val backup = SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "state") + whenever(sparkRepo.exitBackup()).thenReturn(Result.success(backup)) + exitStateGeneration.value = 1L + try { + sut.startObservingBackups() runCurrent() - assertTrue(statusWriteStarted.isCompleted) - assertTrue(statuses.value.getValue(category).running) + advanceTimeBy(61_000) + runCurrent() + sut.stopObservingBackups() - backup.cancel() + exitStateGeneration.value = 2L + sut.startObservingBackups() + runCurrent() + advanceTimeBy(61_000) runCurrent() - assertFalse(backup.isCompleted) - finishStatusWrite.complete(Unit) - backup.join() - val status = statuses.value.getValue(category) - assertTrue(backup.isCancelled) - assertFalse(status.running) - assertEquals(if (uploadSucceeds) status.required else 0L, status.synced) - assertEquals(!uploadSucceeds, status.isRequired) + verify(vssBackupClient, times(2)).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } finally { + sut.stopObservingBackups() } } @Test - fun `cancelled manual wallet backup retains pending state and resumes automatically`() = test { - val statuses = MutableStateFlow( - mapOf(BackupCategory.WALLET to BackupItemStatus(required = 1_000)), - ) - stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} - stubBackupObservers() - paymentSubmissionActive.value = true - whenever(privatePaykitRepo.backupSnapshot()).doSuspendableAnswer { - paymentSubmissionActive.first { !it } - Result.success(PrivatePaykitBackupSnapshot("pending-write", 0)) - } + fun `spark connection backup survives a cancelled required-status write`() = test { + assertSparkBackupSurvivesOwnerRetirement(initiallyReady = false) + } - val backup = launch { sut.triggerBackup(BackupCategory.WALLET) } - runCurrent() - verify(privatePaykitRepo).backupSnapshot() - assertTrue(statuses.value.getValue(BackupCategory.WALLET).running) + @Test + fun `spark exit backup resumes when the pending restore clears`() = test { + assertSparkBackupResumesAfterRestore(expires = false) + } - backup.cancelAndJoin() + @Test + fun `spark exit backup resumes when the pending restore expires`() = test { + assertSparkBackupResumesAfterRestore(expires = true) + } - assertTrue(backup.isCancelled) - assertFalse(statuses.value.getValue(BackupCategory.WALLET).running) - assertTrue(statuses.value.getValue(BackupCategory.WALLET).isRequired) - verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) + @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() - paymentSubmissionActive.value = false runCurrent() - advanceTimeBy(5_000) + 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()) - val payload = argumentCaptor() - verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), payload.capture()) - assertEquals( + 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) + } + + @Test + fun `spark exit observation continues after a required-status storage failure`() = test { + val category = BackupCategory.SPARK_EXIT + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(synced = 1, required = 1))) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + whenever(sparkRepo.state).thenReturn( + MutableStateFlow(SparkState(isSupported = true, isReady = true, hasSynced = true)) + ) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "state")) + ) + var failRequiredWrite = true + whenever(cacheStore.update(any())).doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + val prior = statuses.value[category] ?: BackupItemStatus() + val updated = transform(AppCacheData(backupStatuses = statuses.value)) + val next = updated.backupStatuses[category] ?: BackupItemStatus() + if (failRequiredWrite && next.required > prior.required) { + failRequiredWrite = false + throw IOException("status storage unavailable") + } + statuses.value = updated.backupStatuses + } + try { + sut.startObservingBackups() + runCurrent() + assertFalse(failRequiredWrite) + exitStateGeneration.value = 1L + runCurrent() + advanceTimeBy(61_000) + runCurrent() + verify(vssBackupClient).putObject(eq(category.name), any()) + } finally { + sut.stopObservingBackups() + } + } + + private suspend fun TestScope.assertSparkBackupSurvivesOwnerRetirement( + initiallyReady: Boolean, + ) { + 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(isSupported = true, isReady = initiallyReady, hasSynced = initiallyReady) + ) + whenever(sparkRepo.state).thenReturn(sparkState) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "state")) + ) + val requiredWrite = CompletableDeferred() + var holdRequiredWrite = false + whenever(cacheStore.update(any())).doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + val prior = statuses.value[category] ?: BackupItemStatus() + val updated = transform(AppCacheData(backupStatuses = statuses.value)) + val next = updated.backupStatuses[category] ?: BackupItemStatus() + if (holdRequiredWrite && next.required > prior.required) { + requiredWrite.complete(Unit) + awaitCancellation() + } + statuses.value = updated.backupStatuses + } + try { + sut.startObservingBackups() + runCurrent() + advanceTimeBy(61_000) + runCurrent() + holdRequiredWrite = true + if (initiallyReady) { + exitStateGeneration.value = 1L + } else { + sparkState.value = SparkState(isSupported = true, isReady = true, hasSynced = true) + } + runCurrent() + assertTrue(requiredWrite.isCompleted) + holdRequiredWrite = false + val recovery = connectionRecoveryFixture(settingsStore, keychain, vssClients) + assertFailsWith { + recovery.withIdentityChange { throw BackupRepoTestError("credentials unchanged") } + } + runCurrent() + advanceTimeBy(61_000) + runCurrent() + val expectedUploads = if (initiallyReady) 2 else 1 + verify(vssBackupClient, times(expectedUploads)).putObject(eq(category.name), any()) + + sut.stopObservingBackups() + sut.startObservingBackups() + runCurrent() + advanceTimeBy(61_000) + runCurrent() + verify(vssBackupClient, times(expectedUploads)).putObject(eq(category.name), any()) + } finally { + sut.stopObservingBackups() + } + } + + @Test + fun `spark exit backup defers, without uploading, until Spark has connected and synced`() = test { + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + + assertIs(sut.triggerBackup(BackupCategory.SPARK_EXIT).exceptionOrNull()) + + verify(vssBackupClient, never()).getObject(BackupCategory.SPARK_EXIT.name) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + + @Test + fun `first spark exit backup merges the stored one into Spark before replacing it`() = test { + val stored = SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "stored") + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( + Result.success( + VssItem( + key = BackupCategory.SPARK_EXIT.name, + value = json.encodeToString(stored).toByteArray(), + version = 1, + ) + ) + ) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "merged")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + inOrder(sparkRepo, vssBackupClient) { + verify(sparkRepo).mergeRemoteExitBackup(stored) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + } + + @Test + fun `spark exit backup never replaces a stored one it could not read`() = test { + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.failure(AppError("unreachable"))) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + assertTrue(sut.triggerBackup(BackupCategory.SPARK_EXIT).isFailure) + + verify(sparkRepo, never()).mergeRemoteExitBackup(anyOrNull()) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + + @Test + fun `a failed spark exit restore is reported as an incomplete restore`() = test { + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.failure(AppError("unreachable"))) + + val failed = sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertTrue(BackupCategory.SPARK_EXIT in failed) + } + + @Test + fun `wallet backup waits for submission and includes the latest pending state`() = test { + val statuses = MutableStateFlow( + mapOf(BackupCategory.WALLET to BackupItemStatus(required = 1_000)), + ) + val allowClear = CompletableDeferred(Unit) + stubBackupStatuses(statuses, allowClear) {} + stubBackupObservers() + val proofVersion = MutableStateFlow(0L) + whenever(paykitPaymentProofStore.backupStateVersion).thenReturn(proofVersion) + paymentSubmissionActive.value = true + try { + sut.startObservingBackups() + runCurrent() + advanceTimeBy(5_000) + runCurrent() + proofVersion.value++ + runCurrent() + proofVersion.value++ + 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()) + + whenever(privatePaykitRepo.backupSnapshot()).thenReturn( + Result.success(PrivatePaykitBackupSnapshot("pending-write", 0)), + ) + paymentSubmissionActive.value = false + runCurrent() + + val payload = argumentCaptor() + verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), payload.capture()) + assertEquals( + "pending-write", + json.decodeFromString(String(payload.firstValue)).paykitSdkBackupState, + ) + verify(paykitPaymentProofRepo).backupSnapshot() + verify(privatePaykitRepo).backupSnapshot() + } finally { + sut.stopObservingBackups() + } + } + + @Test + fun `cancelled manual backup completes success and failure status writes`() = test { + for (uploadSucceeds in listOf(true, false)) { + val category = BackupCategory.SETTINGS + val statuses = MutableStateFlow(mapOf(category to BackupItemStatus(required = 1_000))) + val statusWriteStarted = CompletableDeferred() + val finishStatusWrite = CompletableDeferred() + whenever(cacheStore.backupStatuses).thenReturn(statuses) + 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.value = updated + } + val uploadResult = if (uploadSucceeds) { + Result.success(VssItem(key = category.name, value = byteArrayOf(), version = 1)) + } else { + Result.failure(BackupRepoTestError("upload failed")) + } + whenever(vssBackupClient.putObject(eq(category.name), any())).thenReturn(uploadResult) + + val backup = launch { sut.triggerBackup(category) } + runCurrent() + assertTrue(statusWriteStarted.isCompleted) + assertTrue(statuses.value.getValue(category).running) + + backup.cancel() + runCurrent() + assertFalse(backup.isCompleted) + finishStatusWrite.complete(Unit) + backup.join() + + val status = statuses.value.getValue(category) + assertTrue(backup.isCancelled) + assertFalse(status.running) + assertEquals(if (uploadSucceeds) status.required else 0L, status.synced) + assertEquals(!uploadSucceeds, status.isRequired) + } + } + + @Test + fun `cancelled manual wallet backup retains pending state and resumes automatically`() = test { + val statuses = MutableStateFlow( + mapOf(BackupCategory.WALLET to BackupItemStatus(required = 1_000)), + ) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + stubBackupObservers() + paymentSubmissionActive.value = true + whenever(privatePaykitRepo.backupSnapshot()).doSuspendableAnswer { + paymentSubmissionActive.first { !it } + Result.success(PrivatePaykitBackupSnapshot("pending-write", 0)) + } + + val backup = launch { sut.triggerBackup(BackupCategory.WALLET) } + runCurrent() + verify(privatePaykitRepo).backupSnapshot() + assertTrue(statuses.value.getValue(BackupCategory.WALLET).running) + + backup.cancelAndJoin() + + assertTrue(backup.isCancelled) + assertFalse(statuses.value.getValue(BackupCategory.WALLET).running) + assertTrue(statuses.value.getValue(BackupCategory.WALLET).isRequired) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) + + try { + sut.startObservingBackups() + paymentSubmissionActive.value = false + runCurrent() + advanceTimeBy(5_000) + runCurrent() + + val payload = argumentCaptor() + verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), payload.capture()) + assertEquals( "pending-write", json.decodeFromString(String(payload.firstValue)).paykitSdkBackupState, ) @@ -1117,22 +1986,6 @@ class BackupRepoTest : BaseUnitTest() { } } - @Test - fun `restore brings back each identity's sent receipts`() = test { - val sent = mapOf("pubky" + "y".repeat(52) to setOf("receipt-1")) - stubWalletBackup( - paykitPaymentState = PaykitPaymentStateBackup( - subscriptions = emptyMap(), - pendingProofs = emptyList(), - sentReceipts = sent, - ), - ) - - sut.performFullRestoreFromLatestBackup().getOrThrow() - - verify(paykitOutboundDeliveryStore).restoreBackup(sent) - } - @Test fun `restore brings back each identity's allowance journal and history`() = test { val identity = "pubky" + "z".repeat(52) @@ -1513,16 +2366,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 @@ -1789,7 +2646,7 @@ class BackupRepoTest : BaseUnitTest() { verify(settingsStore, never()).update(any()) verify(keychain, never()).delete(Keychain.Key.PAYKIT_PENDING_BACKUP_RESTORE.name) - sut = createSut(createReservationRepo(reservationStore)) + sut = createSut(reservationRepo = createReservationRepo(reservationStore)) assertTrue(sut.hasPendingWalletRestore()) assertTrue(keychain.exists(Keychain.Key.USDT_PENDING_BACKUP_RESTORE.name)) assertTrue(sut.triggerBackup(BackupCategory.WALLET).isFailure) @@ -1812,7 +2669,7 @@ class BackupRepoTest : BaseUnitTest() { val restartedReservations = createReservationRepo(reservationStore) assertTrue(restartedReservations.isUnavailableForReusableReceive(publicAddress)) - sut = createSut(restartedReservations) + sut = createSut(reservationRepo = restartedReservations) sut.triggerBackup(BackupCategory.WALLET).getOrThrow() val uploaded = argumentCaptor() @@ -1832,7 +2689,7 @@ class BackupRepoTest : BaseUnitTest() { assertTrue(sut.hasPendingWalletRestore()) assertFalse(settingsData.value.backupVerified) - sut = createSut(createReservationRepo(reservationStore)) + sut = createSut(reservationRepo = createReservationRepo(reservationStore)) whenever(vssBackupClient.getObject(BackupCategory.METADATA.name)) .thenReturn(Result.failure(BackupRepoTestError("metadata download unavailable"))) @@ -1845,7 +2702,7 @@ class BackupRepoTest : BaseUnitTest() { assertFalse(sut.hasPendingWalletRestore()) val restartedReservations = createReservationRepo(reservationStore) assertTrue(restartedReservations.isUnavailableForReusableReceive(publicAddress)) - sut = createSut(restartedReservations) + sut = createSut(reservationRepo = restartedReservations) sut.triggerBackup(BackupCategory.WALLET).getOrThrow() val uploaded = argumentCaptor() @@ -1933,7 +2790,7 @@ class BackupRepoTest : BaseUnitTest() { assertFalse(reservations.preparePublicAddressRestore()) reservations.capturePublicAddressRestoreSource(metadata.toByteArray()) val source = pendingPublicAddressRestoreRecord("source") - sut = createSut(createReservationRepo(reservationStore)) + sut = createSut(reservationRepo = createReservationRepo(reservationStore)) for (download in listOf(null, "$metadata ")) { whenever(vssBackupClient.getObject(BackupCategory.METADATA.name)).thenReturn( @@ -1983,7 +2840,7 @@ class BackupRepoTest : BaseUnitTest() { assertTrue(sut.triggerBackup(BackupCategory.METADATA).isFailure) verify(vssBackupClient, never()).putObject(any(), any()) - sut = createSut(createReservationRepo(reservationStore)) + sut = createSut(reservationRepo = createReservationRepo(reservationStore)) stubMetadataRestore(envelope = metadataEnvelope()) sut.performFullRestoreFromLatestBackup().getOrThrow() @@ -2005,7 +2862,7 @@ class BackupRepoTest : BaseUnitTest() { assertTrue(reservationStore.data.first().quarantinedPublicAddresses.isEmpty()) verify(vssBackupClient, never()).getObject(BackupCategory.WALLET.name) - sut = createSut(createReservationRepo(reservationStore)) + sut = createSut(reservationRepo = createReservationRepo(reservationStore)) val missingMetadata = listOf( Result.failure(BackupRepoTestError("metadata download unavailable")), Result.success(null), @@ -2062,7 +2919,7 @@ class BackupRepoTest : BaseUnitTest() { assertFalse(settingsData.value.backupVerified) pendingPublicAddressRestoreRecord("source") assertTrue(reservationStore.data.first().quarantinedPublicAddresses.isEmpty()) - sut = createSut(createReservationRepo(reservationStore)) + sut = createSut(reservationRepo = createReservationRepo(reservationStore)) whenever(vssBackupClient.getObject(BackupCategory.METADATA.name)) .thenReturn(Result.failure(BackupRepoTestError("metadata download unavailable"))) @@ -2317,7 +3174,7 @@ class BackupRepoTest : BaseUnitTest() { assertEquals(setOf(publicAddress), reservationStore.data.first().quarantinedPublicAddresses) assertEquals(publicAddress, pendingPublicAddressRestoreRecord("address")["address"]?.jsonPrimitive?.content) - sut = createSut(createReservationRepo(reservationStore)) + sut = createSut(reservationRepo = createReservationRepo(reservationStore)) whenever(vssBackupClient.getObject(BackupCategory.METADATA.name)) .thenReturn(Result.failure(BackupRepoTestError("metadata download unavailable"))) sut.performFullRestoreFromLatestBackup().getOrThrow() @@ -2399,6 +3256,85 @@ class BackupRepoTest : BaseUnitTest() { assertFalse(cacheData.value.backupStatuses.getValue(BackupCategory.METADATA).isRequired) } + @Test + fun `wallet acknowledgement automatically resumes blocked metadata observation`() = test { + val publicAddress = "bcrt1qpublic" + val reservationStore = stubPublicAddressRestore(publicAddress) + val legacyMetadata = envelopeWithRawField( + base = metadataEnvelope(cache = AppCacheData(onchainAddress = publicAddress)), + field = "tagMetadata", + rawJson = LEGACY_METADATA_JSON, + ) + val remote = mutableMapOf( + BackupCategory.METADATA.name to legacyMetadata.toByteArray(), + BackupCategory.WALLET.name to """{"version":1,"createdAt":123,"transfers":[]}""".toByteArray(), + ) + whenever(vssBackupClient.getObject(any())).doSuspendableAnswer { + val key = it.getArgument(0) + Result.success(remote[key]?.let { value -> VssItem(key = key, value = value, version = 1) }) + } + var walletUploadAvailable = false + val uploadedCategories = mutableListOf() + whenever(vssBackupClient.putObject(any(), any())).doSuspendableAnswer { + val key = it.getArgument(0) + val value = it.getArgument(1) + if (key == BackupCategory.WALLET.name && !walletUploadAvailable) { + Result.failure(BackupRepoTestError("wallet upload unavailable")) + } else { + remote[key] = value + uploadedCategories += key + Result.success(VssItem(key = key, value = value, version = 1)) + } + } + + sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertTrue(settingsData.value.backupVerified) + assertFalse(sut.hasPendingWalletRestore()) + assertEquals(setOf(publicAddress), reservationStore.data.first().quarantinedPublicAddresses) + assertEquals(legacyMetadata, remote.getValue(BackupCategory.METADATA.name).decodeToString()) + assertTrue(cacheData.value.backupStatuses.getValue(BackupCategory.WALLET).isRequired) + assertTrue(cacheData.value.backupStatuses.getValue(BackupCategory.METADATA).isRequired) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) + + sut.triggerBackup(BackupCategory.METADATA) + assertTrue(sut.triggerBackup(BackupCategory.WALLET).isFailure) + sut.triggerBackup(BackupCategory.METADATA) + assertEquals(legacyMetadata, remote.getValue(BackupCategory.METADATA.name).decodeToString()) + assertTrue(cacheData.value.backupStatuses.getValue(BackupCategory.WALLET).isRequired) + assertTrue(cacheData.value.backupStatuses.getValue(BackupCategory.METADATA).isRequired) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) + + stubBackupObservers() + sut.startObservingBackups() + runCurrent() + advanceTimeBy(5_000) + runCurrent() + assertEquals(legacyMetadata, remote.getValue(BackupCategory.METADATA.name).decodeToString()) + + try { + walletUploadAvailable = true + sut.triggerBackup(BackupCategory.WALLET).getOrThrow() + val wallet = json.decodeFromString( + remote.getValue(BackupCategory.WALLET.name).decodeToString(), + ) + assertEquals(listOf(publicAddress), wallet.publicPaykitLegacyAddresses) + advanceTimeBy(5_000) + runCurrent() + assertEquals(1, uploadedCategories.count { it == BackupCategory.METADATA.name }) + val metadata = json.decodeFromString( + remote.getValue(BackupCategory.METADATA.name).decodeToString(), + ) + assertEquals("", metadata.cache.onchainAddress) + assertEquals(BackupCategory.WALLET.name, uploadedCategories.first()) + assertTrue(uploadedCategories.indexOf(BackupCategory.METADATA.name) > 0) + assertFalse(cacheData.value.backupStatuses.getValue(BackupCategory.WALLET).isRequired) + assertFalse(cacheData.value.backupStatuses.getValue(BackupCategory.METADATA).isRequired) + } finally { + sut.reset() + } + } + @Test fun `metadata restore waits for admitted metadata capture and upload to drain`() = test { stubMetadataBackupReads() @@ -2486,6 +3422,139 @@ 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( + 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)) @@ -2524,1305 +3593,3019 @@ class BackupRepoTest : BaseUnitTest() { } @Test - fun `busy wallet backup retries after observation pauses and resumes`() = test { - whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(3_000)) - whenever { privatePaykitRepo.backupSnapshot() } - .thenReturn(Result.failure(PaykitException.SharedStateBusy("shared_state_busy", "locked"))) - .thenReturn(Result.success(PrivatePaykitBackupSnapshot(null, 0))) - val backupStatuses = MutableStateFlow( - mapOf(BackupCategory.WALLET to BackupItemStatus(synced = 1_000, required = 2_000)) - ) + 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(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 { - sut.startObservingBackups() - runCurrent() - advanceTimeBy(5_000) runCurrent() - sut.stopObservingBackups() - advanceTimeBy(20_000) + release.complete(Unit) + resetJob?.await() runCurrent() - verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) - + assertTrue(statuses.value.getValue(category).isRequired) sut.startObservingBackups() - runCurrent() advanceTimeBy(5_000) runCurrent() - - verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), any()) + val payload = argumentCaptor() + verify(vssBackupClient).putObject(eq(category.name), payload.capture()) + assertTrue(payload.firstValue.decodeToString().contains("EUR")) + assertFalse(statuses.value.getValue(category).isRequired) } finally { - sut.stopObservingBackups() + release.complete(Unit) + resetJob?.join() + sut.reset() } } @Test - fun `busy wallet backup still warns once it stays pending past the failure window`() = test { - val startedAt = currentTime - whenever(clock.now()).thenAnswer { Instant.fromEpochMilliseconds(3_000 + currentTime - startedAt) } - whenever { privatePaykitRepo.backupSnapshot() } - .thenReturn(Result.failure(PaykitException.SharedStateBusy("shared_state_busy", "locked"))) - whenever(context.getString(R.string.settings__backup__failed_title)).thenReturn("Backup failed") - whenever(context.getString(R.string.settings__backup__failed_message)).thenReturn("Retrying") - val backupStatuses = MutableStateFlow( - mapOf(BackupCategory.WALLET to BackupItemStatus(synced = 1_000, required = 2_000)) - ) - val allowWalletClear = CompletableDeferred().apply { complete(Unit) } - stubBackupStatuses(backupStatuses, allowWalletClear) {} + 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 { - sut.startObservingBackups() runCurrent() - advanceTimeBy(31.minutes.inWholeMilliseconds) + assertFalse(reset.isCompleted) + verify(vssBackupClient, times(1)).setupWithRetry(any(), any(), any()) + reset.cancel() runCurrent() - - verify(context, atLeastOnce()).getString(R.string.settings__backup__failed_title) + assertFalse(reset.isCompleted) } finally { - sut.stopObservingBackups() + release.complete(Unit) + reset.join() } + verify(vssBackupClientLdk, never()).setup() } @Test - fun `start observing backs up stale required status after clearing running flag`() = test { - val backupStatuses = MutableStateFlow( - mapOf( - BackupCategory.WALLET to BackupItemStatus( - running = true, - synced = 1_000, - required = 2_000, - ), - ) - ) - val allowWalletClear = CompletableDeferred() - var delayedWalletClear = false - stubBackupStatuses(backupStatuses, allowWalletClear) { - delayedWalletClear = true - } + 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 { - sut.startObservingBackups() runCurrent() - verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) - - allowWalletClear.complete(Unit) + 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() - - assertTrue(delayedWalletClear) - verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), any()) + assertEquals(2, attempts) + assertFalse(statuses.value.getValue(category).running) + assertFalse(statuses.value.getValue(category).isRequired) } finally { - sut.stopObservingBackups() + release.complete(Unit) + sut.reset() } } @Test - fun `failed automatic backup waits for new required timestamp before retrying`() = test { - whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(3_000)) - whenever { vssBackupClient.putObject(eq(BackupCategory.SETTINGS.name), any()) } - .thenReturn(Result.failure(BackupRepoTestError("backup failed"))) - val backupStatuses = MutableStateFlow( + fun `settings changed during restart cleanup remain pending without another edit`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + val statuses = MutableStateFlow( mapOf( - BackupCategory.SETTINGS to BackupItemStatus( - synced = 1_000, - required = 2_000, - ), + BackupCategory.WIDGETS to BackupItemStatus(required = 1_000), + BackupCategory.SETTINGS to BackupItemStatus(required = 1_000, synced = 1_000), ) ) - val allowWalletClear = CompletableDeferred().apply { complete(Unit) } - stubBackupStatuses(backupStatuses, allowWalletClear) {} + 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 { - sut.startObservingBackups() runCurrent() - advanceTimeBy(5_000) + settingsData.update { it.copy(selectedCurrency = "EUR") } + runCurrent() + verify(vssBackupClient, never()).putObject(eq(BackupCategory.SETTINGS.name), any()) + release.complete(Unit) runCurrent() advanceTimeBy(5_000) runCurrent() - - verify(vssBackupClient).putObject(eq(BackupCategory.SETTINGS.name), any()) + 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 { - sut.stopObservingBackups() + release.complete(Unit) + sut.reset() } } @Test - fun `successful upload leaves a newer required snapshot queued`() = test { - whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(3_000)) - val backupStatuses = MutableStateFlow( + fun `temporary retry waits for other category cleanup during restart`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + val statuses = MutableStateFlow( mapOf( - BackupCategory.SETTINGS to BackupItemStatus( - synced = 1_000, - required = 2_000, - ), + BackupCategory.WIDGETS to BackupItemStatus(required = 1_000), + BackupCategory.WALLET to BackupItemStatus(required = 1_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, - ) - ) + 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() } } } - val allowWalletClear = CompletableDeferred().apply { complete(Unit) } - stubBackupStatuses(backupStatuses, allowWalletClear) {} - stubBackupObservers() - + 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 { - sut.startObservingBackups() + advanceTimeBy(20_000) runCurrent() - advanceTimeBy(5_000) + verify(privatePaykitRepo, times(1)).backupSnapshot() + verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) + release.complete(Unit) runCurrent() advanceTimeBy(5_000) runCurrent() - - verify(vssBackupClient, times(2)).putObject(eq(BackupCategory.SETTINGS.name), any()) + verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), any()) + assertFalse(statuses.value.getValue(BackupCategory.WALLET).isRequired) } finally { - sut.stopObservingBackups() + release.complete(Unit) + sut.reset() } } @Test - fun `failed automatic backup retries newer required timestamp`() = 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.failure(BackupRepoTestError("backup failed")) - } else { - Result.success( - VssItem( - key = BackupCategory.SETTINGS.name, - value = byteArrayOf(), - version = 1, - ) - ) + 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() } } } - val allowWalletClear = CompletableDeferred().apply { complete(Unit) } - stubBackupStatuses(backupStatuses, allowWalletClear) {} - stubBackupObservers() + Result.success(VssItem(key = category.name, value = byteArrayOf(), version = 1)) + } + sut.startObservingBackups() + advanceTimeBy(5_000) + runCurrent() + entered.await() + sut.stopObservingBackups() + sut.scheduleFullBackup() try { - sut.startObservingBackups() runCurrent() - advanceTimeBy(5_000) + 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() - - verify(vssBackupClient, times(2)).putObject(eq(BackupCategory.SETTINGS.name), any()) + assertEquals(2, attempts) + assertFalse(statuses.value.getValue(category).running) + assertFalse(statuses.value.getValue(category).isRequired) } finally { - sut.stopObservingBackups() + release.complete(Unit) + sut.reset() } } @Test - fun `full restore should fail when Paykit initialization fails without a saved SDK backup`() = test { - stubWalletBackup() - whenever { privatePaykitRepo.restoreBackup(anyOrNull()) } - .thenReturn(Result.failure(BackupRepoTestError("restore failed"))) - - val result = sut.performFullRestoreFromLatestBackup() - - assertTrue(result.isFailure) - verify(settingsStore, never()).update(any()) + 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 `wallet backup includes watch-only accounts and allocator state`() = test { - val account = watchOnlyAccount() - val allocationState = WatchOnlyAccountAllocationState( - highestAccountIndexByWallet = mapOf("0" to 7), - pendingAccountIndexByRequest = mapOf("0:pending" to 7), - ) - whenever { watchOnlyAccountStore.backupSnapshot() }.thenReturn( - WatchOnlyAccountBackupSnapshot(listOf(account), allocationState) - ) - val dataCaptor = argumentCaptor() - - sut.triggerBackup(BackupCategory.WALLET) - - verifyBlocking(vssBackupClient) { - putObject(eq(BackupCategory.WALLET.name), dataCaptor.capture()) + 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) + } 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() } - val payload = json.decodeFromString(dataCaptor.firstValue.decodeToString()) - assertEquals(listOf(account), payload.watchOnlyAccounts) - assertEquals(allocationState, payload.watchOnlyAccountAllocationState) } @Test - fun `wallet backup round trips public address exclusions alongside reservation floors`() = test { - val legacy = setOf("bcrt1qpublic") - val floors = mapOf("nativeSegwit" to 8) - whenever(privatePaykitAddressReservationRepo.quarantinedPublicAddressesSnapshot()).thenReturn(legacy) - whenever(privatePaykitAddressReservationRepo.backupSnapshot()).thenReturn(Result.success(floors)) - sut.triggerBackup(BackupCategory.WALLET).getOrThrow() - val bytes = argumentCaptor() - verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), bytes.capture()) - val payload = json.decodeFromString(bytes.firstValue.decodeToString()) - assertEquals(legacy.toList(), payload.publicPaykitLegacyAddresses) - assertEquals(floors, payload.privatePaykitHighestReservedReceiveIndexByAddressType) - whenever(vssBackupClient.getObject(BackupCategory.WALLET.name)).thenReturn( - Result.success(VssItem(BackupCategory.WALLET.name, bytes.firstValue, 1)), - ) - sut.performFullRestoreFromLatestBackup().getOrThrow() - verify(privatePaykitAddressReservationRepo).restoreBackup(floors, legacy) + 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 `wallet restore restores watch-only accounts and allocator before runtime reconciliation`() = test { - val account = watchOnlyAccount() - val allocationState = WatchOnlyAccountAllocationState( - highestAccountIndexByWallet = mapOf("0" to 7), - pendingAccountIndexByRequest = mapOf("0:pending" to 7), - ) - stubWalletBackup( - watchOnlyAccounts = listOf(account), - watchOnlyAccountAllocationState = allocationState, - ) - var accountsWereRestored = false - whenever { watchOnlyAccountRepo.restore(listOf(account), allocationState) }.thenAnswer { - accountsWereRestored = true - Unit - } - whenever { lightningService.reconcileWatchOnlyAccounts() }.thenAnswer { - assertTrue(accountsWereRestored) - Unit + 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() } - - val result = sut.performFullRestoreFromLatestBackup() - - assertTrue(result.isSuccess) - verifyBlocking(watchOnlyAccountRepo) { restore(listOf(account), allocationState) } - verifyBlocking(lightningService) { reconcileWatchOnlyAccounts() } } @Test - fun `full restore should fail when private Paykit reserved indexes fail to reconcile`() = test { - stubWalletBackup() - whenever { privatePaykitAddressReservationRepo.reconcileReservedIndexesWithLdk() } - .thenReturn(Result.failure(BackupRepoTestError("reconcile failed"))) - - val result = sut.performFullRestoreFromLatestBackup() - - assertTrue(result.isFailure) - verify(settingsStore, never()).update(any()) + 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 `legacy activity backup is migrated by core before decode`() = test { - stubWalletBackup() - stubActivityRestore() - - val result = sut.performFullRestoreFromLatestBackup() - - assertTrue(result.isSuccess) - verifyBlocking(activityRepo) { migrateBackupActivitiesJson(LEGACY_ACTIVITIES_JSON) } - verifyBlocking(activityRepo) { migrateBackupActivityTagsJson(LEGACY_TAGS_JSON) } - - val payloadCaptor = argumentCaptor() - verifyBlocking(activityRepo) { restoreFromBackup(payloadCaptor.capture()) } - assertEquals(listOf(defaultTag()), payloadCaptor.firstValue.activityTags) + 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 `legacy metadata backup is migrated by core before decode`() = test { - stubWalletBackup() - stubMetadataRestore() - - val result = sut.performFullRestoreFromLatestBackup() - - assertTrue(result.isSuccess) - verifyBlocking(preActivityMetadataRepo) { migrateBackupPreActivityMetadataJson(LEGACY_METADATA_JSON) } - - val metadataCaptor = argumentCaptor>() - verifyBlocking(preActivityMetadataRepo) { upsertPreActivityMetadata(metadataCaptor.capture()) } - assertEquals(listOf(preActivityMetadata()), metadataCaptor.firstValue) + 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 `iOS metadata backup restores the Pubky profile session`() = test { - stubWalletBackup() - val envelope = iosFixture("metadata") - stubMetadataRestore( - envelope = envelope, - migratedMetadataJson = json.parseToJsonElement(envelope).jsonObject["tagMetadata"].toString(), - ) - - val failed = sut.performFullRestoreFromLatestBackup().getOrThrow() - - assertEquals(emptySet(), failed) - verifyBlocking(pubkyRepo) { restoreSessionBackupState(PubkySessionBackupV1(PubkySessionBackupKind.LocalSeed)) } - val metadataCaptor = argumentCaptor>() - verifyBlocking(preActivityMetadataRepo) { upsertPreActivityMetadata(metadataCaptor.capture()) } - assertEquals(2, metadataCaptor.firstValue.size) + 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 `full restore reports the categories it could not restore`() = test { - stubWalletBackup() - stubMetadataRestore(envelope = iosFixture("metadata")) - whenever { pubkyRepo.restoreSessionBackupState(anyOrNull()) } - .thenReturn(Result.failure(BackupRepoTestError("pubky"))) - stubRestoreEnvelope(BackupCategory.BLOCKTANK, iosFixture("blocktank")) - whenever { blocktankRepo.restoreFromBackup(any()) }.thenReturn(Result.failure(BackupRepoTestError("core"))) - val widgetsEnvelope = json.encodeToString(WidgetsBackupV1(createdAt = 1, widgets = WidgetsData())) - stubRestoreEnvelope(BackupCategory.WIDGETS, widgetsEnvelope) - whenever { widgetsStore.restoreFromBackup(any()) }.thenReturn(Result.failure(BackupRepoTestError("disk"))) - - val failed = sut.performFullRestoreFromLatestBackup().getOrThrow() - - assertEquals(setOf(BackupCategory.METADATA, BackupCategory.WIDGETS, BackupCategory.BLOCKTANK), failed) + 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 `migrated backups are rewritten to vss after restore`() = test { - stubWalletBackup() - stubActivityRestore() - stubMetadataRestore() - - val result = sut.performFullRestoreFromLatestBackup() - - assertTrue(result.isSuccess) - verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.ACTIVITY.name), any()) } - verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.METADATA.name), any()) } + 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 `current backups are not rewritten after restore`() = test { - stubWalletBackup() - // Envelopes already carry wallet ids, so Core hands the slices back untouched. - stubActivityRestore(envelope = activityEnvelope(tags = listOf(defaultTag()))) - stubMetadataRestore(envelope = metadataEnvelope(metadata = listOf(preActivityMetadata()))) - - val result = sut.performFullRestoreFromLatestBackup() - - assertTrue(result.isSuccess) - verify(vssBackupClient, never()).putObject(eq(BackupCategory.ACTIVITY.name), any()) - verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) + 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 `metadata backup carries hardware tags as pre-activity metadata`() = test { - val hardwareTagMetadata = preActivityMetadata().copy( - walletId = HARDWARE_WALLET_ID, - paymentId = "hw-txid", - tags = listOf("hw"), - ) - whenever { preActivityMetadataRepo.getAllPreActivityMetadata() } - .thenReturn(Result.success(listOf(preActivityMetadata()))) - whenever { activityRepo.getHardwareTagsAsPreActivityMetadata() } - .thenReturn(Result.success(listOf(hardwareTagMetadata))) - whenever { pubkyRepo.snapshotSessionBackupState() }.thenReturn(Result.success(null)) - whenever { pubkyRepo.snapshotContactProfileOverrides() }.thenReturn(Result.success(null)) - val dataCaptor = argumentCaptor() - - sut.triggerBackup(BackupCategory.METADATA) - - verifyBlocking(vssBackupClient) { - putObject(eq(BackupCategory.METADATA.name), dataCaptor.capture()) + 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() } - val payload = json.decodeFromString(dataCaptor.firstValue.decodeToString()) - assertEquals(listOf(preActivityMetadata(), hardwareTagMetadata), payload.tagMetadata) } @Test - fun `metadata backup carries the hardware wallet names`() = test { - stubMetadataBackupReads() - whenever { hwWalletStore.backupSnapshot() }.thenReturn(mapOf(HARDWARE_WALLET_ID to "Cold Storage")) - val dataCaptor = argumentCaptor() - - sut.triggerBackup(BackupCategory.METADATA) - - verifyBlocking(vssBackupClient) { - putObject(eq(BackupCategory.METADATA.name), dataCaptor.capture()) + 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() } - val payload = json.decodeFromString(dataCaptor.firstValue.decodeToString()) - assertEquals(mapOf(HARDWARE_WALLET_ID to "Cold Storage"), payload.hwWalletNames) } @Test - fun `metadata backup omits the hardware wallet names when none are set`() = test { - stubMetadataBackupReads() - val dataCaptor = argumentCaptor() - - sut.triggerBackup(BackupCategory.METADATA) - - verifyBlocking(vssBackupClient) { - putObject(eq(BackupCategory.METADATA.name), dataCaptor.capture()) + 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() } - val payload = json.decodeFromString(dataCaptor.firstValue.decodeToString()) - assertNull(payload.hwWalletNames) } @Test - fun `metadata backup fails when the hardware wallet names cannot be read`() = test { - stubMetadataBackupReads() - whenever { hwWalletStore.backupSnapshot() } - .doSuspendableAnswer { throw BackupRepoTestError("store unavailable") } - - val result = sut.triggerBackup(BackupCategory.METADATA) - - assertTrue(result.isFailure) - // This envelope is the only copy of the names, so uploading without them would drop them. - verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) + 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 `metadata restore applies the backed up hardware wallet names`() = test { - val names = mapOf(HARDWARE_WALLET_ID to "Cold Storage") - stubMetadataRestore( - envelope = metadataEnvelope(metadata = listOf(preActivityMetadata()), hwWalletNames = names), - ) - - sut.performFullRestoreFromLatestBackup() - - verifyBlocking(hwWalletStore) { restoreNames(names) } + 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 `metadata restore keeps the stored names when the envelope carries none`() = test { - stubMetadataRestore(envelope = metadataEnvelope(metadata = listOf(preActivityMetadata()))) - - sut.performFullRestoreFromLatestBackup() - - // An envelope written before this field must not clear what this wallet already holds. - verifyBlocking(hwWalletStore) { restoreNames(emptyMap()) } + 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 `metadata restore records the category when the hardware wallet names cannot be stored`() = test { - stubWalletBackup() - stubMetadataRestore( - envelope = metadataEnvelope( - metadata = listOf(preActivityMetadata()), - hwWalletNames = mapOf(HARDWARE_WALLET_ID to "Cold Storage"), - ), - ) - whenever { hwWalletStore.restoreNames(any()) } - .doSuspendableAnswer { throw BackupRepoTestError("store unavailable") } - - val result = sut.performFullRestoreFromLatestBackup() - - assertTrue(result.isSuccess) - // The names are the last and the least of this envelope: the caches and tags above them were - // already applied, so losing the whole category's synced marker over a name would be wrong. - verifyBlocking(cacheStore) { updateBackupStatus(eq(BackupCategory.METADATA), any()) } + 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 `renaming a hardware wallet triggers a metadata backup`() = test { - stubMetadataBackupReads() + 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() - stubBackupStatuses( - MutableStateFlow(emptyMap()), - CompletableDeferred().apply { complete(Unit) }, - ) {} - + 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() - - // Reconnecting rewrites the entry without touching its name. - hwWalletData.update { HwWalletData(knownDevices = listOf(knownDevice())) } + advanceTimeBy(5_000) runCurrent() - advanceTimeBy(10_000) + verify(privatePaykitRepo, times(1)).backupSnapshot() + verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) + advanceTimeBy(20_000) runCurrent() - - verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) - - hwWalletData.update { HwWalletData(knownDevices = listOf(knownDevice(customLabel = "Cold Storage"))) } + verify(privatePaykitRepo, times(1)).backupSnapshot() + removal.withAccess(attempt) { removal.complete(attempt) } + metadataVersion.value++ runCurrent() - advanceTimeBy(10_000) + advanceTimeBy(5_000) runCurrent() - - verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.METADATA.name), any()) } + // 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 `activity traffic alone does not trigger a metadata backup`() = test { - val activitiesChanged = MutableStateFlow(0L) - val activityTagsChanged = MutableStateFlow(0L) - stubMetadataBackupReads() + 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() - whenever(activityRepo.activitiesChanged).thenReturn(activitiesChanged) - whenever(activityRepo.activityTagsChanged).thenReturn(activityTagsChanged) - stubBackupStatuses( - MutableStateFlow(emptyMap()), - CompletableDeferred().apply { complete(Unit) }, - ) {} try { sut.startObservingBackups() runCurrent() - - // A payment or sync bumps activities without touching tags. - activitiesChanged.update { 1L } - runCurrent() - advanceTimeBy(10_000) + advanceTimeBy(5_000) runCurrent() + verify(privatePaykitRepo, times(1)).backupSnapshot() + verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) - verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) - - // Tagging does bump the tag signal, which the metadata backup must follow. - activityTagsChanged.update { 2L } - runCurrent() - advanceTimeBy(10_000) + advanceTimeBy(20_000) runCurrent() - verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.METADATA.name), any()) } + verify(privatePaykitRepo, times(2)).backupSnapshot() + verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), any()) + assertFalse(backupStatuses.value.getValue(BackupCategory.WALLET).isRequired) } finally { sut.stopObservingBackups() } } + 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 `ordinary activity upload is skipped while a restore is pending`() = test { - val activitiesChanged = MutableStateFlow(0L) + fun `explicit USDT recovery backup works after observers stop`() = test { stubBackupObservers() - stubActivityBackupReads() - whenever(activityRepo.activitiesChanged).thenReturn(activitiesChanged) - stubBackupStatuses( - MutableStateFlow(emptyMap()), - CompletableDeferred().apply { complete(Unit) }, - ) {} + 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 { + sut.setWiping(true) + connectionRecoveryFixture(settingsStore, keychain, vssClients).withIdentityChange( + beforeClientsSuspend = { sut.reset() }, + ) { + sdkLock.withWalletWipe { } + } + } + runCurrent() try { - // The restore flow announces itself long before it reads the backup. - sut.setRestorePending(true) - sut.startObservingBackups() - runCurrent() - - // Meanwhile the node started and synced the fresh wallet's activities. - activitiesChanged.update { 1L } - runCurrent() - advanceTimeBy(10_000) - runCurrent() + release.complete(Unit) + withTimeout(5.seconds) { wipe.await() } + blocker.await() + assertFalse(exported) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) + } finally { + release.complete(Unit) + sut.reset() + } + } - // Uploading here replaces the stored envelope with the fresh wallet's state before the - // restore reads it, which loses the tags and the closed channels it still holds. - verify(vssBackupClient, never()).putObject(eq(BackupCategory.ACTIVITY.name), any()) + @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 { - sut.stopObservingBackups() + repo.reset() + dataJob.cancelAndJoin() + dispatcher.close() + directory.deleteRecursively() } } @Test - fun `ordinary activity upload resumes once the restore is no longer pending`() = test { - val activitiesChanged = MutableStateFlow(0L) + fun `busy wallet backup retries after observation pauses and resumes`() = test { + whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(3_000)) + whenever { privatePaykitRepo.backupSnapshot() } + .thenReturn(Result.failure(PaykitException.SharedStateBusy("shared_state_busy", "locked"))) + .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() - stubActivityBackupReads() - whenever(activityRepo.activitiesChanged).thenReturn(activitiesChanged) - stubBackupStatuses( - MutableStateFlow(emptyMap()), - CompletableDeferred().apply { complete(Unit) }, - ) {} try { - sut.setRestorePending(true) sut.startObservingBackups() runCurrent() - - activitiesChanged.update { 1L } + advanceTimeBy(5_000) runCurrent() - advanceTimeBy(10_000) + sut.stopObservingBackups() + advanceTimeBy(20_000) runCurrent() + verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) - verify(vssBackupClient, never()).putObject(eq(BackupCategory.ACTIVITY.name), any()) - - sut.setRestorePending(false) - whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(2_000)) - - activitiesChanged.update { 2L } + sut.startObservingBackups() runCurrent() - advanceTimeBy(10_000) + advanceTimeBy(5_000) runCurrent() - verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.ACTIVITY.name), any()) } + verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), any()) } finally { sut.stopObservingBackups() } } @Test - fun `scheduled activity backup skips an unchanged payload`() = test { - val activitiesChanged = MutableStateFlow(0L) - val backupStatuses = MutableStateFlow>(emptyMap()) + fun `busy wallet backup still warns once it stays pending past the failure window`() = test { + val startedAt = currentTime + whenever(clock.now()).thenAnswer { Instant.fromEpochMilliseconds(3_000 + currentTime - startedAt) } + whenever { privatePaykitRepo.backupSnapshot() } + .thenReturn(Result.failure(PaykitException.SharedStateBusy("shared_state_busy", "locked"))) + whenever(context.getString(R.string.settings__backup__failed_title)).thenReturn("Backup failed") + whenever(context.getString(R.string.settings__backup__failed_message)).thenReturn("Retrying") + val backupStatuses = MutableStateFlow( + mapOf(BackupCategory.WALLET to BackupItemStatus(synced = 1_000, required = 2_000)) + ) + val allowWalletClear = CompletableDeferred().apply { complete(Unit) } + stubBackupStatuses(backupStatuses, allowWalletClear) {} stubBackupObservers() - stubActivityBackupReads() - whenever(activityRepo.activitiesChanged).thenReturn(activitiesChanged) - stubBackupStatuses(backupStatuses, CompletableDeferred().apply { complete(Unit) }) {} try { sut.startObservingBackups() runCurrent() - - activitiesChanged.update { 1L } + advanceTimeBy(31.minutes.inWholeMilliseconds) runCurrent() - advanceTimeBy(10_000) - runCurrent() - verify(vssBackupClient, times(1)).putObject(eq(BackupCategory.ACTIVITY.name), any()) - // Every wallet sync announces a change, even when no activity was added or updated. - whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(2_000)) - activitiesChanged.update { 2L } + verify(context, atLeastOnce()).getString(R.string.settings__backup__failed_title) + } finally { + sut.stopObservingBackups() + } + } + + @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() - advanceTimeBy(10_000) + assertTrue(statuses.value.getValue(category).running) + advanceTimeBy(4_999) runCurrent() + assertTrue(statuses.value.getValue(category).running) + verify(vssBackupClient, never()).putObject(eq(category.name), any()) - verify(vssBackupClient, times(1)).putObject(eq(BackupCategory.ACTIVITY.name), any()) - val status = backupStatuses.value.getValue(BackupCategory.ACTIVITY) - assertFalse(status.isRequired) - assertFalse(status.running) + sut.stopObservingBackups() + runCurrent() + assertFalse(statuses.value.getValue(category).running) + assertTrue(statuses.value.getValue(category).isRequired) - whenever(activityRepo.getAllActivitiesTags()).thenReturn(Result.success(listOf(defaultTag()))) - activitiesChanged.update { 3L } + sut.startObservingBackups() runCurrent() - advanceTimeBy(10_000) + assertTrue(statuses.value.getValue(category).running) + advanceTimeBy(5_000) runCurrent() - - verify(vssBackupClient, times(2)).putObject(eq(BackupCategory.ACTIVITY.name), any()) + verify(vssBackupClient).putObject(eq(category.name), any()) + assertFalse(statuses.value.getValue(category).running) + assertFalse(statuses.value.getValue(category).isRequired) } finally { sut.stopObservingBackups() } } @Test - fun `scheduled activity backup uploads a reverted payload after a failed upload`() = test { - val activitiesChanged = MutableStateFlow(0L) + 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 + var startupUpdates = 0 + whenever(vssBackupClient.setupWithRetry(any(), any(), any())).doSuspendableAnswer { + finishSetup.await() + Result.success(Unit) + } + whenever(cacheStore.backupStatuses).thenReturn(statuses) + whenever(cacheStore.update(any())).doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + // Hold this category's startup update before its persisted-state transform runs. + if (++startupUpdates == BackupCategory.entries.indexOf(category) + 1) { + cleanupEntered = true + finishCleanup.await() + } + statuses.update { current -> transform(AppCacheData(backupStatuses = current)).backupStatuses } + } stubBackupObservers() - stubActivityBackupReads() - whenever(activityRepo.activitiesChanged).thenReturn(activitiesChanged) - stubBackupStatuses(MutableStateFlow(emptyMap()), CompletableDeferred().apply { complete(Unit) }) {} - try { sut.startObservingBackups() runCurrent() - sut.triggerBackup(BackupCategory.ACTIVITY).getOrThrow() - - // The server can commit a write whose response never reaches the client. - whenever(activityRepo.getAllActivitiesTags()).thenReturn(Result.success(listOf(defaultTag()))) - whenever(vssBackupClient.putObject(any(), any())).thenReturn(Result.failure(BackupRepoTestError("io"))) - assertTrue(sut.triggerBackup(BackupCategory.ACTIVITY).isFailure) + assertTrue(cleanupEntered) + assertTrue(statuses.value.getValue(category).running) - val uploaded = VssItem(key = BackupCategory.ACTIVITY.name, value = byteArrayOf(), version = 2) - whenever(vssBackupClient.putObject(any(), any())).thenReturn(Result.success(uploaded)) - whenever(activityRepo.getAllActivitiesTags()).thenReturn(Result.success(emptyList())) - activitiesChanged.update { 1L } + finishCleanup.complete(Unit) runCurrent() - advanceTimeBy(10_000) + assertTrue(statuses.value.getValue(category).running) + advanceTimeBy(5_000) runCurrent() - - verify(vssBackupClient, times(3)).putObject(eq(BackupCategory.ACTIVITY.name), any()) + verify(vssBackupClient).putObject(eq(category.name), any()) + assertFalse(statuses.value.getValue(category).isRequired) } finally { + finishCleanup.complete(Unit) + finishSetup.complete(Unit) sut.stopObservingBackups() } } @Test - fun `scheduled activity backup uploads an unchanged payload after reset`() = test { - val activitiesChanged = MutableStateFlow(0L) + fun `start observing backs up stale required status after clearing running flag`() = test { + val backupStatuses = MutableStateFlow( + mapOf( + BackupCategory.WALLET to BackupItemStatus( + running = true, + synced = 1_000, + required = 2_000, + ), + ) + ) + val allowWalletClear = CompletableDeferred() + var delayedWalletClear = false + stubBackupStatuses(backupStatuses, allowWalletClear) { + delayedWalletClear = true + } stubBackupObservers() - stubActivityBackupReads() - whenever(activityRepo.activitiesChanged).thenReturn(activitiesChanged) - stubBackupStatuses(MutableStateFlow(emptyMap()), CompletableDeferred().apply { complete(Unit) }) {} - sut.triggerBackup(BackupCategory.ACTIVITY).getOrThrow() - sut.reset() try { sut.startObservingBackups() runCurrent() - activitiesChanged.update { 1L } + verify(vssBackupClient, never()).putObject(eq(BackupCategory.WALLET.name), any()) + + allowWalletClear.complete(Unit) runCurrent() - advanceTimeBy(10_000) + advanceTimeBy(5_000) runCurrent() - verify(vssBackupClient, times(2)).putObject(eq(BackupCategory.ACTIVITY.name), any()) + assertTrue(delayedWalletClear) + verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), any()) } finally { sut.stopObservingBackups() } } @Test - fun `explicit activity backup uploads an unchanged payload`() = test { - stubActivityBackupReads() - - sut.triggerBackup(BackupCategory.ACTIVITY).getOrThrow() - sut.triggerBackup(BackupCategory.ACTIVITY).getOrThrow() - - verify(vssBackupClient, times(2)).putObject(eq(BackupCategory.ACTIVITY.name), any()) - } - - @Test - fun `pending restore stops gating uploads once it expires`() = test { - val activitiesChanged = MutableStateFlow(0L) + fun `failed automatic backup waits for new required timestamp before retrying`() = test { + whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(3_000)) + whenever { vssBackupClient.putObject(eq(BackupCategory.SETTINGS.name), any()) } + .thenReturn(Result.failure(BackupRepoTestError("backup failed"))) + val backupStatuses = MutableStateFlow( + mapOf( + BackupCategory.SETTINGS to BackupItemStatus( + synced = 1_000, + required = 2_000, + ), + ) + ) + val allowWalletClear = CompletableDeferred().apply { complete(Unit) } + stubBackupStatuses(backupStatuses, allowWalletClear) {} stubBackupObservers() - stubActivityBackupReads() - whenever(activityRepo.activitiesChanged).thenReturn(activitiesChanged) - stubBackupStatuses( - MutableStateFlow(emptyMap()), - CompletableDeferred().apply { complete(Unit) }, - ) {} try { - sut.setRestorePending(true) sut.startObservingBackups() runCurrent() - - // The restore never returns, so nothing ever clears the gate. - whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(RESTORE_GATE_EXPIRED_AT)) - - activitiesChanged.update { 1L } + advanceTimeBy(5_000) runCurrent() - advanceTimeBy(10_000) + advanceTimeBy(5_000) runCurrent() - verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.ACTIVITY.name), any()) } + verify(vssBackupClient).putObject(eq(BackupCategory.SETTINGS.name), any()) } finally { sut.stopObservingBackups() } } @Test - fun `migration rewrite still uploads while a restore is pending`() = test { - stubWalletBackup() - stubActivityRestore() - sut.setRestorePending(true) - - val result = sut.performFullRestoreFromLatestBackup() - - // The rewrite is the restore's own upload, so the gate must never hold it. - assertTrue(result.isSuccess) - verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.ACTIVITY.name), any()) } - } - - @Test - fun `metadata backup fails when pre-activity metadata cannot be read`() = test { - stubMetadataBackupReads() - whenever { preActivityMetadataRepo.getAllPreActivityMetadata() } - .thenReturn(Result.failure(BackupRepoTestError("core unavailable"))) + fun `successful upload leaves a newer required snapshot queued`() = 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() - val result = sut.triggerBackup(BackupCategory.METADATA) + try { + sut.startObservingBackups() + runCurrent() + advanceTimeBy(5_000) + runCurrent() + advanceTimeBy(5_000) + runCurrent() - assertTrue(result.isFailure) - // Uploading here would replace the stored tags with an empty set. - verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) + verify(vssBackupClient, times(2)).putObject(eq(BackupCategory.SETTINGS.name), any()) + } finally { + sut.stopObservingBackups() + } } @Test - fun `metadata backup fails when hardware tags cannot be read`() = test { - stubMetadataBackupReads() - whenever { activityRepo.getHardwareTagsAsPreActivityMetadata() } - .thenReturn(Result.failure(BackupRepoTestError("core unavailable"))) + 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() - val result = sut.triggerBackup(BackupCategory.METADATA) + try { + sut.scheduleFullBackup() + sut.startObservingBackups() + runCurrent() + advanceTimeBy(5_000) + runCurrent() + advanceTimeBy(5_000) + runCurrent() - assertTrue(result.isFailure) - // This envelope is the only copy of hardware tags, so a partial upload would lose them. - verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) + verify(vssBackupClient, times(2)).putObject(eq(BackupCategory.SETTINGS.name), any()) + } finally { + sut.stopObservingBackups() + } } @Test - fun `activity backup excludes hardware tags`() = test { - whenever { activityRepo.getActivities() }.thenReturn(Result.success(emptyList())) - whenever { activityRepo.getClosedChannels() }.thenReturn(Result.success(emptyList())) - // ActivityRepo already scopes this to the default wallet, so a hardware tag can never appear here. - whenever { activityRepo.getAllActivitiesTags() }.thenReturn(Result.success(listOf(defaultTag()))) + fun `failed automatic backup retries newer required timestamp`() = 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.failure(BackupRepoTestError("backup failed")) + } else { + Result.success( + VssItem( + key = BackupCategory.SETTINGS.name, + value = byteArrayOf(), + version = 1, + ) + ) + } + } + val allowWalletClear = CompletableDeferred().apply { complete(Unit) } + stubBackupStatuses(backupStatuses, allowWalletClear) {} + stubBackupObservers() + + try { + 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 `full restore should fail when Paykit initialization fails without a saved SDK backup`() = test { + stubWalletBackup() + whenever { privatePaykitRepo.restoreBackup(anyOrNull()) } + .thenReturn(Result.failure(BackupRepoTestError("restore failed"))) + + val result = sut.performFullRestoreFromLatestBackup() + + assertTrue(result.isFailure) + verify(settingsStore, never()).update(any()) + } + + @Test + fun `wallet backup includes watch-only accounts and allocator state`() = test { + val account = watchOnlyAccount() + val allocationState = WatchOnlyAccountAllocationState( + highestAccountIndexByWallet = mapOf("0" to 7), + pendingAccountIndexByRequest = mapOf("0:pending" to 7), + ) + whenever { watchOnlyAccountStore.backupSnapshot() }.thenReturn( + WatchOnlyAccountBackupSnapshot(listOf(account), allocationState) + ) val dataCaptor = argumentCaptor() - sut.triggerBackup(BackupCategory.ACTIVITY) + sut.triggerBackup(BackupCategory.WALLET) verifyBlocking(vssBackupClient) { - putObject(eq(BackupCategory.ACTIVITY.name), dataCaptor.capture()) + putObject(eq(BackupCategory.WALLET.name), dataCaptor.capture()) } - val payload = json.decodeFromString(dataCaptor.firstValue.decodeToString()) - assertTrue(payload.activityTags.none { it.walletId == HARDWARE_WALLET_ID }) + val payload = json.decodeFromString(dataCaptor.firstValue.decodeToString()) + assertEquals(listOf(account), payload.watchOnlyAccounts) + assertEquals(allocationState, payload.watchOnlyAccountAllocationState) } @Test - fun `activity backup is not rewritten when core restore fails`() = test { - stubWalletBackup() - stubActivityRestore() - whenever { activityRepo.restoreFromBackup(any()) } - .thenReturn(Result.failure(BackupRepoTestError("upsert failed"))) + fun `wallet backup round trips public address exclusions alongside reservation floors`() = test { + val legacy = setOf("bcrt1qpublic") + val floors = mapOf("nativeSegwit" to 8) + whenever(privatePaykitAddressReservationRepo.quarantinedPublicAddressesSnapshot()).thenReturn(legacy) + whenever(privatePaykitAddressReservationRepo.backupSnapshot()).thenReturn(Result.success(floors)) + sut.triggerBackup(BackupCategory.WALLET).getOrThrow() + val bytes = argumentCaptor() + verify(vssBackupClient).putObject(eq(BackupCategory.WALLET.name), bytes.capture()) + val payload = json.decodeFromString(bytes.firstValue.decodeToString()) + assertEquals(legacy.toList(), payload.publicPaykitLegacyAddresses) + assertEquals(floors, payload.privatePaykitHighestReservedReceiveIndexByAddressType) + whenever(vssBackupClient.getObject(BackupCategory.WALLET.name)).thenReturn( + Result.success(VssItem(BackupCategory.WALLET.name, bytes.firstValue, 1)), + ) + sut.performFullRestoreFromLatestBackup().getOrThrow() + verify(privatePaykitAddressReservationRepo).restoreBackup(floors, legacy) + } + + @Test + fun `wallet restore restores watch-only accounts and allocator before runtime reconciliation`() = test { + val account = watchOnlyAccount() + val allocationState = WatchOnlyAccountAllocationState( + highestAccountIndexByWallet = mapOf("0" to 7), + pendingAccountIndexByRequest = mapOf("0:pending" to 7), + ) + stubWalletBackup( + watchOnlyAccounts = listOf(account), + watchOnlyAccountAllocationState = allocationState, + ) + var accountsWereRestored = false + whenever { watchOnlyAccountRepo.restore(listOf(account), allocationState) }.thenAnswer { + accountsWereRestored = true + Unit + } + whenever { lightningService.reconcileWatchOnlyAccounts() }.thenAnswer { + assertTrue(accountsWereRestored) + Unit + } val result = sut.performFullRestoreFromLatestBackup() - assertEquals(setOf(BackupCategory.ACTIVITY), result.getOrThrow()) - // Rewriting here would replace the legacy backup with whatever Core happens to hold. - verify(vssBackupClient, never()).putObject(eq(BackupCategory.ACTIVITY.name), any()) + assertTrue(result.isSuccess) + verifyBlocking(watchOnlyAccountRepo) { restore(listOf(account), allocationState) } + verifyBlocking(lightningService) { reconcileWatchOnlyAccounts() } } @Test - fun `failed core migration skips the category without failing the restore`() = test { + fun `full restore should fail when private Paykit reserved indexes fail to reconcile`() = test { stubWalletBackup() - stubActivityRestore() - whenever { activityRepo.migrateBackupActivityTagsJson(any()) } - .thenReturn(Result.failure(BackupRepoTestError("core migration failed"))) + whenever { privatePaykitAddressReservationRepo.reconcileReservedIndexesWithLdk() } + .thenReturn(Result.failure(BackupRepoTestError("reconcile failed"))) val result = sut.performFullRestoreFromLatestBackup() - // Only WALLET is fatal, so the restore still succeeds and reports the category. - assertEquals(setOf(BackupCategory.ACTIVITY), result.getOrThrow()) - // The legacy slice stays unmigrated and no longer decodes, so nothing of this category is applied. - verifyBlocking(activityRepo, never()) { restoreFromBackup(any()) } - // Nothing was restored, so the stored backup must not be replaced. - verify(vssBackupClient, never()).putObject(eq(BackupCategory.ACTIVITY.name), any()) + assertTrue(result.isFailure) + verify(settingsStore, never()).update(any()) } - private fun stubActivityBackupReads() { - whenever { activityRepo.getActivities() }.thenReturn(Result.success(emptyList())) - whenever { activityRepo.getClosedChannels() }.thenReturn(Result.success(emptyList())) - whenever { activityRepo.getAllActivitiesTags() }.thenReturn(Result.success(emptyList())) - } + @Test + fun `legacy activity backup is migrated by core before decode`() = test { + stubWalletBackup() + stubActivityRestore() - private fun pendingPublicAddressRestoreRecord(type: String): JsonObject { - val stored = requireNotNull(keychain.loadString(Keychain.Key.PAYKIT_PENDING_PUBLIC_ADDRESS_RESTORE.name)) - return json.parseToJsonElement(stored).jsonObject.also { - assertEquals(type, it["type"]?.jsonPrimitive?.content) - } + val result = sut.performFullRestoreFromLatestBackup() + + assertTrue(result.isSuccess) + verifyBlocking(activityRepo) { migrateBackupActivitiesJson(LEGACY_ACTIVITIES_JSON) } + verifyBlocking(activityRepo) { migrateBackupActivityTagsJson(LEGACY_TAGS_JSON) } + + val payloadCaptor = argumentCaptor() + verifyBlocking(activityRepo) { restoreFromBackup(payloadCaptor.capture()) } + assertEquals(listOf(defaultTag()), payloadCaptor.firstValue.activityTags) } - private suspend fun assertCancelledMetadataDownloadCanRetry(metadataOnRetry: String?) = coroutineScope { - val reservationStore = stubPublicAddressRestore("") - whenever(preActivityMetadataRepo.migrateBackupPreActivityMetadataJson(any())).thenAnswer { - Result.success(it.getArgument(0)) - } - whenever(preActivityMetadataRepo.getAllPreActivityMetadata()).thenReturn(Result.success(emptyList())) - val downloadStarted = CompletableDeferred() - var holdDownload = true - val metadata = metadataOnRetry?.let { - VssItem(key = BackupCategory.METADATA.name, value = it.toByteArray(), version = 1) - } - whenever(vssBackupClient.getObject(BackupCategory.METADATA.name)).doSuspendableAnswer { - if (holdDownload) { - downloadStarted.complete(Unit) - awaitCancellation() - } - Result.success(metadata) - } - val restore = async { sut.performFullRestoreFromLatestBackup() } - try { - downloadStarted.await() - } finally { - restore.cancelAndJoin() - } + @Test + fun `legacy metadata backup is migrated by core before decode`() = test { + stubWalletBackup() + stubMetadataRestore() - assertTrue(restore.isCancelled) - assertFalse(sut.isRestoring.value) - assertFalse(settingsData.value.backupVerified) - assertTrue(sut.hasPendingWalletRestore()) - pendingPublicAddressRestoreRecord("reading") - assertTrue(reservationStore.data.first().quarantinedPublicAddresses.isEmpty()) - verify(vssBackupClient, never()).getObject(BackupCategory.WALLET.name) + val result = sut.performFullRestoreFromLatestBackup() - holdDownload = false - val restartedReservations = createReservationRepo(reservationStore) - sut = createSut(restartedReservations) - sut.setRestorePending(false) - assertTrue(sut.performFullRestoreFromLatestBackup().isSuccess) + assertTrue(result.isSuccess) + verifyBlocking(preActivityMetadataRepo) { migrateBackupPreActivityMetadataJson(LEGACY_METADATA_JSON) } - assertTrue(settingsData.value.backupVerified) - assertFalse(sut.hasPendingWalletRestore()) - assertNull(keychain.loadString(Keychain.Key.PAYKIT_PENDING_PUBLIC_ADDRESS_RESTORE.name)) - assertTrue(reservationStore.data.first().quarantinedPublicAddresses.isEmpty()) - whenever(lightningRepo.newAddressInfoForType(any())) - .thenReturn(Result.success(AddressDerivationInfo("bcrt1qreceive", 0))) - assertEquals("bcrt1qreceive", restartedReservations.nextReusableReceiveAddress().getOrThrow()) - sut.triggerBackup(BackupCategory.METADATA).getOrThrow() - verify(vssBackupClient).putObject(eq(BackupCategory.METADATA.name), any()) + val metadataCaptor = argumentCaptor>() + verifyBlocking(preActivityMetadataRepo) { upsertPreActivityMetadata(metadataCaptor.capture()) } + assertEquals(listOf(preActivityMetadata()), metadataCaptor.firstValue) } - private fun stubPublicAddressRestore( - address: String, - quarantineFailure: Throwable? = null, - addressRecordFailure: Throwable? = null, - sourceRecordFailure: Throwable? = null, - ): PrivatePaykitReservationStore { + @Test + fun `iOS metadata backup restores the Pubky profile session`() = test { + stubWalletBackup() + val envelope = iosFixture("metadata") stubMetadataRestore( - envelope = metadataEnvelope( - metadata = listOf(preActivityMetadata()), - cache = AppCacheData(onchainAddress = address), - ), - ) - stubRestoreEnvelope(BackupCategory.WALLET, """{"version":1,"createdAt":123,"transfers":[]}""") - stubRestoreEnvelope( - BackupCategory.SETTINGS, - json.encodeToString( - SettingsBackupV1( - createdAt = 123, - settings = SettingsData( - sharesPrivatePaykitEndpoints = true, - sharesPublicPaykitEndpoints = true, - hasConfirmedPublicPaykitEndpoints = true, - ), - ), - ), + envelope = envelope, + migratedMetadataJson = json.parseToJsonElement(envelope).jsonObject["tagMetadata"].toString(), ) - whenever { settingsStore.restoreFromBackup(any()) }.thenAnswer { - val payload = it.getArgument(0) - settingsData.update { payload.settings.withPublicSharingDisabledForRestore() } - Result.success(Unit) - } - whenever { settingsStore.update(any()) }.thenAnswer { - val transform = it.getArgument<(SettingsData) -> SettingsData>(0) - settingsData.update(transform) - } - whenever { cacheStore.update(any()) }.thenAnswer { - val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) - cacheData.update(transform) - } - whenever(cacheStore.backupStatuses).thenReturn(cacheData.map { it.backupStatuses }) - whenever { cacheStore.updateBackupStatus(any(), any()) }.thenAnswer { - val category = it.getArgument(0) - val transform = it.getArgument<(BackupItemStatus) -> BackupItemStatus>(1) - cacheData.update { cache -> - val status = cache.backupStatuses[category] ?: BackupItemStatus() - cache.copy(backupStatuses = cache.backupStatuses + (category to transform(status))) - } - } - val retained = mutableMapOf() - var nextRecordFailure = addressRecordFailure - var nextSourceFailure = sourceRecordFailure - whenever(keychain.exists(any())).thenAnswer { it.getArgument(0) in retained } - whenever(keychain.loadString(any())).thenAnswer { retained[it.getArgument(0)] } - whenever { keychain.upsertString(any(), any()) }.thenAnswer { - val key = it.getArgument(0) - val value = it.getArgument(1) - if (key == Keychain.Key.PAYKIT_PENDING_PUBLIC_ADDRESS_RESTORE.name) { - when (json.parseToJsonElement(value).jsonObject["type"]?.jsonPrimitive?.content) { - "source" -> nextSourceFailure?.let { failure -> - nextSourceFailure = null - throw failure - } - "address" -> nextRecordFailure?.let { failure -> - nextRecordFailure = null - throw failure - } - } - } - retained[key] = value - Unit - } - whenever { keychain.delete(any()) }.thenAnswer { - retained.remove(it.getArgument(0)) - Unit - } - val reservationStore = mock() - val reservationData = MutableStateFlow(PrivatePaykitReservationData()) - var nextFailure = quarantineFailure - whenever(reservationStore.data).thenReturn(reservationData) - whenever { reservationStore.update(any()) }.thenAnswer { - nextFailure?.let { failure -> - nextFailure = null - throw failure - } - val transform = it.getArgument<(PrivatePaykitReservationData) -> PrivatePaykitReservationData>(0) - reservationData.update(transform) - } - sut = createSut(createReservationRepo(reservationStore)) - return reservationStore + + val failed = sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertEquals(emptySet(), failed) + verifyBlocking(pubkyRepo) { restoreSessionBackupState(PubkySessionBackupV1(PubkySessionBackupKind.LocalSeed)) } + val metadataCaptor = argumentCaptor>() + verifyBlocking(preActivityMetadataRepo) { upsertPreActivityMetadata(metadataCaptor.capture()) } + assertEquals(2, metadataCaptor.firstValue.size) } - private fun createReservationRepo( - reservationStore: PrivatePaykitReservationStore, - ) = PrivatePaykitAddressReservationRepo( - ioDispatcher = testDispatcher, - reservationStore = reservationStore, - settingsStore = settingsStore, - coreService = coreService, - lightningRepo = lightningRepo, - cacheStore = cacheStore, - keychain = keychain, - ) + @Test + fun `full restore reports the categories it could not restore`() = test { + stubWalletBackup() + stubMetadataRestore(envelope = iosFixture("metadata")) + whenever { pubkyRepo.restoreSessionBackupState(anyOrNull()) } + .thenReturn(Result.failure(BackupRepoTestError("pubky"))) + stubRestoreEnvelope(BackupCategory.BLOCKTANK, iosFixture("blocktank")) + whenever { blocktankRepo.restoreFromBackup(any()) }.thenReturn(Result.failure(BackupRepoTestError("core"))) + val widgetsEnvelope = json.encodeToString(WidgetsBackupV1(createdAt = 1, widgets = WidgetsData())) + stubRestoreEnvelope(BackupCategory.WIDGETS, widgetsEnvelope) + whenever { widgetsStore.restoreFromBackup(any()) }.thenReturn(Result.failure(BackupRepoTestError("disk"))) - private fun stubMetadataBackupReads() { + val failed = sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertEquals(setOf(BackupCategory.METADATA, BackupCategory.WIDGETS, BackupCategory.BLOCKTANK), failed) + } + + @Test + fun `migrated backups are rewritten to vss after restore`() = test { + stubWalletBackup() + stubActivityRestore() + stubMetadataRestore() + + val result = sut.performFullRestoreFromLatestBackup() + + assertTrue(result.isSuccess) + verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.ACTIVITY.name), any()) } + verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.METADATA.name), any()) } + } + + @Test + fun `current backups are not rewritten after restore`() = test { + stubWalletBackup() + // Envelopes already carry wallet ids, so Core hands the slices back untouched. + stubActivityRestore(envelope = activityEnvelope(tags = listOf(defaultTag()))) + stubMetadataRestore(envelope = metadataEnvelope(metadata = listOf(preActivityMetadata()))) + + val result = sut.performFullRestoreFromLatestBackup() + + assertTrue(result.isSuccess) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.ACTIVITY.name), any()) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) + } + + @Test + fun `metadata backup carries hardware tags as pre-activity metadata`() = test { + val hardwareTagMetadata = preActivityMetadata().copy( + walletId = HARDWARE_WALLET_ID, + paymentId = "hw-txid", + tags = listOf("hw"), + ) whenever { preActivityMetadataRepo.getAllPreActivityMetadata() } .thenReturn(Result.success(listOf(preActivityMetadata()))) - whenever { activityRepo.getHardwareTagsAsPreActivityMetadata() }.thenReturn(Result.success(emptyList())) + whenever { activityRepo.getHardwareTagsAsPreActivityMetadata() } + .thenReturn(Result.success(listOf(hardwareTagMetadata))) whenever { pubkyRepo.snapshotSessionBackupState() }.thenReturn(Result.success(null)) whenever { pubkyRepo.snapshotContactProfileOverrides() }.thenReturn(Result.success(null)) + val dataCaptor = argumentCaptor() + + sut.triggerBackup(BackupCategory.METADATA) + + verifyBlocking(vssBackupClient) { + putObject(eq(BackupCategory.METADATA.name), dataCaptor.capture()) + } + val payload = json.decodeFromString(dataCaptor.firstValue.decodeToString()) + assertEquals(listOf(preActivityMetadata(), hardwareTagMetadata), payload.tagMetadata) } - private fun stubActivityRestore( - envelope: String = legacyActivityEnvelope(), - migratedTagsJson: String = json.encodeToString(listOf(defaultTag())), - backedUpTags: List = listOf(defaultTag()), - ) { - stubRestoreEnvelope(BackupCategory.ACTIVITY, envelope) - whenever { activityRepo.migrateBackupActivitiesJson(any()) }.thenReturn(Result.success("[]")) - whenever { activityRepo.migrateBackupActivityTagsJson(any()) }.thenReturn(Result.success(migratedTagsJson)) - whenever { activityRepo.restoreFromBackup(any()) }.thenReturn(Result.success(Unit)) - // Read back by the rewrite through getBackupDataBytes(ACTIVITY). - whenever { activityRepo.getActivities() }.thenReturn(Result.success(emptyList())) - whenever { activityRepo.getClosedChannels() }.thenReturn(Result.success(emptyList())) - whenever { activityRepo.getAllActivitiesTags() }.thenReturn(Result.success(backedUpTags)) + @Test + fun `metadata backup carries the hardware wallet names`() = test { + stubMetadataBackupReads() + whenever { hwWalletStore.backupSnapshot() }.thenReturn(mapOf(HARDWARE_WALLET_ID to "Cold Storage")) + val dataCaptor = argumentCaptor() + + sut.triggerBackup(BackupCategory.METADATA) + + verifyBlocking(vssBackupClient) { + putObject(eq(BackupCategory.METADATA.name), dataCaptor.capture()) + } + val payload = json.decodeFromString(dataCaptor.firstValue.decodeToString()) + assertEquals(mapOf(HARDWARE_WALLET_ID to "Cold Storage"), payload.hwWalletNames) } - private fun stubMetadataRestore( - envelope: String = legacyMetadataEnvelope(), - migratedMetadataJson: String = json.encodeToString(listOf(preActivityMetadata())), - restorableMetadata: List = listOf(preActivityMetadata()), - ) { - stubRestoreEnvelope(BackupCategory.METADATA, envelope) - whenever { preActivityMetadataRepo.migrateBackupPreActivityMetadataJson(any()) } - .thenReturn(Result.success(migratedMetadataJson)) - whenever { preActivityMetadataRepo.upsertPreActivityMetadata(any()) }.thenReturn(Result.success(Unit)) - whenever { pubkyRepo.restoreSessionBackupState(anyOrNull()) }.thenReturn(Result.success(Unit)) - whenever { pubkyRepo.restoreContactProfileOverrides(anyOrNull()) }.thenReturn(Result.success(Unit)) - // Read back by the rewrite through getMetadataBackupDataBytes(). - whenever { preActivityMetadataRepo.getAllPreActivityMetadata() } - .thenReturn(Result.success(restorableMetadata)) - whenever { activityRepo.getHardwareTagsAsPreActivityMetadata() }.thenReturn(Result.success(emptyList())) - whenever { pubkyRepo.snapshotSessionBackupState() }.thenReturn(Result.success(null)) - whenever { pubkyRepo.snapshotContactProfileOverrides() }.thenReturn(Result.success(null)) + @Test + fun `metadata backup omits the hardware wallet names when none are set`() = test { + stubMetadataBackupReads() + val dataCaptor = argumentCaptor() + + sut.triggerBackup(BackupCategory.METADATA) + + verifyBlocking(vssBackupClient) { + putObject(eq(BackupCategory.METADATA.name), dataCaptor.capture()) + } + val payload = json.decodeFromString(dataCaptor.firstValue.decodeToString()) + assertNull(payload.hwWalletNames) } - private fun iosFixture(name: String) = - requireNotNull(javaClass.getResourceAsStream("/ios-backup/$name.json")).bufferedReader().readText() + @Test + fun `metadata backup fails when the hardware wallet names cannot be read`() = test { + stubMetadataBackupReads() + whenever { hwWalletStore.backupSnapshot() } + .doSuspendableAnswer { throw BackupRepoTestError("store unavailable") } - private fun stubRestoreEnvelope(category: BackupCategory, envelope: String) { - whenever { vssBackupClient.getObject(category.name) }.thenReturn( - Result.success( - VssItem(key = category.name, value = envelope.toByteArray(), version = 1) - ) + val result = sut.triggerBackup(BackupCategory.METADATA) + + assertTrue(result.isFailure) + // This envelope is the only copy of the names, so uploading without them would drop them. + verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) + } + + @Test + fun `metadata restore applies the backed up hardware wallet names`() = test { + val names = mapOf(HARDWARE_WALLET_ID to "Cold Storage") + stubMetadataRestore( + envelope = metadataEnvelope(metadata = listOf(preActivityMetadata()), hwWalletNames = names), ) + + sut.performFullRestoreFromLatestBackup() + + verifyBlocking(hwWalletStore) { restoreNames(names) } } - /** An `ActivityBackupV1` whose Core-owned tag records predate `walletId`. */ - private fun legacyActivityEnvelope(): String = envelopeWithRawField( - base = activityEnvelope(), - field = "activityTags", - rawJson = LEGACY_TAGS_JSON, - ) + @Test + fun `metadata restore keeps the stored names when the envelope carries none`() = test { + stubMetadataRestore(envelope = metadataEnvelope(metadata = listOf(preActivityMetadata()))) - /** A `MetadataBackupV1` whose Core-owned metadata records predate `walletId`. */ - private fun legacyMetadataEnvelope(): String = envelopeWithRawField( - base = metadataEnvelope(), - field = "tagMetadata", - rawJson = LEGACY_METADATA_JSON, - ) + sut.performFullRestoreFromLatestBackup() - private fun activityEnvelope(tags: List = emptyList()) = json.encodeToString( - ActivityBackupV1( - createdAt = 123, - activities = emptyList(), - activityTags = tags, - closedChannels = emptyList(), - ) - ) + // An envelope written before this field must not clear what this wallet already holds. + verifyBlocking(hwWalletStore) { restoreNames(emptyMap()) } + } - private fun metadataEnvelope( - metadata: List = emptyList(), - cache: AppCacheData = AppCacheData(), - hwWalletNames: Map? = null, - ) = json.encodeToString( + @Test + fun `metadata restore records the category when the hardware wallet names cannot be stored`() = test { + stubWalletBackup() + stubMetadataRestore( + envelope = metadataEnvelope( + metadata = listOf(preActivityMetadata()), + hwWalletNames = mapOf(HARDWARE_WALLET_ID to "Cold Storage"), + ), + ) + whenever { hwWalletStore.restoreNames(any()) } + .doSuspendableAnswer { throw BackupRepoTestError("store unavailable") } + + val result = sut.performFullRestoreFromLatestBackup() + + assertTrue(result.isSuccess) + // The names are the last and the least of this envelope: the caches and tags above them were + // already applied, so losing the whole category's synced marker over a name would be wrong. + verifyBlocking(cacheStore) { updateBackupStatus(eq(BackupCategory.METADATA), any()) } + } + + @Test + fun `renaming a hardware wallet triggers a metadata backup`() = test { + stubMetadataBackupReads() + stubBackupObservers() + stubBackupStatuses( + MutableStateFlow(emptyMap()), + CompletableDeferred().apply { complete(Unit) }, + ) {} + + try { + sut.startObservingBackups() + runCurrent() + + // Reconnecting rewrites the entry without touching its name. + hwWalletData.update { HwWalletData(knownDevices = listOf(knownDevice())) } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + + verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) + + hwWalletData.update { HwWalletData(knownDevices = listOf(knownDevice(customLabel = "Cold Storage"))) } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + + verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.METADATA.name), any()) } + } finally { + sut.stopObservingBackups() + } + } + + @Test + fun `activity traffic alone does not trigger a metadata backup`() = test { + val activitiesChanged = MutableStateFlow(0L) + val activityTagsChanged = MutableStateFlow(0L) + stubMetadataBackupReads() + stubBackupObservers() + whenever(activityRepo.activitiesChanged).thenReturn(activitiesChanged) + whenever(activityRepo.activityTagsChanged).thenReturn(activityTagsChanged) + stubBackupStatuses( + MutableStateFlow(emptyMap()), + CompletableDeferred().apply { complete(Unit) }, + ) {} + + try { + sut.startObservingBackups() + runCurrent() + + // A payment or sync bumps activities without touching tags. + activitiesChanged.update { 1L } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + + verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) + + // Tagging does bump the tag signal, which the metadata backup must follow. + activityTagsChanged.update { 2L } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + + verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.METADATA.name), any()) } + } finally { + sut.stopObservingBackups() + } + } + + @Test + fun `ordinary activity upload is skipped while a restore is pending`() = test { + val activitiesChanged = MutableStateFlow(0L) + stubBackupObservers() + stubActivityBackupReads() + whenever(activityRepo.activitiesChanged).thenReturn(activitiesChanged) + stubBackupStatuses( + MutableStateFlow(emptyMap()), + CompletableDeferred().apply { complete(Unit) }, + ) {} + + try { + // The restore flow announces itself long before it reads the backup. + sut.setRestorePending(true) + sut.startObservingBackups() + runCurrent() + + // Meanwhile the node started and synced the fresh wallet's activities. + activitiesChanged.update { 1L } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + + // Uploading here replaces the stored envelope with the fresh wallet's state before the + // restore reads it, which loses the tags and the closed channels it still holds. + verify(vssBackupClient, never()).putObject(eq(BackupCategory.ACTIVITY.name), any()) + } finally { + sut.stopObservingBackups() + } + } + + @Test + fun `ordinary activity upload resumes once the restore is no longer pending`() = test { + val activitiesChanged = MutableStateFlow(0L) + stubBackupObservers() + stubActivityBackupReads() + whenever(activityRepo.activitiesChanged).thenReturn(activitiesChanged) + stubBackupStatuses( + MutableStateFlow(emptyMap()), + CompletableDeferred().apply { complete(Unit) }, + ) {} + + try { + sut.setRestorePending(true) + sut.startObservingBackups() + runCurrent() + + activitiesChanged.update { 1L } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + + verify(vssBackupClient, never()).putObject(eq(BackupCategory.ACTIVITY.name), any()) + + sut.setRestorePending(false) + whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(2_000)) + + activitiesChanged.update { 2L } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + + verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.ACTIVITY.name), any()) } + } finally { + sut.stopObservingBackups() + } + } + + @Test + fun `scheduled activity backup skips an unchanged payload`() = test { + val activitiesChanged = MutableStateFlow(0L) + val backupStatuses = MutableStateFlow>(emptyMap()) + stubBackupObservers() + stubActivityBackupReads() + whenever(activityRepo.activitiesChanged).thenReturn(activitiesChanged) + stubBackupStatuses(backupStatuses, CompletableDeferred().apply { complete(Unit) }) {} + + try { + sut.startObservingBackups() + runCurrent() + + activitiesChanged.update { 1L } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + verify(vssBackupClient, times(1)).putObject(eq(BackupCategory.ACTIVITY.name), any()) + + // Every wallet sync announces a change, even when no activity was added or updated. + whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(2_000)) + activitiesChanged.update { 2L } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + + verify(vssBackupClient, times(1)).putObject(eq(BackupCategory.ACTIVITY.name), any()) + val status = backupStatuses.value.getValue(BackupCategory.ACTIVITY) + assertFalse(status.isRequired) + assertFalse(status.running) + + whenever(activityRepo.getAllActivitiesTags()).thenReturn(Result.success(listOf(defaultTag()))) + activitiesChanged.update { 3L } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + + verify(vssBackupClient, times(2)).putObject(eq(BackupCategory.ACTIVITY.name), any()) + } finally { + sut.stopObservingBackups() + } + } + + @Test + fun `a full backup upgrades a pending activity upload for the same wallet`() = test { + val category = BackupCategory.ACTIVITY + val changes = MutableStateFlow(0L) + val statuses = MutableStateFlow>(emptyMap()) + stubBackupObservers() + stubActivityBackupReads() + whenever(activityRepo.activitiesChanged).thenReturn(changes) + stubBackupStatuses(statuses, CompletableDeferred(Unit)) {} + + try { + sut.startObservingBackups() + runCurrent() + sut.triggerBackup(category).getOrThrow() + changes.update { it + 1 } + runCurrent() + assertTrue(statuses.value.getValue(category).running) + sut.scheduleFullBackup() + advanceTimeBy(10_000) + runCurrent() + + verify(vssBackupClient, times(2)).putObject(eq(category.name), any()) + assertFalse(statuses.value.getValue(category).isRequired) + } finally { + sut.stopObservingBackups() + } + } + + @Test + fun `a full backup requested during unchanged activity capture still uploads`() = test { + val category = BackupCategory.ACTIVITY + val changes = MutableStateFlow(0L) + val entered = CompletableDeferred() + val resume = CompletableDeferred() + stubBackupObservers() + stubActivityBackupReads() + whenever(activityRepo.activitiesChanged).thenReturn(changes) + stubBackupStatuses(MutableStateFlow(emptyMap()), CompletableDeferred(Unit)) {} + + try { + sut.startObservingBackups() + runCurrent() + sut.triggerBackup(category).getOrThrow() + whenever(activityRepo.getActivities()).doSuspendableAnswer { + entered.complete(Unit) + resume.await() + Result.success(emptyList()) + } + changes.update { it + 1 } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + assertTrue(entered.isCompleted) + + sut.scheduleFullBackup() + advanceTimeBy(10_000) + runCurrent() + resume.complete(Unit) + runCurrent() + advanceTimeBy(10_000) + runCurrent() + + verify(vssBackupClient, times(2)).putObject(eq(category.name), any()) + } finally { + resume.complete(Unit) + sut.stopObservingBackups() + } + } + + @Test + fun `full activity backup survives observer stop while an unchanged result is being recorded`() = test { + assertFullActivityBackupDuringStatusWrite(afterTransform = false) + } + + @Test + fun `full activity backup survives observer stop before a clean status is published`() = test { + assertFullActivityBackupDuringStatusWrite(afterTransform = true) + } + + private suspend fun TestScope.assertFullActivityBackupDuringStatusWrite(afterTransform: Boolean) { + val category = BackupCategory.ACTIVITY + val changes = MutableStateFlow(0L) + val recording = CompletableDeferred() + val resume = CompletableDeferred() + val storeLock = Mutex() + val statusesBeforePut = mutableListOf() + var fullRequested = false + var uploaded = false + var captured = false + stubBackupObservers() + stubActivityBackupReads() + whenever(activityRepo.activitiesChanged).thenReturn(changes) + + try { + sut.startObservingBackups() + runCurrent() + sut.triggerBackup(category).getOrThrow() + whenever(vssBackupClient.putObject(eq(category.name), any())).doSuspendableAnswer { + uploaded = true + Result.success(VssItem(key = category.name, value = it.getArgument(1), version = 2)) + } + whenever(activityRepo.getClosedChannels()).doSuspendableAnswer { + captured = true + Result.success(emptyList()) + } + whenever(cacheStore.update(any())).doSuspendableAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + storeLock.withLock { + if (captured && !recording.isCompleted) { + val updated = if (afterTransform) transform(cacheData.value) else null + recording.complete(Unit) + resume.await() + cacheData.value = updated ?: transform(cacheData.value) + } else { + cacheData.update(transform) + } + if (fullRequested && !uploaded) { + statusesBeforePut += cacheData.value.backupStatuses.getValue(category) + } + } + } + changes.update { it + 1 } + advanceTimeBy(5_000) + runCurrent() + assertTrue(recording.isCompleted) + verify(vssBackupClient).putObject(eq(category.name), any()) + + fullRequested = true + sut.scheduleFullBackup() + sut.stopObservingBackups() + resume.complete(Unit) + advanceTimeBy(5_000) + runCurrent() + + verify(vssBackupClient, times(2)).putObject(eq(category.name), any()) + assertFalse(cacheData.value.backupStatuses.getValue(category).isRequired) + if (!afterTransform) { + assertTrue(statusesBeforePut.isNotEmpty()) + assertTrue(statusesBeforePut.all { it.isRequired }, "Full request lost: $statusesBeforePut") + } + } finally { + resume.complete(Unit) + sut.stopObservingBackups() + } + } + + @Test + fun `a new wallet owner uploads activity even if its payload matches the previous owner`() = test { + val category = BackupCategory.ACTIVITY + val changes = MutableStateFlow(0L) + stubBackupObservers() + stubActivityBackupReads() + whenever(activityRepo.activitiesChanged).thenReturn(changes) + stubBackupStatuses(MutableStateFlow(emptyMap()), CompletableDeferred(Unit)) {} + + sut.triggerBackup(category).getOrThrow() + vssClients.withSuspendedClients(shutdown = {}) {} + try { + sut.startObservingBackups() + runCurrent() + changes.update { it + 1 } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + + verify(vssBackupClient, times(2)).putObject(eq(category.name), any()) + } finally { + sut.stopObservingBackups() + } + } + + @Test + fun `scheduled activity backup uploads a reverted payload after a failed upload`() = test { + val activitiesChanged = MutableStateFlow(0L) + stubBackupObservers() + stubActivityBackupReads() + whenever(activityRepo.activitiesChanged).thenReturn(activitiesChanged) + stubBackupStatuses(MutableStateFlow(emptyMap()), CompletableDeferred().apply { complete(Unit) }) {} + + try { + sut.startObservingBackups() + runCurrent() + sut.triggerBackup(BackupCategory.ACTIVITY).getOrThrow() + + // The server can commit a write whose response never reaches the client. + whenever(activityRepo.getAllActivitiesTags()).thenReturn(Result.success(listOf(defaultTag()))) + whenever(vssBackupClient.putObject(any(), any())).thenReturn(Result.failure(BackupRepoTestError("io"))) + assertTrue(sut.triggerBackup(BackupCategory.ACTIVITY).isFailure) + + val uploaded = VssItem(key = BackupCategory.ACTIVITY.name, value = byteArrayOf(), version = 2) + whenever(vssBackupClient.putObject(any(), any())).thenReturn(Result.success(uploaded)) + whenever(activityRepo.getAllActivitiesTags()).thenReturn(Result.success(emptyList())) + activitiesChanged.update { 1L } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + + verify(vssBackupClient, times(3)).putObject(eq(BackupCategory.ACTIVITY.name), any()) + } finally { + sut.stopObservingBackups() + } + } + + @Test + fun `scheduled activity backup uploads an unchanged payload after reset`() = test { + val activitiesChanged = MutableStateFlow(0L) + stubBackupObservers() + stubActivityBackupReads() + whenever(activityRepo.activitiesChanged).thenReturn(activitiesChanged) + stubBackupStatuses(MutableStateFlow(emptyMap()), CompletableDeferred().apply { complete(Unit) }) {} + sut.triggerBackup(BackupCategory.ACTIVITY).getOrThrow() + + sut.reset() + try { + sut.startObservingBackups() + runCurrent() + activitiesChanged.update { 1L } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + + verify(vssBackupClient, times(2)).putObject(eq(BackupCategory.ACTIVITY.name), any()) + } finally { + sut.stopObservingBackups() + } + } + + @Test + fun `explicit activity backup uploads an unchanged payload`() = test { + stubActivityBackupReads() + + sut.triggerBackup(BackupCategory.ACTIVITY).getOrThrow() + sut.triggerBackup(BackupCategory.ACTIVITY).getOrThrow() + + verify(vssBackupClient, times(2)).putObject(eq(BackupCategory.ACTIVITY.name), any()) + } + + @Test + fun `pending restore stops gating uploads once it expires`() = test { + val activitiesChanged = MutableStateFlow(0L) + stubBackupObservers() + stubActivityBackupReads() + whenever(activityRepo.activitiesChanged).thenReturn(activitiesChanged) + stubBackupStatuses( + MutableStateFlow(emptyMap()), + CompletableDeferred().apply { complete(Unit) }, + ) {} + + try { + sut.setRestorePending(true) + sut.startObservingBackups() + runCurrent() + + // The restore never returns, so nothing ever clears the gate. + whenever(clock.now()).thenReturn(Instant.fromEpochMilliseconds(RESTORE_GATE_EXPIRED_AT)) + + activitiesChanged.update { 1L } + runCurrent() + advanceTimeBy(10_000) + runCurrent() + + verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.ACTIVITY.name), any()) } + } finally { + sut.stopObservingBackups() + } + } + + @Test + fun `migration rewrite still uploads while a restore is pending`() = test { + stubWalletBackup() + stubActivityRestore() + sut.setRestorePending(true) + + val result = sut.performFullRestoreFromLatestBackup() + + // The rewrite is the restore's own upload, so the gate must never hold it. + assertTrue(result.isSuccess) + verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.ACTIVITY.name), any()) } + } + + @Test + fun `metadata backup fails when pre-activity metadata cannot be read`() = test { + stubMetadataBackupReads() + whenever { preActivityMetadataRepo.getAllPreActivityMetadata() } + .thenReturn(Result.failure(BackupRepoTestError("core unavailable"))) + + val result = sut.triggerBackup(BackupCategory.METADATA) + + assertTrue(result.isFailure) + // Uploading here would replace the stored tags with an empty set. + verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) + } + + @Test + fun `metadata backup fails when hardware tags cannot be read`() = test { + stubMetadataBackupReads() + whenever { activityRepo.getHardwareTagsAsPreActivityMetadata() } + .thenReturn(Result.failure(BackupRepoTestError("core unavailable"))) + + val result = sut.triggerBackup(BackupCategory.METADATA) + + assertTrue(result.isFailure) + // This envelope is the only copy of hardware tags, so a partial upload would lose them. + verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) + } + + @Test + fun `activity backup excludes hardware tags`() = test { + whenever { activityRepo.getActivities() }.thenReturn(Result.success(emptyList())) + whenever { activityRepo.getClosedChannels() }.thenReturn(Result.success(emptyList())) + // ActivityRepo already scopes this to the default wallet, so a hardware tag can never appear here. + whenever { activityRepo.getAllActivitiesTags() }.thenReturn(Result.success(listOf(defaultTag()))) + val dataCaptor = argumentCaptor() + + sut.triggerBackup(BackupCategory.ACTIVITY) + + verifyBlocking(vssBackupClient) { + putObject(eq(BackupCategory.ACTIVITY.name), dataCaptor.capture()) + } + val payload = json.decodeFromString(dataCaptor.firstValue.decodeToString()) + assertTrue(payload.activityTags.none { it.walletId == HARDWARE_WALLET_ID }) + } + + @Test + fun `activity backup is not rewritten when core restore fails`() = test { + stubWalletBackup() + stubActivityRestore() + whenever { activityRepo.restoreFromBackup(any()) } + .thenReturn(Result.failure(BackupRepoTestError("upsert failed"))) + + val result = sut.performFullRestoreFromLatestBackup() + + assertEquals(setOf(BackupCategory.ACTIVITY), result.getOrThrow()) + // Rewriting here would replace the legacy backup with whatever Core happens to hold. + verify(vssBackupClient, never()).putObject(eq(BackupCategory.ACTIVITY.name), any()) + } + + @Test + fun `failed core migration skips the category without failing the restore`() = test { + stubWalletBackup() + stubActivityRestore() + whenever { activityRepo.migrateBackupActivityTagsJson(any()) } + .thenReturn(Result.failure(BackupRepoTestError("core migration failed"))) + + val result = sut.performFullRestoreFromLatestBackup() + + // Only WALLET is fatal, so the restore still succeeds and reports the category. + assertEquals(setOf(BackupCategory.ACTIVITY), result.getOrThrow()) + // The legacy slice stays unmigrated and no longer decodes, so nothing of this category is applied. + verifyBlocking(activityRepo, never()) { restoreFromBackup(any()) } + // Nothing was restored, so the stored backup must not be replaced. + verify(vssBackupClient, never()).putObject(eq(BackupCategory.ACTIVITY.name), any()) + } + + private fun stubActivityBackupReads() { + whenever { activityRepo.getActivities() }.thenReturn(Result.success(emptyList())) + whenever { activityRepo.getClosedChannels() }.thenReturn(Result.success(emptyList())) + whenever { activityRepo.getAllActivitiesTags() }.thenReturn(Result.success(emptyList())) + } + + private fun pendingPublicAddressRestoreRecord(type: String): JsonObject { + val stored = requireNotNull(keychain.loadString(Keychain.Key.PAYKIT_PENDING_PUBLIC_ADDRESS_RESTORE.name)) + return json.parseToJsonElement(stored).jsonObject.also { + assertEquals(type, it["type"]?.jsonPrimitive?.content) + } + } + + private suspend fun assertCancelledMetadataDownloadCanRetry(metadataOnRetry: String?) = coroutineScope { + val reservationStore = stubPublicAddressRestore("") + whenever(preActivityMetadataRepo.migrateBackupPreActivityMetadataJson(any())).thenAnswer { + Result.success(it.getArgument(0)) + } + whenever(preActivityMetadataRepo.getAllPreActivityMetadata()).thenReturn(Result.success(emptyList())) + val downloadStarted = CompletableDeferred() + var holdDownload = true + val metadata = metadataOnRetry?.let { + VssItem(key = BackupCategory.METADATA.name, value = it.toByteArray(), version = 1) + } + whenever(vssBackupClient.getObject(BackupCategory.METADATA.name)).doSuspendableAnswer { + if (holdDownload) { + downloadStarted.complete(Unit) + awaitCancellation() + } + Result.success(metadata) + } + val restore = async { sut.performFullRestoreFromLatestBackup() } + try { + downloadStarted.await() + } finally { + restore.cancelAndJoin() + } + + assertTrue(restore.isCancelled) + assertFalse(sut.isRestoring.value) + assertFalse(settingsData.value.backupVerified) + assertTrue(sut.hasPendingWalletRestore()) + pendingPublicAddressRestoreRecord("reading") + assertTrue(reservationStore.data.first().quarantinedPublicAddresses.isEmpty()) + verify(vssBackupClient, never()).getObject(BackupCategory.WALLET.name) + + holdDownload = false + val restartedReservations = createReservationRepo(reservationStore) + sut = createSut(reservationRepo = restartedReservations) + sut.setRestorePending(false) + assertTrue(sut.performFullRestoreFromLatestBackup().isSuccess) + + assertTrue(settingsData.value.backupVerified) + assertFalse(sut.hasPendingWalletRestore()) + assertNull(keychain.loadString(Keychain.Key.PAYKIT_PENDING_PUBLIC_ADDRESS_RESTORE.name)) + assertTrue(reservationStore.data.first().quarantinedPublicAddresses.isEmpty()) + whenever(lightningRepo.newAddressInfoForType(any())) + .thenReturn(Result.success(AddressDerivationInfo("bcrt1qreceive", 0))) + assertEquals("bcrt1qreceive", restartedReservations.nextReusableReceiveAddress().getOrThrow()) + sut.triggerBackup(BackupCategory.METADATA).getOrThrow() + verify(vssBackupClient).putObject(eq(BackupCategory.METADATA.name), any()) + } + + private fun stubPublicAddressRestore( + address: String, + quarantineFailure: Throwable? = null, + addressRecordFailure: Throwable? = null, + sourceRecordFailure: Throwable? = null, + ): PrivatePaykitReservationStore { + stubMetadataRestore( + envelope = metadataEnvelope( + metadata = listOf(preActivityMetadata()), + cache = AppCacheData(onchainAddress = address), + ), + ) + stubRestoreEnvelope(BackupCategory.WALLET, """{"version":1,"createdAt":123,"transfers":[]}""") + stubRestoreEnvelope( + BackupCategory.SETTINGS, + json.encodeToString( + SettingsBackupV1( + createdAt = 123, + settings = SettingsData( + sharesPrivatePaykitEndpoints = true, + sharesPublicPaykitEndpoints = true, + hasConfirmedPublicPaykitEndpoints = true, + ), + ), + ), + ) + whenever { settingsStore.restoreFromBackup(any()) }.thenAnswer { + val payload = it.getArgument(0) + settingsData.update { payload.settings.withPublicSharingDisabledForRestore() } + Result.success(Unit) + } + whenever { settingsStore.update(any()) }.thenAnswer { + val transform = it.getArgument<(SettingsData) -> SettingsData>(0) + settingsData.update(transform) + } + whenever { cacheStore.update(any()) }.thenAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + cacheData.update(transform) + } + whenever(cacheStore.backupStatuses).thenReturn(cacheData.map { it.backupStatuses }) + whenever { cacheStore.updateBackupStatus(any(), any()) }.thenAnswer { + val category = it.getArgument(0) + val transform = it.getArgument<(BackupItemStatus) -> BackupItemStatus>(1) + cacheData.update { cache -> + val status = cache.backupStatuses[category] ?: BackupItemStatus() + cache.copy(backupStatuses = cache.backupStatuses + (category to transform(status))) + } + } + val retained = mutableMapOf() + var nextRecordFailure = addressRecordFailure + var nextSourceFailure = sourceRecordFailure + whenever(keychain.exists(any())).thenAnswer { it.getArgument(0) in retained } + whenever(keychain.loadString(any())).thenAnswer { retained[it.getArgument(0)] } + whenever { keychain.upsertString(any(), any()) }.thenAnswer { + val key = it.getArgument(0) + val value = it.getArgument(1) + if (key == Keychain.Key.PAYKIT_PENDING_PUBLIC_ADDRESS_RESTORE.name) { + when (json.parseToJsonElement(value).jsonObject["type"]?.jsonPrimitive?.content) { + "source" -> nextSourceFailure?.let { failure -> + nextSourceFailure = null + throw failure + } + "address" -> nextRecordFailure?.let { failure -> + nextRecordFailure = null + throw failure + } + } + } + retained[key] = value + Unit + } + whenever { keychain.delete(any()) }.thenAnswer { + retained.remove(it.getArgument(0)) + Unit + } + val reservationStore = mock() + val reservationData = MutableStateFlow(PrivatePaykitReservationData()) + var nextFailure = quarantineFailure + whenever(reservationStore.data).thenReturn(reservationData) + whenever { reservationStore.update(any()) }.thenAnswer { + nextFailure?.let { failure -> + nextFailure = null + throw failure + } + val transform = it.getArgument<(PrivatePaykitReservationData) -> PrivatePaykitReservationData>(0) + reservationData.update(transform) + } + sut = createSut(reservationRepo = createReservationRepo(reservationStore)) + return reservationStore + } + + private fun createReservationRepo( + reservationStore: PrivatePaykitReservationStore, + ) = PrivatePaykitAddressReservationRepo( + ioDispatcher = testDispatcher, + reservationStore = reservationStore, + settingsStore = settingsStore, + coreService = coreService, + lightningRepo = lightningRepo, + cacheStore = cacheStore, + keychain = keychain, + ) + + private fun stubMetadataBackupReads() { + whenever { preActivityMetadataRepo.getAllPreActivityMetadata() } + .thenReturn(Result.success(listOf(preActivityMetadata()))) + whenever { activityRepo.getHardwareTagsAsPreActivityMetadata() }.thenReturn(Result.success(emptyList())) + whenever { pubkyRepo.snapshotSessionBackupState() }.thenReturn(Result.success(null)) + whenever { pubkyRepo.snapshotContactProfileOverrides() }.thenReturn(Result.success(null)) + } + + private fun stubActivityRestore( + envelope: String = legacyActivityEnvelope(), + migratedTagsJson: String = json.encodeToString(listOf(defaultTag())), + backedUpTags: List = listOf(defaultTag()), + ) { + stubRestoreEnvelope(BackupCategory.ACTIVITY, envelope) + whenever { activityRepo.migrateBackupActivitiesJson(any()) }.thenReturn(Result.success("[]")) + whenever { activityRepo.migrateBackupActivityTagsJson(any()) }.thenReturn(Result.success(migratedTagsJson)) + whenever { activityRepo.restoreFromBackup(any()) }.thenReturn(Result.success(Unit)) + // Read back by the rewrite through getBackupDataBytes(ACTIVITY). + whenever { activityRepo.getActivities() }.thenReturn(Result.success(emptyList())) + whenever { activityRepo.getClosedChannels() }.thenReturn(Result.success(emptyList())) + whenever { activityRepo.getAllActivitiesTags() }.thenReturn(Result.success(backedUpTags)) + } + + private fun stubMetadataRestore( + envelope: String = legacyMetadataEnvelope(), + migratedMetadataJson: String = json.encodeToString(listOf(preActivityMetadata())), + restorableMetadata: List = listOf(preActivityMetadata()), + ) { + stubRestoreEnvelope(BackupCategory.METADATA, envelope) + whenever { preActivityMetadataRepo.migrateBackupPreActivityMetadataJson(any()) } + .thenReturn(Result.success(migratedMetadataJson)) + whenever { preActivityMetadataRepo.upsertPreActivityMetadata(any()) }.thenReturn(Result.success(Unit)) + whenever { pubkyRepo.restoreSessionBackupState(anyOrNull()) }.thenReturn(Result.success(Unit)) + whenever { pubkyRepo.restoreContactProfileOverrides(anyOrNull()) }.thenReturn(Result.success(Unit)) + // Read back by the rewrite through getMetadataBackupDataBytes(). + whenever { preActivityMetadataRepo.getAllPreActivityMetadata() } + .thenReturn(Result.success(restorableMetadata)) + whenever { activityRepo.getHardwareTagsAsPreActivityMetadata() }.thenReturn(Result.success(emptyList())) + whenever { pubkyRepo.snapshotSessionBackupState() }.thenReturn(Result.success(null)) + whenever { pubkyRepo.snapshotContactProfileOverrides() }.thenReturn(Result.success(null)) + } + + private fun iosFixture(name: String) = + requireNotNull(javaClass.getResourceAsStream("/ios-backup/$name.json")).bufferedReader().readText() + + private fun stubRestoreEnvelope(category: BackupCategory, envelope: String) { + whenever { vssBackupClient.getObject(category.name) }.thenReturn( + Result.success( + VssItem(key = category.name, value = envelope.toByteArray(), version = 1) + ) + ) + } + + /** An `ActivityBackupV1` whose Core-owned tag records predate `walletId`. */ + private fun legacyActivityEnvelope(): String = envelopeWithRawField( + base = activityEnvelope(), + field = "activityTags", + rawJson = LEGACY_TAGS_JSON, + ) + + /** A `MetadataBackupV1` whose Core-owned metadata records predate `walletId`. */ + private fun legacyMetadataEnvelope(): String = envelopeWithRawField( + base = metadataEnvelope(), + field = "tagMetadata", + rawJson = LEGACY_METADATA_JSON, + ) + + private fun activityEnvelope(tags: List = emptyList()) = json.encodeToString( + ActivityBackupV1( + createdAt = 123, + activities = emptyList(), + activityTags = tags, + closedChannels = emptyList(), + ) + ) + + private fun metadataEnvelope( + metadata: List = emptyList(), + cache: AppCacheData = AppCacheData(), + hwWalletNames: Map? = null, + ) = json.encodeToString( MetadataBackupV1( createdAt = 123, - tagMetadata = metadata, - cache = cache, - hwWalletNames = hwWalletNames, + tagMetadata = metadata, + cache = cache, + hwWalletNames = hwWalletNames, + ) + ) + + private fun envelopeWithRawField(base: String, field: String, rawJson: String): String { + val patched = json.parseToJsonElement(base).jsonObject.toMutableMap() + patched[field] = json.parseToJsonElement(rawJson) + return JsonObject(patched).toString() + } + + private fun defaultTag() = ActivityTags( + walletId = WalletScope.default, + activityId = "a1", + tags = listOf("coffee"), + ) + + private fun knownDevice(customLabel: String? = null) = KnownDevice( + id = "dev1", + name = "Trezor", + path = "usb-1", + transportType = TransportType.USB, + label = null, + model = "Safe 3", + lastConnectedAt = 1, + xpubs = mapOf("nativeSegwit" to "zpubNS"), + customLabel = customLabel, + walletId = HARDWARE_WALLET_ID, + ) + + private fun preActivityMetadata() = PreActivityMetadata( + walletId = WalletScope.default, + paymentId = "p1", + tags = listOf("coffee"), + paymentHash = null, + txId = null, + address = null, + isReceive = true, + feeRate = 1uL, + isTransfer = false, + channelId = null, + createdAt = 1uL, + ) + + private fun stubWalletBackup( + paykitSdkBackupState: String? = null, + watchOnlyAccounts: List? = null, + watchOnlyAccountAllocationState: WatchOnlyAccountAllocationState? = null, + paykitPaymentState: PaykitPaymentStateBackup? = null, + usdtWallet: String? = null, + ) { + val walletBackup = WalletBackupV1( + createdAt = 123, + transfers = emptyList(), + privatePaykitHighestReservedReceiveIndexByAddressType = mapOf("nativeSegwit" to 5), + paykitSdkBackupState = paykitSdkBackupState, + watchOnlyAccounts = watchOnlyAccounts, + watchOnlyAccountAllocationState = watchOnlyAccountAllocationState, + paykitPaymentState = paykitPaymentState, + usdtWallet = usdtWallet, + ) + whenever { vssBackupClient.getObject(BackupCategory.WALLET.name) } + .thenReturn( + Result.success( + VssItem( + key = BackupCategory.WALLET.name, + value = json.encodeToString(walletBackup).toByteArray(), + version = 1, + ) + ) + ) + } + + private fun stubBackupStatuses( + backupStatuses: MutableStateFlow>, + allowWalletClear: CompletableDeferred, + onWalletClearDelayed: () -> Unit, + ) { + whenever(cacheStore.backupStatuses).thenReturn(backupStatuses) + 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 } + } + } + + private fun stubBackupObservers() { + whenever { transferDao.observeAll() }.thenReturn(MutableStateFlow(emptyList())) + whenever(blocktankRepo.blocktankState).thenReturn(MutableStateFlow(BlocktankState())) + whenever(activityRepo.activitiesChanged).thenReturn(MutableStateFlow(0L)) + whenever(activityRepo.activityTagsChanged).thenReturn(MutableStateFlow(0L)) + whenever(pubkyRepo.backupStateVersion).thenReturn(MutableStateFlow(0L)) + whenever(paykitSdkService.backupStateVersion).thenReturn(MutableStateFlow(0L)) + whenever(privatePaykitRepo.backupStateVersion).thenReturn(MutableStateFlow(0L)) + whenever(privatePaykitAddressReservationRepo.backupStateVersion).thenReturn(MutableStateFlow(0L)) + whenever(paykitPaymentProofStore.backupStateVersion).thenReturn(MutableStateFlow(0L)) + whenever(paykitPresentationStore.backupStateVersion).thenReturn(MutableStateFlow(0L)) + whenever(paykitAllowanceStore.backupStateVersion).thenReturn(MutableStateFlow(0L)) + whenever(paykitOutboundDeliveryStore.backupStateVersion).thenReturn(MutableStateFlow(0L)) + whenever(preActivityMetadataRepo.preActivityMetadataChanged).thenReturn(MutableStateFlow(0L)) + whenever(lightningService.syncStatusChanged).thenReturn(MutableSharedFlow()) + } + + @Test + fun `native restore gate survives malformed connection correction`() = test { + whenever(keychain.loadString(WalletConnectionRecovery.KEY, 0)).thenReturn("malformed") + assertTrue(sut.performFullRestoreFromLatestBackup().isFailure) + verify(keychain).upsertString(Keychain.Key.PAYKIT_PENDING_BACKUP_RESTORE.name, "") + verify(vssBackupClient, never()).getObject(any()) + } + + @Test + fun `stored spark exit data spark can't import is kept apart and the upload goes through`() = test { + val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "v9")) + .toByteArray() + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.mergeRemoteExitBackup(anyOrNull())) + .thenReturn(Result.failure(SparkError.ExitStateUnimportable())) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + inOrder(sparkRepo, vssBackupClient) { + verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) + verify(sparkRepo).skipUnimportableRemoteExitState("v9") + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + } + + @Test + fun `stored spark exit data that doesn't parse is kept apart and the upload goes through`() = test { + val stored = "not exit data".toByteArray() + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) + verify(sparkRepo, never()).mergeRemoteExitBackup(anyOrNull()) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + + @Test + fun `a rejected spark exit copy already set aside is not uploaded again`() = test { + val stored = "not exit data".toByteArray() + stubUnreadableStoredExit(stored) + val key = BackupRepo.rejectedExitKey(stored) + whenever( + vssBackupClient.getObject(key) + ).thenReturn(Result.success(VssItem(key = key, value = stored, version = 1))) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + verify(vssBackupClient, never()).putObject(argThat { startsWith(BackupRepo.SPARK_EXIT_REJECTED_KEY) }, any()) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + + @Test + fun `each rejected spark exit copy goes under its own digest key and never the plain key`() = test { + val stored = "not exit data".toByteArray() + stubUnreadableStoredExit(stored) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + val digest = MessageDigest.getInstance("SHA-256").digest(stored).joinToString("") { "%02x".format(it) } + verify(vssBackupClient).putObject("${BackupRepo.SPARK_EXIT_REJECTED_KEY}_${digest.take(16)}", stored) + verify(vssBackupClient, never()).putObject(eq(BackupRepo.SPARK_EXIT_REJECTED_KEY), any()) + } + + private suspend fun stubUnreadableStoredExit(stored: ByteArray) { + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + } + + @Test + fun `staged exit data spark rejects is set aside as the stored backup that holds it`() = test { + val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "v9")) + .toByteArray() + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.importStagedExitState()).thenReturn(StagedExitImport.Rejected("v9", "regtest")) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + inOrder(sparkRepo, vssBackupClient) { + verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) + verify(sparkRepo).discardStagedExitState("v9") + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + } + + @Test + fun `staged exit data spark rejects is set aside on its own once the stored backup moved on`() = test { + val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "newer")) + .toByteArray() + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.importStagedExitState()).thenReturn(StagedExitImport.Rejected("v9", "regtest")) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + val kept = argumentCaptor() + verify( + vssBackupClient + ).putObject(argThat { startsWith("${BackupRepo.SPARK_EXIT_REJECTED_KEY}_") }, kept.capture()) + assertEquals( + SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "v9"), + json.decodeFromString(String(kept.firstValue)), + ) + verify(sparkRepo).discardStagedExitState("v9") + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + + @Test + fun `staged exit data spark rejects merges the stored backup another device replaced before the upload`() = test { + val newer = SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "newer") + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( + Result.success( + VssItem( + key = BackupCategory.SPARK_EXIT.name, + value = json.encodeToString(newer).toByteArray(), + version = 2 + ) + ) + ) + // A merge already ran in this session, before another device stored newer exit data. + mergeFlagFollowsDiscard(hasMerged = true) + whenever(sparkRepo.importStagedExitState()).thenReturn(StagedExitImport.Rejected("v9", "regtest")) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + inOrder(sparkRepo, vssBackupClient) { + verify(sparkRepo).mergeRemoteExitBackup(newer) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + } + + @Test + fun `a rejected staged copy dropped before a failed merge still merges on the next upload`() = test { + val newer = SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "other device") + val stored = VssItem( + key = BackupCategory.SPARK_EXIT.name, + value = json.encodeToString(newer).toByteArray(), + version = 2 + ) + mergeFlagFollowsDiscard(hasMerged = true) + whenever(sparkRepo.importStagedExitState()) + .thenReturn(StagedExitImport.Rejected("v9", "regtest"), StagedExitImport.NothingStaged) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + // The copy is set aside and dropped, then the read for the merge fails. + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( + Result.success(stored), + Result.failure(IllegalStateException("offline")), + Result.success(stored), ) - ) + assertTrue(sut.triggerBackup(BackupCategory.SPARK_EXIT).isFailure) - private fun envelopeWithRawField(base: String, field: String, rawJson: String): String { - val patched = json.parseToJsonElement(base).jsonObject.toMutableMap() - patched[field] = json.parseToJsonElement(rawJson) - return JsonObject(patched).toString() + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + inOrder(sparkRepo, vssBackupClient) { + verify(sparkRepo).mergeRemoteExitBackup(newer) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } } - private fun defaultTag() = ActivityTags( - walletId = WalletScope.default, - activityId = "a1", - tags = listOf("coffee"), - ) + @Test + fun `stored exit data replaced while unreadable data was set aside is merged before the upload`() = test { + val unreadable = "not exit data".toByteArray() + val replaced = SparkExitBackupV1(createdAt = 600, network = "regtest", exitState = "other device") + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( + Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = unreadable, version = 1)), + Result.success( + VssItem( + key = BackupCategory.SPARK_EXIT.name, + value = json.encodeToString(replaced).toByteArray(), + version = 2 + ) + ), + ) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) - private fun knownDevice(customLabel: String? = null) = KnownDevice( - id = "dev1", - name = "Trezor", - path = "usb-1", - transportType = TransportType.USB, - label = null, - model = "Safe 3", - lastConnectedAt = 1, - xpubs = mapOf("nativeSegwit" to "zpubNS"), - customLabel = customLabel, - walletId = HARDWARE_WALLET_ID, - ) + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() - private fun preActivityMetadata() = PreActivityMetadata( - walletId = WalletScope.default, - paymentId = "p1", - tags = listOf("coffee"), - paymentHash = null, - txId = null, - address = null, - isReceive = true, - feeRate = 1uL, - isTransfer = false, - channelId = null, - createdAt = 1uL, - ) + inOrder(sparkRepo, vssBackupClient) { + verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(unreadable), unreadable) + verify(sparkRepo).mergeRemoteExitBackup(replaced) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + verify(sparkRepo, never()).skipUnimportableRemoteExitState(anyOrNull()) + } - private fun stubWalletBackup( - paykitSdkBackupState: String? = null, - watchOnlyAccounts: List? = null, - watchOnlyAccountAllocationState: WatchOnlyAccountAllocationState? = null, - paykitPaymentState: PaykitPaymentStateBackup? = null, - usdtWallet: String? = null, - ) { - val walletBackup = WalletBackupV1( - createdAt = 123, - transfers = emptyList(), - privatePaykitHighestReservedReceiveIndexByAddressType = mapOf("nativeSegwit" to 5), - paykitSdkBackupState = paykitSdkBackupState, - watchOnlyAccounts = watchOnlyAccounts, - watchOnlyAccountAllocationState = watchOnlyAccountAllocationState, - paykitPaymentState = paykitPaymentState, - usdtWallet = usdtWallet, + @Test + fun `a spark exit merge that fails for another reason still blocks the upload`() = test { + val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "v1")) + .toByteArray() + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.mergeRemoteExitBackup(anyOrNull())).thenReturn(Result.failure(AppError("not connected"))) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) ) - whenever { vssBackupClient.getObject(BackupCategory.WALLET.name) } - .thenReturn( - Result.success( - VssItem( - key = BackupCategory.WALLET.name, - value = json.encodeToString(walletBackup).toByteArray(), - version = 1, - ) - ) - ) - } - private fun stubBackupStatuses( - backupStatuses: MutableStateFlow>, - allowWalletClear: CompletableDeferred, - 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)) - } - } - } + assertTrue(sut.triggerBackup(BackupCategory.SPARK_EXIT).isFailure) - private fun stubBackupObservers() { - whenever { transferDao.observeAll() }.thenReturn(MutableStateFlow(emptyList())) - whenever(blocktankRepo.blocktankState).thenReturn(MutableStateFlow(BlocktankState())) - whenever(activityRepo.activitiesChanged).thenReturn(MutableStateFlow(0L)) - whenever(activityRepo.activityTagsChanged).thenReturn(MutableStateFlow(0L)) - whenever(pubkyRepo.backupStateVersion).thenReturn(MutableStateFlow(0L)) - whenever(paykitSdkService.backupStateVersion).thenReturn(MutableStateFlow(0L)) - whenever(privatePaykitRepo.backupStateVersion).thenReturn(MutableStateFlow(0L)) - whenever(privatePaykitAddressReservationRepo.backupStateVersion).thenReturn(MutableStateFlow(0L)) - whenever(paykitPaymentProofStore.backupStateVersion).thenReturn(MutableStateFlow(0L)) - whenever(paykitPresentationStore.backupStateVersion).thenReturn(MutableStateFlow(0L)) - whenever(paykitAllowanceStore.backupStateVersion).thenReturn(MutableStateFlow(0L)) - whenever(paykitOutboundDeliveryStore.backupStateVersion).thenReturn(MutableStateFlow(0L)) - whenever(preActivityMetadataRepo.preActivityMetadataChanged).thenReturn(MutableStateFlow(0L)) - whenever(lightningService.syncStatusChanged).thenReturn(MutableSharedFlow()) + verify(vssBackupClient, never()).putObject(argThat { startsWith(BackupRepo.SPARK_EXIT_REJECTED_KEY) }, any()) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) } @Test - fun `native restore gate survives malformed connection correction`() = test { - whenever(keychain.loadString(WalletConnectionRecovery.KEY, 0)).thenReturn("malformed") - assertTrue(sut.performFullRestoreFromLatestBackup().isFailure) - verify(keychain).upsertString(Keychain.Key.PAYKIT_PENDING_BACKUP_RESTORE.name, "") - verify(vssBackupClient, never()).getObject(any()) + fun `a restore sets aside spark exit data it can't read and reports it not restored`() = test { + val stored = "not exit data".toByteArray() + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + + val failed = sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertTrue(BackupCategory.SPARK_EXIT in failed) + verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) + verify(sparkRepo, never()).restoreExitBackup(any(), any()) + verify(cacheStore, never()).updateBackupStatus(eq(BackupCategory.SPARK_EXIT), any()) } @Test - fun `legacy USDT restore gate precedes malformed connection correction`() = test { - whenever(keychain.loadString(WalletConnectionRecovery.KEY, 0)).thenReturn("malformed") - assertTrue(sut.restoreUsdtRecoveryAfterLegacyMigration().isFailure) - verify(keychain).upsertString(Keychain.Key.USDT_PENDING_BACKUP_RESTORE.name, "") - verify(vssBackupClient, never()).getObject(any()) - } + fun `restore brings back each identity's sent receipts`() = test { + val sent = mapOf("pubky" + "y".repeat(52) to setOf("receipt-1")) + stubWalletBackup( + paykitPaymentState = PaykitPaymentStateBackup( + subscriptions = emptyMap(), + pendingProofs = emptyList(), + sentReceipts = sent, + ), + ) - private fun createSut( - reservationRepo: PrivatePaykitAddressReservationRepo = privatePaykitAddressReservationRepo, - ioDispatcher: CoroutineDispatcher = testDispatcher, - ) = BackupRepo( - context = context, - ioDispatcher = ioDispatcher, - cacheStore = cacheStore, - vssBackupClient = vssBackupClient, - vssBackupClientLdk = vssBackupClientLdk, - settingsStore = settingsStore, - widgetsStore = widgetsStore, - watchOnlyAccountStore = watchOnlyAccountStore, - watchOnlyAccountRepo = watchOnlyAccountRepo, - hwWalletStore = hwWalletStore, - blocktankRepo = blocktankRepo, - activityRepo = activityRepo, - coreService = coreService, - pubkyRepo = pubkyRepo, - paykitSdkService = paykitSdkService, - privatePaykitRepo = Provider { privatePaykitRepo }, - privatePaykitAddressReservationRepo = Provider { reservationRepo }, - paykitPaymentProofRepo = Provider { paykitPaymentProofRepo }, - paykitUsdtPaymentRepo = Provider { paykitUsdtPaymentRepo }, - usdtRepo = Provider { usdtRepo }, - paykitPaymentProofStore = paykitPaymentProofStore, - paykitPaymentRequestRepo = Provider { paykitPaymentRequestRepo }, - paykitPresentationStore = paykitPresentationStore, - paykitAllowanceStore = paykitAllowanceStore, - paykitOutboundDeliveryStore = paykitOutboundDeliveryStore, - keychain = keychain, - onchainSendAttemptStore = onchainSendAttemptStore, - lightningRepo = Provider { lightningRepo }, - sparkRepo = sparkRepo, - vssStoreIdProvider = vssStoreIdProvider, - preActivityMetadataRepo = preActivityMetadataRepo, - lightningService = lightningService, - clock = clock, - db = db, - connectionRecovery = connectionRecoveryFixture(settingsStore, keychain), - ) + sut.performFullRestoreFromLatestBackup().getOrThrow() + + verify(paykitOutboundDeliveryStore).restoreBackup(sent) + } @Test fun `the restore log leaves out every payment detail`() { @@ -3890,4 +6673,55 @@ class BackupRepoTest : BaseUnitTest() { Result.success(Unit) } } + + @Test + fun `legacy USDT restore gate precedes malformed connection correction`() = test { + whenever(keychain.loadString(WalletConnectionRecovery.KEY, 0)).thenReturn("malformed") + assertTrue(sut.restoreUsdtRecoveryAfterLegacyMigration().isFailure) + verify(keychain).upsertString(Keychain.Key.USDT_PENDING_BACKUP_RESTORE.name, "") + verify(vssBackupClient, never()).getObject(any()) + } + + private fun createSut( + backupCache: CacheStore = cacheStore, + dispatcher: CoroutineDispatcher = testDispatcher, + reservationRepo: PrivatePaykitAddressReservationRepo = privatePaykitAddressReservationRepo, + ) = BackupRepo( + context = context, + ioDispatcher = dispatcher, + cacheStore = backupCache, + vssBackupClient = vssBackupClient, + vssBackupClientLdk = vssBackupClientLdk, + settingsStore = settingsStore, + widgetsStore = widgetsStore, + watchOnlyAccountStore = watchOnlyAccountStore, + watchOnlyAccountRepo = watchOnlyAccountRepo, + hwWalletStore = hwWalletStore, + blocktankRepo = blocktankRepo, + activityRepo = activityRepo, + coreService = coreService, + pubkyRepo = pubkyRepo, + paykitSdkService = paykitSdkService, + privatePaykitRepo = Provider { privatePaykitRepo }, + privatePaykitAddressReservationRepo = Provider { reservationRepo }, + paykitPaymentProofRepo = Provider { paykitPaymentProofRepo }, + paykitUsdtPaymentRepo = Provider { paykitUsdtPaymentRepo }, + usdtRepo = Provider { usdtRepo }, + paykitPaymentProofStore = paykitPaymentProofStore, + paykitPaymentRequestRepo = Provider { paykitPaymentRequestRepo }, + paykitPresentationStore = paykitPresentationStore, + paykitAllowanceStore = paykitAllowanceStore, + paykitOutboundDeliveryStore = paykitOutboundDeliveryStore, + keychain = keychain, + onchainSendAttemptStore = onchainSendAttemptStore, + lightningRepo = Provider { lightningRepo }, + sparkRepo = sparkRepo, + vssStoreIdProvider = vssStoreIdProvider, + preActivityMetadataRepo = preActivityMetadataRepo, + lightningService = lightningService, + clock = clock, + db = db, + 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 f81b8e28a6..9235604cd8 100644 --- a/app/src/test/java/to/bitkit/repositories/ContactPaymentSettingsRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/ContactPaymentSettingsRepoTest.kt @@ -3,14 +3,20 @@ package to.bitkit.repositories import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher 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 @@ -82,6 +88,287 @@ 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.syncPaykitApp(isNull(), eq(Priority.Background), any())).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) + assertFalse(settingsFlow.value.sharesPrivatePaykitEndpoints) + 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 `public sharing requests made during removal or wipe cannot reach a replacement sign in`() = test { + val refused = mutableListOf() + for (wipe in listOf(false, true)) { + for (enabled in listOf(false, true)) { + settingsFlow.value = SettingsData( + hasConfirmedPublicPaykitEndpoints = !enabled, + sharesPublicPaykitEndpoints = !enabled, + ) + whenever(pubkyRepo.currentSignIn()).thenReturn(PubkySignIn("original", 1L)) + val previous = settingsFlow.value + val sut = createSut() + clearInvocations(publicPaykitRepo) + val entered = CompletableDeferred() + val release = CompletableDeferred() + val hold: suspend () -> Unit = { + entered.complete(Unit) + release.await() + } + val barrier = async { + if (wipe) { + sut.withWalletWipe(admitRepository = { it() }, operation = hold) + } else { + sut.withProfileRemoval(hold) + } + } + entered.await() + val request = async { sut.setPublicEnabled(enabled) } + runCurrent() + whenever(pubkyRepo.currentSignIn()).thenReturn(PubkySignIn("replacement", 2L)) + release.complete(Unit) + barrier.await() + val result = request.await() + refused += result.isFailure && settingsFlow.value == previous + if (result.isFailure) verifyNoInteractions(publicPaykitRepo) + } + } + assertEquals(listOf(true, true, true, true), refused) + } + + @Test + fun `sharing requests queued on IO cannot cross a completed removal`() = test { + val operations = listOf Result>( + { setPublicEnabled(true) }, + { setEnabled(true) }, + { disablePaykit() }, + ) + val refused = mutableListOf() + for (operation in operations) { + settingsFlow.value = SettingsData() + whenever(pubkyRepo.currentSignIn()).thenReturn(PubkySignIn("original", 1L)) + val previous = settingsFlow.value + val sut = createSut(StandardTestDispatcher(testScheduler)) + clearInvocations(publicPaykitRepo, privatePaykitRepo) + val request = async(start = CoroutineStart.UNDISPATCHED) { sut.operation() } + assertFalse(request.isCompleted) + sut.withProfileRemoval { + whenever(pubkyRepo.currentSignIn()).thenReturn(PubkySignIn("replacement", 2L)) + } + runCurrent() + val result = request.await() + refused += result.isFailure && settingsFlow.value == previous + if (result.isFailure) verifyNoInteractions(publicPaykitRepo, privatePaykitRepo) + } + assertEquals(listOf(true, true, true), refused) + } + + @Test + fun `disabling private sharing without a live identity retains app cleanup`() = test { + whenever(pubkyRepo.currentSignIn()).thenReturn(null) + settingsFlow.value = SettingsData(sharesPrivatePaykitEndpoints = true) + var canSync: (suspend () -> Boolean)? = null + whenever(publicPaykitRepo.syncPaykitApp(eq(false), canSync = any())).doSuspendableAnswer { + canSync = it.getArgument(1) + Result.success(Unit) + } + + assertTrue(createSut().disablePaykit().isSuccess) + + assertFalse(settingsFlow.value.sharesPrivatePaykitEndpoints) + assertTrue(settingsFlow.value.publicPaykitCleanupPending) + assertFalse(requireNotNull(canSync).invoke()) + } + + @Test + fun `cancelled private-only disable retains app cleanup demand`() = test { + settingsFlow.value = SettingsData(sharesPrivatePaykitEndpoints = true) + whenever(privatePaykitRepo.disableSharingAndPruneUnsavedContactState(any(), anyOrNull())) + .doSuspendableAnswer { awaitCancellation() } + val disable = launch { createSut().disablePaykit() } + runCurrent() + assertFalse(disable.isCompleted) + disable.cancelAndJoin() + + assertFalse(settingsFlow.value.sharesPrivatePaykitEndpoints) + assertTrue(settingsFlow.value.publicPaykitCleanupPending) + } + + @Test + fun `sharing accepts fresh snapshots of the same identity generation`() = test { + whenever(pubkyRepo.currentSignIn()).thenAnswer { PubkySignIn("identity", 1L) } + whenever(pubkyRepo.isCurrent(any())).thenAnswer { + val signIn = it.getArgument(0) + signIn.publicKey == "identity" && signIn.generation == 1L + } + val sut = createSut() + val results = listOf( + sut.setPublicEnabled(true), + sut.setEnabled(true), + sut.setEnabled(false), + sut.disablePaykit(), + ) + assertEquals(List(4) { true }, results.map { it.isSuccess }) + } + + @Test + fun `queued sharing requests retain the original identity generation`() = test { + val operations = listOf Result>( + { setPublicEnabled(true) }, + { setEnabled(true) }, + { setEnabled(false) }, + { disablePaykit() }, + ) + val refused = mutableListOf() + for (waitForMutex in listOf(false, true)) { + for (operation in operations) { + settingsFlow.value = SettingsData(sharesPrivatePaykitEndpoints = true) + var signIn = PubkySignIn("identity", 1L) + whenever(pubkyRepo.currentSignIn()).thenAnswer { signIn } + whenever(pubkyRepo.isCurrent(any())).thenAnswer { it.getArgument(0) == signIn } + val previous = settingsFlow.value + val sut = createSut(StandardTestDispatcher(testScheduler)) + val release = CompletableDeferred() + val reconciliation = if (waitForMutex) { + launch { sut.reconcilePendingEndpoints { release.await() } }.also { runCurrent() } + } else { + null + } + clearInvocations(publicPaykitRepo, privatePaykitRepo) + val request = async(start = CoroutineStart.UNDISPATCHED) { sut.operation() } + if (waitForMutex) runCurrent() + assertFalse(request.isCompleted) + signIn = PubkySignIn("identity", 2L) + release.complete(Unit) + runCurrent() + reconciliation?.join() + val result = request.await() + refused += result.isFailure && settingsFlow.value == previous + if (result.isFailure) verifyNoInteractions(publicPaykitRepo, privatePaykitRepo) + } + } + assertEquals(List(8) { true }, refused) + } + + @Test + fun `disablePaykit preserves replacement state after private cleanup suspends`() = test { + var signIn = PubkySignIn("identity", 1L) + whenever(pubkyRepo.currentSignIn()).thenAnswer { signIn } + whenever(pubkyRepo.isCurrent(any())).thenAnswer { it.getArgument(0) == signIn } + settingsFlow.value = SettingsData( + sharesPublicPaykitEndpoints = true, + sharesPrivatePaykitEndpoints = true, + publicPaykitBolt11 = "old-invoice", + ) + val cleanup = CompletableDeferred() + whenever(privatePaykitRepo.disableSharingAndPruneUnsavedContactState(any(), anyOrNull())) + .doSuspendableAnswer { + cleanup.await() + Result.success(Unit) + } + val remoteOwners = mutableListOf() + whenever(publicPaykitRepo.syncPublishedEndpoints(any(), any(), anyOrNull())).thenAnswer { + val canPublish = it.getArgument<(() -> Boolean)?>(2) + if (canPublish?.invoke() != false) remoteOwners += signIn + Result.success(Unit) + } + val sut = createSut() + val disable = async { sut.disablePaykit() } + runCurrent() + assertFalse(disable.isCompleted) + signIn = PubkySignIn("identity", 2L) + val replacement = SettingsData( + sharesPublicPaykitEndpoints = true, + sharesPrivatePaykitEndpoints = true, + publicPaykitBolt11 = "replacement-invoice", + publicPaykitCleanupPending = true, + ) + settingsFlow.value = replacement + cleanup.complete(Unit) + val result = disable.await() + + assertTrue(result.isFailure && settingsFlow.value == replacement && remoteOwners.isEmpty()) + } + + @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 contact payments only enables private sharing`() = test { settingsFlow.value = SettingsData( @@ -357,7 +644,7 @@ class ContactPaymentSettingsRepoTest : BaseUnitTest() { privateCleanup.await() cleanupResult } - whenever(publicPaykitRepo.syncPublishedEndpoints(publish = false, appSyncPriority = Priority.Interactive)) + whenever(publicPaykitRepo.syncPublishedEndpoints(eq(false), eq(Priority.Interactive), any())) .doSuspendableAnswer { publicCleanup.await() cleanupResult @@ -391,7 +678,7 @@ class ContactPaymentSettingsRepoTest : BaseUnitTest() { eq(listOf(CONTACT_KEY)), anyOrNull(), ) - verify(publicPaykitRepo).syncPublishedEndpoints(publish = false, appSyncPriority = Priority.Interactive) + verify(publicPaykitRepo).syncPublishedEndpoints(eq(false), eq(Priority.Interactive), any()) verify(publicPaykitRepo).syncPaykitApp(isNull(), eq(Priority.Background), any()) verify(privatePaykitRepo).enableSharingAndPrepareSavedContacts( argThat { invoke().toSet() == setOf(CONTACT_KEY) }, @@ -432,6 +719,25 @@ class ContactPaymentSettingsRepoTest : BaseUnitTest() { assertFalse(settingsFlow.value.sharesPrivatePaykitEndpoints) } + @Test + fun `reconciliation queued on IO cannot cross removal or wipe`() = test { + for (wipe in listOf(false, true)) { + val sut = createSut(StandardTestDispatcher(testScheduler)) + var reconciled = false + val reconciliation = async(start = CoroutineStart.UNDISPATCHED) { + sut.reconcilePendingEndpoints { reconciled = true } + } + if (wipe) { + sut.withWalletWipe({ it() }) { } + } else { + sut.withProfileRemoval { } + } + runCurrent() + reconciliation.await() + assertFalse(reconciled, "Queued reconciliation crossed teardown (wipe=$wipe)") + } + } + @Test fun `foreground cleanup coalesces and sharing waits for it`() = test { val cleanup = CompletableDeferred() @@ -504,151 +810,12 @@ class ContactPaymentSettingsRepoTest : BaseUnitTest() { assertTrue(settingsFlow.value.sharesPrivatePaykitEndpoints) } - @Test - fun `enableForNewProfile turns private and public payments on`() = test { - createSut().enableForNewProfile() - runCurrent() - - assertTrue(settingsFlow.value.sharesPrivatePaykitEndpoints) - assertTrue(settingsFlow.value.sharesPublicPaykitEndpoints) - assertTrue(settingsFlow.value.hasConfirmedPublicPaykitEndpoints) - verify(privatePaykitRepo).enableSharingAndPrepareSavedContacts(any<() -> Collection>(), any()) - verify(publicPaykitRepo).syncPublishedEndpoints(eq(true), eq(Priority.Background), any()) - } - - @Test - fun `enableForNewProfile still enables public payments when private payments are unavailable`() = test { - whenever { privatePaykitRepo.hasPrivatePaymentAccess() }.thenReturn(false) - - createSut().enableForNewProfile() - runCurrent() - - assertFalse(settingsFlow.value.sharesPrivatePaykitEndpoints) - assertTrue(settingsFlow.value.sharesPublicPaykitEndpoints) - } - - @Test - fun `enableForNewProfile rolls back public payments when publishing fails`() = test { - whenever { publicPaykitRepo.syncPublishedEndpoints(eq(true), eq(Priority.Background), any()) } - .thenReturn(Result.failure(AppError("publish failed"))) - - createSut().enableForNewProfile() - runCurrent() - - assertTrue(settingsFlow.value.sharesPrivatePaykitEndpoints) - assertFalse(settingsFlow.value.sharesPublicPaykitEndpoints) - assertFalse(settingsFlow.value.hasConfirmedPublicPaykitEndpoints) - } - - @Test - fun `enableForNewProfile turns both settings on before either sync completes`() = test { - val appSync = CompletableDeferred() - whenever(publicPaykitRepo.syncPaykitApp(isNull(), eq(Priority.Background), any())).doSuspendableAnswer { - appSync.await() - Result.success(Unit) - } - - createSut().enableForNewProfile() - runCurrent() - - assertTrue(settingsFlow.value.sharesPrivatePaykitEndpoints) - assertTrue(settingsFlow.value.sharesPublicPaykitEndpoints) - assertTrue(settingsFlow.value.hasConfirmedPublicPaykitEndpoints) - verify(publicPaykitRepo, never()).syncPublishedEndpoints(any(), any(), any()) - - appSync.complete(Unit) - runCurrent() - - verify(publicPaykitRepo).syncPublishedEndpoints(eq(true), eq(Priority.Background), any()) - } - - @Test - fun `enableForNewProfile rolls back only private payments when private setup fails`() = test { - whenever { publicPaykitRepo.syncPaykitApp(isNull(), eq(Priority.Background), any()) } - .thenReturn(Result.failure(AppError("registry failed"))) - - createSut().enableForNewProfile() - runCurrent() - - assertFalse(settingsFlow.value.sharesPrivatePaykitEndpoints) - assertTrue(settingsFlow.value.sharesPublicPaykitEndpoints) - verify(publicPaykitRepo).syncPublishedEndpoints(eq(true), eq(Priority.Background), any()) - } - - @Test - fun `enableForNewProfile writes nothing after its sign in ends`() = test { - whenever(pubkyRepo.isCurrent(any())).thenReturn(false) - - createSut().enableForNewProfile() - runCurrent() - - assertFalse(settingsFlow.value.sharesPrivatePaykitEndpoints) - assertFalse(settingsFlow.value.sharesPublicPaykitEndpoints) - verify(publicPaykitRepo, never()).syncPublishedEndpoints(any(), any(), any()) - } - - @Test - fun `enableForNewProfile ignores a call while one is running`() = test { - val publication = CompletableDeferred() - whenever(publicPaykitRepo.syncPaykitApp(isNull(), eq(Priority.Background), any())).doSuspendableAnswer { - publication.await() - Result.success(Unit) - } - val sut = createSut() - - sut.enableForNewProfile() - runCurrent() - sut.enableForNewProfile() - publication.complete(Unit) - runCurrent() - - verify(publicPaykitRepo).syncPaykitApp(isNull(), eq(Priority.Background), any()) - verify(privatePaykitRepo).enableSharingAndPrepareSavedContacts(any<() -> Collection>(), any()) - } - - @Test - fun `enabling payments is refused while Paykit is disabled`() = test { - paykitEnabled.value = false - val sut = createSut() - - assertSame(PublicPaykitError.PaykitDisabled, sut.setEnabled(true).exceptionOrNull()) - assertSame(PublicPaykitError.PaykitDisabled, sut.setPublicEnabled(true).exceptionOrNull()) - - assertFalse(settingsFlow.value.sharesPrivatePaykitEndpoints) - assertFalse(settingsFlow.value.sharesPublicPaykitEndpoints) - verify(publicPaykitRepo, never()).syncPublishedEndpoints(eq(true), any(), any()) - } - - @Test - fun `a Paykit disable queued during private setup keeps public sharing off`() = test { - val publication = CompletableDeferred() - whenever(publicPaykitRepo.syncPaykitApp(isNull(), eq(Priority.Background), any())).doSuspendableAnswer { - publication.await() - Result.success(Unit) - } - val sut = createSut() - val enablePrivate = async { sut.setEnabled(true) } - runCurrent() - - paykitEnabled.value = false - val disable = async { sut.disablePaykit() } - val enablePublic = async { sut.setPublicEnabled(true) } - runCurrent() - publication.complete(Unit) - enablePrivate.await() - disable.await() - - assertSame(PublicPaykitError.PaykitDisabled, enablePublic.await().exceptionOrNull()) - assertFalse(settingsFlow.value.sharesPublicPaykitEndpoints) - verify(publicPaykitRepo, never()).syncPublishedEndpoints(eq(true), any(), any()) - } - - private fun createSut() = ContactPaymentSettingsRepo( + private fun createSut(dispatcher: CoroutineDispatcher = testDispatcher) = ContactPaymentSettingsRepo( settingsStore = settingsStore, publicPaykitRepo = publicPaykitRepo, privatePaykitRepo = privatePaykitRepo, pubkyRepo = pubkyRepo, - ioDispatcher = testDispatcher, + ioDispatcher = dispatcher, ) @Test @@ -842,6 +1009,145 @@ class ContactPaymentSettingsRepoTest : BaseUnitTest() { assertTrue(sut.setPublicEnabled(false).isSuccess) } + @Test + fun `enableForNewProfile turns private and public payments on`() = test { + createSut().enableForNewProfile() + runCurrent() + + assertTrue(settingsFlow.value.sharesPrivatePaykitEndpoints) + assertTrue(settingsFlow.value.sharesPublicPaykitEndpoints) + assertTrue(settingsFlow.value.hasConfirmedPublicPaykitEndpoints) + verify(privatePaykitRepo).enableSharingAndPrepareSavedContacts(any<() -> Collection>(), any()) + verify(publicPaykitRepo).syncPublishedEndpoints(eq(true), eq(Priority.Background), any()) + } + + @Test + fun `enableForNewProfile still enables public payments when private payments are unavailable`() = test { + whenever { privatePaykitRepo.hasPrivatePaymentAccess() }.thenReturn(false) + + createSut().enableForNewProfile() + runCurrent() + + assertFalse(settingsFlow.value.sharesPrivatePaykitEndpoints) + assertTrue(settingsFlow.value.sharesPublicPaykitEndpoints) + } + + @Test + fun `enableForNewProfile rolls back public payments when publishing fails`() = test { + whenever { publicPaykitRepo.syncPublishedEndpoints(eq(true), eq(Priority.Background), any()) } + .thenReturn(Result.failure(AppError("publish failed"))) + + createSut().enableForNewProfile() + runCurrent() + + assertTrue(settingsFlow.value.sharesPrivatePaykitEndpoints) + assertFalse(settingsFlow.value.sharesPublicPaykitEndpoints) + assertFalse(settingsFlow.value.hasConfirmedPublicPaykitEndpoints) + } + + @Test + fun `enableForNewProfile turns both settings on before either sync completes`() = test { + val appSync = CompletableDeferred() + whenever(publicPaykitRepo.syncPaykitApp(isNull(), eq(Priority.Background), any())).doSuspendableAnswer { + appSync.await() + Result.success(Unit) + } + + createSut().enableForNewProfile() + runCurrent() + + assertTrue(settingsFlow.value.sharesPrivatePaykitEndpoints) + assertTrue(settingsFlow.value.sharesPublicPaykitEndpoints) + assertTrue(settingsFlow.value.hasConfirmedPublicPaykitEndpoints) + verify(publicPaykitRepo, never()).syncPublishedEndpoints(any(), any(), any()) + + appSync.complete(Unit) + runCurrent() + + verify(publicPaykitRepo).syncPublishedEndpoints(eq(true), eq(Priority.Background), any()) + } + + @Test + fun `enableForNewProfile rolls back only private payments when private setup fails`() = test { + whenever { publicPaykitRepo.syncPaykitApp(isNull(), eq(Priority.Background), any()) } + .thenReturn(Result.failure(AppError("registry failed"))) + + createSut().enableForNewProfile() + runCurrent() + + assertFalse(settingsFlow.value.sharesPrivatePaykitEndpoints) + assertTrue(settingsFlow.value.sharesPublicPaykitEndpoints) + verify(publicPaykitRepo).syncPublishedEndpoints(eq(true), eq(Priority.Background), any()) + } + + @Test + fun `enableForNewProfile writes nothing after its sign in ends`() = test { + whenever(pubkyRepo.isCurrent(any())).thenReturn(false) + + createSut().enableForNewProfile() + runCurrent() + + assertFalse(settingsFlow.value.sharesPrivatePaykitEndpoints) + assertFalse(settingsFlow.value.sharesPublicPaykitEndpoints) + verify(publicPaykitRepo, never()).syncPublishedEndpoints(any(), any(), any()) + } + + @Test + fun `enableForNewProfile ignores a call while one is running`() = test { + val publication = CompletableDeferred() + whenever(publicPaykitRepo.syncPaykitApp(isNull(), eq(Priority.Background), any())).doSuspendableAnswer { + publication.await() + Result.success(Unit) + } + val sut = createSut() + + sut.enableForNewProfile() + runCurrent() + sut.enableForNewProfile() + publication.complete(Unit) + runCurrent() + + verify(publicPaykitRepo).syncPaykitApp(isNull(), eq(Priority.Background), any()) + verify(privatePaykitRepo).enableSharingAndPrepareSavedContacts(any<() -> Collection>(), any()) + } + + @Test + fun `enabling payments is refused while Paykit is disabled`() = test { + paykitEnabled.value = false + val sut = createSut() + + assertSame(PublicPaykitError.PaykitDisabled, sut.setEnabled(true).exceptionOrNull()) + assertSame(PublicPaykitError.PaykitDisabled, sut.setPublicEnabled(true).exceptionOrNull()) + + assertFalse(settingsFlow.value.sharesPrivatePaykitEndpoints) + assertFalse(settingsFlow.value.sharesPublicPaykitEndpoints) + verify(publicPaykitRepo, never()).syncPublishedEndpoints(eq(true), any(), any()) + } + + @Test + fun `a Paykit disable queued during private setup keeps public sharing off`() = test { + val publication = CompletableDeferred() + whenever(publicPaykitRepo.syncPaykitApp(isNull(), eq(Priority.Background), any())).doSuspendableAnswer { + publication.await() + Result.success(Unit) + } + val sut = createSut() + val enablePrivate = async { sut.setEnabled(true) } + runCurrent() + + paykitEnabled.value = false + val disable = async { sut.disablePaykit() } + val enablePublic = async { sut.setPublicEnabled(true) } + runCurrent() + publication.complete(Unit) + enablePrivate.await() + disable.await() + + assertSame(PublicPaykitError.PaykitDisabled, enablePublic.await().exceptionOrNull()) + assertFalse(settingsFlow.value.sharesPublicPaykitEndpoints) + verify(publicPaykitRepo, never()).syncPublishedEndpoints(eq(true), any(), any()) + } + @Test fun `public enable admission belongs to its original sign in and excludes profile deletion`() = test { val deleting = MutableStateFlow(false) diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index a0aa9ec43e..58d0b31180 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -84,9 +84,13 @@ import org.mockito.kotlin.verifyBlocking import org.mockito.kotlin.whenever import to.bitkit.data.AppCacheData import to.bitkit.data.CacheStore +import to.bitkit.data.ProfileRemovalPending +import to.bitkit.data.ProfileRemovalScope +import to.bitkit.data.ProfileRemovalStore 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 @@ -166,6 +170,7 @@ class LightningRepoTest : BaseUnitTest() { private val connectivityRepo = mock() private val isOnline = MutableStateFlow(ConnectivityState.CONNECTED) 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" @@ -175,6 +180,8 @@ class LightningRepoTest : BaseUnitTest() { private val restoredAt = 1_800_000_000L private val probeNodeId = "02abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdef12" + private val profileRemovalStore = ProfileRemovalStore.inMemoryForTesting() + @Before fun setUp() = runBlocking { whenever(lightningService.setup(any(), anyOrNull(), anyOrNull(), anyOrNull())) @@ -196,9 +203,10 @@ class LightningRepoTest : BaseUnitTest() { preActivityMetadataRepo = preActivityMetadataRepo, onchainSendAttemptStore = onchainSendAttemptStore, connectivityRepo = connectivityRepo, - vssBackupClientLdk = vssBackupClientLdk, + vssBackupClientLdk = vssBackupClientLdk, vssClients = vssClients, urlValidator = urlValidator, electrumProbeService = electrumProbeService, + profileRemovalStore = profileRemovalStore, sparkRepo = sparkRepo, ) } @@ -338,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 { @@ -373,14 +395,47 @@ class LightningRepoTest : BaseUnitTest() { transferRepo = mock(), activityRepo = mock(), hwWalletRepo = hardware, - connectionRecovery = connectionRecoveryFixture(settingsStore), + connectionRecovery = connectionRecoveryFixture(settingsStore, vssClients = vssClients), + profileRemovalStore = to.bitkit.data.ProfileRemovalStore.inMemoryForTesting(), sparkRepo = sparkRepo, sparkExitRepo = mock { on { state } doReturn MutableStateFlow(SparkExitState()) }, backupRepo = mock { on { restoreInProgress } doReturn MutableStateFlow(false) }, + vssClients = vssClients, invoiceParser = { null }, ) } + @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() @@ -503,6 +558,26 @@ class LightningRepoTest : BaseUnitTest() { payeeNodeId = null, ) + @Test + fun `pending wallet wipe rejects native startup`() = test { + sut.setInitNodeLifecycleState() + whenever(lightningService.node).thenReturn(mock()) + val blocktank = mock() + whenever(coreService.blocktank).thenReturn(blocktank) + whenever(blocktank.info(any())).thenReturn(null) + val attempt = java.util.UUID.randomUUID().toString() + profileRemovalStore.withAccess(attempt, ProfileRemovalScope.WALLET_WIPE) { + 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()) + } + @Test fun `start should transition through correct states`() = test { sut.setInitNodeLifecycleState() @@ -564,6 +639,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" @@ -1309,23 +1425,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() @@ -2798,9 +2952,11 @@ class LightningRepoTest : BaseUnitTest() { onchainSendAttemptStore = onchainSendAttemptStore, connectivityRepo = connectivityRepo, vssBackupClientLdk = vssBackupClientLdk, + vssClients = vssClients, urlValidator = urlValidator, electrumProbeService = electrumProbeService, sparkRepo = sparkRepo, + profileRemovalStore = profileRemovalStore, ) @Test @@ -2918,9 +3074,11 @@ class LightningRepoTest : BaseUnitTest() { onchainSendAttemptStore = onchainSendAttemptStore, connectivityRepo = connectivityRepo, vssBackupClientLdk = vssBackupClientLdk, + vssClients = vssClients, urlValidator = urlValidator, electrumProbeService = electrumProbeService, sparkRepo = spark, + profileRemovalStore = profileRemovalStore, ) startNodeForTesting() val first = async { spark.payInvoice("bolt11", 1_000uL) } @@ -4187,9 +4345,10 @@ class LightningRepoTest : BaseUnitTest() { preActivityMetadataRepo = preActivityMetadataRepo, onchainSendAttemptStore = store, connectivityRepo = connectivityRepo, - vssBackupClientLdk = vssBackupClientLdk, + vssBackupClientLdk = vssBackupClientLdk, vssClients = vssClients, urlValidator = urlValidator, electrumProbeService = electrumProbeService, + profileRemovalStore = profileRemovalStore, sparkRepo = sparkRepo, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) @@ -4648,9 +4807,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() @@ -5050,8 +5211,9 @@ 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, + profileRemovalStore = profileRemovalStore, sparkRepo = sparkRepo, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) @@ -5121,8 +5283,9 @@ 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, + profileRemovalStore = profileRemovalStore, sparkRepo = sparkRepo, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) @@ -5203,8 +5366,9 @@ 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, + profileRemovalStore = profileRemovalStore, sparkRepo = sparkRepo, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) @@ -6266,9 +6430,10 @@ class LightningRepoTest : BaseUnitTest() { preActivityMetadataRepo = preActivityMetadataRepo, onchainSendAttemptStore = onchainSendAttemptStore, connectivityRepo = connectivityRepo, - vssBackupClientLdk = vssBackupClientLdk, + vssBackupClientLdk = vssBackupClientLdk, vssClients = vssClients, urlValidator = failingValidator, electrumProbeService = electrumProbeService, + profileRemovalStore = profileRemovalStore, sparkRepo = sparkRepo, ) sutWithFailingValidator.setInitNodeLifecycleState() diff --git a/app/src/test/java/to/bitkit/repositories/PaykitIssuerInteropTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitIssuerInteropTest.kt index 3c3ff2d45a..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,10 +148,9 @@ class PaykitIssuerInteropTest { lastEventAt = NOW.toString(), invalidReason = null, proposalAppId = "bitkit", + proposalRecordedAt = null, payerAppId = null, executionClaimAppId = null, - proposalRecordedAt = null, - acceptanceRecordedAt = null, ) } diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index 9b3d580b10..73e8d9b63f 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -4294,6 +4294,7 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { ), acceptedEventId = null, acceptedOutboundStatus = null, + acceptanceRecordedAt = null, rejectedEventId = null, rejectedOutboundStatus = null, canceledEventId = null, @@ -4306,9 +4307,8 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { lastEventAt = "2027-01-15T08:00:00Z", invalidReason = null, proposalAppId = "bitkit", + proposalRecordedAt = null, payerAppId = null, executionClaimAppId = null, - proposalRecordedAt = null, - acceptanceRecordedAt = null, ) } diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoSubscriptionTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoSubscriptionTest.kt index 29c6e05819..27ad88a611 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoSubscriptionTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoSubscriptionTest.kt @@ -1678,6 +1678,7 @@ class PaykitPaymentRequestRepoSubscriptionTest : BaseUnitTest(StandardTestDispat ), acceptedEventId = null, acceptedOutboundStatus = null, + acceptanceRecordedAt = null, rejectedEventId = null, rejectedOutboundStatus = null, canceledEventId = null, @@ -1690,10 +1691,9 @@ class PaykitPaymentRequestRepoSubscriptionTest : BaseUnitTest(StandardTestDispat lastEventAt = clock.now().toString(), invalidReason = null, proposalAppId = "bitkit", + proposalRecordedAt = null, payerAppId = null, executionClaimAppId = null, - proposalRecordedAt = null, - acceptanceRecordedAt = null, ) private fun linkedPeer( publicKey: String, diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt index 4e7d680f97..a9a0d269bc 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt @@ -3989,6 +3989,7 @@ class PaykitPaymentRequestRepoTest : BaseUnitTest(StandardTestDispatcher()) { ), acceptedEventId = null, acceptedOutboundStatus = null, + acceptanceRecordedAt = null, rejectedEventId = null, rejectedOutboundStatus = null, canceledEventId = null, @@ -4001,10 +4002,9 @@ class PaykitPaymentRequestRepoTest : BaseUnitTest(StandardTestDispatcher()) { lastEventAt = clock.now().toString(), invalidReason = null, proposalAppId = "bitkit", + proposalRecordedAt = null, payerAppId = null, executionClaimAppId = null, - proposalRecordedAt = null, - acceptanceRecordedAt = null, ) private fun linkedPeer( diff --git a/app/src/test/java/to/bitkit/repositories/PaykitUsdtPaymentRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitUsdtPaymentRepoTest.kt index 49f98c7539..af86171e0f 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitUsdtPaymentRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitUsdtPaymentRepoTest.kt @@ -879,7 +879,6 @@ class PaykitUsdtPaymentRepoTest : BaseUnitTest() { payerAppId = "bitkit", executionClaimAppId = "bitkit", proposalRecordedAt = proposalRecordedAt, - acceptanceRecordedAt = null, terms = PaymentRequestTerms( PaymentRequestAmount("0.05", "usd"), reference, @@ -892,6 +891,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/PrivatePaykitAddressReservationRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PrivatePaykitAddressReservationRepoTest.kt index 404aff7df0..2ca737a49b 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitAddressReservationRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitAddressReservationRepoTest.kt @@ -3,6 +3,7 @@ package to.bitkit.repositories import com.synonym.bitkitcore.AddressType import com.synonym.bitkitcore.TransactionDetails import com.synonym.bitkitcore.TxOutput +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async @@ -34,6 +35,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 @@ -826,4 +828,37 @@ class PrivatePaykitAddressReservationRepoTest : BaseUnitTest() { assertNull(sut.contactPublicKeyForReservedAddress(PRIVATE_ADDRESS)) assertEquals(savedContactKey, sut.contactPublicKeyForReservedAddress(savedPrivateAddress)) } + + @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) + } } diff --git a/app/src/test/java/to/bitkit/repositories/PrivatePaykitAllowancePaymentTest.kt b/app/src/test/java/to/bitkit/repositories/PrivatePaykitAllowancePaymentTest.kt index 39fc8adc82..63c09ae72f 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitAllowancePaymentTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitAllowancePaymentTest.kt @@ -21,6 +21,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 @@ -51,6 +52,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() @@ -94,6 +96,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..a999abbaae 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitContactResolverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitContactResolverTest.kt @@ -1,27 +1,54 @@ package to.bitkit.repositories +import androidx.datastore.core.DataStoreFactory +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +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.Rule import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import to.bitkit.data.PrivatePaykitCacheData +import to.bitkit.data.PrivatePaykitCacheSerializer import to.bitkit.data.PrivatePaykitCacheStore import to.bitkit.data.PrivatePaykitContactCacheData +import to.bitkit.data.PrivatePaykitReservationData +import to.bitkit.data.PrivatePaykitReservationSerializer +import to.bitkit.data.PrivatePaykitReservationStore +import to.bitkit.data.PrivatePaykitStoredAssignmentData import to.bitkit.data.PrivatePaykitStoredInvoiceData +import to.bitkit.data.ProfileRemovalStore import to.bitkit.models.PubkyPublicKeyFormat import to.bitkit.test.BaseUnitTest +import to.bitkit.test.connectionRecoveryFixture +import java.util.UUID import javax.inject.Provider import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse import kotlin.test.assertNull +import kotlin.test.assertTrue class PrivatePaykitContactResolverTest : BaseUnitTest() { + @get:Rule + val folder = TemporaryFolder() companion object { private const val CONTACT_KEY = "pubky3rsduhcxpw74snwyct86m38c63j3pq8x4ycqikxg64roik8yw5xg" private const val PAYMENT_HASH = "010203" private const val PRIVATE_ADDRESS = "bcrt1qterdweva9vextackckt6pjy0mmuc54g87g6lsq" } + private val profileRemovalStore = ProfileRemovalStore.inMemoryForTesting() + private val connectionRecovery = connectionRecoveryFixture(mock()) private val cacheStore = mock() private val addressReservationRepo = mock() private val paymentRequestRepo = mock() @@ -38,9 +65,172 @@ class PrivatePaykitContactResolverTest : BaseUnitTest() { cacheStore = cacheStore, addressReservationRepo = Provider { addressReservationRepo }, paymentRequestRepo = Provider { paymentRequestRepo }, + profileRemovalStore = profileRemovalStore, + connectionRecovery = Provider { connectionRecovery }, ) } + @Test + fun `first receipt captures a cold real reservation ledger without a false concurrent change`() = test { + for (ledger in listOf( + PrivatePaykitReservationData(), + PrivatePaykitReservationData( + contactAssignments = mapOf( + CONTACT_KEY to PrivatePaykitStoredAssignmentData("p2wpkh", 3, PRIVATE_ADDRESS) + ) + ), + )) { + val store = mock() + whenever(store.data).thenReturn(MutableStateFlow(ledger)) + val reservations = PrivatePaykitAddressReservationRepo( + testDispatcher, + store, + mock(), + mock(), + mock(), + mock(), + mock() + ) + val resolver = PrivatePaykitContactResolver( + testDispatcher, + cacheStore, + Provider { reservations }, + Provider { paymentRequestRepo }, + profileRemovalStore, + Provider { connectionRecovery }, + ) + resolver.withReceiptOperation { receipt -> + assertEquals( + ledger.contactAssignments.map { it.key to it.value }, + requireNotNull(receipt.snapshot).assignments + ) + receipt.requireCurrent() + } + } + } + + @Test + fun `malformed real reservation storage cannot turn a partial request into a positive receipt`() = test { + val bytes = "{broken reservation evidence".toByteArray() + val file = folder.newFile("reservations").also { it.writeBytes(bytes) } + val storageScope = CoroutineScope(SupervisorJob() + testDispatcher) + val storage = DataStoreFactory.create(PrivatePaykitReservationSerializer, scope = storageScope) { file } + val store = mock() + whenever(store.data).thenReturn(storage.data) + val reservations = PrivatePaykitAddressReservationRepo( + testDispatcher, + store, + mock(), + mock(), + mock(), + mock(), + mock() + ) + val resolver = PrivatePaykitContactResolver( + testDispatcher, + cacheStore, + Provider { reservations }, + Provider { paymentRequestRepo }, + profileRemovalStore, + Provider { connectionRecovery }, + ) + val request = mock() + whenever(request.contactsForPaymentHash(PAYMENT_HASH)).thenReturn(setOf(CONTACT_KEY)) + whenever(paymentRequestRepo.receivedPaymentContacts).thenReturn(request) + resolver.withReceiptOperation { + assertNull(it.snapshot) + assertNull(it.contactForInvoice(PAYMENT_HASH)) + } + assertFailsWith { storage.updateData { it.copy(version = it.version + 1) } } + requireNotNull(storageScope.coroutineContext[Job]).cancelAndJoin() + assertTrue(file.readBytes().contentEquals(bytes)) + val reopened = DataStoreFactory.create(PrivatePaykitReservationSerializer, scope = backgroundScope) { file } + assertFalse(reopened.data.first().receiptSourceReadable) + } + + @Test + fun `malformed real invoice storage remains unavailable to complete receipt capture`() = test { + val bytes = "{broken invoice evidence".toByteArray() + val file = folder.newFile("invoices").also { it.writeBytes(bytes) } + 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() + assertTrue(file.readBytes().contentEquals(bytes)) + val reopened = DataStoreFactory.create(PrivatePaykitCacheSerializer, scope = backgroundScope) { file } + assertFalse(reopened.data.first().receiptSourceReadable) + } + + @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 7d976b07ae..0e472136b1 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt @@ -17,12 +17,15 @@ import com.synonym.paykit.PaykitException import com.synonym.paykit.PaykitSdk 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 import com.synonym.paykit.PrivatePaymentListSyncChange import com.synonym.paykit.PrivatePaymentResolutionState import com.synonym.paykit.PrivatePaymentResolutionStatus +import com.synonym.paykit.PubkyGrantLogout +import com.synonym.paykit.PubkyGrantLogoutReceipt import com.synonym.paykit.PubkyIdentityCapability import com.synonym.paykit.PublicationStatus import kotlinx.coroutines.CancellationException @@ -34,6 +37,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 @@ -64,9 +68,11 @@ 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 +import to.bitkit.ext.runSuspendCatching import to.bitkit.models.NodeLifecycleState import to.bitkit.models.PaykitAmount import to.bitkit.models.PaykitAsset @@ -74,13 +80,18 @@ 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.PaykitProfileLogout 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 import kotlin.test.assertFailsWith import kotlin.test.assertFalse @@ -110,6 +121,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() @@ -194,6 +206,11 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { whenever { paykitSdkService.clearPrivatePaymentLists(any(), anyOrNull()) }.thenAnswer { privateListDeliveryReport(clearedCounterparties = it.getArgument(0)) } + whenever(paykitSdkService.clearPrivatePaymentLists(any(), anyOrNull(), any())).doSuspendableAnswer { + paykitSdkService.clearPrivatePaymentLists(it.getArgument(0), it.getArgument(1)).also { report -> + if (report != null) it.getArgument<(PrivatePaymentListDeliveryReport) -> Unit>(2).invoke(report) + } + } whenever { publicPaykitRepo.beginPayment(any()) } .thenReturn(Result.success(PublicPaykitPaymentResult.Opened("bitcoin:bcrt1qpublic"))) whenever { publicPaykitRepo.payableEndpoints(any()) }.thenAnswer { it.getArgument>(0) } @@ -220,6 +237,180 @@ 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() + val id = UUID.randomUUID().toString() + profileRemovalStore.withAccess(id) { + profileRemovalStore.begin(id) + assertTrue(sut.finishProfileRemoval(pause).isSuccess) + profileRemovalStore.complete(id) + } + 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() + } + @Test fun `obsolete contact sync preserves the admitted retry and its original priority deadline`() = test { whenever(clock.now()).thenAnswer { @@ -1189,7 +1380,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() @@ -1206,7 +1397,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), ) @@ -1585,7 +1776,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) @@ -1799,7 +1990,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { sut.setContactPreparationActive(false) completion.complete(Unit) runCurrent() - sut.beginProfileDeletion() + beginProfileDeletion() clearInvocations(paykitSdkService) sut.setContactPreparationActive(true) @@ -1836,7 +2027,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { sut.scheduleSavedContactPreparation(listOf(OTHER_CONTACT_KEY)).getOrThrow() advanceTimeBy(2_000) runCurrent() - sut.beginProfileDeletion() + beginProfileDeletion() clearInvocations(paykitSdkService) sut.setContactPreparationActive(true) @@ -2032,8 +2223,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() @@ -2678,6 +2869,237 @@ 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 `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))), + deletePubkyProfile = false, + pubkyProfileRevision = null, + ) + 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)) + val binding = PubkyGrantLogoutReceipt(OWN_KEY, "homeserver", "original-grant", "bitkit") + val native = mock { on { binding() }.thenReturn(binding) } + val logout = PaykitProfileLogout(native, mock()) { current === owner } + whenever(pubky.captureProfileLogout(owner)).thenReturn(Result.success(logout)) + whenever(pubky.executeProfileLogout(logout)).thenAnswer { logout.retainAcknowledgement(binding) } + 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.removeBitkitPaymentEndpointsForRemoval(any(), any(), any(), any())).doSuspendableAnswer { + privatePaymentsEnabled = false + if (failPublicWithdrawal && failOnce) { + failOnce = false + Result.failure(IllegalStateException("public withdrawal response lost")) + } else { + it.getArgument<() -> Unit>(2).invoke() + it.getArgument<() -> Unit>(3).invoke() + Result.success(Unit) + } + } + whenever(pubky.deleteProfile(eq(deletion), any())).doSuspendableAnswer { + if (failOnce) { + failOnce = false + Result.failure(IllegalStateException("profile deletion response lost")) + } else { + it.getArgument<() -> Unit>(1).invoke() + Result.success(Unit) + } + } + whenever(pubky.finishProfileRemovalLocally(eq(logout), any())).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)).executeProfileLogout(logout) + } + @Test fun `profile deletion withdraws private lists without an intermediate registry sync`() = test { cacheData.value = PrivatePaykitCacheData(contacts = mapOf(CONTACT_KEY to cachedPublishedContact())) @@ -3117,7 +3539,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()) @@ -3126,7 +3548,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) @@ -3136,7 +3558,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) @@ -3144,7 +3566,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() @@ -3312,14 +3734,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() @@ -3380,7 +3802,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() @@ -3388,7 +3810,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)) @@ -3406,14 +3828,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)) @@ -3447,8 +3869,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()) @@ -3476,7 +3898,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) @@ -3485,7 +3907,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { sut.awaitContactPreparation() verifyNoInteractions(paykitSdkService) - sut.endProfileDeletion() + endProfileDeletion() sut.closeAndClear() } @@ -3777,7 +4199,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { fun `beginSavedContactPayment does not register a saved contact while the profile is being deleted`() = test { whenever(paykitSdkService.contactRecord(CONTACT_KEY)).thenReturn(contactRecord(CONTACT_KEY)) whenever(paykitSdkService.hasPaykitNoiseKeyAuthorization(CONTACT_KEY)).thenReturn(false) - sut.beginProfileDeletion() + val pause = sut.beginProfileDeletion() repeat(2) { val result = sut.beginSavedContactPayment(CONTACT_KEY).getOrThrow() @@ -3785,7 +4207,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { } verifyBlocking(paykitSdkService, times(2)) { contactRecord(CONTACT_KEY) } - sut.endProfileDeletion() + sut.endProfileDeletion(pause) } @Test @@ -4944,6 +5366,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { usdtRepo = usdtRepo, coreService = coreService, clock = clock, + profileRemovalStore = profileRemovalStore, ).also { it.setContactPreparationActive(true) } private fun resolution( @@ -5012,9 +5435,9 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { error = null, ) }, + acknowledged = emptyList(), failedToQueue = failedToQueue, failedToDeliver = failedToDeliver, - acknowledged = emptyList(), ) private fun cachedPublishedContact() = PrivatePaykitContactCacheData( @@ -5030,9 +5453,9 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { cleared = updates .filter { it.reservations.isEmpty() } .map { privateListSyncChange(it.counterparty) }, + acknowledged = emptyList(), failedToQueue = emptyList(), failedToDeliver = emptyList(), - acknowledged = emptyList(), ) private fun privateListSyncChange( 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..2158136cca --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/PubkyIdentityOperationsTest.kt @@ -0,0 +1,266 @@ +package to.bitkit.repositories + +import kotlinx.coroutines.CancellationException +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 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) +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 `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 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() + 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() + 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 2aeda45520..c396bc07a3 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 @@ -15,6 +16,8 @@ import com.synonym.paykit.ProfileResolution import com.synonym.paykit.ProfileSource import com.synonym.paykit.PubkyAuthCompanionClaim import com.synonym.paykit.PubkyAuthDetails +import com.synonym.paykit.PubkyGrantLogout +import com.synonym.paykit.PubkyGrantLogoutReceipt import com.synonym.paykit.PubkyProfileSnapshot import com.synonym.paykit.PubkyProfileUpdate import com.synonym.paykit.PubkySessionBootstrapResult @@ -42,6 +45,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 @@ -51,6 +55,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 @@ -71,6 +77,8 @@ 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 import to.bitkit.data.PubkyStore @@ -93,14 +101,22 @@ import to.bitkit.models.PubkyProfileDataLink import to.bitkit.models.PubkyProfileLink import to.bitkit.models.PubkySessionBackupKind import to.bitkit.models.PubkySessionBackupV1 +import to.bitkit.services.PaykitProfileDeletionSnapshot +import to.bitkit.services.PaykitProfileLogout 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 +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 import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNotNull @@ -142,11 +158,277 @@ 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 `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) + assertFalse(resumed.sessionRestorationFailed.value) + assertTrue(resumed.requiresProfileRecovery()) + } finally { + unavailable = false + } + } + + @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) + 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() + 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() + } + + @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() 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()) @@ -200,10 +482,51 @@ 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) + } + whenever { pubkyService.captureProfileLogout(any(), any()) }.doSuspendableAnswer { + val binding = PubkyGrantLogoutReceipt(it.getArgument(0), "homeserver", "original-grant", "bitkit") + val native = mock { on { binding() }.thenReturn(binding) } + PaykitProfileLogout(native, mock(), isOriginalLifecycle = it.getArgument(1)) + } + whenever { pubkyService.executeProfileLogout(any()) }.doSuspendableAnswer { + val logout = it.getArgument(0) + logout.retainAcknowledgement(logout.binding) + } + whenever { pubkyService.eraseProfileLogoutCredentials(any(), any()) }.doSuspendableAnswer { + pubkyService.forgetLocalProfileAccess() + } + whenever { pubkyService.removeBitkitPaymentEndpointsForRemoval(any(), any(), any(), any()) } + .doSuspendableAnswer { + pubkyService.removeBitkitPaymentEndpoints() + it.getArgument<() -> Unit>(2).invoke() + it.getArgument<() -> Unit>(3).invoke() + } + whenever { pubkyService.deletePubkyProfile(any(), any(), any()) }.doSuspendableAnswer { + it.getArgument<() -> Unit>(2).invoke() + Unit + } + whenever { pubkyService.deletePaykitProfile(any(), any()) }.doSuspendableAnswer { + pubkyService.deletePaykitProfile(it.getArgument(0)) + it.getArgument<() -> Unit>(1).invoke() + } 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, @@ -214,6 +537,47 @@ class PubkyRepoTest : BaseUnitTest() { settingsStore = settingsStore, httpClient = httpClient, clock = clock, + profileRemovalStore = removalStore, + ) + + 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.removePublishedEndpointsForProfileRemoval(any()) }.thenAnswer { + it.getArgument<() -> Unit>(0).invoke() + 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() { @@ -897,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() @@ -1447,6 +1826,42 @@ class PubkyRepoTest : BaseUnitTest() { verifyBlocking(pubkyService, never()) { publishPaykitProfile(any(), any()) } } + @Test + fun `avatar migration from a replaced sign-in cannot write even for the same key`() = test { + val store = stubGatedPubkyStore() + authenticateForTesting(publicKey = VALID_SELF_KEY) + val originalSignIn = assertNotNull(sut.currentSignIn()) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenReturn(null) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenReturn( + paykitRecord(createPaykitProfile("Old", image = "pubky://self/pub/paykit/blobs/avatar.jpg")) + ) + val readStarted = CompletableDeferred() + val finishRead = CompletableDeferred() + whenever(pubkyService.fetchFile(any(), any())).doSuspendableAnswer { + readStarted.complete(Unit) + finishRead.await() + byteArrayOf(1) + } + val load = async { sut.loadProfile() } + readStarted.await() + whenever(keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn("test mnemonic") + whenever(pubkyService.deriveSecretKey("test mnemonic")).thenReturn("restored_secret") + whenever(pubkyService.publicKeyFromSecret("restored_secret")).thenReturn(VALID_SELF_KEY) + sut.restoreSessionBackupState(PubkySessionBackupV1(kind = PubkySessionBackupKind.LocalSeed)).getOrThrow() + assertFalse(sut.isCurrent(originalSignIn)) + clearInvocations(pubkyService) + + finishRead.complete(Unit) + load.await() + + assertEquals(VALID_SELF_KEY, sut.publicKey.value) + assertNull(sut.profile.value) + verify(pubkyService, never()).uploadPubkyAppAvatar(any(), any(), any()) + verify(pubkyService, never()).publishPubkyProfile(any(), anyOrNull(), any()) + verify(pubkyService, never()).publishPaykitProfile(any(), any()) + assertEquals(PubkyStoreData(), store.data) + } + @Test fun `loadProfile keeps an avatar set on pubky app over a pending avatar move`() = test { whenever(pubkyStore.data).thenReturn( @@ -1653,7 +2068,85 @@ class PubkyRepoTest : BaseUnitTest() { sut.deleteProfile() - verifyBlocking(pubkyService) { deletePubkyProfile("revision-Test", VALID_SELF_KEY) } + verifyBlocking(pubkyService) { deletePubkyProfile(eq("revision-Test"), eq(VALID_SELF_KEY), any()) } + } + + @Test + fun `profile confirmation refuses a later pubky revision before any deletion`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + val coordinator = sut.removalCoordinatorForTest() + val confirmation = coordinator.prepareDeletion(sut.profileOwner()).getOrThrow() + assertEquals("revision-Test", confirmation.deletion?.pubkyProfileRevision) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenReturn(createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Later"))) + assertTrue(coordinator.remove(confirmation).isFailure) + verify(pubkyService, never()).deletePubkyProfile(any(), any(), any()) + verify(pubkyService, never()).deletePaykitProfile(any(), any()) + } + + @Test + fun `acknowledged pubky deletion is not replayed after an uncertain Paykit deletion`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + var remote: PubkyProfileSnapshot? = createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Test")) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenAnswer { remote } + whenever(pubkyService.deletePubkyProfile(any(), any(), any())).doSuspendableAnswer { + remote = null + it.getArgument<() -> Unit>(2).invoke() + Unit + } + val uncertain = IllegalStateException("Paykit response lost") + whenever(pubkyService.deletePaykitProfile(any())).thenThrow(uncertain) + val coordinator = sut.removalCoordinatorForTest() + val original = coordinator.prepareDeletion(sut.profileOwner()).getOrThrow() + val failure = coordinator.remove(original).exceptionOrNull() as ProfileRemovalFailure + assertTrue(original.deletion!!.pubkyProfileAcknowledged.get()) + // Even an identical recreated public revision is outside acknowledged deletion intent. + remote = createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Test")) + assertTrue(coordinator.reviewAgain(failure).isFailure) + remote = null + val reviewed = coordinator.reviewAgain(failure).getOrThrow() + assertNull(reviewed.deletion!!.pubkyProfileRevision) + assertTrue(reviewed.deletion.pubkyProfileAcknowledged.get()) + whenever(pubkyService.deletePaykitProfile(any())).thenReturn(Unit) + assertTrue(coordinator.remove(reviewed).isSuccess) + val deleted = argumentCaptor() + verify(pubkyService, times(2)).deletePaykitProfile(deleted.capture()) + assertEquals(listOf("revision", "revision"), deleted.allValues.map { it.profileRevision }) + verify(pubkyService, times(1)).deletePubkyProfile(eq("revision-Test"), eq(VALID_SELF_KEY), any()) + } + + @Test + fun `an adopted Ring profile is excluded from both confirmation reads and deletion`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + stubAdoptedRingSource() + clearInvocations(pubkyService) + val deletion = sut.prepareProfileDeletion(sut.profileOwner()).getOrThrow() + assertFalse(deletion.deletePubkyProfile) + assertNull(deletion.pubkyProfileRevision) + assertTrue(sut.deleteProfile().isSuccess) + verify(pubkyService, never()).fetchPubkyProfileWithRevision(any()) + verify(pubkyService, never()).deletePubkyProfile(any(), any(), any()) + verify(pubkyService).deletePaykitProfile(any(), any()) + } + + @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(eq("revision-Test"), eq(VALID_SELF_KEY), any())) + .thenAnswer { throw identityError } + .thenReturn(Unit) + + val result = sut.deleteProfile() + + assertSame(identityError, result.exceptionOrNull()) + verify(pubkyService).deletePubkyProfile(eq("revision-Test"), eq(VALID_SELF_KEY), any()) + verify(pubkyService, never()).signIn(any()) + verify(pubkyService, never()).deletePaykitProfile() + verify(pubkyService, never()).signOut() } @Test @@ -1674,8 +2167,9 @@ class PubkyRepoTest : BaseUnitTest() { snapshot } val copyDeleted = CompletableDeferred() - whenever(pubkyService.deletePaykitProfile()).doSuspendableAnswer { + whenever(pubkyService.deletePaykitProfile(any(), any())).doSuspendableAnswer { copyDeleted.complete(Unit) + it.getArgument<() -> Unit>(1).invoke() Unit } clearInvocations(pubkyService) @@ -1988,9 +2482,13 @@ class PubkyRepoTest : BaseUnitTest() { authenticateForTesting(publicKey = VALID_SELF_KEY, profileName = "Old") val loadStarted = CompletableDeferred() val finishLoad = CompletableDeferred() + var firstRead = true whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { - loadStarted.complete(Unit) - finishLoad.await() + if (firstRead) { + firstRead = false + loadStarted.complete(Unit) + finishLoad.await() + } createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Loaded")) } val load = async { sut.loadProfile() } @@ -2125,18 +2623,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) - val result = sut.hasSecretKey() + assertFalse(sut.hasSecretKey()) - assertFalse(result) + assertEquals(backupVersion, sut.backupStateVersion.value) + verify(keychain, never()).delete(any()) + } + + @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 @@ -2188,7 +2816,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, @@ -2201,34 +2829,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 @@ -2290,6 +2918,33 @@ class PubkyRepoTest : BaseUnitTest() { } } + @Test + fun `profile confirmation preserves typed subscription refusal through service errors`() = test { + authenticateForTesting() + whenever(pubkyService.captureProfileDeletion(any(), any())) + .thenAnswer { throw AppError(PubkyContactError.ActiveSubscription) } + assertSame( + PubkyContactError.ActiveSubscription, + sut.prepareProfileDeletion(sut.profileOwner()).exceptionOrNull() + ) + verify(pubkyService, never()).removeContactsForProfile(any()) + } + + @Test + fun `profile validation preserves subscription refusal before pending cleanup`() = test { + authenticateForTesting() + val owner = sut.profileOwner() + val deletion = sut.prepareProfileDeletion(owner).getOrThrow() + whenever(pubkyService.validateProfileDeletion(deletion.snapshot)) + .thenAnswer { throw AppError(PubkyContactError.ActiveSubscription) } + val result = sut.performProfileRemoval(owner, UUID.randomUUID().toString()) { + sut.validateProfileDeletion(deletion) + } + assertSame(PubkyContactError.ActiveSubscription, result.exceptionOrNull()) + verify(pubkyService, never()).removeContactsForProfile(any()) + assertNull(profileRemovalStore.pendingAttempt()) + } + @Test fun `deleteProfile stops public profile reads before deleting contacts`() = test { authenticateForTesting() @@ -2299,7 +2954,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)) @@ -2321,80 +2976,236 @@ class PubkyRepoTest : BaseUnitTest() { } } sut.loadContacts() - val screenLookup = async { sut.resolvePendingContactProfile(VALID_CONTACT_KEY_A) } - val deletionStarted = CompletableDeferred() - val finishDeletion = CompletableDeferred() - whenever(pubkyService.contactRecords()).doSuspendableAnswer { - deletionStarted.complete(Unit) - finishDeletion.await() - records - } - val deletion = async { sut.deleteProfile() } - deletionStarted.await() - bulkCancelled.await() - screenCancelled.await() - assertFalse(deletion.isCompleted) - finishDeletion.complete(Unit) - deletion.await().getOrThrow() - screenLookup.await() - assertTrue(sut.contacts.value.isEmpty()) - verify(pubkyService).removeContacts(records.map { it.publicKey }) - verify(pubkyService, never()).removeContact(any()) + val screenLookup = async { sut.resolvePendingContactProfile(VALID_CONTACT_KEY_A) } + val deletionStarted = CompletableDeferred() + val finishDeletion = CompletableDeferred() + whenever(pubkyService.removeContactsForProfile(records.map { it.publicKey })).doSuspendableAnswer { + deletionStarted.complete(Unit) + finishDeletion.await() + records + } + val deletion = async { sut.deleteProfile() } + deletionStarted.await() + bulkCancelled.await() + screenCancelled.await() + assertFalse(deletion.isCompleted) + finishDeletion.complete(Unit) + deletion.await().getOrThrow() + screenLookup.await() + assertTrue(sut.contacts.value.isEmpty()) + 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 expected = PubkyContactError.ActiveProfileSubscriptions(1_800_000_000_000L) + val wrapped = IllegalStateException("Service operation failed", expected) + whenever(pubkyService.captureProfileDeletion(any(), any())).thenAnswer { throw wrapped } + clearInvocations(pubkyStore, pubkyService) + + assertSame(expected, sut.prepareProfileDeletion(sut.profileOwner()).exceptionOrNull()) + assertSame(expected, 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 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(expected, 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 `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(any(), any())) + .thenAnswer { throw IllegalStateException("Service operation failed", expected) } + clearInvocations(pubkyStore, settingsStore, keychain) + + assertSame(expected, sut.deleteProfile().exceptionOrNull()) + + verify(pubkyService, never()).removeContactsForProfile(any()) + verify(pubkyService, never()).signOut() + verify(pubkyService, never()).executeProfileLogout(any()) + verify(keychain, never()).delete(any()) + verify(pubkyStore, never()).update(any()) + verify(settingsStore, never()).update(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.removeContactsForProfile(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(any()) + 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()).removeContactsForProfile(any()) + verify(pubkyService, never()).deletePaykitProfile(any()) + 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.removeContactsForProfile(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(any()) + 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(any())).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 { + fun `deleteProfile retains local evidence when revocation is uncertain`() = test { authenticateForTesting() settingsFlow.value = SettingsData( sharesPublicPaykitEndpoints = true, sharesPrivatePaykitEndpoints = true, ) whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn("test_secret") - whenever(pubkyService.signOut()).thenAnswer { throw TestAppError("Sign out failed") } + whenever(pubkyService.executeProfileLogout(any())).thenAnswer { throw TestAppError("Sign out failed") } 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 - 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(any())).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(any()) + 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(any())).doSuspendableAnswer { + deletionStarted.complete(Unit) + withContext(NonCancellable) { finishDeletion.await() } + throw uncertainResponse + } + val deletion = async { sut.deleteProfile() } + deletionStarted.await() + assertTrue(sut.signOut().isFailure) + finishDeletion.complete(Unit) - assertTrue(result.isFailure) - verifyBlocking(pubkyService) { deletePaykitProfile() } - verifyBlocking(pubkyService, never()) { signIn(any()) } + assertSame(uncertainResponse, deletion.await().exceptionOrNull()) + sut.signOut().getOrThrow() + assertNull(sut.publicKey.value) + assertFalse(sut.isAuthenticated.value) + verify(pubkyService, never()).signIn(any()) + 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 } @@ -2410,15 +3221,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() @@ -2431,13 +3242,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) } @@ -2448,25 +3259,25 @@ class PubkyRepoTest : BaseUnitTest() { sharesPublicPaykitEndpoints = true, sharesPrivatePaykitEndpoints = true, ) - whenever(pubkyService.signOut()).thenAnswer { throw TestAppError("Server error") } + whenever(pubkyService.executeProfileLogout(any())).thenAnswer { throw TestAppError("Server error") } 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() - whenever(pubkyService.signOut()).doSuspendableAnswer { + whenever(pubkyService.executeProfileLogout(any())).doSuspendableAnswer { revocationStarted.complete(Unit) finishRevocation.await() } @@ -2477,9 +3288,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 @@ -3435,6 +4247,268 @@ 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 `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.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { + refreshed.complete(Unit) + createSnapshot(VALID_SELF_KEY, 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).fetchPubkyProfileWithRevision(VALID_SELF_KEY) + } + + @Test + fun `wipe drains a scheduled profile refresh without restoring its identity`() = test { + val store = stubGatedPubkyStore() + authenticateForTesting(publicKey = VALID_SELF_KEY) + val credentials = mutableMapOf( + Keychain.Key.PAYKIT_SESSION.name to "saved_session", + Keychain.Key.PUBKY_SECRET_KEY.name to "local_secret", + ) + whenever(keychain.loadString(any())).thenAnswer { credentials[it.getArgument(0)] } + whenever(keychain.delete(any())).thenAnswer { + credentials.remove(it.getArgument(0)) + Unit + } + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenReturn(null) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenReturn(paykitRecord(createPaykitProfile("Old"))) + val retryPublished = CompletableDeferred() + whenever(pubkyService.publishPubkyProfile(any(), anyOrNull(), any())) + .thenAnswer { throw PaykitException.Identity("identity_error", "Missing capabilities") } + .thenAnswer { + retryPublished.complete(Unit) + createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Old")) + } + var refreshed = false + whenever(pubkyService.signIn("local_secret")).thenAnswer { + refreshed = true + Unit + } + val refreshStarted = CompletableDeferred() + val finishRefresh = CompletableDeferred() + whenever(pubkyService.publicKeyFromSecret("local_secret")).doSuspendableAnswer { + if (refreshed) { + refreshStarted.complete(Unit) + finishRefresh.await() + } + VALID_SELF_KEY + } + + sut.scheduleInitializationAfterRestore() + refreshStarted.await() + val wipe = async { sut.wipeLocalState() } + runCurrent() + finishRefresh.complete(Unit) + retryPublished.await() + wipe.await() + advanceUntilIdle() + + assertNull(sut.publicKey.value) + assertFalse(sut.hasIdentity()) + assertTrue(credentials.isEmpty()) + assertEquals(PubkyStoreData(), store.data) + } + + @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.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).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()).fetchPubkyProfileWithRevision(VALID_SELF_KEY) + verify(pubkyService, never()).importSession(any()) + profileSetupPending.value = false + doSuspendableAnswer { + createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Completed")) + }.whenever(pubkyService).fetchPubkyProfileWithRevision(VALID_SELF_KEY) + assertFalse(sut.restoreSessionIfNeeded()) + yield() + advanceUntilIdle() + assertEquals("Completed", sut.profile.value?.name) + verify(pubkyService).fetchPubkyProfileWithRevision(VALID_SELF_KEY) + } + + @Test + fun `active identity retries its missing profile on reconnect without delaying wallet maintenance`() = 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.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenAnswer { + throw PaykitException.Transport("transport_error", "offline") + } + assertTrue(sut.restoreSessionIfNeeded()) + val originalSignIn = assertNotNull(sut.currentSignIn()) + assertNull(sut.profile.value) + + val response = CompletableDeferred() + doSuspendableAnswer { + response.await() + createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Restored")) + }.whenever(pubkyService).fetchPubkyProfileWithRevision(VALID_SELF_KEY) + clearInvocations(pubkyService) + try { + repeat(3) { assertFalse(sut.restoreSessionIfNeeded()) } + yield() + runCurrent() + assertTrue(sut.isCurrent(originalSignIn)) + verify(pubkyService).fetchPubkyProfileWithRevision(VALID_SELF_KEY) + assertTrue(sut.isLoadingProfile.value) + verify(pubkyService, never()).importSession(any()) + } finally { + response.complete(Unit) + } + yield() + advanceUntilIdle() + assertEquals("Restored", sut.profile.value?.name) + assertFalse(sut.restoreSessionIfNeeded()) + advanceUntilIdle() + verify(pubkyService).fetchPubkyProfileWithRevision(VALID_SELF_KEY) + } + + @Test + fun `reconnect profile result cannot restore an ended identity`() = 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.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenAnswer { + throw PaykitException.Transport("transport_error", "offline") + } + assertTrue(sut.restoreSessionIfNeeded()) + val response = CompletableDeferred() + doSuspendableAnswer { + response.await() + createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Old")) + }.whenever(pubkyService).fetchPubkyProfileWithRevision(VALID_SELF_KEY) + + try { + assertFalse(sut.restoreSessionIfNeeded()) + yield() + runCurrent() + verify(pubkyService, times(3)).fetchPubkyProfileWithRevision(VALID_SELF_KEY) + assertTrue(sut.isLoadingProfile.value) + sut.restoreSessionBackupState(null).getOrThrow() + assertNull(sut.currentSignIn()) + } finally { + response.complete(Unit) + } + yield() + advanceUntilIdle() + assertNull(sut.profile.value) + } + + @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.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { + releaseFirst.await() + createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Obsolete")) + } + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_CONTACT_KEY_B)).doSuspendableAnswer { + releaseSecond.await() + createSnapshot(VALID_CONTACT_KEY_B, 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() @@ -4426,6 +5500,7 @@ class PubkyRepoTest : BaseUnitTest() { @Test fun `wipe completes while restoration profile loading remains in flight`() = test { + val store = stubGatedPubkyStore() sut.awaitInitialization() val credentials = mutableMapOf(Keychain.Key.PAYKIT_SESSION.name to "saved_session") whenever(keychain.loadString(any())).thenAnswer { credentials[it.getArgument(0)] } @@ -4459,31 +5534,32 @@ class PubkyRepoTest : BaseUnitTest() { assertNull(sut.profile.value) assertTrue(sut.contacts.value.isEmpty()) verify(pubkyStore).reset() + assertEquals(PubkyStoreData(), store.data) } @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) + fun `wipe drains a missing profile setup update before clearing it`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenReturn(null) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenReturn(null) + val updateStarted = CompletableDeferred() + val finishUpdate = CompletableDeferred() + whenever(settingsStore.setPubkyProfileSetupPending(true)).doSuspendableAnswer { + updateStarted.complete(Unit) + finishUpdate.await() + profileSetupPending.value = true + } + val load = async { sut.loadProfile() } + updateStarted.await() + val wipe = async { sut.wipeLocalState() } + runCurrent() - val result = sut.refreshSessionIfPossible() + finishUpdate.complete(Unit) + load.await() + wipe.await() - assertEquals(false, result.getOrNull()) assertNull(sut.publicKey.value) - assertFalse(sut.isAuthenticated.value) + assertFalse(profileSetupPending.value) } @Test @@ -5389,7 +6465,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") @@ -5397,7 +6473,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) @@ -5413,17 +6489,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")) @@ -5674,8 +6753,10 @@ 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.deletePaykitProfile()).thenAnswer { throw TestAppError("Offline") } + whenever(pubkyService.removeContactsForProfile(records.map { it.publicKey })).thenReturn(records) + 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/repositories/PublicPaykitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PublicPaykitRepoTest.kt index ec8360e48a..49b73a70f5 100644 --- a/app/src/test/java/to/bitkit/repositories/PublicPaykitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PublicPaykitRepoTest.kt @@ -13,6 +13,8 @@ import com.synonym.paykit.PubkyIdentityCapability import com.synonym.paykit.PublicationStatus import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.cancel @@ -20,6 +22,7 @@ import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.withContext import org.junit.After import org.junit.Before @@ -228,6 +231,71 @@ class PublicPaykitRepoTest : BaseUnitTest() { ) } + @Test + fun `busy publication admission retains paid invalidation for foreground retry`() = test { + settingsFlow.value = SettingsData( + sharesPublicPaykitEndpoints = true, + publicPaykitOnchainEnabled = false, + publicPaykitUsdtEnabled = false, + publicPaykitBolt11 = "lnbc1paid", + publicPaykitBolt11PaymentHash = "010203", + publicPaykitBolt11ExpiresAtMillis = freshExpiryMillis(), + ) + stubPublicInvoice("lnbc1replacement", byteArrayOf(4, 5, 6)) + var admissionAttempted = false + sut.refreshPublishedBolt11ForPayment("010203", admitPublication = { + admissionAttempted = true + assertEquals("", settingsFlow.value.publicPaykitBolt11) + assertTrue(settingsFlow.value.publicPaykitCleanupPending) + }).getOrThrow() + + assertTrue(admissionAttempted) + verifyNoInteractions(paykitSdkService, addressReservationRepo) + verifyBlocking(lightningRepo, never()) { createInvoice(null, "", PUBLIC_BOLT11_EXPIRY_SECONDS) } + sut.syncCurrentPublishedEndpoints().getOrThrow() + assertEquals("lnbc1replacement", settingsFlow.value.publicPaykitBolt11) + assertFalse(settingsFlow.value.publicPaykitCleanupPending) + } + + @Test + fun `paid invalidation queued on IO cannot capture a replacement sign in`() = test { + var signIn = PubkySignIn("same-public-key", 0L) + whenever(pubkyRepo.currentSignIn()).thenAnswer { signIn } + whenever(pubkyRepo.isCurrent(any())).thenAnswer { it.getArgument(0) == signIn } + val replacement = SettingsData( + sharesPublicPaykitEndpoints = true, + publicPaykitBolt11 = "lnbc1replacement", + publicPaykitBolt11PaymentHash = "same-hash", + ) + settingsFlow.value = replacement + val repo = createRepo(ioDispatcher = StandardTestDispatcher(testScheduler)) + val pending = async(start = CoroutineStart.UNDISPATCHED) { + repo.refreshPublishedBolt11ForPayment("same-hash", admitPublication = { it() }) + } + signIn = PubkySignIn("same-public-key", 1L) + pending.await().getOrThrow() + + assertEquals(replacement, settingsFlow.value) + verifyNoInteractions(paykitSdkService, addressReservationRepo) + } + + @Test + fun `paid invalidation checks the current hash at the persisted settings update`() = test { + settingsFlow.value = SettingsData( + sharesPublicPaykitEndpoints = true, + publicPaykitBolt11 = "lnbc1paid", + publicPaykitBolt11PaymentHash = "paid", + ) + val newer = settingsFlow.value.copy(publicPaykitBolt11 = "lnbc1newer", publicPaykitBolt11PaymentHash = "newer") + whenever { settingsStore.update(any()) }.thenAnswer { + settingsFlow.value = it.getArgument<(SettingsData) -> SettingsData>(0)(newer) + } + sut.refreshPublishedBolt11ForPayment("paid", canPublish = { false }, admitPublication = { it() }).getOrThrow() + + assertEquals(newer, settingsFlow.value) + verifyNoInteractions(paykitSdkService, addressReservationRepo) + } + @Test fun `deferred paid invoice replacement clears the cache before publication resumes`() = test { settingsFlow.value = SettingsData( @@ -240,9 +308,13 @@ class PublicPaykitRepoTest : BaseUnitTest() { ) stubPublicInvoice("lnbc1replacement", byteArrayOf(4, 5, 6)) - sut.refreshPublishedBolt11ForPayment("unrelated", canPublish = { false }).getOrThrow() + sut.refreshPublishedBolt11ForPayment( + "unrelated", + canPublish = { false }, + admitPublication = { it() } + ).getOrThrow() assertEquals("lnbc1paid", settingsFlow.value.publicPaykitBolt11) - sut.refreshPublishedBolt11ForPayment("010203", canPublish = { false }).getOrThrow() + sut.refreshPublishedBolt11ForPayment("010203", canPublish = { false }, admitPublication = { it() }).getOrThrow() assertEquals("", settingsFlow.value.publicPaykitBolt11) assertEquals("", settingsFlow.value.publicPaykitBolt11PaymentHash) verifyNoInteractions(paykitSdkService) @@ -269,7 +341,11 @@ class PublicPaykitRepoTest : BaseUnitTest() { settingsFlow.value = it.getArgument<(SettingsData) -> SettingsData>(0)(settingsFlow.value) } - sut.refreshPublishedBolt11ForPayment("010203", isStillCurrent = { isReceiveSessionCurrent }).getOrThrow() + sut.refreshPublishedBolt11ForPayment( + "010203", + isStillCurrent = { isReceiveSessionCurrent }, + admitPublication = { it() }, + ).getOrThrow() assertEquals(invoiceSettings, settingsFlow.value) verifyNoInteractions(paykitSdkService) @@ -295,7 +371,11 @@ class PublicPaykitRepoTest : BaseUnitTest() { } var deleting = false val replacement = async { - sut.refreshPublishedBolt11ForPayment("010203", canPublish = { !deleting }).getOrThrow() + sut.refreshPublishedBolt11ForPayment( + "010203", + canPublish = { !deleting }, + admitPublication = { it() } + ).getOrThrow() } invoiceStarted.await() assertEquals("", settingsFlow.value.publicPaykitBolt11PaymentHash) @@ -364,7 +444,7 @@ class PublicPaykitRepoTest : BaseUnitTest() { if (offline) throw AppError("offline") syncReport() } - assertTrue(sut.refreshPublishedBolt11ForPayment("paid").isFailure) + assertTrue(sut.refreshPublishedBolt11ForPayment("paid", admitPublication = { it() }).isFailure) assertEquals("", settingsFlow.value.publicPaykitBolt11PaymentHash) assertTrue(settingsFlow.value.publicPaykitCleanupPending) @@ -420,7 +500,7 @@ class PublicPaykitRepoTest : BaseUnitTest() { } val publication = async { sut.syncCurrentPublishedEndpoints() } writeStarted.await() - sut.refreshPublishedBolt11ForPayment("010203", canPublish = { false }).getOrThrow() + sut.refreshPublishedBolt11ForPayment("010203", canPublish = { false }, admitPublication = { it() }).getOrThrow() resumeWrite.complete(Unit) publication.await().getOrThrow() @@ -448,7 +528,7 @@ class PublicPaykitRepoTest : BaseUnitTest() { } val older = async { sut.syncCurrentPublishedEndpoints() } appSyncStarted.await() - sut.refreshPublishedBolt11ForPayment("010203").getOrThrow() + sut.refreshPublishedBolt11ForPayment("010203", admitPublication = { it() }).getOrThrow() assertEquals("lnbc1replacement", settingsFlow.value.publicPaykitBolt11) assertFalse(settingsFlow.value.publicPaykitCleanupPending) resumeAppSync.complete(Unit) @@ -676,7 +756,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) @@ -1005,8 +1085,9 @@ class PublicPaykitRepoTest : BaseUnitTest() { paykitSdkService: PaykitSdkService = this.paykitSdkService, settingsStore: SettingsStore = this.settingsStore, clock: Clock = this.clock, + ioDispatcher: CoroutineDispatcher = testDispatcher, ) = PublicPaykitRepo( - ioDispatcher = testDispatcher, + ioDispatcher = ioDispatcher, pubkyRepo = pubkyRepo, addressReservationRepo = addressReservationRepo, lightningRepo = lightningRepo, diff --git a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt index aec095b3db..a8ad6557f4 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 @@ -39,6 +40,7 @@ import org.mockito.kotlin.clearInvocations import org.mockito.kotlin.doReturn import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq +import org.mockito.kotlin.isNull import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times @@ -49,9 +51,15 @@ import to.bitkit.data.CacheStore import to.bitkit.data.PrivatePaykitReservationData import to.bitkit.data.PrivatePaykitReservationStore import to.bitkit.data.PrivatePaykitStoredAssignmentData +import to.bitkit.data.ProfileRemovalScope +import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore +import to.bitkit.data.WalletResetRecovery +import to.bitkit.data.backup.VssClientCoordinator import to.bitkit.data.keychain.Keychain +import to.bitkit.di.json +import to.bitkit.ext.totalNextOutboundHtlcLimitSats import to.bitkit.models.BalanceState import to.bitkit.models.NodeLifecycleState import to.bitkit.services.AddressDerivationInfo @@ -71,9 +79,11 @@ import to.bitkit.utils.AppError import to.bitkit.utils.ServiceError import java.io.IOException import java.util.ArrayDeque +import java.util.UUID 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 @@ -96,9 +106,11 @@ class WalletRepoTest : BaseUnitTest() { private val activityRepo = mock() private val hwWalletRepo = mock() private val backupRepo = mock() + private val vssClients = VssClientCoordinator() + private val connectionRecovery = connectionRecoveryFixture(settingsStore, vssClients = vssClients) + private val profileRemovalStore = ProfileRemovalStore.inMemoryForTesting() private val sparkExitState = MutableStateFlow(SparkExitState()) private val sparkExitRepo = mock { on { state } doReturn sparkExitState } - private val connectionRecovery = connectionRecoveryFixture(settingsStore) companion object Fixtures { const val ACTIVITY_TAG = "testTag" @@ -184,6 +196,7 @@ class WalletRepoTest : BaseUnitTest() { dispatcher: CoroutineDispatcher = testDispatcher, reservationRepo: PrivatePaykitAddressReservationRepo = privatePaykitAddressReservationRepo, spark: SparkRepo = sparkRepo, + balances: DeriveBalanceStateUseCase = deriveBalanceStateUseCase, ) = WalletRepo( bgDispatcher = dispatcher, keychain = keychain, @@ -192,19 +205,33 @@ class WalletRepoTest : BaseUnitTest() { lightningRepo = lightningRepo, cacheStore = cacheStore, preActivityMetadataRepo = preActivityMetadataRepo, - deriveBalanceStateUseCase = deriveBalanceStateUseCase, + deriveBalanceStateUseCase = balances, wipeWalletUseCase = wipeWalletUseCase, privatePaykitAddressReservationRepo = reservationRepo, transferRepo = transferRepo, activityRepo = activityRepo, hwWalletRepo = hwWalletRepo, connectionRecovery = connectionRecovery, + profileRemovalStore = profileRemovalStore, sparkRepo = spark, sparkExitRepo = sparkExitRepo, backupRepo = backupRepo, + vssClients = vssClients, invoiceParser = { bolt11 -> "parsedHashOf$bolt11" }, ) + @Test + fun `incomplete wallet wipe rejects replacement seed before any write`() = test { + val attempt = UUID.randomUUID().toString() + profileRemovalStore.withAccess(attempt, ProfileRemovalScope.WALLET_WIPE) { + profileRemovalStore.begin(attempt) + } + val result = sut.restoreWallet("replacement-test-mnemonic", null) + assertTrue(result.isFailure) + verify(keychain, never()).saveString(eq(Keychain.Key.BIP39_MNEMONIC.name), any()) + assertEquals(attempt, profileRemovalStore.pendingAttempt()) + } + private fun lightningInvoice(bolt11: String, isExpired: Boolean = false) = LightningInvoice( bolt11 = bolt11, paymentHash = byteArrayOf(1, 2, 3), @@ -282,6 +309,465 @@ 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, + sparkExitRepo = sparkExitRepo, + ) + 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 `Spark balance changes after a finished exit update spending while the node start times out`() = test { + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) + sparkExitState.value = SparkExitState(record = SparkExitFixtures.record(SparkExitRecord.Phase.Done)) + 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, + sparkExitRepo = sparkExitRepo, + ) + sut = createSut(spark = spark, balances = balances) + testScheduler.runCurrent() + assertEquals(119_865uL, sut.balanceState.value.totalLightningSats) + + nodeState.value = LightningState(nodeLifecycleState = NodeLifecycleState.Starting) + whenever(lightningRepo.getBalancesAsync()).thenReturn( + Result.failure(NodeRunTimeoutError("getBalancesAsync")), + ) + sparkState.update { it.copy(balanceSats = 50_000uL, pendingDepositSats = 100uL) } + testScheduler.runCurrent() + + assertEquals(70_000uL, sut.balanceState.value.totalLightningSats) + assertEquals(50_000uL, sut.balanceState.value.totalOnchainSats) + assertEquals(100uL, sut.balanceState.value.balanceInTransferToSpending) + assertEquals(SparkFees.sendableSats(50_000uL), sut.balanceState.value.maxSendLightningSats) + verify(cacheStore).cacheBalance(sut.balanceState.value) + + val recovered = mock { + on { isChannelReady } doReturn true + on { isUsable } doReturn true + on { nextOutboundHtlcLimitMsat } doReturn 55_000_000uL + } + whenever(lightningRepo.getBalancesAsync()).doSuspendableAnswer { + nodeState.value = LightningState( + nodeLifecycleState = NodeLifecycleState.Running, + channels = listOf(recovered).toImmutableList(), + ) + sut.refreshMaxSendLightning() + Result.failure(NodeRunTimeoutError("getBalancesAsync")) + } + sparkState.update { it.copy(balanceSats = 40_000uL) } + testScheduler.runCurrent() + + assertEquals(60_000uL, sut.balanceState.value.totalLightningSats) + assertEquals( + maxOf(listOf(recovered).totalNextOutboundHtlcLimitSats(), sparkState.value.sendableSats), + 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 `exit fallback retains whole balances through cancellation and cache restoration`() = test { + val known = BalanceState( + totalLightningSats = 150_000uL, + sparkBalanceSats = 100_000uL, + sparkPendingDepositSats = 0uL, + ) + var cached = AppCacheData(balance = known) + 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(NodeRunTimeoutError("getBalancesAsync")), + ) + val sparkState = MutableStateFlow(SparkState(isReady = true, balanceSats = 100_000uL)) + val spark = sparkRepoWith(sparkState) + sut = createSut(spark = spark) + sut.loadFromCache() + testScheduler.runCurrent() + + sparkExitState.value = SparkExitState(record = SparkExitFixtures.record()) + sparkState.update { it.copy(isExiting = true, balanceSats = 130_000uL) } + testScheduler.runCurrent() + assertEquals(150_000uL, sut.balanceState.value.totalLightningSats) + assertEquals(0uL, sut.balanceState.value.maxSendLightningSats) + assertEquals(null, sut.balanceState.value.sparkBalanceSats) + + val exiting = BalanceState(totalLightningSats = 80_000uL, balanceInTransferToSavings = 105_000uL) + whenever(deriveBalanceStateUseCase.invoke()).thenReturn(Result.success(exiting)) + sut.syncBalances() + assertEquals(exiting, cached.balance) + whenever(deriveBalanceStateUseCase.invoke()).thenReturn( + Result.failure(NodeRunTimeoutError("getBalancesAsync")), + ) + sparkExitState.value = SparkExitState() + sparkState.update { it.copy(isExiting = false) } + testScheduler.runCurrent() + val retained = exiting.copy(maxSendLightningSats = SparkFees.sendableSats(130_000uL)) + assertEquals(retained, sut.balanceState.value) + assertEquals(exiting, cached.balance) + + cached = cached.copy(balance = json.decodeFromString(json.encodeToString(exiting))) + sut = createSut(spark = spark) + sut.loadFromCache() + testScheduler.runCurrent() + assertEquals(retained, sut.balanceState.value) + + val recovered = BalanceState( + totalLightningSats = 180_000uL, + sparkBalanceSats = 130_000uL, + sparkPendingDepositSats = 0uL, + ) + whenever(deriveBalanceStateUseCase.invoke()).thenReturn(Result.success(recovered)) + sut.syncBalances() + whenever(deriveBalanceStateUseCase.invoke()).thenReturn( + Result.failure(NodeRunTimeoutError("getBalancesAsync")), + ) + sparkState.update { it.copy(balanceSats = 120_000uL) } + testScheduler.runCurrent() + assertEquals(170_000uL, sut.balanceState.value.totalLightningSats) + assertEquals(0uL, sut.balanceState.value.balanceInTransferToSavings) + assertEquals(sut.balanceState.value, cached.balance) + } + + @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() + 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()) + } + @Test fun `funding reaching a running exit syncs balances`() = test { whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) @@ -2161,6 +2647,55 @@ class WalletRepoTest : BaseUnitTest() { assertTrue(sut.walletState.value.bip21.contains(INVOICE_REPLACEMENT)) } + @Test + fun `completed wallet reset publishes current credential absence with clear recovery`() = test { + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) + sut.setWalletExistsState() + testScheduler.runCurrent() + val attempt = "00000000-0000-0000-0000-000000000001" + profileRemovalStore.withAccess(attempt, ProfileRemovalScope.WALLET_WIPE) { + profileRemovalStore.begin(attempt) + testScheduler.runCurrent() + assertEquals(WalletResetRecovery.Pending(attempt), sut.walletState.value.walletResetRecovery) + assertTrue(sut.walletState.value.walletExists) + + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(false) + profileRemovalStore.complete(attempt) + testScheduler.runCurrent() + + assertEquals(WalletResetRecovery.Clear, sut.walletState.value.walletResetRecovery) + assertFalse(sut.walletState.value.walletExists) + } + } + + @Test + fun `unreadable wallet presence keeps completed reset unavailable until refresh`() = test { + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) + sut.setWalletExistsState() + testScheduler.runCurrent() + val attempt = "00000000-0000-0000-0000-000000000002" + profileRemovalStore.withAccess(attempt, ProfileRemovalScope.WALLET_WIPE) { + profileRemovalStore.begin(attempt) + testScheduler.runCurrent() + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenAnswer { throw error } + profileRemovalStore.complete(attempt) + testScheduler.runCurrent() + + assertEquals(WalletResetRecovery.Unavailable, sut.walletState.value.walletResetRecovery) + assertTrue(sut.walletState.value.walletExists) + + sut.resetState() + assertEquals(WalletResetRecovery.Unavailable, sut.walletState.value.walletResetRecovery) + assertTrue(sut.walletState.value.walletExists) + + doReturn(false).whenever(keychain).exists(Keychain.Key.BIP39_MNEMONIC.name) + sut.refreshWalletResetRecovery() + testScheduler.runCurrent() + assertEquals(WalletResetRecovery.Clear, sut.walletState.value.walletResetRecovery) + assertFalse(sut.walletState.value.walletExists) + } + } + @Test fun `refreshBip21 keeps the request and creates a new invoice for its amount`() = test { stubReceiveInvoices(INVOICE, INVOICE_REPLACEMENT) @@ -2353,18 +2888,18 @@ class WalletRepoTest : BaseUnitTest() { @Test fun `wipeWallet should call use case`() = test { - whenever(wipeWalletUseCase.invoke(any(), any(), any())).thenReturn(Result.success(Unit)) + whenever(wipeWalletUseCase.invoke(any(), any(), any(), isNull())).thenReturn(Result.success(Unit)) val result = sut.wipeWallet() assertTrue(result.isSuccess) - verify(wipeWalletUseCase).invoke(any(), any(), any()) + verify(wipeWalletUseCase).invoke(any(), any(), any(), isNull()) } @Test fun `wipeWallet re-reads wallet existence when the wipe is incomplete`() = test { whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) - whenever(wipeWalletUseCase.invoke(any(), any(), any())).thenReturn(Result.failure(WipeIncomplete())) + whenever(wipeWalletUseCase.invoke(any(), any(), any(), isNull())).thenReturn(Result.failure(WipeIncomplete())) val result = sut.wipeWallet() @@ -2372,9 +2907,22 @@ 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(), isNull())).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)) + whenever(wipeWalletUseCase.invoke(any(), any(), any(), isNull())).thenReturn(Result.failure(error)) val result = sut.wipeWallet() diff --git a/app/src/test/java/to/bitkit/services/ActivityServiceLightningMessageTest.kt b/app/src/test/java/to/bitkit/services/ActivityServiceLightningMessageTest.kt index 3c58d0d76d..76d76a9368 100644 --- a/app/src/test/java/to/bitkit/services/ActivityServiceLightningMessageTest.kt +++ b/app/src/test/java/to/bitkit/services/ActivityServiceLightningMessageTest.kt @@ -26,6 +26,7 @@ import to.bitkit.data.AppCacheData import to.bitkit.data.CacheStore import to.bitkit.ext.create import to.bitkit.test.BaseUnitTest +import to.bitkit.test.receiptResolverFixture import kotlin.test.assertEquals import kotlin.test.assertNull @@ -71,7 +72,7 @@ class ActivityServiceLightningMessageTest : BaseUnitTest() { fun `payment sync creates the row with the pending comment and clears it`() = coreTest { whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(pendingLightningMessages = mapOf(HASH to COMMENT)))) - sut().syncLdkNodePaymentsToActivities(listOf(payment())) + sut().syncLdkNodePaymentsToActivities({ listOf(payment()) }) val stored = (row as Activity.Lightning).v1 assertEquals(COMMENT, stored.message) @@ -84,7 +85,7 @@ class ActivityServiceLightningMessageTest : BaseUnitTest() { row = Activity.Lightning(sent(status = PaymentState.PENDING, message = DESCRIPTION_HASH)) whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(pendingLightningMessages = mapOf(HASH to COMMENT)))) - sut().syncLdkNodePaymentsToActivities(listOf(payment())) + sut().syncLdkNodePaymentsToActivities({ listOf(payment()) }) val stored = (row as Activity.Lightning).v1 assertEquals(COMMENT, stored.message) @@ -101,7 +102,7 @@ class ActivityServiceLightningMessageTest : BaseUnitTest() { } whenever(cacheStore.data).thenReturn(commentStoredMeanwhile) - sut().syncLdkNodePaymentsToActivities(listOf(payment())) + sut().syncLdkNodePaymentsToActivities({ listOf(payment()) }) val stored = (row as Activity.Lightning).v1 assertEquals(COMMENT, stored.message) @@ -114,7 +115,7 @@ class ActivityServiceLightningMessageTest : BaseUnitTest() { row = Activity.Lightning(retry) whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(sparkSendHashes = listOf(HASH)))) - sut().syncLdkNodePaymentsToActivities(listOf(payment().copy(status = PaymentStatus.FAILED))) + sut().syncLdkNodePaymentsToActivities({ listOf(payment().copy(status = PaymentStatus.FAILED)) }) assertEquals(PaymentState.PENDING, (row as Activity.Lightning).v1.status) } @@ -124,7 +125,7 @@ class ActivityServiceLightningMessageTest : BaseUnitTest() { row = Activity.Lightning(sent(status = PaymentState.PENDING, message = "").copy(updatedAt = 300uL)) whenever(cacheStore.data).thenReturn(flowOf(AppCacheData())) - sut().syncLdkNodePaymentsToActivities(listOf(payment().copy(status = PaymentStatus.FAILED))) + sut().syncLdkNodePaymentsToActivities({ listOf(payment().copy(status = PaymentStatus.FAILED)) }) assertEquals(PaymentState.FAILED, (row as Activity.Lightning).v1.status) } @@ -134,7 +135,7 @@ class ActivityServiceLightningMessageTest : BaseUnitTest() { row = Activity.Lightning(sent(status = PaymentState.PENDING, message = "")) whenever(cacheStore.data).thenReturn(flowOf(AppCacheData())) - sut().syncLdkNodePaymentsToActivities(listOf(payment().copy(status = PaymentStatus.FAILED))) + sut().syncLdkNodePaymentsToActivities({ listOf(payment().copy(status = PaymentStatus.FAILED)) }) assertEquals(PaymentState.FAILED, (row as Activity.Lightning).v1.status) } @@ -144,7 +145,7 @@ class ActivityServiceLightningMessageTest : BaseUnitTest() { row = Activity.Lightning(sent(status = PaymentState.SUCCEEDED, message = "", fee = 1uL, preimage = "pre")) whenever(cacheStore.data).thenReturn(flowOf(AppCacheData())) - sut().syncLdkNodePaymentsToActivities(listOf(payment().copy(status = PaymentStatus.PENDING))) + sut().syncLdkNodePaymentsToActivities({ listOf(payment().copy(status = PaymentStatus.PENDING)) }) assertEquals(PaymentState.SUCCEEDED, (row as Activity.Lightning).v1.status) } @@ -171,7 +172,7 @@ class ActivityServiceLightningMessageTest : BaseUnitTest() { cacheStore = cacheStore, lightningService = lightningService, settingsStore = mock(), - privatePaykitContactResolver = mock(), + privatePaykitContactResolver = javax.inject.Provider { receiptResolverFixture(testDispatcher) }, ) private fun sent( diff --git a/app/src/test/java/to/bitkit/services/ActivityServicePaykitContactsTest.kt b/app/src/test/java/to/bitkit/services/ActivityServicePaykitContactsTest.kt index 3ffbc62472..bfb13e3ed3 100644 --- a/app/src/test/java/to/bitkit/services/ActivityServicePaykitContactsTest.kt +++ b/app/src/test/java/to/bitkit/services/ActivityServicePaykitContactsTest.kt @@ -16,9 +16,16 @@ import com.synonym.bitkitcore.updateActivity import com.synonym.bitkitcore.upsertActivity import com.synonym.bitkitcore.upsertOnchainActivityPreservingFeeRate import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Job +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.launch +import kotlinx.coroutines.supervisorScope import org.junit.Test import org.lightningdevkit.ldknode.ConfirmationStatus import org.lightningdevkit.ldknode.OnchainWalletAccount @@ -29,6 +36,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.eq import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock @@ -41,18 +49,28 @@ import to.bitkit.data.AppCacheData import to.bitkit.data.CacheStore import to.bitkit.data.PrivatePaykitCacheData import to.bitkit.data.PrivatePaykitCacheStore +import to.bitkit.data.PrivatePaykitContactCacheData +import to.bitkit.data.PrivatePaykitReservationData +import to.bitkit.data.PrivatePaykitReservationStore +import to.bitkit.data.PrivatePaykitStoredAssignmentData +import to.bitkit.data.ProfileRemovalStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.ext.create import to.bitkit.ext.scopedActivityId +import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.PaykitPaymentRequestRepo import to.bitkit.repositories.PaykitReceivedPaymentContacts import to.bitkit.repositories.PaykitReceivedPaymentContactsTest.Companion.BUYER import to.bitkit.repositories.PaykitReceivedPaymentContactsTest.Companion.OTHER_BUYER import to.bitkit.repositories.PrivatePaykitAddressReservationRepo +import to.bitkit.repositories.PrivatePaykitAddressReservationRepo.ReceiptAssignments import to.bitkit.repositories.PrivatePaykitContactResolver import to.bitkit.test.BaseUnitTest +import to.bitkit.test.connectionRecoveryFixture import to.bitkit.utils.AppError +import java.io.IOException +import java.util.UUID import javax.inject.Provider import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -67,7 +85,11 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { private val contacts = mock() private val requestRepo = mock() private val reservations = mock() + private var receiptReservations = reservations private val privateCacheStore = mock() + private val profileRemovalStore = ProfileRemovalStore.inMemoryForTesting() + private var walletBinding = "original-wallet" + private val connectionRecovery = connectionRecoveryFixture(mock(), currentBinding = { walletBinding }) private val cacheStore = mock() private val cacheData = MutableStateFlow(AppCacheData(onchainAddress = "wallet-address")) private val settingsStore = mock() @@ -77,8 +99,10 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { PrivatePaykitContactResolver( ioDispatcher = testDispatcher, cacheStore = privateCacheStore, - addressReservationRepo = Provider { reservations }, + addressReservationRepo = Provider { receiptReservations }, paymentRequestRepo = Provider { requestRepo }, + profileRemovalStore = profileRemovalStore, + connectionRecovery = Provider { connectionRecovery }, ) } private val sut by lazy { @@ -91,6 +115,29 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { private var activityReads = 0 private var detailReads = 0 + @Test + fun `backfill retains its captured contact across completed profile cleanup`() = 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 + } + + assertTrue(sut.backfillPaykitContacts()) + assertEquals(BUYER, (updates.single() as Activity.Onchain).v1.contact) + rows = listOf(updates.single()) + whenever(reservations.contactPublicKeyForReservedAddress(any())).thenReturn(null) + assertFalse(sut.backfillPaykitContacts()) + assertEquals(1, activityReads) + } + @Test fun `backfill matches receiving address in outputs and preserves all other onchain metadata`() = coreTest { val original = onchain(address = "request-address") @@ -109,11 +156,11 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { fun `backfill matches lightning hash when invoice text is missing and preserves metadata`() = coreTest { val original = lightning() rows = listOf(Activity.Lightning(original)) - whenever(contacts.contactsForPaymentHash(original.id)).thenReturn(setOf("buyer")) + whenever(contacts.contactsForPaymentHash(original.id)).thenReturn(setOf(BUYER)) assertTrue(sut.backfillPaykitContacts()) - assertEquals(listOf(Activity.Lightning(original.copy(contact = "buyer"))), updates) + assertEquals(listOf(Activity.Lightning(original.copy(contact = BUYER))), updates) } @Test @@ -125,8 +172,8 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { Activity.Lightning(lightning().copy(txType = PaymentType.SENT)), Activity.Lightning(lightning().copy(status = PaymentState.FAILED)), ) - whenever(contacts.contactsForPaymentHash(any())).thenReturn(setOf("buyer")) - whenever(contacts.contactsForAddresses(any())).thenReturn(setOf("buyer")) + whenever(contacts.contactsForPaymentHash(any())).thenReturn(setOf(BUYER)) + whenever(contacts.contactsForAddresses(any())).thenReturn(setOf(BUYER)) assertFalse(sut.backfillPaykitContacts()) assertTrue(updates.isEmpty()) @@ -154,7 +201,7 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { var cacheReads = 0 whenever(cacheStore.data).thenReturn( flow { - if (++cacheReads == 2) { + if (++cacheReads == 1) { sut.update(original.id, edited) rows = listOf(edited) } @@ -195,21 +242,42 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { } @Test - fun `backfill refuses stale identity snapshot before write`() = coreTest { + fun `backfill keeps its immutable received contact after the live profile cache is cleared`() = coreTest { rows = listOf(Activity.Lightning(lightning())) whenever(contacts.contactsForPaymentHash(any())).thenAnswer { whenever(requestRepo.receivedPaymentContacts).thenReturn(PaykitReceivedPaymentContacts.Empty) - setOf("buyer") + setOf(BUYER) } - assertFalse(sut.backfillPaykitContacts()) - assertTrue(updates.isEmpty()) + assertTrue(sut.backfillPaykitContacts()) + assertEquals(BUYER, (updates.single() as Activity.Lightning).v1.contact) + } + + @Test + fun `backfill drains before wallet replacement and refuses its final write`() = coreTest { + rows = listOf(Activity.Lightning(lightning())) + supervisorScope { + lateinit var replacement: Job + whenever(contacts.contactsForPaymentHash(any())).thenAnswer { + replacement = launch(start = CoroutineStart.UNDISPATCHED) { + connectionRecovery.withIdentityChange { walletBinding = "replacement-wallet" } + } + assertFalse(replacement.isCompleted) + assertEquals("original-wallet", walletBinding) + setOf(BUYER) + } + + assertFailsWith { sut.backfillPaykitContacts() } + replacement.join() + assertEquals("replacement-wallet", walletBinding) + assertTrue(updates.isEmpty()) + } } @Test fun `backfill remains idempotent after persisted activity is reopened`() = coreTest { rows = listOf(Activity.Lightning(lightning())) - whenever(contacts.contactsForPaymentHash(any())).thenReturn(setOf("buyer")) + whenever(contacts.contactsForPaymentHash(any())).thenReturn(setOf(BUYER)) assertTrue(sut.backfillPaykitContacts()) rows = updates.toList() updates.clear() @@ -293,7 +361,7 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { details = mock { on { this.outputs }.thenReturn(outputs) } whenever(reservations.contactPublicKeyForReservedAddress(any())) .thenThrow(IllegalStateException("unavailable")).thenReturn(null) - assertFailsWith { sut.backfillPaykitContacts() } + assertFalse(sut.backfillPaykitContacts()) assertTrue(sut.backfillPaykitContacts()) assertFalse(sut.backfillPaykitContacts()) @@ -329,21 +397,24 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { } @Test - fun `reservation mutation during backfill cannot cache or write stale attribution`() = coreTest { + fun `reservation mutation during snapshot capture cannot cache or write partial attribution`() = 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) - whenever(reservations.contactPublicKeyForReservedAddress(any())).thenAnswer { + whenever(reservations.receiptAssignments()).doSuspendableAnswer { + val captured = reservationVersion.value reservationVersion.value++ - null + ReceiptAssignments(emptyList(), captured) } assertFalse(sut.backfillPaykitContacts()) assertTrue(updates.isEmpty()) - whenever(reservations.contactPublicKeyForReservedAddress(any())).thenReturn(null) + whenever( + reservations.receiptAssignments() + ).thenAnswer { ReceiptAssignments(emptyList(), reservationVersion.value) } assertTrue(sut.backfillPaykitContacts()) - assertEquals(2, activityReads) + assertEquals(1, activityReads) } @Test @@ -397,6 +468,120 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { assertEquals(BUYER, row.contact) } + @Test + fun `reservation derivation failure preserves receipt accounting and retries contact backfill`() = coreTest { + val address = "bcrt1qterdweva9vextackckt6pjy0mmuc54g87g6lsq" + cacheData.value = cacheData.value.copy(onchainAddress = address) + val ledger = flowOf( + PrivatePaykitReservationData( + contactAssignments = mapOf(BUYER to PrivatePaykitStoredAssignmentData("nativeSegwit", 9000, "")), + ) + ) + val store = mock() + whenever(store.data).thenReturn(ledger) + val lightning = mock() + receiptReservations = PrivatePaykitAddressReservationRepo( + testDispatcher, store, settingsStore, coreService, lightning, cacheStore, mock(), + ) + whenever( + lightning.addressInfoForType(any(), any()) + ).thenReturn(Result.failure(IOException("derivation unavailable"))) + val outputs = listOf(output(address)) + details = mock { on { this.outputs }.thenReturn(outputs) } + + sut.syncLdkNodePaymentsToActivities({ listOf(payment()) }) + + val stored = (updates.single() as Activity.Onchain).v1 + assertEquals(15_000uL, stored.value) + assertFalse(stored.confirmed) + assertEquals(address, stored.address) + assertNull(stored.contact) + verify(lightning).addressInfoForType(AddressType.P2WPKH, 9000) + rows = updates.toList() + updates.clear() + assertFalse(sut.backfillPaykitContacts()) + assertTrue(updates.isEmpty()) + whenever(lightning.addressInfoForType(any(), any())) + .thenReturn(Result.success(AddressDerivationInfo(address, 9000))) + assertTrue(sut.backfillPaykitContacts()) + assertEquals(BUYER, (updates.single() as Activity.Onchain).v1.contact) + 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, cacheStore, mock(), + ) + 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 { + whenever(lightningService.listOnchainWalletAccounts()).thenReturn( + listOf(OnchainWalletAccount(LdkAddressType.NATIVE_SEGWIT, 0u)), + ) + val address = "bcrt1qterdweva9vextackckt6pjy0mmuc54g87g6lsq" + val ledger = MutableStateFlow( + PrivatePaykitReservationData( + contactAssignments = mapOf(BUYER to PrivatePaykitStoredAssignmentData("nativeSegwit", 9000, address)), + ) + ) + val store = mock() + whenever(store.data).thenReturn(ledger) + whenever(store.update(any())).thenAnswer { + val transform: (PrivatePaykitReservationData) -> PrivatePaykitReservationData = it.getArgument(0) + ledger.value = transform(ledger.value) + } + receiptReservations = PrivatePaykitAddressReservationRepo( + testDispatcher, store, settingsStore, coreService, mock(), cacheStore, mock(), + ) + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever(lightningService.addressInfosForType(any(), any(), any(), any(), any())).doSuspendableAnswer { + entered.complete(Unit) + release.await() + emptyList() + } + coroutineScope { + val incoming = async { receive(address) } + entered.await() + val id = UUID.randomUUID().toString() + profileRemovalStore.withAccess(id) { + profileRemovalStore.begin(id) + profileRemovalStore.withReceiptCleanup { receiptReservations.clearContactAssignments(emptySet()) } + profileRemovalStore.complete(id) + } + assertTrue(ledger.value.contactAssignments.isEmpty()) + release.complete(Unit) + incoming.await() + } + val row = (updates.single() as Activity.Onchain).v1 + assertEquals(address, row.address) + assertEquals(BUYER, row.contact) + assertEquals(15_000uL, row.value) + } + @Test fun `registered companion account resolves request destination with scoped search indexes`() = coreTest { sharedAddresses("server-address" to BUYER) @@ -556,13 +741,109 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { verify(lightningService, never()).addressInfosForType(AddressType.P2WPKH, true, 1400, 200, 5u) } + @Test + fun `received private invoice keeps its historical contact during pending profile cleanup`() = coreTest { + val cached = MutableStateFlow( + PrivatePaykitCacheData( + contacts = mapOf( + BUYER to PrivatePaykitContactCacheData(receivedInvoicePaymentHashes = listOf("received")) + ) + ) + ) + whenever(privateCacheStore.data).thenReturn(cached) + val id = UUID.randomUUID().toString() + profileRemovalStore.withAccess(id) { profileRemovalStore.begin(id) } + val received = payment().copy( + kind = PaymentKind.Bolt11( + hash = "received", + preimage = "preimage", + secret = null, + bolt11 = null, + description = "receipt", + ) + ) + + sut.syncLdkNodePaymentsToActivities({ listOf(received) }) + + val first = updates.single() as Activity.Lightning + assertEquals(15_000uL, first.v1.value) + assertEquals(BUYER, first.v1.contact) + rows = listOf(first) + cached.value = PrivatePaykitCacheData() + profileRemovalStore.withAccess(id) { profileRemovalStore.complete(id) } + sut.syncLdkNodePaymentsToActivities({ listOf(received) }) + assertEquals(BUYER, (updates.last() as Activity.Lightning).v1.contact) + } + + @Test + fun `profile cleanup preserves accounting without claiming complete contacts`() = coreTest { + verifyAccountingWithUnavailableAssociations(cleanupPending = true) + } + + @Test + fun `unreadable invoice cache preserves accounting and a later valid source can backfill`() = coreTest { + verifyAccountingWithUnavailableAssociations(cleanupPending = false) + } + + private suspend fun verifyAccountingWithUnavailableAssociations(cleanupPending: Boolean) { + whenever(contacts.contactsForPaymentHash(any())).thenReturn(setOf(BUYER)) + val id = UUID.randomUUID().toString() + if (cleanupPending) { + profileRemovalStore.withAccess(id) { + profileRemovalStore.begin(id) + profileRemovalStore.beginLocalCleanup() + } + } else { + whenever(privateCacheStore.data).thenReturn(flowOf(PrivatePaykitCacheData(receiptSourceReadable = false))) + } + val inbound = payment().copy(kind = PaymentKind.Bolt11("received", "preimage", null, null, "receipt")) + val outbound = inbound.copy(id = "sent", direction = PaymentDirection.OUTBOUND) + sut.syncLdkNodePaymentsToActivities({ listOf(inbound, outbound) }) + assertEquals(2, updates.size) + val stored = updates.filterIsInstance() + assertTrue( + stored.all { it.v1.value == 15_000uL && it.v1.status == PaymentState.SUCCEEDED && it.v1.contact == null } + ) + assertEquals(setOf(PaymentType.RECEIVED, PaymentType.SENT), stored.map { it.v1.txType }.toSet()) + rows = updates.toList() + updates.clear() + assertFalse(sut.backfillPaykitContacts()) + assertTrue(updates.isEmpty()) + assertEquals(0, activityReads) + if (cleanupPending) profileRemovalStore.withAccess(id) { profileRemovalStore.complete(id) } + whenever(privateCacheStore.data).thenReturn(flowOf(PrivatePaykitCacheData())) + assertTrue(sut.backfillPaykitContacts()) + assertEquals(BUYER, (updates.single() as Activity.Lightning).v1.contact) + assertEquals(1, activityReads) + } + + @Test + fun `received reserved address keeps its historical contact during pending profile cleanup`() = coreTest { + val outputs = listOf(output("wallet-address")) + details = mock { on { this.outputs }.thenReturn(outputs) } + whenever(reservations.contactPublicKeyForReservedAddress("wallet-address")).thenReturn(BUYER) + val id = UUID.randomUUID().toString() + profileRemovalStore.withAccess(id) { profileRemovalStore.begin(id) } + + sut.syncLdkNodePaymentsToActivities({ listOf(payment()) }) + + val first = updates.single() as Activity.Onchain + assertEquals(15_000uL, first.v1.value) + assertEquals(BUYER, first.v1.contact) + rows = listOf(first) + whenever(reservations.contactPublicKeyForReservedAddress("wallet-address")).thenReturn(null) + profileRemovalStore.withAccess(id) { profileRemovalStore.complete(id) } + sut.syncLdkNodePaymentsToActivities({ listOf(payment()) }) + assertEquals(BUYER, (updates.last() as Activity.Onchain).v1.contact) + } + @Test fun `payment sync uses stored outputs for receiving address attribution`() = coreTest { val outputs = listOf(output("wallet-address"), output("unrelated-address")) details = mock { on { this.outputs }.thenReturn(outputs) } sharedAddresses("wallet-address" to BUYER) - sut.syncLdkNodePaymentsToActivities(listOf(payment())) + sut.syncLdkNodePaymentsToActivities({ listOf(payment()) }) assertEquals(BUYER, (updates.single() as Activity.Onchain).v1.contact) } @@ -574,7 +855,7 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { val outputs = listOf(output("wallet-address")) details = mock { on { this.outputs }.thenReturn(outputs) } - repeat(2) { sut.syncLdkNodePaymentsToActivities(listOf(payment())) } + repeat(2) { sut.syncLdkNodePaymentsToActivities({ listOf(payment()) }) } assertEquals(2, updates.size) assertTrue(updates.all { (it as Activity.Onchain).v1.contact == BUYER }) @@ -593,7 +874,7 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { details = mock { on { this.outputs }.thenReturn(outputs) } sharedAddresses("wallet-address" to BUYER) - repeat(2) { sut.syncLdkNodePaymentsToActivities(listOf(payment())) } + repeat(2) { sut.syncLdkNodePaymentsToActivities({ listOf(payment()) }) } assertEquals(2, updates.size) assertTrue(updates.all { (it as Activity.Onchain).v1.contact == null }) @@ -610,7 +891,7 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { ) repeat(2) { - sut.syncLdkNodePaymentsToActivities(listOf(incoming)) + sut.syncLdkNodePaymentsToActivities({ listOf(incoming) }) rows = listOf(updates.last()) } @@ -646,6 +927,12 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { private fun coreTest(block: suspend () -> Unit) = test { whenever(requestRepo.receivedPaymentContacts).thenReturn(contacts) whenever(reservations.attributionVersion).thenAnswer { reservationVersion.value } + whenever( + reservations.receiptAssignments() + ).thenAnswer { ReceiptAssignments(emptyList(), reservationVersion.value) } + whenever(reservations.contactsForReceipt(any(), any())).doSuspendableAnswer { + listOfNotNull(reservations.contactPublicKeyForReservedAddress(it.getArgument(0))) + } whenever(privateCacheStore.data).thenReturn(flowOf(PrivatePaykitCacheData())) whenever(cacheStore.data).thenReturn(cacheData) whenever(cacheStore.update(any())).thenAnswer { @@ -667,8 +954,13 @@ class ActivityServicePaykitContactsTest : BaseUnitTest() { rows } native.`when` { getActivityById(any(), any()) }.thenAnswer { invocation -> - rows.filterIsInstance().firstOrNull { - it.v1.walletId == invocation.arguments[0] && it.v1.id == invocation.arguments[1] + rows.firstOrNull { + when (it) { + is Activity.Onchain -> it.v1.walletId == invocation.arguments[0] && + it.v1.id == invocation.arguments[1] + is Activity.Lightning -> it.v1.walletId == invocation.arguments[0] && + it.v1.id == invocation.arguments[1] + } } } native.`when` { getActivityByTxId(any(), any()) }.thenAnswer { invocation -> diff --git a/app/src/test/java/to/bitkit/services/ActivityServiceRbfTest.kt b/app/src/test/java/to/bitkit/services/ActivityServiceRbfTest.kt index 6beda874f8..611ca44a63 100644 --- a/app/src/test/java/to/bitkit/services/ActivityServiceRbfTest.kt +++ b/app/src/test/java/to/bitkit/services/ActivityServiceRbfTest.kt @@ -6,9 +6,11 @@ import com.synonym.bitkitcore.PaymentType import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.async import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.launch import org.junit.Test import org.lightningdevkit.ldknode.ConfirmationStatus import org.lightningdevkit.ldknode.PaymentDetails @@ -26,11 +28,20 @@ import org.mockito.kotlin.whenever import to.bitkit.async.ServiceQueue 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.ext.create import to.bitkit.ext.scopedActivityId import to.bitkit.models.WalletScope +import to.bitkit.repositories.PaykitPaymentRequestRepo +import to.bitkit.repositories.PaykitReceivedPaymentContacts +import to.bitkit.repositories.PrivatePaykitAddressReservationRepo +import to.bitkit.repositories.PrivatePaykitContactResolver import to.bitkit.test.BaseUnitTest +import to.bitkit.test.connectionRecoveryFixture import to.bitkit.utils.RbfOriginalConfirmed +import javax.inject.Provider import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse @@ -38,9 +49,32 @@ import kotlin.test.assertTrue class ActivityServiceRbfTest : BaseUnitTest() { private val binding = Class.forName("com.synonym.bitkitcore.Bitkitcore_androidKt") + private val recovery = connectionRecoveryFixture(mock()) + private val receiptCache = mock() + private val reservations = mock() + private val requests = mock() + private val resolver by lazy { + PrivatePaykitContactResolver( + testDispatcher, + receiptCache, + Provider { reservations }, + Provider { requests }, + ProfileRemovalStore.inMemoryForTesting(), + Provider { recovery }, + ) + } + + private suspend fun prepareReceipt() { + whenever(receiptCache.data).thenReturn(flowOf(PrivatePaykitCacheData())) + whenever(requests.receivedPaymentContacts).thenReturn(PaykitReceivedPaymentContacts.Empty) + whenever(reservations.receiptAssignments()).thenReturn( + PrivatePaykitAddressReservationRepo.ReceiptAssignments(emptyList(), 0L), + ) + } + private val cache = mock() private val lightning = mock() - private val sut by lazy { ActivityService(mock(), cache, lightning, mock(), mock()) } + private val sut by lazy { ActivityService(mock(), cache, lightning, mock(), Provider { resolver }) } private val genericWrites = mutableListOf() @Test @@ -85,7 +119,7 @@ class ActivityServiceRbfTest : BaseUnitTest() { whenever(cache.data).thenReturn(flowOf(AppCacheData())) withActivities { saved, _ -> saved["b"] = saved.getValue("b").copy(feeRate = 25uL) - sut.syncLdkNodePaymentsToActivities(listOf(payment("b"))) + sut.syncLdkNodePaymentsToActivities({ listOf(payment("b")) }) assertTrue(saved.getValue("b").confirmed) assertEquals(25uL, saved.getValue("b").feeRate) assertEquals(422uL, saved.getValue("b").fee) @@ -138,6 +172,37 @@ class ActivityServiceRbfTest : BaseUnitTest() { } } + @Test + fun `wallet replacement drains held RBF publication without retiring original metadata`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever(cache.data).thenReturn( + flow { + entered.complete(Unit) + release.await() + emit(AppCacheData()) + } + ) + withActivities { saved, _ -> + val original = saved.getValue("a") + val replacement = saved.getValue("b") + val publication = async { sut.publishRbfBoost("a", "b") } + entered.await() + var replaced = false + val transition = launch(start = CoroutineStart.UNDISPATCHED) { + recovery.withIdentityChange { replaced = true } + } + assertFalse(replaced) + assertFalse(transition.isCompleted) + release.complete(Unit) + assertFailsWith { publication.await() } + transition.join() + assertTrue(replaced) + assertEquals(original, saved.getValue("a")) + assertEquals(replacement, saved.getValue("b")) + } + } + @Test fun `publication cannot retire an original that confirms during the wait`() = test { val entered = CompletableDeferred() @@ -395,6 +460,7 @@ class ActivityServiceRbfTest : BaseUnitTest() { failFirstTagRead: Boolean = false, block: suspend CoroutineScope.(MutableMap, MutableMap>) -> Unit, ) = ServiceQueue.CORE.background { + prepareReceipt() val wallet = WalletScope.default val saved = listOf("a", "b", "c").associateWith { txid -> OnchainActivity.create( diff --git a/app/src/test/java/to/bitkit/services/ActivityServiceTest.kt b/app/src/test/java/to/bitkit/services/ActivityServiceTest.kt index 6eb4e5ebaf..ee9ddf2ee4 100644 --- a/app/src/test/java/to/bitkit/services/ActivityServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/ActivityServiceTest.kt @@ -32,6 +32,7 @@ import to.bitkit.ext.create import to.bitkit.ext.scopedActivityId import to.bitkit.models.WalletScope import to.bitkit.test.BaseUnitTest +import to.bitkit.test.receiptResolverFixture import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNull @@ -66,7 +67,7 @@ class ActivityServiceTest : BaseUnitTest() { cacheStore = cacheStore, lightningService = lightningService, settingsStore = mock(), - privatePaykitContactResolver = mock(), + privatePaykitContactResolver = javax.inject.Provider { receiptResolverFixture(testDispatcher) }, ) } @@ -303,7 +304,7 @@ class ActivityServiceTest : BaseUnitTest() { latestUpdateTimestamp = 100uL, ) withOnchainActivities(transactionId) { saved -> - val syncing = async { sut.syncLdkNodePaymentsToActivities(listOf(payment)) } + val syncing = async { sut.syncLdkNodePaymentsToActivities({ listOf(payment) }) } syncPaused.await() sut.createSentOnchainActivityFromSendResult( txid = transactionId, @@ -322,12 +323,14 @@ class ActivityServiceTest : BaseUnitTest() { assertEquals(listOf(transactionId), saved.keys.toList()) val confirmed = mock { on { timestamp }.thenReturn(200uL) } sut.syncLdkNodePaymentsToActivities( - listOf( - payment.copy( - kind = PaymentKind.Onchain(transactionId, confirmed), - latestUpdateTimestamp = 200uL, - ), - ), + { + listOf( + payment.copy( + kind = PaymentKind.Onchain(transactionId, confirmed), + latestUpdateTimestamp = 200uL, + ), + ) + }, ) val activity = saved.values.single().v1 assertEquals(transactionId, activity.id) diff --git a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt index dc994b87a1..7d686d6b78 100644 --- a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt @@ -1056,6 +1056,22 @@ class LightningServiceTest : BaseUnitTest() { setupDone.await() // proceeds once released (build then fails on the mocked deps, which is fine) } + @Test + fun `wipeStorage reports a refused local delete and succeeds after access is restored`() = runGateTest { + gated.node = null + val directory = File(Env.ldkStoragePath(0)).apply { mkdirs() } + val sentinel = File(directory, "retained-node-state").apply { writeText("test-data") } + assertTrue(directory.setWritable(false, false)) + try { + assertFailsWith { gated.wipeStorage(0) } + assertTrue(sentinel.exists()) + } finally { + assertTrue(directory.setWritable(true, true)) + } + gated.wipeStorage(0) + assertFalse(directory.exists()) + } + // Regression (c): with no pending release the gate must add no latency. @Test fun `wipeStorage proceeds immediately when no release is pending`() = runGateTest { @@ -1315,6 +1331,46 @@ class LightningServiceTest : BaseUnitTest() { verify(watchOnlyAccountStore).completeReconciliation(walletIndex = 0) } + @Test + fun `release never adds an unconfirmed wallet coin`() = test { + val original = releaseCoin("11", 1_200uL) + val unconfirmed = releaseCoin("33", 90_000uL) + // The original's coin alone cannot fund the release; any set with the extra coin can. + stubRelease( + coins = listOf(original, unconfirmed), + confirmedTxids = emptySet(), + funds = { utxos -> unconfirmed in utxos }, + ) + + val prepared = runCatching { sut.prepareRelease(releaseAttempt(original)) }.getOrNull() + + val spent = prepared?.receipt?.inputs.orEmpty().map { it.txid } + assertFalse( + unconfirmed.outpoint.txid in spent, + "Release spends an unconfirmed coin; nodes holding a candidate reject it (BIP125 rule 2)", + ) + } + + @Test + fun `release adds confirmed wallet coins largest first until they fund it`() = test { + val original = releaseCoin("11", 1_200uL) + val large = releaseCoin("22", 50_000uL) + val medium = releaseCoin("33", 40_000uL) + val dust = releaseCoin("44", 600uL) + val coins = listOf(dust, original, medium, large) + stubRelease( + coins = coins, + confirmedTxids = coins.map { it.outpoint.txid }.toSet(), + funds = { utxos -> utxos.sumOf { it.valueSats } >= 80_000uL }, + ) + + val prepared = sut.prepareRelease(releaseAttempt(original)) + + // The original's coin alone and with the largest coin both fall short; the next set pays without the dust. + assertEquals(listOf(original, large, medium).map { it.outpoint.txid }, prepared.receipt.inputs.map { it.txid }) + assertTrue(requireNotNull(prepared.receipt.miningFeeSats) > RELEASE_CANDIDATE_FEE) + } + @Test fun `build without paykit server accounts when the node rejects one`() = test { val account = OnchainWalletAccountConfig(AddressType.NATIVE_SEGWIT, 1u, "xpub-1") @@ -1506,46 +1562,6 @@ class LightningServiceTest : BaseUnitTest() { setupState = WatchOnlyAccountSetupState.Active, ) - @Test - fun `release never adds an unconfirmed wallet coin`() = test { - val original = releaseCoin("11", 1_200uL) - val unconfirmed = releaseCoin("33", 90_000uL) - // The original's coin alone cannot fund the release; any set with the extra coin can. - stubRelease( - coins = listOf(original, unconfirmed), - confirmedTxids = emptySet(), - funds = { utxos -> unconfirmed in utxos }, - ) - - val prepared = runCatching { sut.prepareRelease(releaseAttempt(original)) }.getOrNull() - - val spent = prepared?.receipt?.inputs.orEmpty().map { it.txid } - assertFalse( - unconfirmed.outpoint.txid in spent, - "Release spends an unconfirmed coin; nodes holding a candidate reject it (BIP125 rule 2)", - ) - } - - @Test - fun `release adds confirmed wallet coins largest first until they fund it`() = test { - val original = releaseCoin("11", 1_200uL) - val large = releaseCoin("22", 50_000uL) - val medium = releaseCoin("33", 40_000uL) - val dust = releaseCoin("44", 600uL) - val coins = listOf(dust, original, medium, large) - stubRelease( - coins = coins, - confirmedTxids = coins.map { it.outpoint.txid }.toSet(), - funds = { utxos -> utxos.sumOf { it.valueSats } >= 80_000uL }, - ) - - val prepared = sut.prepareRelease(releaseAttempt(original)) - - // The original's coin alone and with the largest coin both fall short; the next set pays without the dust. - assertEquals(listOf(original, large, medium).map { it.outpoint.txid }, prepared.receipt.inputs.map { it.txid }) - assertTrue(requireNotNull(prepared.receipt.miningFeeSats) > RELEASE_CANDIDATE_FEE) - } - @Test fun `release falls back to every confirmed wallet coin`() = test { val original = releaseCoin("11", 1_200uL) diff --git a/app/src/test/java/to/bitkit/services/PaykitKeyGenerationTest.kt b/app/src/test/java/to/bitkit/services/PaykitKeyGenerationTest.kt index 3a548d24cf..3f4c63b3fe 100644 --- a/app/src/test/java/to/bitkit/services/PaykitKeyGenerationTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitKeyGenerationTest.kt @@ -188,30 +188,63 @@ class PaykitKeyGenerationTest { } @Test - fun `session key rotation rebuilds cached session access with the refreshed key`() { + fun `session key rotation retains live capsule and revokes prior admission before replacement`() { val keychain = mock() whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn("saved-session") val initialKey = mock { on { keyGeneration() }.thenReturn(2uL) } val rotatedKey = mock { on { keyGeneration() }.thenReturn(3uL) } val initialAccess = mock() + val attachedAccess = mock() whenever(initialAccess.exportSessionSecret()).thenReturn("saved-session") whenever(initialAccess.exportPaykitIdentitySecretKey()).thenReturn(initialKey) - val provider = PaykitSdkSessionProvider(keychain, mock()) + whenever(initialAccess.withPaykitIdentitySecretKey(rotatedKey)).thenReturn(attachedAccess) + whenever(attachedAccess.exportSessionSecret()).thenReturn("saved-session") + var invalidations = 0 + val provider = PaykitSdkSessionProvider(keychain, mock()) { invalidations++ } provider.setLiveSessionAccess(initialAccess) provider.setPaykitIdentitySecretKey(initialKey) assertSame(initialAccess, provider.loadSessionAccess()) - mockConstruction(PubkySessionAccess::class.java) { access, context -> - assertEquals(BitkitPaykitSdkConfig.clientId, context.arguments()[0]) - assertEquals("saved-session", context.arguments()[1]) - assertSame(rotatedKey, context.arguments()[3]) - whenever(access.exportSessionSecret()).thenReturn("saved-session") - }.use { sessions -> + assertEquals(1, invalidations) + mockConstruction(PubkySessionAccess::class.java).use { sessions -> provider.setPaykitIdentitySecretKey(rotatedKey) val refreshedAccess = provider.loadSessionAccess() - assertSame(sessions.constructed().single(), refreshedAccess) + assertSame(attachedAccess, refreshedAccess) assertSame(refreshedAccess, provider.loadSessionAccess()) - assertEquals(1, sessions.constructed().size) + assertEquals(0, sessions.constructed().size) + assertEquals(2, invalidations) + } + } + + @Test + fun `bootstrap nil key and same generation replacement use immutable attachment without reconstruction`() { + val keychain = mock() + whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn("saved-session") + val bootstrap = mock() + val first = mock() + val second = mock() + listOf(bootstrap, first, second).forEach { + whenever(it.exportSessionSecret()).thenReturn("saved-session") + } + val firstKey = mock { on { keyGeneration() }.thenReturn(1uL) } + val replacement = mock { on { keyGeneration() }.thenReturn(1uL) } + var invalidations = 0 + whenever(bootstrap.withPaykitIdentitySecretKey(firstKey)).thenAnswer { + assertEquals(2, invalidations) + first + } + whenever(first.withPaykitIdentitySecretKey(replacement)).thenAnswer { + assertEquals(3, invalidations) + second + } + val provider = PaykitSdkSessionProvider(keychain, mock()) { invalidations++ } + mockConstruction(PubkySessionAccess::class.java).use { sessions -> + provider.setLiveSessionAccess(bootstrap) + provider.setPaykitIdentitySecretKey(firstKey) + assertSame(first, provider.loadSessionAccess()) + provider.setPaykitIdentitySecretKey(replacement) + assertSame(second, provider.loadSessionAccess()) + assertEquals(0, sessions.constructed().size) } } diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkOperationLockTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkOperationLockTest.kt index d5c96eab32..16f3d3e5f4 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkOperationLockTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkOperationLockTest.kt @@ -1,14 +1,22 @@ package to.bitkit.services import com.synonym.paykit.PaykitException +import com.synonym.paykit.PubkyGrantLogout +import com.synonym.paykit.PubkyGrantLogoutReceipt 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 org.mockito.kotlin.mock import to.bitkit.services.PaykitSdkOperationLock.Priority import kotlin.coroutines.cancellation.CancellationException import kotlin.test.assertEquals @@ -18,6 +26,206 @@ import kotlin.test.assertTrue @OptIn(ExperimentalCoroutinesApi::class) class PaykitSdkOperationLockTest { + @Test + fun `key replacement inside remote cleanup prevents later native work but admits local completion`() = runTest { + val binding = PubkyGrantLogoutReceipt("identity", "homeserver", "original", "bitkit") + val native = mock { on { binding() }.thenReturn(binding) } + val logout = PaykitProfileLogout(native, mock()) { true } + val lock = PaykitSdkOperationLock() + var localCompletions = 0 + lock.withProfileRemoval({ true }) { + withContext(logout) { + lock.withLock { + // A provider key replacement can occur while preparing a native operation. + logout.revoke() + assertFailsWith { lock.checkProfileRemoval() } + assertFailsWith { lock.requireProfileRemoval() } + } + assertFailsWith { + lock.withLock { error("revoked remote work ran") } + } + } + lock.withLock { localCompletions++ } + } + assertEquals(1, localCompletions) + } + + @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() @@ -204,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() diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt index 2888d2b0d2..4227dcce0f 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt @@ -1,5 +1,9 @@ package to.bitkit.services +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.mutablePreferencesOf +import androidx.datastore.preferences.core.stringPreferencesKey import com.synonym.paykit.AllowanceFilter import com.synonym.paykit.AllowanceRecord import com.synonym.paykit.ContactRecord @@ -31,6 +35,7 @@ import com.synonym.paykit.PaymentRequestRecurrence import com.synonym.paykit.PaymentRequestTerms import com.synonym.paykit.PrivateJsonObject import com.synonym.paykit.PrivateMessageSchedulingSnapshot +import com.synonym.paykit.PrivatePaymentListAcknowledgement import com.synonym.paykit.PrivatePaymentListDeliveryReport import com.synonym.paykit.PrivatePaymentListReservationUpdateInput import com.synonym.paykit.PrivatePaymentListSyncChange @@ -39,6 +44,9 @@ import com.synonym.paykit.PrivateStreamIntakeReport import com.synonym.paykit.ProfileResolution import com.synonym.paykit.PubkyAuthCompanionClaim import com.synonym.paykit.PubkyClientConfig +import com.synonym.paykit.PubkyGrantLogout +import com.synonym.paykit.PubkyGrantLogoutAttempt +import com.synonym.paykit.PubkyGrantLogoutReceipt import com.synonym.paykit.PubkyIdentityCapability import com.synonym.paykit.PubkyLocalSecretKey import com.synonym.paykit.PubkyProfileSnapshot @@ -55,9 +63,11 @@ 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 +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.launch @@ -67,6 +77,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 @@ -85,12 +97,17 @@ 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 import to.bitkit.data.SettingsStore import to.bitkit.data.keychain.Keychain import to.bitkit.data.keychain.KeychainError +import to.bitkit.data.keychain.ProfileCredentialStore +import to.bitkit.data.keychain.ProfileCredentials +import to.bitkit.data.keychain.ProfileCredentialsChanged import to.bitkit.data.sharedpubky.SharedPubkyClient import to.bitkit.ext.runSuspendCatching import to.bitkit.ext.toHex @@ -103,8 +120,12 @@ import to.bitkit.repositories.MethodId import to.bitkit.repositories.PaykitPaymentRequestError import to.bitkit.repositories.PubkyContactError 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 import kotlin.test.assertContentEquals import kotlin.test.assertEquals @@ -119,6 +140,799 @@ 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") + val store = InMemoryDataStore(mutablePreferencesOf(secret to "original")) + val credentials = ProfileCredentialStore(store, { 0L }, { 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)) + } + val receipt = PubkyGrantLogoutReceipt(RING_PUBKY, "homeserver", "original-grant", "bitkit") + val native = mock { on { binding() }.thenReturn(receipt) } + val logout = PaykitProfileLogout(native, target) { true } + val sdk = mock() + whenever( + sdk.identityStatus() + ).thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + whenever(sdk.paymentRequests()).doSuspendableAnswer { + store.edit { it[secret] = "replacement" } + emptyList() + } + val service = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { sdk } + val snapshot = PaykitProfileDeletionSnapshot(RING_PUBKY, "original-profile", emptyList()) + + val failure = runSuspendCatching { + service.withProfileRemoval({ true }) { + withContext(logout) { service.deletePaykitProfile(snapshot) } + } + }.exceptionOrNull() + + assertTrue(generateSequence(failure) { it.cause }.any { it is ProfileCredentialsChanged }) + verify(sdk, never()).deletePaykitProfile(any()) + verify(keychain, never()).eraseProfileCredentials(any(), any()) + store.edit { it[secret] = "original" } + assertFalse(logout.isCurrent()) + service.withProfileRemoval({ true }) { + assertFailsWith { service.validateProfileLogout(logout) } + } + } + + @Test + fun `changed credentials during logout support probe prevent signed execution`() = runTest { + val secret = stringPreferencesKey("PUBKY_SECRET_KEY_0") + val store = InMemoryDataStore(mutablePreferencesOf(secret to "original")) + val credentials = ProfileCredentialStore(store, { 0L }, { 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)) + } + val receipt = PubkyGrantLogoutReceipt(RING_PUBKY, "homeserver", "original-grant", "bitkit") + val native = mock { on { binding() }.thenReturn(receipt) } + val attempt = mock() + whenever(native.prepareAttempt()).doSuspendableAnswer { + store.edit { it[secret] = "replacement" } + attempt + } + val logout = PaykitProfileLogout(native, target) { true } + val service = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { mock() } + + val failure = runSuspendCatching { + service.withProfileRemoval({ true }) { service.executeProfileLogout(logout) } + }.exceptionOrNull() + + assertTrue(generateSequence(failure) { it.cause }.any { it is ProfileCredentialsChanged }) + verify(attempt, never()).execute() + assertFalse(logout.reconcileAcknowledgement()) + store.edit { it[secret] = "original" } + assertFalse(logout.isCurrent()) + service.withProfileRemoval({ true }) { + assertFailsWith { service.executeProfileLogout(logout) } + } + verify(native, times(1)).prepareAttempt() + } + + @Test + fun `logout capture does not construct or restore a missing SDK`() = runTest { + val sdk = mock() + val keychain = mock() + val service = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { sdk } + service.withProfileRemoval({ true }) { + assertFailsWith { service.captureProfileLogout(RING_PUBKY) { true } } + } + verifyNoInteractions(sdk, keychain) + } + + @Test + fun `captured logout drains cancelled execution and retains its native acknowledgement`() = runTest { + val receipt = PubkyGrantLogoutReceipt(RING_PUBKY, "homeserver", "original-grant", "bitkit") + val native = mock { on { binding() }.thenReturn(receipt) } + val attempt = mock() + whenever(native.prepareAttempt()).thenReturn(attempt) + var acknowledged: PubkyGrantLogoutReceipt? = null + whenever(native.acknowledged()).thenAnswer { acknowledged } + val release = CompletableDeferred() + whenever(attempt.execute()).doSuspendableAnswer { + release.await() + acknowledged = receipt + receipt + } + val sdk = mock() + whenever(sdk.captureGrantLogout(RING_PUBKY)).thenReturn(native) + val keychain = mock() + whenever(keychain.captureProfileCredentials(any())).thenReturn(mock()) + val service = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { sdk } + service.fetchPubkyProfile(RING_PUBKY) + val logout = service.withProfileRemoval({ true }) { service.captureProfileLogout(RING_PUBKY) { true } } + val execution = launch { service.withProfileRemoval({ true }) { service.executeProfileLogout(logout) } } + runCurrent() + execution.cancel() + assertFalse(execution.isCompleted) + assertFalse(logout.reconcileAcknowledgement()) + release.complete(Unit) + execution.join() + assertTrue(logout.reconcileAcknowledgement()) + service.withProfileRemoval({ true }) { service.executeProfileLogout(logout) } + verify(attempt, times(1)).execute() + verify(native, times(1)).prepareAttempt() + verify(sdk, never()).signOut() + verify(keychain, never()).eraseProfileCredentials(any(), any()) + } + + @Test + fun `revoking during logout preparation prevents execution but permits explicit local cleanup`() = runTest { + val receipt = PubkyGrantLogoutReceipt(RING_PUBKY, "homeserver", "original-grant", "bitkit") + val native = mock { on { binding() }.thenReturn(receipt) } + val attempt = mock() + val release = CompletableDeferred() + whenever(native.prepareAttempt()).doSuspendableAnswer { + release.await() + attempt + } + val logout = PaykitProfileLogout(native, mock()) { true } + val keychain = mock() + val service = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { mock() } + val execution = async { + runSuspendCatching { service.withProfileRemoval({ true }) { service.executeProfileLogout(logout) } } + } + runCurrent() + logout.revoke() + release.complete(Unit) + assertIs(execution.await().exceptionOrNull()) + verify(attempt, never()).execute() + service.withProfileRemoval({ true }) { service.eraseProfileLogoutCredentials(logout, localOnly = true) } + verify(keychain).eraseProfileCredentialsAfterLocalConfirmation(org.mockito.kotlin.eq(logout.credentials), any()) + assertTrue(logout.credentialsErased.get()) + } + + @Test + fun `failed conditional erase preserves logout acknowledgement and cache until local retry commits`() = runTest { + val receipt = PubkyGrantLogoutReceipt(RING_PUBKY, "homeserver", "original-grant", "bitkit") + val native = mock { on { binding() }.thenReturn(receipt) } + val credentials = mock() + val keychain = mock() + val service = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { mock() } + val generation = service.runtimeGeneration + val logout = PaykitProfileLogout(native, credentials) { service.runtimeGeneration == generation } + logout.retainAcknowledgement(receipt) + val failure = IllegalStateException("Credential storage unavailable") + var fail = true + whenever(keychain.eraseProfileCredentials(org.mockito.kotlin.eq(credentials), any())).doAnswer { + it.getArgument<() -> Unit>(1).invoke() + if (fail) throw failure + Unit + } + service.withProfileRemoval({ true }) { + val actual = assertFailsWith { + service.eraseProfileLogoutCredentials(logout, localOnly = false) + } + assertTrue(generateSequence(actual) { it.cause }.any { it === failure }) + assertEquals(generation, service.runtimeGeneration) + assertTrue(logout.reconcileAcknowledgement()) + assertFalse(logout.credentialsErased.get()) + fail = false + service.eraseProfileLogoutCredentials(logout, localOnly = false) + assertTrue(logout.credentialsErased.get()) + assertEquals(generation + 1, service.runtimeGeneration) + service.eraseProfileLogoutCredentials(logout, localOnly = false) + } + verify(keychain, times(2)).eraseProfileCredentials(org.mockito.kotlin.eq(credentials), any()) + verify(native, never()).prepareAttempt() + } + + @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 `profile confirmation refuses subscriptions before reading profile or contacts`() = runTest { + val sdk = mock() + whenever(sdk.contactRecords()).thenReturn(emptyList()) + whenever(sdk.paymentRequests()).thenReturn(emptyList()) + whenever(sdk.identityStatus()) + .thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + val subscription = mock { + on { state } doReturn PaymentRequestLifecycleState.ACTIVE_RECURRING + } + whenever(sdk.paymentRequests()).thenReturn(listOf(subscription)) + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + + val refusal = assertFailsWith { + service.captureProfileDeletion(RING_PUBKY) { true } + } + assertNull(refusal.endsAtMillis) + verify(sdk, never()).fetchPaykitProfile(any()) + verify(sdk, never()).contactRecords() + verify(sdk, never()).removeContactsAndBlockPeers(any()) + } + + @Test + fun `confirmed profile rechecks subscriptions before cleanup and final deletion`() = runTest { + val sdk = mock() + whenever(sdk.contactRecords()).thenReturn(emptyList()) + whenever(sdk.paymentRequests()).thenReturn(emptyList()) + whenever(sdk.identityStatus()) + .thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + val snapshot = service.captureProfileDeletion(RING_PUBKY) { true } + val subscription = mock { + on { state } doReturn PaymentRequestLifecycleState.ACTIVE_RECURRING + } + whenever(sdk.paymentRequests()).thenReturn(listOf(subscription)) + + val validation = assertFailsWith { + service.validateProfileDeletion(snapshot) + } + val deletion = assertFailsWith { + service.deletePaykitProfile(snapshot) + } + assertNull(validation.endsAtMillis) + assertNull(deletion.endsAtMillis) + verify(sdk, never()).deletePaykitProfile(any()) + verify(sdk, never()).removeContactsAndBlockPeers(any()) + } + + @Test + fun `cancellation after confirmed profile deletion retains backup dirtiness`() = runTest { + val sdk = mock() + whenever(sdk.paymentRequests()).thenReturn(emptyList()) + 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 `pubky profile acknowledgement survives cancellation during native deletion`() = runTest { + val sdk = mock() + whenever(sdk.paymentRequests()).thenReturn(emptyList()) + whenever(sdk.identityStatus()).thenReturn( + IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE), + ) + val release = CompletableDeferred() + whenever(sdk.deletePubkyProfile("confirmed")).doSuspendableAnswer { release.await() } + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + var acknowledged = false + val removal = launch { + service.withProfileRemoval({ true }) { + service.deletePubkyProfile("confirmed", RING_PUBKY) { acknowledged = true } + } + } + runCurrent() + removal.cancel() + assertFalse(removal.isCompleted) + assertFalse(acknowledged) + release.complete(Unit) + removal.join() + assertTrue(acknowledged) + assertTrue(removal.isCancelled) + verify(sdk).deletePubkyProfile("confirmed") + verify(sdk, never()).fetchPubkyProfileWithRevision(any()) + } + + @Test + fun `profile deletion uses the confirmed revision without fetching a newer profile`() = runTest { + val sdk = mock() + whenever(sdk.paymentRequests()).thenReturn(emptyList()) + 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.paymentRequests()).thenReturn(emptyList()) + 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.paymentRequests()).thenReturn(emptyList()) + 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.paymentRequests()).thenReturn(emptyList()) + 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.paymentRequests()).thenReturn(emptyList()) + 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.paymentRequests()).thenReturn(emptyList()) + 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" @@ -440,53 +1254,6 @@ class PaykitSdkServiceTest { verify(sdk).importContacts(any(), any()) } - @Test - fun `a current endpoint publication is reusable while another write has not started`() = runTest { - mockConstruction(PaymentPayload::class.java).use { - val sdk = mock() - val report = EndpointSyncReport(emptyList(), emptyList(), emptyList()) - whenever(sdk.syncPublicEndpointsWithReceivingDetails(any())).thenReturn(report) - val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } - val endpoints = listOf(Endpoint(MethodId.P2tr, "bc1ptest", rawPayload = "bc1ptest")) - val published = checkNotNull(service.syncPublicEndpointsWithEpoch(endpoints, { true }, null)) - - assertNull(service.syncPublicEndpointsWithEpoch(endpoints, { false }, published)) - assertSame(published, service.syncPublicEndpointsWithEpoch(endpoints, { true }, published)) - verify(sdk).syncPublicEndpointsWithReceivingDetails(any()) - } - } - - @Test - fun `a direct public withdrawal invalidates overlapping refresh reuse even if it fails`() = runTest { - mockConstruction(PaymentPayload::class.java).use { - for (withdrawalFails in listOf(false, true)) { - val sdk = mock() - val report = EndpointSyncReport(emptyList(), emptyList(), emptyList()) - whenever(sdk.syncPublicEndpointsWithReceivingDetails(any())).doSuspendableAnswer { - if (withdrawalFails && it.getArgument>(0).isEmpty()) { - error("offline") - } - report - } - val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } - val endpoints = listOf(Endpoint(MethodId.P2tr, "bc1ptest", rawPayload = "bc1ptest")) - val published = checkNotNull(service.syncPublicEndpointsWithEpoch(endpoints, { true }, null)) - - if (withdrawalFails) { - assertFailsWith { service.syncPublicEndpoints(emptyList()) } - } else { - service.syncPublicEndpoints(emptyList()) - } - assertTrue(service.publicEndpointSyncEpoch() > published.epoch) - val repeated = checkNotNull(service.syncPublicEndpointsWithEpoch(endpoints, { true }, published)) - - assertTrue(repeated.epoch > published.epoch) - verify(sdk).syncPublicEndpointsWithReceivingDetails(emptyList()) - verify(sdk, times(3)).syncPublicEndpointsWithReceivingDetails(any()) - } - } - } - @Test fun `queued public publication cannot restore endpoints after cleanup ends admission`() = runTest { mockConstruction(PaymentPayload::class.java).use { @@ -1060,84 +1827,33 @@ class PaykitSdkServiceTest { whenever(sdk.publishPaykitApp(any(), any())).doSuspendableAnswer { entered.complete(Unit) release.await() - events += "registry completed" - mock() - } - whenever(sdk.contactRecords()).thenAnswer { - events += "next admitted" - emptyList() - } - val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } - var ownsWithdrawal = true - val withdrawal = async { service.syncPaykitApp(false, Priority.Interactive) { ownsWithdrawal } } - entered.await() - ownsWithdrawal = false - withdrawal.cancel() - val next = async { service.contactRecords() } - runCurrent() - assertFalse(next.isCompleted) - assertFalse(withdrawal.isCompleted) - release.complete(Unit) - - assertFailsWith { withdrawal.await() } - assertEquals(emptyList(), next.await()) - assertEquals(listOf("registry completed", "next admitted"), events) - verify(sdk).publishPaykitApp("Bitkit", PaykitAppCapabilities(false, true, true, true)) - } - - @Test - fun `profile and tag writes overtake queued registration and allowance reads`() = runTest { - val sdk = mock() - val release = CompletableDeferred() - val finishRegistration = CompletableDeferred() - val events = mutableListOf() - whenever(sdk.contactRecords()).doSuspendableAnswer { - release.await() - events += "active completed" - emptyList() - } - whenever(sdk.identityStatus()) - .thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) - whenever(sdk.publishPaykitApp(any(), any())).doSuspendableAnswer { - events += "registration" - finishRegistration.await() + events += "registry completed" mock() } - whenever(sdk.listAllowances(any())).thenAnswer { - events += "allowances" - emptyList() - } - whenever(sdk.publishPubkyProfile(any(), any())).thenAnswer { - events += "profile" - mock() - } - whenever(sdk.publishPaykitProfile(any(), isNull())).thenAnswer { - events += "tags" - mock() + whenever(sdk.contactRecords()).thenAnswer { + events += "next admitted" + emptyList() } - val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } - val active = async { service.contactRecords() } - runCurrent() - val registration = async { service.syncPaykitApp(true, Priority.Background) } - val allowances = async { service.listAllowances(AllowanceFilter(null, null, emptyList())) } - service.setPaymentSubmissionActive(true) - val setup = async { service.hasPrivatePaymentAccess() } - val save = async { - service.publishPubkyProfile(mock(), "revision", RING_PUBKY) - service.publishPaykitProfile(mock(), RING_PUBKY) + var ownsWithdrawal = true + val withdrawal = async { + service.syncPaykitApp(false, Priority.Interactive, { ownsWithdrawal }) { + events += "registry acknowledged" + } } + entered.await() + ownsWithdrawal = false + withdrawal.cancel() + val next = async { service.contactRecords() } runCurrent() - val beforeRelease = events.toList() + assertFalse(next.isCompleted) + assertFalse(withdrawal.isCompleted) release.complete(Unit) - runCurrent() - val duringRegistration = events.toList() - finishRegistration.complete(Unit) - awaitAll(active, registration, allowances, setup, save) - assertTrue(beforeRelease.isEmpty()) - assertEquals(listOf("active completed", "profile", "registration"), duringRegistration) - assertTrue(setup.await()) - assertEquals(listOf("active completed", "profile", "registration", "tags", "allowances"), events) + + assertFailsWith { withdrawal.await() } + assertEquals(emptyList(), next.await()) + assertEquals(listOf("registry completed", "registry acknowledged", "next admitted"), events) + verify(sdk).publishPaykitApp("Bitkit", PaykitAppCapabilities(false, true, true, true)) } @Test @@ -2196,6 +2912,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() @@ -2578,6 +3310,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()) @@ -2591,9 +3327,174 @@ 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 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 deletion rejects a subscription received after preflight`() = runTest { + for (pubkyApp in listOf(false, true)) { + 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 { + if (pubkyApp) { + service.deletePubkyProfile("original", RING_PUBKY) + } else { + service.deletePaykitProfile() + } + } + } + runCurrent() + finishCheck.complete(Unit) + preflight.await() + receive.await() + + assertIs(deletion.await().exceptionOrNull()) + verify(sdk, never()).deletePaykitProfile(any()) + verify(sdk, never()).deletePubkyProfile(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() + service.deletePubkyProfile("original", RING_PUBKY) + + verify(sdk).deletePaykitProfile("original") + verify(sdk).deletePubkyProfile("original") } } + @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 } + whenever(sdk.identityStatus()) + .thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + + assertSame(error, assertFailsWith { service.checkProfileDeletionAllowed() }) + assertSame(error, assertFailsWith { service.deletePaykitProfile() }) + assertSame( + error, + assertFailsWith { service.deletePubkyProfile("original", RING_PUBKY) } + ) + assertSame( + error, + assertFailsWith { + service.removeContactsForProfile(listOf(RING_PUBKY)) + } + ) + verify(sdk, never()).removeContactsAndBlockPeers(any()) + verify(sdk, never()).deletePaykitProfile(any()) + verify(sdk, never()).deletePubkyProfile(any()) + verify(sdk, never()).fetchPaykitProfile(any()) + } + @Test fun `unreadable profile cache stops activation`() = runTest { for (error in listOf( @@ -3431,6 +4332,9 @@ class PaykitSdkServiceTest { fun `obsolete contact withdrawal is rejected after queue and preflight waits`() = runTest { for (holdQueue in listOf(false, true)) { val sdk = mock() + whenever(sdk.syncPrivatePaymentListsWithReservationsAndProcessOutbound(any(), any())).thenReturn( + PrivatePaymentListDeliveryReport(emptyList(), emptyList(), emptyList(), emptyList(), emptyList()), + ) val started = CompletableDeferred() val resume = CompletableDeferred() whenever(sdk.contactRecords()).doSuspendableAnswer { @@ -3502,7 +4406,7 @@ class PaykitSdkServiceTest { } @Test - fun `disabled private capability does not queue withdrawal`() = runTest { + fun `disabled private capability still queues withdrawal`() = runTest { val sdk = mock() val capabilities = PaykitAppCapabilities(false, true, false, true) whenever(sdk.linkedPeers()).thenReturn(listOf(contactPeer(LinkedPeerState.LINKED))) @@ -3512,11 +4416,53 @@ class PaykitSdkServiceTest { whenever(sdk.paykitAppRegistry(RING_PUBKY)).thenReturn( PaykitAppRegistry(1u, null, listOf(PaykitApp("bitkit", "Bitkit", capabilities)), null, emptyMap()), ) + val report = PrivatePaymentListDeliveryReport( + queued = emptyList(), + cleared = listOf(PrivatePaymentListSyncChange(RING_PUBKY, 17uL, null)), + failedToQueue = emptyList(), + failedToDeliver = emptyList(), + acknowledged = listOf(PrivatePaymentListAcknowledgement(RING_PUBKY, 17uL)), + ) + val updates = listOf(PrivatePaymentListReservationUpdateInput(RING_PUBKY, emptyList())) val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + for (outcome in listOf(report.copy(acknowledged = emptyList()), report)) { + whenever(sdk.syncPrivatePaymentListsWithReservationsAndProcessOutbound(updates, false)).thenReturn(outcome) + assertSame(outcome, service.clearPrivatePaymentLists(listOf(RING_PUBKY))) + } - assertNull(service.clearPrivatePaymentLists(listOf(RING_PUBKY))) + verify(sdk, times(2)).syncPrivatePaymentListsWithReservationsAndProcessOutbound(updates, false) + verify(sdk, never()).paykitAppRegistry(any()) + verify(sdk, never()).publishPaykitApp(any(), any()) + } - verify(sdk, never()).syncPrivatePaymentListsWithReservationsAndProcessOutbound(any(), any()) + @Test + fun `profile removal withdraws disabled sharing through exact admitted owner`() = runTest { + val sdk = mock() + val capabilities = PaykitAppCapabilities(false, true, false, true) + whenever(sdk.linkedPeers()).thenReturn(listOf(contactPeer(LinkedPeerState.LINKED))) + whenever(sdk.identityStatus()).thenReturn( + IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE), + ) + whenever(sdk.paykitAppRegistry(RING_PUBKY)).thenReturn( + PaykitAppRegistry(1u, null, listOf(PaykitApp("bitkit", "Bitkit", capabilities)), null, emptyMap()), + ) + val report = PrivatePaymentListDeliveryReport( + queued = emptyList(), + cleared = listOf(PrivatePaymentListSyncChange(RING_PUBKY, 17uL, null)), + failedToQueue = emptyList(), + failedToDeliver = emptyList(), + acknowledged = listOf(PrivatePaymentListAcknowledgement(RING_PUBKY, 17uL)), + ) + val updates = listOf(PrivatePaymentListReservationUpdateInput(RING_PUBKY, emptyList())) + whenever(sdk.syncPrivatePaymentListsWithReservationsAndProcessOutbound(updates, false)).thenReturn(report) + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + var current = true + service.withProfileRemoval({ current }) { + assertSame(report, service.clearPrivatePaymentLists(listOf(RING_PUBKY))) + current = false + assertFailsWith { service.clearPrivatePaymentLists(listOf(RING_PUBKY)) } + } + verify(sdk, times(1)).syncPrivatePaymentListsWithReservationsAndProcessOutbound(updates, false) verify(sdk, never()).publishPaykitApp(any(), any()) } @@ -3547,8 +4493,8 @@ class PaykitSdkServiceTest { } verify(sdk, times(3)).linkedPeers() - verify(sdk, times(3)).identityStatus() - verify(sdk, times(3)).paykitAppRegistry(RING_PUBKY) + verify(sdk, never()).identityStatus() + verify(sdk, never()).paykitAppRegistry(any()) verify(sdk, times(3)).syncPrivatePaymentListsWithReservationsAndProcessOutbound(updates, false) verify(sdk, never()).clearPrivatePaymentListAndProcessOutbound(any()) } @@ -3792,6 +4738,108 @@ class PaykitSdkServiceTest { assertTrue(!provider.canDeferStaleSession("local Pubky secret key does not match session public key")) } + @Test + fun `a current endpoint publication is reusable while another write has not started`() = runTest { + mockConstruction(PaymentPayload::class.java).use { + val sdk = mock() + val report = EndpointSyncReport(emptyList(), emptyList(), emptyList()) + whenever(sdk.syncPublicEndpointsWithReceivingDetails(any())).thenReturn(report) + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + val endpoints = listOf(Endpoint(MethodId.P2tr, "bc1ptest", rawPayload = "bc1ptest")) + val published = checkNotNull(service.syncPublicEndpointsWithEpoch(endpoints, { true }, null)) + + assertNull(service.syncPublicEndpointsWithEpoch(endpoints, { false }, published)) + assertSame(published, service.syncPublicEndpointsWithEpoch(endpoints, { true }, published)) + verify(sdk).syncPublicEndpointsWithReceivingDetails(any()) + } + } + + @Test + fun `a direct public withdrawal invalidates overlapping refresh reuse even if it fails`() = runTest { + mockConstruction(PaymentPayload::class.java).use { + for (withdrawalFails in listOf(false, true)) { + val sdk = mock() + val report = EndpointSyncReport(emptyList(), emptyList(), emptyList()) + whenever(sdk.syncPublicEndpointsWithReceivingDetails(any())).doSuspendableAnswer { + if (withdrawalFails && it.getArgument>(0).isEmpty()) { + error("offline") + } + report + } + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + val endpoints = listOf(Endpoint(MethodId.P2tr, "bc1ptest", rawPayload = "bc1ptest")) + val published = checkNotNull(service.syncPublicEndpointsWithEpoch(endpoints, { true }, null)) + + if (withdrawalFails) { + assertFailsWith { service.syncPublicEndpoints(emptyList()) } + } else { + service.syncPublicEndpoints(emptyList()) + } + assertTrue(service.publicEndpointSyncEpoch() > published.epoch) + val repeated = checkNotNull(service.syncPublicEndpointsWithEpoch(endpoints, { true }, published)) + + assertTrue(repeated.epoch > published.epoch) + verify(sdk).syncPublicEndpointsWithReceivingDetails(emptyList()) + verify(sdk, times(3)).syncPublicEndpointsWithReceivingDetails(any()) + } + } + } + + @Test + fun `profile and tag writes overtake queued registration and allowance reads`() = runTest { + val sdk = mock() + val release = CompletableDeferred() + val finishRegistration = CompletableDeferred() + val events = mutableListOf() + whenever(sdk.contactRecords()).doSuspendableAnswer { + release.await() + events += "active completed" + emptyList() + } + whenever(sdk.identityStatus()) + .thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + whenever(sdk.publishPaykitApp(any(), any())).doSuspendableAnswer { + events += "registration" + finishRegistration.await() + mock() + } + whenever(sdk.listAllowances(any())).thenAnswer { + events += "allowances" + emptyList() + } + whenever(sdk.publishPubkyProfile(any(), any())).thenAnswer { + events += "profile" + mock() + } + whenever(sdk.publishPaykitProfile(any(), isNull())).thenAnswer { + events += "tags" + mock() + } + + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + val active = async { service.contactRecords() } + runCurrent() + val registration = async { service.syncPaykitApp(true, Priority.Background) } + val allowances = async { service.listAllowances(AllowanceFilter(null, null, emptyList())) } + service.setPaymentSubmissionActive(true) + val setup = async { service.hasPrivatePaymentAccess() } + val save = async { + service.publishPubkyProfile(mock(), "revision", RING_PUBKY) + service.publishPaykitProfile(mock(), RING_PUBKY) + } + runCurrent() + val beforeRelease = events.toList() + release.complete(Unit) + runCurrent() + val duringRegistration = events.toList() + finishRegistration.complete(Unit) + awaitAll(active, registration, allowances, setup, save) + assertTrue(beforeRelease.isEmpty()) + assertEquals(listOf("active completed", "profile", "registration"), duringRegistration) + assertTrue(setup.await()) + assertEquals(listOf("active completed", "profile", "registration", "tags", "allowances"), events) + } + @Test fun `session teardown attempts both credentials with session first`() { val attemptedKeys = mutableListOf() diff --git a/app/src/test/java/to/bitkit/services/ProfileLogoutSignerTest.kt b/app/src/test/java/to/bitkit/services/ProfileLogoutSignerTest.kt new file mode 100644 index 0000000000..2e8b04c388 --- /dev/null +++ b/app/src/test/java/to/bitkit/services/ProfileLogoutSignerTest.kt @@ -0,0 +1,97 @@ +package to.bitkit.services + +import com.synonym.paykit.PubkyGrantLogout +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 +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.whenever +import to.bitkit.data.keychain.Keychain +import to.bitkit.data.sharedpubky.SharedPubkyClient +import to.bitkit.data.sharedpubky.SharedPubkyContract +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class ProfileLogoutSignerTest { + private val owner = "3rsduhcxpw74snwyct86m38c63j3pq8x4ycqikxg64roik8yw5xg" + + @Test + fun `managed signer must match original owner and does not consult an unused Ring reference`() { + val keychain = mock() + val shared = mock() + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("managed") + var selectedOwner = "different" + val provider = PaykitSdkSessionProvider(keychain, shared, derivePublicKey = { selectedOwner }) + assertFailsWith { provider.captureOriginalSigner(owner) } + selectedOwner = owner + provider.captureOriginalSigner(owner).invoke() + verifyNoInteractions(shared) + } + + @Test + fun `adopted reference and selected key must both belong to original owner`() { + val keychain = mock() + val shared = mock() + var reference = "different" + whenever(keychain.loadString(Keychain.Key.SHARED_PUBKY_SOURCE.name)).thenAnswer { + SharedPubkyContract.RING_SOURCE_PREFIX + reference + } + val provider = PaykitSdkSessionProvider(keychain, shared, derivePublicKey = { "different" }) + assertFailsWith { provider.captureOriginalSigner(owner) } + verifyNoInteractions(shared) + reference = owner + assertFailsWith { provider.captureOriginalSigner(owner) } + whenever(shared.readCredential(owner)).thenReturn("invalid-owner-key") + assertFailsWith { provider.captureOriginalSigner(owner) } + } + + @Test + fun `adopted credential loss revokes remote authority permanently but permits owned local erase`() = runTest { + val keychain = mock() + val shared = mock() + whenever(keychain.loadString(Keychain.Key.SHARED_PUBKY_SOURCE.name)) + .thenReturn(SharedPubkyContract.RING_SOURCE_PREFIX + owner) + var credential: String? = "original-shared-key" + whenever(shared.readCredential(owner)).thenAnswer { credential } + val provider = PaykitSdkSessionProvider(keychain, shared, derivePublicKey = { owner }) + val receipt = PubkyGrantLogoutReceipt(owner, "homeserver", "original-grant", "bitkit") + val native = mock() + whenever(native.binding()).thenReturn(receipt) + val logout = PaykitProfileLogout(native, mock(), provider.captureOriginalSigner(owner)) { true } + val service = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { mock() } + service.withProfileRemoval({ true }) { service.validateProfileLogout(logout) } + credential = null + service.withProfileRemoval({ true }) { + assertFailsWith { service.validateProfileLogout(logout) } + } + credential = "original-shared-key" + assertFalse(logout.isCurrent()) + service.withProfileRemoval({ true }) { + assertFailsWith { service.executeProfileLogout(logout) } + } + logout.retainAcknowledgement(receipt) + service.withProfileRemoval({ true }) { service.eraseProfileLogoutCredentials(logout, localOnly = true) } + assertTrue(logout.reconcileAcknowledgement()) + assertTrue(logout.credentialsErased.get()) + verify(native, never()).prepareAttempt() + verify(shared, times(3)).readCredential(owner) + verify(keychain).eraseProfileCredentialsAfterLocalConfirmation(eq(logout.credentials), any()) + verify(keychain, never()).eraseProfileCredentials(any(), any()) + } + + @Test + fun `live delegate without a local root does not acquire one during validation`() { + val keychain = mock() + val shared = mock() + val provider = PaykitSdkSessionProvider(keychain, shared, derivePublicKey = { error("No root expected") }) + provider.captureOriginalSigner(owner).invoke() + verifyNoInteractions(shared) + } +} diff --git a/app/src/test/java/to/bitkit/services/PubkyServiceTest.kt b/app/src/test/java/to/bitkit/services/PubkyServiceTest.kt index a2dc689d09..1d3d2e9659 100644 --- a/app/src/test/java/to/bitkit/services/PubkyServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/PubkyServiceTest.kt @@ -1,6 +1,8 @@ package to.bitkit.services import com.synonym.paykit.EndpointSyncReport +import com.synonym.paykit.PubkyGrantLogout +import com.synonym.paykit.PubkyGrantLogoutReceipt import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.cancelAndJoin @@ -11,6 +13,7 @@ import kotlinx.coroutines.launch import org.junit.Test import org.mockito.Mockito.mockStatic import org.mockito.kotlin.KInvocationOnMock +import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.inOrder @@ -28,12 +31,36 @@ import kotlin.coroutines.Continuation import kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn import kotlin.test.assertEquals import kotlin.test.assertFailsWith +import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertTrue import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds class PubkyServiceTest : BaseUnitTest() { + @Test + fun `cancelled queue return revokes the captured logout before releasing original admission`() = test { + val binding = PubkyGrantLogoutReceipt("identity", "homeserver", "original", "bitkit") + val native = mock { on { binding() }.thenReturn(binding) } + val captured = PaykitProfileLogout(native, mock()) { true } + val paykit = mock() + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever { paykit.captureProfileLogout(any(), any()) }.doSuspendableAnswer { + entered.complete(Unit) + release.await() + captured + } + val sut = PubkyService(paykit) + val caller = launch { sut.captureProfileLogout("identity") { true } } + entered.await() + caller.cancel() + release.complete(Unit) + caller.join() + assertTrue(caller.isCancelled) + assertFalse(captured.isCurrent()) + } + @Test fun `paykit initialization does not hold the core queue`() = test { val paykit = mock() 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/app/src/test/java/to/bitkit/test/ReceiptResolverFixture.kt b/app/src/test/java/to/bitkit/test/ReceiptResolverFixture.kt new file mode 100644 index 0000000000..9346a8e167 --- /dev/null +++ b/app/src/test/java/to/bitkit/test/ReceiptResolverFixture.kt @@ -0,0 +1,32 @@ +package to.bitkit.test + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.flow.flowOf +import org.mockito.kotlin.mock +import to.bitkit.data.PrivatePaykitCacheData +import to.bitkit.data.PrivatePaykitCacheStore +import to.bitkit.data.ProfileRemovalStore +import to.bitkit.repositories.PaykitPaymentRequestRepo +import to.bitkit.repositories.PaykitReceivedPaymentContacts +import to.bitkit.repositories.PrivatePaykitAddressReservationRepo +import to.bitkit.repositories.PrivatePaykitContactResolver +import javax.inject.Provider + +fun receiptResolverFixture(dispatcher: CoroutineDispatcher): PrivatePaykitContactResolver { + val recovery = connectionRecoveryFixture(mock()) + val cache = mock { on { data }.thenReturn(flowOf(PrivatePaykitCacheData())) } + val reservations = mock { + on { receiptAssignments() }.thenReturn(PrivatePaykitAddressReservationRepo.ReceiptAssignments(emptyList(), 0)) + } + val requests = mock { + on { receivedPaymentContacts }.thenReturn(PaykitReceivedPaymentContacts.Empty) + } + return PrivatePaykitContactResolver( + dispatcher, + cache, + Provider { reservations }, + Provider { requests }, + ProfileRemovalStore.inMemoryForTesting(), + Provider { recovery }, + ) +} diff --git a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt index cc74c2d683..a1ea79e9f9 100644 --- a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt @@ -23,6 +23,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 @@ -30,15 +31,16 @@ 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.R 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 +import to.bitkit.models.BackupCategory import to.bitkit.models.BalanceState import to.bitkit.models.NodeLifecycleState import to.bitkit.repositories.BackupRepo @@ -94,12 +96,15 @@ class WalletViewModelTest : BaseUnitTest() { private val walletState = MutableStateFlow(WalletState()) private val balanceState = MutableStateFlow(BalanceState()) private val isRecoveryMode = MutableStateFlow(false) + private val isWiping = MutableStateFlow(false) private val isOnline = MutableStateFlow(ConnectivityState.CONNECTED) @Before fun setUp() = runBlocking { whenever(context.getString(any())).thenReturn("") whenever(walletRepo.walletState).thenReturn(walletState) + whenever(backupRepo.isWiping).thenReturn(isWiping) + whenever(walletRepo.checkWalletAvailable()).thenReturn(Result.success(Unit)) whenever(walletRepo.refreshReceiveState()).thenReturn(Result.success(Unit)) whenever(lightningRepo.lightningState).thenReturn(lightningState) whenever(lightningRepo.stop()).thenReturn(Result.success(Unit)) @@ -114,21 +119,235 @@ class WalletViewModelTest : BaseUnitTest() { whenever(settingsStore.data).thenReturn(flowOf(SettingsData())) 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, - connectionRecovery = connectionRecovery, - pubkySwapsRouteRepo = pubkySwapsRouteRepo, - sparkRepo = sparkRepo, - ) + 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, + connectionRecovery = connectionRecovery, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, + sparkRepo = sparkRepo, + ) + + @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) + assertTrue(recovering.isRNMigrationUnavailable.value) + verify(migrationService, never()).markMigrationChecked() + unreadable = false + whenever(migrationService.hasRNWalletData()).thenReturn(true) + recovering.refreshWalletResetRecovery() + 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 + 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 + fun `active wipe rejects a queued reset recovery action`() = test { + isWiping.value = true + sut.finishPendingWalletReset("original").join() + verify(walletRepo, never()).wipeWallet(any(), anyOrNull()) + assertFalse(sut.isFinishingWalletReset.value) + } + + @Test + fun `failed reset admission blocks restore preparation and replacement seed`() = test { + whenever(walletRepo.checkWalletAvailable()).thenReturn(Result.failure(AppError("reset pending"))) + sut.restoreWallet("replacement", null) + sut.createWallet(null) + verify(walletRepo, never()).restoreWallet(any(), anyOrNull()) + verify(walletRepo, never()).createWallet(anyOrNull()) + verify(backupRepo, never()).setRestorePending(true) + verify(lightningRepo, never()).setInitNodeLifecycleState() } @Test @@ -1002,11 +1221,48 @@ class WalletViewModelTest : BaseUnitTest() { } @Test - fun `post restore profile failure allows proceeding only while safety markers stay clear`() = test { - whenever( - backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull()) - ).thenReturn(Result.success(emptySet())) - whenever(pubkyRepo.initialize()).doSuspendableAnswer { throw AppError("profile cache unavailable") } + fun `completed wallet restore retains failed categories without waiting for optional identity activation`() = test { + val release = CompletableDeferred() + val failedCategories = setOf(BackupCategory.SETTINGS, BackupCategory.WIDGETS) + whenever(backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull())) + .thenReturn(Result.success(failedCategories)) + whenever(pubkyRepo.initialize()).doSuspendableAnswer { + release.await() + Result.success(Unit) + } + try { + sut.onBackupRestoreRetry() + runCurrent() + assertEquals(RestoreState.Completed(failedCategories), sut.restoreState.value) + verify(pubkyRepo).scheduleInitializationAfterRestore() + verify(pubkyRepo, never()).initialize() + verify(backupRepo).setRestorePending(false) + } finally { + release.complete(Unit) + } + } + + @Test + fun `most recent backup restore preserves failed categories while identity activates separately`() = test { + val failedCategories = setOf(BackupCategory.METADATA) + whenever(backupRepo.getLatestBackupTime()).thenReturn(1uL) + whenever(backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull())) + .thenReturn(Result.success(failedCategories)) + whenever(pubkyRepo.initialize()).doSuspendableAnswer { throw AppError("identity unavailable") } + + sut.restoreWallet("mnemonic", "passphrase") + walletState.value = walletState.value.copy(walletExists = true) + advanceUntilIdle() + + assertEquals(RestoreState.Completed(failedCategories), sut.restoreState.value) + verify(pubkyRepo).scheduleInitializationAfterRestore() + verify(pubkyRepo, never()).initialize() + } + + @Test + fun `proceed rechecks safety markers after an optional restore failure`() = test { + whenever(backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull())) + .thenReturn(Result.failure(AppError("metadata cache unavailable"))) sut.onBackupRestoreRetry() advanceUntilIdle() assertEquals(RestoreState.BackupFailed(1, hasPendingWalletRestore = false), sut.restoreState.value) @@ -1014,6 +1270,7 @@ class WalletViewModelTest : BaseUnitTest() { advanceUntilIdle() assertEquals(RestoreState.BackupFailed(2, hasPendingWalletRestore = false), sut.restoreState.value) assertEquals(null, sut.connectionStartupError.value) + verify(pubkyRepo, never()).scheduleInitializationAfterRestore() whenever(backupRepo.hasPendingWalletRestore()).thenReturn(true) var dismissed = false @@ -1196,7 +1453,7 @@ class WalletViewModelTest : BaseUnitTest() { walletState.value = walletState.value.copy(walletExists = true) advanceUntilIdle() - verifyBlocking(pubkyRepo) { initialize() } + verify(pubkyRepo).scheduleInitializationAfterRestore() } @Test @@ -1788,10 +2045,8 @@ class WalletViewModelTest : BaseUnitTest() { @Test fun `backup only retry with saved correction counts one retry`() = test { stubRecoveryRecord() - whenever( - backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull()) - ).thenReturn(Result.success(emptySet())) - whenever(pubkyRepo.initialize()).doSuspendableAnswer { throw AppError("profile cache unavailable") } + whenever(backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull())) + .thenReturn(Result.failure(AppError("restore completion unavailable"))) whenever(lightningRepo.restartNode(anyOrNull(), any())).thenReturn(Result.success(Unit)) lightningState.value = lightningState.value.copy(nodeLifecycleState = NodeLifecycleState.Running) sut.onBackupRestoreRetry() @@ -1954,12 +2209,10 @@ class WalletViewModelTest : BaseUnitTest() { } @Test - fun `optional profile failure cannot replay a completed correction over later settings`() = test { + fun `restore completion failure cannot replay a completed correction over later settings`() = test { val stored = stubRecoveryRecord() - whenever( - backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull()) - ).thenReturn(Result.success(emptySet())) - whenever(pubkyRepo.initialize()).doSuspendableAnswer { throw AppError("profile unavailable") } + whenever(backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull())) + .thenReturn(Result.failure(AppError("restore completion unavailable"))) whenever(lightningRepo.restartNode(anyOrNull(), any())).thenReturn(Result.success(Unit)) whenever( lightningRepo.start(any(), anyOrNull(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any()), @@ -1986,10 +2239,8 @@ class WalletViewModelTest : BaseUnitTest() { @Test fun `proceed retains an unapplied correction until explicit retry`() = test { stubRecoveryRecord() - whenever( - backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull()) - ).thenReturn(Result.success(emptySet())) - whenever(pubkyRepo.initialize()).doSuspendableAnswer { throw AppError("profile unavailable") } + whenever(backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull())) + .thenReturn(Result.failure(AppError("restore completion unavailable"))) lightningState.value = lightningState.value.copy(nodeLifecycleState = NodeLifecycleState.Running) repeat(2) { sut.onBackupRestoreRetry() 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 cca371bf28..844ec85b59 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 @@ -23,10 +23,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 @@ -34,16 +36,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 @@ -84,6 +91,7 @@ class ContactSaveSessionChangeTest : BaseUnitTest() { private var heldSave: CompletableDeferred? = null private var heldSaveSucceeds = true + private val removalStore = ProfileRemovalStore.inMemoryForTesting() private lateinit var repo: PubkyRepo @Before @@ -106,6 +114,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 @@ -128,6 +140,7 @@ class ContactSaveSessionChangeTest : BaseUnitTest() { settingsStore = settingsStore, httpClient = mock(), clock = clock, + profileRemovalStore = removalStore, ) } @@ -273,6 +286,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 c341830802..e364969c71 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 @@ -5,144 +5,452 @@ import androidx.lifecycle.viewModelScope import app.cash.turbine.test import com.synonym.paykit.PaykitException 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.anyOrNull +import org.mockito.kotlin.doAnswer 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.ext.toLocalizedTimestamp import to.bitkit.models.PubkyAppLinkError import to.bitkit.models.PubkyProfile import to.bitkit.models.PubkyProfileLink -import to.bitkit.repositories.PrivatePaykitRepo +import to.bitkit.models.Toast import to.bitkit.repositories.ProfileEditBase +import to.bitkit.repositories.PubkyContactError +import to.bitkit.repositories.PubkyProfileOwner import to.bitkit.repositories.PubkyRepo +import to.bitkit.repositories.PubkySignIn +import to.bitkit.services.PaykitProfileLogout import to.bitkit.test.BaseUnitTest +import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.utils.AppError +import java.util.Locale 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 `fixed term refusal preserves expiry and offers only fresh local confirmation`() = test { + val previousLocale = Locale.getDefault() + Locale.setDefault(Locale.US) + try { + val sut = createSut() + val endsAt = 1_800_000_000_000L + whenever(pubkyRepo.prepareProfileDeletion(fixture.original)) + .thenReturn(Result.failure(PubkyContactError.ActiveProfileSubscriptions(endsAt))) + advanceUntilIdle() + ToastEventBus.events.test { + sut.showDeleteConfirmation() + advanceUntilIdle() + awaitItem() + } + verify(context).getString(R.string.subscriptions__expires_date, endsAt.toLocalizedTimestamp()) + 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(), any()) + sut.showLocalDisconnectConfirmation() + advanceUntilIdle() + assertTrue(sut.uiState.value.showDeleteDialog) + assertTrue(sut.uiState.value.isLocalDisconnect) + assertNull(fixture.store.pendingAttempt()) + } finally { + Locale.setDefault(previousLocale) + } + } + + @Test + fun `active subscriptions refuse confirmation without starting cleanup`() = test { val sut = createSut() - val forget = CompletableDeferred>() - whenever(pubkyRepo.forgetUnrestoredIdentity()).doSuspendableAnswer { forget.await() } + whenever(pubkyRepo.prepareProfileDeletion(fixture.original)) + .thenReturn(Result.failure(PubkyContactError.ActiveSubscription)) advanceUntilIdle() + ToastEventBus.events.test { + sut.showDeleteConfirmation() + advanceUntilIdle() + assertEquals("End active subscriptions first", awaitItem().description) + } + 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(), any()) + } - sut.disconnectProfile() + @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() - assertTrue(sut.uiState.value.isDeleting) - assertFalse(sut.uiState.value.isSaving) - assertTrue(sut.uiState.value.isBusy) - - sut.disconnectProfile() + 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() - sut.save() + 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(), any()) + verify(pubkyRepo, never()).removeBitkitPaymentEndpointsForRemoval(any(), any(), any(), any()) + verify(pubkyRepo, never()).executeProfileLogout(any()) + verify(fixture.privateRepo, never()).removePublishedEndpointsForProfileRemoval(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() - verify(pubkyRepo, times(1)).forgetUnrestoredIdentity() - verify(pubkyRepo, never()).deleteProfileWithSessionRetry() - verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), anyOrNull(), any()) + 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() + } - sut.viewModelScope.cancel() - forget.complete(Result.success(true)) + @Test + fun `subscription beginning after confirmation prevents endpoint withdrawal and marker`() = test { + val sut = createSut() advanceUntilIdle() - - assertFalse(sut.uiState.value.isDeleting) - assertFalse(sut.uiState.value.isBusy) - verify(privatePaykitRepo).closeAndClear() - verify(pubkyRepo, never()).signOut() + sut.showDeleteConfirmation() + advanceUntilIdle() + doAnswer { throw PubkyContactError.ActiveSubscription } + .whenever(pubkyRepo).validateProfileDeletion(fixture.deletion) + ToastEventBus.events.test { + sut.deleteProfile() + advanceUntilIdle() + assertEquals("End active subscriptions first", awaitItem().description) + } + assertNull(fixture.store.pendingAttempt()) + assertFalse(sut.uiState.value.showDeleteFailureDialog) + assertTrue(sut.uiState.value.canDisconnectLocally) + verify(fixture.privateRepo, never()).removePublishedEndpointsForProfileRemoval(any()) + verify(pubkyRepo, never()).deleteProfile(any(), any()) } @Test - fun `disconnect forgets unrestored identity without remote cleanup`() = test { + fun `late subscription rejection retains durable removal and explicit review`() = test { val sut = createSut() - whenever(pubkyRepo.forgetUnrestoredIdentity()).thenReturn(Result.success(true)) - whenever(privatePaykitRepo.removePublishedEndpointsForCleanup(any())) - .thenReturn(Result.failure(AppError("No session"))) + whenever(pubkyRepo.deleteProfile(eq(fixture.deletion), any())) + .thenReturn(Result.failure(PubkyContactError.ActiveSubscription)) advanceUntilIdle() + sut.showDeleteConfirmation() + advanceUntilIdle() + sut.deleteProfile() + advanceUntilIdle() + assertNotNull(fixture.store.pendingAttempt()) + assertTrue(sut.uiState.value.showDeleteFailureDialog) + verify(pubkyRepo, never()).executeProfileLogout(any()) + sut.retryDeleteProfile() + advanceUntilIdle() + assertTrue(sut.uiState.value.showDeleteDialog) + verify(pubkyRepo, times(1)).deleteProfile(eq(fixture.deletion), any()) + } + @Test + fun `confirmation is required and consumed once`() = test { + val sut = createSut() + advanceUntilIdle() + sut.deleteProfile() + advanceUntilIdle() + verify(pubkyRepo, never()).deleteProfile(any(), any()) + sut.showDeleteConfirmation() + advanceUntilIdle() + assertTrue(sut.uiState.value.showDeleteDialog) sut.effects.test { - sut.disconnectProfile() + sut.deleteProfile() + sut.deleteProfile() advanceUntilIdle() - assertEquals(EditProfileEffect.DisconnectSuccess, awaitItem()) + 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(eq(fixture.deletion), any()) + assertNull(fixture.store.pendingAttempt()) + } - assertFalse(sut.uiState.value.isDeleting) - verify(privatePaykitRepo, never()).removePublishedEndpointsForCleanup(any()) - verify(pubkyRepo, never()).signOut() - verify(privatePaykitRepo).closeAndClear() + @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 `failed local disconnect preserves private state`() = test { + fun `uncertain deletion review reads state and requires fresh confirmation`() = test { val sut = createSut() - whenever(pubkyRepo.forgetUnrestoredIdentity()).thenReturn(Result.failure(AppError("Storage failed"))) + whenever( + pubkyRepo.deleteProfile(eq(fixture.deletion), any()) + ).thenReturn(Result.failure(TestAppError("lost response"))) advanceUntilIdle() + 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(eq(fixture.deletion), any()) + sut.dismissDeleteDialog() + assertTrue(sut.uiState.value.showDeleteFailureDialog) + sut.deleteProfile() + advanceUntilIdle() + verify(pubkyRepo, times(1)).deleteProfile(eq(fixture.deletion), any()) + } + + @Test + fun `failed review removes retired grant action and preserves local confirmation`() = test { + val sut = createSut() + whenever(pubkyRepo.deleteProfile(eq(fixture.deletion), any())) + .thenReturn(Result.failure(TestAppError("lost response"))) + advanceUntilIdle() + sut.showDeleteConfirmation() + advanceUntilIdle() + sut.deleteProfile() + advanceUntilIdle() + val attempt = assertNotNull(fixture.store.pendingAttempt()) + assertTrue(sut.uiState.value.canReviewRemoval) + + whenever(pubkyRepo.validateProfileLogout(any())).thenAnswer { + it.getArgument(0).revoke() + throw TestAppError("Original grant no longer active") + } + ToastEventBus.events.test { + sut.retryDeleteProfile() + advanceUntilIdle() + assertEquals(Toast.ToastType.ERROR, awaitItem().type) + expectNoEvents() + } + + assertFalse(sut.uiState.value.canReviewRemoval) + assertTrue(sut.uiState.value.showDeleteFailureDialog) + assertFalse(sut.uiState.value.showDeleteDialog) + assertEquals(attempt, fixture.store.pendingAttempt()) + verify(pubkyRepo, times(1)).deleteProfile(eq(fixture.deletion), any()) + verify(pubkyRepo, never()).executeProfileLogout(any()) + verify(pubkyRepo, never()).finishProfileRemovalLocally() sut.disconnectProfile() advanceUntilIdle() + assertTrue(sut.uiState.value.showDeleteDialog) + assertTrue(sut.uiState.value.isLocalDisconnect) + assertEquals(attempt, fixture.store.pendingAttempt()) + sut.dismissDeleteDialog() + sut.deleteProfile() + advanceUntilIdle() + verify(pubkyRepo, never()).finishProfileRemovalLocally() + assertEquals(attempt, fixture.store.pendingAttempt()) + } - assertFalse(sut.uiState.value.isDeleting) - verify(privatePaykitRepo, never()).closeAndClear() - verify(pubkyRepo, never()).signOut() + @Test + fun `failure disconnect asks again and never replays remote cleanup`() = test { + val sut = createSut() + whenever( + pubkyRepo.deleteProfile(eq(fixture.deletion), any()) + ).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() + ToastEventBus.events.test { + sut.effects.test { + sut.deleteProfile() + advanceUntilIdle() + assertIs(awaitItem()) + } + assertEquals("Pubky unlinked", expectMostRecentItem().title) + } + verify(pubkyRepo, times(1)).deleteProfile(eq(fixture.deletion), any()) + verify(pubkyRepo, never()).executeProfileLogout(any()) + verify(fixture.privateRepo, times(1)).removePublishedEndpointsForProfileRemoval(any()) + assertNull(fixture.store.pendingAttempt()) } @Test - fun `pending deletion blocks duplicate actions and clears progress on failure`() = test { + fun `failed private cleanup retains marker and stops profile deletion`() = test { val sut = createSut() + whenever(fixture.privateRepo.removePublishedEndpointsForProfileRemoval(any())) + .thenReturn(Result.failure(TestAppError("pending cleanup"))) advanceUntilIdle() - val result = CompletableDeferred>() - whenever(pubkyRepo.deleteProfileWithSessionRetry()).doSuspendableAnswer { result.await() } + sut.showDeleteConfirmation() + advanceUntilIdle() + sut.effects.test { + sut.deleteProfile() + advanceUntilIdle() + expectNoEvents() + } + assertTrue(sut.uiState.value.showDeleteFailureDialog) + assertNotNull(fixture.store.pendingAttempt()) + verify(pubkyRepo, never()).deleteProfile(any(), 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() + assertTrue(sut.uiState.value.isLocalDisconnect) + assertTrue(sut.uiState.value.showDeleteDialog) + } + @Test + fun `cancelled screen preserves pending removal without success`() = test { + val sut = createSut() + val cleanup = CompletableDeferred>() + whenever(fixture.privateRepo.removePublishedEndpointsForProfileRemoval(any())) + .doSuspendableAnswer { cleanup.await() } + advanceUntilIdle() 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(), anyOrNull(), any()) + sut.viewModelScope.cancel() + advanceUntilIdle() + assertFalse(sut.uiState.value.isBusy) + assertNotNull(fixture.store.pendingAttempt()) + verify(pubkyRepo, never()).deleteProfile(any(), 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(), 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(), 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)).deleteProfileWithSessionRetry() - verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), anyOrNull(), 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 @@ -167,8 +475,8 @@ class EditProfileViewModelTest : BaseUnitTest() { sut.showDeleteConfirmation() advanceUntilIdle() verify(pubkyRepo, times(1)).saveProfile(any(), any(), any(), any(), anyOrNull(), any()) - verify(pubkyRepo, never()).deleteProfileWithSessionRetry() - verify(pubkyRepo, never()).forgetUnrestoredIdentity() + verify(pubkyRepo, never()).deleteProfile(any(), any()) + verify(pubkyRepo, never()).prepareProfileDeletion(any()) assertFalse(sut.uiState.value.showDeleteDialog) result.complete(Result.failure(TestAppError("Offline"))) @@ -187,21 +495,6 @@ class EditProfileViewModelTest : BaseUnitTest() { assertEquals("https://updated.example.com", sut.uiState.value.links.first().url) } - @Test - fun `save does not send an existing link edited to a non-web value`() = test { - val sut = createSut() - advanceUntilIdle() - whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), anyOrNull(), any())) - .thenReturn(Result.success(Unit)) - - sut.onNameChange("Alice Renamed") - sut.updateLinkUrl(0, "me@example.com") - sut.save() - advanceUntilIdle() - - verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), anyOrNull(), any()) - } - @Test fun `stored links are not checked while they are unchanged`() = test { val sut = createSut(links = listOf(PubkyProfileLink("x".repeat(101), "https://example.com"))) @@ -339,64 +632,6 @@ class EditProfileViewModelTest : BaseUnitTest() { assertTrue(sut.uiState.value.linkErrors.isEmpty()) } - @Test - fun `deleteProfile should emit success when repository delete succeeds`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).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).deleteProfileWithSessionRetry() - verify(privatePaykitRepo).closeAndClear() - } - } - - @Test - fun `profile created in Bitkit keeps delete copy`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).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.deleteProfileWithSessionRetry()).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).deleteProfileWithSessionRetry() - verify(privatePaykitRepo).closeAndClear() - } - } - @Test fun `ring identity keeps loading until unlink copy is resolved`() = test { val ringCheck = CompletableDeferred() @@ -413,137 +648,100 @@ class EditProfileViewModelTest : BaseUnitTest() { } @Test - fun `retryDeleteProfile should emit success when repository delete succeeds`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn(Result.success(Unit)) - + fun `dismissed failure flow cannot reopen after a delayed review`() = test { val sut = createSut() + whenever( + pubkyRepo.deleteProfile(eq(fixture.deletion), any()) + ).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).deleteProfileWithSessionRetry() - verify(privatePaykitRepo).closeAndClear() - } - } - - @Test - fun `deleteProfile should show retry dialog when delete still fails`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).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.deleteProfileWithSessionRetry()).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(eq(fixture.deletion), any()) } @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(eq(fixture.deletion), any())) + .thenReturn(Result.failure(TestAppError("Unknown response"))) + advanceUntilIdle() + sut.showDeleteConfirmation() + advanceUntilIdle() + sut.deleteProfile() advanceUntilIdle() - sut.disconnectProfile() advanceUntilIdle() - - assertFalse(sut.uiState.value.isDeleting) - verify(pubkyRepo, never()).signOut() - 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(eq(fixture.deletion), any()) } @Test - fun `disconnectProfile preserves local Paykit state when Pubky sign out fails`() = test { + fun `save does not send an existing link edited to a non-web value`() = test { val sut = createSut() - whenever(pubkyRepo.signOut()).thenReturn(Result.failure(TestAppError("sign out failed"))) advanceUntilIdle() + whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), anyOrNull(), any())) + .thenReturn(Result.success(Unit)) - sut.disconnectProfile() + sut.onNameChange("Alice Renamed") + sut.updateLinkUrl(0, "me@example.com") + sut.save() advanceUntilIdle() - assertFalse(sut.uiState.value.isDeleting) - verify(privatePaykitRepo, never()).closeAndClear() + verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), anyOrNull(), any()) } @Test - fun `deleteProfile should continue when private cleanup fails`() = test { + fun `cancelled local completion retains its owner through a later admission failure`() = test { val sut = createSut() - whenever { privatePaykitRepo.removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) } - .thenReturn(Result.failure(TestAppError("cleanup failed"))) - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn(Result.success(Unit)) + org.mockito.kotlin.doAnswer { + fixture.current = fixture.ended + throw CancellationException("Cancelled after acknowledged credential removal") + }.whenever(pubkyRepo).finishProfileRemovalLocally() + advanceUntilIdle() + sut.showDeleteConfirmation() 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).deleteProfileWithSessionRetry() - verify(privatePaykitRepo).closeAndClear() + 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()) } - } - - @Test - fun `dismissDeleteFailureDialog should hide retry dialog`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn( - Result.failure(TestAppError("expired session")), - ) - - val sut = createSut() - advanceUntilIdle() - sut.deleteProfile() - advanceUntilIdle() - - sut.dismissDeleteFailureDialog() - - assertFalse(sut.uiState.value.showDeleteFailureDialog) + verify(pubkyRepo, times(1)).executeProfileLogout(any()) } private fun createSut( @@ -552,25 +750,24 @@ class EditProfileViewModelTest : BaseUnitTest() { links: List = listOf(PubkyProfileLink("Website", "https://example.com")), ): EditProfileViewModel { whenever(context.getString(any())).thenReturn("") + whenever(context.getString(R.string.profile__delete_success)).thenReturn("Profile deleted") + whenever(context.getString(R.string.profile__delete_active_subscription)) + .thenReturn("End active subscriptions first") + whenever(context.getString(R.string.profile__unlink_success)).thenReturn("Pubky unlinked") if (ringCheck != null) { whenever { pubkyRepo.isRingAdoptedIdentity() }.doSuspendableAnswer { ringCheck.await() } } else { whenever { pubkyRepo.isRingAdoptedIdentity() }.thenReturn(isRingIdentity) } - whenever { pubkyRepo.forgetUnrestoredIdentity() }.thenReturn(Result.success(false)) + fixture.setup() whenever(pubkyRepo.profile).thenReturn(MutableStateFlow(createProfile(links))) whenever(pubkyRepo.profileEditBase()).thenReturn(ProfileEditBase(createProfile(links), "revision")) 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..1c2853fd43 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileRemovalUiFixture.kt @@ -0,0 +1,89 @@ +package to.bitkit.ui.screens.profile + +import com.synonym.paykit.PubkyGrantLogout +import com.synonym.paykit.PubkyGrantLogoutReceipt +import org.mockito.kotlin.any +import org.mockito.kotlin.doSuspendableAnswer +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.services.PaykitProfileLogout +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()), + false, + null + ) + 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)) + val binding = PubkyGrantLogoutReceipt("pubkyalice", "homeserver", "original-grant", "bitkit") + whenever { pubky.captureProfileLogout(original) }.doSuspendableAnswer { + val native = mock { on { binding() }.thenReturn(binding) } + Result.success(PaykitProfileLogout(native, mock()) { current == original }) + } + whenever { pubky.executeProfileLogout(any()) }.thenAnswer { + it.getArgument(0).retainAcknowledgement(binding) + } + 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.removePublishedEndpointsForProfileRemoval(any()) }.thenAnswer { + it.getArgument<() -> Unit>(0).invoke() + Result.success(Unit) + } + whenever { pubky.removeBitkitPaymentEndpointsForRemoval(any(), any(), any(), any()) }.thenAnswer { + it.getArgument<() -> Unit>(2).invoke() + it.getArgument<() -> Unit>(3).invoke() + Result.success(Unit) + } + whenever { pubky.deleteProfile(any(), any()) }.thenAnswer { + it.getArgument<() -> Unit>(1).invoke() + Result.success(Unit) + } + whenever { pubky.finishProfileRemovalLocally() }.thenAnswer { current = ended } + whenever { pubky.finishProfileRemovalLocally(any(), any()) }.doSuspendableAnswer { + pubky.finishProfileRemovalLocally() + } + 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 bed0ba19f2..fd3220222c 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,14 +21,17 @@ 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.ProfileEditBase +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 @@ -38,7 +40,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 { @@ -247,57 +249,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() @@ -349,52 +300,6 @@ class ProfileViewModelTest : BaseUnitTest() { verify(pubkyRepo, never()).saveProfile(any(), 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 profile = createProfile() @@ -523,8 +428,243 @@ 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()).executeProfileLogout(any()) + } + + @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()).executeProfileLogout(any()) + verify(fixture.privateRepo, never()).removePublishedEndpointsForProfileRemoval(any()) + 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()).executeProfileLogout(any()) + cancelAndIgnoreRemainingEvents() + } + } + + @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()).executeProfileLogout(any()) + 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)).executeProfileLogout(any()) + } + + @Test + fun `uncertain sign out offers local confirmation without replaying revocation`() = test { + val sut = createSut(createProfile()) + whenever(pubkyRepo.executeProfileLogout(any())).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)).executeProfileLogout(any()) + verify(fixture.privateRepo, times(1)).removePublishedEndpointsForProfileRemoval(any()) + } + + @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()).executeProfileLogout(any()) + 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()).executeProfileLogout(any()) + 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()).executeProfileLogout(any()) + 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)).executeProfileLogout(any()) + } + 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", @@ -538,7 +678,9 @@ 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.profileRecoveryCanDisconnect).thenReturn(recoveryCanDisconnect) whenever(pubkyRepo.profile).thenReturn(profileFlow) whenever(pubkyRepo.profileEditBase()).thenAnswer { ProfileEditBase(profileFlow.value, "revision") } whenever(pubkyRepo.readOnlyProfile).thenReturn(readOnlyProfileFlow) @@ -549,16 +691,12 @@ class ProfileViewModelTest : BaseUnitTest() { whenever(pubkyRepo.restorationNeedsUpdate).thenReturn(restorationNeedsUpdate) 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(), 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/ui/screens/recovery/RecoveryPhraseSessionTest.kt b/app/src/test/java/to/bitkit/ui/screens/recovery/RecoveryPhraseSessionTest.kt new file mode 100644 index 0000000000..2e6ceedf76 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/recovery/RecoveryPhraseSessionTest.kt @@ -0,0 +1,47 @@ +package to.bitkit.ui.screens.recovery + +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs + +class RecoveryPhraseSessionTest { + @Test + fun `a fresh auth response is one use and never survives revoke`() { + val session = RecoveryPhraseSession() + session.begin(true) + val first = assertIs(session.phase) + session.authorize(first, admitted = false) + assertEquals(first, session.phase) + session.authorize(first, admitted = true) + assertEquals(RecoveryPhrasePhase.Phrase, session.phase) + session.revoke() + session.authorize(first, admitted = true) + assertEquals(RecoveryPhrasePhase.Overview, session.phase) + session.begin(true) + val second = assertIs(session.phase) + session.authorize(first, admitted = true) + assertEquals(second, session.phase) + session.authorize(second, admitted = true) + assertEquals(RecoveryPhrasePhase.Phrase, session.phase) + } + + @Test + fun `disposing recovery rejects callbacks and new requests`() { + val session = RecoveryPhraseSession() + session.begin(true) + val attempt = assertIs(session.phase) + session.close() + session.authorize(attempt, admitted = true) + session.begin(false) + assertEquals(RecoveryPhrasePhase.Overview, session.phase) + } + + @Test + fun `explicit request with pin disabled is also revoked`() { + val session = RecoveryPhraseSession() + session.begin(false) + assertEquals(RecoveryPhrasePhase.Phrase, session.phase) + session.revoke() + assertEquals(RecoveryPhrasePhase.Overview, session.phase) + } +} 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/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt index 4e63b72c58..82337dc75c 100644 --- a/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt @@ -89,6 +89,8 @@ class DeriveBalanceStateUseCaseTest : BaseUnitTest() { // Spark keeps 0.25% of a send as its fee, so the most it can send leaves room for it. assertEquals(29_925uL, balanceState.maxSendLightningSats) assertEquals(20_000uL, balanceState.balanceInTransferToSpending) + assertEquals(30_000uL, balanceState.sparkBalanceSats) + assertEquals(20_000uL, balanceState.sparkPendingDepositSats) } @Test @@ -116,6 +118,8 @@ class DeriveBalanceStateUseCaseTest : BaseUnitTest() { assertEquals(105_000uL, balanceState.balanceInTransferToSavings) // Lightning's 50,000 plus the 30,000 Spark holds beyond the exit's leaves. assertEquals(80_000uL, balanceState.totalLightningSats) + assertEquals(null, balanceState.sparkBalanceSats) + assertEquals(null, balanceState.sparkPendingDepositSats) } @Test @@ -135,6 +139,8 @@ class DeriveBalanceStateUseCaseTest : BaseUnitTest() { val balanceState = sut().getOrThrow() assertEquals(64_167uL, balanceState.totalLightningSats) + assertEquals(null, balanceState.sparkBalanceSats) + assertEquals(null, balanceState.sparkPendingDepositSats) } @Test 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..509e978f39 --- /dev/null +++ b/app/src/test/java/to/bitkit/usecases/ProfileRemovalCoordinatorTest.kt @@ -0,0 +1,990 @@ +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 +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 +import kotlinx.coroutines.flow.flow +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.data.ReceiptAssociationsUnavailable +import to.bitkit.data.keychain.ProfileCredentialStore +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.services.PaykitProfileLogout +import to.bitkit.test.BaseUnitTest +import to.bitkit.test.InMemoryDataStore +import java.io.IOException +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()), + false, + null + ) + private val sut by lazy { ProfileRemovalCoordinator(pubky, privateRepo, sharing, store) } + 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() + val changed = IOException("Original credential snapshot changed") + whenever { pubky.validateProfileLogout(logouts.single()) }.doSuspendableAnswer { throw changed } + + assertTrue(sut.remove(confirmation).isFailure) + + verify(pubky, never()).validateProfileDeletion(any()) + verify(privateRepo, never()).removePublishedEndpointsForProfileRemoval(any()) + verify(pubky, never()).removeBitkitPaymentEndpointsForRemoval(any(), any(), any(), any()) + verify(pubky, never()).executeProfileLogout(any()) + verify(pubky, never()).finishProfileRemovalLocally(any(), any()) + assertNull(store.pendingAttempt()) + assertSame(original, current) + } + + @Test + fun `an active logout cannot offer or mint retry confirmation until its unknown outcome has drained`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever { pubky.executeProfileLogout(any()) }.doSuspendableAnswer { + entered.complete(Unit) + release.await() + throw IOException("response lost") + } + val first = sut.prepareDeletion(original).getOrThrow() + val removal = async { sut.remove(first) } + entered.await() + assertFalse(sut.canRetry(original)) + assertNull(sut.retryOwner.value) + assertTrue(sut.prepareRemoteRetry(original).isFailure) + assertSame(first, first.intent?.confirmation?.get()) + release.complete(Unit) + assertIs(removal.await().exceptionOrNull()) + assertTrue(sut.canRetry(original)) + assertTrue(sut.prepareRemoteRetry(original).isSuccess) + verify(pubky, times(1)).executeProfileLogout(logouts.single()) + } + + @Test + fun `fresh confirmation retries original grant without replaying acknowledged cleanup`() = test { + var executions = 0 + whenever { pubky.executeProfileLogout(any()) }.doSuspendableAnswer { + executions++ + if (executions == 1) throw IOException("logout response lost") + it.getArgument(0).retainAcknowledgement(binding) + } + val first = sut.prepareDeletion(original).getOrThrow() + val failure = assertIs(sut.remove(first).exceptionOrNull()) + assertTrue(sut.canRetry(original)) + assertSame(original, sut.retryOwner.value) + assertEquals(first.attemptId, store.pendingAttempt()) + verify(pubky, never()).finishProfileRemovalLocally(any(), any()) + + val second = sut.prepareRemoteRetry(original).getOrThrow() + assertFalse(second.used.get()) + assertEquals(first.attemptId, second.attemptId) + assertEquals(1, executions) + assertSame(ended, sut.remove(second).getOrThrow()) + assertEquals(2, executions) + verify(pubky, times(1)).captureProfileLogout(original) + verify(pubky, times(1)).prepareProfileDeletion(original) + verify(pubky, times(1)).deleteProfile(eq(deletion), any()) + verify(privateRepo, times(1)).removePublishedEndpointsForProfileRemoval(any()) + verify(pubky, times(1)).removeBitkitPaymentEndpointsForRemoval(any(), any(), any(), any()) + verify(pubky, times(2)).executeProfileLogout(logouts.single()) + assertNull(store.pendingAttempt()) + assertFalse(sut.canRetry(original)) + 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 { + it.getArgument(0).retainAcknowledgement(binding) + throw kotlinx.coroutines.CancellationException("caller left after acknowledgement") + } + val confirmation = sut.prepareDeletion(original).getOrThrow() + assertIs( + runCatching { sut.remove(confirmation) }.exceptionOrNull(), + ) + val failure = assertNotNull(sut.failureFor(confirmation)) + assertFalse(sut.canRetry(original)) + assertFalse(failure.canReview) + assertTrue(sut.prepareRemoteRetry(original).isFailure) + assertTrue(sut.reviewAgain(failure).isFailure) + assertNotNull(store.pendingAttempt()) + assertTrue(sut.remove(sut.prepareLocalDisconnect(failure).getOrThrow()).isSuccess) + verify(pubky, times(1)).executeProfileLogout(logouts.single()) + assertNull(store.pendingAttempt()) + } + + @Test + fun `restart and revoked same-owner handle cannot recreate remote logout from pending UUID`() = test { + whenever { pubky.executeProfileLogout(any()) }.doSuspendableAnswer { throw IOException("offline") } + val confirmation = sut.prepareDeletion(original).getOrThrow() + assertTrue(sut.remove(confirmation).isFailure) + 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) + assertFalse(restarted.canRetry(original)) + assertTrue(restarted.prepareRemoteRetry(original).isFailure) + val local = restarted.prepareSignOut(original).getOrThrow() + assertTrue(local.localOnly) + assertTrue(restarted.remove(local).isSuccess) + verify(pubky, times(1)).captureProfileLogout(original) + verify(pubky, times(1)).executeProfileLogout(logouts.single()) + } + + @Test + fun `discarding an unused confirmation revokes capture without starting durable removal`() = test { + val first = sut.prepareDeletion(original).getOrThrow() + val firstLogout = logouts.single() + sut.discard(first) + assertFalse(firstLogout.isCurrent()) + assertNull(store.pendingAttempt()) + assertTrue(events.isEmpty()) + assertTrue(sut.prepareDeletion(original).isSuccess) + assertEquals(2, logouts.size) + assertTrue(logouts.last().isCurrent()) + } + + @Test + fun `failed local metadata teardown closes receipt admission before any observer can clear requests`() = test { + var receiptBlocked = false + doSuspendableAnswer { + current = ended + receiptBlocked = runCatching { store.withReceiptSnapshot { "partial maps" } } + .exceptionOrNull() is ReceiptAssociationsUnavailable + throw IOException("metadata unavailable after identity ended") + }.whenever(pubky).finishProfileRemovalLocally() + val confirmation = sut.prepareDeletion(original).getOrThrow() + assertTrue(sut.remove(confirmation).isFailure) + assertTrue(receiptBlocked) + assertNotNull(store.pendingAttempt()) + verify(privateRepo, never()).finishProfileRemoval(any()) + } + + @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 { pubky.captureProfileLogout(original) }.doSuspendableAnswer { + val native = mock { on { binding() } doReturn binding } + Result.success(PaykitProfileLogout(native, mock()) { current === original }.also(logouts::add)) + } + 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.removePublishedEndpointsForProfileRemoval(any()) }.doSuspendableAnswer { + assertNotNull(store.pendingAttempt()) + events += "private endpoints" + it.getArgument<() -> Unit>(0).invoke() + Result.success(Unit) + } + whenever { pubky.removeBitkitPaymentEndpointsForRemoval(any(), any(), any(), any()) }.thenAnswer { + events += "public endpoints" + it.getArgument<() -> Unit>(2).invoke() + it.getArgument<() -> Unit>(3).invoke() + Result.success(Unit) + } + whenever { pubky.deleteProfile(any(), any()) }.thenAnswer { + events += "profile" + it.getArgument<() -> Unit>(1).invoke() + Result.success(Unit) + } + whenever { pubky.executeProfileLogout(any()) }.thenAnswer { + events += "revoke" + it.getArgument(0).retainAcknowledgement(binding) + Unit + } + whenever { pubky.finishProfileRemovalLocally() }.doSuspendableAnswer { + assertNotNull(store.pendingAttempt()) + events += "local credentials and metadata" + current = ended + } + whenever { pubky.finishProfileRemovalLocally(any(), any()) }.doSuspendableAnswer { + pubky.finishProfileRemovalLocally() + } + 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" + Result.success(Unit) + } + } + + @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(any()) + val confirmation = sut.prepareDeletion(original).getOrThrow() + + val result = assertIs(sut.remove(confirmation).exceptionOrNull()) + + assertTrue(generateSequence(result.cause) { it.cause }.any { it === failure }) + assertFalse(result.canReview) + assertTrue(sut.reviewAgain(result).isFailure) + verify(pubky, times(1)).prepareProfileDeletion(original) + verify(privateRepo, times(1)).removePublishedEndpointsForProfileRemoval(any()) + assertEquals(confirmation.attemptId, store.pendingAttempt()) + verify(pubky, never()).removeBitkitPaymentEndpointsForRemoval(any(), any(), any(), any()) + verify(pubky, never()).deleteProfile(any(), any()) + verify(pubky, never()).executeProfileLogout(any()) + 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() + 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()).removePublishedEndpointsForProfileRemoval(any()) + verify(pubky, never()).removeBitkitPaymentEndpointsForRemoval(any(), any(), any(), any()) + verify(pubky, never()).deleteProfile(any(), any()) + verify(pubky, never()).executeProfileLogout(any()) + 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()).executeProfileLogout(any()) + } + + @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(), any()) + verify(pubky, never()).executeProfileLogout(any()) + } + + @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 { + val next = transform(data.value) + if (next == data.value) return next + writes++ + throw failure + } + }) + val confirmation = sut.prepareLocalDisconnect(original).getOrThrow() + assertEquals(failure.message, assertIs(sut.remove(confirmation).exceptionOrNull()).message) + assertNull(sut.failureFor(confirmation)) + assertEquals(1, writes) + assertNull(store.pendingAttempt()) + assertTrue(events.isEmpty()) + verify(pubky, never()).finishProfileRemovalLocally() + verify(privateRepo, never()).finishProfileRemoval(any()) + verify(privateRepo, never()).removePublishedEndpointsForProfileRemoval(any()) + verify(pubky, never()).removeBitkitPaymentEndpointsForRemoval(any(), any(), any(), any()) + verify(pubky, never()).deleteProfile(any(), any()) + verify(pubky, never()).executeProfileLogout(any()) + 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() + assertNull(store.pendingAttempt()) + assertSame(ended, sut.remove(confirmation).getOrThrow()) + assertEquals( + listOf( + "validate", + "private endpoints", + "public endpoints", + "profile", + "revoke", + "local credentials and metadata", + "private local", + "wallet backup ready", + "backup ready" + ), + events + ) + assertNull(store.pendingAttempt()) + assertFalse(sut.isCurrent(original)) + 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(eq(deletion), any()) + ).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(eq(deletion), any()) + verify(pubky, never()).executeProfileLogout(any()) + 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(eq(deletion), any()) + ).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(eq(deletion), any()) + current = PubkyProfileOwner(PubkySignIn("replacement", 3), 3) + assertTrue(sut.reviewAgain(failure).isFailure) + 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(eq(deletion), any())).thenAnswer { + it.getArgument<() -> Unit>(1).invoke() + Result.success(Unit) + } + + assertSame(ended, sut.remove(third).getOrThrow()) + assertEquals(second.attemptId, third.attemptId) + verify(privateRepo, times(1)).removePublishedEndpointsForProfileRemoval(any()) + verify(pubky, times(3)).prepareProfileDeletion(original) + verify(pubky, times(3)).deleteProfile(eq(deletion), any()) + verify(pubky, times(1)).executeProfileLogout(any()) + assertNull(store.pendingAttempt()) + } + + @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(eq(deletion), any()) + } + + @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(eq(first), any()) + } + + @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(eq(first), any()) + whenever( + pubky.deleteProfile(eq(residual), any()) + ).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(eq(residual), any()) + } + + @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(eq(absent), any())).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 `review cannot reintroduce a pubky profile after observing its absence`() = test { + val first = PubkyProfileDeletion(original, 1, deletion.snapshot, true, "pubky-original") + val failure = failRemoval(first) + val absent = PubkyProfileDeletion(original, 1, deletion.snapshot, true, null) + whenever(pubky.prepareProfileDeletion(original)).thenReturn(Result.success(absent)) + val reviewed = sut.reviewAgain(failure).getOrThrow() + assertSame(absent, reviewed.deletion) + whenever(pubky.prepareProfileDeletion(original)).thenReturn(Result.success(first)) + assertTrue(sut.reviewAgain(failure).isFailure) + verify(pubky, times(1)).deleteProfile(eq(first), any()) + verify(pubky, never()).deleteProfile(eq(absent), any()) + } + + @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(eq(first), any()) + verify(pubky, never()).deleteProfile(eq(remaining), any()) + } + + @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(eq(deletion), any()) + } + + @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(eq(first), any()) + } + + @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(eq(deletion), any()) + } + + private fun PubkyProfileDeletion.withSnapshot(snapshot: PaykitProfileDeletionSnapshot) = + PubkyProfileDeletion(owner, profileWriteRevision, snapshot, deletePubkyProfile, pubkyProfileRevision) + + private suspend fun failRemoval(snapshot: PubkyProfileDeletion): ProfileRemovalFailure { + whenever(pubky.prepareProfileDeletion(original)).thenReturn(Result.success(snapshot)) + whenever( + pubky.deleteProfile(eq(snapshot), any()) + ).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 `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") } + val confirmation = sut.prepareDeletion(original).getOrThrow() + assertTrue(sut.remove(confirmation).isFailure) + assertNull(store.pendingAttempt()) + verify(privateRepo, never()).removePublishedEndpointsForProfileRemoval(any()) + } + + @Test + fun `changed confirmation before any cleanup permits a fresh deletion without uncertainty`() = test { + whenever { pubky.validateProfileDeletion(deletion) }.thenAnswer { error("profile changed") } + 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(), any()) + verify(privateRepo, never()).removePublishedEndpointsForProfileRemoval(any()) + assertTrue(sut.prepareDeletion(original).isSuccess) + } + + @Test + fun `public cleanup failure retains marker and never revokes or clears private state`() = test { + whenever( + pubky.removeBitkitPaymentEndpointsForRemoval(any(), any(), any(), any()) + ).thenReturn(Result.failure(IllegalStateException("unknown"))) + 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()) + } + + @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(eq(deletion), any()) + verify(pubky, times(1)).executeProfileLogout(any()) + } + + @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()).executeProfileLogout(any()) + verify(pubky, never()).removeBitkitPaymentEndpointsForRemoval(any(), any(), any(), any()) + verify(privateRepo, never()).removePublishedEndpointsForProfileRemoval(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) + 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(eq(deletion), any()) + verify(pubky, times(1)).executeProfileLogout(any()) + } + + @Test + fun `cancellation during destructive work leaves obligation and does not clear watermarks`() = test { + val entered = CompletableDeferred() + val wait = CompletableDeferred() + whenever { pubky.deleteProfile(eq(deletion), any()) }.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 9f6c9c61d3..d5c5a473e7 100644 --- a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt @@ -1,31 +1,67 @@ package to.bitkit.usecases +import androidx.datastore.core.DataStoreFactory +import androidx.datastore.core.Serializer import com.google.firebase.messaging.FirebaseMessaging +import com.synonym.bitkitcore.AddressType import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +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.Rule import org.junit.Test +import org.junit.rules.TemporaryFolder import org.mockito.kotlin.any +import org.mockito.kotlin.clearInvocations +import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify 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.ProfileRemovalPending +import to.bitkit.data.ProfileRemovalScope +import to.bitkit.data.ProfileRemovalSerializer +import to.bitkit.data.ProfileRemovalState +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.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 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 @@ -37,19 +73,31 @@ import to.bitkit.repositories.PubkySwapsRouteRepo import to.bitkit.repositories.UsdtRepo import to.bitkit.repositories.WakeRepo 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 +import to.bitkit.services.PubkyService import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture +import java.io.IOException +import java.io.OutputStream +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() { + @get:Rule + val folder = TemporaryFolder() private val backupRepo = mock() private val keychain = mock() @@ -58,6 +106,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { private val paykitUsdtPaymentRepo = mock() private val db = mock() private val settingsStore = mock() + private val connectionRecovery = connectionRecoveryFixture(settingsStore) private val cacheStore = mock() private val watchOnlyAccountRepo = mock() private val widgetsStore = mock() @@ -67,12 +116,21 @@ class WipeWalletUseCaseTest : BaseUnitTest() { private val lightningRepo = mock() private val pubkyRepo = mock() private val pubkySwapsRouteRepo = 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(), + profileRemovalStore = profileRemovalStore, + ) { mock() } private val wakeRepo = mock() - private val paykitSdkService = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { mock() } private val privatePaykitRepoProvider = Provider { privatePaykitRepo } private lateinit var sut: WipeWalletUseCase @@ -82,7 +140,19 @@ 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 { coreService.wipeData() }.thenReturn(Result.success(Unit)) whenever { usdtRepo.wipe(any()) }.doSuspendableAnswer { it.getArgument Unit>(0).invoke() Result.success(Unit) @@ -97,32 +167,346 @@ class WipeWalletUseCaseTest : BaseUnitTest() { onWipeCalled = false onSetWalletExistsStateCalled = false - sut = WipeWalletUseCase( - backupRepo = backupRepo, + sut = createSut() + } + + private fun createSut( + pubkyRepo: PubkyRepo = this.pubkyRepo, + sharingRepo: ContactPaymentSettingsRepo = contactPaymentSettingsRepo, + reservations: PrivatePaykitAddressReservationRepo = privatePaykitAddressReservationRepo, + removalStore: ProfileRemovalStore = profileRemovalStore, + sdk: PaykitSdkService = paykitSdkService, + ) = WipeWalletUseCase( + backupRepo = backupRepo, + keychain = keychain, + coreService = coreService, + usdtRepo = usdtRepo, + paykitUsdtPaymentRepo = paykitUsdtPaymentRepo, + paykitReceiptRepo = mock(), + db = db, + settingsStore = settingsStore, + cacheStore = cacheStore, + watchOnlyAccountRepo = watchOnlyAccountRepo, + widgetsStore = widgetsStore, + blocktankRepo = blocktankRepo, + activityRepo = activityRepo, + hwWalletRepo = hwWalletRepo, + lightningRepo = lightningRepo, + pubkyRepo = pubkyRepo, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, + privatePaykitRepo = privatePaykitRepoProvider, + privatePaykitAddressReservationRepo = reservations, + firebaseMessaging = firebaseMessaging, + migrationService = migrationService, + paykitSdkService = sdk, + profileRemovalStore = removalStore, + contactPaymentSettingsRepo = Provider { sharingRepo }, + connectionRecovery = connectionRecovery, + wakeRepo = wakeRepo, + ) + + 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, - paykitReceiptRepo = mock(), - 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, - pubkySwapsRouteRepo = pubkySwapsRouteRepo, - privatePaykitRepo = privatePaykitRepoProvider, - privatePaykitAddressReservationRepo = privatePaykitAddressReservationRepo, - firebaseMessaging = firebaseMessaging, - migrationService = migrationService, - paykitSdkService = paykitSdkService, - connectionRecovery = connectionRecoveryFixture(settingsStore), - wakeRepo = wakeRepo, + httpClient = mock(), + clock = Clock.System, + profileRemovalStore = profileRemovalStore, + ) + } + + @Test + fun `wallet wipe drains the queued receipt before SDK cleanup and credential deletion`() = test { + val entered = CompletableDeferred() + val release = CompletableDeferred() + val rejected = CompletableDeferred() + var receiptWritten = false + val receipt = launch { + connectionRecovery.withReceiptOperation { owner -> + ServiceQueue.CORE.background { + entered.complete(Unit) + release.await() + rejected.complete( + runCatching { owner.commitReceiptState { receiptWritten = true } } + .exceptionOrNull() is CancellationException + ) + } + } + } + entered.await() + val wipe = async { + sut.invoke( + resetWalletState = { onWipeCalled = true }, + onSuccess = { onSetWalletExistsStateCalled = true }, + ) + } + runCurrent() + verify(keychain, never()).wipe() + verify(privatePaykitRepo, never()).finishProfileRemoval(any()) + verify(lightningRepo, never()).stop() + assertFalse(wipe.isCompleted) + release.complete(Unit) + assertTrue(rejected.await()) + receipt.join() + assertTrue(wipe.await().isSuccess) + assertFalse(receiptWritten) + verify(keychain).wipe() + assertTrue(onWipeCalled) + assertTrue(onSetWalletExistsStateCalled) + assertNull(profileRemovalStore.pendingAttempt()) + } + + @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 `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, + cacheStore, + keychain, ) + 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() + profileRemovalStore.withAccess(id, ProfileRemovalScope.WALLET_WIPE) { 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 `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 { + 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, assertIs(result.exceptionOrNull()).cause?.message) + verify(keychain).wipe() + verify(privatePaykitRepo).finishProfileRemoval(profilePause) + verify(privatePaykitAddressReservationRepo).clear() + assertNotNull(profileRemovalStore.pendingAttempt()) + assertFalse(onWipeCalled) + assertFalse(onSetWalletExistsStateCalled) + } + + @Test + fun `core cleanup refusal retains wipe marker and blocks success`() = test { + whenever { coreService.wipeData() }.thenReturn(Result.failure(IllegalStateException("core unavailable"))) + val result = sut.invoke( + resetWalletState = { onWipeCalled = true }, + onSuccess = { onSetWalletExistsStateCalled = true }, + ) + assertTrue(result.isFailure) + 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, assertIs(result.exceptionOrNull()).cause?.message) + verify(keychain).wipe() + verify(pubkyRepo).finishProfileWipeLocally() + verify(privatePaykitAddressReservationRepo).clear() + assertNotNull(profileRemovalStore.pendingAttempt()) + assertFalse(onWipeCalled) + assertFalse(onSetWalletExistsStateCalled) } @Test @@ -161,17 +545,17 @@ class WipeWalletUseCaseTest : BaseUnitTest() { inOrder.verify(lightningRepo).stop() inOrder.verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any()) inOrder.verify(pubkyRepo).removeBitkitPaymentEndpoints() - inOrder.verify(privatePaykitRepo).closeAndClear() inOrder.verify(wakeRepo).unregister() inOrder.verify(lightningRepo).wipeStorage(0) inOrder.verify(pubkySwapsRouteRepo).resetForWipe() 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(privatePaykitAddressReservationRepo).clear() + inOrder.verify(privatePaykitRepo).finishProfileRemoval(profilePause) + inOrder.verify(pubkyRepo).finishProfileWipeLocally() inOrder.verify(coreService).wipeData() inOrder.verify(db).clearAllTables() inOrder.verify(settingsStore).reset() @@ -208,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) @@ -226,12 +630,38 @@ 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 `invoke should continue when address reservation clear fails`() = runTest { + 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")) val result = sut.invoke( @@ -239,25 +669,32 @@ class WipeWalletUseCaseTest : BaseUnitTest() { onSuccess = { onSetWalletExistsStateCalled = true }, ) - assertTrue(result.isSuccess) + assertEquals("clear failed", assertIs(result.exceptionOrNull()).cause?.message) 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()) + val failure = assertIs(result.exceptionOrNull()) + assertTrue(generateSequence(failure.cause) { it.cause }.any { it === error }) 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()) + verify(privatePaykitAddressReservationRepo, never()).clear() + assertNotNull(profileRemovalStore.pendingAttempt()) assertFalse(onSetWalletExistsStateCalled) } @@ -317,7 +754,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { ) assertTrue(result.isSuccess) - verify(pubkyRepo).wipeLocalState() + verify(pubkyRepo).finishProfileWipeLocally() verify(keychain).wipe() verify(backupRepo).setWiping(false) } @@ -334,28 +771,12 @@ 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) } - @Test - fun `invoke should unregister the wake device before wiping the keychain and continue when it fails`() = runTest { - whenever { wakeRepo.unregister() }.thenReturn(Result.failure(RuntimeException("Gateway unreachable"))) - - val result = sut.invoke( - resetWalletState = { onWipeCalled = true }, - onSuccess = { onSetWalletExistsStateCalled = true }, - ) - - assertTrue(result.isSuccess) - val inOrder = inOrder(wakeRepo, keychain) - inOrder.verify(wakeRepo).unregister() - inOrder.verify(keychain).wipe() - verify(backupRepo).setWiping(false) - } - @Test fun `invoke should fail before wiping local state when LDK storage wipe fails`() = runTest { val error = RuntimeException("Lightning wipe failed") @@ -367,7 +788,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) @@ -389,51 +810,200 @@ class WipeWalletUseCaseTest : BaseUnitTest() { } @Test - fun `invoke should mark migration checked when migration data clear fails`() = runTest { - whenever { migrationService.cleanupAfterMigration() }.thenThrow(RuntimeException("clear failed")) + fun `migration cleanup failure keeps the wipe pending without erasing credentials`() = runTest { + whenever { migrationService.cleanupAfterMigration() }.thenThrow(IllegalStateException("clear failed")) + val result = sut.invoke(resetWalletState = {}, onSuccess = { onWipeCalled = true }) + assertTrue(result.isFailure) + assertNotNull(profileRemovalStore.pendingAttempt()) + verify(migrationService).setNeedsPostMigrationSync(false) + verify(migrationService, never()).markMigrationChecked() + verify(keychain, never()).wipe() + assertFalse(onWipeCalled) + } - val result = sut.invoke( - resetWalletState = { onWipeCalled = true }, - onSuccess = { onSetWalletExistsStateCalled = true }, - ) + @Test + fun `migration flag refusal keeps the wipe pending without clearing migration data`() = runTest { + whenever { migrationService.setNeedsPostMigrationSync(false) }.thenThrow(IllegalStateException("flag failed")) + val result = sut.invoke(resetWalletState = {}, onSuccess = { onWipeCalled = true }) + assertTrue(result.isFailure) + assertNotNull(profileRemovalStore.pendingAttempt()) + verify(migrationService, never()).cleanupAfterMigration() + verify(migrationService, never()).markMigrationChecked() + verify(keychain, never()).wipe() + assertFalse(onWipeCalled) + } - assertTrue(result.isSuccess) - verify(migrationService).markMigrationChecked() - assertTrue(onSetWalletExistsStateCalled) + @Test + fun `database refusal retains the same attempt for confirmed local retry`() = runTest { + whenever(db.clearAllTables()).thenThrow(IllegalStateException("DB clear failed")) + val first = sut.invoke(resetWalletState = {}, onSuccess = { onWipeCalled = true }) + assertTrue(first.isFailure) + val attempt = assertNotNull(profileRemovalStore.pendingAttempt()) + verify(keychain).wipe() + verify(settingsStore, never()).reset() + assertFalse(onWipeCalled) + doAnswer { Unit }.whenever(db).clearAllTables() + clearInvocations(pubkyRepo, privatePaykitRepo) + val retry = sut.invoke( + resetWalletState = {}, + onSuccess = { onWipeCalled = true }, + expectedPendingAttemptId = attempt, + ) + assertTrue(retry.isSuccess) + assertNull(profileRemovalStore.pendingAttempt()) + assertTrue(onWipeCalled) + verify(pubkyRepo, never()).removeBitkitPaymentEndpoints() + verify(privatePaykitRepo, never()).removePublishedEndpointsForCleanup(any()) } + private fun localWipe(removalStore: ProfileRemovalStore) = createSut( + removalStore = removalStore, + sdk = PaykitSdkService( + mock(), + keychain, + mock(), + settingsStore = mock(), + profileRemovalStore = removalStore, + ) { mock() }, + ) + @Test - fun `invoke should clear post-migration sync flag even when migration data clear fails`() = runTest { - whenever { migrationService.cleanupAfterMigration() }.thenThrow(RuntimeException("clear failed")) + fun `post-credential refusal survives durable restart and finishes only after a fresh local retry`() = test { + val file = folder.newFile("wipe-restart.json").also { it.delete() } + val owner = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler)) + val original = ProfileRemovalStore(DataStoreFactory.create(ProfileRemovalSerializer, scope = owner) { file }) + var credentialsPresent = true + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenAnswer { credentialsPresent } + whenever { keychain.wipe() }.doSuspendableAnswer { credentialsPresent = false } + var refuseLocalMetadata = true + whenever { pubkyRepo.finishProfileWipeLocally() }.doSuspendableAnswer { + if (refuseLocalMetadata) throw IOException("profile persistence refused") + } + val first = localWipe(original).invoke( + resetWalletState = { onWipeCalled = true }, + onSuccess = { onSetWalletExistsStateCalled = true }, + ) + assertIs(first.exceptionOrNull()) + val id = assertNotNull(original.pendingAttempt()) + assertFalse(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)) + assertFalse(onWipeCalled) + assertFalse(onSetWalletExistsStateCalled) + requireNotNull(owner.coroutineContext[Job]).cancelAndJoin() - val result = sut.invoke( + val restarted = ProfileRemovalStore( + DataStoreFactory.create(ProfileRemovalSerializer, scope = backgroundScope) { file } + ) + val recoveredWipe = localWipe(restarted) + assertEquals(WalletResetRecovery.Pending(id), restarted.walletResetRecovery.first()) + assertFailsWith { restarted.requireWalletAvailable() } + clearInvocations(pubkyRepo, privatePaykitRepo, keychain) + // Restart/observation itself cannot replay cleanup or reconstruct absent credentials. + verify(keychain, never()).wipe() + val refusedRetry = recoveredWipe.invoke( resetWalletState = { onWipeCalled = true }, onSuccess = { onSetWalletExistsStateCalled = true }, + expectedPendingAttemptId = id, ) + assertIs(refusedRetry.exceptionOrNull()) + assertEquals(id, restarted.pendingAttempt()) + assertFalse(onWipeCalled) + assertFalse(onSetWalletExistsStateCalled) - assertTrue(result.isSuccess) - verify(migrationService).setNeedsPostMigrationSync(false) - verify(migrationService).markMigrationChecked() + refuseLocalMetadata = false + val completed = recoveredWipe.invoke( + resetWalletState = { onWipeCalled = true }, + onSuccess = { onSetWalletExistsStateCalled = true }, + expectedPendingAttemptId = id, + ) + assertTrue(completed.isSuccess) + assertNull(restarted.pendingAttempt()) + restarted.requireWalletAvailable() + assertEquals(WalletResetRecovery.Clear, restarted.walletResetRecovery.first()) + assertTrue(onWipeCalled) + assertTrue(onSetWalletExistsStateCalled) + verify(pubkyRepo, never()).removeBitkitPaymentEndpoints() + verify(privatePaykitRepo, never()).removePublishedEndpointsForCleanup(any()) + verify(privatePaykitRepo, never()).closeAndClear() } @Test - fun `invoke should clear migration data and finish when post-migration sync flag clear fails`() = runTest { - whenever { migrationService.setNeedsPostMigrationSync(false) }.thenThrow(RuntimeException("flag failed")) - - val result = sut.invoke( + fun `final completion write refusal keeps the durable marker until a confirmed restart retry`() = test { + val file = folder.newFile("wipe-completion.json").also { it.delete() } + var refuseCompletion = true + val serializer = object : Serializer by ProfileRemovalSerializer { + override suspend fun writeTo(t: ProfileRemovalState, output: OutputStream) { + if (refuseCompletion && t.attemptId == null) throw IOException("completion write refused") + ProfileRemovalSerializer.writeTo(t, output) + } + } + val owner = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler)) + val original = ProfileRemovalStore(DataStoreFactory.create(serializer, scope = owner) { file }) + val result = localWipe(original).invoke( resetWalletState = { onWipeCalled = true }, onSuccess = { onSetWalletExistsStateCalled = true }, ) - - assertTrue(result.isSuccess) - verify(migrationService).cleanupAfterMigration() + assertIs(result.exceptionOrNull()) + verify(keychain).wipe() + verify(settingsStore).reset() verify(migrationService).markMigrationChecked() + val id = assertNotNull(original.pendingAttempt()) + assertFalse(onWipeCalled) + assertFalse(onSetWalletExistsStateCalled) + requireNotNull(owner.coroutineContext[Job]).cancelAndJoin() + + val restarted = ProfileRemovalStore(DataStoreFactory.create(serializer, scope = backgroundScope) { file }) + assertEquals(WalletResetRecovery.Pending(id), restarted.walletResetRecovery.first()) + assertFailsWith { restarted.requireWalletAvailable() } + clearInvocations(pubkyRepo, privatePaykitRepo) + refuseCompletion = false + assertTrue( + localWipe(restarted).invoke( + resetWalletState = { onWipeCalled = true }, + onSuccess = { onSetWalletExistsStateCalled = true }, + expectedPendingAttemptId = id, + ).isSuccess + ) + assertNull(restarted.pendingAttempt()) + restarted.requireWalletAvailable() + assertTrue(onWipeCalled) assertTrue(onSetWalletExistsStateCalled) + verify(pubkyRepo, never()).removeBitkitPaymentEndpoints() + verify(privatePaykitRepo, never()).removePublishedEndpointsForCleanup(any()) } @Test - fun `invoke should complete the wipe when database clear fails`() = runTest { - whenever(db.clearAllTables()).thenThrow(RuntimeException("DB clear failed")) + fun `confirmed stale reset attempt cannot erase the current wallet`() = runTest { + val current = UUID.randomUUID().toString() + profileRemovalStore.withAccess(current, ProfileRemovalScope.WALLET_WIPE) { profileRemovalStore.begin(current) } + val entered = CompletableDeferred() + val release = CompletableDeferred() + val active = async { + connectionRecovery.withCurrentWallet { + entered.complete(Unit) + release.await() + } + } + entered.await() + val result = sut.invoke( + resetWalletState = {}, + onSuccess = {}, + expectedPendingAttemptId = UUID.randomUUID().toString(), + ) + assertTrue(active.isActive) + release.complete(Unit) + active.await() + verify(backupRepo, never()).setWiping(any()) + verify(lightningRepo, never()).setWiping(any()) + assertTrue(result.isFailure) + assertEquals(current, profileRemovalStore.pendingAttempt()) + verify(lightningRepo, never()).stop() + verify(keychain, never()).wipe() + verify(coreService, never()).wipeData() + } + + @Test + fun `invoke should unregister the wake device before wiping the keychain and continue when it fails`() = runTest { + whenever { wakeRepo.unregister() }.thenReturn(Result.failure(RuntimeException("Gateway unreachable"))) val result = sut.invoke( resetWalletState = { onWipeCalled = true }, @@ -441,9 +1011,19 @@ class WipeWalletUseCaseTest : BaseUnitTest() { ) assertTrue(result.isSuccess) - verify(settingsStore).reset() - verify(keychain).wipe() - assertTrue(onWipeCalled) - assertTrue(onSetWalletExistsStateCalled) + val inOrder = inOrder(wakeRepo, keychain) + inOrder.verify(wakeRepo).unregister() + inOrder.verify(keychain).wipe() + verify(backupRepo).setWiping(false) + } + + @Test + fun `profile-only removal cannot be resumed as a wallet reset`() = runTest { + val current = UUID.randomUUID().toString() + profileRemovalStore.withAccess(current) { profileRemovalStore.begin(current) } + val result = sut.invoke(resetWalletState = {}, onSuccess = {}, expectedPendingAttemptId = current) + assertTrue(result.isFailure) + verify(keychain, never()).wipe() + assertEquals(current, profileRemovalStore.pendingAttempt()) } } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 672cf8b27a..da87c06d3f 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -1,6 +1,7 @@ package to.bitkit.viewmodels import android.app.Activity +import android.app.Application import android.app.NotificationManager import android.content.ClipData import android.content.ClipboardManager @@ -153,6 +154,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 @@ -190,6 +192,8 @@ import to.bitkit.repositories.OnchainSendNotDispatchedError import to.bitkit.repositories.OnchainSendOutcome import to.bitkit.repositories.OnchainSendReviewInterruptedError 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 @@ -303,7 +307,7 @@ import com.synonym.bitkitcore.Activity as BitkitActivity @OptIn(ExperimentalCoroutinesApi::class, ExperimentalTime::class) @RunWith(RobolectricTestRunner::class) -@Config(sdk = [34]) +@Config(application = Application::class, sdk = [34]) class AppViewModelSendFlowTest : BaseUnitTest() { private lateinit var sut: AppViewModel @@ -442,6 +446,93 @@ class AppViewModelSendFlowTest : BaseUnitTest() { App.currentActivity = null } + @Test + fun `recovery PIN policy waits for durable settings before exposing disabled`() = test { + val loaded = CompletableDeferred() + whenever(settingsStore.data).thenReturn(kotlinx.coroutines.flow.flow { emit(loaded.await()) }) + sut.recoveryPinRequired.test { + assertEquals(null, awaitItem()) + runCurrent() + expectNoEvents() + loaded.complete(to.bitkit.data.SettingsData(isPinEnabled = true)) + assertEquals(true, awaitItem()) + awaitComplete() + } + } + + @Test + fun `recovery requires an existing keychain PIN even when settings say disabled`() = test { + whenever(keychain.loadString(Keychain.Key.PIN.name)).thenReturn("test-pin") + sut.recoveryPinRequired.test { + assertEquals(null, awaitItem()) + assertEquals(true, awaitItem()) + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `unreadable recovery PIN never becomes disabled`() = test { + whenever(keychain.loadString(Keychain.Key.PIN.name)).thenThrow(IllegalStateException("unreadable test PIN")) + sut.recoveryPinRequired.test { + assertEquals(null, awaitItem()) + assertEquals(null, awaitItem()) + awaitComplete() + } + } + + @Test + fun `recovery PIN exhaustion stays bounded without automatic wipe`() = test { + val access = mock() + whenever(keychain.accessBlocking(any())).thenAnswer { + it.getArgument Boolean>(0).invoke(access) + } + whenever(access.load(Keychain.Key.PIN.name)).thenReturn("test-pin".toByteArray()) + var attempts = "1" + whenever(access.load(Keychain.Key.PIN_ATTEMPTS_REMAINING.name)).thenAnswer { attempts.toByteArray() } + org.mockito.kotlin.doAnswer { + attempts = it.getArgument(1).decodeToString() + Unit + }.whenever(access).upsert(eq(Keychain.Key.PIN_ATTEMPTS_REMAINING.name), any()) + sut.mainScreenEffect.test { + assertFalse(sut.validateRecoveryPin("wrong")) + assertEquals("0", attempts) + assertFalse(sut.validateRecoveryPin("test-pin")) + assertFalse(sut.validateRecoveryPin("wrong")) + runCurrent() + expectNoEvents() + verify(access, times(1)).upsert(eq(Keychain.Key.PIN_ATTEMPTS_REMAINING.name), any()) + } + } + + @Test + fun `recovery PIN requires acknowledged attempt persistence`() = test { + val access = mock() + whenever(keychain.accessBlocking(any())).thenAnswer { + it.getArgument Boolean>(0).invoke(access) + } + whenever(access.load(Keychain.Key.PIN.name)).thenReturn("test-pin".toByteArray()) + whenever(access.load(Keychain.Key.PIN_ATTEMPTS_REMAINING.name)).thenReturn("2".toByteArray()) + org.mockito.kotlin.doThrow(IllegalStateException("test storage refused")) + .whenever(access).upsert(any(), any()) + assertFalse(sut.validateRecoveryPin("test-pin")) + verify(access).upsert(eq(Keychain.Key.PIN_ATTEMPTS_REMAINING.name), any()) + } + + @Test + fun `recovery PIN rejects malformed accounting and accepts a persisted valid attempt`() = test { + val access = mock() + whenever(keychain.accessBlocking(any())).thenAnswer { + it.getArgument Boolean>(0).invoke(access) + } + whenever(access.load(Keychain.Key.PIN.name)).thenReturn("test-pin".toByteArray()) + whenever(access.load(Keychain.Key.PIN_ATTEMPTS_REMAINING.name)).thenReturn("broken".toByteArray()) + assertFalse(sut.validateRecoveryPin("test-pin")) + verify(access, never()).upsert(any(), any()) + whenever(access.load(Keychain.Key.PIN_ATTEMPTS_REMAINING.name)).thenReturn("2".toByteArray()) + assertTrue(sut.validateRecoveryPin("test-pin")) + verify(access).upsert(eq(Keychain.Key.PIN_ATTEMPTS_REMAINING.name), any()) + } + @Test fun `a tapped exit notification stays requested until the exit loaded`() = test { val loaded = CompletableDeferred() @@ -845,6 +936,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)) @@ -973,7 +1066,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { .thenReturn(Result.success(Unit)) whenever { privatePaykitRepo.contactPublicKeyForPrivateInvoicePaymentHash(any()) } .thenReturn(null) - whenever { publicPaykitRepo.refreshPublishedBolt11ForPayment(any(), any(), any()) } + whenever { publicPaykitRepo.refreshPublishedBolt11ForPayment(any(), any(), any(), any()) } .thenReturn(Result.success(Unit)) whenever { privatePaykitRepo.handleReceivedPayment(any()) } .thenReturn(Result.success(Unit)) @@ -3471,6 +3564,60 @@ 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(executor.isLedgerBehind(any())).thenReturn(false) + whenever(sdk.listAllowances(any())).thenReturn(emptyList()) + val realAllowances = PaykitAllowanceRepo( + ioDispatcher = testDispatcher, + paykitSdkService = sdk, + executor = executor, + lightningRepo = lightningRepo, + activityRepo = activityRepo, + clock = Clock.System, + backupRepo = { backupRepo }, + ) + 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() @@ -5946,6 +6093,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 `pubky auth deeplink for another pubky is refused before the Ring hint`() = test { enablePaykitUi() @@ -10531,7 +10746,9 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(pubkyRepo.isCurrent(signIn)).thenReturn(true) whenever(activityRepo.isActivitySeen(paymentId)).thenReturn(false) whenever(privatePaykitRepo.contactPublicKeyForPrivateInvoicePaymentHash(paymentHash)).thenReturn(contactKey) - whenever(publicPaykitRepo.refreshPublishedBolt11ForPayment(eq(paymentHash), any(), any())).doSuspendableAnswer { + whenever( + publicPaykitRepo.refreshPublishedBolt11ForPayment(eq(paymentHash), any(), any(), any()) + ).doSuspendableAnswer { resumePublicRefresh.await() Result.failure(AppError("Public invoice refresh failed")) } @@ -10559,7 +10776,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(activityRepo).notifyPaymentActivityChanged() verify(activityRepo).markActivityAsSeen(paymentId) verify(activityRepo).setContact(contactKey, paymentHash, syncLdkPayments = false) - verify(publicPaykitRepo).refreshPublishedBolt11ForPayment(eq(paymentHash), any(), any()) + verify(publicPaykitRepo).refreshPublishedBolt11ForPayment(eq(paymentHash), any(), any(), any()) } verify(privatePaykitRepo, never()).handleReceivedPayment(paymentHash) @@ -10596,7 +10813,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(activityRepo).isActivitySeen(paymentId) verify(activityRepo, never()).markActivityAsSeen(any(), any()) verify(privatePaykitRepo, never()).contactPublicKeyForPrivateInvoicePaymentHash(any()) - verify(publicPaykitRepo, never()).refreshPublishedBolt11ForPayment(any(), any(), any()) + verify(publicPaykitRepo, never()).refreshPublishedBolt11ForPayment(any(), any(), any(), any()) verify(privatePaykitRepo, never()).handleReceivedPayment(any()) } @@ -10677,7 +10894,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { emitNodeEvent(Event.PaymentReceived(paymentId, paymentHash, 1_000uL, emptyList())) advanceUntilIdle() assertEquals(paymentHash, sut.transactionSheet.value.paymentHashOrTxId) - verify(publicPaykitRepo, never()).refreshPublishedBolt11ForPayment(any(), any(), any()) + verify(publicPaykitRepo, never()).refreshPublishedBolt11ForPayment(any(), any(), any(), any()) signIn = PubkySignIn(testPublicKey, 1L) isRestoringPubkySession.value = false @@ -10689,6 +10906,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { eq(paymentHash), canPublish.capture(), isStillCurrent.capture(), + any(), ) assertTrue(canPublish.firstValue()) assertTrue(isStillCurrent.firstValue()) @@ -10713,7 +10931,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceUntilIdle() assertEquals(paymentHash, sut.transactionSheet.value.paymentHashOrTxId) - verify(publicPaykitRepo, never()).refreshPublishedBolt11ForPayment(any(), any(), any()) + verify(publicPaykitRepo, never()).refreshPublishedBolt11ForPayment(any(), any(), any(), any()) verify(privatePaykitRepo, never()).handleReceivedPayment(any()) } @@ -10725,7 +10943,9 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val refreshAdmission = CompletableDeferred<() -> Boolean>() val resumeRefresh = CompletableDeferred() val paymentHash = "payment-hash" - whenever(publicPaykitRepo.refreshPublishedBolt11ForPayment(eq(paymentHash), any(), any())).doSuspendableAnswer { + whenever( + publicPaykitRepo.refreshPublishedBolt11ForPayment(eq(paymentHash), any(), any(), any()) + ).doSuspendableAnswer { refreshAdmission.complete(it.getArgument(2)) resumeRefresh.await() Result.success(Unit) @@ -21400,6 +21620,101 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(activityRepo, never()).setLightningMessageIfEmpty(any(), any()) } + @Test + fun `wallet wipe drains background public address preparation before clearing reservations`() = test { + enablePublicPaykitSharing() + pubkyPublicKey.value = testPublicKey + advanceUntilIdle() + settingsData.update { + it.copy(publicPaykitLightningEnabled = false, publicPaykitUsdtEnabled = false) + } + val ledger = MutableStateFlow(PrivatePaykitReservationData()) + val reservationStore = mock() + whenever(reservationStore.data).thenReturn(ledger) + whenever(reservationStore.update(any())).thenAnswer { + ledger.update(it.getArgument<(PrivatePaykitReservationData) -> PrivatePaykitReservationData>(0)) + } + whenever(reservationStore.reset()).thenAnswer { ledger.value = PrivatePaykitReservationData() } + whenever(cacheStore.data).thenReturn(MutableStateFlow(AppCacheData(onchainAddress = "bcrt1qordinary"))) + val derived = CompletableDeferred() + val deliverAddress = CompletableDeferred() + whenever(lightningRepo.newAddressInfoForType(AddressType.P2WPKH)).doSuspendableAnswer { + val oldWalletAddress = AddressDerivationInfo("bcrt1qoldwallet", 1) + derived.complete(Unit) + deliverAddress.await() + Result.success(oldWalletAddress) + } + val reservations = PrivatePaykitAddressReservationRepo( + testDispatcher, + reservationStore, + settingsStore, + coreService, + lightningRepo, + cacheStore, + keychain, + ) + val publisher = PublicPaykitRepo( + testDispatcher, + pubkyRepo, + lightningRepo, + coreService, + mock(), + settingsStore, + Clock.System, + usdtRepo, + reservations, + ) + whenever(publicPaykitRepo.syncCurrentPublishedEndpoints(any(), any(), any())).doSuspendableAnswer { + publisher.syncCurrentPublishedEndpoints(it.getArgument(0), it.getArgument(1), it.getArgument(2)) + } + walletState.update { it.copy(onchainAddress = "bcrt1qchanged") } + runCurrent() + advanceTimeBy(1_000) + runCurrent() + assertTrue(derived.isCompleted) + + val wipe = async { + contactPaymentSettingsRepo.withWalletWipe( + admitRepository = { operation -> + isProfileDeletionInProgress.value = true + operation() + }, + ) { + reservations.clear() + } + } + runCurrent() + val clearedBeforeDelivery = wipe.isCompleted + deliverAddress.complete(Unit) + wipe.await() + runCurrent() + + assertFalse(clearedBeforeDelivery, "Wipe must drain the admitted public preparation") + assertEquals(PrivatePaykitReservationData(), ledger.value) + } + + @Test + fun `public invoice expiry waits for sharing admission without losing its refresh`() = test { + enablePublicPaykitSharing() + pubkyPublicKey.value = testPublicKey + advanceUntilIdle() + val finishCleanup = CompletableDeferred() + val cleanup = launch { + contactPaymentSettingsRepo.reconcilePendingEndpoints { finishCleanup.await() } + } + runCurrent() + clearInvocations(publicPaykitRepo) + + settingsData.update { it.copy(publicPaykitBolt11ExpiresAtMillis = 1L) } + runCurrent() + verify(publicPaykitRepo, never()).syncCurrentPublishedEndpoints(any(), any(), any()) + finishCleanup.complete(Unit) + cleanup.join() + advanceUntilIdle() + + verify(publicPaykitRepo).syncCurrentPublishedEndpoints(eq(false), eq(false), any()) + } + @Test fun `public Paykit publication coalesces startup and resumes with the latest address`() = test { enablePublicPaykitSharing() @@ -22335,6 +22650,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { eq("received-hash"), publicationAdmission.capture(), any(), + any(), ) assertFalse(publicationAdmission.firstValue()) isProfileDeletionInProgress.value = false @@ -22405,7 +22721,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { privateCleanup.await() Result.success(Unit) } - whenever(publicPaykitRepo.syncPublishedEndpoints(publish = false, appSyncPriority = Priority.Interactive)) + whenever(publicPaykitRepo.syncPublishedEndpoints(eq(false), eq(Priority.Interactive), any())) .doSuspendableAnswer { publicCleanup.await() Result.success(Unit) @@ -22429,8 +22745,9 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(privatePaykitRepo, never()).retryPendingEndpointRemoval(any>(), any()) verify(publicPaykitRepo, times(1)).syncPublishedEndpoints( - publish = false, - appSyncPriority = Priority.Interactive, + publish = eq(false), + appSyncPriority = eq(Priority.Interactive), + isStillCurrent = any(), ) assertTrue(settingsData.value.publicPaykitCleanupPending) publicCleanup.complete(Unit) diff --git a/app/src/test/java/to/bitkit/viewmodels/SettingsViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/SettingsViewModelTest.kt index 3827414161..cf4570732e 100644 --- a/app/src/test/java/to/bitkit/viewmodels/SettingsViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/SettingsViewModelTest.kt @@ -15,6 +15,7 @@ import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.clearInvocations import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify @@ -26,6 +27,7 @@ import to.bitkit.models.PubkyProfile import to.bitkit.repositories.ContactPaymentSettingsRepo import to.bitkit.repositories.PrivatePaykitRepo import to.bitkit.repositories.PubkyRepo +import to.bitkit.repositories.PubkySignIn import to.bitkit.repositories.PublicPaykitRepo import to.bitkit.repositories.UsdtPreferencesRepo import to.bitkit.repositories.WidgetsRepo @@ -88,7 +90,13 @@ class SettingsViewModelTest : BaseUnitTest() { whenever(pubkyRepo.isAuthenticated).thenReturn(MutableStateFlow(false)) whenever(pubkyRepo.identityExists).thenReturn(MutableStateFlow(false)) whenever(pubkyRepo.contacts).thenReturn(contacts) - whenever { publicPaykitRepo.syncPublishedEndpoints(publish = false, appSyncPriority = Priority.Interactive) } + whenever(pubkyRepo.currentSignIn()).thenAnswer { PubkySignIn("identity", 0L) } + whenever(pubkyRepo.isCurrent(any())).thenAnswer { + val signIn = it.getArgument(0) + signIn.publicKey == "identity" && signIn.generation == 0L + } + whenever(privatePaykitRepo.isProfileDeletionInProgress).thenReturn(MutableStateFlow(false)) + whenever { publicPaykitRepo.syncPublishedEndpoints(eq(false), eq(Priority.Interactive), any()) } .thenReturn(Result.success(Unit)) whenever { publicPaykitRepo.syncPaykitApp(anyOrNull(), canSync = anyOrNull()) }.thenReturn(Result.success(Unit)) whenever { privatePaykitRepo.disableSharingAndPruneUnsavedContactState(any>(), anyOrNull()) } @@ -142,13 +150,15 @@ class SettingsViewModelTest : BaseUnitTest() { assertEquals("", settings.publicPaykitBolt11) assertEquals("", settings.publicPaykitBolt11PaymentHash) assertEquals(0L, settings.publicPaykitBolt11ExpiresAtMillis) - verify(publicPaykitRepo).syncPublishedEndpoints(publish = false, appSyncPriority = Priority.Interactive) - verify(privatePaykitRepo).disableSharingAndPruneUnsavedContactState(contacts.value.map { it.publicKey }) + verify(publicPaykitRepo).syncPublishedEndpoints(eq(false), eq(Priority.Interactive), any()) + verify( + privatePaykitRepo + ).disableSharingAndPruneUnsavedContactState(eq(contacts.value.map { it.publicKey }), any()) } @Test fun `disabling Paykit keeps public cleanup pending when public removal fails`() = test { - whenever { publicPaykitRepo.syncPublishedEndpoints(publish = false, appSyncPriority = Priority.Interactive) } + whenever { publicPaykitRepo.syncPublishedEndpoints(eq(false), eq(Priority.Interactive), any()) } .thenReturn(Result.failure(SettingsViewModelTestError("cleanup failed"))) isPaykitEnabled.value = true settingsData.value = SettingsData( @@ -160,7 +170,9 @@ class SettingsViewModelTest : BaseUnitTest() { advanceUntilIdle() assertTrue(settingsData.value.publicPaykitCleanupPending) - verify(privatePaykitRepo).disableSharingAndPruneUnsavedContactState(contacts.value.map { it.publicKey }) + verify( + privatePaykitRepo + ).disableSharingAndPruneUnsavedContactState(eq(contacts.value.map { it.publicKey }), any()) } @Test @@ -176,11 +188,14 @@ class SettingsViewModelTest : BaseUnitTest() { assertFalse(settingsData.value.publicPaykitCleanupPending) verify(publicPaykitRepo, never()).syncPublishedEndpoints( - publish = false, - appSyncPriority = Priority.Interactive, + publish = eq(false), + appSyncPriority = eq(Priority.Interactive), + isStillCurrent = any(), ) - verify(publicPaykitRepo).syncPaykitApp(privateSharingEnabled = false) - verify(privatePaykitRepo).disableSharingAndPruneUnsavedContactState(contacts.value.map { it.publicKey }) + verify(publicPaykitRepo).syncPaykitApp(eq(false), canSync = any()) + verify( + privatePaykitRepo + ).disableSharingAndPruneUnsavedContactState(eq(contacts.value.map { it.publicKey }), any()) } @Test @@ -188,7 +203,8 @@ class SettingsViewModelTest : BaseUnitTest() { clearInvocations(publicPaykitRepo) whenever { publicPaykitRepo.syncPaykitApp( - privateSharingEnabled = false, + privateSharingEnabled = eq(false), + canSync = any(), ) } .thenReturn(Result.failure(SettingsViewModelTestError("marker cleanup failed"))) @@ -202,11 +218,14 @@ class SettingsViewModelTest : BaseUnitTest() { assertTrue(settingsData.value.publicPaykitCleanupPending) verify(publicPaykitRepo, never()).syncPublishedEndpoints( - publish = false, - appSyncPriority = Priority.Interactive, + publish = eq(false), + appSyncPriority = eq(Priority.Interactive), + isStillCurrent = any(), ) - verify(publicPaykitRepo).syncPaykitApp(privateSharingEnabled = false) - verify(privatePaykitRepo).disableSharingAndPruneUnsavedContactState(contacts.value.map { it.publicKey }) + verify(publicPaykitRepo).syncPaykitApp(eq(false), canSync = any()) + verify( + privatePaykitRepo + ).disableSharingAndPruneUnsavedContactState(eq(contacts.value.map { it.publicKey }), any()) } @Test @@ -230,11 +249,27 @@ class SettingsViewModelTest : BaseUnitTest() { assertFalse(settings.sharesPrivatePaykitEndpoints) assertFalse(settings.publicPaykitCleanupPending) assertEquals("", settings.publicPaykitBolt11) - verify(publicPaykitRepo).syncPublishedEndpoints(publish = false, appSyncPriority = Priority.Interactive) - verify(privatePaykitRepo).disableSharingAndPruneUnsavedContactState(contacts.value.map { it.publicKey }) + verify(publicPaykitRepo).syncPublishedEndpoints(eq(false), eq(Priority.Interactive), any()) + verify( + privatePaykitRepo + ).disableSharingAndPruneUnsavedContactState(eq(contacts.value.map { it.publicKey }), any()) verify(settingsStore, never()).setIsPaykitEnabled(any()) } + @Test + fun `disabling Paykit without a live profile retains public cleanup`() = test { + whenever(pubkyRepo.currentSignIn()).thenReturn(null) + isPaykitEnabled.value = true + settingsData.value = SettingsData(sharesPrivatePaykitEndpoints = true) + + sut.setIsPaykitEnabled(false) + advanceUntilIdle() + + assertFalse(isPaykitEnabled.value) + assertFalse(settingsData.value.sharesPrivatePaykitEndpoints) + assertTrue(settingsData.value.publicPaykitCleanupPending) + } + @Test fun `keepBitkitActiveInBackground defaults to false`() = test { assertFalse(sut.keepBitkitActiveInBackground.value) diff --git a/changelog.d/next/1686.fixed.md b/changelog.d/next/1686.fixed.md new file mode 100644 index 0000000000..8612b615a1 --- /dev/null +++ b/changelog.d/next/1686.fixed.md @@ -0,0 +1 @@ +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. diff --git a/docs/screens-map.md b/docs/screens-map.md index d01eb8fdfa..d9705ef9f0 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 @@ -91,6 +92,7 @@ Frame names are stable across handoff iterations; node ids are not, so the map l | - | - | | RecoveryMnemonicScreen.kt | `n/a` | | RecoveryModeScreen.kt | `n/a` | +| WalletResetRecoveryScreen.kt | `todo` | ## ui/screens/scanner diff --git a/journeys/README.md b/journeys/README.md index 4f6d0b5529..6120bf9be4 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -179,6 +179,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/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 diff --git a/journeys/backup-restore/connection-recovery.xml b/journeys/backup-restore/connection-recovery.xml index 4bf9e8817a..e8472f1155 100644 --- a/journeys/backup-restore/connection-recovery.xml +++ b/journeys/backup-restore/connection-recovery.xml @@ -20,6 +20,6 @@ Keep required recovery unavailable and restart the app; verify the correction is retained and spending remains gated Allow restoration of the old SETTINGS backup; verify only the explicitly corrected endpoints override that backup and unrelated preferences restore normally Complete required WALLET and USDT recovery; verify ordinary wallet actions become available only after both acknowledgements - Repeat with only optional profile caching unavailable after required recovery; verify that error retains its optional recovery controls and is not classified as failed node startup + Repeat with only optional profile enrichment unavailable after required recovery; verify ordinary wallet actions remain available and no failed-node-startup or restore-retry screen appears diff --git a/journeys/backup-restore/wallet-snapshot-consistency.md b/journeys/backup-restore/wallet-snapshot-consistency.md index 6b58ef5e31..4dccf9d071 100644 --- a/journeys/backup-restore/wallet-snapshot-consistency.md +++ b/journeys/backup-restore/wallet-snapshot-consistency.md @@ -25,3 +25,43 @@ 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. + 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. +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. 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 + + diff --git a/journeys/profile/README.md b/journeys/profile/README.md index 82662e5476..9e399d8851 100644 --- a/journeys/profile/README.md +++ b/journeys/profile/README.md @@ -14,11 +14,11 @@ Android restores metadata before sharing settings. It conservatively quarantines `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. After restart, only an explicit local Disconnect may finish interrupted local cleanup; it does not claim that the remote profile was deleted. While the original live logout is still retained, an unknown grant-revocation outcome may instead be retried after a fresh confirmation, as described below. 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. @@ -28,7 +28,7 @@ Hold initial session restoration with public payments enabled, turn public payme 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. @@ -46,7 +46,39 @@ 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, while the process remains alive. Verify cleanup remains pending and authenticated automatic work does not resume. Review reads the original identity again and requires a new confirmation; after restart, only local Disconnect is available and remote state remains 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. +On Android, this includes both the pubky.app profile and the Paykit copy; an adopted Ring profile +is excluded from pubky.app deletion. Each captured revision is checked independently. An acknowledged +pubky.app deletion is retained if the Paykit deletion fails, so a freshly confirmed retry does not +repeat that deletion or target a recreated profile. +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. `create-profile.xml` records the name-only saving interval and checks the saved name after reopening and relaunching. Use a fresh unfunded identity per run and record the exact app/SDK revisions and network. With controlled network fault injection, block direct UDP while keeping the configured HTTP relays and homeserver reachable; saving should still complete. Reject the required profile write separately and verify saving reports failure instead of navigating to Pay Contacts. Fault injection is a manual check beyond journey-runner capabilities. @@ -55,3 +87,33 @@ For controlled fault testing, interrupt deletion after private withdrawal but be On Android, the restart check waits for the full profile (`ProfileViewName`). A matching `ProfileCachedName` during loading does not complete that check. Record an unfinished load separately from a loaded profile with a missing or incorrect name. `profile-link-validation.xml` checks that Add Link in Edit Profile shows an inline error and keeps Save disabled for a link pubky.app would refuse, and accepts a bare domain. The 100-code-point label and 300-code-point URL limits, and an already-stored invalid link blocking the profile save, are manual checks: long values cannot be typed reliably on a device, and an invalid stored link needs a profile written outside the current app. + +For the sharing-disabled deletion variant of `delete-profile.xml`, first save a disposable contact +and establish its private link, turn Pay Contacts off, and let sharing cleanup finish. Keep the saved +contact. Profile deletion must still obtain a private-list withdrawal acknowledgement for retained +linked peers before removing the profile. A disabled App Registry flag alone is not an acknowledgement. +Ordinary background cleanup while sharing is disabled remains unchanged. Record the app revision and +actual homeserver/private-link responses; a service mock is not completion evidence for this variant. + +## Original-grant logout retry + +Use a disposable live profile with a homeserver advertising the existing grant-proof-logout protocol. +Reject its logout once before server acceptance, after endpoint withdrawal and profile deletion have +been acknowledged. The app must retain local credentials and pending recovery. It must make no +further logout request when the dialog closes, the app resumes, or Retry opens a new confirmation. +Cancel that confirmation and verify the request count stays unchanged. Confirm a fresh Retry and +verify it uses the original grant and signer, without repeating acknowledged endpoint withdrawal, +profile deletion or contact reads. Same-grant bearer refresh may occur; a replacement grant or +identity must never be used by this intent. + +Separately, discard the logout response after the server commits. The app must retain uncertainty +until another explicitly confirmed attempt from the same live handle acknowledges the original +grant. If the native acknowledgement was retained but cancellation or local storage failure hid +completion, offer only local completion and send no further logout. Replace the identity while a +logout is held and verify replacement waits for cancellation to drain; an old dialog cannot erase +the replacement credentials. Restart with pending removal and verify the app cannot reconstruct +remote authority from the saved UUID or credentials. + +Record the exact app and released SDK revisions, redacted grant/operation counters, server commit +observation, and local marker transitions. These fault cases need controlled network boundaries; +component tests and the ordinary journey runner do not establish an authenticated app pass. diff --git a/journeys/profile/delete-profile-uncertain-response.xml b/journeys/profile/delete-profile-uncertain-response.xml new file mode 100644 index 0000000000..ce66d6666a --- /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 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..b10634c646 100644 --- a/journeys/profile/delete-profile.xml +++ b/journeys/profile/delete-profile.xml @@ -5,6 +5,9 @@ Record the sequence so progress can be checked even when deletion completes quickly. Start with zero contacts and record the deletion time without a fixed latency target. Repeat with 62 imported contacts, once after preparation settles and once immediately after import. + Separately repeat with a saved linked contact after turning Pay Contacts off and waiting for + sharing cleanup to finish. Deletion must still withdraw any retained private lists, require + their acknowledgement, and reach onboarding without turning sharing back on. Measure confirmation to onboarding and check logs for any uncertain-write safety wait. During deletion, check the indicator on Delete Profile. Save stays disabled with its label visible. Cleanup may still wait for admitted operations and remote safety checks; no fixed duration is expected. @@ -15,7 +18,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 new file mode 100644 index 0000000000..4d83179fb1 --- /dev/null +++ b/journeys/profile/profile-cleanup-failure.xml @@ -0,0 +1,28 @@ + + + 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 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; profile-removal-recovery.xml covers explicit recovery. Cross-device conditional contact deletion + requires the separate native contract. + + + 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 + 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 + 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 pending local cleanup is shown without automatic profile deletion or authenticated reactivation + + 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 + + diff --git a/journeys/profile/profile-removal-recovery.xml b/journeys/profile/profile-removal-recovery.xml new file mode 100644 index 0000000000..881644b0ae --- /dev/null +++ b/journeys/profile/profile-removal-recovery.xml @@ -0,0 +1,27 @@ + + + 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 a separate failed-removal fixture, make the original credentials unreadable during Review and verify the failure dialog offers Disconnect instead of another Review, retains the pending attempt and performs no remote mutation + 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 + 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 + + diff --git a/journeys/security/README.md b/journeys/security/README.md index 9b8be02a9e..ddb7b1a76c 100644 --- a/journeys/security/README.md +++ b/journeys/security/README.md @@ -3,3 +3,31 @@ `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. + +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. + +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. diff --git a/journeys/security/wallet-reset-recovery-pin.xml b/journeys/security/wallet-reset-recovery-pin.xml new file mode 100644 index 0000000000..50e00f4ec6 --- /dev/null +++ b/journeys/security/wallet-reset-recovery-pin.xml @@ -0,0 +1,17 @@ + + + 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 + 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 + 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 + + diff --git a/journeys/security/wallet-wipe-new-profile.xml b/journeys/security/wallet-wipe-new-profile.xml index 602475eb05..8ab6191759 100644 --- a/journeys/security/wallet-wipe-new-profile.xml +++ b/journeys/security/wallet-wipe-new-profile.xml @@ -11,6 +11,7 @@ Return Home and leave the app active for at least 10 seconds so background Paykit work can run Open Settings, select Security, and open Reset wallet (identifier "ResetAndRestore") Tap Reset Wallet and confirm the reset + While reset is running, verify only busy progress is offered: no failed-reset message, second Reset action or seed display Wait for reset to finish and verify wallet onboarding is visible Accept the terms, skip the introduction, and create a new wallet Wait for Home, then open Profile from the header diff --git a/journeys/wallet/restore-during-identity-outage.xml b/journeys/wallet/restore-during-identity-outage.xml new file mode 100644 index 0000000000..e549f8d36a --- /dev/null +++ b/journeys/wallet/restore-during-identity-outage.xml @@ -0,0 +1,19 @@ + + + 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 + Fail the restored identity's own public profile read, then reconnect or resume while staying on Home; verify wallet maintenance continues while the read is held, and the saved profile replaces the placeholder after release without opening Profile or re-importing the active session + Repeat with delayed profile/contact enrichment, then replace or remove the identity; verify late results cannot republish the old identity or overwrite current profile data + Restart during the outage; verify saved credentials resume recovery without duplicating a payment or contact mutation + Fail a required wallet or USDT restore instead; verify spending and address allocation remain gated and retry resumes the same required recovery + +