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/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/PubkySwapsRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt index 669beba904..9b759ba7a0 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 @@ -11,16 +12,31 @@ 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.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 import kotlinx.coroutines.withTimeoutOrNull 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 @@ -31,6 +47,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 @@ -48,6 +65,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" @@ -55,15 +73,30 @@ 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 + + /** 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) + /** 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() + + /** The loop advancing each swap in the background, one per swap. */ + private val advancing = ConcurrentHashMap() + val isEnabled: Boolean get() = Env.isPubkySwapsRouteEnabled /** The contact behind a provider's pubky, so the review shows who routes the payment. */ @@ -96,27 +129,93 @@ 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. It ends when the wallet is wiped. */ - suspend fun restoreSwaps(): Result = withSecrets { mnemonic, passphrase -> - 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) + fun restoredSwaps(): Flow = channelFlow { + 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 + } + } + } + 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() + } + + /** + * 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. + */ + 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()) + // 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() + 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. + run.restoredProviders += readInFull + if (incomplete.isNotEmpty()) Logger.warn("Swap lists incomplete from '$incomplete'", context = TAG) + track(restored + known) + RestoredPubkySwaps( + restored = restored.filter(run.reportedSwaps::add), + known = known.filter(run.reportedSwaps::add), + incompleteProviders = 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. */ @@ -138,36 +237,116 @@ 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) } + } } /** * 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 { - var lastFailure: Throwable? = null - withTimeoutOrNull(timeout) { - pollClaim(swapId, POLL_INTERVAL, untilConfirmed = false) { lastFailure = it } - }?.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)) + suspend fun awaitClaim( + swapId: String, + timeout: Duration = CLAIM_TIMEOUT, + holdFailure: Job? = null, + ): Result = scope.async { + 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) } + } + } + private fun advanceInBackground(swapId: String) { - scope.launch { withTimeoutOrNull(CONFIRMATION_TIMEOUT) { awaitConfirmation(swapId) } } + if (advancing.containsKey(swapId)) return + val loop = scope.launch(start = CoroutineStart.LAZY) { + try { + awaitConfirmation(swapId) + } finally { + 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) { 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( @@ -177,8 +356,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) @@ -208,12 +390,28 @@ 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. */ +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) + +private class RestoreRun { + val restoredProviders = mutableSetOf() + val reportedSwaps = mutableSetOf() + var payoutAddress: String? = null +} 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/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 0edcc7f9d4..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) { @@ -580,6 +584,13 @@ 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 + + /** 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 @@ -2980,6 +2991,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)) { @@ -5027,7 +5039,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 +5081,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. @@ -6762,6 +6781,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 @@ -7302,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 && @@ -7320,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 } @@ -7341,11 +7364,16 @@ class AppViewModel @Inject constructor( contactPaymentContext?.let { synchronized(contactPaymentContextLock) { pendingContactPaymentContexts[holdPaymentHash] = it } } + 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) failSwapRoutedPayment(it, contactPaymentContext, allowanceAttemptId, isSendCurrent()) @@ -7371,7 +7399,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, + sendSession = session, + ), holdFailure, isSendCurrent, ) @@ -7392,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 { @@ -7403,11 +7439,16 @@ 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) + 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) 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)) @@ -7415,6 +7456,13 @@ class AppViewModel @Inject constructor( } } + private fun restoreSwapContact(swap: SwapRoutedPayment) { + if (swap.sendSession != sendSession) 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, @@ -7423,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) @@ -7445,6 +7490,47 @@ class AppViewModel @Inject constructor( } } + private fun showCommittedSwap(): Boolean { + val swap = committedSwap?.takeIf { it.sendSession == sendSession } ?: return false + setSendEffect( + SendEffect.NavigateToPending( + paymentHash = swap.holdPaymentHash, + amount = swap.deliveredSat.toLong(), + retryRoute = SendRetryRoute.Amount, + ), + ) + 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 + } + + 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.sendSession != sendSession) return + synchronized(contactPaymentContextLock) { + if (activeContactPaymentContext == null) { + activeContactPaymentContext = pendingContactPaymentContexts[paymentHash] + } + } + } + private fun clearSwapRouteQuote(isSendCurrent: Boolean, keepHoldPaymentHash: Boolean = false) { if (!isSendCurrent) return _sendUiState.update { @@ -7464,7 +7550,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 { @@ -8516,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() @@ -10380,6 +10467,13 @@ private data class SwapRoutedPayment( val tagsSaved: Boolean, val contactPaymentContext: ContactPaymentContext?, val allowanceAttemptId: String?, + val sendSession: Long, +) + +private data class CommittedSwap( + val sendSession: Long, + val holdPaymentHash: String, + val deliveredSat: ULong, ) private class LightningPaymentFailedError( diff --git a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index 8e22e31fef..5e507ea248 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -573,34 +573,37 @@ 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) { - 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, - ) + // 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", + 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, + ) + } } } } @@ -826,6 +829,7 @@ class WalletViewModel @Inject constructor( walletRepo.refreshBip21() } ensureSwapUpdatesRunning() + if (pubkySwapsRouteRepo.isEnabled) pubkySwapsRouteRepo.resumeUnfinishedSwaps() // checkForOrphanedChannelMonitorRecovery() } } 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/PubkySwapsRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt index 3e4e2f5a4e..040a32a30f 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkySwapsRouteRepoTest.kt @@ -1,11 +1,23 @@ package to.bitkit.repositories +import com.synonym.bitkitcore.PubkySwapException +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 +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.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent import org.junit.Before @@ -14,14 +26,21 @@ 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.verify 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 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 @@ -36,16 +55,26 @@ 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 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 = mock(), - lightningRepo = mock(), + pubkyRepo = pubkyRepo, + lightningRepo = lightningRepo, + cacheStore = cacheStore, ) } @@ -105,6 +134,261 @@ 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() + cacheData.value = AppCacheData(unfinishedPubkySwaps = listOf(SWAP_ID)) + + val result = async { sut.awaitClaim(SWAP_ID, holdFailure = holdFailure) } + runCurrent() + holdFailure.complete(Unit) + 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)) + } + } + + @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()) + } + } + + @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 + @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")) + 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()) + } + + @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, + 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 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(), + ) = 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/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/ui/WalletViewModelTest.kt b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt index 3b853cfe9f..709f0b5d51 100644 --- a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt @@ -357,9 +357,9 @@ 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.awaitClaim(eq("swap"), any())).thenReturn(Result.success("txid")) + 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) whenever(backupRepo.performFullRestoreFromLatestBackup(any(), anyOrNull())).thenReturn( @@ -372,17 +372,17 @@ class WalletViewModelTest : BaseUnitTest() { advanceUntilIdle() assertEquals(RestoreState.Completed(emptySet()), sut.restoreState.value) - verify(pubkySwapsRouteRepo).restoreSwaps() - verify(pubkySwapsRouteRepo).awaitClaim(eq("swap"), any()) + verify(pubkySwapsRouteRepo).restoredSwaps() + verify(pubkySwapsRouteRepo).awaitClaim(eq("swap"), any(), anyOrNull()) verify(context).getString(R.string.wallet__swap_route_restored_title) } @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.awaitClaim(eq("swap"), any())).thenReturn(Result.success("txid")) + 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) 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) } @@ -412,7 +412,7 @@ class WalletViewModelTest : BaseUnitTest() { advanceUntilIdle() assertEquals(RestoreState.Completed(emptySet()), sut.restoreState.value) - verify(pubkySwapsRouteRepo, never()).restoreSwaps() + verify(pubkySwapsRouteRepo, never()).restoredSwaps() } @Test 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 c0ea574350..37adc82582 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), @@ -19402,6 +19404,72 @@ 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) + 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"))) @@ -19431,7 +19499,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(SendRetryRoute.Amount, assertIs(awaitItem()).retryRoute) expectNoEvents() } - verify(pubkySwapsRouteRepo, never()).awaitClaim(any(), any()) + verify(pubkySwapsRouteRepo, never()).awaitClaim(any(), any(), anyOrNull()) + verify(pubkySwapsRouteRepo).dropFailedSwap(SWAP_ID) } @Test @@ -19440,7 +19509,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 +19522,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 +19532,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 +19553,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 +19573,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 +19598,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 +19620,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 { @@ -19560,6 +19642,59 @@ 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) + 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)) + 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) @@ -19580,7 +19715,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 +19764,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 +19788,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 +19818,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() @@ -19710,34 +19847,118 @@ 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())).doSuspendableAnswer { claim.await() } + 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() - // 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 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())) + 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) + // 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), + syncLdkPayments = any(), + walletId = any(), + ) } @Test @@ -19788,7 +20009,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 +20050,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 +20059,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 +20091,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 +20100,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(