From a9bdaf23f203e5f39d85c3f09b7ff65a0c41d300 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Wed, 25 Nov 2026 11:21:08 -0300 Subject: [PATCH 01/15] fix: skip quickpay's node wait when spark covers the amount The QuickPay check passes the amount to the channel wait, so a payment Spark covers alone does not wait for the node to start. Spark covering the amount means no update is needed for any channel state, and the rail is still picked at send time. Co-Authored-By: Claude Fable 5.2 --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 3 +- .../viewmodels/AppViewModelSendFlowTest.kt | 119 ++++++++++++++++++ changelog.d/next/2028.fixed.md | 1 + 3 files changed, 122 insertions(+), 1 deletion(-) create mode 100644 changelog.d/next/2028.fixed.md diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 645ee70721..9b417d1054 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6786,8 +6786,9 @@ class AppViewModel @Inject constructor( val open = invoiceHash != null && quickPayRepo.hasOpen(invoiceHash) // QuickPay has no confirm screen to show the update fee, so a payment that needs the update is reviewed. While // the node starts or its channels reconnect their balance is unknown, so that is decided once they are usable. + // An amount Spark covers alone never needs the update, so it does not wait for the node. val isQuickPayOn = settingsStore.data.first().isQuickPayEnabled - if (!open && isQuickPayOn && channelsAreSettling()) waitForUsableChannels(walletGeneration) + if (!open && isQuickPayOn && channelsAreSettling()) waitForUsableChannels(walletGeneration, amountSats) if (!open && moveToSparkRepo.needsUpdateToSend(amountSats)) return false val canApply = open || canApplyQuickPay(amountSats) requireCurrentPaymentPreparation(walletGeneration) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 720ab7ccbd..acd4f4b710 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -22459,6 +22459,125 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertNull(sut.quickPayData.value, "QuickPay paid a payment that needs the update") } + @Test + fun `a scan while the node starts uses QuickPay without the channel wait when Spark covers the amount`() = test { + val bolt11 = "lnbcrt1quickpaysparkstarting" + enableQuickPay() + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + whenever(lightningRepo.canSendWithSpark(500u)).thenReturn(true) + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Starting))) + + sut.onScanResult(bolt11) + advanceUntilIdle() + + verify(lightningRepo, never()).waitForUsableChannels(any()) + assertEquals(QuickPayData.Bolt11(sats = 500u, bolt11 = bolt11), sut.quickPayData.value?.data) + assertEquals(Sheet.Send(SendRoute.QuickPay), sut.currentSheet.value) + } + + @Test + fun `a scan while the node starts waits for the channels when Spark covers less than the amount`() = test { + val bolt11 = "lnbcrt1quickpaysparkshort" + enableQuickPay() + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + whenever(lightningRepo.canSendWithSpark(499u)).thenReturn(true) + val nodeState = MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Starting)) + whenever(lightningRepo.lightningState).thenReturn(nodeState) + var isQuickPaySetBeforeWait = false + whenever(lightningRepo.waitForUsableChannels()).thenAnswer { + isQuickPaySetBeforeWait = sut.quickPayData.value != null + nodeState.value = LightningState(nodeLifecycleState = NodeLifecycleState.Running) + Unit + } + + sut.onScanResult(bolt11) + advanceUntilIdle() + + verify(lightningRepo).waitForUsableChannels() + assertFalse(isQuickPaySetBeforeWait) + assertEquals(QuickPayData.Bolt11(sats = 500u, bolt11 = bolt11), sut.quickPayData.value?.data) + } + + @Test + fun `a scan with unusable channels uses QuickPay without waiting for them when Spark covers the amount`() = test { + val bolt11 = "lnbcrt1quickpaysparkpeeroffline" + enableQuickPay() + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + whenever(lightningRepo.canSendWithSpark(500u)).thenReturn(true) + val offlinePeerChannel = mock { on { isUsable } doReturn false } + whenever(lightningRepo.lightningState).thenReturn( + MutableStateFlow( + LightningState( + nodeLifecycleState = NodeLifecycleState.Running, + channels = persistentListOf(offlinePeerChannel), + ) + ) + ) + + sut.onScanResult(bolt11) + advanceUntilIdle() + + verify(lightningRepo, never()).waitForUsableChannels() + verify(lightningRepo).waitForUsableChannels(awaitUsable = false) + assertEquals(QuickPayData.Bolt11(sats = 500u, bolt11 = bolt11), sut.quickPayData.value?.data) + } + + @Test + fun `a fixed lnurl scan while the node starts uses QuickPay without the channel wait when Spark covers`() = test { + val input = "lnurl1quickpaysparkstarting" + val data = + LnurlPayData(input, "https://example.com/callback", 1_000_000uL, 1_000_000uL, "[]", null, false, null) + enableQuickPay() + whenever(coreService.decode(input)).thenReturn(Scanner.LnurlPay(data)) + whenever(lightningRepo.canSend(1_000u)).thenReturn(true) + whenever(lightningRepo.canSendWithSpark(1_000u)).thenReturn(true) + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Starting))) + + sut.onScanResult(input) + advanceUntilIdle() + + verify(lightningRepo, never()).waitForUsableChannels(any()) + assertEquals(QuickPayData.LnurlPay(sats = 1_000u, data = data), sut.quickPayData.value?.data) + } + + @Test + fun `a unified scan while the node starts uses QuickPay without the channel wait when Spark covers`() = test { + val bolt11 = "lnbcrt1quickpaysparkunified" + val uri = "bitcoin:$REGTEST_ADDRESS?amount=0.0002&lightning=$bolt11" + enableQuickPay() + stubUnifiedScan(uri = uri, bolt11 = bolt11, amountSats = 20_000u, payeeNodeId = FOREIGN_NODE_ID.fromHex()) + whenever(lightningRepo.canSendWithSpark(20_000u)).thenReturn(true) + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Starting))) + + sut.onScanResult(uri) + advanceUntilIdle() + + verify(lightningRepo, never()).waitForUsableChannels(any()) + assertEquals(QuickPayData.Bolt11(sats = 20_000u, bolt11 = bolt11), sut.quickPayData.value?.data) + } + + @Test + fun `a payment that needs the update is never sent by QuickPay when the channel wait is skipped`() = test { + val bolt11 = "lnbcrt1quickpaysparkupdate" + enableQuickPay() + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + whenever(lightningRepo.canSendWithSpark(500u)).thenReturn(true) + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Starting))) + whenever(moveToSparkRepo.needsUpdateToSend(500uL)).thenReturn(true) + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(MoveToSparkQuote("lnbcrt1spark", 500uL, 1uL))) + whenever(moveToSparkRepo.estimateFeeAfterUpdate(bolt11, 500uL)).thenReturn(2uL) + + sut.onScanResult(bolt11) + advanceUntilIdle() + + assertNull(sut.quickPayData.value, "QuickPay paid a payment that needs the update") + verify(quickPayRepo, never()).canApply(any()) + } + @Test fun `a fixed-amount scan with QuickPay off does not wait for channels whose peer is offline`() = test { val bolt11 = "lnbcrt1quickpayoffpeeroffline" diff --git a/changelog.d/next/2028.fixed.md b/changelog.d/next/2028.fixed.md new file mode 100644 index 0000000000..36755808e2 --- /dev/null +++ b/changelog.d/next/2028.fixed.md @@ -0,0 +1 @@ +Fixed QuickPay waiting about 10 seconds for the Lightning node when Bitkit is opened by a payment request and the Spark balance covers the amount. From e14b9d6e998cf1b4b2054b6eef6e171cc1a54da7 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Wed, 25 Nov 2026 11:35:24 -0300 Subject: [PATCH 02/15] chore: rename changelog fragment Co-Authored-By: Claude Fable 5.2 --- changelog.d/next/{2028.fixed.md => 2036.fixed.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changelog.d/next/{2028.fixed.md => 2036.fixed.md} (100%) diff --git a/changelog.d/next/2028.fixed.md b/changelog.d/next/2036.fixed.md similarity index 100% rename from changelog.d/next/2028.fixed.md rename to changelog.d/next/2036.fixed.md From 646a152a3eead81a147ea1109d297b6b55bceec8 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Wed, 25 Nov 2026 12:14:16 -0300 Subject: [PATCH 03/15] fix: retry a held spark send once the node starts A Spark send refused until the node lists its earlier sends waits for a starting node and starts over once, so it no longer fails where QuickPay used to wait. An amountless invoice keeps the channel wait, and the tests cover the update invariant the skip relies on. Co-Authored-By: Claude Fable 5.2 --- .../to/bitkit/repositories/LightningRepo.kt | 32 ++++- .../java/to/bitkit/viewmodels/AppViewModel.kt | 9 +- .../bitkit/repositories/LightningRepoTest.kt | 126 ++++++++++++++++++ .../repositories/MoveToSparkRepoTest.kt | 33 +++++ .../viewmodels/AppViewModelSendFlowTest.kt | 21 ++- 5 files changed, 215 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 7c7a9f88d5..160045b408 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -299,7 +299,7 @@ class LightningRepo @Inject constructor( */ suspend fun executeWhenNodeRunning( operationName: String, - waitTimeout: Duration = 1.minutes, + waitTimeout: Duration = NODE_RUN_WAIT_TIMEOUT, operation: suspend () -> Result, ): Result = withContext(bgDispatcher) { Logger.verbose("Operation called: '$operationName'", context = TAG) @@ -1610,6 +1610,7 @@ class LightningRepo @Inject constructor( paymentDeadlineAt: Instant?, maxTotalRoutingFeeMsat: ULong?, isAuthorizedAtSubmission: (() -> Boolean)?, + isRetryAfterNodeStart: Boolean = false, onBeforeSend: suspend () -> Boolean, ): Result { // The rail is picked again on every attempt, so each one checks the other holds no live send of the invoice. @@ -1621,7 +1622,21 @@ class LightningRepo @Inject constructor( val ldkRecordsBefore = ldkSendRecords.get() val sparkRecordsBefore = sparkRepo.sendRecordMark() runSuspendCatching { earlierNodeSend(bolt11, paymentHash) } - .getOrElse { return Result.failure(it) } + .getOrElse { + // Nothing is authorized or admitted yet, so the payment starts over once the node can list its + // sends: the rail is picked again, and an earlier node send of the invoice is found. + val canRetry = it is ServiceError.NodeNotStarted && !isRetryAfterNodeStart + if (!canRetry || !awaitNodeRunning()) return Result.failure(it) + return payInvoiceChecked( + bolt11 = bolt11, + sats = sats, + paymentDeadlineAt = paymentDeadlineAt, + maxTotalRoutingFeeMsat = maxTotalRoutingFeeMsat, + isAuthorizedAtSubmission = isAuthorizedAtSubmission, + isRetryAfterNodeStart = true, + onBeforeSend = onBeforeSend, + ) + } ?.let { // The node paid it, so its caller settles from the node's payment, as its event already fired. if (it is EarlierSend.Paid) recordSendRail(it.paymentHash, LightningRail.Ldk) @@ -1682,6 +1697,16 @@ class LightningRepo @Inject constructor( ) } + private suspend fun awaitNodeRunning(): Boolean { + if (!_lightningState.value.nodeLifecycleState.canRun()) return false + withTimeoutOrNull(NODE_RUN_WAIT_TIMEOUT) { + _lightningState.first { it.nodeLifecycleState.isRunning() } + } ?: return false + // The node is marked running before its channels are published, and the rail is picked from them. + refreshChannelsAndPeers() + return true + } + /** Pays [bolt11] from the node's channels only, for a send quoted on them that must never fall back to Spark. */ suspend fun payInvoiceWithNode(bolt11: String): Result { val paymentHash = runCatching { Bolt11Invoice.fromStr(bolt11).paymentHash() }.getOrNull() @@ -3401,6 +3426,9 @@ class LightningRepo @Inject constructor( private val ABANDON_SYNC_TIMEOUT = 30.seconds private val NO_USABLE_CHANNELS_FEEDBACK_DELAY = 2_500.milliseconds + /** Max time an operation waits for a starting node to run. */ + private val NODE_RUN_WAIT_TIMEOUT = 1.minutes + /** Max time to wait for a starting node before its id is treated as unavailable. */ private val NODE_ID_WAIT_TIMEOUT = 15.seconds diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 9b417d1054..c9140723a8 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6502,7 +6502,7 @@ class AppViewModel @Inject constructor( ) if (quickPayHandled) return - waitForUsableChannels(walletGeneration, amount) + waitForUsableChannels(walletGeneration, amount.coerceAtLeast(1u)) if (!canSendLightning(amount)) { val maxSendLightning = walletRepo.balanceState.value.maxSendLightningSats val shortfall = amount.safe() - maxSendLightning.safe() @@ -6786,9 +6786,12 @@ class AppViewModel @Inject constructor( val open = invoiceHash != null && quickPayRepo.hasOpen(invoiceHash) // QuickPay has no confirm screen to show the update fee, so a payment that needs the update is reviewed. While // the node starts or its channels reconnect their balance is unknown, so that is decided once they are usable. - // An amount Spark covers alone never needs the update, so it does not wait for the node. + // An amount Spark covers alone never needs the update, so it does not wait for the node. An amountless + // invoice has no amount to cover yet, so it keeps the wait. val isQuickPayOn = settingsStore.data.first().isQuickPayEnabled - if (!open && isQuickPayOn && channelsAreSettling()) waitForUsableChannels(walletGeneration, amountSats) + if (!open && isQuickPayOn && channelsAreSettling()) { + waitForUsableChannels(walletGeneration, amountSats.takeIf { it > 0uL }) + } if (!open && moveToSparkRepo.needsUpdateToSend(amountSats)) return false val canApply = open || canApplyQuickPay(amountSats) requireCurrentPaymentPreparation(walletGeneration) diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 018e16b1bf..74f1070421 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -39,6 +39,7 @@ import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.runCurrent import org.junit.Before import org.junit.Test @@ -1396,6 +1397,131 @@ class LightningRepoTest : BaseUnitTest() { assertIs(retry.exceptionOrNull()) } + @Test + fun `a spark send held for the node's listing is retried once the starting node runs`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + var authorizations = 0 + + val payment = async { sut.payInvoice("bolt11", 1_000uL, onBeforeSend = { authorizations++ == 0 }) } + runCurrent() + assertFalse(payment.isCompleted, "The send failed instead of waiting for the starting node") + assertEquals(0, authorizations, "The send was authorized before the node listed its sends") + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + startNodeForTesting() + + assertEquals("hash", payment.await().getOrThrow()) + verify(sparkRepo, times(1)).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + verify(lightningService, never()).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) + } + + @Test + fun `a spark send held for the node's listing fails with the hold once the node start times out`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + var isAuthorizationAsked = false + + val payment = async { + sut.payInvoice("bolt11", 1_000uL, onBeforeSend = { + isAuthorizationAsked = true + true + }) + } + advanceTimeBy(59.seconds) + assertFalse(payment.isCompleted) + advanceTimeBy(2.seconds) + + assertIs(payment.await().exceptionOrNull()) + assertFalse(isAuthorizationAsked) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `a spark send held for the node's listing fails at once when the node cannot run`() = test { + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + runCurrent() + + assertTrue(payment.isCompleted) + assertIs(payment.await().exceptionOrNull()) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `a held spark send is retried only once while the running node still can't list`() = test { + startNodeForTesting() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + clearInvocations(lightningService) + + val retry = sut.payInvoice("bolt11", 1_000uL) + + assertIs(retry.exceptionOrNull()) + verify(lightningService, times(2)).listPayments() + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `the retry after the node starts pays over the node when its channels cover the amount`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("spark-hash")) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn("node-hash") + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + runCurrent() + assertFalse(payment.isCompleted) + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + whenever(lightningService.channels).thenReturn( + listOf(createChannelDetails().copy(isUsable = true, nextOutboundHtlcLimitMsat = 2_000_000uL)), + ) + startNodeForTesting() + + assertEquals("node-hash", payment.await().getOrThrow()) + verify(lightningService, times(1)).send(eq("bolt11"), eq(1_000uL), anyOrNull(), anyOrNull()) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `the retry after the node starts sends nothing when the node lists its earlier send`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + var isAuthorizationAsked = false + + val payment = async { + sut.payInvoice("bolt11", 1_000uL, onBeforeSend = { + isAuthorizationAsked = true + true + }) + } + runCurrent() + assertFalse(payment.isCompleted) + whenever(lightningService.listPayments()).thenReturn(listOf(nodeSend("bolt11", PaymentStatus.PENDING))) + startNodeForTesting() + + assertIs(payment.await().exceptionOrNull()) + assertFalse(isAuthorizationAsked) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + verify(lightningService, never()).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) + } + @Test fun `spark still pays while the node can't list when the node never tried the invoice`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index d162fe1508..674f72c894 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -580,6 +580,39 @@ class MoveToSparkRepoTest : BaseUnitTest() { assertTrue(!MoveToSparkMath.needsUpdateToSend(149_126uL, channels, spark)) } + @Test + fun `a payment Spark can send alone never needs the update, whatever the channels hold`() { + val channelSets = listOf( + null, + emptyList(), + listOf(channel("c1", 10_000uL)), + listOf(channel("c1", 100_000uL)), + listOf(channel("c1", 100_000uL), channel("c2", 400_000uL)), + ) + val sparkStates = listOf(0uL, 1uL, 999uL, 50_000uL, 1_000_000uL).flatMap { balance -> + listOf( + SparkState(isReady = true, balanceSats = balance), + SparkState(isReady = false, balanceSats = balance), + SparkState(isReady = true, isExiting = true, balanceSats = balance), + SparkState(isReady = false, isExiting = true, balanceSats = balance), + ) + } + for (spark in sparkStates) { + val amounts = listOf(0uL, 1uL, 500uL, 10_000uL, 100_000uL, 149_125uL, 2_000_000uL) + + listOf(spark.sendableSats, spark.sendableSats + 1uL, spark.balanceSats) + for (channels in channelSets) { + for (amount in amounts.filter { spark.canSend(it) }) { + assertTrue( + !MoveToSparkMath.needsUpdateToSend(amount, channels, spark), + "'$amount' sats need the update though Spark sends them alone: $spark, $channels", + ) + } + } + if (!spark.isReady) assertTrue(amounts.none { spark.canSend(it) }) + if (spark.isExiting) assertTrue(amounts.none { it > 0uL && spark.canSend(it) }) + } + } + @Test fun `max send counts the combined balance`() { val channels = listOf(channel("c1", 100_000uL)) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index acd4f4b710..ff4efe0898 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -22481,7 +22481,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val bolt11 = "lnbcrt1quickpaysparkshort" enableQuickPay() stubLightningScan(bolt11 = bolt11, amountSats = 500u) - whenever(lightningRepo.canSendWithSpark(499u)).thenReturn(true) + whenever(lightningRepo.canSendWithSpark(any())).thenAnswer { (it.arguments[0] as Long) <= 499L } val nodeState = MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Starting)) whenever(lightningRepo.lightningState).thenReturn(nodeState) var isQuickPaySetBeforeWait = false @@ -22499,6 +22499,25 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(QuickPayData.Bolt11(sats = 500u, bolt11 = bolt11), sut.quickPayData.value?.data) } + @Test + fun `an amountless scan while the node starts keeps the channel wait when Spark is ready with no balance`() = test { + val bolt11 = "lnbcrt1quickpayamountless" + // QuickPay never takes a zero amount. + enableQuickPay(canApply = false) + stubLightningScan(bolt11 = bolt11, amountSats = 0u) + whenever(lightningRepo.canSendWithSpark(0u)).thenReturn(true) + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Starting))) + + sut.onScanResult(bolt11) + advanceUntilIdle() + + // Once before the QuickPay decision and once before the send path reads what Lightning can send. + verify(lightningRepo, times(2)).waitForUsableChannels() + verify(lightningRepo, never()).waitForUsableChannels(awaitUsable = false) + assertNull(sut.quickPayData.value) + } + @Test fun `a scan with unusable channels uses QuickPay without waiting for them when Spark covers the amount`() = test { val bolt11 = "lnbcrt1quickpaysparkpeeroffline" From 8f47458aae3c7a79681637ca6f4ece0b9bb83f8d Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Wed, 25 Nov 2026 13:39:04 -0300 Subject: [PATCH 04/15] fix: hold a spark send through a node stop, start failure and wipe The held Spark send waits until the node runs and lists its payments, also while it stops with a start queued and across a start retry or stale-graph restart. It ends at once when the start fails, the node stops with no start coming, or the wallet was wiped meanwhile. Co-Authored-By: Claude Fable 5.2 --- .../to/bitkit/repositories/LightningRepo.kt | 98 ++++++--- .../bitkit/repositories/LightningRepoTest.kt | 203 +++++++++++++++++- 2 files changed, 269 insertions(+), 32 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 160045b408..77ef98562c 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -27,6 +27,7 @@ import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.first @@ -212,6 +213,12 @@ class LightningRepo @Inject constructor( private val pendingStopLock = Any() private val lifecycleMutex = Mutex() + /** Starts called and not returned yet, also while one waits for a stop to finish or between its retries. */ + private val pendingStartCount = MutableStateFlow(0) + + /** Counts [wipeStorage] calls, so a send that waited for the node can tell the wallet was wiped meanwhile. */ + private val wipeCount = AtomicLong(0) + /** * Serializes a whole server-change transaction (stop, start, persist) against the background * recovery a failed change launches. [lifecycleMutex] is taken separately by `stop()` and @@ -379,17 +386,28 @@ class LightningRepo @Inject constructor( eventHandler: NodeEventHandler? = null, channelMigration: ChannelDataMigration? = null, shouldValidateGraph: Boolean = true, - ): Result = startNode( - walletIndex = walletIndex, - timeout = timeout, - shouldRetry = shouldRetry, - customServerUrl = customServerUrl, - customRgsServerUrl = customRgsServerUrl, - eventHandler = eventHandler, - channelMigration = channelMigration, - shouldValidateGraph = shouldValidateGraph, - shouldRetryYieldToStop = false, - ) + ): Result = whileStartPending { + startNode( + walletIndex = walletIndex, + timeout = timeout, + shouldRetry = shouldRetry, + customServerUrl = customServerUrl, + customRgsServerUrl = customRgsServerUrl, + eventHandler = eventHandler, + channelMigration = channelMigration, + shouldValidateGraph = shouldValidateGraph, + shouldRetryYieldToStop = false, + ) + } + + private suspend fun whileStartPending(start: suspend () -> T): T { + pendingStartCount.update { it + 1 } + try { + return start() + } finally { + pendingStartCount.update { it - 1 } + } + } private suspend fun startNode( walletIndex: Int = 0, @@ -988,6 +1006,7 @@ class LightningRepo @Inject constructor( suspend fun wipeStorage(walletIndex: Int): Result = withContext(bgDispatcher) { Logger.debug("wipeStorage called, stopping node first", context = TAG) + wipeCount.incrementAndGet() lifecycleMutex.withLock { stopLocked().mapCatching { Logger.debug("node stopped, calling wipeStorage", context = TAG) @@ -1330,11 +1349,13 @@ class LightningRepo @Inject constructor( Logger.warn("Retrying recovery start '$attempt/$RECOVERY_START_ATTEMPTS'", context = TAG) } // A direct stop since recovery's own stop wins over every attempt. - result = startNode( - shouldRetry = false, - shouldCancelPendingStop = false, - stopRequestsSeen = stopRequests, - ) + result = whileStartPending { + startNode( + shouldRetry = false, + shouldCancelPendingStop = false, + stopRequestsSeen = stopRequests, + ) + } } while (result.exceptionOrNull().isKvStoreSetupFailure() && attempt < RECOVERY_START_ATTEMPTS) result.onSuccess { Logger.debug("Successfully started node with previous config", context = TAG) @@ -1618,6 +1639,7 @@ class LightningRepo @Inject constructor( if (shouldPayWithSpark(bolt11, sats)) { runCatching { requireWalletRestoreComplete() }.onFailure { return Result.failure(it) } val key = ldkSendKey(bolt11, paymentHash) + val wipesBefore = wipeCount.get() // Read before the checks, so a send of either rail recorded after them refuses this one at submission. val ldkRecordsBefore = ldkSendRecords.get() val sparkRecordsBefore = sparkRepo.sendRecordMark() @@ -1626,7 +1648,7 @@ class LightningRepo @Inject constructor( // Nothing is authorized or admitted yet, so the payment starts over once the node can list its // sends: the rail is picked again, and an earlier node send of the invoice is found. val canRetry = it is ServiceError.NodeNotStarted && !isRetryAfterNodeStart - if (!canRetry || !awaitNodeRunning()) return Result.failure(it) + if (!canRetry || !awaitNodeListing(wipesBefore)) return Result.failure(it) return payInvoiceChecked( bolt11 = bolt11, sats = sats, @@ -1697,14 +1719,33 @@ class LightningRepo @Inject constructor( ) } - private suspend fun awaitNodeRunning(): Boolean { - if (!_lightningState.value.nodeLifecycleState.canRun()) return false + /** + * Waits, up to [NODE_RUN_WAIT_TIMEOUT], until the node runs and lists its payments. A node stopping, or stopped + * with a start called, is waited for, also across a start's retry or its restart for a stale graph. The wait + * ends without it when the start fails, when the node is stopped with no start coming, or when the wallet was + * wiped since [wipesBefore], as the node that runs next can be another wallet's. + */ + private suspend fun awaitNodeListing(wipesBefore: Long): Boolean { + val isWiped = { isWiping || wipeCount.get() != wipesBefore } + val startStates = combine(_lightningState, pendingStartCount) { state, starts -> + state.nodeLifecycleState to starts + } + var isListing = false withTimeoutOrNull(NODE_RUN_WAIT_TIMEOUT) { - _lightningState.first { it.nodeLifecycleState.isRunning() } - } ?: return false + while (!isListing) { + val (lifecycle, _) = startStates.first { (lifecycle, starts) -> + val canStillRun = lifecycle.canRun() || lifecycle is NodeLifecycleState.Stopping || starts > 0 + lifecycle.isRunning() || lifecycle is NodeLifecycleState.ErrorStarting || isWiped() || !canStillRun + } + if (!lifecycle.isRunning() || isWiped()) return@withTimeoutOrNull + isListing = listPaymentsKeepingSendHashes() != null + if (!isListing) delay(NODE_LISTING_POLL_DELAY) + } + } + if (!isListing || isWiped()) return false // The node is marked running before its channels are published, and the rail is picked from them. refreshChannelsAndPeers() - return true + return !isWiped() } /** Pays [bolt11] from the node's channels only, for a send quoted on them that must never fall back to Spark. */ @@ -3381,11 +3422,13 @@ class LightningRepo @Inject constructor( Logger.error("Failed to stop node during restart", it, context = TAG) return@withContext Result.failure(it) } - startNode( - walletIndex = walletIndex, - channelMigration = channelMigration, - shouldRetryYieldToStop = true - ).onFailure { + whileStartPending { + startNode( + walletIndex = walletIndex, + channelMigration = channelMigration, + shouldRetryYieldToStop = true + ) + }.onFailure { if (it is NodeStartYieldedToStopError) { Logger.info("Deferred node restart to a requested stop", context = TAG) } else { @@ -3428,6 +3471,7 @@ class LightningRepo @Inject constructor( /** Max time an operation waits for a starting node to run. */ private val NODE_RUN_WAIT_TIMEOUT = 1.minutes + private val NODE_LISTING_POLL_DELAY = 500.milliseconds /** Max time to wait for a starting node before its id is treated as unavailable. */ private val NODE_ID_WAIT_TIMEOUT = 15.seconds diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 74f1070421..d58276263e 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -129,6 +129,7 @@ import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant import breez_sdk_spark.PaymentStatus as SparkPaymentStatus @@ -1458,20 +1459,201 @@ class LightningRepoTest : BaseUnitTest() { } @Test - fun `a held spark send is retried only once while the running node still can't list`() = test { + fun `a held spark send gives up after the bound while the running node still can't list`() = test { startNodeForTesting() whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) whenever(lightningService.listPayments()).thenReturn(null) whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) - clearInvocations(lightningService) - val retry = sut.payInvoice("bolt11", 1_000uL) + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + advanceTimeBy(59.seconds) + assertFalse(payment.isCompleted, "The send gave up while the node could still list its sends in time") + advanceTimeBy(2.seconds) - assertIs(retry.exceptionOrNull()) - verify(lightningService, times(2)).listPayments() + assertIs(payment.await().exceptionOrNull()) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `a held spark send waits for the listing when the node runs before it can list`() = test { + startNodeForTesting() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + advanceTimeBy(5.seconds) + assertFalse(payment.isCompleted, "The send used its retry before the node could list") + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + + assertEquals("hash", payment.await().getOrThrow()) + verify(sparkRepo, times(1)).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `a held spark send sends nothing when its caller is cancelled during the wait`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + var isAuthorizationAsked = false + + val payment = async { + sut.payInvoice("bolt11", 1_000uL, onBeforeSend = { + isAuthorizationAsked = true + true + }) + } + runCurrent() + assertFalse(payment.isCompleted) + payment.cancel() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + startNodeForTesting() + advanceTimeBy(2.minutes) + + assertTrue(payment.isCancelled) + assertFalse(isAuthorizationAsked) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + verify(lightningService, never()).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) + } + + @Test + fun `a held spark send fails promptly when the node start fails`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(lightningService.node).thenReturn(mock()) + whenever { lightningService.start(anyOrNull(), any()) }.doSuspendableAnswer { throw AppError("start failed") } + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + runCurrent() + assertFalse(payment.isCompleted) + assertTrue(sut.start(shouldRetry = false).isFailure) + runCurrent() + + assertTrue(payment.isCompleted, "The send kept waiting for a node whose start failed") + assertIs(payment.await().exceptionOrNull()) verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) } + @Test + fun `a held spark send sends nothing when the wallet is wiped during the wait`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + whenever(sparkRepo.wipe(0)).thenReturn(Result.success(Unit)) + whenever(lightningService.node).thenReturn(mock()) + withHeldStop { stopped -> + var isAuthorizationAsked = false + + val payment = async { + sut.payInvoice("bolt11", 1_000uL, onBeforeSend = { + isAuthorizationAsked = true + true + }) + } + runCurrent() + val wipe = launch { sut.wipeStorage(0) } + runCurrent() + // The next wallet's node starts behind the wipe, so the wait sees a start coming all along. + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + val start = launch { startNodeForTesting() } + runCurrent() + stopped.complete(Unit) + wipe.join() + start.join() + + assertIs(payment.await().exceptionOrNull()) + assertFalse(isAuthorizationAsked) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + } + + @Test + fun `a spark send held while the node stops is retried once the queued start runs`() = test { + startNodeForTesting() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + withHeldStop { stopped -> + val stop = launch { sut.stop() } + runCurrent() + assertEquals(NodeLifecycleState.Stopping, sut.lightningState.value.nodeLifecycleState) + whenever(lightningService.listPayments()).thenReturn(null) + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + runCurrent() + assertFalse(payment.isCompleted, "The send failed while the node was stopping") + val start = launch { sut.start() } + runCurrent() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + stopped.complete(Unit) + stop.join() + start.join() + + assertEquals("hash", payment.await().getOrThrow()) + verify(sparkRepo, times(1)).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + } + + @Test + fun `a spark send held while the node stops fails once it is stopped with no start coming`() = test { + startNodeForTesting() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + withHeldStop { stopped -> + val stop = launch { sut.stop() } + runCurrent() + whenever(lightningService.listPayments()).thenReturn(null) + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + runCurrent() + assertFalse(payment.isCompleted) + stopped.complete(Unit) + stop.join() + runCurrent() + + assertTrue(payment.isCompleted, "The send kept waiting for a node nothing starts") + assertIs(payment.await().exceptionOrNull()) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + } + + @Test + fun `the retry after the node starts returns the node's payment when it lists the invoice as paid`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + var isAuthorizationAsked = false + + val payment = async { + sut.payInvoice("bolt11", 1_000uL, onBeforeSend = { + isAuthorizationAsked = true + true + }) + } + runCurrent() + whenever(lightningService.listPayments()).thenReturn(listOf(nodeSend("bolt11", PaymentStatus.SUCCEEDED))) + startNodeForTesting() + + assertEquals("bolt11", payment.await().getOrThrow()) + assertFalse(isAuthorizationAsked) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + verify(lightningService, never()).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) + } + @Test fun `the retry after the node starts pays over the node when its channels cover the amount`() = test { sut.setInitNodeLifecycleState() @@ -1586,6 +1768,17 @@ class LightningRepoTest : BaseUnitTest() { assertEquals(listOf("paid"), store.data.first().ldkSendHashes) } + /** Holds the node's stop until [block] releases it or ends, as a stop left held would hang a failed test. */ + private suspend fun withHeldStop(block: suspend (CompletableDeferred) -> Unit) { + val stopped = CompletableDeferred() + whenever(lightningService.stop()).doSuspendableAnswer { stopped.await() } + try { + block(stopped) + } finally { + stopped.complete(Unit) + } + } + private suspend fun restoredCacheWithInvoiceAt(createdAt: Long) { val cache = AppCacheData(ldkSendHashesSeeded = true, ldkHistoryUnseededSince = restoredAt) whenever(cacheStore.data).thenReturn(flowOf(cache)) From 285f07877ec7f04e1b25bee7aaf13f890777fe23 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Wed, 25 Nov 2026 14:42:13 -0300 Subject: [PATCH 05/15] fix: keep a held spark send from throwing and from ending early A listing that fails during the hold is asked again, so the send returns its failure. The wait reads the start count and the node state when woken instead of as a pair, counts a restart from its stop, no longer ends on a failed start while another start is pending, and ends when a wipe begins. Co-Authored-By: Claude Fable 5.2 --- .../to/bitkit/repositories/LightningRepo.kt | 128 +++++++++--------- .../bitkit/repositories/LightningRepoTest.kt | 100 +++++++++++++- 2 files changed, 166 insertions(+), 62 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 77ef98562c..5bb2addb34 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -400,7 +400,7 @@ class LightningRepo @Inject constructor( ) } - private suspend fun whileStartPending(start: suspend () -> T): T { + private inline fun whileStartPending(start: () -> T): T { pendingStartCount.update { it + 1 } try { return start() @@ -1040,17 +1040,19 @@ class LightningRepo @Inject constructor( waitForNodeToStop().onFailure { return@withContext Result.failure(it) } recoverOnCancellation { - stop().onFailure { - Logger.error("Failed to stop node during electrum server change", it, context = TAG) - return@withContext Result.failure(it) - } + whileStartPending { + stop().onFailure { + Logger.error("Failed to stop node during electrum server change", it, context = TAG) + return@withContext Result.failure(it) + } - Logger.debug("Starting node with new electrum server: '$newServerUrl'", context = TAG) + Logger.debug("Starting node with new electrum server: '$newServerUrl'", context = TAG) - start( - shouldRetry = false, - customServerUrl = newServerUrl, - ) + start( + shouldRetry = false, + customServerUrl = newServerUrl, + ) + } }.onFailure { // Recover in the background: a wedged node's release can gate the rebuild for tens of // seconds, and the caller must surface this failure now rather than block on recovery. @@ -1327,40 +1329,40 @@ class LightningRepo @Inject constructor( configChangeMutex.withLock { Logger.debug("Stopping node for recovery attempt", context = TAG) - stop().onFailure { e -> - Logger.error("Failed to stop node during recovery", e, context = TAG) - return@withContext Result.failure(e) - } - - Logger.debug("Starting node with previous config for recovery", context = TAG) - val stopRequests = stopRequestCount.get() - - var result: Result - var attempt = 0 - // The stopped node's VSS writes can keep retrying for minutes, past one build's wait for them. - do { - // A stop requested since the app went to the background wins over recovery. - if (pendingStopJob.get() != null) { - Logger.info("Skipped recovery start because a stop was requested", context = TAG) - return@withContext Result.failure(NodeStartYieldedToStopError(null)) - } - attempt++ - if (attempt > 1) { - Logger.warn("Retrying recovery start '$attempt/$RECOVERY_START_ATTEMPTS'", context = TAG) + whileStartPending { + stop().onFailure { e -> + Logger.error("Failed to stop node during recovery", e, context = TAG) + return@withContext Result.failure(e) } - // A direct stop since recovery's own stop wins over every attempt. - result = whileStartPending { - startNode( + + Logger.debug("Starting node with previous config for recovery", context = TAG) + val stopRequests = stopRequestCount.get() + + var result: Result + var attempt = 0 + // The stopped node's VSS writes can keep retrying for minutes, past one build's wait for them. + do { + // A stop requested since the app went to the background wins over recovery. + if (pendingStopJob.get() != null) { + Logger.info("Skipped recovery start because a stop was requested", context = TAG) + return@withContext Result.failure(NodeStartYieldedToStopError(null)) + } + attempt++ + if (attempt > 1) { + Logger.warn("Retrying recovery start '$attempt/$RECOVERY_START_ATTEMPTS'", context = TAG) + } + // A direct stop since recovery's own stop wins over every attempt. + result = startNode( shouldRetry = false, shouldCancelPendingStop = false, stopRequestsSeen = stopRequests, ) + } while (result.exceptionOrNull().isKvStoreSetupFailure() && attempt < RECOVERY_START_ATTEMPTS) + result.onSuccess { + Logger.debug("Successfully started node with previous config", context = TAG) + }.onFailure { + Logger.error("Failed starting node with previous config", it, context = TAG) } - } while (result.exceptionOrNull().isKvStoreSetupFailure() && attempt < RECOVERY_START_ATTEMPTS) - result.onSuccess { - Logger.debug("Successfully started node with previous config", context = TAG) - }.onFailure { - Logger.error("Failed starting node with previous config", it, context = TAG) } } } @@ -1722,23 +1724,27 @@ class LightningRepo @Inject constructor( /** * Waits, up to [NODE_RUN_WAIT_TIMEOUT], until the node runs and lists its payments. A node stopping, or stopped * with a start called, is waited for, also across a start's retry or its restart for a stale graph. The wait - * ends without it when the start fails, when the node is stopped with no start coming, or when the wallet was - * wiped since [wipesBefore], as the node that runs next can be another wallet's. + * ends without it when the node cannot run and no start is left pending, as after a failed start, or when the + * wallet was wiped since [wipesBefore], as the node that runs next can be another wallet's. */ private suspend fun awaitNodeListing(wipesBefore: Long): Boolean { val isWiped = { isWiping || wipeCount.get() != wipesBefore } - val startStates = combine(_lightningState, pendingStartCount) { state, starts -> - state.nodeLifecycleState to starts - } + // The two flows only wake the wait. What it decides on is read then, the count before the state: read as a + // pair they can show a failed start beside a count another start has left since, which never was the case. + val changes = combine(_lightningState, pendingStartCount) { _, _ -> } + val isRunning = { _lightningState.value.nodeLifecycleState.isRunning() } var isListing = false withTimeoutOrNull(NODE_RUN_WAIT_TIMEOUT) { while (!isListing) { - val (lifecycle, _) = startStates.first { (lifecycle, starts) -> + changes.first { + val starts = pendingStartCount.value + val lifecycle = _lightningState.value.nodeLifecycleState val canStillRun = lifecycle.canRun() || lifecycle is NodeLifecycleState.Stopping || starts > 0 - lifecycle.isRunning() || lifecycle is NodeLifecycleState.ErrorStarting || isWiped() || !canStillRun + lifecycle.isRunning() || isWiped() || !canStillRun } - if (!lifecycle.isRunning() || isWiped()) return@withTimeoutOrNull - isListing = listPaymentsKeepingSendHashes() != null + if (!isRunning() || isWiped()) return@withTimeoutOrNull + // A listing that fails is asked again, so the wait ends with the hold's own error, never a throw. + isListing = runSuspendCatching { listPaymentsKeepingSendHashes() }.getOrNull() != null if (!isListing) delay(NODE_LISTING_POLL_DELAY) } } @@ -3417,26 +3423,26 @@ class LightningRepo @Inject constructor( channelMigration: ChannelDataMigration? = null, walletIndex: Int = 0, ): Result = withContext(bgDispatcher) { - Logger.info("Restarting node", context = TAG) - stop().onFailure { - Logger.error("Failed to stop node during restart", it, context = TAG) - return@withContext Result.failure(it) - } whileStartPending { + Logger.info("Restarting node", context = TAG) + stop().onFailure { + Logger.error("Failed to stop node during restart", it, context = TAG) + return@withContext Result.failure(it) + } startNode( walletIndex = walletIndex, channelMigration = channelMigration, shouldRetryYieldToStop = true - ) - }.onFailure { - if (it is NodeStartYieldedToStopError) { - Logger.info("Deferred node restart to a requested stop", context = TAG) - } else { - Logger.error("Failed to start node during restart", it, context = TAG) + ).onFailure { + if (it is NodeStartYieldedToStopError) { + Logger.info("Deferred node restart to a requested stop", context = TAG) + } else { + Logger.error("Failed to start node during restart", it, context = TAG) + } + return@withContext Result.failure(it) + }.onSuccess { + Logger.info("Node restarted successfully", context = TAG) } - return@withContext Result.failure(it) - }.onSuccess { - Logger.info("Node restarted successfully", context = TAG) } } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index d58276263e..354296e13e 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1459,7 +1459,8 @@ class LightningRepoTest : BaseUnitTest() { } @Test - fun `a held spark send gives up after the bound while the running node still can't list`() = test { + // Reachable only while a running node is being reset: the stale-graph restart and the recovery screen's reset. + fun `a held spark send fails with the hold after the bound when a running node never lists`() = test { startNodeForTesting() whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) whenever(lightningService.listPayments()).thenReturn(null) @@ -1474,6 +1475,103 @@ class LightningRepoTest : BaseUnitTest() { verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) } + @Test + fun `a listing that fails during the hold returns the hold's failure instead of throwing`() = test { + startNodeForTesting() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + var listings = 0 + whenever(lightningService.listPayments()).doSuspendableAnswer { + if (listings++ == 0) null else throw AppError("listing failed") + } + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + + val payment = runCatching { sut.payInvoice("bolt11", 1_000uL) } + + assertTrue(payment.isSuccess, "The send threw instead of returning its failure") + assertIs(payment.getOrThrow().exceptionOrNull()) + assertTrue(listings > 1) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `a held spark send keeps waiting through a failed start when another start is queued`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + whenever(lightningService.node).thenReturn(mock()) + whenever(lightningService.sync()).thenReturn(Unit) + val blocktank = mock() + whenever(coreService.blocktank).thenReturn(blocktank) + whenever(blocktank.info(any())).thenReturn(null) + val failed = CompletableDeferred() + var starts = 0 + whenever { lightningService.start(anyOrNull(), any()) }.doSuspendableAnswer { + if (starts++ == 0) { + failed.await() + throw AppError("start failed") + } + } + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + runCurrent() + val failingStart = async { sut.start(shouldRetry = false) } + runCurrent() + val queuedStart = async { sut.start(shouldRetry = false) } + runCurrent() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + failed.complete(Unit) + + assertTrue(failingStart.await().isFailure) + assertTrue(queuedStart.await().isSuccess) + assertEquals("hash", payment.await().getOrThrow()) + } + + @Test + fun `a held spark send ends when a wipe begins, before any storage is wiped`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + runCurrent() + sut.setWiping(true) + assertTrue(sut.start().isFailure) + runCurrent() + + assertTrue(payment.isCompleted, "The send kept waiting through a wipe") + assertIs(payment.await().exceptionOrNull()) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `a spark send held while a restart stops the node is retried once the restart runs it`() = test { + startNodeForTesting() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + withHeldStop { stopped -> + val restart = async { sut.restartNode() } + runCurrent() + whenever(lightningService.listPayments()).thenReturn(null) + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + runCurrent() + assertFalse(payment.isCompleted) + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + stopped.complete(Unit) + + assertTrue(restart.await().isSuccess) + assertEquals("hash", payment.await().getOrThrow()) + } + } + @Test fun `a held spark send waits for the listing when the node runs before it can list`() = test { startNodeForTesting() From bb59960e3acad1d14192b7cc3569fb9e07202d58 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Wed, 25 Nov 2026 14:56:47 -0300 Subject: [PATCH 06/15] chore: move a test comment above its annotation Co-Authored-By: Claude Fable 5.2 --- app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 354296e13e..ff155a44d6 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1458,8 +1458,8 @@ class LightningRepoTest : BaseUnitTest() { verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) } - @Test // Reachable only while a running node is being reset: the stale-graph restart and the recovery screen's reset. + @Test fun `a held spark send fails with the hold after the bound when a running node never lists`() = test { startNodeForTesting() whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) From 229581d1d7fa27b0cae8c4f6f01015831b9112b6 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Wed, 25 Nov 2026 15:11:59 -0300 Subject: [PATCH 07/15] fix: keep the spark hold through a node that stops again The wait decides on the state that woke it, so a node that left Running since is waited for again instead of ending the hold. An RGS server change counts its start from its stop, like the Electrum one. Co-Authored-By: Claude Fable 5.2 --- .../to/bitkit/repositories/LightningRepo.kt | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 5bb2addb34..fb58978941 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1082,17 +1082,19 @@ class LightningRepo @Inject constructor( waitForNodeToStop().onFailure { return@withContext Result.failure(it) } recoverOnCancellation { - stop().onFailure { - Logger.error("Failed to stop node during RGS server change", it, context = TAG) - return@withContext Result.failure(it) - } + whileStartPending { + stop().onFailure { + Logger.error("Failed to stop node during RGS server change", it, context = TAG) + return@withContext Result.failure(it) + } - Logger.debug("Starting node with new RGS server: '$newRgsUrl'", context = TAG) + Logger.debug("Starting node with new RGS server: '$newRgsUrl'", context = TAG) - start( - shouldRetry = false, - customRgsServerUrl = newRgsUrl, - ) + start( + shouldRetry = false, + customRgsServerUrl = newRgsUrl, + ) + } }.onFailure { // Recover in the background: a wedged node's release can gate the rebuild for tens of // seconds, and the caller must surface this failure now rather than block on recovery. @@ -1732,17 +1734,19 @@ class LightningRepo @Inject constructor( // The two flows only wake the wait. What it decides on is read then, the count before the state: read as a // pair they can show a failed start beside a count another start has left since, which never was the case. val changes = combine(_lightningState, pendingStartCount) { _, _ -> } - val isRunning = { _lightningState.value.nodeLifecycleState.isRunning() } var isListing = false withTimeoutOrNull(NODE_RUN_WAIT_TIMEOUT) { while (!isListing) { + var wasRunning = false changes.first { val starts = pendingStartCount.value val lifecycle = _lightningState.value.nodeLifecycleState val canStillRun = lifecycle.canRun() || lifecycle is NodeLifecycleState.Stopping || starts > 0 - lifecycle.isRunning() || isWiped() || !canStillRun + wasRunning = lifecycle.isRunning() + wasRunning || isWiped() || !canStillRun } - if (!isRunning() || isWiped()) return@withTimeoutOrNull + // Decided on what woke the wait: a node that stopped again since is asked for its listing and waited. + if (!wasRunning || isWiped()) return@withTimeoutOrNull // A listing that fails is asked again, so the wait ends with the hold's own error, never a throw. isListing = runSuspendCatching { listPaymentsKeepingSendHashes() }.getOrNull() != null if (!isListing) delay(NODE_LISTING_POLL_DELAY) From 6015762350ea7c642f3c1111843f45834cdc531e Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 26 Nov 2026 14:14:25 -0300 Subject: [PATCH 08/15] fix: report quickpay already paid when the send skips dispatch Co-Authored-By: Claude Opus 5.5 --- .../to/bitkit/repositories/QuickPayRepo.kt | 12 +++++++++-- .../bitkit/repositories/QuickPayRepoTest.kt | 20 +++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index e6ff629b86..79640c33c2 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -438,7 +438,7 @@ class QuickPayRepo @Inject constructor( isAuthorizationLapsed = !canDispatch() !isAuthorizationLapsed && tryMarkDispatched(invoiceHash) }.fold( - onSuccess = { onInvoiceAccepted(invoiceHash, it) }, + onSuccess = { onInvoiceAccepted(invoiceHash, invoice.bolt11, it) }, onFailure = { when { isAuthorizationLapsed -> fallBackBeforeDispatch(invoiceHash) @@ -487,8 +487,16 @@ class QuickPayRepo @Inject constructor( return null } - private suspend fun onInvoiceAccepted(invoiceHash: String, paymentId: String) { + private suspend fun onInvoiceAccepted(invoiceHash: String, paymentRequest: String, paymentId: String) { mutex.withLock { + val undispatched = opsByKey[invoiceHash]?.takeIf { !it.dispatched } + if (undispatched != null) { + // Accepted without a dispatch, so an earlier send of the invoice paid it and nothing new went out. + spend.release(invoiceHash) + emitErrorLocked(undispatched, QuickPayAlreadyPaidError(), paymentRequest) + removeOpLocked(undispatched) + return@withLock + } spend.markSubmitted(invoiceHash, paymentId) val current = opsByKey[invoiceHash] ?: return@withLock current.paymentId = paymentId diff --git a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt index af3c71bde8..b0287c7f6d 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -876,6 +876,26 @@ class QuickPayRepoTest : BaseUnitTest() { assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) } + @Test + fun `already paid return without a dispatch refunds a fresh reserve and emits already paid`() = test { + val (bolt11, hash) = testInvoice() + // An earlier send of the invoice paid it: success without authorizing, dispatching or a new payment event. + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { Result.success(hash) } + val session = QuickPaySession() + + sut.attach(session).test { + sut.payNow(session, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u)) + val error = assertIs(awaitItem()) + assertIs(error.error) + assertEquals(bolt11, error.paymentRequest) + } + assertEquals(0L, spentCents()) + assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) + verify(pendingPaymentRepo, never()).track(any()) + } + @Test fun `re-pay of a settled hash does not double-count`() = test { val (bolt11, hash) = testInvoice() From a0045ff8ac4d19d7de5329de8dbbd582a9bb8710 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 27 Nov 2026 06:24:08 -0300 Subject: [PATCH 09/15] fix: show quickpay pending for an earlier send still in flight Co-Authored-By: Claude Opus 5.5 --- .../to/bitkit/repositories/QuickPayRepo.kt | 3 ++- .../bitkit/repositories/QuickPayRepoTest.kt | 21 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index 79640c33c2..32ef4bb866 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -612,7 +612,8 @@ class QuickPayRepo @Inject constructor( val op = opsByKey[invoiceHash] if (!duplicate && op != null && !op.dispatched) { spend.release(invoiceHash) - emitErrorLocked(op, error, paymentRequest) + // Refused for an earlier send of the invoice still in flight, which QuickPay didn't make: it is tracked. + if (error is PaymentPendingException) emitPendingLocked(op) else emitErrorLocked(op, error, paymentRequest) removeOpLocked(op) return } diff --git a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt index b0287c7f6d..0b83dcd82d 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -896,6 +896,27 @@ class QuickPayRepoTest : BaseUnitTest() { verify(pendingPaymentRepo, never()).track(any()) } + @Test + fun `pending return without a dispatch refunds a fresh reserve and emits pending`() = test { + val (bolt11, hash) = testInvoice() + // An earlier send of the invoice is still in flight: refused without authorizing or dispatching. + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { Result.failure(PaymentPendingException(hash)) } + val session = QuickPaySession() + + sut.attach(session).test { + sut.payNow(session, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u)) + val pending = assertIs(awaitItem()) + assertEquals(hash, pending.paymentHash) + assertEquals(bolt11, pending.paymentRequest) + } + assertEquals(0L, spentCents()) + assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) + verify(pendingPaymentRepo).track(hash) + assertFalse(sut.hasOpen(hash)) + } + @Test fun `re-pay of a settled hash does not double-count`() = test { val (bolt11, hash) = testInvoice() From a7ed600f2000331aba60921a255e6276dd8f8034 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 27 Nov 2026 06:51:31 -0300 Subject: [PATCH 10/15] fix: settle a quickpay earlier send from its rows before pending Co-Authored-By: Claude Opus 5.5 --- .../to/bitkit/repositories/QuickPayRepo.kt | 56 +++++++++++++++--- .../bitkit/repositories/QuickPayRepoTest.kt | 57 +++++++++++++++++-- 2 files changed, 102 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index 32ef4bb866..11d091d262 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -589,7 +589,7 @@ class QuickPayRepo @Inject constructor( QuickPayDispatchClass.AMBIGUOUS, -> { val rows = loadPaymentRows() - mutex.withLock { + val isEarlierSendTracked = mutex.withLock { settleAmbiguousLocked( invoiceHash = invoiceHash, paymentRequest = paymentRequest, @@ -598,24 +598,40 @@ class QuickPayRepo @Inject constructor( duplicate = kind == QuickPayDispatchClass.DUPLICATE_PAYMENT, ) } + if (isEarlierSendTracked) resolveSettledEarlierSend(invoiceHash) } } } + /** Settles a dispatch error, true when it tracked an earlier send of the invoice that QuickPay didn't make. */ private suspend fun settleAmbiguousLocked( invoiceHash: String, paymentRequest: String, error: Throwable, rows: List?, duplicate: Boolean, - ) { + ): Boolean { val op = opsByKey[invoiceHash] if (!duplicate && op != null && !op.dispatched) { spend.release(invoiceHash) - // Refused for an earlier send of the invoice still in flight, which QuickPay didn't make: it is tracked. - if (error is PaymentPendingException) emitPendingLocked(op) else emitErrorLocked(op, error, paymentRequest) removeOpLocked(op) - return + if (error !is PaymentPendingException) { + emitErrorLocked(op, error, paymentRequest) + return false + } + // Refused for an earlier send of the invoice, which may have ended since it was refused. + when (rows?.let { earlierSendStatus(invoiceHash, it) }) { + QuickPayReconcileRow.Status.SUCCEEDED -> emitErrorLocked(op, QuickPayAlreadyPaidError(), paymentRequest) + // Nothing of the invoice is live, so the payer reviews a new send of it. + QuickPayReconcileRow.Status.FAILED -> { + emitToSession(op.sessionId, QuickPaySessionEvent.FallBackToConfirm) + } + QuickPayReconcileRow.Status.PENDING, null -> { + emitPendingLocked(op) + return true + } + } + return false } val record = spend.matching(invoiceHash) val applied = if (record != null && rows != null) { @@ -627,9 +643,9 @@ class QuickPayRepo @Inject constructor( if (remaining != null) { op?.dispatched = true op?.let { emitPendingLocked(it) } - return + return false } - if (op == null) return + if (op == null) return false when (applied) { AmbiguousApply.SUCCEEDED -> emitSuccessLocked(op, feePaidMsat = null) AmbiguousApply.ALREADY_PAID -> emitErrorLocked(op, QuickPayAlreadyPaidError(), paymentRequest) @@ -638,6 +654,32 @@ class QuickPayRepo @Inject constructor( -> emitErrorLocked(op, error, paymentRequest) } removeOpLocked(op) + return false + } + + /** + * Resolves the tracked earlier send of [invoiceHash] when its rows show it ended, as its event may have been + * handled before it was tracked, which no later event resolves. + */ + private suspend fun resolveSettledEarlierSend(invoiceHash: String) { + val rows = loadPaymentRows() ?: return + val resolution = when (earlierSendStatus(invoiceHash, rows)) { + QuickPayReconcileRow.Status.SUCCEEDED -> PendingPaymentResolution.Success(invoiceHash) + QuickPayReconcileRow.Status.FAILED -> PendingPaymentResolution.Failure(invoiceHash) + QuickPayReconcileRow.Status.PENDING, null -> return + } + if (pendingPaymentRepo.isPending(invoiceHash)) pendingPaymentRepo.resolve(resolution) + } + + /** An earlier send's status from its rows on either rail: paid by any, else live while any is, else failed. */ + private fun earlierSendStatus(invoiceHash: String, rows: List): QuickPayReconcileRow.Status? { + val sends = rows.filter { it.isOutboundBolt11 && it.invoicePaymentHash.equals(invoiceHash, ignoreCase = true) } + return when { + sends.isEmpty() -> null + sends.any { it.status == QuickPayReconcileRow.Status.SUCCEEDED } -> QuickPayReconcileRow.Status.SUCCEEDED + sends.any { it.status == QuickPayReconcileRow.Status.PENDING } -> QuickPayReconcileRow.Status.PENDING + else -> QuickPayReconcileRow.Status.FAILED + } } private suspend fun detachSession(sessionId: String) { diff --git a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt index 0b83dcd82d..a9c572d03a 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -917,6 +917,52 @@ class QuickPayRepoTest : BaseUnitTest() { assertFalse(sut.hasOpen(hash)) } + @Test + fun `pending return for an earlier send that failed since falls back to confirm`() = test { + val (bolt11, hash) = testInvoice() + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { Result.failure(PaymentPendingException(hash)) } + paymentRows = listOf(failedRow(hash)) + val session = QuickPaySession() + + sut.attach(session).test { + sut.payNow(session, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u)) + assertEquals(QuickPaySessionEvent.FallBackToConfirm, awaitItem()) + } + assertEquals(0L, spentCents()) + assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) + verify(pendingPaymentRepo, never()).track(any()) + assertFalse(sut.hasOpen(hash)) + } + + @Test + fun `pending return for an earlier send resolved before it was tracked resolves it again`() = test { + val (bolt11, hash) = testInvoice() + val pendingPayments = PendingPaymentRepo() + // The earlier send's screen tracked it, and its success resolved it before QuickPay tracked it. + pendingPayments.track(hash) + pendingPayments.resolve(PendingPaymentResolution.Success(hash)) + var rowLoads = 0 + val lookup = QuickPayPaymentLookup { + // Read at the refusal, before the row showed the success, then after it. + if (rowLoads++ == 0) listOf(pendingRow(hash)) else listOf(succeededRow(hash)) + } + sut = repo(pendingPaymentRepo = pendingPayments, paymentLookup = lookup) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { Result.failure(PaymentPendingException(hash)) } + val session = QuickPaySession() + + sut.attach(session).test { + sut.payNow(session, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u)) + assertIs(awaitItem()) + } + assertFalse(pendingPayments.isPending(hash)) + assertIs(pendingPayments.consumeResolution(hash)) + assertEquals(0L, spentCents()) + } + @Test fun `re-pay of a settled hash does not double-count`() = test { val (bolt11, hash) = testInvoice() @@ -1772,7 +1818,12 @@ class QuickPayRepoTest : BaseUnitTest() { quickPayDailyLimitMultiplier = 5, ) - private fun repo(): QuickPayRepo { + private fun repo( + pendingPaymentRepo: PendingPaymentRepo = this.pendingPaymentRepo, + paymentLookup: QuickPayPaymentLookup = QuickPayPaymentLookup { + paymentRows ?: lightningRepo.listPaymentsOrNull()?.map { QuickPayReconcileRow(it) } + }, + ): QuickPayRepo { return QuickPayRepo( cacheStore = cacheStore, settingsStore = settingsStore, @@ -1782,9 +1833,7 @@ class QuickPayRepoTest : BaseUnitTest() { invoiceParser = QuickPayInvoiceParser { bolt11 -> bolt11.takeIf { it == TEST_BOLT11 }?.let { TEST_HASH } }, - paymentLookup = QuickPayPaymentLookup { - paymentRows ?: lightningRepo.listPaymentsOrNull()?.map { QuickPayReconcileRow(it) } - }, + paymentLookup = paymentLookup, ioDispatcher = testDispatcher, clock = clock, ) From 0ba85013e4698e0d3f00393edde656c4d76a8a8c Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 27 Nov 2026 07:08:27 -0300 Subject: [PATCH 11/15] fix: keep a quickpay earlier send pending unless its rail settled it Co-Authored-By: Claude Opus 5.5 --- .../to/bitkit/repositories/QuickPayRepo.kt | 47 ++++++++----------- .../bitkit/repositories/QuickPayRepoTest.kt | 20 ++++---- 2 files changed, 31 insertions(+), 36 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index 11d091d262..b76f6ab61f 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -25,6 +25,7 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull +import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.NodeException import org.lightningdevkit.ldknode.PaymentDetails import org.lightningdevkit.ldknode.PaymentDirection @@ -619,19 +620,14 @@ class QuickPayRepo @Inject constructor( emitErrorLocked(op, error, paymentRequest) return false } - // Refused for an earlier send of the invoice, which may have ended since it was refused. - when (rows?.let { earlierSendStatus(invoiceHash, it) }) { - QuickPayReconcileRow.Status.SUCCEEDED -> emitErrorLocked(op, QuickPayAlreadyPaidError(), paymentRequest) - // Nothing of the invoice is live, so the payer reviews a new send of it. - QuickPayReconcileRow.Status.FAILED -> { - emitToSession(op.sessionId, QuickPaySessionEvent.FallBackToConfirm) - } - QuickPayReconcileRow.Status.PENDING, null -> { - emitPendingLocked(op) - return true - } + // Refused for an earlier send of the invoice, which may have been paid since. A failed row proves nothing, + // as the refusal can be for a retry of it still in flight, so anything else is tracked as pending. + if (rows != null && isEarlierSendPaid(invoiceHash, rows)) { + emitErrorLocked(op, QuickPayAlreadyPaidError(), paymentRequest) + return false } - return false + emitPendingLocked(op) + return true } val record = spend.matching(invoiceHash) val applied = if (record != null && rows != null) { @@ -658,28 +654,25 @@ class QuickPayRepo @Inject constructor( } /** - * Resolves the tracked earlier send of [invoiceHash] when its rows show it ended, as its event may have been + * Resolves the tracked earlier send of [invoiceHash] when its rail shows it settled, as its event may have been * handled before it was tracked, which no later event resolves. */ private suspend fun resolveSettledEarlierSend(invoiceHash: String) { - val rows = loadPaymentRows() ?: return - val resolution = when (earlierSendStatus(invoiceHash, rows)) { - QuickPayReconcileRow.Status.SUCCEEDED -> PendingPaymentResolution.Success(invoiceHash) - QuickPayReconcileRow.Status.FAILED -> PendingPaymentResolution.Failure(invoiceHash) - QuickPayReconcileRow.Status.PENDING, null -> return + // Settled only when confirmed: a node send once it succeeded, a Spark send once no attempt of it is live. + val event = runSuspendCatching { lightningRepo.settledSparkSendEvent(invoiceHash) }.getOrNull() + val resolution = when (event) { + is Event.PaymentSuccessful if event.paymentHash == invoiceHash -> + PendingPaymentResolution.Success(invoiceHash) + is Event.PaymentFailed if event.paymentHash == invoiceHash -> + PendingPaymentResolution.Failure(invoiceHash, event.reason) + else -> return } if (pendingPaymentRepo.isPending(invoiceHash)) pendingPaymentRepo.resolve(resolution) } - /** An earlier send's status from its rows on either rail: paid by any, else live while any is, else failed. */ - private fun earlierSendStatus(invoiceHash: String, rows: List): QuickPayReconcileRow.Status? { - val sends = rows.filter { it.isOutboundBolt11 && it.invoicePaymentHash.equals(invoiceHash, ignoreCase = true) } - return when { - sends.isEmpty() -> null - sends.any { it.status == QuickPayReconcileRow.Status.SUCCEEDED } -> QuickPayReconcileRow.Status.SUCCEEDED - sends.any { it.status == QuickPayReconcileRow.Status.PENDING } -> QuickPayReconcileRow.Status.PENDING - else -> QuickPayReconcileRow.Status.FAILED - } + private fun isEarlierSendPaid(invoiceHash: String, rows: List): Boolean = rows.any { + it.isOutboundBolt11 && it.status == QuickPayReconcileRow.Status.SUCCEEDED && + it.invoicePaymentHash.equals(invoiceHash, ignoreCase = true) } private suspend fun detachSession(sessionId: String) { diff --git a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt index a9c572d03a..5d1071aa6d 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -20,6 +20,7 @@ import kotlinx.coroutines.yield import org.junit.Before import org.junit.Test import org.junit.runner.RunWith +import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.NodeException import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull @@ -918,21 +919,24 @@ class QuickPayRepoTest : BaseUnitTest() { } @Test - fun `pending return for an earlier send that failed since falls back to confirm`() = test { + fun `pending return with a failed row and a live retry tracks pending`() = test { val (bolt11, hash) = testInvoice() + // Refused for a retry of the invoice in flight, whose earlier attempt is listed failed. whenever { lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) }.doSuspendableAnswer { Result.failure(PaymentPendingException(hash)) } + whenever { lightningRepo.settledSparkSendEvent(hash) }.thenReturn(null) paymentRows = listOf(failedRow(hash)) val session = QuickPaySession() sut.attach(session).test { sut.payNow(session, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u)) - assertEquals(QuickPaySessionEvent.FallBackToConfirm, awaitItem()) + assertIs(awaitItem()) } assertEquals(0L, spentCents()) assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) - verify(pendingPaymentRepo, never()).track(any()) + verify(pendingPaymentRepo).track(hash) + verify(pendingPaymentRepo, never()).resolve(any()) assertFalse(sut.hasOpen(hash)) } @@ -943,15 +947,13 @@ class QuickPayRepoTest : BaseUnitTest() { // The earlier send's screen tracked it, and its success resolved it before QuickPay tracked it. pendingPayments.track(hash) pendingPayments.resolve(PendingPaymentResolution.Success(hash)) - var rowLoads = 0 - val lookup = QuickPayPaymentLookup { - // Read at the refusal, before the row showed the success, then after it. - if (rowLoads++ == 0) listOf(pendingRow(hash)) else listOf(succeededRow(hash)) - } - sut = repo(pendingPaymentRepo = pendingPayments, paymentLookup = lookup) + // Read at the refusal, before the row showed the success. + sut = repo(pendingPaymentRepo = pendingPayments, paymentLookup = { listOf(pendingRow(hash)) }) whenever { lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) }.doSuspendableAnswer { Result.failure(PaymentPendingException(hash)) } + whenever { lightningRepo.settledSparkSendEvent(hash) } + .thenReturn(Event.PaymentSuccessful("pid", hash, null, null)) val session = QuickPaySession() sut.attach(session).test { From 3128ffad8a842ac0735a1145a88d02cd1b4e0aa1 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 27 Nov 2026 07:45:35 -0300 Subject: [PATCH 12/15] fix: refund an undispatched quickpay reserve on an earlier success Co-Authored-By: Claude Opus 5.5 --- .../to/bitkit/repositories/QuickPayRepo.kt | 7 ++ .../bitkit/repositories/QuickPayRepoTest.kt | 68 +++++++++++++++++++ 2 files changed, 75 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index b76f6ab61f..15de88fe04 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -712,6 +712,13 @@ class QuickPayRepo @Inject constructor( if (!success && !isAttributedFailure(record, op, paymentId, paymentHash)) { return QuickPayCompletionOutcome.None } + if (success && op != null && !op.dispatched) { + // QuickPay sent nothing yet, so the success is an earlier send's: the invoice is paid, and not by QuickPay. + spend.release(record.invoicePaymentHash) + emitErrorLocked(op, QuickPayAlreadyPaidError(), op.paymentRequest) + removeOpLocked(op) + return QuickPayCompletionOutcome.None + } spend.settle(keys, success) diff --git a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt index 5d1071aa6d..903d214069 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -965,6 +965,74 @@ class QuickPayRepoTest : BaseUnitTest() { assertEquals(0L, spentCents()) } + @Test + fun `earlier send success during the lookup refunds an undispatched reserve`() = test { + val (bolt11, hash) = testInvoice() + var isDelivered = false + sut = repo( + paymentLookup = { + // The earlier manual send's success arrives while the refusal's rows are read. + if (!isDelivered) { + isDelivered = true + sut.signalCompletion(paymentId = hash, paymentHash = hash, success = true) + } + listOf(succeededRow(hash)) + }, + ) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { Result.failure(PaymentPendingException(hash)) } + val session = QuickPaySession() + + sut.attach(session).test { + sut.payNow(session, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u)) + val error = assertIs(awaitItem()) + assertIs(error.error) + expectNoEvents() + } + assertTrue(isDelivered) + assertEquals(0L, spentCents()) + assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) + verify(pendingPaymentRepo, never()).track(any()) + } + + @Test + fun `success event before dispatch refunds the reserve and stops the send`() = test { + val (bolt11, hash) = testInvoice() + val started = CompletableDeferred() + val proceed = CompletableDeferred() + var isAuthorized: Boolean? = null + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) + started.complete(Unit) + proceed.await() + isAuthorized = onBeforeSend() + if (isAuthorized == true) Result.success("pid") else Result.failure(PaymentAbortedBeforeSend()) + } + val session = QuickPaySession() + + sut.attach(session).test { + val pay = backgroundScope.launch { + sut.payNow(session, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u)) + } + started.await() + assertEquals(250L, spentCents()) + + val outcome = sut.signalCompletion(paymentId = hash, paymentHash = hash, success = true) + + assertEquals(QuickPayCompletionKind.NONE, outcome.kind) + assertIs(assertIs(awaitItem()).error) + proceed.complete(Unit) + pay.join() + expectNoEvents() + } + assertEquals(false, isAuthorized) + assertEquals(0L, spentCents()) + assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) + } + @Test fun `re-pay of a settled hash does not double-count`() = test { val (bolt11, hash) = testInvoice() From 1abe3bf1820ed0a19476a8885341dd65cbe1c58b Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 27 Nov 2026 09:28:30 -0300 Subject: [PATCH 13/15] fix: keep a stale quickpay dispatch off a later pay of the invoice Co-Authored-By: Claude Opus 5.5 --- .../to/bitkit/repositories/QuickPayRepo.kt | 57 ++++++++++++------- .../bitkit/repositories/QuickPayRepoTest.kt | 46 +++++++++++++++ 2 files changed, 81 insertions(+), 22 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index 15de88fe04..f7f5882187 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -284,8 +284,10 @@ class QuickPayRepo @Inject constructor( PreparePayResult.REJECTED -> return PreparePayResult.RECOVERED -> settleRecovered(invoiceHash) PreparePayResult.FRESH -> { - dispatchBolt11(invoice, invoiceHash, canDispatch) - awaitCompletionOrPending(invoiceHash) + val job = currentCoroutineContext()[Job] + val op = mutex.withLock { opsByKey[invoiceHash]?.takeIf { it.job === job } } ?: return + dispatchBolt11(invoice, op, canDispatch) + awaitCompletionOrPending(op) } } } @@ -433,27 +435,29 @@ class QuickPayRepo @Inject constructor( } } - private suspend fun dispatchBolt11(invoice: ResolvedInvoice, invoiceHash: String, canDispatch: () -> Boolean) { + private suspend fun dispatchBolt11(invoice: ResolvedInvoice, op: InFlightOp, canDispatch: () -> Boolean) { var isAuthorizationLapsed = false lightningRepo.payInvoiceAuthorizedAtSubmission(invoice.bolt11, sats = null, canDispatch) { isAuthorizationLapsed = !canDispatch() - !isAuthorizationLapsed && tryMarkDispatched(invoiceHash) + !isAuthorizationLapsed && tryMarkDispatched(op) }.fold( - onSuccess = { onInvoiceAccepted(invoiceHash, invoice.bolt11, it) }, + onSuccess = { onInvoiceAccepted(op, invoice.bolt11, it) }, onFailure = { when { - isAuthorizationLapsed -> fallBackBeforeDispatch(invoiceHash) + isAuthorizationLapsed -> fallBackBeforeDispatch(op) // Stopped on the node's queue, after it was marked dispatched but before anything was submitted. - it.isStoppedAtSubmission() -> fallBackBeforeDispatch(invoiceHash, isMarkedDispatched = true) - else -> onInvoiceRejected(invoiceHash, invoice.bolt11, it) + it.isStoppedAtSubmission() -> fallBackBeforeDispatch(op, isMarkedDispatched = true) + else -> onInvoiceRejected(op, invoice.bolt11, it) } }, ) } /** Releases a payment that was never submitted and sends its session to the swipe review. */ - private suspend fun fallBackBeforeDispatch(invoiceHash: String, isMarkedDispatched: Boolean = false) { + private suspend fun fallBackBeforeDispatch(op: InFlightOp, isMarkedDispatched: Boolean = false) { + val invoiceHash = op.invoiceHash mutex.withLock { + if (isSupersededLocked(op)) return@withLock val current = opsByKey[invoiceHash] if (current == null || current.dispatched != isMarkedDispatched) return@withLock spend.release(invoiceHash) @@ -462,10 +466,10 @@ class QuickPayRepo @Inject constructor( } } - private suspend fun tryMarkDispatched(invoiceHash: String): Boolean { + private suspend fun tryMarkDispatched(op: InFlightOp): Boolean { val settings = readSettings() return mutex.withLock { - val current = opsByKey[invoiceHash] ?: return@withLock false + val current = opsByKey[op.invoiceHash]?.takeIf { it === op } ?: return@withLock false if (current.rejection != null) return@withLock false val rejection = sendRejectionLocked(current, settings) if (rejection != null) { @@ -488,8 +492,10 @@ class QuickPayRepo @Inject constructor( return null } - private suspend fun onInvoiceAccepted(invoiceHash: String, paymentRequest: String, paymentId: String) { + private suspend fun onInvoiceAccepted(op: InFlightOp, paymentRequest: String, paymentId: String) { + val invoiceHash = op.invoiceHash mutex.withLock { + if (isSupersededLocked(op)) return@withLock val undispatched = opsByKey[invoiceHash]?.takeIf { !it.dispatched } if (undispatched != null) { // Accepted without a dispatch, so an earlier send of the invoice paid it and nothing new went out. @@ -508,30 +514,31 @@ class QuickPayRepo @Inject constructor( } private suspend fun onInvoiceRejected( - invoiceHash: String, + op: InFlightOp, paymentRequest: String, error: Throwable, ) { if (error is PaymentAbortedBeforeSend) { - releaseIfNotDispatched(invoiceHash) + releaseIfNotDispatched(op) return } - handleDispatchError(invoiceHash, paymentRequest, error) + handleDispatchError(op, paymentRequest, error) } - private suspend fun awaitCompletionOrPending(invoiceHash: String) { - val current = mutex.withLock { opsByKey[invoiceHash] } ?: return + private suspend fun awaitCompletionOrPending(op: InFlightOp) { + if (mutex.withLock { opsByKey[op.invoiceHash] !== op }) return withTimeoutOrNull(LightningRepo.SEND_LN_TIMEOUT) { - current.settled.await() + op.settled.await() } mutex.withLock { - val live = opsByKey[invoiceHash] ?: return@withLock - emitPendingLocked(live) + if (opsByKey[op.invoiceHash] === op) emitPendingLocked(op) } } - private suspend fun releaseIfNotDispatched(invoiceHash: String) { + private suspend fun releaseIfNotDispatched(op: InFlightOp) { + val invoiceHash = op.invoiceHash mutex.withLock { + if (isSupersededLocked(op)) return@withLock val current = opsByKey[invoiceHash] if (current == null || current.dispatched) return@withLock spend.release(invoiceHash) @@ -571,13 +578,15 @@ class QuickPayRepo @Inject constructor( } private suspend fun handleDispatchError( - invoiceHash: String, + op: InFlightOp, paymentRequest: String, error: Throwable, ) { + val invoiceHash = op.invoiceHash when (val kind = classifyDispatchError(error)) { QuickPayDispatchClass.PRE_DISPATCH_REJECTION -> { mutex.withLock { + if (isSupersededLocked(op)) return@withLock signalCompletionLocked( paymentId = null, paymentHash = invoiceHash, @@ -591,6 +600,7 @@ class QuickPayRepo @Inject constructor( -> { val rows = loadPaymentRows() val isEarlierSendTracked = mutex.withLock { + if (isSupersededLocked(op)) return@withLock false settleAmbiguousLocked( invoiceHash = invoiceHash, paymentRequest = paymentRequest, @@ -857,6 +867,9 @@ class QuickPayRepo @Inject constructor( op.paymentId?.takeIf { it.isNotBlank() && it != op.invoiceHash }?.let { opsByKey[it] = op } } + /** True when a later pay registered its own op for this op's invoice, which this op's dispatch must not touch. */ + private fun isSupersededLocked(op: InFlightOp): Boolean = opsByKey[op.invoiceHash].let { it != null && it !== op } + private fun removeOpLocked(op: InFlightOp) { opsByKey.entries.removeAll { it.value === op } } diff --git a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt index 903d214069..75cf7deafa 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -8,6 +8,7 @@ import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow @@ -1033,6 +1034,51 @@ class QuickPayRepoTest : BaseUnitTest() { assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) } + @Test + fun `stale dispatch after an early success leaves a later pay of the invoice alone`() = test { + val (bolt11, hash) = testInvoice() + val started = CompletableDeferred() + val proceed = CompletableDeferred() + var calls = 0 + var isStaleAuthorized: Boolean? = null + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + if (++calls > 1) awaitCancellation() + // The first send is still waiting before dispatch, for example on the node, when the invoice is paid. + started.complete(Unit) + proceed.await() + isStaleAuthorized = invocation.getArgument Boolean>(3)() + Result.failure(PaymentAbortedBeforeSend()) + } + val first = QuickPaySession() + val second = QuickPaySession() + val request = QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u) + + sut.attach(first).test { + val stale = backgroundScope.launch { sut.payNow(first, request) } + started.await() + sut.signalCompletion(paymentId = hash, paymentHash = hash, success = true) + assertIs(assertIs(awaitItem()).error) + + sut.attach(second).test { + val later = backgroundScope.launch { sut.payNow(second, request) } + runCurrent() + assertEquals(2, calls) + assertEquals(250L, spentCents()) + + proceed.complete(Unit) + stale.join() + + assertEquals(false, isStaleAuthorized) + assertTrue(sut.hasOpen(hash)) + assertEquals(250L, spentCents()) + expectNoEvents() + later.cancel() + } + } + } + @Test fun `re-pay of a settled hash does not double-count`() = test { val (bolt11, hash) = testInvoice() From 668f8a92e146436fb0f21b2c35c5b26d5dba25eb Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 27 Nov 2026 10:20:45 -0300 Subject: [PATCH 14/15] fix: resolve an earlier failed node send with no live attempt Co-Authored-By: Claude Opus 5.5 --- .../to/bitkit/repositories/LightningRepo.kt | 37 ++++++++-- .../java/to/bitkit/viewmodels/AppViewModel.kt | 6 +- .../bitkit/repositories/LightningRepoTest.kt | 71 +++++++++++++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 24 +++---- 4 files changed, 119 insertions(+), 19 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 50d90bed83..ccaa399980 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -3077,21 +3077,46 @@ class LightningRepo @Inject constructor( /** * The completion event of a send that settled before its caller started watching for it, read from the rail it - * last went out on: a node send only when it succeeded, as one the node paid earlier gets no new event. + * last went out on: a node send once it succeeded, or with [includeNodeFailure] once it failed with no attempt of + * it live. The node lists no failure reason, so a caller that can still get the node's failure event leaves it out. */ - suspend fun settledSparkSendEvent(paymentHash: String): Event? = - if (isLdkSend(paymentHash)) paidNodeSendEvent(paymentHash) else sparkRepo.settledSendEvent(paymentHash) + suspend fun settledSparkSendEvent(paymentHash: String, includeNodeFailure: Boolean = true): Event? = + if (isLdkSend(paymentHash)) { + settledNodeSendEvent(paymentHash, includeNodeFailure) + } else { + sparkRepo.settledSendEvent(paymentHash) + } - private suspend fun paidNodeSendEvent(paymentHash: String): Event? { + private suspend fun settledNodeSendEvent(paymentHash: String, includeFailure: Boolean): Event? { + val key = paymentHash.lowercase() + // Read before the row too, so a retry that ends while it is read still counts as live. The marks come first, + // so a send they count as recorded is already admitted or in flight when liveness is read. + val ldkRecordsBefore = ldkSendRecordedAt[key] ?: 0L + val sparkRecordsBefore = sparkRepo.sendRecordMark() + val wasLive = isSendLive(paymentHash, key, ldkRecordsBefore) val payments = runSuspendCatching { lightningService.listPayments() } .onFailure { Logger.warn("Failed to list node payments", it, context = TAG) } .getOrNull() val payment = payments?.firstOrNull { - it.direction == PaymentDirection.OUTBOUND && it.status == PaymentStatus.SUCCEEDED && + it.direction == PaymentDirection.OUTBOUND && (it.kind as? PaymentKind.Bolt11)?.hash.equals(paymentHash, ignoreCase = true) } ?: return null val kind = payment.kind as PaymentKind.Bolt11 - return Event.PaymentSuccessful(payment.id, kind.hash, kind.preimage, payment.feePaidMsat) + return when (payment.status) { + PaymentStatus.SUCCEEDED -> Event.PaymentSuccessful( + payment.id, + kind.hash, + kind.preimage, + payment.feePaidMsat, + ) + PaymentStatus.FAILED -> { + // A failed row can be an earlier attempt's while a retry of it on either rail can still pay it. + val isLive = wasLive || isSendLive(paymentHash, key, ldkRecordsBefore) || + sparkRepo.hasRecordedSendSince(sparkRecordsBefore, paymentHash) + Event.PaymentFailed(payment.id, kind.hash, null).takeIf { includeFailure && !isLive } + } + PaymentStatus.PENDING -> null + } } /** Spark's record of the Lightning send with [paymentHash], for recovery after its completion event was missed. */ diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index c55d255cdc..6b1eed9af1 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -8967,7 +8967,11 @@ class AppViewModel @Inject constructor( outcome(it)?.let { result -> WatchResult.Complete(result) } ?: WatchResult.Continue() } } - lightningRepo.settledSparkSendEvent(hash)?.let(::outcome)?.also { watch.cancel() } ?: watch.await() + // A node failure comes with its reason in the watched event, which the payment list does not carry. + lightningRepo.settledSparkSendEvent(hash, includeNodeFailure = false) + ?.let(::outcome) + ?.also { watch.cancel() } + ?: watch.await() } return result ?: Result.failure(PaymentPendingException(hash)) } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 63b8054c6f..64870eadc7 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -2416,6 +2416,77 @@ class LightningRepoTest : BaseUnitTest() { verify(lightningService).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) } + @Test + fun `a failed node send with no attempt live settles as failed`() = test { + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn("h") + assertEquals("h", sut.payInvoice("h", 1_000uL).getOrThrow()) + + // Its failure event was handled before the caller watched for it, so the caller reads the settled payment. + whenever(lightningService.listPayments()).thenReturn(listOf(nodeSend("h", PaymentStatus.FAILED))) + + assertEquals("h", assertIs(sut.settledSparkSendEvent("h")).paymentHash) + } + + @Test + fun `a failed node send settles nothing while a retry of it is sent`() = test { + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn("h") + assertEquals("h", sut.payInvoice("h", 1_000uL).getOrThrow()) + whenever(lightningService.listPayments()).thenReturn(listOf(nodeSend("h", PaymentStatus.FAILED))) + val proceed = CompletableDeferred() + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).doSuspendableAnswer { + proceed.await() + "h" + } + val retry = backgroundScope.launch { sut.payInvoice("h", 1_000uL) } + runCurrent() + + assertNull(sut.settledSparkSendEvent("h")) + proceed.complete(Unit) + retry.join() + } + + @Test + fun `a failed node send settles nothing when a retry of it ends while the payments are listed`() = test { + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn("h") + assertEquals("h", sut.payInvoice("h", 1_000uL).getOrThrow()) + val proceed = CompletableDeferred() + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).doSuspendableAnswer { + proceed.await() + "h" + } + val retry = backgroundScope.launch { sut.payInvoice("h", 1_000uL) } + runCurrent() + // The listing reads the earlier attempt's failed row, and the retry is sent and released before it returns. + whenever(lightningService.listPayments()).doSuspendableAnswer { + proceed.complete(Unit) + retry.join() + listOf(nodeSend("h", PaymentStatus.FAILED)) + } + + assertNull(sut.settledSparkSendEvent("h")) + } + + @Test + fun `a failed node send is left to its event when the caller can still get it`() = test { + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn("h") + assertEquals("h", sut.payInvoice("h", 1_000uL).getOrThrow()) + whenever(lightningService.listPayments()).thenReturn(listOf(nodeSend("h", PaymentStatus.FAILED))) + + assertNull(sut.settledSparkSendEvent("h", includeNodeFailure = false)) + } + @Test fun `a spark send of an invoice the node already paid settles as paid`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index d95a70b007..a836969b16 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12353,7 +12353,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val invoice = lightningInvoice(bolt11, 1_000u) val paymentHash = invoice.paymentHash.toHex() whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -12390,7 +12390,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val paymentHash = invoice.paymentHash.toHex() whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = 1_000u)).thenReturn(Result.success(paymentHash)) whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = 2_000u)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -12423,7 +12423,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val paymentHash = invoice.paymentHash.toHex() whenever(context.getString(R.string.wallet__send_quickpay__already_paid)).thenReturn("Already paid") whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -12460,7 +12460,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val invoice = lightningInvoice(bolt11, 0u) val paymentHash = invoice.paymentHash.toHex() whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = 2_000u)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -12488,7 +12488,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val invoice = lightningInvoice(bolt11, 1_000u) val paymentHash = invoice.paymentHash.toHex() whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -12514,7 +12514,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val invoice = lightningInvoice(bolt11, 1_000u) val paymentHash = invoice.paymentHash.toHex() whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -12562,7 +12562,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val paymentHash = invoice.paymentHash.toHex() whenever(moveToSparkRepo.needsUpdateToSend(1_000uL)).thenReturn(true) whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -12590,7 +12590,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val invoice = lightningInvoice(bolt11, 1_000u) val paymentHash = invoice.paymentHash.toHex() whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -12795,7 +12795,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.onSendSuccess(details) Result.success(paymentHash) } - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -20758,7 +20758,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val paymentHash = "spark_hash" balanceState.value = BalanceState(maxSendLightningSats = 100_000u) whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = paymentHash, paymentHash = paymentHash, @@ -20790,7 +20790,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)) .thenReturn(Result.failure(PaymentPendingException(paymentHash))) // Spark's success was handled after the send returned pending, before the send screen tracked it. - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = paymentHash, paymentHash = paymentHash, @@ -20824,7 +20824,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)) .thenReturn(Result.failure(PaymentPendingException(paymentHash))) // The send screen moved on to a payment to a contact before the pending send's success was read. - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenAnswer { + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenAnswer { setActiveContactPaymentContext(nextContactKey) Event.PaymentSuccessful( paymentId = paymentHash, From 57bdfe07eea7f55d9f53a3a59e960ab75a6a6675 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Fri, 27 Nov 2026 11:59:10 -0300 Subject: [PATCH 15/15] docs: describe failed node sends in the quickpay settled lookup Co-Authored-By: Claude Opus 5.5 --- app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index f7f5882187..0363f244d7 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -668,7 +668,7 @@ class QuickPayRepo @Inject constructor( * handled before it was tracked, which no later event resolves. */ private suspend fun resolveSettledEarlierSend(invoiceHash: String) { - // Settled only when confirmed: a node send once it succeeded, a Spark send once no attempt of it is live. + // Settled only when confirmed: once it succeeded, or once it failed with no attempt of it live on either rail. val event = runSuspendCatching { lightningRepo.settledSparkSendEvent(invoiceHash) }.getOrNull() val resolution = when (event) { is Event.PaymentSuccessful if event.paymentHash == invoiceHash ->