From 51f95a17c44cdf2c9b0a666c991e750503ce7a1c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 16:33:27 +0100 Subject: [PATCH 1/6] fix: offer existing server accounts on re-approval Verified: just test (7034 tests; ElectrumProbeServiceTest unreachable-host case failed under load and passes alone, untouched by this change), just lint, PubkyAuthApprovalViewModelTest and WatchOnlyAccountRepoTest after the last edit --- .../repositories/WatchOnlyAccountRepo.kt | 41 +++- .../screens/profile/PubkyAuthApprovalSheet.kt | 132 +++++++++++-- .../profile/PubkyAuthApprovalViewModel.kt | 90 +++++++-- app/src/main/res/values/strings.xml | 3 + .../repositories/WatchOnlyAccountRepoTest.kt | 58 ++++++ .../profile/PubkyAuthApprovalViewModelTest.kt | 187 +++++++++++++++++- changelog.d/next/2237.fixed.md | 1 + journeys/pubky-marketplace/README.md | 1 + .../reapprove-server-account.xml | 23 +++ 9 files changed, 495 insertions(+), 41 deletions(-) create mode 100644 changelog.d/next/2237.fixed.md create mode 100644 journeys/pubky-marketplace/reapprove-server-account.xml diff --git a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt index 83f26930f1..c9cbea764e 100644 --- a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt @@ -64,18 +64,34 @@ class WatchOnlyAccountRepo @Inject constructor( } val currentWalletAccountCount: Flow = currentWalletAccounts.map { it.size } - suspend fun prepareUnsignedClaim(authUrl: String, name: String): PreparedWatchOnlyAccountClaim = + /** + * Prepares the claim for a Paykit server approval. With [reuseAccountId] the claim shares that active account + * of the current wallet again instead of reserving a new one; the user picks it when re-approving a server. + */ + suspend fun prepareUnsignedClaim( + authUrl: String, + name: String, + reuseAccountId: String? = null, + ): PreparedWatchOnlyAccountClaim = withContext(bgDispatcher) { lifecycleCoordinator.withLock { - val normalizedName = normalizeName(name) val walletIndex = lightningService.currentWalletIndex val fingerprint = requestFingerprint(authUrl) val current = store.load() - current.firstOrNull { - it.walletIndex == walletIndex && - it.requestFingerprint == fingerprint && - it.setupState != WatchOnlyAccountSetupState.Active - }?.let { existing -> + val incomplete = current.incompleteSetup(walletIndex, fingerprint) + if (reuseAccountId != null && incomplete == null) { + val reused = current.firstOrNull { + it.id == reuseAccountId && + it.walletIndex == walletIndex && + it.setupState == WatchOnlyAccountSetupState.Active + } ?: throw WatchOnlyAccountError.AuthorizationAccountMissing() + return@withLock PreparedWatchOnlyAccountClaim( + account = reused, + payload = WatchOnlyAccountClaimCodec.encode(reused, xpubSerializer::serialize), + ) + } + val normalizedName = normalizeName(name) + incomplete?.let { existing -> val refreshed = existing.copy(name = normalizedName) if (refreshed != existing) { store.save(current.map { if (it.id == existing.id) refreshed else it }) @@ -297,6 +313,17 @@ class WatchOnlyAccountRepo @Inject constructor( } } + /** Whether this request already has an account whose setup has not finished; approving it resumes that account. */ + suspend fun hasIncompleteSetup(authUrl: String): Boolean = withContext(bgDispatcher) { + store.load().incompleteSetup(lightningService.currentWalletIndex, requestFingerprint(authUrl)) != null + } + + private fun List.incompleteSetup(walletIndex: Int, fingerprint: String) = firstOrNull { + it.walletIndex == walletIndex && + it.requestFingerprint == fingerprint && + it.setupState != WatchOnlyAccountSetupState.Active + } + private fun normalizeName(name: String): String { val normalized = name.trim() if (normalized.isEmpty() || normalized.length > MAX_NAME_LENGTH) { diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt index 3621d40178..89a5b654c6 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt @@ -52,6 +52,8 @@ import to.bitkit.models.PubkyAuthClaim import to.bitkit.models.PubkyAuthClaim.Item import to.bitkit.models.PubkyAuthPermission import to.bitkit.models.PubkyProfile +import to.bitkit.models.WatchOnlyAccountRecord +import to.bitkit.models.WatchOnlyAccountSetupState import to.bitkit.ui.appViewModel import to.bitkit.ui.components.AuthCheckView import to.bitkit.ui.components.BiometricsView @@ -71,6 +73,8 @@ import to.bitkit.ui.components.SecondaryButton import to.bitkit.ui.components.SheetSize import to.bitkit.ui.components.Text13Up import to.bitkit.ui.components.VerticalSpacer +import to.bitkit.ui.components.settings.SettingsButtonRow +import to.bitkit.ui.components.settings.SettingsButtonValue import to.bitkit.ui.scaffold.SheetTopBar import to.bitkit.ui.settingsViewModel import to.bitkit.ui.shared.modifiers.sheetHeight @@ -106,9 +110,11 @@ fun PubkyAuthApprovalSheet( onApproveWatchOnly = { if (uiState.authUrl == authUrl) viewModel.approveWatchOnlyConsent(authUrl) }, - onBackToWatchOnly = { - if (uiState.authUrl == authUrl) viewModel.returnToWatchOnlyConsent(authUrl) + onBack = { + if (uiState.authUrl == authUrl) viewModel.returnToPreviousStep(authUrl) }, + onSelectAccount = { viewModel.selectAccount(authUrl, it) }, + onConfirmAccount = { viewModel.confirmAccountChoice(authUrl) }, onRetryUsdt = { viewModel.loadUsdtAddress(authUrl) }, onShareUsdt = viewModel::setShareUsdt, onCancel = { viewModel.dismiss() }, @@ -222,18 +228,20 @@ private fun Content( isCurrentRequest: Boolean, onAuthorize: () -> Unit, onApproveWatchOnly: () -> Unit, - onBackToWatchOnly: () -> Unit, + onBack: () -> Unit, onCancel: () -> Unit, onDismiss: () -> Unit, onRetryUsdt: () -> Unit = {}, onShareUsdt: (Boolean) -> Unit = {}, + onSelectAccount: (String?) -> Unit = {}, + onConfirmAccount: () -> Unit = {}, ) { val approvalState = if (isCurrentRequest) uiState.state else ApprovalState.Loading val headerTitle = approvalHeaderTitle(approvalState) - val onBack = approvalBackAction( + val onBackAction = approvalBackAction( approvalState = approvalState, showsReceivingDetails = uiState.showsReceivingDetails, - onBackToWatchOnly = onBackToWatchOnly, + onBack = onBack, onCancel = onCancel, onDismiss = onDismiss, ) @@ -247,7 +255,7 @@ private fun Content( ) { SheetTopBar( titleText = headerTitle, - onBack = onBack, + onBack = onBackAction, titleStyle = if (approvalState == ApprovalState.WatchOnlyConsent) { AppTextStyles.Subtitle.copy(letterSpacing = 0.sp, lineHeight = 22.sp) } else { @@ -264,6 +272,12 @@ private fun Content( onApprove = onApproveWatchOnly, onCancel = onCancel, ) + ApprovalState.ChooseAccount -> ChooseAccountContent( + uiState = uiState, + onSelect = onSelectAccount, + onContinue = onConfirmAccount, + onCancel = onCancel, + ) ApprovalState.Authorize -> AuthorizeContent( uiState = uiState, onAuthorize = onAuthorize, @@ -283,6 +297,7 @@ private fun Content( @Composable private fun approvalHeaderTitle(approvalState: ApprovalState): String = when (approvalState) { ApprovalState.WatchOnlyConsent -> stringResource(R.string.profile__auth_approval_watch_only_intro_nav_title) + ApprovalState.ChooseAccount -> stringResource(R.string.profile__auth_approval_account_nav_title) ApprovalState.Success -> stringResource(R.string.profile__auth_approval_success) else -> stringResource(R.string.profile__auth_approval_title) } @@ -290,11 +305,12 @@ private fun approvalHeaderTitle(approvalState: ApprovalState): String = when (ap private fun approvalBackAction( approvalState: ApprovalState, showsReceivingDetails: Boolean, - onBackToWatchOnly: () -> Unit, + onBack: () -> Unit, onCancel: () -> Unit, onDismiss: () -> Unit, ): (() -> Unit)? = when (approvalState) { - ApprovalState.Authorize if showsReceivingDetails -> onBackToWatchOnly + ApprovalState.ChooseAccount -> onBack + ApprovalState.Authorize if showsReceivingDetails -> onBack ApprovalState.Authorize, ApprovalState.Authenticating, ApprovalState.Authorizing -> onCancel ApprovalState.Success -> onDismiss else -> null @@ -369,6 +385,60 @@ private fun ColumnScope.WatchOnlyConsentContent( VerticalSpacer(16.dp) } +@Composable +private fun ColumnScope.ChooseAccountContent( + uiState: PubkyAuthApprovalUiState, + onSelect: (String?) -> Unit, + onContinue: () -> Unit, + onCancel: () -> Unit, +) { + Column( + modifier = Modifier + .weight(1f) + .verticalScroll(rememberScrollState()) + .testTag("PubkyAuthChooseAccount") + ) { + VerticalSpacer(8.dp) + BodyM( + text = stringResource(R.string.profile__auth_approval_account_description), + color = Colors.White64, + letterSpacing = 0.sp, + ) + VerticalSpacer(16.dp) + uiState.existingAccounts.forEach { account -> + SettingsButtonRow( + title = account.name, + subtitle = account.derivationPath, + value = SettingsButtonValue.BooleanValue(uiState.selectedAccountId == account.id), + onClick = { onSelect(account.id) }, + modifier = Modifier.testTag("PubkyAuthAccount_${account.accountIndex}") + ) + } + SettingsButtonRow( + title = stringResource(R.string.profile__auth_approval_account_new), + value = SettingsButtonValue.BooleanValue(uiState.selectedAccountId == null), + onClick = { onSelect(null) }, + modifier = Modifier.testTag("PubkyAuthAccountNew") + ) + } + VerticalSpacer(32.dp) + Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { + SecondaryButton( + text = stringResource(R.string.common__cancel), + onClick = onCancel, + textStyle = AppTextStyles.BodySSB.copy(letterSpacing = 0.sp), + modifier = Modifier.weight(1f) + ) + PrimaryButton( + text = stringResource(R.string.common__continue), + onClick = onContinue, + textStyle = AppTextStyles.BodySSB.copy(letterSpacing = 0.sp), + modifier = Modifier.weight(1f).testTag("PubkyAuthAccountContinue") + ) + } + VerticalSpacer(16.dp) +} + @Composable private fun UsdtSharingChoice( uiState: PubkyAuthApprovalUiState, @@ -833,7 +903,7 @@ private fun WatchOnlyConsentPreview() { isCurrentRequest = true, onAuthorize = {}, onApproveWatchOnly = {}, - onBackToWatchOnly = {}, + onBack = {}, onCancel = {}, onDismiss = {}, ) @@ -841,6 +911,46 @@ private fun WatchOnlyConsentPreview() { } } +@Preview(showSystemUi = true) +@Composable +private fun ChooseAccountPreview() { + AppThemeSurface { + BottomSheetPreview { + Content( + uiState = PubkyAuthApprovalUiState( + state = ApprovalState.ChooseAccount, + serviceName = "paykit", + bitkitClaim = PubkyAuthClaim(Item.PAYKIT_ACCESS_V1, Item.WATCH_ONLY_ACCOUNT_V1), + existingAccounts = persistentListOf( + previewAccount(id = "1", accountIndex = 1, name = "paykit server"), + previewAccount(id = "2", accountIndex = 2, name = "shop server"), + ), + selectedAccountId = "1", + ), + isCurrentRequest = true, + onAuthorize = {}, + onApproveWatchOnly = {}, + onBack = {}, + onCancel = {}, + onDismiss = {}, + ) + } + } +} + +private fun previewAccount(id: String, accountIndex: Int, name: String) = WatchOnlyAccountRecord( + id = id, + walletIndex = 0, + accountIndex = accountIndex, + addressType = "nativeSegwit", + xpub = "", + requestFingerprint = "", + createdAt = 0, + name = name, + isTrackingEnabled = true, + setupState = WatchOnlyAccountSetupState.Active, +) + @Preview(showSystemUi = true) @Composable private fun AuthorizePreview() { @@ -868,7 +978,7 @@ private fun AuthorizePreview() { isCurrentRequest = true, onAuthorize = {}, onApproveWatchOnly = {}, - onBackToWatchOnly = {}, + onBack = {}, onCancel = {}, onDismiss = {}, ) @@ -890,7 +1000,7 @@ private fun SuccessPreview() { isCurrentRequest = true, onAuthorize = {}, onApproveWatchOnly = {}, - onBackToWatchOnly = {}, + onBack = {}, onCancel = {}, onDismiss = {}, ) diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt index 7af36f1a84..aa76874002 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt @@ -25,6 +25,7 @@ import to.bitkit.models.PubkyAuthRequest import to.bitkit.models.PubkyAuthRequestError import to.bitkit.models.PubkyProfile import to.bitkit.models.Toast +import to.bitkit.models.WatchOnlyAccountRecord import to.bitkit.models.WatchOnlyAccountSetupState import to.bitkit.repositories.Endpoint import to.bitkit.repositories.PubkyAlreadySignedInError @@ -129,6 +130,15 @@ class PubkyAuthApprovalViewModel @Inject constructor( return@launch } val profile = approvalProfile(identityPublicKey) + val existingAccounts = if (request.bitkitClaim?.sharesBitcoin == true && + !watchOnlyAccountRepo.hasIncompleteSetup(authUrl) + ) { + watchOnlyAccountRepo.currentWalletAccounts.first() + .filter { it.setupState == WatchOnlyAccountSetupState.Active } + } else { + emptyList() + } + if (_uiState.value.authUrl != authUrl) return@launch _uiState.update { it.copy( state = if (request.bitkitClaim?.sharesBitcoin == true || @@ -148,6 +158,9 @@ class PubkyAuthApprovalViewModel @Inject constructor( profile = profile, isUsdtEnabled = usdtEnabled, shareUsdt = usdtEnabled, + existingAccounts = existingAccounts.toImmutableList(), + selectedAccountId = existingAccounts.takeIf { accounts -> accounts.isNotEmpty() } + ?.let { accounts -> preselectedAccountId(accounts, defaultWatchOnlyAccountName(request)) }, ) } if (usdtEnabled) loadUsdtAddress(authUrl) @@ -198,27 +211,49 @@ class PubkyAuthApprovalViewModel @Inject constructor( fun approveWatchOnlyConsent(authUrl: String) { _uiState.update { state -> if (state.authUrl == authUrl && state.state == ApprovalState.WatchOnlyConsent && state.canAuthorize) { - state.copy(state = ApprovalState.Authorize) + state.copy( + state = if (state.showsAccountChoice) ApprovalState.ChooseAccount else ApprovalState.Authorize, + ) } else { state } } } - fun returnToWatchOnlyConsent(authUrl: String) { + /** Selects the existing account to share again, or `null` for a new account. */ + fun selectAccount(authUrl: String, accountId: String?) { _uiState.update { state -> - if ( - state.authUrl == authUrl && - state.state == ApprovalState.Authorize && - state.showsReceivingDetails - ) { - state.copy(state = ApprovalState.WatchOnlyConsent) + if (state.authUrl == authUrl && state.state == ApprovalState.ChooseAccount) { + state.copy(selectedAccountId = accountId) + } else { + state + } + } + } + + fun confirmAccountChoice(authUrl: String) { + _uiState.update { state -> + if (state.authUrl == authUrl && state.state == ApprovalState.ChooseAccount) { + state.copy(state = ApprovalState.Authorize) } else { state } } } + fun returnToPreviousStep(authUrl: String) { + _uiState.update { state -> + if (state.authUrl != authUrl) return@update state + when { + state.state == ApprovalState.ChooseAccount -> state.copy(state = ApprovalState.WatchOnlyConsent) + state.state != ApprovalState.Authorize -> state + state.showsAccountChoice -> state.copy(state = ApprovalState.ChooseAccount) + state.showsReceivingDetails -> state.copy(state = ApprovalState.WatchOnlyConsent) + else -> state + } + } + } + fun cancelLocalAuth(authUrl: String) { _uiState.update { state -> if (state.authUrl == authUrl && state.state == ApprovalState.Authenticating) { @@ -261,7 +296,8 @@ class PubkyAuthApprovalViewModel @Inject constructor( handleApprovalFailure(PubkyAuthRequestError.RequesterChanged, authUrl) return } - if (!approveRequest(request, authUrl, approvalState.createsIdentity)) return + val reuseAccountId = approvalState.selectedAccountId.takeIf { approvalState.showsAccountChoice } + if (!approveRequest(request, authUrl, approvalState.createsIdentity, reuseAccountId)) return Logger.info("Auth approved for '${request.serviceNames.firstOrNull().orEmpty()}'", context = TAG) if (approvalState.createsIdentity) { @@ -277,6 +313,7 @@ class PubkyAuthApprovalViewModel @Inject constructor( request: PubkyAuthRequest, authUrl: String, createsIdentity: Boolean, + reuseAccountId: String?, ): Boolean = if (createsIdentity) { pubkyRepo.approveSignupAuth(request).fold( onSuccess = { true }, @@ -286,12 +323,13 @@ class PubkyAuthApprovalViewModel @Inject constructor( }, ) } else { - approveSignInRequest(request, authUrl) + approveSignInRequest(request, authUrl, reuseAccountId) } private suspend fun approveSignInRequest( request: PubkyAuthRequest, authUrl: String, + reuseAccountId: String?, ): Boolean { if (request.expectedSigner != null) { pubkyRepo.checkExpectedSigner(authUrl).onFailure { @@ -308,7 +346,7 @@ class PubkyAuthApprovalViewModel @Inject constructor( } val preparedClaim = runSuspendCatching { if (request.bitkitClaim?.sharesBitcoin == true) { - watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, defaultWatchOnlyAccountName(request)) + watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, defaultWatchOnlyAccountName(request), reuseAccountId) } else { null } @@ -317,8 +355,10 @@ class PubkyAuthApprovalViewModel @Inject constructor( return false } + // A reused account is already active: it skips the setup states and only needs tracking on after approval. + val isReused = preparedClaim?.account?.setupState == WatchOnlyAccountSetupState.Active var preserveAuthorizingState = preparedClaim?.account?.setupState == WatchOnlyAccountSetupState.Authorizing - preparedClaim?.let { claim -> + preparedClaim?.takeUnless { isReused }?.let { claim -> runSuspendCatching { watchOnlyAccountRepo.beginAuthorization(claim.account.id) } .onSuccess { preserveAuthorizingState = it } .getOrElse { @@ -345,8 +385,12 @@ class PubkyAuthApprovalViewModel @Inject constructor( if (approvalResult.isFailure) { val approvalError = checkNotNull(approvalResult.exceptionOrNull()) { "Authorization failed" } preparedClaim?.let { claim -> - if (!approvalError.isPostDeliveryAuthorizationFailure()) { - cancelIncompleteSetup( + when { + // The server already holds the reused account, so it is tracked as after a successful approval. + isReused && approvalError.isPostDeliveryAuthorizationFailure() -> runSuspendCatching { + watchOnlyAccountRepo.setTrackingEnabled(claim.account.id, enabled = true) + } + !isReused && !approvalError.isPostDeliveryAuthorizationFailure() -> cancelIncompleteSetup( claim.account.id, preserveAuthorizingState, ) @@ -357,7 +401,13 @@ class PubkyAuthApprovalViewModel @Inject constructor( } return runSuspendCatching { - preparedClaim?.let { watchOnlyAccountRepo.markActive(it.account.id) } + preparedClaim?.let { + if (isReused) { + watchOnlyAccountRepo.setTrackingEnabled(it.account.id, enabled = true) + } else { + watchOnlyAccountRepo.markActive(it.account.id) + } + } }.onFailure { handleApprovalFailure(it, authUrl) }.isSuccess } @@ -439,6 +489,12 @@ class PubkyAuthApprovalViewModel @Inject constructor( return context.getString(R.string.profile__auth_approval_watch_only_account_default_name, serviceName) } + /** A same-name account is preselected, tracked first, then newest; with none, a new account keeps servers apart. */ + private fun preselectedAccountId(accounts: List, name: String): String? = accounts + .filter { it.name == name.trim() } + .maxWithOrNull(compareBy { it.isTrackingEnabled }.thenBy { it.createdAt }) + ?.id + private fun approvalProfile(identityPublicKey: String?): PubkyProfile? { pubkyRepo.profile.value?.let { return it } val publicKey = identityPublicKey ?: return null @@ -470,7 +526,10 @@ data class PubkyAuthApprovalUiState( val usdtUnavailable: Boolean = false, val shareUsdt: Boolean = true, val isUsdtEnabled: Boolean = false, + val existingAccounts: ImmutableList = persistentListOf(), + val selectedAccountId: String? = null, ) { + val showsAccountChoice: Boolean get() = bitkitClaim?.sharesBitcoin == true && existingAccounts.isNotEmpty() val showsUsdtDetails: Boolean get() = bitkitClaim?.sharesUsdt == true && isUsdtEnabled val showsReceivingDetails: Boolean get() = bitkitClaim?.sharesBitcoin == true || showsUsdtDetails val usdtRequired: Boolean get() = bitkitClaim?.requiresUsdtAddress == true @@ -483,6 +542,7 @@ data class PubkyAuthApprovalUiState( sealed interface ApprovalState { data object Loading : ApprovalState data object WatchOnlyConsent : ApprovalState + data object ChooseAccount : ApprovalState data object Authorize : ApprovalState data object Authenticating : ApprovalState data object Authorizing : ApprovalState diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c930a202b0..d40806d509 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -767,6 +767,9 @@ Add Tag TAG For example: \'Developer\' + Choose the Bitcoin account this server can view. A new account keeps this server apart from your other servers. + Bitcoin Account + New account Authorize Authorizing… Before you continue diff --git a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt index 20dcdb3150..3c7d0aaf9f 100644 --- a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt @@ -76,6 +76,64 @@ class WatchOnlyAccountRepoTest : BaseUnitTest() { verify(node, never()).addOnchainWalletAccount(any(), any(), any()) } + @Test + fun `chosen active account is shared again without reserving an index`() = test { + val active = account() + val store = mock() + val lightningService = mock() + whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = listOf(active)))) + whenever(store.load()).thenReturn(listOf(active)) + + val prepared = repository(store, lightningService).prepareUnsignedClaim( + "pubkyauth://signin?secret=again&x-bitkit-claim=watch-only-account-v1", + "paykit server", + reuseAccountId = active.id, + ) + + assertSame(active, prepared.account) + assertEquals(WatchOnlyAccountClaimCodec.PAYLOAD_LENGTH, prepared.payload.size) + verify(store, never()).reserveAccountIndex(any(), any()) + verify(store, never()).save(any()) + } + + @Test + fun `unfinished setup for the request is resumed instead of a chosen account`() = test { + val active = account() + val pending = account().copy( + id = "pending", + accountIndex = 2, + requestFingerprint = RESTORED_REQUEST_FINGERPRINT, + setupState = WatchOnlyAccountSetupState.Authorizing, + ) + val store = mock() + whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = listOf(active, pending)))) + whenever(store.load()).thenReturn(listOf(active, pending)) + val sut = repository(store, mock()) + + assertTrue(sut.hasIncompleteSetup(RESTORED_AUTH_URL)) + val prepared = sut.prepareUnsignedClaim(RESTORED_AUTH_URL, "paykit server", reuseAccountId = active.id) + + assertEquals(pending.id, prepared.account.id) + verify(store, never()).reserveAccountIndex(any(), any()) + } + + @Test + fun `chosen account must be active on the current wallet`() = test { + val pending = account().copy(setupState = WatchOnlyAccountSetupState.PendingDelivery) + val otherWallet = account().copy(id = "other-wallet", walletIndex = 1) + val store = mock() + whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = listOf(pending, otherWallet)))) + whenever(store.load()).thenReturn(listOf(pending, otherWallet)) + val sut = repository(store, mock()) + + listOf(pending.id, otherWallet.id, "missing").forEach { id -> + assertFailsWith { + sut.prepareUnsignedClaim("pubkyauth://signin?secret=again", "paykit server", reuseAccountId = id) + } + } + verify(store, never()).reserveAccountIndex(any(), any()) + } + @Test fun `authorization rejects an active account before tracking`() = test { val active = account() diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt index 881f49c1a9..43467d9f75 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt @@ -19,6 +19,7 @@ import org.junit.Before import org.junit.Test import org.mockito.Mockito.mockStatic import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argThat import org.mockito.kotlin.clearInvocations import org.mockito.kotlin.doReturn @@ -75,7 +76,11 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { } private val usdtEnabled = MutableStateFlow(true) private val usdtRepo: UsdtRepo = mock() - private val watchOnlyAccountRepo: WatchOnlyAccountRepo = mock() + private val existingAccounts = MutableStateFlow>(emptyList()) + private val watchOnlyAccountRepo: WatchOnlyAccountRepo = mock { + on { currentWalletAccounts } doReturn existingAccounts + onBlocking { hasIncompleteSetup(any()) } doReturn false + } @Before fun setUp() { @@ -171,7 +176,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { sut.dismiss() advanceUntilIdle() - verifyNoInteractions(watchOnlyAccountRepo) + verifyNoAccountChanges() verifyBlocking(pubkyRepo, never()) { approveAuthWithCompanionClaim(any(), any(), any()) } } @@ -219,7 +224,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { advanceUntilIdle() } assertEquals(ApprovalState.Authorize, sut.uiState.value.state) - verifyBlocking(watchOnlyAccountRepo, never()) { prepareUnsignedClaim(any(), any()) } + verifyBlocking(watchOnlyAccountRepo, never()) { prepareUnsignedClaim(any(), any(), anyOrNull()) } verifyBlocking(pubkyRepo, never()) { approveAuthWithCompanionClaim(any(), any(), any()) } } @@ -366,7 +371,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { assertEquals("https://httprelay.pubky.app/inbox/", sut.uiState.value.relayUrl) verifyBlocking(pubkyRepo) { approveAuth(authUrl, capabilities, clientId) } verifyBlocking(pubkyRepo, never()) { approveAuthWithCompanionClaim(any(), any(), any()) } - verifyBlocking(watchOnlyAccountRepo, never()) { prepareUnsignedClaim(any(), any()) } + verifyBlocking(watchOnlyAccountRepo, never()) { prepareUnsignedClaim(any(), any(), anyOrNull()) } } @Test @@ -431,7 +436,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { assertEquals(ApprovalState.Authorize, sut.uiState.value.state) assertEquals("This request is for 5jsj...tryo, not this wallet's pubky.", toasts.single().description) - verifyNoInteractions(watchOnlyAccountRepo) + verifyNoAccountChanges() verifyBlocking(pubkyRepo, never()) { approveAuth(any(), any(), any()) } verifyBlocking(pubkyRepo, never()) { approveAuthWithCompanionClaim(any(), any(), any()) } toastJob.cancel() @@ -728,7 +733,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { sut.cancelLocalAuth(authUrl) assertEquals(ApprovalState.Authorize, sut.uiState.value.state) - sut.returnToWatchOnlyConsent(authUrl) + sut.returnToPreviousStep(authUrl) assertEquals(ApprovalState.WatchOnlyConsent, sut.uiState.value.state) } @@ -1155,7 +1160,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { ) verifyBlocking(watchOnlyAccountRepo) { markActive(prepared.account.id) } } else { - verifyBlocking(watchOnlyAccountRepo, never()) { prepareUnsignedClaim(any(), any()) } + verifyBlocking(watchOnlyAccountRepo, never()) { prepareUnsignedClaim(any(), any(), anyOrNull()) } } } } @@ -1177,7 +1182,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { assertEquals(ApprovalState.Authorize, sut.uiState.value.state) assertFalse(sut.uiState.value.shareUsdt) assertTrue(sut.uiState.value.canAuthorize) - sut.returnToWatchOnlyConsent(url) + sut.returnToPreviousStep(url) assertFalse(sut.uiState.value.shareUsdt) sut.setShareUsdt(true) assertTrue(sut.uiState.value.shareUsdt) @@ -1391,6 +1396,172 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { return url } + @Test + fun `re-approval preselects the same-name account and shares it again`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=paykit-access-v1.watch-only-account-v1" + val request = authRequest( + authUrl, + PubkyAuthClaim.REQUIRED_CAPABILITIES, + PubkyAuthClaim(Item.PAYKIT_ACCESS_V1, Item.WATCH_ONLY_ACCOUNT_V1), + ) + val untracked = activeAccount(id = "old", accountIndex = 1, isTrackingEnabled = false, createdAt = 3) + val tracked = activeAccount(id = "tracked", accountIndex = 2, createdAt = 1) + val newer = activeAccount(id = "newer", accountIndex = 3, createdAt = 2) + val other = activeAccount(id = "other", accountIndex = 4, name = "shop server", createdAt = 4) + existingAccounts.value = listOf(untracked, tracked, newer, other, watchOnlyAccount()) + val prepared = PreparedWatchOnlyAccountClaim(newer, ByteArray(84)) + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn(Result.success(request)) + whenever(watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, "paykit server", newer.id)).thenReturn(prepared) + whenever(pubkyRepo.approveAuthWithCompanionClaim(authUrl, clientId, prepared.payload)) + .thenReturn(Result.success(Unit)) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + sut.approveWatchOnlyConsent(authUrl) + + assertEquals(ApprovalState.ChooseAccount, sut.uiState.value.state) + assertEquals(listOf(untracked, tracked, newer, other), sut.uiState.value.existingAccounts) + assertEquals(newer.id, sut.uiState.value.selectedAccountId) + + sut.confirmAccountChoice(authUrl) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + + assertEquals(ApprovalState.Success, sut.uiState.value.state) + verifyBlocking(watchOnlyAccountRepo) { setTrackingEnabled(newer.id, true) } + verifyBlocking(watchOnlyAccountRepo, never()) { beginAuthorization(any()) } + verifyBlocking(watchOnlyAccountRepo, never()) { markActive(any()) } + } + + @Test + fun `re-approval with no same-name account preselects a new account`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn( + Result.success( + authRequest(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1)), + ), + ) + existingAccounts.value = listOf(activeAccount(id = "other", accountIndex = 1, name = "shop server")) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + sut.approveWatchOnlyConsent(authUrl) + + assertEquals(ApprovalState.ChooseAccount, sut.uiState.value.state) + assertEquals(null, sut.uiState.value.selectedAccountId) + + sut.selectAccount(authUrl, "other") + sut.confirmAccountChoice(authUrl) + sut.returnToPreviousStep(authUrl) + assertEquals(ApprovalState.ChooseAccount, sut.uiState.value.state) + assertEquals("other", sut.uiState.value.selectedAccountId) + sut.returnToPreviousStep(authUrl) + assertEquals(ApprovalState.WatchOnlyConsent, sut.uiState.value.state) + } + + @Test + fun `choosing a new account beside existing ones sets up a new account`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" + existingAccounts.value = listOf(activeAccount(id = "old", accountIndex = 1)) + val prepared = PreparedWatchOnlyAccountClaim(watchOnlyAccount(), ByteArray(84)) + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn( + Result.success( + authRequest(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1)), + ), + ) + whenever(watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, "paykit server", null)).thenReturn(prepared) + whenever(watchOnlyAccountRepo.beginAuthorization(prepared.account.id)).thenReturn(false) + whenever(pubkyRepo.approveAuthWithCompanionClaim(authUrl, clientId, prepared.payload)) + .thenReturn(Result.success(Unit)) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + sut.approveWatchOnlyConsent(authUrl) + sut.selectAccount(authUrl, null) + sut.confirmAccountChoice(authUrl) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + + assertEquals(ApprovalState.Success, sut.uiState.value.state) + verifyBlocking(watchOnlyAccountRepo) { beginAuthorization(prepared.account.id) } + verifyBlocking(watchOnlyAccountRepo) { markActive(prepared.account.id) } + verifyBlocking(watchOnlyAccountRepo, never()) { setTrackingEnabled(any(), any()) } + } + + @Test + fun `reused account is tracked when authorization fails after delivery`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" + val reused = activeAccount(id = "old", accountIndex = 1, isTrackingEnabled = false) + existingAccounts.value = listOf(reused) + val prepared = PreparedWatchOnlyAccountClaim(reused, ByteArray(84)) + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn( + Result.success( + authRequest(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1)), + ), + ) + whenever(watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, "paykit server", reused.id)).thenReturn(prepared) + whenever(pubkyRepo.approveAuthWithCompanionClaim(authUrl, clientId, prepared.payload)).thenReturn( + Result.failure(PubkyAuthCompanionClaimApprovalException.AuthorizationFailure("AuthToken delivery failed")), + ) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + sut.approveWatchOnlyConsent(authUrl) + sut.confirmAccountChoice(authUrl) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + + verifyBlocking(watchOnlyAccountRepo) { setTrackingEnabled(reused.id, true) } + verifyBlocking(watchOnlyAccountRepo, never()) { cancelAuthorization(any(), any()) } + verifyBlocking(watchOnlyAccountRepo, never()) { markActive(any()) } + } + + @Test + fun `unfinished setup for the request skips the account choice`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" + existingAccounts.value = listOf(activeAccount(id = "old", accountIndex = 1)) + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn( + Result.success( + authRequest(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1)), + ), + ) + whenever(watchOnlyAccountRepo.hasIncompleteSetup(authUrl)).thenReturn(true) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + sut.approveWatchOnlyConsent(authUrl) + + assertEquals(ApprovalState.Authorize, sut.uiState.value.state) + assertTrue(sut.uiState.value.existingAccounts.isEmpty()) + } + + private suspend fun verifyNoAccountChanges() { + verify(watchOnlyAccountRepo, never()).prepareUnsignedClaim(any(), any(), anyOrNull()) + verify(watchOnlyAccountRepo, never()).beginAuthorization(any()) + verify(watchOnlyAccountRepo, never()).setTrackingEnabled(any(), any()) + verify(watchOnlyAccountRepo, never()).markActive(any()) + } + + private fun activeAccount( + id: String, + accountIndex: Int, + name: String = "paykit server", + isTrackingEnabled: Boolean = true, + createdAt: Long = 1, + ) = watchOnlyAccount().copy( + id = id, + accountIndex = accountIndex, + name = name, + isTrackingEnabled = isTrackingEnabled, + createdAt = createdAt, + setupState = WatchOnlyAccountSetupState.Active, + ) + private fun createSut() = PubkyAuthApprovalViewModel( context = context, pubkyRepo = pubkyRepo, diff --git a/changelog.d/next/2237.fixed.md b/changelog.d/next/2237.fixed.md new file mode 100644 index 0000000000..5c8bbd2c7d --- /dev/null +++ b/changelog.d/next/2237.fixed.md @@ -0,0 +1 @@ +Re-approving a Paykit server now offers to share an existing server account instead of always creating a new one. diff --git a/journeys/pubky-marketplace/README.md b/journeys/pubky-marketplace/README.md index 4f3448fe07..f4a347fbc8 100644 --- a/journeys/pubky-marketplace/README.md +++ b/journeys/pubky-marketplace/README.md @@ -16,6 +16,7 @@ The companion journey is shared with iOS; only platform build instructions diffe - `paykit-only-approval.xml` checks Paykit-only consent and cancellation without account creation. - `paykit-reconnect.xml` checks Paykit-only reconnect consent and cancellation without changing the existing service account. +- `reapprove-server-account.xml` checks that re-approving a server offers its existing account, preselected by name, keeps one account when it is reused and adds one only when "New account" is chosen. - `approval-while-node-restarts.xml` checks that a Bitcoin watch-only setup approved while the node is stopped or rebuilding completes on the first Authorize and is tracked once the node starts. These visible consent and cancel checks require valid auth URL fixtures but do not authorize a diff --git a/journeys/pubky-marketplace/reapprove-server-account.xml b/journeys/pubky-marketplace/reapprove-server-account.xml new file mode 100644 index 0000000000..3151ee5342 --- /dev/null +++ b/journeys/pubky-marketplace/reapprove-server-account.xml @@ -0,0 +1,23 @@ + + + Verifies that re-approving a Paykit server offers the existing server accounts instead of + always creating a new one. Precondition: an isolated wallet with one active server account + created by approving the setup fixture once (combined x-bitkit-claim=paykit-access-v1.watch-only-account-v1), + and a second fresh setup auth URL for the same server. The cancel steps need no live + authorization relay; the approve step needs the same fixture runtime as wallet-leg.xml. + + + Open Settings, Advanced, Server Accounts and record the existing account's name, derivation path and xpub + Open the second setup auth URL in the wallet + Verify the Earn introduction is visible and tap Approve (id "PubkyAuthWatchOnlyApprove") + Verify the account choice (id "PubkyAuthChooseAccount") lists the existing account (id "PubkyAuthAccount_1") with its name and derivation path, and a "New account" row (id "PubkyAuthAccountNew") + Verify the existing account is preselected, since its name matches the server's default account name + Tap Back and verify the Earn introduction is shown again; tap Approve and verify the account choice returns with the same selection + Tap Continue (id "PubkyAuthAccountContinue"), verify the authorization screen, then tap Back and verify the account choice is shown + Tap Cancel and verify Server Accounts still lists exactly one account, unchanged + Open the second setup auth URL again, tap Approve, keep the existing account, tap Continue and Authorize + Verify the success screen, then verify Server Accounts still lists exactly one account with the same derivation path and xpub, tracked + Open a third fresh setup auth URL, tap Approve, select "New account", tap Continue and Authorize + Verify Server Accounts now lists two accounts, the new one at the next derivation path + + From 3b9ed537fbf9180435d0ca79bb4fc0b42d968a70 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 18:10:30 +0100 Subject: [PATCH 2/6] fix: drop the account choice once a setup is unfinished Verified: just test, just lint --- .../screens/profile/PubkyAuthApprovalSheet.kt | 5 +- .../profile/PubkyAuthApprovalViewModel.kt | 34 ++++++++++- .../profile/PubkyAuthApprovalViewModelTest.kt | 60 +++++++++++++++++++ 3 files changed, 94 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt index 89a5b654c6..13b0c612f5 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt @@ -52,6 +52,7 @@ import to.bitkit.models.PubkyAuthClaim import to.bitkit.models.PubkyAuthClaim.Item import to.bitkit.models.PubkyAuthPermission import to.bitkit.models.PubkyProfile +import to.bitkit.models.WATCH_ONLY_ACCOUNT_NATIVE_SEGWIT_ADDRESS_TYPE import to.bitkit.models.WatchOnlyAccountRecord import to.bitkit.models.WatchOnlyAccountSetupState import to.bitkit.ui.appViewModel @@ -427,7 +428,7 @@ private fun ColumnScope.ChooseAccountContent( text = stringResource(R.string.common__cancel), onClick = onCancel, textStyle = AppTextStyles.BodySSB.copy(letterSpacing = 0.sp), - modifier = Modifier.weight(1f) + modifier = Modifier.weight(1f).testTag("PubkyAuthAccountCancel") ) PrimaryButton( text = stringResource(R.string.common__continue), @@ -942,7 +943,7 @@ private fun previewAccount(id: String, accountIndex: Int, name: String) = WatchO id = id, walletIndex = 0, accountIndex = accountIndex, - addressType = "nativeSegwit", + addressType = WATCH_ONLY_ACCOUNT_NATIVE_SEGWIT_ADDRESS_TYPE, xpub = "", requestFingerprint = "", createdAt = 0, diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt index aa76874002..bb111c0bc9 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt @@ -297,7 +297,11 @@ class PubkyAuthApprovalViewModel @Inject constructor( return } val reuseAccountId = approvalState.selectedAccountId.takeIf { approvalState.showsAccountChoice } - if (!approveRequest(request, authUrl, approvalState.createsIdentity, reuseAccountId)) return + if (!approveRequest(request, authUrl, approvalState.createsIdentity, reuseAccountId)) { + // A retry resumes an unfinished new account, so the choice of an existing one is no longer offered. + dropAccountChoiceIfSetupUnfinished(authUrl) + return + } Logger.info("Auth approved for '${request.serviceNames.firstOrNull().orEmpty()}'", context = TAG) if (approvalState.createsIdentity) { @@ -389,6 +393,8 @@ class PubkyAuthApprovalViewModel @Inject constructor( // The server already holds the reused account, so it is tracked as after a successful approval. isReused && approvalError.isPostDeliveryAuthorizationFailure() -> runSuspendCatching { watchOnlyAccountRepo.setTrackingEnabled(claim.account.id, enabled = true) + }.onFailure { + Logger.error("Failed to track reused account '${claim.account.id}'", it, context = TAG) } !isReused && !approvalError.isPostDeliveryAuthorizationFailure() -> cancelIncompleteSetup( claim.account.id, @@ -411,6 +417,25 @@ class PubkyAuthApprovalViewModel @Inject constructor( }.onFailure { handleApprovalFailure(it, authUrl) }.isSuccess } + private suspend fun dropAccountChoiceIfSetupUnfinished(authUrl: String) { + if (!_uiState.value.showsAccountChoice) return + val isUnfinished = runSuspendCatching { watchOnlyAccountRepo.hasIncompleteSetup(authUrl) }.getOrDefault(false) + if (!isUnfinished) return + _uiState.update { state -> + if (state.authUrl == authUrl) { + state.copy( + existingAccounts = persistentListOf(), + selectedAccountId = null, + state = state.state + .takeUnless { it == ApprovalState.ChooseAccount } + ?: ApprovalState.WatchOnlyConsent, + ) + } else { + state + } + } + } + private suspend fun validatedUsdtEndpoint(request: PubkyAuthRequest): Endpoint? { val claim = request.bitkitClaim ?: return null if (!claim.sharesUsdt) return null @@ -489,10 +514,13 @@ class PubkyAuthApprovalViewModel @Inject constructor( return context.getString(R.string.profile__auth_approval_watch_only_account_default_name, serviceName) } - /** A same-name account is preselected, tracked first, then newest; with none, a new account keeps servers apart. */ private fun preselectedAccountId(accounts: List, name: String): String? = accounts .filter { it.name == name.trim() } - .maxWithOrNull(compareBy { it.isTrackingEnabled }.thenBy { it.createdAt }) + .maxWithOrNull( + compareBy { it.isTrackingEnabled } + .thenBy { it.createdAt } + .thenBy { it.accountIndex }, + ) ?.id private fun approvalProfile(identityPublicKey: String?): PubkyProfile? { diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt index 43467d9f75..59a969cbef 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt @@ -58,6 +58,7 @@ import to.bitkit.utils.AppError import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertIs +import kotlin.test.assertNotEquals import kotlin.test.assertTrue @OptIn(ExperimentalCoroutinesApi::class) @@ -1491,6 +1492,37 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { verifyBlocking(watchOnlyAccountRepo, never()) { setTrackingEnabled(any(), any()) } } + @Test + fun `unfinished new account after a failed authorization drops the account choice`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" + existingAccounts.value = listOf(activeAccount(id = "old", accountIndex = 1)) + val prepared = PreparedWatchOnlyAccountClaim(watchOnlyAccount(), ByteArray(84)) + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn( + Result.success( + authRequest(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1)), + ), + ) + whenever(watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, "paykit server", null)).thenReturn(prepared) + whenever(watchOnlyAccountRepo.beginAuthorization(prepared.account.id)).thenReturn(false) + whenever(pubkyRepo.approveAuthWithCompanionClaim(authUrl, clientId, prepared.payload)).thenReturn( + Result.failure(PubkyAuthCompanionClaimApprovalException.AuthorizationFailure("AuthToken delivery failed")), + ) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + sut.approveWatchOnlyConsent(authUrl) + sut.selectAccount(authUrl, null) + sut.confirmAccountChoice(authUrl) + whenever(watchOnlyAccountRepo.hasIncompleteSetup(authUrl)).thenReturn(true) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + sut.returnToPreviousStep(authUrl) + + assertFalse(sut.uiState.value.showsAccountChoice) + assertNotEquals(ApprovalState.ChooseAccount, sut.uiState.value.state) + } + @Test fun `reused account is tracked when authorization fails after delivery`() = test { val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" @@ -1520,6 +1552,34 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { verifyBlocking(watchOnlyAccountRepo, never()) { markActive(any()) } } + @Test + fun `reused account stays untouched when authorization fails before delivery`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" + val reused = activeAccount(id = "old", accountIndex = 1, isTrackingEnabled = false) + existingAccounts.value = listOf(reused) + val prepared = PreparedWatchOnlyAccountClaim(reused, ByteArray(84)) + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn( + Result.success( + authRequest(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1)), + ), + ) + whenever(watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, "paykit server", reused.id)).thenReturn(prepared) + whenever(pubkyRepo.approveAuthWithCompanionClaim(authUrl, clientId, prepared.payload)) + .thenReturn(Result.failure(IllegalStateException("relay unreachable"))) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + sut.approveWatchOnlyConsent(authUrl) + sut.confirmAccountChoice(authUrl) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + + verifyBlocking(watchOnlyAccountRepo, never()) { setTrackingEnabled(any(), any()) } + verifyBlocking(watchOnlyAccountRepo, never()) { cancelAuthorization(any(), any()) } + assertTrue(sut.uiState.value.showsAccountChoice) + } + @Test fun `unfinished setup for the request skips the account choice`() = test { val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" From e3ffa9e84c380f677df26ffaf98ab86dc008a119 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 19:13:39 +0100 Subject: [PATCH 3/6] fix: track a reused account before its claim is sent Verified: just test, just lint --- .../screens/profile/PubkyAuthApprovalSheet.kt | 10 +++- .../profile/PubkyAuthApprovalViewModel.kt | 48 +++++++++++++------ .../profile/PubkyAuthApprovalViewModelTest.kt | 48 +++++++++++++++++-- 3 files changed, 84 insertions(+), 22 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt index 13b0c612f5..2d0b3e88dd 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt @@ -40,6 +40,8 @@ import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @@ -412,14 +414,18 @@ private fun ColumnScope.ChooseAccountContent( subtitle = account.derivationPath, value = SettingsButtonValue.BooleanValue(uiState.selectedAccountId == account.id), onClick = { onSelect(account.id) }, - modifier = Modifier.testTag("PubkyAuthAccount_${account.accountIndex}") + modifier = Modifier + .semantics { selected = uiState.selectedAccountId == account.id } + .testTag("PubkyAuthAccount_${account.accountIndex}") ) } SettingsButtonRow( title = stringResource(R.string.profile__auth_approval_account_new), value = SettingsButtonValue.BooleanValue(uiState.selectedAccountId == null), onClick = { onSelect(null) }, - modifier = Modifier.testTag("PubkyAuthAccountNew") + modifier = Modifier + .semantics { selected = uiState.selectedAccountId == null } + .testTag("PubkyAuthAccountNew") ) } VerticalSpacer(32.dp) diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt index bb111c0bc9..07707751c3 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt @@ -296,7 +296,8 @@ class PubkyAuthApprovalViewModel @Inject constructor( handleApprovalFailure(PubkyAuthRequestError.RequesterChanged, authUrl) return } - val reuseAccountId = approvalState.selectedAccountId.takeIf { approvalState.showsAccountChoice } + val reuseAccountId = approvalState.deliveredAccountId + ?: approvalState.selectedAccountId.takeIf { approvalState.showsAccountChoice } if (!approveRequest(request, authUrl, approvalState.createsIdentity, reuseAccountId)) { // A retry resumes an unfinished new account, so the choice of an existing one is no longer offered. dropAccountChoiceIfSetupUnfinished(authUrl) @@ -359,8 +360,16 @@ class PubkyAuthApprovalViewModel @Inject constructor( return false } - // A reused account is already active: it skips the setup states and only needs tracking on after approval. + // A reused account is already active: it skips the setup states and only needs tracking on. val isReused = preparedClaim?.account?.setupState == WatchOnlyAccountSetupState.Active + // The server can hold the claim as soon as it is sent, so a reused account is tracked before delivery and + // stays tracked whatever the outcome. + preparedClaim?.takeIf { isReused && !it.account.isTrackingEnabled }?.let { claim -> + runSuspendCatching { watchOnlyAccountRepo.setTrackingEnabled(claim.account.id, enabled = true) }.getOrElse { + handleApprovalFailure(it, authUrl) + return false + } + } var preserveAuthorizingState = preparedClaim?.account?.setupState == WatchOnlyAccountSetupState.Authorizing preparedClaim?.takeUnless { isReused }?.let { claim -> runSuspendCatching { watchOnlyAccountRepo.beginAuthorization(claim.account.id) } @@ -390,12 +399,9 @@ class PubkyAuthApprovalViewModel @Inject constructor( val approvalError = checkNotNull(approvalResult.exceptionOrNull()) { "Authorization failed" } preparedClaim?.let { claim -> when { - // The server already holds the reused account, so it is tracked as after a successful approval. - isReused && approvalError.isPostDeliveryAuthorizationFailure() -> runSuspendCatching { - watchOnlyAccountRepo.setTrackingEnabled(claim.account.id, enabled = true) - }.onFailure { - Logger.error("Failed to track reused account '${claim.account.id}'", it, context = TAG) - } + // The server holds the reused account now, so a retry must share the same one. + isReused && approvalError.isPostDeliveryAuthorizationFailure() -> + pinDeliveredAccount(authUrl, claim.account.id) !isReused && !approvalError.isPostDeliveryAuthorizationFailure() -> cancelIncompleteSetup( claim.account.id, preserveAuthorizingState, @@ -407,16 +413,27 @@ class PubkyAuthApprovalViewModel @Inject constructor( } return runSuspendCatching { - preparedClaim?.let { - if (isReused) { - watchOnlyAccountRepo.setTrackingEnabled(it.account.id, enabled = true) - } else { - watchOnlyAccountRepo.markActive(it.account.id) - } - } + preparedClaim?.takeUnless { isReused }?.let { watchOnlyAccountRepo.markActive(it.account.id) } }.onFailure { handleApprovalFailure(it, authUrl) }.isSuccess } + private fun pinDeliveredAccount(authUrl: String, accountId: String) { + _uiState.update { state -> + if (state.authUrl == authUrl) { + state.copy( + deliveredAccountId = accountId, + existingAccounts = persistentListOf(), + selectedAccountId = accountId, + state = state.state + .takeUnless { it == ApprovalState.ChooseAccount } + ?: ApprovalState.WatchOnlyConsent, + ) + } else { + state + } + } + } + private suspend fun dropAccountChoiceIfSetupUnfinished(authUrl: String) { if (!_uiState.value.showsAccountChoice) return val isUnfinished = runSuspendCatching { watchOnlyAccountRepo.hasIncompleteSetup(authUrl) }.getOrDefault(false) @@ -556,6 +573,7 @@ data class PubkyAuthApprovalUiState( val isUsdtEnabled: Boolean = false, val existingAccounts: ImmutableList = persistentListOf(), val selectedAccountId: String? = null, + val deliveredAccountId: String? = null, ) { val showsAccountChoice: Boolean get() = bitkitClaim?.sharesBitcoin == true && existingAccounts.isNotEmpty() val showsUsdtDetails: Boolean get() = bitkitClaim?.sharesUsdt == true && isUsdtEnabled diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt index 59a969cbef..63a50ec17a 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt @@ -80,11 +80,11 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { private val existingAccounts = MutableStateFlow>(emptyList()) private val watchOnlyAccountRepo: WatchOnlyAccountRepo = mock { on { currentWalletAccounts } doReturn existingAccounts - onBlocking { hasIncompleteSetup(any()) } doReturn false } @Before fun setUp() { + whenever { watchOnlyAccountRepo.hasIncompleteSetup(any()) }.thenReturn(false) whenever(context.getString(R.string.profile__auth_approval_service_unknown)).thenReturn("Unknown service") whenever(context.getString(R.string.profile__auth_approval_services_separator)).thenReturn(" and ") whenever(context.getString(R.string.profile__auth_error_title)).thenReturn("Authorization failed") @@ -1430,7 +1430,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { advanceUntilIdle() assertEquals(ApprovalState.Success, sut.uiState.value.state) - verifyBlocking(watchOnlyAccountRepo) { setTrackingEnabled(newer.id, true) } + verifyBlocking(watchOnlyAccountRepo, never()) { setTrackingEnabled(any(), any()) } verifyBlocking(watchOnlyAccountRepo, never()) { beginAuthorization(any()) } verifyBlocking(watchOnlyAccountRepo, never()) { markActive(any()) } } @@ -1524,7 +1524,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { } @Test - fun `reused account is tracked when authorization fails after delivery`() = test { + fun `reused account stays tracked and pinned when authorization fails after delivery`() = test { val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" val reused = activeAccount(id = "old", accountIndex = 1, isTrackingEnabled = false) existingAccounts.value = listOf(reused) @@ -1548,12 +1548,21 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { advanceUntilIdle() verifyBlocking(watchOnlyAccountRepo) { setTrackingEnabled(reused.id, true) } + verifyBlocking(watchOnlyAccountRepo, never()) { setTrackingEnabled(reused.id, false) } verifyBlocking(watchOnlyAccountRepo, never()) { cancelAuthorization(any(), any()) } verifyBlocking(watchOnlyAccountRepo, never()) { markActive(any()) } + assertFalse(sut.uiState.value.showsAccountChoice) + + sut.selectAccount(authUrl, null) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + + verifyBlocking(watchOnlyAccountRepo, times(2)) { prepareUnsignedClaim(authUrl, "paykit server", reused.id) } + verifyBlocking(watchOnlyAccountRepo, never()) { prepareUnsignedClaim(authUrl, "paykit server", null) } } @Test - fun `reused account stays untouched when authorization fails before delivery`() = test { + fun `reused account stays tracked when authorization fails before delivery`() = test { val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" val reused = activeAccount(id = "old", accountIndex = 1, isTrackingEnabled = false) existingAccounts.value = listOf(reused) @@ -1575,11 +1584,40 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { sut.confirmAuthorize(authUrl) advanceUntilIdle() - verifyBlocking(watchOnlyAccountRepo, never()) { setTrackingEnabled(any(), any()) } + verifyBlocking(watchOnlyAccountRepo) { setTrackingEnabled(reused.id, true) } + verifyBlocking(watchOnlyAccountRepo, never()) { setTrackingEnabled(reused.id, false) } verifyBlocking(watchOnlyAccountRepo, never()) { cancelAuthorization(any(), any()) } assertTrue(sut.uiState.value.showsAccountChoice) } + @Test + fun `reused account that cannot be tracked is not sent`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" + val reused = activeAccount(id = "old", accountIndex = 1, isTrackingEnabled = false) + existingAccounts.value = listOf(reused) + val prepared = PreparedWatchOnlyAccountClaim(reused, ByteArray(84)) + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn( + Result.success( + authRequest(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1)), + ), + ) + whenever(watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, "paykit server", reused.id)).thenReturn(prepared) + whenever(watchOnlyAccountRepo.setTrackingEnabled(reused.id, true)) + .thenThrow(IllegalStateException("node stopped")) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + sut.approveWatchOnlyConsent(authUrl) + sut.confirmAccountChoice(authUrl) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + + verifyBlocking(pubkyRepo, never()) { approveAuthWithCompanionClaim(any(), any(), any()) } + assertEquals(ApprovalState.Authorize, sut.uiState.value.state) + assertTrue(sut.uiState.value.showsAccountChoice) + } + @Test fun `unfinished setup for the request skips the account choice`() = test { val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" From b5c7d5677307a1776ad8d6e1b29f4cdcd562ff5c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 19:41:24 +0100 Subject: [PATCH 4/6] docs: note the default server account name per app Verified: git diff --check --- journeys/pubky-marketplace/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/journeys/pubky-marketplace/README.md b/journeys/pubky-marketplace/README.md index f4a347fbc8..f708afe938 100644 --- a/journeys/pubky-marketplace/README.md +++ b/journeys/pubky-marketplace/README.md @@ -16,7 +16,7 @@ The companion journey is shared with iOS; only platform build instructions diffe - `paykit-only-approval.xml` checks Paykit-only consent and cancellation without account creation. - `paykit-reconnect.xml` checks Paykit-only reconnect consent and cancellation without changing the existing service account. -- `reapprove-server-account.xml` checks that re-approving a server offers its existing account, preselected by name, keeps one account when it is reused and adds one only when "New account" is chosen. +- `reapprove-server-account.xml` checks that re-approving a server offers its existing account, preselected by name, keeps one account when it is reused and adds one only when "New account" is chosen. The Android default account name is "{service} server" where iOS uses "{service} account"; the preselection compares names on the same platform. - `approval-while-node-restarts.xml` checks that a Bitcoin watch-only setup approved while the node is stopped or rebuilding completes on the first Authorize and is tracked once the node starts. These visible consent and cancel checks require valid auth URL fixtures but do not authorize a From b8fcf7119d6eaaa7a73534f47b0a23d1846759bd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 20:04:23 +0100 Subject: [PATCH 5/6] fix: stop sending a reused account that is gone Verified: just test, just lint --- .../repositories/WatchOnlyAccountRepo.kt | 37 +++++++++++++++---- .../profile/PubkyAuthApprovalViewModel.kt | 4 +- .../repositories/WatchOnlyAccountRepoTest.kt | 15 ++++++++ .../profile/PubkyAuthApprovalViewModelTest.kt | 8 ++-- 4 files changed, 50 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt index c9cbea764e..91187b335b 100644 --- a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt @@ -216,16 +216,37 @@ class WatchOnlyAccountRepo @Inject constructor( val account = current.firstOrNull { it.id == id } ?: return@withLock if (account.setupState != WatchOnlyAccountSetupState.Active) return@withLock if (account.isTrackingEnabled == enabled) return@withLock + saveTracking(current, account, enabled) + } + } - setAccountTracking(account, enabled) - val saveResult = runSuspendCatching { - store.save(current.map { if (it.id == id) it.copy(isTrackingEnabled = enabled) else it }) - } - saveResult.onFailure { - runSuspendCatching { setAccountTracking(account, enabled = !enabled) } - } - saveResult.getOrThrow() + /** Tracks a reused account before its claim is sent, failing when it is no longer active on this wallet. */ + suspend fun trackReusedAccount(id: String) = withContext(NonCancellable) { + lifecycleCoordinator.withLock { + val current = store.load() + val account = current.firstOrNull { + it.id == id && + it.walletIndex == lightningService.currentWalletIndex && + it.setupState == WatchOnlyAccountSetupState.Active + } ?: throw WatchOnlyAccountError.AuthorizationAccountMissing() + if (account.isTrackingEnabled) return@withLock + saveTracking(current, account, enabled = true) + } + } + + private suspend fun saveTracking( + current: List, + account: WatchOnlyAccountRecord, + enabled: Boolean, + ) { + setAccountTracking(account, enabled) + val saveResult = runSuspendCatching { + store.save(current.map { if (it.id == account.id) it.copy(isTrackingEnabled = enabled) else it }) + } + saveResult.onFailure { + runSuspendCatching { setAccountTracking(account, enabled = !enabled) } } + saveResult.getOrThrow() } suspend fun restore( diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt index 07707751c3..a4847b198d 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt @@ -364,8 +364,8 @@ class PubkyAuthApprovalViewModel @Inject constructor( val isReused = preparedClaim?.account?.setupState == WatchOnlyAccountSetupState.Active // The server can hold the claim as soon as it is sent, so a reused account is tracked before delivery and // stays tracked whatever the outcome. - preparedClaim?.takeIf { isReused && !it.account.isTrackingEnabled }?.let { claim -> - runSuspendCatching { watchOnlyAccountRepo.setTrackingEnabled(claim.account.id, enabled = true) }.getOrElse { + preparedClaim?.takeIf { isReused }?.let { claim -> + runSuspendCatching { watchOnlyAccountRepo.trackReusedAccount(claim.account.id) }.getOrElse { handleApprovalFailure(it, authUrl) return false } diff --git a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt index 3c7d0aaf9f..8303e66b15 100644 --- a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt @@ -149,6 +149,21 @@ class WatchOnlyAccountRepoTest : BaseUnitTest() { verify(store, never()).update(any()) } + @Test + fun `tracking a reused account fails when it is no longer active`() = test { + val authorizing = account().copy(isTrackingEnabled = false, setupState = WatchOnlyAccountSetupState.Authorizing) + val store = mock() + val lightningService = mock() + whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = listOf(authorizing)))) + whenever(store.load()).thenReturn(listOf(authorizing)) + + assertFailsWith { + repository(store, lightningService).trackReusedAccount(authorizing.id) + } + verify(lightningService, never()).node + verify(store, never()).update(any()) + } + @Test fun `current wallet accounts exclude records from other wallets`() = test { val currentWalletAccount = account().copy(walletIndex = 1) diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt index 63a50ec17a..dd06ece548 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt @@ -1430,7 +1430,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { advanceUntilIdle() assertEquals(ApprovalState.Success, sut.uiState.value.state) - verifyBlocking(watchOnlyAccountRepo, never()) { setTrackingEnabled(any(), any()) } + verifyBlocking(watchOnlyAccountRepo) { trackReusedAccount(newer.id) } verifyBlocking(watchOnlyAccountRepo, never()) { beginAuthorization(any()) } verifyBlocking(watchOnlyAccountRepo, never()) { markActive(any()) } } @@ -1547,7 +1547,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { sut.confirmAuthorize(authUrl) advanceUntilIdle() - verifyBlocking(watchOnlyAccountRepo) { setTrackingEnabled(reused.id, true) } + verifyBlocking(watchOnlyAccountRepo) { trackReusedAccount(reused.id) } verifyBlocking(watchOnlyAccountRepo, never()) { setTrackingEnabled(reused.id, false) } verifyBlocking(watchOnlyAccountRepo, never()) { cancelAuthorization(any(), any()) } verifyBlocking(watchOnlyAccountRepo, never()) { markActive(any()) } @@ -1584,7 +1584,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { sut.confirmAuthorize(authUrl) advanceUntilIdle() - verifyBlocking(watchOnlyAccountRepo) { setTrackingEnabled(reused.id, true) } + verifyBlocking(watchOnlyAccountRepo) { trackReusedAccount(reused.id) } verifyBlocking(watchOnlyAccountRepo, never()) { setTrackingEnabled(reused.id, false) } verifyBlocking(watchOnlyAccountRepo, never()) { cancelAuthorization(any(), any()) } assertTrue(sut.uiState.value.showsAccountChoice) @@ -1602,7 +1602,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { ), ) whenever(watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, "paykit server", reused.id)).thenReturn(prepared) - whenever(watchOnlyAccountRepo.setTrackingEnabled(reused.id, true)) + whenever(watchOnlyAccountRepo.trackReusedAccount(reused.id)) .thenThrow(IllegalStateException("node stopped")) val sut = createSut() From 5b2a9b52997c928b7a31cd8ae30a3734b7b91ac3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 20:19:47 +0100 Subject: [PATCH 6/6] fix: track a reused account on the node even when stored as tracked The store can say tracked while the node lost the account, so the node is always asked to track a reused account before its claim is sent. Verified: just test, just lint --- .../repositories/WatchOnlyAccountRepo.kt | 8 ++- .../repositories/WatchOnlyAccountRepoTest.kt | 55 +++++++++++++++++-- .../profile/PubkyAuthApprovalViewModelTest.kt | 4 +- 3 files changed, 57 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt index 91187b335b..751a14c8ae 100644 --- a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt @@ -229,8 +229,12 @@ class WatchOnlyAccountRepo @Inject constructor( it.walletIndex == lightningService.currentWalletIndex && it.setupState == WatchOnlyAccountSetupState.Active } ?: throw WatchOnlyAccountError.AuthorizationAccountMissing() - if (account.isTrackingEnabled) return@withLock - saveTracking(current, account, enabled = true) + // The store can say tracked while the node lost the account, so the node is always asked to track it. + if (account.isTrackingEnabled) { + setAccountTracking(account, enabled = true) + } else { + saveTracking(current, account, enabled = true) + } } } diff --git a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt index 8303e66b15..15c8a16a61 100644 --- a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt @@ -150,18 +150,61 @@ class WatchOnlyAccountRepoTest : BaseUnitTest() { } @Test - fun `tracking a reused account fails when it is no longer active`() = test { + fun `tracking a reused account fails when it is no longer active on this wallet`() = test { val authorizing = account().copy(isTrackingEnabled = false, setupState = WatchOnlyAccountSetupState.Authorizing) + val otherWallet = account().copy(id = "other-wallet", walletIndex = 1) val store = mock() val lightningService = mock() - whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = listOf(authorizing)))) - whenever(store.load()).thenReturn(listOf(authorizing)) + whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = listOf(authorizing, otherWallet)))) + whenever(store.load()).thenReturn(listOf(authorizing, otherWallet)) + val sut = repository(store, lightningService) - assertFailsWith { - repository(store, lightningService).trackReusedAccount(authorizing.id) + listOf(authorizing.id, otherWallet.id, "missing").forEach { id -> + assertFailsWith { sut.trackReusedAccount(id) } } verify(lightningService, never()).node - verify(store, never()).update(any()) + verify(store, never()).save(any()) + } + + @Test + fun `tracking a reused account adds it to the node and saves it`() = test { + val untracked = account().copy(isTrackingEnabled = false) + var storedAccounts = listOf(untracked) + val store = mock() + val lightningService = mock() + val node = mock() + whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = storedAccounts))) + whenever(store.load()).thenAnswer { storedAccounts } + whenever(store.save(any())).thenAnswer { + storedAccounts = it.getArgument(0) + Unit + } + whenever(lightningService.node).thenReturn(node) + whenever(node.listOnchainWalletAccounts()).thenReturn(emptyList()) + whenever(node.onchainPayment()).thenReturn(mock()) + + repository(store, lightningService).trackReusedAccount(untracked.id) + + assertTrue(storedAccounts.single().isTrackingEnabled) + verify(node).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, untracked.xpub) + } + + @Test + fun `tracking an already tracked reused account adds it back to the node`() = test { + val tracked = account() + val store = mock() + val lightningService = mock() + val node = mock() + whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = listOf(tracked)))) + whenever(store.load()).thenReturn(listOf(tracked)) + whenever(lightningService.node).thenReturn(node) + whenever(node.listOnchainWalletAccounts()).thenReturn(emptyList()) + whenever(node.onchainPayment()).thenReturn(mock()) + + repository(store, lightningService).trackReusedAccount(tracked.id) + + verify(node).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, tracked.xpub) + verify(store, never()).save(any()) } @Test diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt index dd06ece548..5a3c0c68a9 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt @@ -1489,7 +1489,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { assertEquals(ApprovalState.Success, sut.uiState.value.state) verifyBlocking(watchOnlyAccountRepo) { beginAuthorization(prepared.account.id) } verifyBlocking(watchOnlyAccountRepo) { markActive(prepared.account.id) } - verifyBlocking(watchOnlyAccountRepo, never()) { setTrackingEnabled(any(), any()) } + verifyBlocking(watchOnlyAccountRepo, never()) { trackReusedAccount(any()) } } @Test @@ -1641,7 +1641,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { private suspend fun verifyNoAccountChanges() { verify(watchOnlyAccountRepo, never()).prepareUnsignedClaim(any(), any(), anyOrNull()) verify(watchOnlyAccountRepo, never()).beginAuthorization(any()) - verify(watchOnlyAccountRepo, never()).setTrackingEnabled(any(), any()) + verify(watchOnlyAccountRepo, never()).trackReusedAccount(any()) verify(watchOnlyAccountRepo, never()).markActive(any()) }