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/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 84aba06367..edd8bba7fe 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) @@ -1753,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 += key + 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 -= key } + .also { + isCounted = false + uncount() + } .onSuccess { recordSendRail(it, LightningRail.Ldk) } .also { syncState() } } finally { + if (isCounted) uncount() releaseSend(key) } } @@ -1792,7 +1803,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 +1828,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 f00c626747..9e293753a2 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() @@ -568,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 -> { @@ -585,12 +584,22 @@ class SparkRepo @Inject constructor( bolt11, invoice.timestamp.toEpochSeconds(), expiresAt.toEpochSeconds(), - isFailedUnsent = canListPayments(), + isFailedUnsent = canList, ) } - // 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()) { - throw SparkError.SendRefused("Spark could not list its payments to check the invoice") + // 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 (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 -> { + 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() @@ -722,9 +731,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 = 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 -> { @@ -740,6 +749,7 @@ class SparkRepo @Inject constructor( is SparkLightningSend.Found -> reportListedSend(paymentHash, uncertain, send, listing, isReported) SparkLightningSend.Unavailable -> Unit } + restoredAtStart.remove(key) return true } @@ -755,6 +765,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 +774,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 @@ -778,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 } } @@ -1476,8 +1493,19 @@ class SparkRepo @Inject constructor( ).withBroadcastDeposits() } markClaimedDeposits(claimed) - payments.decidingRows() - .filter { it.id in unsavedPayments || (it.id in sendsRecordedWithoutFee && it.fees.toLong() > 0) } + // 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 + 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) + } .forEach { recordActivity(it) } // Off the refresh, so a slow Electrum server never holds a send that waits for it. scope.launch { confirmMinedPayouts(payments) } @@ -1702,6 +1730,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 { holdRestoreMutex.withLock { restoredAtStart.remove(it) } } val recordsBefore = sendRecords.get() val keptUncertain = cacheStore.data.first().sparkUncertainSends.keys val isOfInvoice = { send: Map.Entry -> @@ -2129,7 +2159,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 +2169,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 @@ -2148,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 @@ -2179,11 +2213,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/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 0d820c3b12..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 @@ -1603,6 +1606,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))) @@ -1863,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 a451196628..45ade0777f 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5076,6 +5076,41 @@ 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 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 @@ -5109,6 +5144,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 +5237,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 +5246,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 +5258,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 cancelled spark send restored by a foreground restart reports its failure at expiry`() = 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 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 +5324,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 }, @@ -5178,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 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.