From cf9b183fd1ce79407b4ba7e088aeec1d49decab6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 12:58:36 +0100 Subject: [PATCH 1/8] fix: refuse a spark retry at another amount A retry of an amountless invoice reuses its earlier attempt's Spark key, so at another amount Spark returned the first payment while the send showed the new amount. Each attempt now keeps its amount, and a retry under the same key at another amount is refused before anything goes out. Verified: SparkRepoTest, CacheStoreTest, the unit suite and lint pass. --- .../main/java/to/bitkit/data/CacheStore.kt | 15 ++-- .../java/to/bitkit/repositories/SparkRepo.kt | 14 ++++ .../java/to/bitkit/data/CacheStoreTest.kt | 8 +- .../to/bitkit/repositories/SparkRepoTest.kt | 83 +++++++++++++++++++ 4 files changed, 110 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index f6f64bf3d9..86f884f01a 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -202,14 +202,14 @@ class CacheStore internal constructor( } /** - * Keeps [attempt] as the latest attempt at paying the invoice with [paymentHash], which expires at [expiresAt], - * and drops the attempts of invoices expired before [now], both in epoch seconds. + * Keeps [attempt], sending [amountSats], as the latest attempt at paying the invoice with [paymentHash], which + * expires at [expiresAt], and drops the attempts of invoices expired before [now], both in epoch seconds. */ - suspend fun setSparkSendAttempt(paymentHash: String, attempt: Int, expiresAt: Long, now: Long) { + suspend fun setSparkSendAttempt(paymentHash: String, attempt: Int, amountSats: ULong, expiresAt: Long, now: Long) { val hash = paymentHash.lowercase() store.updateData { val live = it.sparkSendAttempts.filterValues { kept -> kept.expiresAt >= now } - it.copy(sparkSendAttempts = live + (hash to SparkSendAttempt(attempt, expiresAt))) + it.copy(sparkSendAttempts = live + (hash to SparkSendAttempt(attempt, expiresAt, amountSats))) } } @@ -508,9 +508,12 @@ data class AppCacheData( fun invalidateReceiveOnchainAddress() = copy(bip21 = "", onchainAddress = "") } -/** An attempt at paying an invoice through Spark, the [attempt]th, of an invoice that expires at [expiresAt]. */ +/** + * An attempt at paying an invoice through Spark, the [attempt]th, of an invoice that expires at [expiresAt], sending + * [amountSats] (null for one kept before amounts were). + */ @Serializable -data class SparkSendAttempt(val attempt: Int, val expiresAt: Long) +data class SparkSendAttempt(val attempt: Int, val expiresAt: Long, val amountSats: ULong? = null) @Serializable data class CachedUsdtBalance( diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index c1d97099d0..f80207073b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1,6 +1,7 @@ package to.bitkit.repositories import breez_sdk_spark.AutoOptimizationEvent +import breez_sdk_spark.Bolt11InvoiceDetails import breez_sdk_spark.ClaimDeferredReason import breez_sdk_spark.ClaimDepositOutcome import breez_sdk_spark.FeePolicy @@ -51,6 +52,7 @@ import to.bitkit.async.appScope import to.bitkit.data.CacheStore import to.bitkit.data.SettingsStore import to.bitkit.data.SparkPayoutChain +import to.bitkit.data.SparkSendAttempt import to.bitkit.di.BgDispatcher import to.bitkit.env.Defaults import to.bitkit.env.Env @@ -655,6 +657,9 @@ class SparkRepo @Inject constructor( // A held send whose attempt Spark lists failed is settled by the next listing, and a send after that // goes through the restore checks above, as a new key's send must. if (isKeyedRetry && !isReusedKey) throw PaymentPendingException(paymentHash) + // Spark returns the earlier attempt's payment for its key, so a retry at another amount is refused. + val sendSats = sendAmountSats(amountSats, invoice) + if (isReusedKey) ensureKeptAmount(previousAttempt, sendSats) // A send refused before anything went out is taken as not having used its key, so a retry refuses the // same way. The hold of an earlier attempt under the same key stays, as it may have committed a @@ -672,6 +677,7 @@ class SparkRepo @Inject constructor( cacheStore.setSparkSendAttempt( paymentHash, attempt, + sendSats, expiresAt.toEpochSeconds(), clock.now().epochSeconds, ) @@ -1022,6 +1028,14 @@ class SparkRepo @Inject constructor( return info.lastSyncError == null && syncedAt != null && (seconds == null || syncedAt > seconds) } + private fun sendAmountSats(amountSats: ULong?, invoice: Bolt11InvoiceDetails): ULong = + amountSats ?: invoice.amountMsat?.div(MSATS_PER_SAT) ?: 0uL + + private fun ensureKeptAmount(previous: SparkSendAttempt?, sendSats: ULong) { + val keptSats = previous?.amountSats ?: return + if (keptSats != sendSats) throw SparkError.SendRefused("An earlier attempt at '$keptSats' sats may still pay") + } + private fun ensurePaymentDeadline(paymentDeadlineAt: Instant?) { if (paymentDeadlineAt != null && clock.now() > paymentDeadlineAt) throw ServiceError.PaymentDeadlineExpired() } diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index 619d6b0df5..7ffdb39037 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -34,11 +34,11 @@ class CacheStoreTest : BaseUnitTest() { @Test fun `a spark send attempt drops expired ones and restores the earlier one`() = test { - sut.setSparkSendAttempt("OLD", attempt = 2, expiresAt = 1_500, now = 1_000) - sut.setSparkSendAttempt("hash", attempt = 0, expiresAt = 3_000, now = 1_000) - sut.setSparkSendAttempt("hash", attempt = 1, expiresAt = 3_000, now = 2_000) + sut.setSparkSendAttempt("OLD", attempt = 2, amountSats = 100uL, expiresAt = 1_500, now = 1_000) + sut.setSparkSendAttempt("hash", attempt = 0, amountSats = 100uL, expiresAt = 3_000, now = 1_000) + sut.setSparkSendAttempt("hash", attempt = 1, amountSats = 100uL, expiresAt = 3_000, now = 2_000) - assertEquals(mapOf("hash" to SparkSendAttempt(1, 3_000)), sut.data.first().sparkSendAttempts) + assertEquals(mapOf("hash" to SparkSendAttempt(1, 3_000, 100uL)), sut.data.first().sparkSendAttempts) sut.restoreSparkSendAttempt("HASH", SparkSendAttempt(0, 3_000)) assertEquals(0, sut.data.first().sparkSendAttempts["hash"]?.attempt) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 2b657e8352..73aa8420ce 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5425,6 +5425,67 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(1, store.data.first().sparkSendAttempts["hash"]?.attempt) } + @Test + fun `a spark retry under the same key at another amount is refused`() = test { + val attempt = SparkSendAttempt(0, now.epochSeconds + 3_600, 50uL) + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkSendAttempts = mapOf("hash" to attempt))), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.listPayments()).thenReturn(emptyList()) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + verify(sparkService, never()).send(any(), anyOrNull()) + assertEquals(50uL, store.data.first().sparkSendAttempts["hash"]?.amountSats) + } + + @Test + fun `a spark retry under the same key is refused when the invoice's amount differs from the kept one`() = test { + val attempt = SparkSendAttempt(0, now.epochSeconds + 3_600, 50uL) + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkSendAttempts = mapOf("hash" to attempt))), clock) + whenever(sparkService.isConnected).thenReturn(true) + val details = mock { + on { paymentHash } doReturn "hash" + on { timestamp }.thenAnswer { now.epochSeconds } + on { expiry }.thenAnswer { 3_600L } + on { amountMsat } doReturn 100_000uL + } + val prepared = prepared(feeSats = 0uL).copy(paymentMethod = SendPaymentMethod.Bolt11Invoice(details, null, 0uL)) + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.listPayments()).thenReturn(emptyList()) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", null).exceptionOrNull()) + + verify(sparkService, never()).send(any(), anyOrNull()) + } + + @Test + fun `a spark retry at another amount goes out under the next key once spark lists its attempt failed`() = test { + val attempt = SparkSendAttempt(0, now.epochSeconds + 3_600, 50uL) + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkSendAttempts = mapOf("hash" to attempt))), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(sentPayment(fees = 0)) + val failed = sentPayment(fees = 0).copy(id = "hash-0", status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + sut.payInvoice("lnbc1", 100uL).getOrThrow() + + assertEquals("hash-1", sentKey()) + assertEquals(100uL, store.data.first().sparkSendAttempts["hash"]?.amountSats) + } + @Test fun `a spark retry takes the next attempt's key once spark lists its attempt failed`() = test { val kept = AppCacheData(sparkSendAttempts = mapOf("hash" to SparkSendAttempt(0, now.epochSeconds + 3_600))) @@ -5712,6 +5773,28 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(1, events.count { it is Event.PaymentSuccessful }) } + @Test + fun `a spark retry of a held send at another amount is refused and keeps the send held`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) } + whenever(sparkService.listPayments()).thenReturn(emptyList()) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { throw leafSelectionFailure() } + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + sut.start(0).getOrThrow() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + clearInvocations(sparkService) + + assertIs(sut.payInvoice("lnbc1", 200uL).exceptionOrNull()) + + verify(sparkService, never()).send(any(), anyOrNull()) + assertTrue("hash" in store.data.first().sparkUncertainSends) + assertEquals(100uL, store.data.first().sparkSendAttempts["hash"]?.amountSats) + } + @Test fun `a spark retry of a held send stopped by its deadline keeps the send held`() = test { whenever(sparkService.isSupported).thenReturn(true) From d547acaa8f4ca43bfb117c7482b4aa663893990e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 13:47:25 +0100 Subject: [PATCH 2/8] chore: add changelog fragment Verified: none (changelog fragment only) --- changelog.d/next/2071.fixed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/next/2071.fixed.md diff --git a/changelog.d/next/2071.fixed.md b/changelog.d/next/2071.fixed.md new file mode 100644 index 0000000000..e22ebb39ce --- /dev/null +++ b/changelog.d/next/2071.fixed.md @@ -0,0 +1 @@ +A retry of an invoice at another amount than its earlier Spark payment is refused instead of showing the new amount as paid. From ce6236544f79460890d293e36f923d20bae87f76 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 14:12:17 +0100 Subject: [PATCH 3/8] fix: show a pending payment's own amount on a repeat Paying an amountless invoice again at another amount while its first payment was pending opened Payment Pending at the new amount, and its success receipt kept it. Pending now shows the amount stored for the payment it waits on. Fixes #2072 Verified: AppViewModelSendFlowTest, the unit suite and lint pass. --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 4 +++- .../viewmodels/AppViewModelSendFlowTest.kt | 23 +++++++++++++++++++ changelog.d/next/2071.fixed.md | 2 +- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index e06d777c1d..e068e4196a 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -8289,7 +8289,9 @@ class AppViewModel @Inject constructor( pendingPaymentRepo.track(pendingHash) preserveContactPaymentContext(pendingHash) if (incomingPaymentRequest != null) refreshIncomingPaykitPaymentRequests() - setSendEffect(SendEffect.NavigateToPending(pendingHash, displayAmountSats.toLong())) + // A repeat of a pending payment shows what that payment sends, also when its amount was typed. + val pendingSats = earlierLightningSendSats(pendingHash) ?: displayAmountSats + setSendEffect(SendEffect.NavigateToPending(pendingHash, pendingSats.toLong())) lnurlComment?.let { activityRepo.setLightningMessageIfEmpty(paymentHash, it) } resolveSettledPendingSend(pendingHash) return@onFailure diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 80d409ce9c..723250894a 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12141,6 +12141,29 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(1_000L, sut.successSendUiState.value.sats) } + @Test + fun `repaying an amountless invoice still pending with another amount shows the pending amount`() = test { + val bolt11 = "lnbcrt1amountlesspending" + val invoice = lightningInvoice(bolt11, 0u) + val paymentHash = invoice.paymentHash.toHex() + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = 2_000u)) + .thenReturn(Result.failure(PaymentPendingException(paymentHash))) + val earlier = mock { + on { value } doReturn 1_000u + on { txType } doReturn PaymentType.SENT + } + whenever(activityRepo.getActivity(paymentHash)).thenReturn(Result.success(BitkitActivity.Lightning(earlier))) + val state = SendUiState(address = bolt11, payMethod = SendMethod.LIGHTNING, decodedInvoice = invoice) + + sut.sendEffect.test { + setSendState(state.copy(amount = 2_000u)) + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + val pending = assertIs(expectMostRecentItem()) + assertEquals(1_000L, pending.amount) + } + } + @Test fun `a payment shown by its event during the swipe shows its success once`() = test { val bolt11 = "lnbcrt1eventfirst" diff --git a/changelog.d/next/2071.fixed.md b/changelog.d/next/2071.fixed.md index e22ebb39ce..e8638d5a4f 100644 --- a/changelog.d/next/2071.fixed.md +++ b/changelog.d/next/2071.fixed.md @@ -1 +1 @@ -A retry of an invoice at another amount than its earlier Spark payment is refused instead of showing the new amount as paid. +A repeat of an invoice at another amount than its earlier Spark payment is refused, and a repeat of a pending payment shows the amount that payment sends. From a423e00011f74dfc9c47e3db9c21ec2a742afaf5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 14:21:26 +0100 Subject: [PATCH 4/8] fix: keep another request's proof when a spark retry is refused A refused Spark retry cleared every Paykit Lightning proof of its invoice, so refusing a second request's retry at another amount dropped the first request's pending proof. A refusal now clears only its own request's proof. Verified: PaykitPaymentProofRepoTest, PaykitAllowanceExecutorTest and AppViewModelSendFlowTest pass. --- .../repositories/PaykitAllowanceExecutor.kt | 6 +++--- .../repositories/PaykitPaymentProofRepo.kt | 17 +++++++++++++++-- .../java/to/bitkit/viewmodels/AppViewModel.kt | 8 ++++---- .../repositories/PaykitAllowanceExecutorTest.kt | 8 ++++---- .../repositories/PaykitPaymentProofRepoTest.kt | 14 ++++++++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 10 +++++----- 6 files changed, 45 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt index 642eb194b4..41ab2298e8 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt @@ -119,8 +119,8 @@ class PaykitAllowancePayer @Inject constructor( ): Result = lightningRepo.payInvoice(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) { true } /** Clears the proof when [error] proves the payment never left; returns whether it did. */ - suspend fun failLightningPayment(paymentHash: String, error: Throwable): Boolean = - paymentProofRepo.failLightningPayment(paymentHash, error) + suspend fun failLightningPayment(paymentHash: String, error: Throwable, requestId: PaykitPaymentRequestId): Boolean = + paymentProofRepo.failLightningPayment(paymentHash, error, requestId) suspend fun discardLightningProof(paymentHash: String) = paymentProofRepo.failLightningPayment(paymentHash) @@ -987,7 +987,7 @@ class PaykitAllowanceExecutor @Inject constructor( ).onFailure { // Only an error that proves the payment never left releases the reservation; anything else stays open, // and the node's payment event records its outcome. - if (payer.failLightningPayment(paymentHash, it)) { + if (payer.failLightningPayment(paymentHash, it, request.id)) { failUnsent(attemptId, identity) throw it } diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index b8fe69b490..ba128f7054 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -934,7 +934,16 @@ class PaykitPaymentProofRepo @Inject constructor( it.kind == PaykitPaymentProofKind.Lightning && it.paymentIdentifier.equals(paymentHash, ignoreCase = true) } - suspend fun failLightningPayment(paymentHash: String, submissionError: Throwable): Boolean { + /** + * Clears the Lightning proofs of [paymentHash] when [submissionError] proves the payment never left, only those of + * [requestId] when given, so a refused request leaves another request's proof of the same invoice; returns whether + * it did. + */ + suspend fun failLightningPayment( + paymentHash: String, + submissionError: Throwable, + requestId: PaykitPaymentRequestId? = null, + ): Boolean { val error = generateSequence(submissionError) { it.cause } .firstOrNull { it is ServiceError.PaymentDeadlineExpired || it is SparkError.SendRefused } ?: submissionError.asNodeException() ?: submissionError @@ -948,7 +957,11 @@ class PaykitPaymentProofRepo @Inject constructor( is NodeException.NotRunning, is NodeException.InvalidInvoice, is NodeException.InvalidAmount, - is NodeException.PaymentSendingFailed -> failLightningPayment(paymentHash) + is NodeException.PaymentSendingFailed -> removeProofs { + it.kind == PaykitPaymentProofKind.Lightning && + it.paymentIdentifier.equals(paymentHash, ignoreCase = true) && + (requestId == null || it.requestId == requestId) + } else -> return false } return true diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index e068e4196a..7f2a48b877 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -8282,7 +8282,7 @@ class AppViewModel @Inject constructor( ) lnurlComment?.let { activityRepo.setLightningMessageIfEmpty(paymentHash, it) } }.onFailure { error -> - if (!clearFailedLightningPayment(paymentHash, error, incomingPaymentRequest != null, updateFailed)) { + if (!clearFailedLightningPayment(paymentHash, error, incomingPaymentRequest?.id, updateFailed)) { val pendingHash = (error as? PaymentPendingException)?.paymentHash ?: paymentHash proofRequest = null Logger.info("Lightning payment pending", context = TAG) @@ -8430,17 +8430,17 @@ class AppViewModel @Inject constructor( private suspend fun clearFailedLightningPayment( paymentHash: String, error: Throwable, - isPaymentRequest: Boolean, + requestId: PaykitPaymentRequestId?, updateFailed: Boolean, ): Boolean = when (error) { is PaymentPendingException -> false - else if !isPaymentRequest -> true + else if requestId == null -> true // Any failed spending balance update happens before the invoice is paid, so nothing was sent. else if updateFailed || error is LightningPaymentFailedError -> { paykitPaymentProofRepo.failLightningPayment(paymentHash) true } - else -> paykitPaymentProofRepo.failLightningPayment(paymentHash, error) + else -> paykitPaymentProofRepo.failLightningPayment(paymentHash, error, requestId) } private suspend fun prepareContactPayment( diff --git a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt index 050b8b5bb3..cfb5deec07 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt @@ -247,7 +247,7 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { whenever(payer.prepareProof(any(), any(), any(), anyOrNull())).thenReturn(Result.success(Unit)) whenever(payer.associateLightningPayment(any(), any(), any(), any())).thenReturn(Result.success(Unit)) whenever(payer.payLightning(any(), anyOrNull(), anyOrNull(), any())).thenReturn(Result.success(PAYMENT_HASH)) - whenever(payer.failLightningPayment(any(), any())).thenReturn(true) + whenever(payer.failLightningPayment(any(), any(), any())).thenReturn(true) whenever(payer.lightningPaymentStatus(any())).thenAnswer { nodeStatuses[it.getArgument(0)] } whenever(payer.canListLightningPayments()).thenAnswer { nodeListsPayments } } @@ -1071,7 +1071,7 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { whenever( payer.payLightning(any(), anyOrNull(), anyOrNull(), any()) ).thenReturn(Result.failure(TestAllowanceError("send"))) - whenever(payer.failLightningPayment(any(), any())).thenReturn(true, false) + whenever(payer.failLightningPayment(any(), any(), any())).thenReturn(true, false) val first = sut.autoPay(fixtures.paymentRequest(id = "request-1"), listOf(fixtures.allowance()), identity) val second = sut.autoPay(fixtures.paymentRequest(id = "request-2"), listOf(fixtures.allowance()), identity) @@ -1092,7 +1092,7 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { whenever( payer.payLightning(any(), anyOrNull(), anyOrNull(), any()) ).thenReturn(Result.failure(TestAllowanceError("send"))) - whenever(payer.failLightningPayment(any(), any())).thenReturn(true) + whenever(payer.failLightningPayment(any(), any(), any())).thenReturn(true) // The node's failure event lands during the failed send's release; a repeated release is owner-checked. var isSettling = false @@ -1247,7 +1247,7 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { sut.lightningPaymentSettled(PAYMENT_HASH, succeeded = false) Result.failure(TestAllowanceError("send")) } - whenever(payer.failLightningPayment(any(), any())).thenReturn(true) + whenever(payer.failLightningPayment(any(), any(), any())).thenReturn(true) sut.autoPay(fixtures.paymentRequest(), listOf(fixtures.allowance()), identity) diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index 428c884fbb..efeb2fd6e4 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -1501,6 +1501,20 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { } } + @Test + fun `refused submission for one request keeps another request's proof of the same invoice`() = test { + val first = paymentRequest(MethodId.Bolt11.rawValue) + val second = paymentRequest(MethodId.Bolt11.rawValue, paymentRequestId = "second-request") + val repo = paymentProofRepo() + for (request in listOf(first, second)) { + repo.prepare(request, MethodId.Bolt11.rawValue, "bitkit", PaykitPaymentProofKind.Lightning).getOrThrow() + repo.associateLightningPayment(request, PAYMENT_HASH, MethodId.Bolt11.rawValue, "bitkit").getOrThrow() + } + + assertTrue(repo.failLightningPayment(PAYMENT_HASH, SparkError.SendRefused("refused"), second.id)) + assertEquals(listOf(first.id), storedProofs.map { it.requestId }) + } + @Test fun `onchain proof uses selected endpoint and transaction id`() = test { val txid = "ab".repeat(32) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 723250894a..61c706572e 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -16321,7 +16321,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { .thenReturn(Result.success(Unit)) whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)) .thenReturn(Result.failure(error)) - whenever(paykitPaymentProofRepo.failLightningPayment(invoicePaymentHash, error)).thenReturn(true) + whenever(paykitPaymentProofRepo.failLightningPayment(eq(invoicePaymentHash), eq(error), anyOrNull())).thenReturn(true) setActiveContactPaymentContext(testPublicKey, privateContext, request) setSendState( SendUiState( @@ -16348,7 +16348,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { "bitkit", ) verify(lightningRepo).payInvoice(bolt11 = bolt11, sats = null) - verify(paykitPaymentProofRepo).failLightningPayment(invoicePaymentHash, error) + verify(paykitPaymentProofRepo).failLightningPayment(eq(invoicePaymentHash), eq(error), anyOrNull()) verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) verify(paykitPaymentProofRepo).cancelPreparation(request) } @@ -16449,7 +16449,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) .thenReturn(Result.success(Unit)) whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.failure(error)) - whenever(paykitPaymentProofRepo.failLightningPayment(paymentHash, error)).thenReturn(false) + whenever(paykitPaymentProofRepo.failLightningPayment(eq(paymentHash), eq(error), anyOrNull())).thenReturn(false) setActiveContactPaymentContext(testPublicKey, privateContext, request) setSendState( SendUiState( @@ -23209,7 +23209,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val error = NodeException.InsufficientFunds("refused") whenever(moveToSparkRepo.updateToSend(any(), any(), eq(request.amount.atomic), any())) .thenReturn(Result.failure(error)) - whenever(paykitPaymentProofRepo.failLightningPayment(paymentHash, error)).thenReturn(false) + whenever(paykitPaymentProofRepo.failLightningPayment(eq(paymentHash), eq(error), anyOrNull())).thenReturn(false) setActiveContactPaymentContext(testPublicKey, privateContext, request) setSendState( SendUiState( @@ -23231,7 +23231,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(pendingPaymentRepo, never()).track(any()) verify(paykitPaymentProofRepo).failLightningPayment(paymentHash) verify(paykitPaymentProofRepo).cancelPreparation(request) - verify(paykitPaymentProofRepo, never()).failLightningPayment(eq(paymentHash), any()) + verify(paykitPaymentProofRepo, never()).failLightningPayment(eq(paymentHash), any(), anyOrNull()) verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) verify(paykitAllowanceRepo).finishManualPayment("node-error-attempt", false, null) From b805940c2a98c2c4e704c66e73fe8c5a86580982 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 14:35:17 +0100 Subject: [PATCH 5/8] fix: scope every request-bound proof clear to its request A refused authorization, a failed spending balance update and an allowance's unsaved sending stage still cleared every Lightning proof of the invoice. They now clear only their own request's proof. Pending also skips a failed earlier payment's amount and shows the draft amount. Verified: PaykitPaymentProofRepoTest, PaykitAllowanceExecutorTest and AppViewModelSendFlowTest pass. --- .../repositories/PaykitAllowanceExecutor.kt | 12 +++-- .../repositories/PaykitPaymentProofRepo.kt | 22 ++++---- .../java/to/bitkit/viewmodels/AppViewModel.kt | 7 +-- .../PaykitAllowanceExecutorTest.kt | 13 +++-- .../viewmodels/AppViewModelSendFlowTest.kt | 50 ++++++++++++++----- 5 files changed, 69 insertions(+), 35 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt index 41ab2298e8..c24e9b6841 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt @@ -119,10 +119,14 @@ class PaykitAllowancePayer @Inject constructor( ): Result = lightningRepo.payInvoice(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) { true } /** Clears the proof when [error] proves the payment never left; returns whether it did. */ - suspend fun failLightningPayment(paymentHash: String, error: Throwable, requestId: PaykitPaymentRequestId): Boolean = - paymentProofRepo.failLightningPayment(paymentHash, error, requestId) + suspend fun failLightningPayment( + paymentHash: String, + error: Throwable, + requestId: PaykitPaymentRequestId, + ): Boolean = paymentProofRepo.failLightningPayment(paymentHash, error, requestId) - suspend fun discardLightningProof(paymentHash: String) = paymentProofRepo.failLightningPayment(paymentHash) + suspend fun discardLightningProof(paymentHash: String, requestId: PaykitPaymentRequestId) = + paymentProofRepo.failLightningPayment(paymentHash, requestId) suspend fun cancelProofPreparation(request: PaykitPaymentRequest) = paymentProofRepo.cancelPreparation(request) @@ -970,7 +974,7 @@ class PaykitAllowanceExecutor @Inject constructor( } runSuspendCatching { setStage(Stage.SENDING, attemptId, identity) }.onFailure { - payer.discardLightningProof(paymentHash) + payer.discardLightningProof(paymentHash, request.id) failUnsent(attemptId, identity) throw it } diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index ba128f7054..fc7b03fd22 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -930,15 +930,17 @@ class PaykitPaymentProofRepo @Inject constructor( completed } - suspend fun failLightningPayment(paymentHash: String) = removeProofs { - it.kind == PaykitPaymentProofKind.Lightning && it.paymentIdentifier.equals(paymentHash, ignoreCase = true) - } - /** - * Clears the Lightning proofs of [paymentHash] when [submissionError] proves the payment never left, only those of - * [requestId] when given, so a refused request leaves another request's proof of the same invoice; returns whether - * it did. + * Clears the Lightning proofs of [paymentHash], only those of [requestId] when given, so a request that sent nothing + * leaves another request's proof of the same invoice. */ + suspend fun failLightningPayment(paymentHash: String, requestId: PaykitPaymentRequestId? = null) = removeProofs { + it.kind == PaykitPaymentProofKind.Lightning && + it.paymentIdentifier.equals(paymentHash, ignoreCase = true) && + (requestId == null || it.requestId == requestId) + } + + /** Clears the proofs as above when [submissionError] proves the payment never left; returns whether it did. */ suspend fun failLightningPayment( paymentHash: String, submissionError: Throwable, @@ -957,11 +959,7 @@ class PaykitPaymentProofRepo @Inject constructor( is NodeException.NotRunning, is NodeException.InvalidInvoice, is NodeException.InvalidAmount, - is NodeException.PaymentSendingFailed -> removeProofs { - it.kind == PaykitPaymentProofKind.Lightning && - it.paymentIdentifier.equals(paymentHash, ignoreCase = true) && - (requestId == null || it.requestId == requestId) - } + is NodeException.PaymentSendingFailed -> failLightningPayment(paymentHash, requestId) else -> return false } return true diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 7f2a48b877..1581df6c53 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -29,6 +29,7 @@ import com.synonym.bitkitcore.LnurlWithdrawData import com.synonym.bitkitcore.OnChainInvoice import com.synonym.bitkitcore.PaykitEndpoint import com.synonym.bitkitcore.PaykitRoute +import com.synonym.bitkitcore.PaymentState import com.synonym.bitkitcore.PaymentType import com.synonym.bitkitcore.PubkySwapRoutePayment import com.synonym.bitkitcore.PubkySwapRouteQuote @@ -8257,7 +8258,7 @@ class AppViewModel @Inject constructor( onFailure = { Result.failure(it) }, ) authorizationError?.let { - paykitPaymentProofRepo.failLightningPayment(paymentHash) + paykitPaymentProofRepo.failLightningPayment(paymentHash, incomingPaymentRequest?.id) releasePrivatePaymentListIfNeeded(contactPaymentContext) cancelPaymentProofPreparation(proofRequest) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) @@ -8320,7 +8321,7 @@ class AppViewModel @Inject constructor( private suspend fun earlierLightningSendSats(paymentHash: String): ULong? = (activityRepo.getActivity(paymentHash).getOrNull() as? Activity.Lightning)?.v1 - ?.takeIf { it.txType == PaymentType.SENT } + ?.takeIf { it.txType == PaymentType.SENT && it.status != PaymentState.FAILED } ?.value /** @@ -8437,7 +8438,7 @@ class AppViewModel @Inject constructor( else if requestId == null -> true // Any failed spending balance update happens before the invoice is paid, so nothing was sent. else if updateFailed || error is LightningPaymentFailedError -> { - paykitPaymentProofRepo.failLightningPayment(paymentHash) + paykitPaymentProofRepo.failLightningPayment(paymentHash, requestId) true } else -> paykitPaymentProofRepo.failLightningPayment(paymentHash, error, requestId) diff --git a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt index cfb5deec07..15ac13a291 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt @@ -1056,12 +1056,13 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { @Test fun `unsaved sending stage releases the payment list and never sends`() = test { failSave = { "SENDING" in it } + val request = fixtures.paymentRequest() - val result = sut.autoPay(fixtures.paymentRequest(), listOf(fixtures.allowance()), identity) + val result = sut.autoPay(request, listOf(fixtures.allowance()), identity) assertEquals(PaykitAllowanceAutoPayResult.MANUAL, result) assertEquals(listOf(PaymentOutcomeReport(AUTOMATIC_ATTEMPT_ID, PaymentOutcome.FAILED)), recordedOutcomes) - verify(payer).discardLightningProof(PAYMENT_HASH) + verify(payer).discardLightningProof(PAYMENT_HASH, request.id) verify(payer).releasePaymentList(any(), any(), any()) verify(payer, never()).payLightning(any(), anyOrNull(), anyOrNull(), any()) } @@ -1073,8 +1074,10 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { ).thenReturn(Result.failure(TestAllowanceError("send"))) whenever(payer.failLightningPayment(any(), any(), any())).thenReturn(true, false) - val first = sut.autoPay(fixtures.paymentRequest(id = "request-1"), listOf(fixtures.allowance()), identity) - val second = sut.autoPay(fixtures.paymentRequest(id = "request-2"), listOf(fixtures.allowance()), identity) + val firstRequest = fixtures.paymentRequest(id = "request-1") + val secondRequest = fixtures.paymentRequest(id = "request-2") + val first = sut.autoPay(firstRequest, listOf(fixtures.allowance()), identity) + val second = sut.autoPay(secondRequest, listOf(fixtures.allowance()), identity) assertEquals(PaykitAllowanceAutoPayResult.MANUAL, first) // An uncertain send stays with the node, whose payment event records the outcome. @@ -1084,6 +1087,8 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { recordedOutcomes.map { it.outcome }, ) assertEquals(Stage.UNKNOWN, sut.localState(identity).journal.single().stage) + verify(payer).failLightningPayment(eq(PAYMENT_HASH), any(), eq(firstRequest.id)) + verify(payer).failLightningPayment(eq(PAYMENT_HASH), any(), eq(secondRequest.id)) } @Test diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 61c706572e..577143ed67 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -23,6 +23,7 @@ import com.synonym.bitkitcore.NetworkType import com.synonym.bitkitcore.OnChainInvoice import com.synonym.bitkitcore.PaykitEndpoint import com.synonym.bitkitcore.PaykitRoute +import com.synonym.bitkitcore.PaymentState import com.synonym.bitkitcore.PaymentType import com.synonym.bitkitcore.PubkySwapRoutePayment import com.synonym.bitkitcore.PubkySwapRouteQuote @@ -12164,6 +12165,30 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } } + @Test + fun `repaying an amountless invoice whose earlier payment failed shows the new amount as pending`() = test { + val bolt11 = "lnbcrt1amountlessfailed" + val invoice = lightningInvoice(bolt11, 0u) + val paymentHash = invoice.paymentHash.toHex() + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = 2_000u)) + .thenReturn(Result.failure(PaymentPendingException(paymentHash))) + val earlier = mock { + on { value } doReturn 1_000u + on { txType } doReturn PaymentType.SENT + on { status } doReturn PaymentState.FAILED + } + whenever(activityRepo.getActivity(paymentHash)).thenReturn(Result.success(BitkitActivity.Lightning(earlier))) + val state = SendUiState(address = bolt11, payMethod = SendMethod.LIGHTNING, decodedInvoice = invoice) + + sut.sendEffect.test { + setSendState(state.copy(amount = 2_000u)) + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + val pending = assertIs(expectMostRecentItem()) + assertEquals(2_000L, pending.amount) + } + } + @Test fun `a payment shown by its event during the swipe shows its success once`() = test { val bolt11 = "lnbcrt1eventfirst" @@ -16224,13 +16249,13 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) if (preparationSucceeds) { verify(paykitPaymentRequestRepo).accept(request) - verify(paykitPaymentProofRepo).failLightningPayment(paymentHash) + verify(paykitPaymentProofRepo).failLightningPayment(paymentHash, request.id) verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) } else { verify(paykitPaymentRequestRepo, never()).accept(request) verify(privatePaykitRepo, never()).consumePrivatePaymentList(any(), any()) verify(paykitPaymentProofRepo, never()).associateLightningPayment(any(), any(), any(), eq("bitkit")) - verify(paykitPaymentProofRepo, never()).failLightningPayment(any()) + verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) } clearInvocations(lightningRepo, paykitPaymentProofRepo, paykitPaymentRequestRepo, privatePaykitRepo) } @@ -16289,7 +16314,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) verify(lightningRepo).payInvoice(bolt11 = bolt11, sats = null) } - verify(paykitPaymentProofRepo, never()).failLightningPayment(any()) + verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) verify(paykitPaymentProofRepo, never()).cancelPreparation(any()) verify(privatePaykitRepo, never()).releasePrivatePaymentList(any(), any()) } @@ -16321,7 +16346,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { .thenReturn(Result.success(Unit)) whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)) .thenReturn(Result.failure(error)) - whenever(paykitPaymentProofRepo.failLightningPayment(eq(invoicePaymentHash), eq(error), anyOrNull())).thenReturn(true) + whenever(paykitPaymentProofRepo.failLightningPayment(eq(invoicePaymentHash), eq(error), eq(request.id))) + .thenReturn(true) setActiveContactPaymentContext(testPublicKey, privateContext, request) setSendState( SendUiState( @@ -16348,7 +16374,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { "bitkit", ) verify(lightningRepo).payInvoice(bolt11 = bolt11, sats = null) - verify(paykitPaymentProofRepo).failLightningPayment(eq(invoicePaymentHash), eq(error), anyOrNull()) + verify(paykitPaymentProofRepo).failLightningPayment(invoicePaymentHash, error, request.id) verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) verify(paykitPaymentProofRepo).cancelPreparation(request) } @@ -16467,7 +16493,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(SendEffect.NavigateToPending(paymentHash, request.amount.atomic.toLong()), awaitItem()) } verify(pendingPaymentRepo).track(paymentHash) - verify(paykitPaymentProofRepo, never()).failLightningPayment(any()) + verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) verify(paykitPaymentProofRepo, never()).cancelPreparation(any()) verify(privatePaykitRepo, never()).releasePrivatePaymentList(any(), any()) } @@ -18715,7 +18741,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.setSendEvent(SendEvent.PayConfirmed) advanceUntilIdle() - verify(paykitPaymentProofRepo).failLightningPayment("010203") + verify(paykitPaymentProofRepo).failLightningPayment("010203", request.id) verify(paykitPaymentProofRepo).cancelPreparation(request) verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) @@ -19852,7 +19878,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { balanceState.value = BalanceState(maxSendLightningSats = 100_000u) whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)) .thenReturn(Result.failure(NodeException.PaymentSendingFailed("no route"))) - whenever(paykitPaymentProofRepo.failLightningPayment(any())).doSuspendableAnswer { + whenever(paykitPaymentProofRepo.failLightningPayment(any(), anyOrNull())).doSuspendableAnswer { cleanup.await() Result.success(Unit) } @@ -19869,7 +19895,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.setSendEvent(SendEvent.PayConfirmed) advanceUntilIdle() assertTrue(awaitItem() is SendEffect.NavigateToError) - verify(paykitPaymentProofRepo, never()).failLightningPayment(any()) + verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) verify(lightningRepo).payInvoice(bolt11 = bolt11, sats = null) } } finally { @@ -23107,7 +23133,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertTrue(awaitItem() is SendEffect.NavigateToError) } verify(pendingPaymentRepo, never()).track(any()) - verify(paykitPaymentProofRepo).failLightningPayment(paymentHash) + verify(paykitPaymentProofRepo).failLightningPayment(paymentHash, request.id) verify(paykitPaymentProofRepo).cancelPreparation(request) verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) @@ -23229,7 +23255,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertTrue(awaitItem() is SendEffect.NavigateToError) } verify(pendingPaymentRepo, never()).track(any()) - verify(paykitPaymentProofRepo).failLightningPayment(paymentHash) + verify(paykitPaymentProofRepo).failLightningPayment(paymentHash, request.id) verify(paykitPaymentProofRepo).cancelPreparation(request) verify(paykitPaymentProofRepo, never()).failLightningPayment(eq(paymentHash), any(), anyOrNull()) verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) @@ -23374,7 +23400,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(moveToSparkRepo, never()).updateToSend(any(), any(), any(), any()) verify(closeChannelUseCase, never()).closeEmptiedByMove(any(), anyOrNull()) verify(pendingPaymentRepo, never()).track(any()) - verify(paykitPaymentProofRepo).failLightningPayment(paymentHash) + verify(paykitPaymentProofRepo).failLightningPayment(paymentHash, request.id) verify(paykitPaymentProofRepo).cancelPreparation(request) verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) From 8bfa3b8a2793f267ed7ac7cdfe848b7a6680ac53 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 14:52:59 +0100 Subject: [PATCH 6/8] test: wrap long proof matcher lines Verified: just compile, just test and just lint pass. --- .../bitkit/repositories/PaykitPaymentProofRepo.kt | 4 ++-- .../bitkit/viewmodels/AppViewModelSendFlowTest.kt | 13 ++++++++----- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index fc7b03fd22..20ee9882df 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -931,8 +931,8 @@ class PaykitPaymentProofRepo @Inject constructor( } /** - * Clears the Lightning proofs of [paymentHash], only those of [requestId] when given, so a request that sent nothing - * leaves another request's proof of the same invoice. + * Clears the Lightning proofs of [paymentHash], only those of [requestId] when given, so a request that sent + * nothing leaves another request's proof of the same invoice. */ suspend fun failLightningPayment(paymentHash: String, requestId: PaykitPaymentRequestId? = null) = removeProofs { it.kind == PaykitPaymentProofKind.Lightning && diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 577143ed67..274409c3ae 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12152,6 +12152,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val earlier = mock { on { value } doReturn 1_000u on { txType } doReturn PaymentType.SENT + on { status } doReturn PaymentState.PENDING } whenever(activityRepo.getActivity(paymentHash)).thenReturn(Result.success(BitkitActivity.Lightning(earlier))) val state = SendUiState(address = bolt11, payMethod = SendMethod.LIGHTNING, decodedInvoice = invoice) @@ -16255,7 +16256,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(paykitPaymentRequestRepo, never()).accept(request) verify(privatePaykitRepo, never()).consumePrivatePaymentList(any(), any()) verify(paykitPaymentProofRepo, never()).associateLightningPayment(any(), any(), any(), eq("bitkit")) - verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) + verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) } clearInvocations(lightningRepo, paykitPaymentProofRepo, paykitPaymentRequestRepo, privatePaykitRepo) } @@ -16314,7 +16315,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) verify(lightningRepo).payInvoice(bolt11 = bolt11, sats = null) } - verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) + verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) verify(paykitPaymentProofRepo, never()).cancelPreparation(any()) verify(privatePaykitRepo, never()).releasePrivatePaymentList(any(), any()) } @@ -16493,7 +16494,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(SendEffect.NavigateToPending(paymentHash, request.amount.atomic.toLong()), awaitItem()) } verify(pendingPaymentRepo).track(paymentHash) - verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) + verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) verify(paykitPaymentProofRepo, never()).cancelPreparation(any()) verify(privatePaykitRepo, never()).releasePrivatePaymentList(any(), any()) } @@ -19878,7 +19879,9 @@ class AppViewModelSendFlowTest : BaseUnitTest() { balanceState.value = BalanceState(maxSendLightningSats = 100_000u) whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)) .thenReturn(Result.failure(NodeException.PaymentSendingFailed("no route"))) - whenever(paykitPaymentProofRepo.failLightningPayment(any(), anyOrNull())).doSuspendableAnswer { + whenever( + paykitPaymentProofRepo.failLightningPayment(any(), anyOrNull()) + ).doSuspendableAnswer { cleanup.await() Result.success(Unit) } @@ -19895,7 +19898,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.setSendEvent(SendEvent.PayConfirmed) advanceUntilIdle() assertTrue(awaitItem() is SendEffect.NavigateToError) - verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) + verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) verify(lightningRepo).payInvoice(bolt11 = bolt11, sats = null) } } finally { From e3a80464a9bc2c69467e3b7c105a5d14d2e61a8d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 15:09:58 +0100 Subject: [PATCH 7/8] fix: show a held spark send's amount on pending A repeat that waits on an earlier Spark send not yet in Activity showed the draft amount on Pending. It now shows the amount kept on that send's attempt. Verified: AppViewModelSendFlowTest passes. --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 10 +++++--- .../viewmodels/AppViewModelSendFlowTest.kt | 25 +++++++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 1581df6c53..3cfd783d08 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -8319,10 +8319,12 @@ class AppViewModel @Inject constructor( } } - private suspend fun earlierLightningSendSats(paymentHash: String): ULong? = - (activityRepo.getActivity(paymentHash).getOrNull() as? Activity.Lightning)?.v1 - ?.takeIf { it.txType == PaymentType.SENT && it.status != PaymentState.FAILED } - ?.value + private suspend fun earlierLightningSendSats(paymentHash: String): ULong? { + val sent = (activityRepo.getActivity(paymentHash).getOrNull() as? Activity.Lightning)?.v1 + ?.takeIf { it.txType == PaymentType.SENT } + ?: return cacheStore.data.first().sparkSendAttempts[paymentHash.lowercase()]?.amountSats + return sent.value.takeIf { sent.status != PaymentState.FAILED } + } /** * Before a payment of [bolt11] for [amountSats] that fits only across the channels and Spark, moves the channels' diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 274409c3ae..bc7738b726 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -121,6 +121,7 @@ import to.bitkit.data.PrivatePaykitReservationData import to.bitkit.data.PrivatePaykitReservationStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore +import to.bitkit.data.SparkSendAttempt import to.bitkit.data.UsdtPreference import to.bitkit.data.WalletConnectionRecovery import to.bitkit.data.dto.PlatformDetails @@ -12166,6 +12167,27 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } } + @Test + fun `repaying an amountless invoice held by spark without activity shows the held amount`() = test { + val bolt11 = "lnbcrt1amountlessheld" + val invoice = lightningInvoice(bolt11, 0u) + val paymentHash = invoice.paymentHash.toHex() + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = 2_000u)) + .thenReturn(Result.failure(PaymentPendingException(paymentHash))) + whenever(activityRepo.getActivity(paymentHash)).thenReturn(Result.success(null)) + val attempt = SparkSendAttempt(attempt = 0, expiresAt = Long.MAX_VALUE, amountSats = 1_000u) + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(sparkSendAttempts = mapOf(paymentHash to attempt)))) + val state = SendUiState(address = bolt11, payMethod = SendMethod.LIGHTNING, decodedInvoice = invoice) + + sut.sendEffect.test { + setSendState(state.copy(amount = 2_000u)) + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + val pending = assertIs(expectMostRecentItem()) + assertEquals(1_000L, pending.amount) + } + } + @Test fun `repaying an amountless invoice whose earlier payment failed shows the new amount as pending`() = test { val bolt11 = "lnbcrt1amountlessfailed" @@ -12179,6 +12201,9 @@ class AppViewModelSendFlowTest : BaseUnitTest() { on { status } doReturn PaymentState.FAILED } whenever(activityRepo.getActivity(paymentHash)).thenReturn(Result.success(BitkitActivity.Lightning(earlier))) + val failedAttempt = SparkSendAttempt(attempt = 0, expiresAt = Long.MAX_VALUE, amountSats = 1_000u) + val cache = AppCacheData(sparkSendAttempts = mapOf(paymentHash to failedAttempt)) + whenever(cacheStore.data).thenReturn(flowOf(cache)) val state = SendUiState(address = bolt11, payMethod = SendMethod.LIGHTNING, decodedInvoice = invoice) sut.sendEffect.test { From 2c5eb30558ef1cf21fa2af79e226b31f63e95d55 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 16:26:51 +0100 Subject: [PATCH 8/8] fix: show a kept spark amount on pending only while held Pending fell back to the kept Spark attempt's amount whenever Activity had no sent row, so a failed attempt's amount showed for a new payment, and a failed row hid a held retry's amount. Pending now shows a non-failed sent row's amount, else the kept amount while Spark holds that send, else the draft amount. Verified: AppViewModelSendFlowTest passes. --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 8 ++- .../viewmodels/AppViewModelSendFlowTest.kt | 57 ++++++++++++++++++- 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 3cfd783d08..1098b4de31 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -8321,9 +8321,11 @@ class AppViewModel @Inject constructor( private suspend fun earlierLightningSendSats(paymentHash: String): ULong? { val sent = (activityRepo.getActivity(paymentHash).getOrNull() as? Activity.Lightning)?.v1 - ?.takeIf { it.txType == PaymentType.SENT } - ?: return cacheStore.data.first().sparkSendAttempts[paymentHash.lowercase()]?.amountSats - return sent.value.takeIf { sent.status != PaymentState.FAILED } + ?.takeIf { it.txType == PaymentType.SENT && it.status != PaymentState.FAILED } + if (sent != null) return sent.value + val hash = paymentHash.lowercase() + val cache = cacheStore.data.first() + return cache.sparkSendAttempts[hash]?.amountSats?.takeIf { hash in cache.sparkUncertainSends } } /** diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index bc7738b726..de44a01028 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12176,7 +12176,11 @@ class AppViewModelSendFlowTest : BaseUnitTest() { .thenReturn(Result.failure(PaymentPendingException(paymentHash))) whenever(activityRepo.getActivity(paymentHash)).thenReturn(Result.success(null)) val attempt = SparkSendAttempt(attempt = 0, expiresAt = Long.MAX_VALUE, amountSats = 1_000u) - whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(sparkSendAttempts = mapOf(paymentHash to attempt)))) + val cache = AppCacheData( + sparkSendAttempts = mapOf(paymentHash to attempt), + sparkUncertainSends = mapOf(paymentHash to 0L), + ) + whenever(cacheStore.data).thenReturn(flowOf(cache)) val state = SendUiState(address = bolt11, payMethod = SendMethod.LIGHTNING, decodedInvoice = invoice) sut.sendEffect.test { @@ -12188,6 +12192,57 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } } + @Test + fun `repaying an amountless invoice after a failed spark attempt without activity shows the new amount`() = test { + val bolt11 = "lnbcrt1amountlessdropped" + val invoice = lightningInvoice(bolt11, 0u) + val paymentHash = invoice.paymentHash.toHex() + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = 2_000u)) + .thenReturn(Result.failure(PaymentPendingException(paymentHash))) + whenever(activityRepo.getActivity(paymentHash)).thenReturn(Result.success(null)) + val attempt = SparkSendAttempt(attempt = 1, expiresAt = Long.MAX_VALUE, amountSats = 6_000u) + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(sparkSendAttempts = mapOf(paymentHash to attempt)))) + val state = SendUiState(address = bolt11, payMethod = SendMethod.LIGHTNING, decodedInvoice = invoice) + + sut.sendEffect.test { + setSendState(state.copy(amount = 2_000u)) + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + val pending = assertIs(expectMostRecentItem()) + assertEquals(2_000L, pending.amount) + } + } + + @Test + fun `repaying an amountless invoice held by spark after a failed row shows the held amount`() = test { + val bolt11 = "lnbcrt1amountlessheldfailed" + val invoice = lightningInvoice(bolt11, 0u) + val paymentHash = invoice.paymentHash.toHex() + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = 2_000u)) + .thenReturn(Result.failure(PaymentPendingException(paymentHash))) + val failed = mock { + on { value } doReturn 5_000u + on { txType } doReturn PaymentType.SENT + on { status } doReturn PaymentState.FAILED + } + whenever(activityRepo.getActivity(paymentHash)).thenReturn(Result.success(BitkitActivity.Lightning(failed))) + val attempt = SparkSendAttempt(attempt = 1, expiresAt = Long.MAX_VALUE, amountSats = 6_000u) + val cache = AppCacheData( + sparkSendAttempts = mapOf(paymentHash to attempt), + sparkUncertainSends = mapOf(paymentHash to 0L), + ) + whenever(cacheStore.data).thenReturn(flowOf(cache)) + val state = SendUiState(address = bolt11, payMethod = SendMethod.LIGHTNING, decodedInvoice = invoice) + + sut.sendEffect.test { + setSendState(state.copy(amount = 2_000u)) + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + val pending = assertIs(expectMostRecentItem()) + assertEquals(6_000L, pending.amount) + } + } + @Test fun `repaying an amountless invoice whose earlier payment failed shows the new amount as pending`() = test { val bolt11 = "lnbcrt1amountlessfailed"