diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index a856a29844..296fc3798f 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -275,12 +275,19 @@ class CacheStore internal constructor( /** * Drops the node's sends a listing showed as [failed] only, or as [paid] with an expired invoice, ones it didn't * show ([listed] is every hash it shows) whose invoice expired past [UNLISTED_SEND_SETTLE_SECS], and past the cap - * the oldest paid or unlisted ones with no known expiry. A send that may be pending ([live]) always stays. + * the oldest paid or unlisted ones with no known expiry. A send that may be pending ([live], or [isLive] inside + * the write, as for one recorded since the listing) always stays. */ - suspend fun trimLdkSendHashes(paid: Set, failed: Set, listed: Set, live: Set) { + suspend fun trimLdkSendHashes( + paid: Set, + failed: Set, + listed: Set, + live: Set, + isLive: (String) -> Boolean = { false }, + ) { store.updateData { - val (hashes, expiries) = - withoutSettled(it.ldkSendHashes, it.ldkSendExpiries, SendListing(paid, failed, listed, live)) + val listing = SendListing(paid, failed, listed, live + it.ldkSendHashes.filter(isLive)) + val (hashes, expiries) = withoutSettled(it.ldkSendHashes, it.ldkSendExpiries, listing) it.copy(ldkSendHashes = hashes, ldkSendExpiries = expiries) } } @@ -325,10 +332,12 @@ class CacheStore internal constructor( return kept to expiries.filterKeys { it in kept } } - suspend fun removeLdkSendHash(paymentHash: String) { + /** Drops the node's send of [paymentHash] unless [isKept] holds inside the write, as for a send recorded since. */ + suspend fun removeLdkSendHash(paymentHash: String, isKept: () -> Boolean = { false }) { val hash = paymentHash.lowercase() if (hash !in store.data.first().ldkSendHashes) return store.updateData { + if (isKept()) return@updateData it it.copy(ldkSendHashes = it.ldkSendHashes - hash, ldkSendExpiries = it.ldkSendExpiries - hash) } } diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 0011f3ce73..14acac1874 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1336,10 +1336,12 @@ class BackupRepo @Inject constructor( } runCatching { restoreSparkExitEarlierAddresses(parsed.sparkExitEarlierAddresses) } .onFailure { Logger.warn("Failed to restore the earlier Spark exit addresses", it, context = TAG) } - // Payment history stays out of the log, as support requests attach it. + // Payment history and Spark attempt ids stay out of the log, as support requests attach it. val logged = parsed.cache.copy( cachedRates = emptyList(), moveToSparkHashes = emptyList(), + sparkSendAttemptIds = emptyMap(), + sparkUnsavedOwnFailures = emptySet(), ) Logger.debug("Restored caches: ${jsonLogOf(logged)}", TAG) onCacheRestored() diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index edd8bba7fe..c40e866b8d 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1661,11 +1661,15 @@ 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 = ldkSendsInFlight.containsKey(key) || key in inFlightBefore || - (ldkSendRecordedAt[key] ?: 0L) > recordsBefore + 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) - cacheStore.removeLdkSendHash(key) + if (isRetried()) return EarlierSend.Pending(key) + // Checked again inside the release and after it, so a node send recorded meanwhile keeps its hash. + cacheStore.removeLdkSendHash(key, isKept = isRetried) + if (isRetried()) return EarlierSend.Pending(key) } if (send == null) return null val hash = (send.kind as PaymentKind.Bolt11).hash @@ -1832,8 +1836,13 @@ class LightningRepo @Inject constructor( val paid = hashes(PaymentStatus.SUCCEEDED) val failed = hashes(PaymentStatus.FAILED) - paid - live val listed = outbound.mapNotNullTo(mutableSetOf()) { (it.kind as? PaymentKind.Bolt11)?.hash?.lowercase() } - cacheStore.trimLdkSendHashes(paid = paid - live, failed = failed, listed = listed, live = live) - failed.forEach { ldkSendRecordedAt.remove(it) } + // A send recorded while the listing was read or trimmed keeps its hash and its record. + cacheStore.trimLdkSendHashes(paid = paid - live, failed = failed, listed = listed, live = live) { + ldkSendsInFlight.containsKey(it) || (ldkSendRecordedAt[it] ?: 0L) > recordsBefore + } + failed.forEach { hash -> + ldkSendRecordedAt.computeIfPresent(hash) { _, at -> at.takeIf { at > recordsBefore } } + } } /** When [bolt11] expires, in epoch seconds, or null when it can't be parsed. */ diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 9e293753a2..2bbeb986b4 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -567,9 +567,9 @@ class SparkRepo @Inject constructor( // 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) + // Read after the listing, so a first sync that lands during it counts, as the listing saw it synced. + val canList = canListPayments() when (earlier) { is SparkLightningSend.Found if earlier.status == PaymentStatus.COMPLETED -> { Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG) @@ -588,9 +588,9 @@ 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. + // key. It is read again here: the local one before Spark's first sync, else the synced one. if (earlier == SparkLightningSend.Unavailable) { - val local = (if (canList) null else runSuspendCatching { listPayments() }.getOrNull()) + val local = runSuspendCatching { listPayments() }.getOrNull() ?: throw SparkError.SendRefused("Spark could not list its payments to check the invoice") when (local.latestSend(paymentHash)?.status) { PaymentStatus.COMPLETED -> { @@ -1500,7 +1500,7 @@ class SparkRepo @Inject constructor( // 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) } + .forEach { markUnsavedOwnFailure(it.id, isUnsaved = false) } deciding .filter { it.id in unsavedPayments || it.id in unsavedOwnFailures || @@ -2169,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) cacheStore.addSparkUnsavedOwnFailure(payment.id) + if (isOwn) markUnsavedOwnFailure(payment.id, isUnsaved = true) return false } val existing = (stored as? Activity.Lightning)?.v1 @@ -2180,7 +2180,7 @@ class SparkRepo @Inject constructor( } // Another attempt of the same invoice, on either rail, already paid it. if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) { - cacheStore.removeSparkUnsavedOwnFailure(payment.id) + markUnsavedOwnFailure(payment.id, isUnsaved = false) return true } // A failure, possibly an earlier attempt's, only fails the send's row, which keeps its own details. @@ -2213,11 +2213,11 @@ class SparkRepo @Inject constructor( .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } if (!saved) { unsavedPayments.add(payment.id) - if (isOwn) cacheStore.addSparkUnsavedOwnFailure(payment.id) + if (isOwn) markUnsavedOwnFailure(payment.id, isUnsaved = true) return false } unsavedPayments.remove(payment.id) - cacheStore.removeSparkUnsavedOwnFailure(payment.id) + markUnsavedOwnFailure(payment.id, isUnsaved = false) if (payment.paymentType == SparkPaymentType.SEND && payment.fees.toLong() == 0L) { sendsRecordedWithoutFee.add(payment.id) } else { @@ -2226,6 +2226,20 @@ class SparkRepo @Inject constructor( return true } + /** + * Keeps [paymentId] as an own failure whose row is still to save, or drops it. A failed cache write only loses + * that detail, so it never stops the settlement, hold release or report around it. + */ + private suspend fun markUnsavedOwnFailure(paymentId: String, isUnsaved: Boolean) { + runSuspendCatching { + if (isUnsaved) { + cacheStore.addSparkUnsavedOwnFailure(paymentId) + } else { + cacheStore.removeSparkUnsavedOwnFailure(paymentId) + } + }.onFailure { Logger.warn("Failed to update Spark own failure '$paymentId'", it, context = TAG) } + } + private suspend fun settleMoveToSpark(payment: Payment, send: LightningActivity): Boolean { if (payment.status != PaymentStatus.COMPLETED || send.status == PaymentState.SUCCEEDED) return true val settled = Activity.Lightning(send.copy(status = PaymentState.SUCCEEDED)) diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index ac07d41885..a80c36f49c 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -113,6 +113,17 @@ class CacheStoreTest : BaseUnitTest() { assertFalse(paid.first() in kept, "The oldest paid send was kept over the cap") } + @Test + fun `a node send listed failed stays kept when it is recorded again before the trim writes`() = test { + sut.addLdkSendHash("h") + + sut.trimLdkSendHashes(paid = emptySet(), failed = setOf("h"), listed = setOf("h"), live = emptySet()) { + it == "h" + } + + assertEquals(listOf("h"), sut.data.first().ldkSendHashes) + } + @Test fun `a node send still pending behind the cap of later sends stays kept`() = test { sut.addLdkSendHash("pending") diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 1f83ad43cb..c57456b7cf 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -22,6 +22,7 @@ import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancel @@ -36,6 +37,7 @@ import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runCurrent import org.junit.Before import org.junit.Test @@ -1932,6 +1934,54 @@ class LightningRepoTest : BaseUnitTest() { verify(sparkRepo).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) } + @Test + fun `a node send recorded while a spark check releases the invoice keeps its hash`() = test { + assertNodeSendRecordedDuringReleaseKeepsHash(listed = emptyList()) + } + + @Test + fun `a node send recorded while the listing trims its failed attempt keeps its hash`() = test { + assertNodeSendRecordedDuringReleaseKeepsHash(listed = listOf(nodeSend("h", PaymentStatus.FAILED))) + } + + /** The node sends the invoice again once a Spark send's check decided to release the node's [listed] attempt. */ + private suspend fun TestScope.assertNodeSendRecordedDuringReleaseKeepsHash(listed: List) { + val inner = InMemoryDataStore(AppCacheData(ldkSendHashesSeeded = true, ldkSendHashes = listOf("h"))) + val entered = CompletableDeferred() + val queued = CompletableDeferred() + var isArmed = true + var node: Job? = null + val store = CacheStore( + object : DataStore by inner { + override suspend fun updateData(transform: suspend (t: AppCacheData) -> AppCacheData): AppCacheData { + val current = inner.data.first() + if (isArmed && "h" in current.ldkSendHashes && "h" !in transform(current).ldkSendHashes) { + isArmed = false + node = launch { sut.payInvoiceWithNode("h") } + entered.await() + } + return inner.updateData(transform) + } + } + ) + sut = repoWith(store) + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.listPayments()).thenReturn(listed) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).doSuspendableAnswer { + entered.complete(Unit) + queued.await() + } + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + + val result = sut.payInvoice("h", 1_000uL) + + assertIs(result.exceptionOrNull()) + assertEquals(listOf("h"), store.data.first().ldkSendHashes, "a Spark check released a node send's hold") + queued.complete("h") + node?.join() + } + private fun failingOnceOnLdkHash(hash: String): DataStore = object : DataStore { private val inner = InMemoryDataStore(AppCacheData(ldkSendHashesSeeded = true)) private var isArmed = true @@ -2009,10 +2059,11 @@ class LightningRepoTest : BaseUnitTest() { verifyBlocking(cacheStore) { trimLdkSendHashes( - paid = setOf("paid"), - failed = setOf("failed"), - listed = setOf("pending", "paid", "failed"), - live = setOf("pending"), + paid = eq(setOf("paid")), + failed = eq(setOf("failed")), + listed = eq(setOf("pending", "paid", "failed")), + live = eq(setOf("pending")), + isLive = any(), ) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 45ade0777f..fc2beaaaab 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -43,6 +43,7 @@ import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.test.TestScope @@ -93,7 +94,9 @@ import to.bitkit.test.InMemoryDataStore import to.bitkit.utils.AppError import to.bitkit.utils.ServiceError import java.io.File +import java.io.IOException import java.math.BigInteger +import java.util.concurrent.atomic.AtomicBoolean import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse @@ -5387,6 +5390,122 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService).send(any(), anyOrNull()) } + @Test + fun `a spark send that returns failed reports it when keeping its unsaved failure fails too`() = 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())).doSuspendableAnswer { + sentPayment(fees = 3).copy(id = it.getArgument(1), status = PaymentStatus.FAILED) + } + whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.failure(SdkException.Generic("storage"))) + // The cache can't keep the failure whose row didn't save either. + val sut = createSut(ownFailureWriteFailingStore(AppCacheData())) + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + sut.start(0).getOrThrow() + + sut.payInvoice("lnbc1", 100uL) + advanceUntilIdle() + + assertEquals("hash", assertIs(events.single()).paymentHash) + } + + @Test + fun `a sync whose own failure cleanup fails still ends a paid hold`() = test { + val sentAt = now.epochSeconds + // A superseded own failure whose cache entry can't be dropped, next to a held send Spark has since paid. + val store = ownFailureWriteFailingStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to sentAt + 3_600), + sparkUncertainSends = mapOf("hash" to sentAt), + sparkSendAttemptIds = mapOf("hash" to "attempt"), + sparkUnsavedOwnFailures = setOf("earlier"), + ) + ) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + whenever(sparkService.listPayments()).thenReturn( + listOf( + sentPayment(fees = 3).copy(id = "earlier", status = PaymentStatus.FAILED, timestamp = 1uL), + sentPayment(fees = 3).copy(id = "attempt", timestamp = 2uL), + ) + ) + val sut = createSut(store) + sut.start(0).getOrThrow() + + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals(emptyMap(), store.data.first().sparkUncertainSends) + } + + @Test + fun `a pre-restore retry is sent when spark's first sync lands during its listing and the operators show failed`() = + test { + val restored = AppCacheData(sparkRestoredAt = now.epochSeconds) + val isSyncPending = AtomicBoolean(false) + lateinit var sut: SparkRepo + val backing = InMemoryDataStore(restored) + // Spark's first sync lands on the listing's first cache read, after the send's checks began. + val store = CacheStore( + object : DataStore by backing { + override val data = backing.data.onStart { + if (isSyncPending.compareAndSet(true, false)) { + 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") + } + } + }, + clock, + ) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL).copy(lastSyncedAt = null)) + val earlier = sentPayment(fees = 0).copy(id = "earlier", status = PaymentStatus.FAILED) + whenever { sparkService.listPayments() }.thenReturn(listOf(earlier)) + whenever { sparkService.lightningSendStatus(any()) }.thenReturn(PaymentStatus.FAILED) + val prepared = prepared(feeSats = 0uL, createdAt = (now.epochSeconds - 600).toULong(), expirySecs = 3_600uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.doSuspendableAnswer { + isSyncPending.set(true) + prepared + } + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) + sut = createSut(store) + sut.start(0).getOrThrow() + assertFalse(sut.canListPayments()) + + val result = sut.payInvoice("lnbc1280n1send", 128uL) + + assertTrue(result.isSuccess, "refused with '${result.exceptionOrNull()}'") + verify(sparkService).send(any(), anyOrNull()) + } + + /** A cache whose writes of Spark's unsaved own failures fail, as on a full disk. */ + private fun ownFailureWriteFailingStore(initial: AppCacheData): CacheStore { + val backing = InMemoryDataStore(initial) + return CacheStore( + object : DataStore { + override val data = backing.data + + override suspend fun updateData(transform: suspend (t: AppCacheData) -> AppCacheData): AppCacheData = + backing.updateData { current -> + transform(current).also { + if (it.sparkUnsavedOwnFailures != current.sparkUnsavedOwnFailures) { + throw IOException("disk full") + } + } + } + }, + clock, + ) + } + /** 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/2015.fixed.md b/changelog.d/next/2015.fixed.md new file mode 100644 index 0000000000..1a02818837 --- /dev/null +++ b/changelog.d/next/2015.fixed.md @@ -0,0 +1 @@ +Fixed rare cases where a Spark payment outcome could be missed after a storage error, or a retry of an invoice from before a restore was refused.