diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 28ed612fde..b8cba1e4b6 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -311,7 +311,7 @@ class SparkExitRepo @Inject constructor( _state.update { it.copy(tipHeight = tip ?: it.tipHeight) } tip?.let { height -> sparkExitTip.height.update { height } } refreshNetworkFees(chain) - refreshFundingSeen(chain, current) + val seen = refreshFundingSeen(chain, current) if (current.isActive) noteSavingsSend(current) val store = store // A reconnect for the exit that failed left Spark ready but disconnected: the tick connects it again. @@ -324,7 +324,11 @@ class SparkExitRepo @Inject constructor( rememberLostLeaves(updated) _state.update { it.copy(record = updated, lastError = null) } // A tick that changed the phase, such as a build short of fees, needs the funding state of the new phase. - if (updated.phase != current.phase) refreshFundingSeen(chain, updated) + // So does one that forgot the exit's own payment, which brings the ask back. + // A failed read then keeps the first: a short payment it saw still counts, so only the rest is asked for. + if (updated.phase != current.phase || updated.fundingPaymentTxid != current.fundingPaymentTxid) { + refreshFundingSeen(chain, updated, earlier = seen) + } // Spark's balance next to the exit's leaves shows value outside the exit. if (recovering != null) _state.update { it.copy(sparkBalanceSats = sparkRepo.state.value.balanceSats) } // A rebuild needs the SDK; every other running step can go out from the stored recovery without it. Steps @@ -418,14 +422,21 @@ class SparkExitRepo @Inject constructor( _state.update { it.copy(networkFees = fees ?: it.networkFees) } } - private suspend fun refreshFundingSeen(chain: SparkExitChain, record: SparkExitRecord) { - val address = record.funding.firstOrNull()?.address ?: return + /** Reads the funding address for [record], or goes by [earlier] when the read fails; returns the UTXOs used. */ + private suspend fun refreshFundingSeen( + chain: SparkExitChain, + record: SparkExitRecord, + earlier: List? = null, + ): List? { + val address = record.funding.firstOrNull()?.address ?: return null _state.update { it.copy(fundingAddress = address) } if (record.fundingShortfallSats == null) { _state.update { it.copy(fundingState = null) } - return + return null } - noteFundingSeen(record, runSuspendCatching { chain.utxos(address) }.getOrNull()) + val utxos = runSuspendCatching { chain.utxos(address) }.getOrNull() ?: earlier + noteFundingSeen(record, utxos) + return utxos } /** What [utxos] at the funding address, null when unread, says the exit still needs. */ @@ -649,7 +660,11 @@ class SparkExitRepo @Inject constructor( // On a chain Spark does not read, the exit would never see the payment. require(option.extraSats == 0uL || sharesNodeChain()) { "Spark does not read the node's chain" } val txid = if (option.extraSats > 0uL) { - sendFunding(address, option.extraSats, option.feeRates, option.totalSats.safe() - option.extraSats.safe()) + val approvedFeeSats = option.totalSats.safe() - option.extraSats.safe() + runSuspendCatching { sendFunding(address, option.extraSats, option.feeRates, approvedFeeSats) }.getOrElse { + // With no answer it may still go out: kept like a payment of unknown result. + pendingFundingTxid(it, address) ?: throw it + } } else { null } @@ -676,6 +691,8 @@ class SparkExitRepo @Inject constructor( it.copy(record = bumped, fundingState = SparkExitMath.fundingState(bumped, utxos = null)) } } + // Progress says at once whether the payment may still land. + _state.value.record?.takeIf { it.isActive }?.let { noteSavingsSend(it) } if (_state.value.record?.needsDriving == true) work.schedulePeriodic() Logger.info( "Raised the Spark exit fee to '${option.rateSatPerVbyte}' sat/vB, paying '${option.extraSats}' sats", @@ -871,8 +888,9 @@ class SparkExitRepo @Inject constructor( runSuspendCatching { payFunding(createdAt, key.address, savingsSats, pending.savingsFeeRates, pending.savingsFeeSats) } - // A refused payment shows on progress at once, with the offer to pay again. - .onFailure { _state.value.record?.let { current -> noteSavingsSend(current) } } + // A refused payment shows on progress at once, with the offer to pay again, and one that may + // still land with its note. + .also { _state.value.record?.let { current -> noteSavingsSend(current) } } .getOrThrow() } } @@ -947,18 +965,44 @@ class SparkExitRepo @Inject constructor( // Refused by a node, or with no answer, it went out: its own retry or the exit's wait takes over. if (it is OnchainSendPendingError || it is SparkExitError) noteSavingsRefusal(null) } - .getOrThrow() - val record = _state.value.record ?: return@withLock - val paid = record.copy(fundingPaymentTxid = txid, savingsRefusal = null) - // Kept as paid even when the save fails, so progress never offers to pay it again; a later tick saves it. - runCatching { saveRecord(paid) } - .onFailure { Logger.error("Failed to save the Spark exit funding payment '$txid'", it, context = TAG) } - _state.update { - it.copy(record = paid, fundingState = SparkExitMath.fundingState(paid, utxos = null)) - } + .getOrElse { + pendingFundingTxid(it, address)?.let { pending -> keepFundingPayment(pending) } + throw it + } + keepFundingPayment(txid) } } + /** + * Keeps [txid] as the exit's savings payment: progress shows it paid, with no ask, until it lands or the + * own-payment wait forgets it. Kept even when the save fails, so progress never offers to pay it again; a later + * tick saves it. + */ + private fun keepFundingPayment(txid: String) { + val record = _state.value.record ?: return + val paid = record.copy(fundingPaymentTxid = txid, savingsRefusal = null) + runCatching { saveRecord(paid) } + .onFailure { Logger.error("Failed to save the Spark exit funding payment '$txid'", it, context = TAG) } + _state.update { + it.copy(record = paid, fundingState = SparkExitMath.fundingState(paid, utxos = null)) + } + } + + /** + * The transaction of a savings payment to [address] with no answer yet: it may still go out, so it is kept like + * one of unknown result. From the error, or else from the send journal. A retry the journal rolled back to refused + * never went out, whatever txid its error names. + */ + private suspend fun pendingFundingTxid(error: Throwable, address: String): String? { + if (error !is OnchainSendPendingError) return null + val attempt = runSuspendCatching { lightningRepo.currentOnchainSendAttempt() }.getOrNull() + ?.takeIf { it.address == address } + if (attempt?.evidence == OnchainSendEvidence.Rejected) return null + val isPending = attempt?.evidence == OnchainSendEvidence.Pending || + attempt?.evidence == OnchainSendEvidence.Unknown + return error.txid ?: attempt?.takeIf { isPending }?.txid + } + private fun noteSavingsRefusal(sats: ULong, feeSats: ULong) = noteSavingsRefusal(SparkExitRecord.SavingsRefusal(sats, feeSats)) @@ -1032,7 +1076,7 @@ class SparkExitRepo @Inject constructor( } } // A payment that went out and failed shows as such, with its own retry. - .onFailure { _state.value.record?.let { current -> noteSavingsSend(current) } } + .also { _state.value.record?.let { current -> noteSavingsSend(current) } } .recover { if (isKept) Unit else throw it } .getOrThrow() } @@ -1119,18 +1163,14 @@ class SparkExitRepo @Inject constructor( walletId = refused.walletId, feeRateSatsPerVByte = refused.feeRateSatsPerVByte, ) { check(it.attemptId == refused.attemptId && it.address == refused.address) } - .getOrThrow() - val txid = fundingTxid(outcome, refused.amountSats) - val current = _state.value.record ?: return@withLock - val paid = current.copy(fundingPaymentTxid = txid, savingsRefusal = null) - saveRecord(paid) - _state.update { - it.copy( - record = paid, - fundingState = SparkExitMath.fundingState(paid, utxos = null), - isSavingsPaymentRefused = false, - ) - } + .getOrElse { + pendingFundingTxid(it, refused.address)?.let { pending -> keepFundingPayment(pending) } + _state.value.record?.let { current -> noteSavingsSend(current) } + throw it + } + keepFundingPayment(fundingTxid(outcome, refused.amountSats)) + _state.value.record?.let { current -> noteSavingsSend(current) } + Unit } } } finally { diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index 490228ca7f..b728a74bd3 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -220,6 +220,14 @@ private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState, modifier = Modifier.testTag("SparkExitSavingsRefused") ) } + if (uiState.isSavingsSendLanding) { + VerticalSpacer(24.dp) + BodyS( + text = stringResource(R.string.lightning__spark_exit__savings_unresolved), + color = Colors.White64, + modifier = Modifier.testTag("SparkExitSavingsUnresolved") + ) + } if (funding is SparkExitFundingState.Ask && address != null) { VerticalSpacer(24.dp) SparkExitFeesRow( diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index afe85f86be..5e437077cb 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -507,6 +507,14 @@ data class SparkExitUiState( /** Progress says the savings payment didn't go through and offers to pay it again. */ val offersSavingsRetry: Boolean get() = isSavingsPaymentRefused || savingsRetryOffer != null + /** + * The exit waits for its own savings payment, which the send journal has not seen accepted yet: it may still land, + * so progress says to wait for it before paying from another wallet. + */ + val isSavingsSendLanding: Boolean + get() = record?.isAwaitingOwnPayment == true && isSavingsSendUnresolved && !isSavingsPaymentRefused && + progressFunding == SparkExitFundingState.Paid + /** Progress offers Pay a higher fee. */ val canPayHigherFee: Boolean get() = record?.canPayHigherFee(tipHeight, networkFees) == true @@ -560,8 +568,11 @@ data class SparkExitUiState( */ val progressFunding: SparkExitFundingState? get() { - val shortfall = record?.fundingShortfallSats ?: return null - return fundingState ?: SparkExitFundingState.Ask(maxOf(shortfall, SparkExitMath.FUNDING_DUST_SATS)) + val current = record ?: return null + val shortfall = current.fundingShortfallSats ?: return null + // Before the first read, a payment the record keeps still holds the ask. + return fundingState ?: SparkExitFundingState.Paid.takeIf { current.isAwaitingOwnPayment } + ?: SparkExitFundingState.Ask(maxOf(shortfall, SparkExitMath.FUNDING_DUST_SATS)) } } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 77614b84c1..8d48895103 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -334,6 +334,7 @@ تعذّر على Bitkit قراءة التقدم المحفوظ لهذا التحويل، لذا يعيد بناءه من السلسلة. ستستلم (تقديريًا) لم يكتمل دفعك من المدخرات. ادفع مرة أخرى، أو موّل من محفظة أخرى. + لم يتأكد دفعك من المدخرات بعد. انتظره قبل أن تدفع من محفظة أخرى. إرسال إلى العنوان تأكيد رسوم الطوارئ نشر معاملة الخروج diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 06b95bfe98..719d0cd30c 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -341,6 +341,7 @@ Bitkit no pudo leer el progreso guardado de esta transferencia, así que lo reconstruye a partir de la cadena. Recibes (estimado) Tu pago desde ahorros no se completó. Paga de nuevo o financia desde otra billetera. + Tu pago desde ahorros aún no se confirmó. Espéralo antes de pagar desde otra billetera. Enviar a dirección Confirmación de las comisiones de emergencia Publicación de la transacción de salida diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index d6d4a9f2cb..cd214cf2c2 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -338,6 +338,7 @@ Bitkit no ha pogut llegir el progrés desat d\'aquesta transferència, així que el reconstrueix a partir de la cadena. Rebràs (estimació) El teu pagament dels estalvis no s\'ha completat. Torna a pagar o finança des d\'un altre moneder. + El teu pagament dels estalvis encara no s\'ha confirmat. Espera\'l abans de pagar des d\'un altre moneder. Enviar a l\'adreça Confirmació de les comissions d\'emergència Publicació de la transacció de sortida diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 82f4fd4833..46cba33f2f 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -341,6 +341,7 @@ Bitkit nemohl přečíst uložený průběh tohoto převodu, proto ho znovu sestaví z blockchainu. Obdržíte (odhad) Vaše platba z úspor neprošla. Zaplaťte znovu, nebo financujte z jiné peněženky. + Vaše platba z úspor ještě není potvrzena. Počkejte na ni, než zaplatíte z jiné peněženky. Odeslat na adresu Potvrzení nouzových poplatků Zveřejnění transakce odchodu diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index b596372ffc..6c0c92a6eb 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -223,6 +223,7 @@ Bitkit konnte den gespeicherten Fortschritt dieser Übertragung nicht lesen und stellt ihn daher aus der Chain wieder her. Du erhältst (Schätzung) Deine Zahlung vom Sparkonto ist nicht durchgegangen. Zahle erneut oder finanziere aus einer anderen Wallet. + Deine Zahlung vom Sparkonto ist noch nicht bestätigt. Warte darauf, bevor du aus einer anderen Wallet zahlst. An Adresse senden Bestätigung der Notfallgebühren Veröffentlichung der Ausstiegstransaktion diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 42a34f22fe..954f084df2 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -334,6 +334,7 @@ Το Bitkit δεν μπόρεσε να διαβάσει την αποθηκευμένη πρόοδο αυτής της μεταφοράς, γι\' αυτό την ανακατασκευάζει από την αλυσίδα. Λαμβάνετε (εκτίμηση) Η πληρωμή σας από αποταμιεύσεις δεν ολοκληρώθηκε. Πληρώστε ξανά ή χρηματοδοτήστε από άλλο πορτοφόλι. + Η πληρωμή σας από αποταμιεύσεις δεν έχει επιβεβαιωθεί ακόμη. Περιμένετέ την πριν πληρώσετε από άλλο πορτοφόλι. Αποστολή σε διεύθυνση Επιβεβαίωση έκτακτων τελών Δημοσίευση συναλλαγής εξόδου diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 6dc0e1e3d2..6b25de874f 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -340,6 +340,7 @@ Bitkit no pudo leer el progreso guardado de esta transferencia, así que lo reconstruye a partir de la cadena. Recibes (estimado) Tu pago desde ahorros no se ha completado. Paga de nuevo o financia desde otro monedero. + Tu pago desde ahorros aún no se ha confirmado. Espéralo antes de pagar desde otro monedero. Enviar a la dirección Confirmación de las comisiones de emergencia Publicación de la transacción de salida diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 263394119f..586c8de23a 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -282,6 +282,7 @@ Bitkit no pudo leer el progreso guardado de esta transferencia, así que lo reconstruye a partir de la cadena. Recibes (estimado) Tu pago desde ahorros no se completó. Paga de nuevo o financia desde otro monedero. + Tu pago desde ahorros aún no se confirmó. Espéralo antes de pagar desde otro monedero. Enviar a la dirección Confirmación de las comisiones de emergencia Publicación de la transacción de salida diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index f5a04008e8..10986173b2 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -222,6 +222,7 @@ Bitkit n\'a pas pu lire la progression enregistrée de ce transfert, il la reconstruit donc à partir de la chaîne. Vous recevez (estimation) Votre paiement depuis l\'épargne n\'a pas abouti. Payez à nouveau ou financez depuis un autre portefeuille. + Votre paiement depuis l\'épargne n\'est pas encore confirmé. Attendez-le avant de payer depuis un autre portefeuille. Envoyer à l\'adresse Confirmation des frais d\'urgence Publication de la transaction de sortie diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 93b5988584..04c3a8e3df 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -339,6 +339,7 @@ Bitkit non è riuscito a leggere l\'avanzamento salvato di questo trasferimento, quindi lo ricostruisce dalla blockchain. Riceverai (stima) Il tuo pagamento dai risparmi non è andato a buon fine. Paga di nuovo o finanzia da un altro portafoglio. + Il tuo pagamento dai risparmi non è ancora confermato. Attendilo prima di pagare da un altro portafoglio. Invia all\'indirizzo Conferma delle commissioni di emergenza Pubblicazione della transazione di uscita diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index da06deedb7..0ddaae8d43 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -338,6 +338,7 @@ Bitkit kon de opgeslagen voortgang van deze overboeking niet lezen en bouwt die daarom opnieuw op vanaf de chain. Je ontvangt (schatting) Je betaling uit spaargeld is niet gelukt. Betaal opnieuw of financier vanuit een andere wallet. + Je betaling uit spaargeld is nog niet bevestigd. Wacht erop voordat je vanuit een andere wallet betaalt. Naar adres sturen Bevestiging van noodkosten Exittransactie publiceren diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 2eca3d9717..70adfdfcfc 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -224,6 +224,7 @@ Bitkit nie mógł odczytać zapisanego postępu tego transferu, więc odbudowuje go z łańcucha. Otrzymasz (szacunkowo) Twoja płatność z Oszczędności nie przeszła. Zapłać ponownie lub sfinansuj z innego portfela. + Twoja płatność z Oszczędności nie jest jeszcze potwierdzona. Poczekaj na nią, zanim zapłacisz z innego portfela. Wyślij na adres Potwierdzenie opłat awaryjnych Publikowanie transakcji wyjścia diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index ecf958ac73..504a6bcc94 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -342,6 +342,7 @@ A Bitkit não conseguiu ler o progresso salvo desta transferência, então o reconstrói a partir da blockchain. Você recebe (estimativa) Seu pagamento da poupança não foi concluído. Pague novamente ou financie de outra carteira. + Seu pagamento da poupança ainda não foi confirmado. Aguarde antes de pagar de outra carteira. Enviar para o endereço Confirmação das taxas de emergência Publicação da transação de saída diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index fe167db418..fa27892541 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -219,6 +219,7 @@ A Bitkit não conseguiu ler o progresso guardado desta transferência, por isso reconstrói-o a partir da blockchain. Recebe (estimativa) O seu pagamento da poupança não foi concluído. Pague novamente ou financie a partir de outra carteira. + O seu pagamento da poupança ainda não foi confirmado. Aguarde antes de pagar a partir de outra carteira. Enviar para o endereço Confirmação das taxas de emergência Publicação da transação de saída diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 08e92af37c..3fc7e03eff 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -350,6 +350,7 @@ Bitkit не смог прочитать сохранённый прогресс этого перевода, поэтому восстанавливает его по блокчейну. Вы получите (оценка) Платёж из сбережений не прошёл. Оплатите снова или пополните с другого кошелька. + Платёж из сбережений ещё не подтверждён. Дождитесь его, прежде чем платить с другого кошелька. Отправить на адрес Подтверждение экстренных комиссий Публикация транзакции выхода diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 47968335dd..fec690af0a 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -502,6 +502,7 @@ Bitkit couldn\'t read this transfer\'s saved progress, so it rebuilds it from the chain. You receive (estimate) Your savings payment didn\'t go through. Pay again, or fund from another wallet. + Your savings payment hasn\'t confirmed yet. Wait for it before you pay from another wallet. Send to address Confirmation of emergency fees Publishing of exit transaction diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index f15d0a2772..62abd8b7d2 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -1686,8 +1686,12 @@ class SparkExitRepoTest : BaseUnitTest() { // A payment with no answer may have gone out: it is never offered again. outcome = Result.failure(OnchainSendPendingError(IOException("no answer"), "pending")) assertTrue(sut.paySavingsRefusal(retry).isFailure) - assertNull(assertNotNull(store.load()).savingsRefusal) + // Stops the foreground loop before the checks, or runTest drives it forever when one fails. sut.onAppBackgrounded() + assertNull(assertNotNull(store.load()).savingsRefusal) + // Kept as the exit's payment, so progress holds the ask until it lands or the own-payment wait forgets it. + assertEquals("pending", store.load()?.fundingPaymentTxid) + assertEquals(SparkExitFundingState.Paid, sut.state.value.fundingState) verify(lightning, times(2)).sendOnChain( any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), @@ -1751,7 +1755,11 @@ class SparkExitRepoTest : BaseUnitTest() { @OptIn(ExperimentalCoroutinesApi::class) @Test fun `a savings payment with an unknown result counts as paid and keeps the exit`() = test { - stubFunding { Result.success(OnchainSendOutcome.Unknown("maybe")) } + stubFunding { + whenever(lightning.currentOnchainSendAttempt()) + .thenReturn(refusedSavingsPayment().copy(evidence = OnchainSendEvidence.Unknown, txid = "maybe")) + Result.success(OnchainSendOutcome.Unknown("maybe")) + } val sut = quotedSut(FakeSparkExitRecovering()) sut.loadQuote().getOrThrow() @@ -1761,6 +1769,7 @@ class SparkExitRepoTest : BaseUnitTest() { val record = assertNotNull(sut.state.value.record) assertEquals("maybe", record.fundingPaymentTxid) assertTrue(record.isAwaitingOwnPayment) + assertTrue(sut.state.value.isSavingsSendUnresolved, "progress says at once that it may still land") assertFalse(sut.canCancel) assertTrue(sut.cancel().isFailure) val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) @@ -1915,13 +1924,19 @@ class SparkExitRepoTest : BaseUnitTest() { whenever(lightning.currentOnchainSendAttempt()).thenReturn(refused) whenever( lightning.retryOriginalOnchainSend(any(), any(), any(), anyOrNull(), any(), any()) - ).thenReturn(Result.success(OnchainSendOutcome.Accepted("again"))) + ).doSuspendableAnswer { + whenever(lightning.currentOnchainSendAttempt()) + .thenReturn(refused.copy(evidence = OnchainSendEvidence.Accepted, txid = "again")) + Result.success(OnchainSendOutcome.Accepted("again")) + } whenever(lightning.completeAcceptedOrdinaryFollowup(any())).thenReturn(Unit) val sut = quotedSut(FakeSparkExitRecovering()) sut.load().getOrThrow() sut.tick().getOrThrow() + assertTrue(sut.state.value.isSavingsSendUnresolved) sut.retrySavingsPayment().getOrThrow() + sut.onAppBackgrounded() // The same attempt at the rate the user approved: it spends the refused payment's inputs, so at most one of // the two can ever confirm. No new payment picks other coins. @@ -1936,7 +1951,92 @@ class SparkExitRepoTest : BaseUnitTest() { ) assertEquals("again", assertNotNull(store.load()).fundingPaymentTxid) assertFalse(sut.state.value.isSavingsPaymentRefused) + assertFalse(sut.state.value.isSavingsSendUnresolved, "an accepted payment says nothing about landing") + } + + @Test + fun `paying again from savings with no answer keeps the payment as the exit's own`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(awaitingRecord()) + val refused = refusedSavingsPayment() + whenever(lightning.currentOnchainSendAttempt()).thenReturn(refused) + whenever( + lightning.retryOriginalOnchainSend(any(), any(), any(), anyOrNull(), any(), any()) + ).doSuspendableAnswer { + // The error carries no txid: the send journal holds it, unresolved, for the funding address. + whenever(lightning.currentOnchainSendAttempt()) + .thenReturn(refused.copy(evidence = OnchainSendEvidence.Unknown, txid = "maybe")) + Result.failure(OnchainSendPendingError(IOException("no answer"))) + } + val sut = quotedSut(FakeSparkExitRecovering()) + sut.load().getOrThrow() + sut.tick().getOrThrow() + + assertTrue(sut.retrySavingsPayment().isFailure) + sut.onAppBackgrounded() + + assertEquals("maybe", assertNotNull(store.load()).fundingPaymentTxid) + assertEquals(SparkExitFundingState.Paid, sut.state.value.fundingState) + assertFalse(sut.state.value.isSavingsPaymentRefused, "it may still land, so it is not offered again") + assertTrue(sut.state.value.isSavingsSendUnresolved) + assertFalse(sut.canCancel, "savings may have paid this exit") + } + + @Test + fun `paying again from savings keeps no payment the send journal rolled back to refused`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(awaitingRecord()) + whenever(lightning.currentOnchainSendAttempt()).thenReturn(refusedSavingsPayment()) + // It failed before it went out: the journal stays refused, though the error names the unsent candidate. + whenever( + lightning.retryOriginalOnchainSend(any(), any(), any(), anyOrNull(), any(), any()) + ).thenReturn(Result.failure(OnchainSendPendingError(IOException("not sent"), "candidate"))) + val sut = quotedSut(FakeSparkExitRecovering()) + sut.load().getOrThrow() + sut.tick().getOrThrow() + + assertTrue(sut.retrySavingsPayment().isFailure) sut.onAppBackgrounded() + + assertNull(assertNotNull(store.load()).fundingPaymentTxid) + assertTrue(sut.state.value.isSavingsPaymentRefused, "the retry is offered again") + } + + @Test + fun `a tick that forgets the exit's own payment brings the ask back at once`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + // Seen at height 800, and the tip is 1000: the own-payment wait is over. + store.save(awaitingRecord(paidTxid = "lost").copy(fundingPaymentSeenAtHeight = 800u)) + val sut = quotedSut(FakeSparkExitRecovering(), fundingChain()) + sut.load().getOrThrow() + + sut.tick().getOrThrow() + sut.onAppBackgrounded() + + assertNull(assertNotNull(store.load()).fundingPaymentTxid) + assertIs(sut.state.value.fundingState) + } + + @Test + fun `a short savings payment keeps its remainder asked when the refresh after it fails`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + val paid = "e1".repeat(32) + store.save(awaitingRecord(paidTxid = paid).copy(fundingPaymentSeenAtHeight = 990u)) + val short = """[{"txid":"$paid","vout":0,"value":8000,"status":{"confirmed":true}}]""" + lateinit var sut: SparkExitRepo + // The tick's reads see the short payment confirmed; the refresh after the exit forgets it fails. + sut = quotedSut( + FakeSparkExitRecovering(), + fundingChain { short.takeIf { sut.state.value.record?.fundingPaymentTxid != null } }, + ) + sut.load().getOrThrow() + + sut.tick().getOrThrow() + sut.onAppBackgrounded() + + assertNull(assertNotNull(store.load()).fundingPaymentTxid) + val ask = assertIs(sut.state.value.fundingState) + assertEquals(8000uL, ask.receivedSats, "the payment the first read found still counts") } @OptIn(ExperimentalCoroutinesApi::class) @@ -2062,6 +2162,30 @@ class SparkExitRepoTest : BaseUnitTest() { assertTrue(ended.payHigherFee(option).isFailure) } + @Test + fun `a higher fee paid from savings with no answer is kept as the exit's payment`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(runningRecord()) + stubFunding { + // The error carries no txid: the send journal holds it, unresolved, for the funding address. + whenever(lightning.currentOnchainSendAttempt()) + .thenReturn(refusedSavingsPayment().copy(evidence = OnchainSendEvidence.Unknown, txid = "bump")) + Result.failure(OnchainSendPendingError(IOException("no answer"))) + } + val sut = quotedSut(FakeSparkExitRecovering()) + sut.load().getOrThrow() + + sut.payHigherFee(SparkExitFeeBumpOption(FeeRate.FAST, 9uL, 6_000uL, 6_400uL)).getOrThrow() + // Progress says at once that it may still land, before any tick. + assertTrue(sut.state.value.isSavingsSendUnresolved) + sut.onAppBackgrounded() + + // It may still go out, so the exit keeps it and its higher fee, and watches for it. + val record = assertNotNull(store.load()) + assertEquals("bump", record.fundingPaymentTxid) + assertEquals(9uL, record.feeRateSatPerVbyte) + } + @Test fun `a higher fee is never paid from savings on a chain spark does not read`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index e4420f60c5..b124d9998c 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -425,6 +425,30 @@ class SparkExitViewModelTest : BaseUnitTest() { ) } + @Test + fun `progress says a savings payment may still land only while the exit waits for it`() { + val paid = SparkExitFixtures.record().copy(fundingPaymentTxid = "pending") + val landing = SparkExitUiState( + record = paid, + fundingState = SparkExitFundingState.Paid, + isSavingsSendUnresolved = true, + ) + + assertTrue(landing.isSavingsSendLanding) + assertEquals(SparkExitFundingState.Paid, landing.progressFunding) + assertFalse(landing.copy(isSavingsSendUnresolved = false).isSavingsSendLanding, "accepted") + assertFalse(landing.copy(isSavingsPaymentRefused = true).isSavingsSendLanding, "refused: its own retry shows") + val seen = landing.copy(fundingState = SparkExitFundingState.Seen) + assertFalse(seen.isSavingsSendLanding, "it reached the address") + // Before the first read of the address, the kept payment still holds the ask. + assertEquals(SparkExitFundingState.Paid, landing.copy(fundingState = null).progressFunding) + // Once the own-payment wait forgets it, the ask comes back, even with the journal still unresolved. + val ask = SparkExitFundingState.Ask(20_000uL) + val forgotten = landing.copy(record = paid.copy(fundingPaymentTxid = null), fundingState = ask) + assertFalse(forgotten.isSavingsSendLanding) + assertEquals(ask, forgotten.progressFunding) + } + /** The qa-03 rerun, case 5: one 32,768-sat leaf lost to an older owner, 1,696 sats Spark could not exit. */ @Test fun `a stopped exit names what spark's live balance holds beyond its leaves`() = test { diff --git a/changelog.d/next/2059.fixed.md b/changelog.d/next/2059.fixed.md new file mode 100644 index 0000000000..a2ea8418dd --- /dev/null +++ b/changelog.d/next/2059.fixed.md @@ -0,0 +1 @@ +Fixed force transfer progress asking for the emergency fees while a payment of them from savings could still confirm.