From 57138908e4ef3275c3fb0ce545842913d08eacec Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 15:09:32 +0100 Subject: [PATCH 1/4] fix: close spark retry hold gaps - The node path's ask for an invoice clears its restored-at-start mute, as payInvoice does. - A muted outcome claims its payment before its row is written, and the mute stays until then. - A send before Spark's first sync is refused when its list can't be read: spark-sdk 0.28.3 pays a paid invoice again under a new key on the Spark route. - A retry's own failure stays owned across a restart until its row saves. Raised by @pwltr on synonymdev/bitkit-android#2007. Verified: just compile, just test, just lint --- .../main/java/to/bitkit/data/CacheStore.kt | 15 ++ .../java/to/bitkit/repositories/SparkRepo.kt | 32 ++-- .../to/bitkit/repositories/SparkRepoTest.kt | 163 +++++++++++++++++- 3 files changed, 188 insertions(+), 22 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 46a6b84ca7..a856a29844 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -200,6 +200,16 @@ class CacheStore internal constructor( } } + suspend fun addSparkUnsavedOwnFailure(paymentId: String) { + if (paymentId in store.data.first().sparkUnsavedOwnFailures) return + store.updateData { it.copy(sparkUnsavedOwnFailures = it.sparkUnsavedOwnFailures + paymentId) } + } + + suspend fun removeSparkUnsavedOwnFailure(paymentId: String) { + if (paymentId !in store.data.first().sparkUnsavedOwnFailures) return + store.updateData { it.copy(sparkUnsavedOwnFailures = it.sparkUnsavedOwnFailures - paymentId) } + } + suspend fun addMoveToSparkHash(paymentHash: String) { val hash = paymentHash.lowercase() if (hash in store.data.first().moveToSparkHashes) return @@ -394,6 +404,11 @@ data class AppCacheData( * only its own outcome settles it. A hold without one waits for a paid attempt or its invoice's expiry. */ val sparkSendAttemptIds: Map = mapOf(), + /** + * Payment ids of Spark send attempts whose own failure a failed Activity write still has to save over an earlier + * attempt's row, kept across a restart until it saves. + */ + val sparkUnsavedOwnFailures: Set = setOf(), /** * Payment hashes of the moves to Spark, kept across restarts so neither leg of a move is announced as a payment and * Activity shows the move as one. diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index f00c626747..40b4c9f290 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -179,9 +179,6 @@ class SparkRepo @Inject constructor( /** The invoice of each send still inside Spark's send call, by lowercase payment hash. */ private val sendsInFlight = ConcurrentHashMap() - /** Payment ids of failed attempts whose own details a failed write still has to save over an older row. */ - private val unsavedOwnFailures = ConcurrentHashMap.newKeySet() - /** Sends taken back at start, whose outcome Spark settled while the app was closed, so none is reported again. */ private val restoredAtStart = ConcurrentHashMap.newKeySet() @@ -326,7 +323,6 @@ class SparkRepo @Inject constructor( broadcastDeposits.clear() sendsRecordedWithoutFee.clear() unsavedPayments.clear() - unsavedOwnFailures.clear() sendsInFlight.clear() uncertainSends.clear() restoredAtStart.clear() @@ -588,8 +584,11 @@ class SparkRepo @Inject constructor( isFailedUnsent = canListPayments(), ) } - // A synced list that can't be read may hide a payment of the invoice, also one from another device. - if (earlier == SparkLightningSend.Unavailable && canListPayments()) { + // A list that can't be read may hide a payment of the invoice, which Spark would pay again under a new + // key. Before Spark's first sync its local list is read here, as the synced one was above. + if (earlier == SparkLightningSend.Unavailable && + (canListPayments() || runSuspendCatching { listPayments() }.isFailure) + ) { throw SparkError.SendRefused("Spark could not list its payments to check the invoice") } // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. @@ -723,8 +722,9 @@ class SparkRepo @Inject constructor( // Only the caller that takes the hash off settles it, so its outcome is reported once. if (!isSettled) return false if (!takeUncertainSend(paymentHash, uncertain, send)) return true - // A send Spark settled while the app was closed updates its row only, as nobody waits for it now. - val isReported = !restoredAtStart.remove(key) + // A send Spark settled while the app was closed updates its row only, as nobody waits for it now. Its marker + // stays until its payment is claimed, so Spark's event for it meanwhile claims it too. + val isReported = key !in restoredAtStart when (send) { // A send Spark never recorded settles only at its expiry, so it is reported, as a caller may wait for it. SparkLightningSend.NotFound -> { @@ -740,6 +740,7 @@ class SparkRepo @Inject constructor( is SparkLightningSend.Found -> reportListedSend(paymentHash, uncertain, send, listing, isReported) SparkLightningSend.Unavailable -> Unit } + restoredAtStart.remove(key) return true } @@ -755,6 +756,8 @@ class SparkRepo @Inject constructor( // The send's own failure decides its row and outcome, also when another attempt failed later. val own = payments?.firstOrNull { it.id == uncertain.attemptId } val listed = own?.takeIf { deciding?.status == PaymentStatus.FAILED } ?: deciding + // Claimed before the write, so Spark's event for the same payment during it reports nothing either. + if (!isReported) listed?.let { reportedSendIds.add(it.id) } if (send.status == PaymentStatus.FAILED) { // Its row stayed pending while held, so it takes the failure now. // A retry that started since the hold was taken keeps its own row. @@ -762,7 +765,7 @@ class SparkRepo @Inject constructor( } when { // Spark's event for the same payment, which can follow a reconnect, reports nothing either. - !isReported -> listed?.let { reportedSendIds.add(it.id) } + !isReported -> Unit listed == null -> settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } // A retry started after the hold was taken reads as pending, and its own event reports it. listed.status == PaymentStatus.PENDING -> Unit @@ -1702,6 +1705,8 @@ class SparkRepo @Inject constructor( invoiceExpiresAt: Long? = null, ): EarlierSend? = withContext(bgDispatcher) { + // A caller asking for the invoice again waits for its outcome, also for a send settled while closed. + paymentHash?.lowercase()?.let { restoredAtStart.remove(it) } val recordsBefore = sendRecords.get() val keptUncertain = cacheStore.data.first().sparkUncertainSends.keys val isOfInvoice = { send: Map.Entry -> @@ -2129,7 +2134,8 @@ class SparkRepo @Inject constructor( return true } val id = lightning.htlcDetails.paymentHash - val isOwn = payment.status == PaymentStatus.FAILED && (isOwnAttempt || payment.id in unsavedOwnFailures) + val isOwn = payment.status == PaymentStatus.FAILED && + (isOwnAttempt || payment.id in cacheStore.data.first().sparkUnsavedOwnFailures) // A send in doubt or in Spark's send call shows as pending until Spark settles it, whatever another attempt on // its invoice failed with. if (payment.status == PaymentStatus.FAILED && !isOwnAttempt && isHeldFrom(payment)) { @@ -2138,7 +2144,7 @@ class SparkRepo @Inject constructor( // A failed read would drop the stored note, contact and seen time, so the write waits for the next refresh. val stored = activityRepo.get().getActivity(id).getOrElse { unsavedPayments.add(payment.id) - if (isOwn) unsavedOwnFailures.add(payment.id) + if (isOwn) cacheStore.addSparkUnsavedOwnFailure(payment.id) return false } val existing = (stored as? Activity.Lightning)?.v1 @@ -2179,11 +2185,11 @@ class SparkRepo @Inject constructor( .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } if (!saved) { unsavedPayments.add(payment.id) - if (isOwn) unsavedOwnFailures.add(payment.id) + if (isOwn) cacheStore.addSparkUnsavedOwnFailure(payment.id) return false } unsavedPayments.remove(payment.id) - unsavedOwnFailures.remove(payment.id) + cacheStore.removeSparkUnsavedOwnFailure(payment.id) if (payment.paymentType == SparkPaymentType.SEND && payment.fees.toLong() == 0L) { sendsRecordedWithoutFee.add(payment.id) } else { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index a451196628..53dff79ff4 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5076,6 +5076,24 @@ class SparkRepoTest : BaseUnitTest() { assertFalse("hash" in store.data.first().sparkUncertainSends) } + @Test + fun `a spark send is refused before spark's first sync while its list can't be read`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + // No wallet sync has succeeded yet, and Spark's local list can't be read either. + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = null)) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val sut = createSut() + sut.start(0).getOrThrow() + advanceUntilIdle() + whenever(sparkService.listPayments()).thenAnswer { throw SdkException.Generic("storage") } + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + verify(sparkService, never()).send(any(), anyOrNull()) + } + @Test fun `a held spark send spark never recorded reports its failure at expiry after a restart`() = test { val sentAt = now.epochSeconds @@ -5109,6 +5127,89 @@ class SparkRepoTest : BaseUnitTest() { assertEquals("hash", assertIs(events.single()).paymentHash) } + @Test + fun `a held spark send restored at launch reports its outcome once the node path asks for it again`() = test { + val sentAt = now.epochSeconds + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to sentAt + 3_600), + sparkUncertainSends = mapOf("hash" to sentAt), + sparkSendAttemptIds = mapOf("hash" to "attempt"), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + val pending = sentPayment(fees = 0).copy(id = "attempt", status = PaymentStatus.PENDING) + whenever(sparkService.listPayments()).thenReturn(listOf(pending)) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val sut = createSut(store) + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + sut.start(0).getOrThrow() + advanceUntilIdle() + + // After the relaunch the channels can pay, so the node path asks for the invoice and waits on Spark's send. + assertIs(sut.earlierLightningSend("lnbc1280n1send", "hash")) + whenever(sparkService.listPayments()).thenReturn(listOf(pending.copy(status = PaymentStatus.COMPLETED))) + now += 1.minutes + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals("hash", assertIs(events.single()).paymentHash) + } + + @Test + fun `spark's callback during the row write of a send settled while closed reports nothing`() = test { + val sentAt = now.epochSeconds + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to sentAt + 3_600), + sparkUncertainSends = mapOf("hash" to sentAt), + sparkSendAttemptIds = mapOf("hash" to "attempt"), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + now += 1.minutes + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val failed = sentPayment(fees = 0).copy(id = "attempt", status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) + // The write of the settled row is still in progress when Spark's callback comes. + val rowWrite = CompletableDeferred() + var writes = 0 + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + if (writes++ == 1) rowWrite.await() + Result.success(Unit) + } + val sut = createSut(store) + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + val starting = launch { sut.start(0) } + runCurrent() + assertEquals(2, writes, "the settled row's write never started") + + sparkEvents.emit(SdkEvent.PaymentFailed(failed)) + runCurrent() + rowWrite.complete(Unit) + starting.join() + advanceUntilIdle() + + assertEquals( + emptyList(), + events.filter { it is Event.PaymentSuccessful || it is Event.PaymentFailed }, + "a payment settled while the app was closed was reported at launch", + ) + } + @Test fun `a spark retry's own failure keeps its details through a failed activity write`() = test { whenever(sparkService.isSupported).thenReturn(true) @@ -5119,7 +5220,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } whenever { activityRepo.getActivity(eq("hash"), any()) } .thenReturn(Result.success(Activity.Lightning(storedSend(PaymentState.FAILED)))) - val sut = createSut() + val sut = createSut(CacheStore(InMemoryDataStore(AppCacheData()), clock)) sut.start(0).getOrThrow() assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) advanceUntilIdle() @@ -5128,8 +5229,11 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.listPayments()).thenReturn(listOf(own)) // The first write of the retry's failure fails. var writes = 0 + val saved = mutableListOf() whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - if (writes++ == 0) Result.failure(SdkException.Generic("storage")) else Result.success(Unit) + if (writes++ == 0) return@doSuspendableAnswer Result.failure(SdkException.Generic("storage")) + (it.arguments[0] as? Activity.Lightning)?.let { row -> saved += row.v1 } + Result.success(Unit) } sparkEvents.emit(SdkEvent.PaymentFailed(own)) advanceUntilIdle() @@ -5137,13 +5241,52 @@ class SparkRepoTest : BaseUnitTest() { sparkEvents.emit(SdkEvent.Synced) advanceUntilIdle() - verify(activityRepo, atLeastOnce()).upsertActivity( - argThat { this is Activity.Lightning && v1.fee == 3uL && v1.timestamp == retryAt } - ) + val row = saved.last { it.id == "hash" } + assertEquals(PaymentState.FAILED, row.status) + assertEquals(3uL, row.fee) + assertEquals(retryAt, row.timestamp) + } + + @Test + fun `a spark retry's own failure keeps its details through a failed write and a restart`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + whenever { activityRepo.getActivity(eq("hash"), any()) } + .thenReturn(Result.success(Activity.Lightning(storedSend(PaymentState.FAILED)))) + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + sut.start(0).getOrThrow() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + val retryAt = now.epochSeconds.toULong() + val own = sentPayment(fees = 3).copy(id = sentKey(), status = PaymentStatus.FAILED, timestamp = retryAt) + whenever(sparkService.listPayments()).thenReturn(listOf(own)) + whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.failure(SdkException.Generic("storage"))) + sparkEvents.emit(SdkEvent.PaymentFailed(own)) + advanceUntilIdle() + + // The app restarts before another refresh, so only the stored state knows whose failure it is. + val saved = mutableListOf() + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + (it.arguments[0] as? Activity.Lightning)?.let { row -> saved += row.v1 } + Result.success(Unit) + } + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + + val row = saved.last { it.id == "hash" } + assertEquals(PaymentState.FAILED, row.status) + assertEquals(3uL, row.fee) + assertEquals(retryAt, row.timestamp) + assertTrue(store.data.first().sparkUnsavedOwnFailures.isEmpty()) } @Test - fun `a cancelled spark send restored by a foreground restart reports its failure at expiry`() = test { + fun `a cancelled spark send restored by a foreground restart reports its listed failure`() = test { whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) @@ -5164,13 +5307,15 @@ class SparkRepoTest : BaseUnitTest() { sut.start(0).getOrThrow() advanceUntilIdle() - // Spark never lists the send, and syncs after its invoice expired. - now += 2.hours + // Spark lists the send's own failure before its invoice expires, which only a muted restore would hide. + val own = sentPayment(fees = 0).copy(id = sentKey(), status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(own)) + now += 1.minutes whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) sparkEvents.emit(SdkEvent.Synced) advanceUntilIdle() - assertFalse("hash" in store.data.first().sparkUncertainSends, "a cancelled send stayed held past expiry") + assertFalse("hash" in store.data.first().sparkUncertainSends, "a cancelled send stayed held") assertEquals( 1, events.count { it is Event.PaymentFailed }, From cfebd4441700238c54e48efc7fcc9c745dbce34a Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 15:30:08 +0100 Subject: [PATCH 2/4] fix: keep a node send's hold while another of its invoice runs - Node sends in flight are counted per invoice, so one that ends no longer releases another still queued, which let a later Spark attempt pay the invoice again. - Before Spark's first sync, a send uses its local list: an invoice it shows paid or pending is not sent again. - A restored send's mute is read before its hold is taken, and a refresh retries an own failure kept from before a restart. Closes synonymdev/bitkit-android#2011 Verified: just compile, just test, just lint --- .../to/bitkit/repositories/LightningRepo.kt | 19 +++++++------ .../java/to/bitkit/repositories/SparkRepo.kt | 27 ++++++++++++++----- .../bitkit/repositories/LightningRepoTest.kt | 25 +++++++++++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 17 ++++++++++++ 4 files changed, 73 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 84aba06367..a53b433352 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -178,8 +178,11 @@ class LightningRepo @Inject constructor( /** The rail each Lightning send last went out on, by payment hash, so a retry settles only from its own rail. */ private val sendRails = ConcurrentHashMap() - /** Node sends under way, kept so a listing that shows only an earlier failed attempt doesn't drop its hash. */ - private val ldkSendsInFlight = ConcurrentHashMap.newKeySet() + /** + * Node sends under way, counted by send key, so a listing that shows only an earlier failed attempt doesn't drop + * its hash while any send of the invoice is still under way. + */ + private val ldkSendsInFlight = ConcurrentHashMap() /** Counts node sends recorded, so a listing drops a failed hash only when it was recorded before the listing. */ private val ldkSendRecords = AtomicLong() @@ -1632,7 +1635,7 @@ class LightningRepo @Inject constructor( private suspend fun earlierNodeSend(bolt11: String, paymentHash: String?): EarlierSend? { val key = ldkSendKey(bolt11, paymentHash) val recordsBefore = ldkSendRecords.get() - val inFlightBefore = ldkSendsInFlight.toSet() + val inFlightBefore = ldkSendsInFlight.keys.toSet() val payments = listPaymentsKeepingSendHashes() if (payments == null) { val cache = cacheStore.data.first() @@ -1658,7 +1661,7 @@ class LightningRepo @Inject constructor( (kind.bolt11.equals(bolt11, ignoreCase = true) || kind.hash.equals(paymentHash, ignoreCase = true)) } // A retry in flight, also one that ended while the listing was read, or recorded meanwhile, holds the invoice. - val isRetried = key in ldkSendsInFlight || key in inFlightBefore || + val isRetried = ldkSendsInFlight.containsKey(key) || key in inFlightBefore || (ldkSendRecordedAt[key] ?: 0L) > recordsBefore if (send == null || send.status == PaymentStatus.FAILED) { if (isRetried) return EarlierSend.Pending(key) @@ -1754,11 +1757,11 @@ class LightningRepo @Inject constructor( return@executeWhenNodeRunning Result.failure(PaymentPendingException(paymentHash ?: key)) } try { - ldkSendsInFlight += key + ldkSendsInFlight.merge(key, 1, Int::plus) ldkSendRecordedAt[key] = ldkSendRecords.incrementAndGet() cacheStore.addLdkSendHash(key, invoiceExpiresAt(bolt11)) runCatching { lightningService.send(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) } - .also { ldkSendsInFlight -= key } + .also { ldkSendsInFlight.computeIfPresent(key) { _, count -> (count - 1).takeIf { it > 0 } } } .onSuccess { recordSendRail(it, LightningRail.Ldk) } .also { syncState() } } finally { @@ -1792,7 +1795,7 @@ class LightningRepo @Inject constructor( private suspend fun listPaymentsKeepingSendHashes(): List? { // Read after the records, as a send counts as in flight before it is recorded, so one of the two shows it. val recordsBefore = ldkSendRecords.get() - val inFlightBefore = ldkSendsInFlight.toSet() + val inFlightBefore = ldkSendsInFlight.keys.toSet() return listPaymentsOrNull()?.also { keepLdkSendHashes(it, recordsBefore, inFlightBefore) } } @@ -1817,7 +1820,7 @@ class LightningRepo @Inject constructor( .mapNotNullTo(mutableSetOf()) { (it.kind as? PaymentKind.Bolt11)?.hash?.lowercase() } } val recordedSince = ldkSendRecordedAt.filterValues { it > recordsBefore }.keys - val live = hashes(PaymentStatus.PENDING) + ldkSendsInFlight + inFlightBefore + recordedSince + val live = hashes(PaymentStatus.PENDING) + ldkSendsInFlight.keys + inFlightBefore + recordedSince val paid = hashes(PaymentStatus.SUCCEEDED) val failed = hashes(PaymentStatus.FAILED) - paid - live val listed = outbound.mapNotNullTo(mutableSetOf()) { (it.kind as? PaymentKind.Bolt11)?.hash?.lowercase() } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 40b4c9f290..2603e847fc 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -586,10 +586,17 @@ class SparkRepo @Inject constructor( } // A list that can't be read may hide a payment of the invoice, which Spark would pay again under a new // key. Before Spark's first sync its local list is read here, as the synced one was above. - if (earlier == SparkLightningSend.Unavailable && - (canListPayments() || runSuspendCatching { listPayments() }.isFailure) - ) { - throw SparkError.SendRefused("Spark could not list its payments to check the invoice") + if (earlier == SparkLightningSend.Unavailable) { + val local = (if (canListPayments()) null else runSuspendCatching { listPayments() }.getOrNull()) + ?: throw SparkError.SendRefused("Spark could not list its payments to check the invoice") + when (local.latestSend(paymentHash)?.status) { + PaymentStatus.COMPLETED -> { + Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG) + return@runSuspendCatching paymentHash + } + PaymentStatus.PENDING -> throw PaymentPendingException(paymentHash) + else -> Unit + } } // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. if (!onBeforeSend()) throw PaymentAbortedBeforeSend() @@ -721,10 +728,11 @@ class SparkRepo @Inject constructor( } // Only the caller that takes the hash off settles it, so its outcome is reported once. if (!isSettled) return false - if (!takeUncertainSend(paymentHash, uncertain, send)) return true // A send Spark settled while the app was closed updates its row only, as nobody waits for it now. Its marker - // stays until its payment is claimed, so Spark's event for it meanwhile claims it too. + // stays until its payment is claimed, so Spark's event for it meanwhile claims it too. It is read before the + // hold is taken, as that event can remove it right after. val isReported = key !in restoredAtStart + if (!takeUncertainSend(paymentHash, uncertain, send)) return true when (send) { // A send Spark never recorded settles only at its expiry, so it is reported, as a caller may wait for it. SparkLightningSend.NotFound -> { @@ -1479,8 +1487,13 @@ class SparkRepo @Inject constructor( ).withBroadcastDeposits() } markClaimedDeposits(claimed) + // An own failure a write didn't save before a restart is kept in the cache, not in this process's list. + val unsavedOwnFailures = cacheStore.data.first().sparkUnsavedOwnFailures payments.decidingRows() - .filter { it.id in unsavedPayments || (it.id in sendsRecordedWithoutFee && it.fees.toLong() > 0) } + .filter { + it.id in unsavedPayments || it.id in unsavedOwnFailures || + (it.id in sendsRecordedWithoutFee && it.fees.toLong() > 0) + } .forEach { recordActivity(it) } // Off the refresh, so a slow Electrum server never holds a send that waits for it. scope.launch { confirmMinedPayouts(payments) } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 0d820c3b12..dccb674483 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1603,6 +1603,31 @@ class LightningRepoTest : BaseUnitTest() { verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) } + @Test + fun `a node send of an invoice that ends keeps the hold of another node send of it still under way`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(ldkSendHashesSeeded = true))) + sut = repoWith(store) + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + // The first node send waits in the node's queue, unlisted; the second fails before it is submitted. + val queued = CompletableDeferred() + var sends = 0 + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).doSuspendableAnswer { + if (sends++ == 0) queued.await() else throw ServiceError.NodeNotStarted() + } + val first = launch { sut.payInvoiceWithNode("h") } + runCurrent() + assertTrue(sut.payInvoiceWithNode("h").isFailure) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + + sut.payInvoice("h", 1_000uL) + + assertEquals(listOf("h"), store.data.first().ldkSendHashes, "an ended node send released a queued one's hold") + queued.complete("h") + first.join() + } + @Test fun `a node send of an invoice spark admitted is refused at submission`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData(ldkSendHashesSeeded = true))) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 53dff79ff4..492366be23 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5094,6 +5094,23 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any(), anyOrNull()) } + @Test + fun `a spark send before spark's first sync skips an invoice its local list shows paid`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = null)) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.listPayments()).thenReturn(listOf(sentPayment(fees = 0))) + val sut = createSut() + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + + verify(sparkService, never()).send(any(), anyOrNull()) + } + @Test fun `a held spark send spark never recorded reports its failure at expiry after a restart`() = test { val sentAt = now.epochSeconds From 0027b89cbf74fff4c5328e3808e0c5a27b7eb314 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 15:31:56 +0100 Subject: [PATCH 3/4] chore: add changelog fragment Verified: none (changelog fragment only) --- changelog.d/next/2014.fixed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/next/2014.fixed.md diff --git a/changelog.d/next/2014.fixed.md b/changelog.d/next/2014.fixed.md new file mode 100644 index 0000000000..86d947c3a1 --- /dev/null +++ b/changelog.d/next/2014.fixed.md @@ -0,0 +1 @@ +Fixed rare cases where a Lightning payment retried over Spark could be sent twice or show a stale outcome. From dafb072e0a277aa2fbf2dbad292f3a0e1608b9b8 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 16:17:09 +0100 Subject: [PATCH 4/4] fix: release a node send's count and read the spark mute under its lock - A node send whose hash write fails or is cancelled releases its in-flight count. - A kept own failure is dropped once its row shows paid or another attempt decides it. - The restored-at-start mute is read while the hold is taken and cleared by a caller under the same lock, so a caller asking again always gets the outcome. - A Spark send reads whether it can list payments once, so a first sync during its checks doesn't refuse it. Raised by @jvsena42 on synonymdev/bitkit-android#2014; tests from his review. Verified: just compile, just test, just lint --- .../to/bitkit/repositories/LightningRepo.kt | 10 +++- .../java/to/bitkit/repositories/SparkRepo.kt | 51 ++++++++++------ .../bitkit/repositories/LightningRepoTest.kt | 59 +++++++++++++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 47 +++++++++++++++ 4 files changed, 148 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 a53b433352..edd8bba7fe 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1756,15 +1756,23 @@ class LightningRepo @Inject constructor( Logger.warn("Refused a node send of '$key', Spark sent it meanwhile", context = TAG) return@executeWhenNodeRunning Result.failure(PaymentPendingException(paymentHash ?: key)) } + // Counted until the send returns, also when the hash write before it fails or is cancelled. + var isCounted = false + val uncount = { ldkSendsInFlight.computeIfPresent(key) { _, count -> (count - 1).takeIf { it > 0 } } } try { ldkSendsInFlight.merge(key, 1, Int::plus) + isCounted = true ldkSendRecordedAt[key] = ldkSendRecords.incrementAndGet() cacheStore.addLdkSendHash(key, invoiceExpiresAt(bolt11)) runCatching { lightningService.send(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) } - .also { ldkSendsInFlight.computeIfPresent(key) { _, count -> (count - 1).takeIf { it > 0 } } } + .also { + isCounted = false + uncount() + } .onSuccess { recordSendRail(it, LightningRail.Ldk) } .also { syncState() } } finally { + if (isCounted) uncount() releaseSend(key) } } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 2603e847fc..9e293753a2 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -564,8 +564,11 @@ class SparkRepo @Inject constructor( val paymentHash = method.invoiceDetails.paymentHash val invoice = method.invoiceDetails val expiresAt = invoice.timestamp.safe() + invoice.expiry.safe() - // A caller asking for the invoice again waits for its outcome, also for a send settled while closed. - restoredAtStart.remove(paymentHash.lowercase()) + // A caller asking for the invoice again waits for its outcome, also for a send settled while closed. The + // restore lock orders it against a settle taking the hold, which reads the marker under the same lock. + holdRestoreMutex.withLock { restoredAtStart.remove(paymentHash.lowercase()) } + // Read once, as Spark's first sync can land during the checks below. + val canList = canListPayments() val earlier = lightningSend(paymentHash) when (earlier) { is SparkLightningSend.Found if earlier.status == PaymentStatus.COMPLETED -> { @@ -581,13 +584,13 @@ class SparkRepo @Inject constructor( bolt11, invoice.timestamp.toEpochSeconds(), expiresAt.toEpochSeconds(), - isFailedUnsent = canListPayments(), + isFailedUnsent = canList, ) } // A list that can't be read may hide a payment of the invoice, which Spark would pay again under a new // key. Before Spark's first sync its local list is read here, as the synced one was above. if (earlier == SparkLightningSend.Unavailable) { - val local = (if (canListPayments()) null else runSuspendCatching { listPayments() }.getOrNull()) + val local = (if (canList) null else runSuspendCatching { listPayments() }.getOrNull()) ?: throw SparkError.SendRefused("Spark could not list its payments to check the invoice") when (local.latestSend(paymentHash)?.status) { PaymentStatus.COMPLETED -> { @@ -729,10 +732,8 @@ class SparkRepo @Inject constructor( // Only the caller that takes the hash off settles it, so its outcome is reported once. if (!isSettled) return false // A send Spark settled while the app was closed updates its row only, as nobody waits for it now. Its marker - // stays until its payment is claimed, so Spark's event for it meanwhile claims it too. It is read before the - // hold is taken, as that event can remove it right after. - val isReported = key !in restoredAtStart - if (!takeUncertainSend(paymentHash, uncertain, send)) return true + // stays until its payment is claimed, so Spark's event for it meanwhile claims it too. + val isReported = takeUncertainSend(paymentHash, uncertain, send) ?: return true when (send) { // A send Spark never recorded settles only at its expiry, so it is reported, as a caller may wait for it. SparkLightningSend.NotFound -> { @@ -789,22 +790,27 @@ class SparkRepo @Inject constructor( } } + /** + * Takes the hold [uncertain] off [paymentHash]; null when another caller took it, else whether its outcome is + * reported, which it is unless it was taken back at start and no caller has asked for the invoice since. + */ private suspend fun takeUncertainSend( paymentHash: String, uncertain: UncertainSend, send: SparkLightningSend, - ): Boolean { + ): Boolean? { val key = paymentHash.lowercase() val isFailed = send == SparkLightningSend.NotFound || send is SparkLightningSend.Found && send.status == PaymentStatus.FAILED // Both copies go under the restore lock, so a sync never takes back a hold settled here. A send enters Spark's - // send call under the same lock, so a retry's saved send is never dropped here. + // send call under the same lock, so a retry's saved send is never dropped here. A caller asking for the + // invoice again clears its marker under the same lock, so it either sees the hold and gets its report, or + // finds it settled. return holdRestoreMutex.withLock { - uncertainSends.remove(key, uncertain).also { - if (!it) return@also - cacheStore.removeSparkUncertainSend(paymentHash) - if (isFailed && !sendsInFlight.containsKey(key)) cacheStore.removeSparkSendHash(paymentHash) - } + if (!uncertainSends.remove(key, uncertain)) return@withLock null + cacheStore.removeSparkUncertainSend(paymentHash) + if (isFailed && !sendsInFlight.containsKey(key)) cacheStore.removeSparkSendHash(paymentHash) + key !in restoredAtStart } } @@ -1489,7 +1495,13 @@ class SparkRepo @Inject constructor( markClaimedDeposits(claimed) // An own failure a write didn't save before a restart is kept in the cache, not in this process's list. val unsavedOwnFailures = cacheStore.data.first().sparkUnsavedOwnFailures - payments.decidingRows() + val deciding = payments.decidingRows() + // A kept failure that another attempt now decides has no row of its own left to save. One not listed yet is + // kept, as its event can come before the list shows it. + val decidingIds = deciding.mapTo(mutableSetOf()) { it.id } + payments.filter { it.id in unsavedOwnFailures && it.id !in decidingIds } + .forEach { cacheStore.removeSparkUnsavedOwnFailure(it.id) } + deciding .filter { it.id in unsavedPayments || it.id in unsavedOwnFailures || (it.id in sendsRecordedWithoutFee && it.fees.toLong() > 0) @@ -1719,7 +1731,7 @@ class SparkRepo @Inject constructor( ): EarlierSend? = withContext(bgDispatcher) { // A caller asking for the invoice again waits for its outcome, also for a send settled while closed. - paymentHash?.lowercase()?.let { restoredAtStart.remove(it) } + paymentHash?.lowercase()?.let { holdRestoreMutex.withLock { restoredAtStart.remove(it) } } val recordsBefore = sendRecords.get() val keptUncertain = cacheStore.data.first().sparkUncertainSends.keys val isOfInvoice = { send: Map.Entry -> @@ -2167,7 +2179,10 @@ class SparkRepo @Inject constructor( return settleMoveToSpark(payment, existing) } // Another attempt of the same invoice, on either rail, already paid it. - if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) return true + if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) { + cacheStore.removeSparkUnsavedOwnFailure(payment.id) + return true + } // A failure, possibly an earlier attempt's, only fails the send's row, which keeps its own details. val failedRow = existing?.takeIf { payment.status == PaymentStatus.FAILED && it.txType == PaymentType.SENT && !isOwn diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index dccb674483..1f83ad43cb 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1,5 +1,6 @@ package to.bitkit.repositories +import androidx.datastore.core.DataStore import app.cash.turbine.test import breez_sdk_spark.Bolt11InvoiceDetails import breez_sdk_spark.FeePolicy @@ -25,6 +26,7 @@ import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancel import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first @@ -110,6 +112,7 @@ import to.bitkit.utils.AppError import to.bitkit.utils.LdkError import to.bitkit.utils.ServiceError import to.bitkit.utils.UrlValidator +import java.io.IOException import java.math.BigInteger import kotlin.coroutines.cancellation.CancellationException import kotlin.test.assertEquals @@ -1888,6 +1891,62 @@ class LightningRepoTest : BaseUnitTest() { assertTrue(events.none { it is Event.PaymentFailed }, "an older node failure failed the Spark retry") } + @Test + fun `a node send whose hash write fails releases its in-flight count`() = test { + sut = repoWith(CacheStore(failingOnceOnLdkHash("h"))) + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + + assertTrue(runCatching { sut.payInvoiceWithNode("h").getOrThrow() }.isFailure) + verify(lightningService, never()).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("h")) + + val result = sut.payInvoice("h", 1_000uL) + + assertFalse(result.exceptionOrNull() is PaymentPendingException, "a node send that never left held the invoice") + verify(sparkRepo).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `a failed hash write's in-flight count is released by the next node send of the invoice`() = test { + sut = repoWith(CacheStore(failingOnceOnLdkHash("h"))) + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())) + .thenAnswer { throw AppError("Route not found") } + + assertTrue(runCatching { sut.payInvoiceWithNode("h").getOrThrow() }.isFailure) + // The node retries and fails before anything leaves. + assertTrue(sut.payInvoiceWithNode("h").isFailure) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("h")) + + val result = sut.payInvoice("h", 1_000uL) + + assertFalse(result.exceptionOrNull() is PaymentPendingException, "a node send that never left held the invoice") + verify(sparkRepo).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + private fun failingOnceOnLdkHash(hash: String): DataStore = object : DataStore { + private val inner = InMemoryDataStore(AppCacheData(ldkSendHashesSeeded = true)) + private var isArmed = true + override val data: Flow = inner.data + override suspend fun updateData(transform: suspend (t: AppCacheData) -> AppCacheData) = + inner.updateData { current -> + transform(current).also { + if (isArmed && hash in it.ldkSendHashes && hash !in current.ldkSendHashes) { + isArmed = false + throw IOException("disk full") + } + } + } + } + private fun nodeSend(hash: String, status: PaymentStatus) = PaymentDetails( id = hash, kind = PaymentKind.Bolt11(hash = hash, preimage = null, secret = null, description = null, bolt11 = hash), diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 492366be23..45ade0777f 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5340,6 +5340,53 @@ class SparkRepoTest : BaseUnitTest() { ) } + @Test + fun `an own failure kept in the cache is dropped once its row shows paid`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkUnsavedOwnFailures = setOf("a"))), clock) + val own = sentPayment(fees = 3).copy(id = "a", status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(own)) + whenever { activityRepo.getActivity(eq("hash"), any()) } + .thenReturn(Result.success(Activity.Lightning(storedSend(PaymentState.SUCCEEDED)))) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals(emptySet(), store.data.first().sparkUnsavedOwnFailures) + } + + @Test + fun `a send whose first sync lands during the invoice check is not refused`() = test { + val restored = AppCacheData(sparkHistoryUnseededSince = now.epochSeconds, sparkRestoredAt = now.epochSeconds) + val store = CacheStore(InMemoryDataStore(restored), clock) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL).copy(lastSyncedAt = null)) + val prepared = prepared(feeSats = 0uL, createdAt = (now.epochSeconds - 600).toULong(), expirySecs = 3_600uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) + val sut = createSut(store) + sut.start(0).getOrThrow() + assertFalse(sut.canListPayments()) + // Spark's first sync lands while the operators are asked about the pre-restore invoice. + whenever { sparkService.lightningSendStatus(any()) }.doSuspendableAnswer { + whenever { sparkService.getInfo() } + .thenReturn(info(10_000uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + repeat(100) { if (!sut.canListPayments()) delay(10) } + assertTrue(sut.canListPayments(), "the first sync never landed") + null + } + + val result = sut.payInvoice("lnbc1280n1send", 128uL) + + assertTrue(result.isSuccess, "refused with '${result.exceptionOrNull()}'") + verify(sparkService).send(any(), anyOrNull()) + } + /** The idempotency key of the latest Spark send, which Spark keeps as that attempt's payment id. */ private suspend fun sentKey(): String = argumentCaptor().apply { verify(sparkService, atLeastOnce()).send(any(), capture()) }.lastValue