From 6c25562bfea53cbe9608ef08492a16384003dd4e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 14 Nov 2026 04:04:15 +0100 Subject: [PATCH 1/9] fix: stop the swap claim poll on a failed hold payment --- .../repositories/PubkySwapsRouteRepo.kt | 36 +++++++++++-- .../java/to/bitkit/viewmodels/AppViewModel.kt | 2 +- .../repositories/PubkySwapsRouteRepoTest.kt | 39 ++++++++++++++ .../java/to/bitkit/ui/WalletViewModelTest.kt | 8 +-- .../viewmodels/AppViewModelSendFlowTest.kt | 54 ++++++++++++------- 5 files changed, 111 insertions(+), 28 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt index 669beba904..443159995d 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt @@ -11,10 +11,13 @@ import com.synonym.bitkitcore.pubkySwapsAdvance import com.synonym.bitkitcore.pubkySwapsCommitRoute import com.synonym.bitkitcore.pubkySwapsRestore import com.synonym.bitkitcore.pubkySwapsRoutePaykitPayment +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.launch +import kotlinx.coroutines.selects.select import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import org.lightningdevkit.ldknode.PaymentDirection @@ -145,15 +148,35 @@ class PubkySwapsRouteRepo @Inject constructor( /** * Advance the swap until bitkit-core broadcasts the claim to the contact, returning the claim txid. The provider * settles the hold invoice once it sees the claim, so the payment is done; the claim is still advanced in the - * background so bitkit-core rebroadcasts it until it confirms. + * background so bitkit-core rebroadcasts it until it confirms. [holdFailure] completing normally means the hold + * payment failed: the provider never funds that swap, so advancing stops with [PubkySwapHoldFailedException]. */ // Runs on the app scope: the swap keeps advancing towards its claim when the caller, such as a cleared screen, // stops waiting. - suspend fun awaitClaim(swapId: String, timeout: Duration = CLAIM_TIMEOUT): Result = scope.async { + suspend fun awaitClaim( + swapId: String, + timeout: Duration = CLAIM_TIMEOUT, + holdFailure: Job? = null, + ): Result = scope.async { var lastFailure: Throwable? = null - withTimeoutOrNull(timeout) { - pollClaim(swapId, POLL_INTERVAL, untilConfirmed = false) { lastFailure = it } - }?.onSuccess { advanceInBackground(swapId) } ?: run { + val poll = async { + withTimeoutOrNull(timeout) { + pollClaim(swapId, POLL_INTERVAL, untilConfirmed = false) { lastFailure = it } + } + } + // A cancelled watch, as on a cleared screen, says nothing about the hold payment, so the swap keeps advancing. + val holdFailed = CompletableDeferred() + val handle = holdFailure?.invokeOnCompletion { if (it == null) holdFailed.complete(Unit) } + val isHoldFailed = select { + poll.onJoin { false } + holdFailed.onJoin { true } + } + handle?.dispose() + if (isHoldFailed) { + poll.cancel() + return@async Result.failure(PubkySwapHoldFailedException(swapId)) + } + poll.await()?.onSuccess { advanceInBackground(swapId) } ?: run { // The provider may still settle the hold payment, so the swap keeps advancing towards its claim. advanceInBackground(swapId) Result.failure(PubkySwapClaimTimeoutException(swapId, lastFailure)) @@ -214,6 +237,9 @@ data class RestoredPubkySwaps( val known: List, ) +/** The swap's hold payment failed, so the provider never funds its lockup and the swap is not advanced further. */ +class PubkySwapHoldFailedException(swapId: String) : AppError("Hold payment of swap '$swapId' failed") + /** A claim wait that ran out with the swap still open: its hold payment may yet settle. */ class PubkySwapClaimTimeoutException(swapId: String, cause: Throwable?) : AppError("Swap '$swapId' not claimed yet", cause) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 0edcc7f9d4..6de89e8502 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -7464,7 +7464,7 @@ class AppViewModel @Inject constructor( payment: PubkySwapRoutePayment, holdFailure: Deferred, ): Result = coroutineScope { - val claim = async { pubkySwapsRouteRepo.awaitClaim(payment.swapId) } + val claim = async { pubkySwapsRouteRepo.awaitClaim(payment.swapId, holdFailure = holdFailure) } select { claim.onAwait { it } holdFailure.onAwait { diff --git a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt index 3e4e2f5a4e..86b7807095 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt @@ -3,7 +3,9 @@ package to.bitkit.repositories import com.synonym.bitkitcore.PubkySwapRouteState import com.synonym.bitkitcore.PubkySwapRouteStatus import com.synonym.bitkitcore.pubkySwapsAdvance +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.advanceUntilIdle @@ -105,6 +107,43 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } } + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `awaitClaim stops advancing the swap once its hold payment fails`() = test { + mockStatic(CORE).use { core -> + core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } + .thenReturn(status(PubkySwapRouteState.AwaitingLockup(confirmations = 0u, required = 1u))) + val holdFailure = CompletableDeferred() + + val result = async { sut.awaitClaim(SWAP_ID, holdFailure = holdFailure) } + runCurrent() + holdFailure.complete(Unit) + advanceUntilIdle() + + assertIs(result.await().exceptionOrNull()) + core.verify({ runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } }, times(1)) + } + } + + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `awaitClaim keeps advancing the swap when its hold payment watch is cancelled`() = test { + mockStatic(CORE).use { core -> + core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } + .thenReturn(status(PubkySwapRouteState.AwaitingLockup(confirmations = 0u, required = 1u))) + .thenReturn(status(PubkySwapRouteState.ClaimBroadcast(CLAIM_TXID))) + .thenReturn(status(PubkySwapRouteState.Claimed(CONFIRMED_CLAIM_TXID))) + val holdFailure = CompletableDeferred() + + val result = async { sut.awaitClaim(SWAP_ID, holdFailure = holdFailure) } + runCurrent() + holdFailure.cancel() + advanceUntilIdle() + + assertEquals(Result.success(CLAIM_TXID), result.await()) + } + } + private suspend fun advancing(vararg answers: Any, block: suspend () -> T): T = mockStatic(CORE).use { core -> var stub = core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } diff --git a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt index 3b853cfe9f..34e9ed9b92 100644 --- a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt @@ -359,7 +359,7 @@ class WalletViewModelTest : BaseUnitTest() { whenever(pubkySwapsRouteRepo.isEnabled).thenReturn(true) whenever(pubkySwapsRouteRepo.restoreSwaps()) .thenReturn(Result.success(RestoredPubkySwaps(listOf("swap"), emptyList()))) - whenever(pubkySwapsRouteRepo.awaitClaim(eq("swap"), any())).thenReturn(Result.success("txid")) + whenever(pubkySwapsRouteRepo.awaitClaim(eq("swap"), any(), anyOrNull())).thenReturn(Result.success("txid")) whenever(context.getString(any())).thenReturn("text") whenever(backupRepo.getLatestBackupTime()).thenReturn(1uL) whenever(backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull())).thenReturn( @@ -373,7 +373,7 @@ class WalletViewModelTest : BaseUnitTest() { assertEquals(RestoreState.Completed(emptySet()), sut.restoreState.value) verify(pubkySwapsRouteRepo).restoreSwaps() - verify(pubkySwapsRouteRepo).awaitClaim(eq("swap"), any()) + verify(pubkySwapsRouteRepo).awaitClaim(eq("swap"), any(), anyOrNull()) verify(context).getString(R.string.wallet__swap_route_restored_title) } @@ -382,7 +382,7 @@ class WalletViewModelTest : BaseUnitTest() { whenever(pubkySwapsRouteRepo.isEnabled).thenReturn(true) whenever(pubkySwapsRouteRepo.restoreSwaps()) .thenReturn(Result.success(RestoredPubkySwaps(emptyList(), listOf("swap")))) - whenever(pubkySwapsRouteRepo.awaitClaim(eq("swap"), any())).thenReturn(Result.success("txid")) + whenever(pubkySwapsRouteRepo.awaitClaim(eq("swap"), any(), anyOrNull())).thenReturn(Result.success("txid")) whenever(context.getString(any())).thenReturn("text") whenever(backupRepo.getLatestBackupTime()).thenReturn(1uL) whenever(backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull())).thenReturn( @@ -394,7 +394,7 @@ class WalletViewModelTest : BaseUnitTest() { walletState.value = walletState.value.copy(walletExists = true) advanceUntilIdle() - verify(pubkySwapsRouteRepo).awaitClaim(eq("swap"), any()) + verify(pubkySwapsRouteRepo).awaitClaim(eq("swap"), any(), anyOrNull()) verify(context, never()).getString(R.string.wallet__swap_route_restored_title) } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index c0ea574350..78dc4ad08c 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -46,6 +46,7 @@ import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation @@ -19304,7 +19305,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.success(SWAP_HOLD_HASH)) - whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).thenReturn(Result.success(SWAP_CLAIM_TXID)) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())) + .thenReturn(Result.success(SWAP_CLAIM_TXID)) whenever( preActivityMetadataRepo.savePreActivityMetadata( id = eq(SWAP_HOLD_HASH), @@ -19431,7 +19433,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(SendRetryRoute.Amount, assertIs(awaitItem()).retryRoute) expectNoEvents() } - verify(pubkySwapsRouteRepo, never()).awaitClaim(any(), any()) + verify(pubkySwapsRouteRepo, never()).awaitClaim(any(), any(), anyOrNull()) } @Test @@ -19440,7 +19442,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.failure(PaymentPendingException(SWAP_HOLD_HASH))) - whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { awaitCancellation() } + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())) + .doSuspendableAnswer { awaitCancellation() } openSwapRoutedContactPayment(privatePaymentContext = privateContext) sut.sendEffect.test { @@ -19452,7 +19455,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { cancelAndIgnoreRemainingEvents() } verify(pendingPaymentRepo).track(SWAP_HOLD_HASH) - verify(pubkySwapsRouteRepo).awaitClaim(eq(SWAP_ID), any()) + verify(pubkySwapsRouteRepo).awaitClaim(eq(SWAP_ID), any(), anyOrNull()) verify(privatePaykitRepo, never()).releasePrivatePaymentList(testPublicKey, privateContext) } @@ -19462,7 +19465,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.success(SWAP_HOLD_HASH)) - whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())).doSuspendableAnswer { try { awaitCancellation() } finally { @@ -19483,6 +19486,15 @@ class AppViewModelSendFlowTest : BaseUnitTest() { expectNoEvents() } assertTrue(claimCancelled) + // The repo stops advancing the swap only on a hold payment that failed, never on a cancelled watch. + verify(pubkySwapsRouteRepo).awaitClaim( + eq(SWAP_ID), + any(), + check { + assertTrue(it.isCompleted) + assertFalse(it.isCancelled) + }, + ) verify(pendingPaymentRepo).resolve(check { assertIs(it) }) assertNull(sut.successSendUiState.value.paymentHashOrTxId) } @@ -19494,7 +19506,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { emitSwapHoldPaymentFailed() Result.success(SWAP_HOLD_HASH) } - whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { awaitCancellation() } + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())) + .doSuspendableAnswer { awaitCancellation() } openSwapRoutedContactPayment() sut.sendEffect.test { @@ -19518,7 +19531,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { emitSwapHoldPaymentFailed() Result.success(SWAP_HOLD_HASH) } - whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { awaitCancellation() } + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())) + .doSuspendableAnswer { awaitCancellation() } openSwapRoutedContactPayment() sut.sendEffect.test { @@ -19539,7 +19553,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.success(SWAP_HOLD_HASH)) - whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { awaitCancellation() } + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())) + .doSuspendableAnswer { awaitCancellation() } openSwapRoutedContactPayment() sut.sendEffect.test { @@ -19580,7 +19595,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { .thenReturn(Result.failure(AppError("quote_expired")), Result.success(swapRoutePayment())) whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.success(SWAP_HOLD_HASH)) - whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { awaitCancellation() } + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())) + .doSuspendableAnswer { awaitCancellation() } openSwapRoutedContactPayment(privatePaymentContext = privateContext) sut.sendEffect.test { @@ -19628,7 +19644,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.success(SWAP_HOLD_HASH)) - whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).thenReturn(Result.failure(AppError("refunded"))) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())) + .thenReturn(Result.failure(AppError("refunded"))) openSwapRoutedContactPayment() sut.sendEffect.test { @@ -19651,7 +19668,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.success(SWAP_HOLD_HASH)) - whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { claim.await() } + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())).doSuspendableAnswer { claim.await() } openSwapRoutedContactPayment() sut.sendEffect.test { sut.setSendEvent(SendEvent.AmountContinue) @@ -19681,7 +19698,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.success(SWAP_HOLD_HASH)) - whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())) .thenReturn(Result.failure(PubkySwapClaimTimeoutException(SWAP_ID, AppError("awaiting lockup")))) openSwapRoutedContactPayment() @@ -19717,7 +19734,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(pubkySwapsRouteRepo.commit("edited-quote")).doSuspendableAnswer { awaitCancellation() } whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.success(SWAP_HOLD_HASH)) - whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { claim.await() } + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())).doSuspendableAnswer { claim.await() } openSwapRoutedContactPayment() sut.sendEffect.test { sut.setSendEvent(SendEvent.AmountContinue) @@ -19788,7 +19805,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).doSuspendableAnswer { commit.await() } whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.success(SWAP_HOLD_HASH)) - whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { awaitCancellation() } + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())) + .doSuspendableAnswer { awaitCancellation() } openSwapRoutedContactPayment() sut.sendEffect.test { sut.setSendEvent(SendEvent.AmountContinue) @@ -19828,7 +19846,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.success(SWAP_HOLD_HASH)) - whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { claim.await() } + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())).doSuspendableAnswer { claim.await() } openSwapRoutedContactPayment() sut.sendEffect.test { sut.setSendEvent(SendEvent.AmountContinue) @@ -19837,7 +19855,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { confirmSwapRoutedPayment() cancelAndIgnoreRemainingEvents() } - verify(pubkySwapsRouteRepo).awaitClaim(eq(SWAP_ID), any()) + verify(pubkySwapsRouteRepo).awaitClaim(eq(SWAP_ID), any(), anyOrNull()) sut.hideSheet() advanceBeforeHoldWatchDeadline() openSwapRoutedContactPayment(settle = { advanceBeforeHoldWatchDeadline() }) @@ -19869,7 +19887,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.success(SWAP_HOLD_HASH)) - whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any())).doSuspendableAnswer { claim.await() } + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())).doSuspendableAnswer { claim.await() } openSwapRoutedContactPayment() sut.sendEffect.test { sut.setSendEvent(SendEvent.AmountContinue) @@ -19878,7 +19896,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { confirmSwapRoutedPayment() cancelAndIgnoreRemainingEvents() } - verify(pubkySwapsRouteRepo).awaitClaim(eq(SWAP_ID), any()) + verify(pubkySwapsRouteRepo).awaitClaim(eq(SWAP_ID), any(), anyOrNull()) sut.hideSheet() advanceBeforeHoldWatchDeadline() sut.openContactPayment( From 2a70b40819f45feb52496b204425b60c39e6d971 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 14 Nov 2026 04:04:15 +0100 Subject: [PATCH 2/9] fix: offer the swap fallback while spark settles another contact --- .../to/bitkit/repositories/PaykitRouteRepo.kt | 5 +-- .../java/to/bitkit/repositories/SparkRepo.kt | 4 +- .../java/to/bitkit/services/SparkService.kt | 6 ++- .../java/to/bitkit/viewmodels/AppViewModel.kt | 11 +++++- .../repositories/PaykitRouteRepoTest.kt | 7 ++-- .../to/bitkit/repositories/SparkRepoTest.kt | 11 +++++- .../viewmodels/AppViewModelSendFlowTest.kt | 37 +++++++++++++++++++ 7 files changed, 69 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt index 395a6fd446..097e2598b2 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt @@ -68,9 +68,8 @@ class PaykitRouteRepo @Inject constructor( if (legs.isNotEmpty()) { return@runSuspendCatching paykitRoutePayment(request.copy(serviceLegs = legs), network) } - if (quotes.any { it.exceptionOrNull() is SparkError.WithdrawalPending }) { - throw SparkError.WithdrawalPending() - } + // The pending withdrawal's address and contact tell the app whether it pays this contact. + quotes.firstNotNullOfOrNull { it.exceptionOrNull() as? SparkError.WithdrawalPending }?.let { throw it } if (quotes.any { it.exceptionOrNull() is SparkError.WithdrawalOverBalance }) { throw SparkError.WithdrawalOverBalance() } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index ef09b202aa..8285211fb4 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -886,7 +886,9 @@ class SparkRepo @Inject constructor( suspend fun withdrawalRouteLeg(endpoint: PaykitEndpoint, amountSats: ULong): Result = withContext(bgDispatcher) { runSuspendCatching { - if (cacheStore.data.first().pendingSparkWithdrawal != null) throw SparkError.WithdrawalPending() + cacheStore.data.first().pendingSparkWithdrawal?.let { + throw SparkError.WithdrawalPending(address = it.address, contact = it.contact) + } if (!canWithdraw(amountSats)) return@runSuspendCatching null val method = sparkService.prepareSend(endpoint.value, amountSats).paymentMethod val quote = (method as SendPaymentMethod.BitcoinAddress).feeQuote diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index d2b1448ca5..594bc11371 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -366,7 +366,11 @@ sealed class SparkError(message: String, cause: Throwable? = null) : AppError(me /** The withdrawal fee rose above the fee the user confirmed. */ class WithdrawalFeeChanged : SparkError("Spark withdrawal fee changed since it was confirmed") - class WithdrawalPending : SparkError("An earlier Spark withdrawal is still settling") + /** An earlier contact withdrawal, to [address] for [contact] where its journal records them, is still settling. */ + class WithdrawalPending( + val address: String? = null, + val contact: String? = null, + ) : SparkError("An earlier Spark withdrawal is still settling") /** Spark could withdraw to the contact, but its balance can't cover the amount plus the withdrawal fee. */ class WithdrawalOverBalance : SparkError("Spark balance can't cover the withdrawal and its fee") diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 6de89e8502..fb715d146d 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -5027,7 +5027,14 @@ class AppViewModel @Inject constructor( // Spark could reach the contact, but not with the withdrawal fee on top, so no route pays for want of balance. val isLegOverBalance = result.exceptionOrNull() is SparkError.WithdrawalOverBalance // Only a Spark leg could pay, and Spark takes one contact withdrawal at a time. - val isLegSettling = result.exceptionOrNull() is SparkError.WithdrawalPending + val settling = result.exceptionOrNull() as? SparkError.WithdrawalPending + val isLegSettling = settling != null + // A swap pays from Spending, so only a withdrawal still settling to this contact, or to an unknown one, keeps + // the payment from a swap that could pay the contact a second time. + val isSettlingHere = settling != null && ( + settling.address == null || settling.address in route.endpoints.map { it.value } || + settling.contact == contact?.publicKey + ) val picked = if (isLegOverBalance || isLegSettling) { PaykitRoute.None(result.exceptionOrNull()?.message.orEmpty()) } else { @@ -5062,7 +5069,7 @@ class AppViewModel @Inject constructor( _sendUiState.update { it.copy(paykitRoute = route.copy(serviceLeg = null)) } // A Spark balance too small for the amount and fee, or no route at all, leaves the payment to a swap // provider when one can carry it: its quote follows, so nothing shows here. - if (hasSwapFallback && !isLegSettling) return PaykitRouteOutcome.SwapFallback + if (hasSwapFallback && !isSettlingHere) return PaykitRouteOutcome.SwapFallback // The router's reason is English for the log: the app tells a short balance from an unusable contact. val isAmountShort = state.amount > lightningSpendable.safe() + onchainSpendable.safe() // The router never saw an LNURL whose limits refuse the amount, so its limit says why. diff --git a/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt index f5e46ecb99..5838e94eb5 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt @@ -19,6 +19,7 @@ import to.bitkit.services.SparkError import to.bitkit.test.BaseUnitTest import kotlin.test.assertEquals import kotlin.test.assertIs +import kotlin.test.assertSame class PaykitRouteRepoTest : BaseUnitTest() { private val sparkRepo = mock() @@ -103,8 +104,8 @@ class PaykitRouteRepoTest : BaseUnitTest() { @Test fun `a spark leg refused while an earlier withdrawal settles routes as settling`() = test { - whenever(sparkRepo.withdrawalRouteLeg(onchain, 9_000uL)) - .thenReturn(Result.failure(SparkError.WithdrawalPending())) + val pending = SparkError.WithdrawalPending(address = "bcrt1qearlier", contact = "earlier-contact") + whenever(sparkRepo.withdrawalRouteLeg(onchain, 9_000uL)).thenReturn(Result.failure(pending)) val route = sut.route( amountSats = 9_000uL, @@ -114,6 +115,6 @@ class PaykitRouteRepoTest : BaseUnitTest() { quoteServiceLegs = true, ) - assertIs(route.exceptionOrNull()) + assertSame(pending, route.exceptionOrNull()) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 2bf9725ab6..597177f9a3 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1260,9 +1260,16 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `quotes no route leg while an earlier contact withdrawal settles`() = test { val sut = readySpark(balanceSats = 50_000uL) - cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qearlier", 5_000uL, null)) } + cacheData.update { + it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qearlier", 5_000uL, "earlier-contact")) + } - assertIs(sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).exceptionOrNull()) + val pending = assertIs( + sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).exceptionOrNull(), + ) + // The app tells a withdrawal to this endpoint from one to another contact by the journal's address and contact. + assertEquals("bcrt1qearlier", pending.address) + assertEquals("earlier-contact", pending.contact) verify(sparkService, never()).prepareSend(any(), anyOrNull(), anyOrNull()) } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 78dc4ad08c..f315b245b2 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -19404,6 +19404,43 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(toastManager, never()).enqueue(any()) } + @Test + fun `spark withdrawal settling to another contact still falls back to a swap quote`() = test { + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())).thenReturn( + Result.failure(SparkError.WithdrawalPending(address = "bcrt1qothercontact", contact = "other-contact")), + ) + openSwapRoutedContactPayment() + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + } + + assertEquals(swapRouteQuote(), sut.sendUiState.value.paykitSwapRoute?.quote) + verify(toastManager, never()).enqueue(any()) + } + + @Test + fun `spark withdrawal settling to this contact keeps the swap fallback off`() = test { + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())).thenReturn( + Result.failure(SparkError.WithdrawalPending(address = REGTEST_ADDRESS, contact = testPublicKey)), + ) + openSwapRoutedContactPayment() + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + expectNoEvents() + } + + assertNull(sut.sendUiState.value.paykitSwapRoute?.quote) + verify(pubkySwapsRouteRepo, never()).route(any(), any(), any(), any(), any()) + verify(toastManager).enqueue(check { assertEquals("PaykitRouteSettlingToast", it.testTag) }) + } + @Test fun `swap route quote failure stays on the amount screen`() = test { openSwapRoutedContactPayment(quote = Result.failure(AppError("no provider"))) From 088f387f79bd13154121c81fd4c6cb55527f586a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 14 Nov 2026 04:04:15 +0100 Subject: [PATCH 3/9] test: cover a smaller amount after a swap quote taking the spark leg --- .../viewmodels/AppViewModelSendFlowTest.kt | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index f315b245b2..42dafbb630 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -19404,6 +19404,35 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(toastManager, never()).enqueue(any()) } + @Test + fun `smaller amount after a swap quote takes the spark leg and clears the quote`() = test { + val leg = sparkRouteLeg(REGTEST_ADDRESS) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(lightningRepo.canWithdrawWithSpark(any())).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.failure(SparkError.WithdrawalOverBalance())) + openSwapRoutedContactPayment() + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + assertEquals(swapRouteQuote(), sut.sendUiState.value.paykitSwapRoute?.quote) + + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + sut.setSendEvent(SendEvent.AmountChange(leg.deliveredSat)) + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + } + + verify(paykitRouteRepo).route(eq(leg.deliveredSat), any(), any(), eq(0uL), eq(true)) + assertNull(sut.sendUiState.value.paykitSwapRoute) + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + verify(pubkySwapsRouteRepo, times(1)).route(any(), any(), any(), any(), any()) + } + @Test fun `spark withdrawal settling to another contact still falls back to a swap quote`() = test { whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) From 2022c96e10bfa8274e150660befa5f639d308181 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 14 Nov 2026 04:04:16 +0100 Subject: [PATCH 4/9] fix: show the committed swap instead of paying a contact twice --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 51 +++++++++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 62 ++++++++++++++++--- 2 files changed, 104 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index fb715d146d..c3a28f733f 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -580,6 +580,10 @@ class AppViewModel @Inject constructor( /** The address and amount of the uncertain Spark withdrawal to a contact a pending screen waits on. */ @Volatile private var uncertainSparkWithdrawal: Pair? = null + + /** The swap whose hold payment went out for a send, which may still pay the contact, so that send pays once. */ + @Volatile + private var committedSwap: CommittedSwap? = null private var isPresentingPaymentRequest = false private val isPaymentRequestPollingStopped = MutableStateFlow(false) private var isPaymentRequestOverlayVisible = false @@ -2980,6 +2984,7 @@ class AppViewModel @Inject constructor( if (isAutomaticAllowancePayment(paymentHash)) return if (moveToSparkRepo.isWatchedMovePayment(paymentHash)) return if (pendingPaymentRepo.isPending(paymentHash)) { + releaseFailedSwapHold(paymentHash) clearPendingContactPaymentContext(paymentHash) pendingPaymentRepo.resolve(PendingPaymentResolution.Failure(paymentHash, event.reason)) if (shouldNotifyPendingResolution(paymentHash)) { @@ -6769,6 +6774,7 @@ class AppViewModel @Inject constructor( private suspend fun proceedWithPayment(contactPaymentContext: ContactPaymentContext?) { delay(SCREEN_TRANSITION_DELAY) // wait for screen transitions when applicable + if (showCommittedSwap()) return if (!validateIncomingPaymentRequest(contactPaymentContext)) return _sendUiState.value.activePaykitSwapRoute?.let { route -> if (route.quote?.deliveredSat == _sendUiState.value.amount) return@let @@ -7348,11 +7354,13 @@ class AppViewModel @Inject constructor( contactPaymentContext?.let { synchronized(contactPaymentContextLock) { pendingContactPaymentContexts[holdPaymentHash] = it } } + committedSwap = CommittedSwap(sendGeneration, holdPaymentHash, payment.deliveredSat) // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending. lightningRepo.payInvoice(payment.invoice).onFailure { // Spark may have sent it, so an unknown outcome waits on the claim like a sent hold payment. if (it is PaymentPendingException) return@onFailure holdFailure.cancel() + clearCommittedSwap(holdPaymentHash) clearPendingContactPaymentContext(holdPaymentHash) if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) failSwapRoutedPayment(it, contactPaymentContext, allowanceAttemptId, isSendCurrent()) @@ -7410,6 +7418,7 @@ class AppViewModel @Inject constructor( // A failed hold payment keeps its hash on the send: its own failure handler may still be on its way to // the error screen and finds the send by that hash. clearSwapRouteQuote(isSendCurrent(), keepHoldPaymentHash = it is LightningPaymentFailedError) + clearCommittedSwap(holdPaymentHash) finishManualAllowancePayment(swap.allowanceAttemptId, succeeded = false) clearPendingContactPaymentContext(holdPaymentHash) releasePrivatePaymentListIfNeeded(swap.contactPaymentContext) @@ -7452,6 +7461,41 @@ class AppViewModel @Inject constructor( } } + /** + * Shows the pending payment of a swap this send already paid a hold invoice for, instead of paying again: a quote + * made after backing out of Confirm mid-commit would pay the contact a second time. + */ + private fun showCommittedSwap(): Boolean { + val swap = committedSwap?.takeIf { it.sendGeneration == sendStateGeneration } ?: return false + setSendEffect( + SendEffect.NavigateToPending( + paymentHash = swap.holdPaymentHash, + amount = swap.deliveredSat.toLong(), + retryRoute = SendRetryRoute.Amount, + ), + ) + return true + } + + private fun clearCommittedSwap(holdPaymentHash: String) { + if (committedSwap?.holdPaymentHash == holdPaymentHash) committedSwap = null + } + + /** + * A failed hold payment paid nothing, also one that failed after the claim wait ran out, so its send may retry + * from Amount, for the contact Pending took off the send. + */ + private fun releaseFailedSwapHold(paymentHash: String) { + val swap = committedSwap?.takeIf { it.holdPaymentHash == paymentHash } ?: return + committedSwap = null + if (swap.sendGeneration != sendStateGeneration) return + synchronized(contactPaymentContextLock) { + if (activeContactPaymentContext == null) { + activeContactPaymentContext = pendingContactPaymentContexts[paymentHash] + } + } + } + private fun clearSwapRouteQuote(isSendCurrent: Boolean, keepHoldPaymentHash: Boolean = false) { if (!isSendCurrent) return _sendUiState.update { @@ -10389,6 +10433,13 @@ private data class SwapRoutedPayment( val allowanceAttemptId: String?, ) +/** A swap whose hold payment went out for the send of [sendGeneration], which may still pay the contact. */ +private data class CommittedSwap( + val sendGeneration: Long, + val holdPaymentHash: String, + val deliveredSat: ULong, +) + private class LightningPaymentFailedError( val reason: PaymentFailureReason?, val paymentRequest: String?, diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 42dafbb630..78133a0bf0 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -19793,11 +19793,12 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } @Test - fun `swap route claim wait leaves a re-quoted send free to pay`() = test { + fun `swap route send backed out of mid-commit pays the contact once`() = test { + val commit = CompletableDeferred>() val claim = CompletableDeferred>() val editedQuote = swapRouteQuote().copy(quoteId = "edited-quote", deliveredSat = SWAP_DELIVERED_SATS + 1_000u) - whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) - whenever(pubkySwapsRouteRepo.commit("edited-quote")).doSuspendableAnswer { awaitCancellation() } + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).doSuspendableAnswer { commit.await() } + whenever(pubkySwapsRouteRepo.commit("edited-quote")).thenReturn(Result.success(swapRoutePayment())) whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.success(SWAP_HOLD_HASH)) whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())).doSuspendableAnswer { claim.await() } @@ -19807,20 +19808,63 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceUntilIdle() assertEquals(SendEffect.NavigateToConfirm, awaitItem()) confirmSwapRoutedPayment() - // Backups and Paykit's background work do not wait for the claim. - assertFalse(paymentSubmissionActive.value) + // Backing out of Confirm while the provider is slow to commit quotes a new amount afresh. whenever(pubkySwapsRouteRepo.route(any(), any(), any(), any(), any())) .thenReturn(Result.success(PaykitRoute.Swap(editedQuote))) sut.setSendEvent(SendEvent.AmountChange(editedQuote.deliveredSat)) sut.setSendEvent(SendEvent.AmountContinue) advanceBeforeHoldWatchDeadline() - // The first swap's hold payment is no longer this send's. - assertNull(sut.sendUiState.value.paykitSwapRoute?.holdPaymentHash) + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + commit.complete(Result.success(swapRoutePayment())) + advanceBeforeHoldWatchDeadline() + // Backups and Paykit's background work do not wait for the claim. + assertFalse(paymentSubmissionActive.value) + + // The first swap's hold payment is out, so confirming the new quote shows it instead of paying again. confirmSwapRoutedPayment() + assertEquals(swapHoldPending(), awaitItem()) cancelAndIgnoreRemainingEvents() } - verify(pubkySwapsRouteRepo).commit("edited-quote") - assertFalse(sut.sendUiState.value.shouldConfirmPay) + verify(pubkySwapsRouteRepo, never()).commit("edited-quote") + verify(lightningRepo, times(1)).payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull()) + } + + @Test + fun `swap route hold failing after the claim wait ran out retries for the same contact`() = test { + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) + .thenReturn(Result.success(SWAP_HOLD_HASH)) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())) + .thenReturn(Result.failure(PubkySwapClaimTimeoutException(SWAP_ID, AppError("awaiting lockup")))) + openSwapRoutedContactPayment() + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmSwapRoutedPayment() + assertEquals(swapHoldPending(), awaitItem()) + emitSwapHoldPaymentFailed() + advanceBeforeHoldWatchDeadline() + + // Retry on the error screen goes back to Amount, which quotes afresh before confirming. + sut.setSendEvent(SendEvent.ClearPayConfirmation) + sut.setSendEvent(SendEvent.AmountContinue) + advanceBeforeHoldWatchDeadline() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmSwapRoutedPayment() + assertEquals(swapHoldPending(), awaitItem()) + emitSwapHoldPaymentSuccessful() + advanceBeforeHoldWatchDeadline() + cancelAndIgnoreRemainingEvents() + } + verify(pubkySwapsRouteRepo, times(2)).commit(SWAP_QUOTE_ID) + verify(activityRepo).setContact( + contactPublicKey = eq(testPublicKey), + forPaymentId = eq(SWAP_HOLD_HASH), + syncLdkPayments = any(), + walletId = any(), + ) } @Test From 5c9da91ee9f289b56144a81c500dcea15748b3f9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 14 Nov 2026 04:04:16 +0100 Subject: [PATCH 5/9] fix: keep the contact on a swap send retried after its hold fails --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 23 +++++++++- .../viewmodels/AppViewModelSendFlowTest.kt | 42 +++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index c3a28f733f..0d9b3f12c3 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -7386,7 +7386,14 @@ class AppViewModel @Inject constructor( // Paykit's background work go on meanwhile. viewModelScope.launch { finishSwapRoutedPayment( - SwapRoutedPayment(payment, holdPaymentHash, tagsSaved, contactPaymentContext, allowanceAttemptId), + SwapRoutedPayment( + payment = payment, + holdPaymentHash = holdPaymentHash, + tagsSaved = tagsSaved, + contactPaymentContext = contactPaymentContext, + allowanceAttemptId = allowanceAttemptId, + sendGeneration = sendGeneration, + ), holdFailure, isSendCurrent, ) @@ -7423,7 +7430,10 @@ class AppViewModel @Inject constructor( clearPendingContactPaymentContext(holdPaymentHash) releasePrivatePaymentListIfNeeded(swap.contactPaymentContext) if (swap.tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) - if (it is LightningPaymentFailedError) return + if (it is LightningPaymentFailedError) { + restoreSwapContact(swap) + return + } // A failed swap never reveals the preimage, so its hold payment cannot settle and a retry is safe. Logger.error("Failed Pubky Swaps route '${payment.swapId}'", it, context = TAG) pendingPaymentRepo.resolve(PendingPaymentResolution.Failure(holdPaymentHash)) @@ -7431,6 +7441,14 @@ class AppViewModel @Inject constructor( } } + /** Pending took the contact off the send, so a retry from Amount after a failed hold payment pays them again. */ + private fun restoreSwapContact(swap: SwapRoutedPayment) { + if (swap.sendGeneration != sendStateGeneration) return + synchronized(contactPaymentContextLock) { + if (activeContactPaymentContext == null) activeContactPaymentContext = swap.contactPaymentContext + } + } + /** A swap that failed before its hold payment went out moved no funds, so the send retries from the amount. */ private suspend fun failSwapRoutedPayment( error: Throwable, @@ -10431,6 +10449,7 @@ private data class SwapRoutedPayment( val tagsSaved: Boolean, val contactPaymentContext: ContactPaymentContext?, val allowanceAttemptId: String?, + val sendGeneration: Long, ) /** A swap whose hold payment went out for the send of [sendGeneration], which may still pay the contact. */ diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 78133a0bf0..7117400b46 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -19641,6 +19641,48 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(pubkySwapsRouteRepo, times(1)).commit(SWAP_QUOTE_ID) } + @Test + fun `swap route retried after its hold payment fails keeps the contact`() = test { + val privateContext = PrivatePaykitPaymentContext(mapOf(MethodId.P2wpkh.rawValue to REGTEST_ADDRESS), 7uL) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) + .thenReturn(Result.success(SWAP_HOLD_HASH)) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())) + .doSuspendableAnswer { awaitCancellation() } + openSwapRoutedContactPayment(privatePaymentContext = privateContext) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmSwapRoutedPayment() + assertEquals(swapHoldPending(), awaitItem()) + emitSwapHoldPaymentFailed() + advanceBeforeHoldWatchDeadline() + + // Retry on the error screen goes back to Amount, which quotes afresh before confirming. + sut.setSendEvent(SendEvent.ClearPayConfirmation) + sut.setSendEvent(SendEvent.AmountContinue) + advanceBeforeHoldWatchDeadline() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmSwapRoutedPayment() + assertEquals(swapHoldPending(), awaitItem()) + emitSwapHoldPaymentSuccessful() + advanceBeforeHoldWatchDeadline() + cancelAndIgnoreRemainingEvents() + } + verify(pubkySwapsRouteRepo, times(2)).commit(SWAP_QUOTE_ID) + verify(privatePaykitRepo, times(2)).consumePrivatePaymentList(testPublicKey, privateContext) + verify(activityRepo).setContact( + contactPublicKey = eq(testPublicKey), + forPaymentId = eq(SWAP_HOLD_HASH), + syncLdkPayments = any(), + walletId = any(), + ) + } + @Test fun `swap route retry after a refused commit pays from the same private payment list`() = test { val privateContext = PrivatePaykitPaymentContext(mapOf(MethodId.P2wpkh.rawValue to REGTEST_ADDRESS), 7uL) From cca60baeb54f7e08d06599a5077b7f45b8466294 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 14 Nov 2026 04:04:16 +0100 Subject: [PATCH 6/9] feat: retry the swap restore for missed providers --- .../repositories/PubkySwapsRouteRepo.kt | 112 +++++++++++++++--- .../to/bitkit/viewmodels/WalletViewModel.kt | 41 ++++--- .../repositories/PubkySwapsRouteRepoTest.kt | 91 +++++++++++++- .../java/to/bitkit/ui/WalletViewModelTest.kt | 12 +- 4 files changed, 208 insertions(+), 48 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt index 443159995d..fa5d06070f 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt @@ -16,6 +16,11 @@ import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.channelFlow +import kotlinx.coroutines.flow.conflate +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.selects.select import kotlinx.coroutines.withContext @@ -34,6 +39,7 @@ import to.bitkit.models.toCoreNetwork import to.bitkit.utils.AppError import to.bitkit.utils.Logger import to.bitkit.utils.ServiceError +import java.util.concurrent.ConcurrentHashMap import javax.inject.Inject import javax.inject.Singleton import kotlin.time.Duration @@ -63,10 +69,25 @@ class PubkySwapsRouteRepo @Inject constructor( /** How long a broadcast claim is advanced in the background before polling stops. */ private val CONFIRMATION_TIMEOUT = 60.minutes + + /** The most providers bitkit-core asks in one restore; it reports the others incomplete. */ + private const val MAX_RESTORE_PROVIDERS = 30 + + /** How many times a restore asks the providers whose swap list it read only in part. */ + private const val RESTORE_ATTEMPTS = 3 + + /** How long a restore waits before asking again the providers it read only in part. */ + private val RESTORE_RETRY_INTERVAL = 1.minutes } private val scope = appScope(ioDispatcher, TAG) + /** Providers whose swap list a restore read in full, so a later restore asks only the others. */ + private val restoredProviders = ConcurrentHashMap.newKeySet() + + /** Swaps a restore already reported, so a provider asked again never reports one twice. */ + private val reportedSwaps = ConcurrentHashMap.newKeySet() + val isEnabled: Boolean get() = Env.isPubkySwapsRouteEnabled /** The contact behind a provider's pubky, so the review shows who routes the payment. */ @@ -99,27 +120,73 @@ class PubkySwapsRouteRepo @Inject constructor( } /** - * Rebuilds the swaps this wallet started from each provider's listing, after a restore from the seed. The listing - * does not carry the contact's address, so a restored swap claims to a fresh Savings address. bitkit-core checks - * each listed lockup against the Lightning payment this node sent for its hash. Swaps already on record keep the - * destination they were committed with. + * Rebuilds the swaps this wallet started from each provider's listing, after a restore from the seed, emitting the + * swaps each restore found. It restores again whenever the contacts change, as a deferred Pubky session loads them + * late, and a few times for providers whose list it read only in part; each restore asks only the providers not + * yet read in full. + */ + fun restoredSwaps(): Flow = channelFlow { + // A running restore finishes before the next contact list starts one, so none is cut short. + val contactKeys = pubkyRepo.contacts.map { contacts -> contacts.map { it.publicKey }.toSet() } + contactKeys.distinctUntilChanged().conflate().collect { + repeat(RESTORE_ATTEMPTS) { attempt -> + if (attempt > 0) delay(RESTORE_RETRY_INTERVAL) + val swaps = restoreSwaps().getOrElse { + Logger.warn("Failed to restore Pubky Swaps routes", it, context = TAG) + return@repeat + } + if (swaps.restored.isNotEmpty() || swaps.known.isNotEmpty()) send(swaps) + if (swaps.incompleteProviders.isEmpty()) return@collect + } + } + } + + /** + * The listing does not carry the contact's address, so a restored swap claims to a fresh Savings address. + * bitkit-core checks each listed lockup against the Lightning payment this node sent for its hash. Swaps already on + * record keep the destination they were committed with. */ - suspend fun restoreSwaps(): Result = withSecrets { mnemonic, passphrase -> + private suspend fun restoreSwaps(): Result = withSecrets { mnemonic, passphrase -> + val providers = candidates().filterNot { bare(it) in restoredProviders } + if (providers.isEmpty()) return@withSecrets RestoredPubkySwaps(emptyList(), emptyList()) val payoutAddress = lightningRepo.newAddress().getOrThrow() - val report = pubkySwapsRestore( - providers = candidates(), - sentPayments = sentPayments(), - electrumUrl = Env.electrumServerUrl, - payoutAddress = payoutAddress, - feeRateSatVb = CLAIM_FEE_RATE_SAT_VB, - network = Env.network.toCoreNetwork(), - mnemonic = mnemonic, - bip39Passphrase = passphrase, - ) - if (report.incompleteProviders.isNotEmpty()) { - Logger.warn("Swap lists incomplete from '${report.incompleteProviders}'", context = TAG) + val sentPayments = sentPayments() + val restored = mutableListOf() + val known = mutableListOf() + val incomplete = mutableListOf() + val readInFull = mutableListOf() + // bitkit-core asks at most MAX_RESTORE_PROVIDERS providers at once, so a contact past them gets its own call. + providers.chunked(MAX_RESTORE_PROVIDERS).forEach { chunk -> + val report = pubkySwapsRestore( + providers = chunk, + sentPayments = sentPayments, + electrumUrl = Env.electrumServerUrl, + payoutAddress = payoutAddress, + feeRateSatVb = CLAIM_FEE_RATE_SAT_VB, + network = Env.network.toCoreNetwork(), + mnemonic = mnemonic, + bip39Passphrase = passphrase, + ) + restored += report.restored + known += report.known + incomplete += report.incompleteProviders + val incompleteBare = report.incompleteProviders.map(::bare).toSet() + readInFull += chunk.map(::bare).filterNot { it in incompleteBare } } - RestoredPubkySwaps(restored = report.restored, known = report.known) + // Only a restore that returned its swaps marks their providers read, so a failed one asks them again. + restoredProviders += readInFull + if (incomplete.isNotEmpty()) Logger.warn("Swap lists incomplete from '$incomplete'", context = TAG) + RestoredPubkySwaps( + restored = restored.filter(reportedSwaps::add), + known = known.filter(reportedSwaps::add), + incompleteProviders = incomplete, + ) + } + + /** The pubky without its scheme or prefix, as bitkit-core names a provider it reports incomplete. */ + private fun bare(pubky: String): String { + val key = pubky.trim().removePrefix("pubky://") + return key.removePrefix("pubky").takeIf { it.length == PUBKY_KEY_LENGTH } ?: key } /** The Lightning payments this node sent, pending or settled, by hash and the amount paid to the payee. */ @@ -231,10 +298,17 @@ class PubkySwapsRouteRepo @Inject constructor( } } -/** The swaps a restore found: those rebuilt now claim to Savings, those already on record keep their destination. */ +/** Length of a z-base-32 encoded pubky without its prefix. */ +private const val PUBKY_KEY_LENGTH = 52 + +/** + * The swaps a restore found: those rebuilt now claim to Savings, those already on record keep their destination. The + * providers it read only in part are asked again. + */ data class RestoredPubkySwaps( val restored: List, val known: List, + val incompleteProviders: List = emptyList(), ) /** The swap's hold payment failed, so the provider never funds its lockup and the swap is not advanced further. */ diff --git a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index 8e22e31fef..74552a528a 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -580,27 +580,26 @@ class WalletViewModel @Inject constructor( private fun restorePubkySwaps() { if (!pubkySwapsRouteRepo.isEnabled) return viewModelScope.launch(bgDispatcher) { - val swaps = pubkySwapsRouteRepo.restoreSwaps().getOrElse { - Logger.warn("Failed to restore Pubky Swaps routes", it, context = TAG) - return@launch - } - Logger.info( - "Restored '${swaps.restored.size}' Pubky Swaps routes, '${swaps.known.size}' known", - context = TAG, - ) - // A known swap keeps the destination it was committed with, such as the contact, so it is driven silently. - swaps.known.forEach { launch { pubkySwapsRouteRepo.awaitClaim(it) } } - swaps.restored.forEach { swapId -> - launch { - pubkySwapsRouteRepo.awaitClaim(swapId).onSuccess { - // The claim also opens the received sheet above the toasts: stay until dismissed so the user - // still sees why the money came back once that sheet closes. - ToastEventBus.send( - type = Toast.ToastType.INFO, - title = context.getString(R.string.wallet__swap_route_restored_title), - description = context.getString(R.string.wallet__swap_route_restored_text), - autoHide = false, - ) + pubkySwapsRouteRepo.restoredSwaps().collect { swaps -> + Logger.info( + "Restored '${swaps.restored.size}' Pubky Swaps routes, '${swaps.known.size}' known", + context = TAG, + ) + // A known swap keeps the destination it was committed with, such as the contact, so it is driven + // silently. + swaps.known.forEach { launch { pubkySwapsRouteRepo.awaitClaim(it) } } + swaps.restored.forEach { swapId -> + launch { + pubkySwapsRouteRepo.awaitClaim(swapId).onSuccess { + // The claim also opens the received sheet above the toasts: stay until dismissed so the + // user still sees why the money came back once that sheet closes. + ToastEventBus.send( + type = Toast.ToastType.INFO, + title = context.getString(R.string.wallet__swap_route_restored_title), + description = context.getString(R.string.wallet__swap_route_restored_text), + autoHide = false, + ) + } } } } diff --git a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt index 86b7807095..dc27335355 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt @@ -1,11 +1,16 @@ package to.bitkit.repositories +import com.synonym.bitkitcore.PubkySwapRestoreReport import com.synonym.bitkitcore.PubkySwapRouteState import com.synonym.bitkitcore.PubkySwapRouteStatus import com.synonym.bitkitcore.pubkySwapsAdvance +import com.synonym.bitkitcore.pubkySwapsRestore import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.flow.toList import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.advanceUntilIdle @@ -16,14 +21,18 @@ import org.mockito.Mockito.mockStatic import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.atLeast +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.whenever import to.bitkit.data.keychain.Keychain +import to.bitkit.models.PubkyProfile import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError import kotlin.test.assertEquals import kotlin.test.assertIs +import kotlin.test.assertTrue import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds @@ -38,6 +47,9 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } private val keychain = mock() + private val contacts = MutableStateFlow>(emptyList()) + private val pubkyRepo = mock { on { contacts } doReturn contacts } + private val lightningRepo = mock() private lateinit var sut: PubkySwapsRouteRepo @Before @@ -46,8 +58,8 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { sut = PubkySwapsRouteRepo( ioDispatcher = testDispatcher, keychain = keychain, - pubkyRepo = mock(), - lightningRepo = mock(), + pubkyRepo = pubkyRepo, + lightningRepo = lightningRepo, ) } @@ -144,6 +156,81 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } } + @Test + fun `restoredSwaps asks again only the providers it read in part`() = test { + contacts.value = listOf(PubkyProfile.placeholder("provider-a"), PubkyProfile.placeholder("provider-b")) + val asked = mutableListOf>() + val swaps = restoring( + asked, + report(restored = listOf("swap-a"), incomplete = listOf("provider-a")), + report(restored = listOf("swap-a", "swap-a2")), + ) { sut.restoredSwaps().take(2).toList() } + + assertEquals(listOf(listOf("swap-a"), listOf("swap-a2")), swaps.map { it.restored }) + assertEquals(listOf("provider-a"), asked.last()) + } + + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `restoredSwaps asks the providers past bitkit-core's limit in another call`() = test { + val keys = (1..31).map { "provider-$it" } + contacts.value = keys.map(PubkyProfile::placeholder) + val asked = mutableListOf>() + restoring(asked, report()) { + backgroundScope.launch { sut.restoredSwaps().collect {} } + advanceUntilIdle() + } + + assertEquals(keys.toSet(), asked.flatten().toSet()) + assertTrue(asked.all { it.size <= 30 }) + } + + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `restoredSwaps restores again for contacts that load later`() = test { + val asked = mutableListOf>() + restoring(asked, report()) { + backgroundScope.launch { sut.restoredSwaps().collect {} } + advanceUntilIdle() + contacts.value = listOf(PubkyProfile.placeholder("provider-late")) + advanceUntilIdle() + } + + assertEquals(listOf("provider-late"), asked.last()) + } + + private suspend fun restoring( + asked: MutableList>, + vararg reports: PubkySwapRestoreReport, + block: suspend () -> T, + ): T { + whenever(lightningRepo.newAddress()).thenReturn(Result.success("bcrt1qpayout")) + whenever(lightningRepo.getPayments()).thenReturn(Result.success(emptyList())) + return mockStatic(CORE).use { core -> + var call = 0 + core.`when` { + runBlocking { + pubkySwapsRestore(any(), any(), any(), any(), eq(2uL), any(), any(), anyOrNull()) + } + }.thenAnswer { + @Suppress("UNCHECKED_CAST") + asked += it.arguments[0] as List + reports[minOf(call++, reports.lastIndex)] + } + block() + } + } + + private fun report( + restored: List = emptyList(), + incomplete: List = emptyList(), + ) = PubkySwapRestoreReport( + restored = restored, + known = emptyList(), + finished = emptyList(), + incompleteProviders = incomplete, + ) + private suspend fun advancing(vararg answers: Any, block: suspend () -> T): T = mockStatic(CORE).use { core -> var stub = core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } diff --git a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt index 34e9ed9b92..709f0b5d51 100644 --- a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt @@ -357,8 +357,8 @@ class WalletViewModelTest : BaseUnitTest() { @Test fun `restores swap routes once a wallet restore completes`() = test { whenever(pubkySwapsRouteRepo.isEnabled).thenReturn(true) - whenever(pubkySwapsRouteRepo.restoreSwaps()) - .thenReturn(Result.success(RestoredPubkySwaps(listOf("swap"), emptyList()))) + whenever(pubkySwapsRouteRepo.restoredSwaps()) + .thenReturn(flowOf(RestoredPubkySwaps(listOf("swap"), emptyList()))) whenever(pubkySwapsRouteRepo.awaitClaim(eq("swap"), any(), anyOrNull())).thenReturn(Result.success("txid")) whenever(context.getString(any())).thenReturn("text") whenever(backupRepo.getLatestBackupTime()).thenReturn(1uL) @@ -372,7 +372,7 @@ class WalletViewModelTest : BaseUnitTest() { advanceUntilIdle() assertEquals(RestoreState.Completed(emptySet()), sut.restoreState.value) - verify(pubkySwapsRouteRepo).restoreSwaps() + verify(pubkySwapsRouteRepo).restoredSwaps() verify(pubkySwapsRouteRepo).awaitClaim(eq("swap"), any(), anyOrNull()) verify(context).getString(R.string.wallet__swap_route_restored_title) } @@ -380,8 +380,8 @@ class WalletViewModelTest : BaseUnitTest() { @Test fun `drives known swap routes after a restore without the Savings notice`() = test { whenever(pubkySwapsRouteRepo.isEnabled).thenReturn(true) - whenever(pubkySwapsRouteRepo.restoreSwaps()) - .thenReturn(Result.success(RestoredPubkySwaps(emptyList(), listOf("swap")))) + whenever(pubkySwapsRouteRepo.restoredSwaps()) + .thenReturn(flowOf(RestoredPubkySwaps(emptyList(), listOf("swap")))) whenever(pubkySwapsRouteRepo.awaitClaim(eq("swap"), any(), anyOrNull())).thenReturn(Result.success("txid")) whenever(context.getString(any())).thenReturn("text") whenever(backupRepo.getLatestBackupTime()).thenReturn(1uL) @@ -412,7 +412,7 @@ class WalletViewModelTest : BaseUnitTest() { advanceUntilIdle() assertEquals(RestoreState.Completed(emptySet()), sut.restoreState.value) - verify(pubkySwapsRouteRepo, never()).restoreSwaps() + verify(pubkySwapsRouteRepo, never()).restoredSwaps() } @Test From 09d69f73a7bb96dc41f9e9efcc2e3d424df6984a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 14 Nov 2026 04:04:17 +0100 Subject: [PATCH 7/9] feat: resume unfinished swaps until their claim confirms --- .../main/java/to/bitkit/data/CacheStore.kt | 2 + .../repositories/PubkySwapsRouteRepo.kt | 115 +++++++++++++----- .../to/bitkit/viewmodels/WalletViewModel.kt | 1 + .../repositories/PubkySwapsRouteRepoTest.kt | 82 +++++++++++++ 4 files changed, 172 insertions(+), 28 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 872ad97ccb..65cd48635b 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -356,6 +356,8 @@ data class AppCacheData( val pendingSparkWithdrawal: PendingSparkWithdrawal? = null, /** The latest Spark withdrawals to Paykit contacts that settled as sent, so a restart never reads one as unsent. */ val sentSparkWithdrawals: List = listOf(), + /** Pubky Swaps routes committed or restored whose claim has not confirmed yet, so each start resumes them. */ + val unfinishedPubkySwaps: List = listOf(), /** Hashes of the latest Lightning sends Spark started, so the node holds off while Spark can't list them. */ val sparkSendHashes: List = listOf(), /** Invoice expiry in epoch seconds of the [sparkSendHashes] that know it. */ diff --git a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt index fa5d06070f..3e8348c828 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt @@ -15,11 +15,13 @@ import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.conflate import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.selects.select @@ -29,6 +31,7 @@ import org.lightningdevkit.ldknode.PaymentDirection import org.lightningdevkit.ldknode.PaymentKind import org.lightningdevkit.ldknode.PaymentStatus import to.bitkit.async.appScope +import to.bitkit.data.CacheStore import to.bitkit.data.keychain.Keychain import to.bitkit.di.IoDispatcher import to.bitkit.env.Env @@ -57,6 +60,7 @@ class PubkySwapsRouteRepo @Inject constructor( private val keychain: Keychain, private val pubkyRepo: PubkyRepo, private val lightningRepo: LightningRepo, + private val cacheStore: CacheStore, ) { companion object { private const val TAG = "PubkySwapsRouteRepo" @@ -64,12 +68,9 @@ class PubkySwapsRouteRepo @Inject constructor( private val POLL_INTERVAL = 2.seconds private val CLAIM_TIMEOUT = 10.minutes - /** How often a broadcast claim is advanced, so bitkit-core rebroadcasts it until it confirms. */ + /** How often a swap is advanced in the background, so bitkit-core rebroadcasts its claim until it confirms. */ private val CONFIRMATION_POLL_INTERVAL = 30.seconds - /** How long a broadcast claim is advanced in the background before polling stops. */ - private val CONFIRMATION_TIMEOUT = 60.minutes - /** The most providers bitkit-core asks in one restore; it reports the others incomplete. */ private const val MAX_RESTORE_PROVIDERS = 30 @@ -88,6 +89,12 @@ class PubkySwapsRouteRepo @Inject constructor( /** Swaps a restore already reported, so a provider asked again never reports one twice. */ private val reportedSwaps = ConcurrentHashMap.newKeySet() + /** Swaps a caller awaits the claim of, which no resume advances beside it. */ + private val claiming = ConcurrentHashMap.newKeySet() + + /** Swaps advanced in the background, each by one loop. */ + private val advancing = ConcurrentHashMap.newKeySet() + val isEnabled: Boolean get() = Env.isPubkySwapsRouteEnabled /** The contact behind a provider's pubky, so the review shows who routes the payment. */ @@ -176,6 +183,7 @@ class PubkySwapsRouteRepo @Inject constructor( // Only a restore that returned its swaps marks their providers read, so a failed one asks them again. restoredProviders += readInFull if (incomplete.isNotEmpty()) Logger.warn("Swap lists incomplete from '$incomplete'", context = TAG) + track(restored + known) RestoredPubkySwaps( restored = restored.filter(reportedSwaps::add), known = known.filter(reportedSwaps::add), @@ -208,8 +216,21 @@ class PubkySwapsRouteRepo @Inject constructor( private fun candidates(): List = (Env.pubkySwapsProviders + pubkyRepo.contacts.value.map { it.publicKey }).distinct() + /** Commits the quote and keeps its swap until its claim confirms or it fails, so a later start resumes it. */ suspend fun commit(quoteId: String): Result = withSecrets { mnemonic, passphrase -> - pubkySwapsCommitRoute(quoteId, Env.electrumServerUrl, mnemonic, passphrase) + pubkySwapsCommitRoute(quoteId, Env.electrumServerUrl, mnemonic, passphrase).also { track(listOf(it.swapId)) } + } + + /** + * Advances each swap a closed app left unfinished until its claim confirms or it fails: the provider settles the + * hold invoice once it sees the claim, so a claim that never confirms could leave the contact unpaid. + */ + fun resumeUnfinishedSwaps() { + scope.launch { + cacheStore.data.first().unfinishedPubkySwaps + .filterNot { it in claiming } + .forEach { advanceInBackground(it) } + } } /** @@ -225,39 +246,77 @@ class PubkySwapsRouteRepo @Inject constructor( timeout: Duration = CLAIM_TIMEOUT, holdFailure: Job? = null, ): Result = scope.async { - var lastFailure: Throwable? = null - val poll = async { - withTimeoutOrNull(timeout) { - pollClaim(swapId, POLL_INTERVAL, untilConfirmed = false) { lastFailure = it } - } - } - // A cancelled watch, as on a cleared screen, says nothing about the hold payment, so the swap keeps advancing. - val holdFailed = CompletableDeferred() - val handle = holdFailure?.invokeOnCompletion { if (it == null) holdFailed.complete(Unit) } - val isHoldFailed = select { - poll.onJoin { false } - holdFailed.onJoin { true } - } - handle?.dispose() - if (isHoldFailed) { - poll.cancel() - return@async Result.failure(PubkySwapHoldFailedException(swapId)) - } - poll.await()?.onSuccess { advanceInBackground(swapId) } ?: run { - // The provider may still settle the hold payment, so the swap keeps advancing towards its claim. - advanceInBackground(swapId) - Result.failure(PubkySwapClaimTimeoutException(swapId, lastFailure)) + claiming.add(swapId) + try { + awaitClaimOnce(swapId, timeout, holdFailure) + } finally { + claiming.remove(swapId) } }.await() + private suspend fun awaitClaimOnce(swapId: String, timeout: Duration, holdFailure: Job?): Result = + coroutineScope { + var lastFailure: Throwable? = null + val poll = async { + withTimeoutOrNull(timeout) { + pollClaim(swapId, POLL_INTERVAL, untilConfirmed = false) { lastFailure = it } + } + } + // A cancelled watch, as on a cleared screen, says nothing about the hold payment, so the swap keeps + // advancing. + val holdFailed = CompletableDeferred() + val handle = holdFailure?.invokeOnCompletion { if (it == null) holdFailed.complete(Unit) } + val isHoldFailed = select { + poll.onJoin { false } + holdFailed.onJoin { true } + } + handle?.dispose() + if (isHoldFailed) { + poll.cancel() + untrack(swapId) + return@coroutineScope Result.failure(PubkySwapHoldFailedException(swapId)) + } + when (val claim = poll.await()) { + null -> { + // The provider may still settle the hold payment, so the swap keeps advancing towards its claim. + advanceInBackground(swapId) + Result.failure(PubkySwapClaimTimeoutException(swapId, lastFailure)) + } + else -> claim.onSuccess { advanceInBackground(swapId) }.onFailure { untrack(swapId) } + } + } + + /** Advances the swap until its claim confirms or it fails, in one loop per swap. */ private fun advanceInBackground(swapId: String) { - scope.launch { withTimeoutOrNull(CONFIRMATION_TIMEOUT) { awaitConfirmation(swapId) } } + if (!advancing.add(swapId)) return + scope.launch { + try { + awaitConfirmation(swapId) + } finally { + advancing.remove(swapId) + } + } } private suspend fun awaitConfirmation(swapId: String) { pollClaim(swapId, CONFIRMATION_POLL_INTERVAL, untilConfirmed = true) {} .onSuccess { Logger.info("Confirmed Pubky Swaps claim '$it' for '$swapId'", context = TAG) } .onFailure { Logger.warn("Failed to confirm Pubky Swaps claim for '$swapId'", it, context = TAG) } + untrack(swapId) + } + + // A failed write never fails the swap it records: the commit already happened. + private suspend fun track(swapIds: List) { + if (swapIds.isEmpty()) return + runSuspendCatching { + cacheStore.update { it.copy(unfinishedPubkySwaps = (it.unfinishedPubkySwaps + swapIds).distinct()) } + }.onFailure { Logger.warn("Failed to record unfinished Pubky Swaps routes '$swapIds'", it, context = TAG) } + } + + private suspend fun untrack(swapId: String) { + runSuspendCatching { + cacheStore.update { it.copy(unfinishedPubkySwaps = it.unfinishedPubkySwaps - swapId) } + }.onFailure { Logger.warn("Failed to drop finished Pubky Swaps route '$swapId'", it, context = TAG) } } private suspend fun pollClaim( diff --git a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index 74552a528a..81a38f2966 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -825,6 +825,7 @@ class WalletViewModel @Inject constructor( walletRepo.refreshBip21() } ensureSwapUpdatesRunning() + if (pubkySwapsRouteRepo.isEnabled) pubkySwapsRouteRepo.resumeUnfinishedSwaps() // checkForOrphanedChannelMonitorRecovery() } } diff --git a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt index dc27335355..e519abb74a 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt @@ -1,9 +1,11 @@ package to.bitkit.repositories import com.synonym.bitkitcore.PubkySwapRestoreReport +import com.synonym.bitkitcore.PubkySwapRoutePayment import com.synonym.bitkitcore.PubkySwapRouteState import com.synonym.bitkitcore.PubkySwapRouteStatus import com.synonym.bitkitcore.pubkySwapsAdvance +import com.synonym.bitkitcore.pubkySwapsCommitRoute import com.synonym.bitkitcore.pubkySwapsRestore import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -11,6 +13,7 @@ import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.advanceUntilIdle @@ -26,6 +29,8 @@ import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.whenever +import to.bitkit.data.AppCacheData +import to.bitkit.data.CacheStore import to.bitkit.data.keychain.Keychain import to.bitkit.models.PubkyProfile import to.bitkit.test.BaseUnitTest @@ -50,16 +55,23 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { private val contacts = MutableStateFlow>(emptyList()) private val pubkyRepo = mock { on { contacts } doReturn contacts } private val lightningRepo = mock() + private val cacheData = MutableStateFlow(AppCacheData()) + private val cacheStore = mock { on { data } doReturn cacheData } private lateinit var sut: PubkySwapsRouteRepo @Before fun setUp() { whenever(keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn("mnemonic") + whenever { cacheStore.update(any()) }.thenAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + cacheData.update(transform) + } sut = PubkySwapsRouteRepo( ioDispatcher = testDispatcher, keychain = keychain, pubkyRepo = pubkyRepo, lightningRepo = lightningRepo, + cacheStore = cacheStore, ) } @@ -126,6 +138,7 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } .thenReturn(status(PubkySwapRouteState.AwaitingLockup(confirmations = 0u, required = 1u))) val holdFailure = CompletableDeferred() + cacheData.value = AppCacheData(unfinishedPubkySwaps = listOf(SWAP_ID)) val result = async { sut.awaitClaim(SWAP_ID, holdFailure = holdFailure) } runCurrent() @@ -133,6 +146,8 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { advanceUntilIdle() assertIs(result.await().exceptionOrNull()) + // The provider never funds a swap whose hold payment failed, so no later start resumes it. + assertEquals(emptyList(), cacheData.value.unfinishedPubkySwaps) core.verify({ runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } }, times(1)) } } @@ -156,6 +171,63 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } } + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `commit keeps the swap to resume until its claim confirms`() = test { + mockStatic(CORE).use { core -> + core.`when` { runBlocking { pubkySwapsCommitRoute(any(), any(), any(), anyOrNull()) } } + .thenReturn(swapPayment()) + core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } + .thenReturn(status(PubkySwapRouteState.ClaimBroadcast(CLAIM_TXID))) + .thenReturn(status(PubkySwapRouteState.Claimed(CONFIRMED_CLAIM_TXID))) + + sut.commit("quote") + assertEquals(listOf(SWAP_ID), cacheData.value.unfinishedPubkySwaps) + + sut.awaitClaim(SWAP_ID) + advanceUntilIdle() + assertEquals(emptyList(), cacheData.value.unfinishedPubkySwaps) + } + } + + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `resumeUnfinishedSwaps advances a stored swap past an hour until its claim confirms`() = test { + cacheData.value = AppCacheData(unfinishedPubkySwaps = listOf(SWAP_ID)) + mockStatic(CORE).use { core -> + var calls = 0 + core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } }.thenAnswer { + // At 30 s apart, 150 unconfirmed claims outlast an hour. + if (++calls <= 150) { + status(PubkySwapRouteState.ClaimBroadcast(CLAIM_TXID)) + } else { + status(PubkySwapRouteState.Claimed(CONFIRMED_CLAIM_TXID)) + } + } + + sut.resumeUnfinishedSwaps() + advanceUntilIdle() + + assertEquals(151, calls) + assertEquals(emptyList(), cacheData.value.unfinishedPubkySwaps) + } + } + + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `resumeUnfinishedSwaps drops a swap that failed`() = test { + cacheData.value = AppCacheData(unfinishedPubkySwaps = listOf(SWAP_ID)) + mockStatic(CORE).use { core -> + core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } + .thenReturn(status(PubkySwapRouteState.Failed("refunded"))) + + sut.resumeUnfinishedSwaps() + advanceUntilIdle() + + assertEquals(emptyList(), cacheData.value.unfinishedPubkySwaps) + } + } + @Test fun `restoredSwaps asks again only the providers it read in part`() = test { contacts.value = listOf(PubkyProfile.placeholder("provider-a"), PubkyProfile.placeholder("provider-b")) @@ -221,6 +293,16 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } } + private fun swapPayment() = PubkySwapRoutePayment( + swapId = SWAP_ID, + invoice = "invoice", + debitSat = 20_100u, + deliveredSat = 20_000u, + destinationAddress = "address", + htlcAddress = "htlc", + timeoutBlockHeight = 0u, + ) + private fun report( restored: List = emptyList(), incomplete: List = emptyList(), From 816eb30eed649c3acc8d2782c887d7a471a3f623 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 14 Nov 2026 04:56:28 +0100 Subject: [PATCH 8/9] fix: stop advancing a swap bitkit-core has no record of --- .../bitkit/repositories/PubkySwapsRouteRepo.kt | 8 ++++++-- .../repositories/PubkySwapsRouteRepoTest.kt | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt index 3e8348c828..f0cc067d13 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt @@ -3,6 +3,7 @@ package to.bitkit.repositories import com.synonym.bitkitcore.PaykitEndpoint import com.synonym.bitkitcore.PaykitRoute import com.synonym.bitkitcore.PaykitRouteRequest +import com.synonym.bitkitcore.PubkySwapException import com.synonym.bitkitcore.PubkySwapRoutePayment import com.synonym.bitkitcore.PubkySwapRouteState import com.synonym.bitkitcore.PubkySwapSentPayment @@ -326,8 +327,11 @@ class PubkySwapsRouteRepo @Inject constructor( onPending: (Throwable) -> Unit, ): Result { while (true) { - // A failed advance, such as a transient Electrum error, is retried: the swap is already funded. - val state = withSecrets { mnemonic, passphrase -> pubkySwapsAdvance(swapId, mnemonic, passphrase) } + // A failed advance, such as a transient Electrum error, is retried: the swap is already funded. A swap + // bitkit-core has no record of, as one carried over by a metadata backup, never advances, so it ends here. + val advance = withSecrets { mnemonic, passphrase -> pubkySwapsAdvance(swapId, mnemonic, passphrase) } + advance.exceptionOrNull()?.let { if (it is PubkySwapException.NotFound) return Result.failure(it) } + val state = advance .onFailure { Logger.warn("Failed to advance Pubky Swaps route '$swapId'", it, context = TAG) onPending(it) diff --git a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt index e519abb74a..63f27c3c4b 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt @@ -1,5 +1,6 @@ package to.bitkit.repositories +import com.synonym.bitkitcore.PubkySwapException import com.synonym.bitkitcore.PubkySwapRestoreReport import com.synonym.bitkitcore.PubkySwapRoutePayment import com.synonym.bitkitcore.PubkySwapRouteState @@ -228,6 +229,22 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { } } + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `resumeUnfinishedSwaps drops a swap bitkit-core has no record of`() = test { + cacheData.value = AppCacheData(unfinishedPubkySwaps = listOf(SWAP_ID)) + mockStatic(CORE).use { core -> + core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } } + .thenThrow(PubkySwapException.NotFound("no swap record")) + + sut.resumeUnfinishedSwaps() + advanceUntilIdle() + + assertEquals(emptyList(), cacheData.value.unfinishedPubkySwaps) + core.verify({ runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } }, times(1)) + } + } + @Test fun `restoredSwaps asks again only the providers it read in part`() = test { contacts.value = listOf(PubkyProfile.placeholder("provider-a"), PubkyProfile.placeholder("provider-b")) From 276df1098794945f7af4fa1787ab6456e334f7b6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 14 Nov 2026 06:17:14 +0100 Subject: [PATCH 9/9] fix: stop failed swaps and pay once across source switches --- .../repositories/PubkySwapsRouteRepo.kt | 93 +++++++++++++------ .../to/bitkit/usecases/WipeWalletUseCase.kt | 3 + .../java/to/bitkit/viewmodels/AppViewModel.kt | 61 +++++++----- .../to/bitkit/viewmodels/WalletViewModel.kt | 6 +- .../repositories/PubkySwapsRouteRepoTest.kt | 59 ++++++++++++ .../bitkit/usecases/WipeWalletUseCaseTest.kt | 5 + .../viewmodels/AppViewModelSendFlowTest.kt | 56 ++++++++++- 7 files changed, 229 insertions(+), 54 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt index f0cc067d13..9b759ba7a0 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt @@ -14,16 +14,20 @@ import com.synonym.bitkitcore.pubkySwapsRestore import com.synonym.bitkitcore.pubkySwapsRoutePaykitPayment import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.conflate import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.job import kotlinx.coroutines.launch import kotlinx.coroutines.selects.select import kotlinx.coroutines.withContext @@ -84,17 +88,14 @@ class PubkySwapsRouteRepo @Inject constructor( private val scope = appScope(ioDispatcher, TAG) - /** Providers whose swap list a restore read in full, so a later restore asks only the others. */ - private val restoredProviders = ConcurrentHashMap.newKeySet() - - /** Swaps a restore already reported, so a provider asked again never reports one twice. */ - private val reportedSwaps = ConcurrentHashMap.newKeySet() + /** Bumped by each wallet wipe, which ends the wiped wallet's restore. */ + private val wipes = MutableStateFlow(0L) /** Swaps a caller awaits the claim of, which no resume advances beside it. */ private val claiming = ConcurrentHashMap.newKeySet() - /** Swaps advanced in the background, each by one loop. */ - private val advancing = ConcurrentHashMap.newKeySet() + /** The loop advancing each swap in the background, one per swap. */ + private val advancing = ConcurrentHashMap() val isEnabled: Boolean get() = Env.isPubkySwapsRouteEnabled @@ -131,22 +132,39 @@ class PubkySwapsRouteRepo @Inject constructor( * Rebuilds the swaps this wallet started from each provider's listing, after a restore from the seed, emitting the * swaps each restore found. It restores again whenever the contacts change, as a deferred Pubky session loads them * late, and a few times for providers whose list it read only in part; each restore asks only the providers not - * yet read in full. + * yet read in full. It ends when the wallet is wiped. */ fun restoredSwaps(): Flow = channelFlow { - // A running restore finishes before the next contact list starts one, so none is cut short. - val contactKeys = pubkyRepo.contacts.map { contacts -> contacts.map { it.publicKey }.toSet() } - contactKeys.distinctUntilChanged().conflate().collect { - repeat(RESTORE_ATTEMPTS) { attempt -> - if (attempt > 0) delay(RESTORE_RETRY_INTERVAL) - val swaps = restoreSwaps().getOrElse { - Logger.warn("Failed to restore Pubky Swaps routes", it, context = TAG) - return@repeat + val wallet = wipes.value + val run = RestoreRun() + val restore = launch { + // A running restore finishes before the next contact list starts one, so none is cut short. + val contactKeys = pubkyRepo.contacts.map { contacts -> contacts.map { it.publicKey }.toSet() } + contactKeys.distinctUntilChanged().conflate().collect { + repeat(RESTORE_ATTEMPTS) { attempt -> + if (attempt > 0) delay(RESTORE_RETRY_INTERVAL) + val swaps = restoreSwaps(run).getOrElse { + Logger.warn("Failed to restore Pubky Swaps routes", it, context = TAG) + return@repeat + } + if (swaps.restored.isNotEmpty() || swaps.known.isNotEmpty()) send(swaps) + if (swaps.incompleteProviders.isEmpty()) return@collect } - if (swaps.restored.isNotEmpty() || swaps.known.isNotEmpty()) send(swaps) - if (swaps.incompleteProviders.isEmpty()) return@collect } } + val wiped = launch { + wipes.first { it != wallet } + restore.cancel() + } + restore.join() + wiped.cancel() + } + + /** Stops the wiped wallet's restore and background swaps, so a wallet restored next starts from nothing. */ + fun resetForWipe() { + wipes.update { it + 1 } + advancing.values.forEach { it.cancel() } + advancing.clear() } /** @@ -154,10 +172,13 @@ class PubkySwapsRouteRepo @Inject constructor( * bitkit-core checks each listed lockup against the Lightning payment this node sent for its hash. Swaps already on * record keep the destination they were committed with. */ - private suspend fun restoreSwaps(): Result = withSecrets { mnemonic, passphrase -> - val providers = candidates().filterNot { bare(it) in restoredProviders } + private suspend fun restoreSwaps( + run: RestoreRun + ): Result = withSecrets { mnemonic, passphrase -> + val providers = candidates().filterNot { bare(it) in run.restoredProviders } if (providers.isEmpty()) return@withSecrets RestoredPubkySwaps(emptyList(), emptyList()) - val payoutAddress = lightningRepo.newAddress().getOrThrow() + // One address for the whole run, so restores asked again reveal no unused addresses. + val payoutAddress = run.payoutAddress ?: lightningRepo.newAddress().getOrThrow().also { run.payoutAddress = it } val sentPayments = sentPayments() val restored = mutableListOf() val known = mutableListOf() @@ -182,17 +203,16 @@ class PubkySwapsRouteRepo @Inject constructor( readInFull += chunk.map(::bare).filterNot { it in incompleteBare } } // Only a restore that returned its swaps marks their providers read, so a failed one asks them again. - restoredProviders += readInFull + run.restoredProviders += readInFull if (incomplete.isNotEmpty()) Logger.warn("Swap lists incomplete from '$incomplete'", context = TAG) track(restored + known) RestoredPubkySwaps( - restored = restored.filter(reportedSwaps::add), - known = known.filter(reportedSwaps::add), + restored = restored.filter(run.reportedSwaps::add), + known = known.filter(run.reportedSwaps::add), incompleteProviders = incomplete, ) } - /** The pubky without its scheme or prefix, as bitkit-core names a provider it reports incomplete. */ private fun bare(pubky: String): String { val key = pubky.trim().removePrefix("pubky://") return key.removePrefix("pubky").takeIf { it.length == PUBKY_KEY_LENGTH } ?: key @@ -287,16 +307,25 @@ class PubkySwapsRouteRepo @Inject constructor( } } - /** Advances the swap until its claim confirms or it fails, in one loop per swap. */ private fun advanceInBackground(swapId: String) { - if (!advancing.add(swapId)) return - scope.launch { + if (advancing.containsKey(swapId)) return + val loop = scope.launch(start = CoroutineStart.LAZY) { try { awaitConfirmation(swapId) } finally { - advancing.remove(swapId) + advancing.remove(swapId, coroutineContext.job) } } + if (advancing.putIfAbsent(swapId, loop) == null) loop.start() else loop.cancel() + } + + /** + * Stops a swap whose hold payment failed or never went out: the provider never funds it, so advancing it would + * only poll until bitkit-core gives up. + */ + suspend fun dropFailedSwap(swapId: String) { + advancing.remove(swapId)?.cancel() + untrack(swapId) } private suspend fun awaitConfirmation(swapId: String) { @@ -380,3 +409,9 @@ class PubkySwapHoldFailedException(swapId: String) : AppError("Hold payment of s /** A claim wait that ran out with the swap still open: its hold payment may yet settle. */ class PubkySwapClaimTimeoutException(swapId: String, cause: Throwable?) : AppError("Swap '$swapId' not claimed yet", cause) + +private class RestoreRun { + val restoredProviders = mutableSetOf() + val reportedSwaps = mutableSetOf() + var payoutAddress: String? = null +} diff --git a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt index 684585d997..f87460754d 100644 --- a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt @@ -18,6 +18,7 @@ import to.bitkit.repositories.PaykitUsdtPaymentRepo import to.bitkit.repositories.PrivatePaykitAddressReservationRepo import to.bitkit.repositories.PrivatePaykitRepo import to.bitkit.repositories.PubkyRepo +import to.bitkit.repositories.PubkySwapsRouteRepo import to.bitkit.repositories.UsdtRepo import to.bitkit.repositories.WatchOnlyAccountRepo import to.bitkit.services.CoreService @@ -44,6 +45,7 @@ class WipeWalletUseCase @Inject constructor( private val hwWalletRepo: HwWalletRepo, private val lightningRepo: LightningRepo, private val pubkyRepo: PubkyRepo, + private val pubkySwapsRouteRepo: PubkySwapsRouteRepo, private val privatePaykitRepo: Provider, private val privatePaykitAddressReservationRepo: PrivatePaykitAddressReservationRepo, private val firebaseMessaging: FirebaseMessaging, @@ -100,6 +102,7 @@ class WipeWalletUseCase @Inject constructor( private suspend fun wipeLocal(walletIndex: Int, resetWalletState: () -> 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() } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 0d9b3f12c3..a2a8eec8f0 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -285,6 +285,7 @@ import to.bitkit.utils.timedsheets.sheets.NotificationsTimedSheet import to.bitkit.utils.timedsheets.sheets.QuickPayTimedSheet import to.bitkit.utils.timedsheets.sheets.UsdtTimedSheet import java.math.BigDecimal +import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicLong import javax.inject.Inject import kotlin.coroutines.cancellation.CancellationException @@ -420,6 +421,9 @@ class AppViewModel @Inject constructor( private var onchainSendRefreshJob: Job? = null private var sendStateGeneration = 0L + /** Bumped only when a new send starts, unlike [sendStateGeneration], which edits within one send also bump. */ + private var sendSession = 0L + fun setSendEvent(event: SendEvent) { if ((currentSheet.value as? Sheet.Send)?.preparingRequest != null) return when (event) { @@ -584,6 +588,9 @@ class AppViewModel @Inject constructor( /** The swap whose hold payment went out for a send, which may still pay the contact, so that send pays once. */ @Volatile private var committedSwap: CommittedSwap? = null + + /** The swap behind each hold payment still out, so a hold that fails stops its swap. */ + private val swapIdsByHoldHash = ConcurrentHashMap() private var isPresentingPaymentRequest = false private val isPaymentRequestPollingStopped = MutableStateFlow(false) private var isPaymentRequestOverlayVisible = false @@ -7315,6 +7322,7 @@ class AppViewModel @Inject constructor( allowanceAttemptId: String?, ) { val sendGeneration = sendStateGeneration + val session = sendSession // A payment edited from Amount in the same sheet holds a fresh quote or none, so the result is no longer its. val isSendCurrent = { sendGeneration == sendStateGeneration && @@ -7333,6 +7341,8 @@ class AppViewModel @Inject constructor( "Swap hold invoice is not a Lightning invoice" }.paymentHash.toHex() }.getOrElse { + // No hold payment goes out, so the provider never funds the swap. + pubkySwapsRouteRepo.dropFailedSwap(payment.swapId) failSwapRoutedPayment(it, contactPaymentContext, allowanceAttemptId, isSendCurrent()) return } @@ -7354,12 +7364,15 @@ class AppViewModel @Inject constructor( contactPaymentContext?.let { synchronized(contactPaymentContextLock) { pendingContactPaymentContexts[holdPaymentHash] = it } } - committedSwap = CommittedSwap(sendGeneration, holdPaymentHash, payment.deliveredSat) + committedSwap = CommittedSwap(session, holdPaymentHash, payment.deliveredSat) + swapIdsByHoldHash[holdPaymentHash] = payment.swapId // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending. lightningRepo.payInvoice(payment.invoice).onFailure { // Spark may have sent it, so an unknown outcome waits on the claim like a sent hold payment. if (it is PaymentPendingException) return@onFailure holdFailure.cancel() + swapIdsByHoldHash.remove(holdPaymentHash) + pubkySwapsRouteRepo.dropFailedSwap(payment.swapId) clearCommittedSwap(holdPaymentHash) clearPendingContactPaymentContext(holdPaymentHash) if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) @@ -7392,7 +7405,7 @@ class AppViewModel @Inject constructor( tagsSaved = tagsSaved, contactPaymentContext = contactPaymentContext, allowanceAttemptId = allowanceAttemptId, - sendGeneration = sendGeneration, + sendSession = session, ), holdFailure, isSendCurrent, @@ -7414,6 +7427,7 @@ class AppViewModel @Inject constructor( holdFailure.cancel() } claim.onSuccess { + swapIdsByHoldHash.remove(holdPaymentHash) finishManualAllowancePayment(swap.allowanceAttemptId, succeeded = true) Logger.info("Claimed Pubky Swaps route '${payment.swapId}' in '$it'", context = TAG) }.onFailure { @@ -7426,9 +7440,10 @@ class AppViewModel @Inject constructor( // the error screen and finds the send by that hash. clearSwapRouteQuote(isSendCurrent(), keepHoldPaymentHash = it is LightningPaymentFailedError) clearCommittedSwap(holdPaymentHash) + swapIdsByHoldHash.remove(holdPaymentHash) finishManualAllowancePayment(swap.allowanceAttemptId, succeeded = false) clearPendingContactPaymentContext(holdPaymentHash) - releasePrivatePaymentListIfNeeded(swap.contactPaymentContext) + releaseSwapPrivatePaymentList(swap.contactPaymentContext) if (swap.tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash) if (it is LightningPaymentFailedError) { restoreSwapContact(swap) @@ -7441,9 +7456,8 @@ class AppViewModel @Inject constructor( } } - /** Pending took the contact off the send, so a retry from Amount after a failed hold payment pays them again. */ private fun restoreSwapContact(swap: SwapRoutedPayment) { - if (swap.sendGeneration != sendStateGeneration) return + if (swap.sendSession != sendSession) return synchronized(contactPaymentContextLock) { if (activeContactPaymentContext == null) activeContactPaymentContext = swap.contactPaymentContext } @@ -7457,10 +7471,7 @@ class AppViewModel @Inject constructor( isCurrent: Boolean, ) { clearSwapRouteQuote(isCurrent) - // Nothing was paid to the list's address, so a retry may pay from the same list. - contactPaymentContext?.privatePaymentContext?.let { - privatePaykitRepo.releasePrivatePaymentList(contactPaymentContext.publicKey, it) - } + releaseSwapPrivatePaymentList(contactPaymentContext) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) if (!isCurrent) { handlePaymentPreparationFailure(error, contactPaymentContext, isSendCurrent = false) @@ -7479,12 +7490,8 @@ class AppViewModel @Inject constructor( } } - /** - * Shows the pending payment of a swap this send already paid a hold invoice for, instead of paying again: a quote - * made after backing out of Confirm mid-commit would pay the contact a second time. - */ private fun showCommittedSwap(): Boolean { - val swap = committedSwap?.takeIf { it.sendGeneration == sendStateGeneration } ?: return false + val swap = committedSwap?.takeIf { it.sendSession == sendSession } ?: return false setSendEffect( SendEffect.NavigateToPending( paymentHash = swap.holdPaymentHash, @@ -7495,18 +7502,28 @@ class AppViewModel @Inject constructor( return true } + private suspend fun releaseSwapPrivatePaymentList(context: ContactPaymentContext?) { + val privatePaymentContext = context?.privatePaymentContext ?: return + privatePaykitRepo.releasePrivatePaymentList(context.publicKey, privatePaymentContext) + } + private fun clearCommittedSwap(holdPaymentHash: String) { if (committedSwap?.holdPaymentHash == holdPaymentHash) committedSwap = null } - /** - * A failed hold payment paid nothing, also one that failed after the claim wait ran out, so its send may retry - * from Amount, for the contact Pending took off the send. - */ private fun releaseFailedSwapHold(paymentHash: String) { + // The provider never funds a swap whose hold payment failed, so it stops advancing, and the contact's list + // paid nothing. + swapIdsByHoldHash.remove(paymentHash)?.let { swapId -> + val context = synchronized(contactPaymentContextLock) { pendingContactPaymentContexts[paymentHash] } + viewModelScope.launch { + pubkySwapsRouteRepo.dropFailedSwap(swapId) + releaseSwapPrivatePaymentList(context) + } + } val swap = committedSwap?.takeIf { it.holdPaymentHash == paymentHash } ?: return committedSwap = null - if (swap.sendGeneration != sendStateGeneration) return + if (swap.sendSession != sendSession) return synchronized(contactPaymentContextLock) { if (activeContactPaymentContext == null) { activeContactPaymentContext = pendingContactPaymentContexts[paymentHash] @@ -8585,6 +8602,7 @@ class AppViewModel @Inject constructor( val hardwareAvailableSats = hardwareWalletId?.let { hardwareEstimatedAvailable(it, speed, rates) } ?: 0uL if (!canPrepareSend(walletGeneration)) return false sendStateGeneration++ + sendSession++ addressValidationJob?.cancel() paykitReviewedAmount = null paykitAmountConversion = PaykitAmountConversion() @@ -10449,12 +10467,11 @@ private data class SwapRoutedPayment( val tagsSaved: Boolean, val contactPaymentContext: ContactPaymentContext?, val allowanceAttemptId: String?, - val sendGeneration: Long, + val sendSession: Long, ) -/** A swap whose hold payment went out for the send of [sendGeneration], which may still pay the contact. */ private data class CommittedSwap( - val sendGeneration: Long, + val sendSession: Long, val holdPaymentHash: String, val deliveredSat: ULong, ) diff --git a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index 81a38f2966..5e507ea248 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -573,13 +573,17 @@ class WalletViewModel @Inject constructor( _restoreState.update { RestoreState.Settled } } + private var pubkySwapsRestoreJob: Job? = null + /** * Finishes swap routes a restored wallet left in flight: each is rebuilt from its provider's listing and claimed to * Savings, since the contact's address did not survive the restore, so the user learns the payment came back. */ private fun restorePubkySwaps() { if (!pubkySwapsRouteRepo.isEnabled) return - viewModelScope.launch(bgDispatcher) { + // One restore watches the contacts at a time; a wipe ends it. + pubkySwapsRestoreJob?.cancel() + pubkySwapsRestoreJob = viewModelScope.launch(bgDispatcher) { pubkySwapsRouteRepo.restoredSwaps().collect { swaps -> Logger.info( "Restored '${swaps.restored.size}' Pubky Swaps routes, '${swaps.known.size}' known", diff --git a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt index 63f27c3c4b..040a32a30f 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt @@ -17,6 +17,7 @@ import kotlinx.coroutines.flow.toList import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent import org.junit.Before @@ -29,6 +30,7 @@ import org.mockito.kotlin.doReturn 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.AppCacheData import to.bitkit.data.CacheStore @@ -288,6 +290,63 @@ class PubkySwapsRouteRepoTest : BaseUnitTest() { assertEquals(listOf("provider-late"), asked.last()) } + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `dropFailedSwap stops advancing a swap after its claim wait ran out`() = test { + cacheData.value = AppCacheData(unfinishedPubkySwaps = listOf(SWAP_ID)) + mockStatic(CORE).use { core -> + var calls = 0 + core.`when` { runBlocking { pubkySwapsAdvance(any(), any(), anyOrNull()) } }.thenAnswer { + calls++ + status(PubkySwapRouteState.AwaitingLockup(confirmations = 0u, required = 1u)) + } + + sut.awaitClaim(SWAP_ID, timeout = 1.seconds) + sut.dropFailedSwap(SWAP_ID) + val callsAtDrop = calls + advanceTimeBy(10.minutes) + runCurrent() + + assertEquals(callsAtDrop, calls) + assertEquals(emptyList(), cacheData.value.unfinishedPubkySwaps) + } + } + + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `restoredSwaps reveals one payout address for all its restores`() = test { + contacts.value = listOf(PubkyProfile.placeholder("provider-a")) + val asked = mutableListOf>() + restoring(asked, report(incomplete = listOf("provider-a"))) { + backgroundScope.launch { sut.restoredSwaps().collect {} } + advanceTimeBy(5.minutes) + contacts.value = listOf(PubkyProfile.placeholder("provider-a"), PubkyProfile.placeholder("provider-b")) + advanceTimeBy(5.minutes) + } + + assertEquals(6, asked.size) + verify(lightningRepo, times(1)).newAddress() + } + + @Test + @OptIn(ExperimentalCoroutinesApi::class) + fun `restoredSwaps after a wipe asks again the providers the wiped wallet read`() = test { + contacts.value = listOf(PubkyProfile.placeholder("provider-a")) + val asked = mutableListOf>() + restoring(asked, report()) { + val first = backgroundScope.launch { sut.restoredSwaps().collect {} } + advanceUntilIdle() + sut.resetForWipe() + advanceUntilIdle() + assertTrue(first.isCompleted) + + backgroundScope.launch { sut.restoredSwaps().collect {} } + advanceUntilIdle() + } + + assertEquals(listOf(listOf("provider-a"), listOf("provider-a")), asked) + } + private suspend fun restoring( asked: MutableList>, vararg reports: PubkySwapRestoreReport, diff --git a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt index 6d5147b117..b3e5f16f2b 100644 --- a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt @@ -33,6 +33,7 @@ import to.bitkit.repositories.PaykitUsdtPaymentRepo import to.bitkit.repositories.PrivatePaykitAddressReservationRepo import to.bitkit.repositories.PrivatePaykitRepo import to.bitkit.repositories.PubkyRepo +import to.bitkit.repositories.PubkySwapsRouteRepo import to.bitkit.repositories.UsdtRepo import to.bitkit.repositories.WatchOnlyAccountRepo import to.bitkit.services.CoreService @@ -64,6 +65,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { private val hwWalletRepo = mock() private val lightningRepo = mock() private val pubkyRepo = mock() + private val pubkySwapsRouteRepo = mock() private val privatePaykitRepo = mock() private val privatePaykitAddressReservationRepo = mock() private val firebaseMessaging = mock() @@ -108,6 +110,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { hwWalletRepo = hwWalletRepo, lightningRepo = lightningRepo, pubkyRepo = pubkyRepo, + pubkySwapsRouteRepo = pubkySwapsRouteRepo, privatePaykitRepo = privatePaykitRepoProvider, privatePaykitAddressReservationRepo = privatePaykitAddressReservationRepo, firebaseMessaging = firebaseMessaging, @@ -141,6 +144,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { hwWalletRepo, lightningRepo, pubkyRepo, + pubkySwapsRouteRepo, privatePaykitRepo, privatePaykitAddressReservationRepo, migrationService, @@ -153,6 +157,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { inOrder.verify(pubkyRepo).removeBitkitPaymentEndpoints() inOrder.verify(privatePaykitRepo).closeAndClear() inOrder.verify(lightningRepo).wipeStorage(0) + inOrder.verify(pubkySwapsRouteRepo).resetForWipe() inOrder.verify(migrationService).setNeedsPostMigrationSync(false) inOrder.verify(migrationService).cleanupAfterMigration() inOrder.verify(privatePaykitAddressReservationRepo).clear() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 7117400b46..37adc82582 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -19500,6 +19500,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { expectNoEvents() } verify(pubkySwapsRouteRepo, never()).awaitClaim(any(), any(), anyOrNull()) + verify(pubkySwapsRouteRepo).dropFailedSwap(SWAP_ID) } @Test @@ -19644,8 +19645,19 @@ class AppViewModelSendFlowTest : BaseUnitTest() { @Test fun `swap route retried after its hold payment fails keeps the contact`() = test { val privateContext = PrivatePaykitPaymentContext(mapOf(MethodId.P2wpkh.rawValue to REGTEST_ADDRESS), 7uL) - whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) - .thenReturn(Result.success(Unit)) + var consumed = false + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)).doSuspendableAnswer { + if (consumed) { + Result.failure(PrivatePaykitError.PaymentListAlreadyConsumed) + } else { + consumed = true + Result.success(Unit) + } + } + whenever(privatePaykitRepo.releasePrivatePaymentList(testPublicKey, privateContext)).doSuspendableAnswer { + consumed = false + Result.success(Unit) + } whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) .thenReturn(Result.success(SWAP_HOLD_HASH)) @@ -19871,6 +19883,44 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(lightningRepo, times(1)).payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull()) } + @Test + fun `swap route send switched between sources mid-commit pays the contact once`() = test { + val commit = CompletableDeferred>() + val claim = CompletableDeferred>() + val freshQuote = swapRouteQuote().copy(quoteId = "fresh-quote") + whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).doSuspendableAnswer { commit.await() } + whenever(pubkySwapsRouteRepo.commit("fresh-quote")).thenReturn(Result.success(swapRoutePayment())) + whenever(lightningRepo.payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull())) + .thenReturn(Result.success(SWAP_HOLD_HASH)) + whenever(pubkySwapsRouteRepo.awaitClaim(eq(SWAP_ID), any(), anyOrNull())).doSuspendableAnswer { claim.await() } + openSwapRoutedContactPayment() + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + confirmSwapRoutedPayment() + // Backing out of Confirm while the provider is slow to commit, Savings then Spending quotes afresh. + whenever(pubkySwapsRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Swap(freshQuote))) + sut.setSendEvent(SendEvent.PaymentMethodSwitch) + advanceBeforeHoldWatchDeadline() + sut.setSendEvent(SendEvent.PaymentMethodSwitch) + advanceBeforeHoldWatchDeadline() + sut.setSendEvent(SendEvent.AmountContinue) + advanceBeforeHoldWatchDeadline() + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + commit.complete(Result.success(swapRoutePayment())) + advanceBeforeHoldWatchDeadline() + + // The first swap's hold payment is out, so confirming the fresh quote shows it instead of paying again. + confirmSwapRoutedPayment() + assertEquals(swapHoldPending(), awaitItem()) + cancelAndIgnoreRemainingEvents() + } + verify(pubkySwapsRouteRepo, never()).commit("fresh-quote") + verify(lightningRepo, times(1)).payInvoice(eq(SWAP_HOLD_INVOICE), anyOrNull()) + } + @Test fun `swap route hold failing after the claim wait ran out retries for the same contact`() = test { whenever(pubkySwapsRouteRepo.commit(SWAP_QUOTE_ID)).thenReturn(Result.success(swapRoutePayment())) @@ -19901,6 +19951,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { cancelAndIgnoreRemainingEvents() } verify(pubkySwapsRouteRepo, times(2)).commit(SWAP_QUOTE_ID) + // The failed hold's swap stops advancing; the retry's swap goes on. + verify(pubkySwapsRouteRepo, times(1)).dropFailedSwap(SWAP_ID) verify(activityRepo).setContact( contactPublicKey = eq(testPublicKey), forPaymentId = eq(SWAP_HOLD_HASH),