From de447dcbcc443a7d1a81f1682d953138ba2076d7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:06:57 +0100 Subject: [PATCH 01/21] fix: hold pre-restore invoices until spark lists its sends --- .../main/java/to/bitkit/data/CacheStore.kt | 19 +++++ .../java/to/bitkit/repositories/BackupRepo.kt | 11 ++- .../to/bitkit/repositories/LightningRepo.kt | 7 +- .../java/to/bitkit/repositories/SparkRepo.kt | 43 ++++++++++- .../java/to/bitkit/services/SparkService.kt | 3 +- .../to/bitkit/repositories/BackupRepoTest.kt | 40 ++++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 76 +++++++++++++++++++ changelog.d/next/0000.fixed.md | 1 + 8 files changed, 194 insertions(+), 6 deletions(-) create mode 100644 changelog.d/next/0000.fixed.md diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 136c9413d1..df981552c7 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -211,6 +211,19 @@ class CacheStore internal constructor( } } + /** After a restore, keeps [paymentHashes], Spark's pending and paid sends from its synced list, once. */ + suspend fun seedSparkSendHashes(paymentHashes: List) { + if (store.data.first().sparkHistoryUnseededSince == null) return + store.updateData { data -> + if (data.sparkHistoryUnseededSince == null) return@updateData data + val seeded = paymentHashes.map { it.lowercase() }.distinct() - data.sparkSendHashes.toSet() + data.copy( + sparkSendHashes = seeded + data.sparkSendHashes, + sparkHistoryUnseededSince = null, + ) + } + } + /** * 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 @@ -323,6 +336,12 @@ data class AppCacheData( * there. Until then an unlistable node holds every Spark send. */ val ldkSendHashesSeeded: Boolean = false, + /** + * When a metadata restore brought back [sparkSendHashes], in epoch seconds, until Spark's synced list fills them: + * the backup can predate a send Spark made, so meanwhile a Spark that can't list its payments holds the node off + * invoices created before it. Null on an install that was never restored, whose kept hashes are complete. + */ + val sparkHistoryUnseededSince: Long? = null, ) { fun isContactDetached(activityId: String, walletId: String): Boolean = scopedActivityId(walletId, activityId) in detachedActivityContacts diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 4945114a10..f580467ede 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -98,6 +98,7 @@ import javax.inject.Inject import javax.inject.Provider import javax.inject.Singleton import kotlin.time.Clock +import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.ExperimentalTime @@ -1201,7 +1202,15 @@ class BackupRepo @Inject constructor( ) val parsed = decodeBackup(migration.json) val cleanCache = parsed.cache.resetBip21() // Force address rotation - cacheStore.update { cleanCache.copy(backupStatuses = it.backupStatuses) } + // The backed-up send hashes can predate either rail's latest sends, so each rail's own list seeds them again. + val restoredAt = currentTimeMillis().milliseconds.inWholeSeconds + cacheStore.update { + cleanCache.copy( + backupStatuses = it.backupStatuses, + sparkHistoryUnseededSince = restoredAt, + ldkSendHashesSeeded = false, + ) + } Logger.debug("Restored caches: ${jsonLogOf(parsed.cache.copy(cachedRates = emptyList()))}", TAG) onCacheRestored() val persisted = preActivityMetadataRepo.upsertPreActivityMetadata(parsed.tagMetadata) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 63b44b991b..63a9a70a51 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1654,7 +1654,8 @@ class LightningRepo @Inject constructor( requireWalletRestoreComplete() // Read before the checks, so a Spark send admitted after them refuses this one at submission. val sparkRecordsBefore = sparkRepo.sendRecordMark() - sparkRepo.earlierLightningSend(bolt11, paymentHash)?.let { return@executeWhenNodeRunning it.toResult() } + sparkRepo.earlierLightningSend(bolt11, paymentHash, invoiceCreatedAt(bolt11)) + ?.let { return@executeWhenNodeRunning it.toResult() } if (!onBeforeSend()) return@executeWhenNodeRunning Result.failure(PaymentAbortedBeforeSend()) requireWalletRestoreComplete() val key = ldkSendKey(bolt11, paymentHash) @@ -1738,6 +1739,10 @@ class LightningRepo @Inject constructor( .coerceAtMost(Long.MAX_VALUE.toULong()).toLong() }.getOrNull() + private fun invoiceCreatedAt(bolt11: String): Long? = runCatching { + Bolt11Invoice.fromStr(bolt11).secondsSinceEpoch().coerceAtMost(Long.MAX_VALUE.toULong()).toLong() + }.getOrNull() + /** The payment hash a node send is kept under, or the invoice itself when it can't be parsed. */ private fun ldkSendKey(bolt11: String, paymentHash: String?): String = (paymentHash ?: bolt11).lowercase() diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index f3a06f67f0..914336d89f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -876,9 +876,16 @@ class SparkRepo @Inject constructor( /** * Spark's pending or paid send of [bolt11], matched by the invoice or its [paymentHash], so the node never pays it * again; a send still inside Spark's send call is pending. Null when Spark's send failed or none is known. - * While Spark can't list its payments, a send it started for [paymentHash] counts as pending, since it may be live. + * While Spark can't list its payments, a send it started for [paymentHash] counts as pending, since it may be live, + * and after a restore, until Spark's synced list seeds the kept hashes, [SparkError.SendRefused] is thrown for an + * invoice created before the restore ([invoiceCreatedAt] in epoch seconds, null when unknown), as the restored + * hashes can lack a send Spark made of it. */ - suspend fun earlierLightningSend(bolt11: String, paymentHash: String?): EarlierSend? = + suspend fun earlierLightningSend( + bolt11: String, + paymentHash: String?, + invoiceCreatedAt: Long? = null, + ): EarlierSend? = withContext(bgDispatcher) { val recordsBefore = sendRecords.get() val keptUncertain = cacheStore.data.first().sparkUncertainSends.keys @@ -903,7 +910,17 @@ class SparkRepo @Inject constructor( } else { null } - if (payments == null) return@withContext startedSend(paymentHash)?.let { EarlierSend.Pending(it) } + if (payments == null) { + startedSend(paymentHash)?.let { return@withContext EarlierSend.Pending(it) } + // Restored hashes can lack a send Spark made before the restore, never one of a newer invoice. + val unseededSince = cacheStore.data.first().sparkHistoryUnseededSince + if (sparkService.isSupported && unseededSince != null && (invoiceCreatedAt ?: 0L) < unseededSince) { + Logger.warn("Refused a node send until Spark lists its earlier sends once", context = TAG) + throw SparkError.SendRefused("Spark hasn't listed its earlier sends yet") + } + return@withContext null + } + seedSendHashes(payments) val send = payments .latestSend { it.invoice.equals(bolt11, ignoreCase = true) || @@ -998,12 +1015,31 @@ class SparkRepo @Inject constructor( ?.toSet() } + /** Seeds the restored send hashes from Spark's list once it has synced, so the hold on older invoices ends. */ + private suspend fun seedRestoredSendHashes() { + if (cacheStore.data.first().sparkHistoryUnseededSince == null || !canListPayments()) return + runSuspendCatching { sparkService.listPayments() } + .onSuccess { seedSendHashes(it) } + .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } + } + + /** Keeps Spark's pending and paid sends once, from a list read after it synced, so a restart holds the node off. */ + private suspend fun seedSendHashes(payments: List) = cacheStore.seedSparkSendHashes( + payments + .filter { it.status != PaymentStatus.FAILED } + .sortedBy { it.timestamp } + .mapNotNull { it.sendHash() }, + ) + /** Records every Spark payment, returning whether all were saved, so a failed write leaves the sync to redo. */ private suspend fun syncActivities(): Boolean { // Read after the records, as a send counts as in flight before it is recorded, so one of the two shows it. val recordsBefore = sendRecords.get() val inFlightBefore = sendsInFlight.keys.toSet() + // Read before the list, as one read before Spark's first sync can lack its restored sends. + val isSynced = canListPayments() val payments = sparkService.listPayments() + if (isSynced) seedSendHashes(payments) val isSaved = payments.map { recordActivity(it) }.all { it } val sendHashes = { status: PaymentStatus -> payments.mapNotNullTo(mutableSetOf()) { it.sendHash(status)?.lowercase() } @@ -1051,6 +1087,7 @@ class SparkRepo @Inject constructor( is SdkEvent.Synced -> { // Spark also reports Synced for a partial or skipped sync, while its wallet sync still fails. if (hasSyncedSince(null)) _state.update { it.copy(hasSynced = true) } + seedRestoredSendHashes() refresh() // A send whose outcome stayed unknown past its polling settles on a later sync. uncertainSends.keys.toList().forEach { trySettleUncertainSend(it) } diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index d1f1e5b8ba..3ade9b137e 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -305,7 +305,8 @@ sealed class SparkError(message: String, cause: Throwable? = null) : AppError(me /** * Spark refused a Lightning payment before anything left the wallet: it was not connected, could not prepare the - * payment, or its fee was over the caller's limit. A Paykit request or allowance attempt can then end as failed. + * payment, or its fee was over the caller's limit; or the node refused one because Spark hadn't listed its earlier + * sends yet. A Paykit request or allowance attempt can then end as failed. */ open class SendRefused(message: String, cause: Throwable? = null) : SparkError(message, cause) diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index a21e8842bd..81f79f590f 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -105,6 +105,7 @@ import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNotEquals +import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock @@ -1829,6 +1830,45 @@ class BackupRepoTest : BaseUnitTest() { verify(vssBackupClient, never()).putObject(any(), any()) } + @Test + fun `a metadata restore keeps spark's backed-up send hashes but holds older invoices until spark lists them`() = + test { + val publicAddress = "bcrt1qpublic" + stubPublicAddressRestore(publicAddress) + stubMetadataRestore( + envelope = metadataEnvelope( + metadata = listOf(preActivityMetadata()), + cache = AppCacheData(onchainAddress = publicAddress, sparkSendHashes = listOf("hash")), + ), + ) + + sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertEquals(listOf("hash"), cacheData.value.sparkSendHashes) + assertNotNull(cacheData.value.sparkHistoryUnseededSince) + } + + @Test + fun `a metadata restore leaves the node's backed-up send hashes for its own list to seed`() = test { + val publicAddress = "bcrt1qpublic" + stubPublicAddressRestore(publicAddress) + stubMetadataRestore( + envelope = metadataEnvelope( + metadata = listOf(preActivityMetadata()), + cache = AppCacheData( + onchainAddress = publicAddress, + ldkSendHashes = listOf("hash"), + ldkSendHashesSeeded = true, + ), + ), + ) + + sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertEquals(listOf("hash"), cacheData.value.ldkSendHashes) + assertFalse(cacheData.value.ldkSendHashesSeeded) + } + @Test fun `metadata cache failure remains optional after public address quarantine succeeds`() = test { val publicAddress = "bcrt1qpublic" diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index c3d2fa1273..e8349d776a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -76,6 +76,7 @@ import to.bitkit.utils.ServiceError import java.io.File import java.math.BigInteger import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNull @@ -205,6 +206,81 @@ class SparkRepoTest : BaseUnitTest() { assertNull(createSut().earlierLightningSend("lnbc1280n1send", "hash")) } + @Test + fun `a restored wallet's unsynced history refuses the node's send of an invoice from before the restore`() = + test { + cacheData.value = AppCacheData(sparkHistoryUnseededSince = now.epochSeconds) + whenever(sparkService.isConnected).thenReturn(true) + val sut = createSut() + + assertFailsWith { + sut.earlierLightningSend("lnbc1280n1send", "hash", invoiceCreatedAt = now.epochSeconds - 60) + } + assertFailsWith { sut.earlierLightningSend("lnbc1280n1send", "hash") } + } + + @Test + fun `an invoice created after the restore pays over the node while spark is unsynced`() = test { + cacheData.value = AppCacheData(sparkHistoryUnseededSince = now.epochSeconds) + whenever(sparkService.isConnected).thenReturn(false) + + assertNull(createSut().earlierLightningSend("lnbc1280n1send", "hash", invoiceCreatedAt = now.epochSeconds + 60)) + } + + @Test + fun `an updated install that was never restored is never held while spark is unsynced`() = test { + whenever(sparkService.isConnected).thenReturn(false) + val sut = createSut() + + assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash", invoiceCreatedAt = 1L)) + assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) + } + + @Test + fun `spark's synced list seeds the restored hashes so a later unsynced start holds only its sends`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkHistoryUnseededSince = now.epochSeconds)), clock) + whenever(sparkService.isConnected).thenReturn(true) + val failed = sentPayment(fees = 0).copy(id = "failed", status = PaymentStatus.FAILED).withHash("failed") + whenever { sparkService.listPayments() }.thenReturn(listOf(sentPayment(fees = 2), failed)) + createSut(store).start(0).getOrThrow() + + assertEquals(listOf("hash"), store.data.first().sparkSendHashes) + assertNull(store.data.first().sparkHistoryUnseededSince) + + whenever(sparkService.isConnected).thenReturn(false) + val restarted = createSut(store) + assertEquals(EarlierSend.Pending("hash"), restarted.earlierLightningSend("lnbc1280n1send", "hash")) + assertNull(restarted.earlierLightningSend("lnbc1280n1other", "other", invoiceCreatedAt = 1L)) + } + + @Test + fun `a list read before spark's first sync seeds no hashes`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkHistoryUnseededSince = now.epochSeconds)), clock) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = null)) + createSut(store).start(0).getOrThrow() + + assertEquals(now.epochSeconds, store.data.first().sparkHistoryUnseededSince) + } + + @Test + fun `spark's synced event seeds the restored hashes and ends the hold`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkHistoryUnseededSince = now.epochSeconds)), clock) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = null)) + val sut = createSut(store) + sut.start(0).getOrThrow() + assertEquals(now.epochSeconds, store.data.first().sparkHistoryUnseededSince) + + whenever { sparkService.getInfo() }.thenReturn(info(0uL)) + whenever { sparkService.listPayments() }.thenReturn(listOf(sentPayment(fees = 2))) + sparkEvents.emit(SdkEvent.Synced) + runCurrent() + + assertNull(store.data.first().sparkHistoryUnseededSince) + assertEquals(listOf("hash"), store.data.first().sparkSendHashes) + } + @Test fun `a spark retry recorded while an older list is read holds the node off the invoice`() = test { whenever(sparkService.isConnected).thenReturn(true) diff --git a/changelog.d/next/0000.fixed.md b/changelog.d/next/0000.fixed.md new file mode 100644 index 0000000000..7eef3de22d --- /dev/null +++ b/changelog.d/next/0000.fixed.md @@ -0,0 +1 @@ +After a wallet restore, Bitkit no longer pays a Lightning invoice over its channels again before Spark has confirmed it did not already pay it. From 1fd041164b19c7974c2687afd89c1f5a486752db Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:09:11 +0100 Subject: [PATCH 02/21] fix: refuse a spark send once its deadline passed --- .../java/to/bitkit/repositories/SparkRepo.kt | 7 ++++--- .../to/bitkit/repositories/SparkRepoTest.kt | 21 +++++++++++++++++++ changelog.d/next/0000.fixed.md | 2 +- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 914336d89f..8887d7fa19 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -309,13 +309,14 @@ class SparkRepo @Inject constructor( val sent = try { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() cacheStore.addSparkSendHash(paymentHash, expiresAt.coerceAtMost(Long.MAX_VALUE.toULong()).toLong()) - // The checks above and saving the hash suspend, so the deadline is checked last, before the send. + // Kept until the call returns, so a send cut off by process death or cancellation stays held. + cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds) + // The checks above and both writes suspend, so the deadline is checked last, before the send. runCatching { ensurePaymentDeadline(paymentDeadlineAt) }.onFailure { + cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) throw it } - // Kept until the call returns, so a send cut off by process death or cancellation stays held. - cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds) runSuspendCatching { sparkService.send(prepared) } } finally { sendsInFlight.remove(paymentHash.lowercase()) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index e8349d776a..8fb2525ffc 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1726,6 +1726,27 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any()) } + @Test + fun `a spark send whose deadline passes while its uncertainty is written never leaves`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + val deadline = now + 1.seconds + whenever { cacheStore.addSparkUncertainSend(any(), any()) }.thenAnswer { + now = deadline + 1.seconds + Unit + } + val sut = createSut() + + val result = sut.payInvoice("lnbc1", 100uL, deadline, null) { true } + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any()) + verifyBlocking(cacheStore) { removeSparkUncertainSend("hash") } + verifyBlocking(cacheStore) { removeSparkSendHash("hash") } + } + @Test fun `an older failed row never ends an uncertain spark send while spark can't resync`() = test { whenever(sparkService.isSupported).thenReturn(true) diff --git a/changelog.d/next/0000.fixed.md b/changelog.d/next/0000.fixed.md index 7eef3de22d..2689a597bc 100644 --- a/changelog.d/next/0000.fixed.md +++ b/changelog.d/next/0000.fixed.md @@ -1 +1 @@ -After a wallet restore, Bitkit no longer pays a Lightning invoice over its channels again before Spark has confirmed it did not already pay it. +Bitkit no longer pays a Lightning invoice again over its channels right after a wallet restore, or sends a payment request's payment after its deadline has passed. From 2b240a573ac36d50557b1a9726fec6dfe5d236b3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:19:46 +0100 Subject: [PATCH 03/21] fix: let spark pay while the node is down --- .../java/to/bitkit/repositories/SparkRepo.kt | 5 ++- .../java/to/bitkit/ui/sheets/SendSheet.kt | 31 ++++++++++++++- .../ui/sheets/SendSheetSyncOverlayTest.kt | 39 +++++++++++++++++++ 3 files changed, 72 insertions(+), 3 deletions(-) create mode 100644 app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 8887d7fa19..112d8e4b8a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -226,7 +226,7 @@ class SparkRepo @Inject constructor( fun canReceive(): Boolean = _state.value.isReady - fun canSend(amountSats: ULong): Boolean = _state.value.isReady && _state.value.sendableSats >= amountSats + fun canSend(amountSats: ULong): Boolean = _state.value.canSend(amountSats) suspend fun createInvoice(amountSats: ULong?, description: String, expirySecs: UInt): Result = withContext(bgDispatcher) { @@ -1252,6 +1252,9 @@ data class SparkState( /** The most Spark can send once its service fee is paid, so a payment near the full balance isn't offered. */ val sendableSats: ULong get() = SparkFees.sendableSats(balanceSats) + /** Whether Spark is ready and can send [amountSats] once its service fee is paid. */ + fun canSend(amountSats: ULong): Boolean = isReady && sendableSats >= amountSats + /** The balance shown in Spending and on the Spark connection, which [keptBalanceSats] stands in for. */ val shownBalanceSats: ULong get() = keptBalanceSats ?: balanceSats } diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index 7906998ac3..51a21afd25 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -56,6 +56,7 @@ import to.bitkit.models.WalletScope import to.bitkit.repositories.ConnectivityState import to.bitkit.repositories.PaykitPaymentRequest import to.bitkit.repositories.PaykitSubscriptionId +import to.bitkit.repositories.SparkState import to.bitkit.ui.components.ConnectionIssuesView import to.bitkit.ui.components.SyncNodeVariant import to.bitkit.ui.components.SyncNodeView @@ -110,6 +111,26 @@ private const val HARDWARE_SEND_FALLBACK_SATS_PER_VBYTE = 3uL /** A peer reconnecting makes a channel usable again without any node event, so the overlay polls. */ private val CHANNELS_REFRESH_INTERVAL = 1.seconds +/** Whether Spark can pay the scanned Lightning invoice's own amount, so an amountless one still waits for the node. */ +internal fun sparkCanPayInvoice(payMethod: SendMethod, invoiceSats: ULong?, sparkState: SparkState): Boolean = + payMethod == SendMethod.LIGHTNING && invoiceSats != null && invoiceSats > 0uL && sparkState.canSend(invoiceSats) + +/** + * A Lightning payment Spark can pay goes ahead without the node. Otherwise the node must run, and with channels a + * payment waits for a usable one. With no channels at all there is nothing to sync into, so validation reports the + * missing capacity instead. + */ +internal fun waitsForNode( + isNodeRunning: Boolean, + hasAnyChannels: Boolean, + hasUsableChannels: Boolean, + sparkCanPay: Boolean, +): Boolean { + if (sparkCanPay) return false + if (!isNodeRunning) return true + return hasAnyChannels && !hasUsableChannels +} + internal fun NavDestination.isPaymentReview(): Boolean = hasRoute() || hasRoute() || hasRoute() || hasRoute() @@ -153,11 +174,17 @@ fun SendSheet( val hasAnyChannels = lightningState.channels.isNotEmpty() val syncNodeVariant = if (hasAnyChannels) SyncNodeVariant.LIGHTNING else SyncNodeVariant.BITCOIN + val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle() val shouldShowSyncOverlay = run { if (preparingRequest != null || sendUiState.paykitUsesUsdt) return@run false if (sendUiState.hardwareWalletId != null) return@run false - if (!lightningState.nodeLifecycleState.isRunning()) return@run true - hasAnyChannels && lightningState.channels.none { it.isUsable } + val invoiceSats = sendUiState.decodedInvoice?.amountSatoshis + waitsForNode( + isNodeRunning = lightningState.nodeLifecycleState.isRunning(), + hasAnyChannels = hasAnyChannels, + hasUsableChannels = lightningState.channels.any { it.isUsable }, + sparkCanPay = sparkCanPayInvoice(sendUiState.payMethod, invoiceSats, sparkState), + ) } val lifecycle = LocalLifecycleOwner.current.lifecycle diff --git a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt new file mode 100644 index 0000000000..d4de062b12 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt @@ -0,0 +1,39 @@ +package to.bitkit.ui.sheets + +import org.junit.Test +import to.bitkit.repositories.SparkState +import to.bitkit.viewmodels.SendMethod +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class SendSheetSyncOverlayTest { + private val funded = SparkState(isSupported = true, isReady = true, balanceSats = 100_000uL) + + @Test + fun `a scanned invoice a ready funded spark can pay skips the wait for a stopped node`() { + val sparkCanPay = sparkCanPayInvoice(SendMethod.LIGHTNING, 1_000uL, funded) + + assertTrue(sparkCanPay) + assertFalse(waitsForNode(false, hasAnyChannels = true, hasUsableChannels = false, sparkCanPay = sparkCanPay)) + assertFalse(waitsForNode(true, hasAnyChannels = true, hasUsableChannels = false, sparkCanPay = sparkCanPay)) + } + + @Test + fun `on-chain, amountless and payments spark can't cover still wait for a stopped node`() { + val cases = listOf( + sparkCanPayInvoice(SendMethod.ONCHAIN, 1_000uL, funded), + sparkCanPayInvoice(SendMethod.LIGHTNING, 0uL, funded), + sparkCanPayInvoice(SendMethod.LIGHTNING, null, funded), + sparkCanPayInvoice(SendMethod.LIGHTNING, 1_000uL, funded.copy(isReady = false)), + sparkCanPayInvoice(SendMethod.LIGHTNING, 1_000uL, funded.copy(balanceSats = 1_000uL)), + ) + + cases.forEach { sparkCanPay -> + assertFalse(sparkCanPay) + assertTrue(waitsForNode(false, hasAnyChannels = false, hasUsableChannels = false, sparkCanPay)) + } + assertFalse(waitsForNode(true, hasAnyChannels = false, hasUsableChannels = false, sparkCanPay = false)) + assertTrue(waitsForNode(true, hasAnyChannels = true, hasUsableChannels = false, sparkCanPay = false)) + assertFalse(waitsForNode(true, hasAnyChannels = true, hasUsableChannels = true, sparkCanPay = false)) + } +} From 14813371d16ab35db79ea3a85126e96a9c76067c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:23:01 +0100 Subject: [PATCH 04/21] fix: drop the spending balance after a full spark withdrawal --- .../java/to/bitkit/repositories/SparkRepo.kt | 12 +++++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 27 +++++++++++++++++++ changelog.d/next/0000.fixed.md | 2 +- 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 112d8e4b8a..769473139c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -121,6 +121,10 @@ class SparkRepo @Inject constructor( @Volatile private var withdrawalFailedAtSecs: ULong? = null + /** Whether a withdrawal moved the whole balance, so a read of 0 is real until Spark reads a balance again. */ + @Volatile + private var withdrewAll = false + /** Deposits this app broadcast that Spark hasn't listed yet, by txid, so they show as pending at once. */ private val broadcastDeposits = ConcurrentHashMap() @@ -212,6 +216,7 @@ class SparkRepo @Inject constructor( preparedWithdrawal = null withdrawalTxids.clear() withdrawalFailedAtSecs = null + withdrewAll = false broadcastDeposits.clear() sendsRecordedWithoutFee.clear() unsavedPayments.clear() @@ -570,6 +575,7 @@ class SparkRepo @Inject constructor( Unit }.onSuccess { withdrawalFailedAtSecs = null + withdrewAll = true runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after its withdrawal", it, context = TAG) } }.onFailure { @@ -730,13 +736,14 @@ class SparkRepo @Inject constructor( val failedAt = withdrawalFailedAtSecs val hasSyncedSince = failedAt != null && info.lastSyncError == null && (info.lastSyncedAt ?: 0uL) > failedAt if (info.balanceSats > 0uL || hasSyncedSince) withdrawalFailedAtSecs = null + withdrewAll = withdrewAll && info.balanceSats == 0uL val isStale = withdrawalFailedAtSecs != null || info.lastSyncError != null _state.update { it.copy( isReady = true, balanceSats = info.balanceSats, keptBalanceSats = it.shownBalanceSats.takeIf { kept -> - info.balanceSats == 0uL && isStale && kept > 0uL + info.balanceSats == 0uL && isStale && !withdrewAll && kept > 0uL }, pendingDepositSats = pending.sumOf { deposit -> deposit.amountSats }, deposits = (pending + claimed).toImmutableList(), @@ -1241,7 +1248,8 @@ data class SparkState( val balanceSats: ULong = 0uL, /** * The balance shown while Spark reads 0 after a failed withdrawal or a failed sync, with the funds likely still - * there; null once Spark reads a balance again or syncs after the failure. Never offered to a send. + * there; null once Spark reads a balance again or syncs after the failure, and after a full withdrawal, whose 0 is + * real. Never offered to a send. */ val keptBalanceSats: ULong? = null, /** Deposits seen on-chain that Spark claims into [balanceSats] after 3 confirmations. */ diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 8fb2525ffc..fc147e052e 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1101,6 +1101,33 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(0uL, sut.state.value.sendableSats, "a send was offered from the kept balance") } + @Test + fun `a zero read after a full withdrawal clears the balance even while spark's sync fails`() = test { + val staleZero = info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + var read = info(10_000uL) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenAnswer { read } + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } + .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) + whenever { sparkService.send(any()) }.thenAnswer { + read = staleZero + sentPayment(fees = 500) + } + val sut = createSut() + sut.refreshState().getOrThrow() + + sut.withdrawAll(ADDRESS, confirmedFeeSats = 500uL).getOrThrow() + sut.refreshState().getOrThrow() + + assertEquals(0uL, sut.state.value.shownBalanceSats, "the withdrawn balance stayed shown") + + read = info(2_000uL) + sut.refreshState().getOrThrow() + read = staleZero + sut.refreshState().getOrThrow() + assertEquals(2_000uL, sut.state.value.shownBalanceSats, "a stale zero after new funds hid them") + } + @Test fun `a synced read after a failed withdrawal clears the kept balance even when it reads zero`() = test { whenever(sparkService.isConnected).thenReturn(true) diff --git a/changelog.d/next/0000.fixed.md b/changelog.d/next/0000.fixed.md index 2689a597bc..9d65523bea 100644 --- a/changelog.d/next/0000.fixed.md +++ b/changelog.d/next/0000.fixed.md @@ -1 +1 @@ -Bitkit no longer pays a Lightning invoice again over its channels right after a wallet restore, or sends a payment request's payment after its deadline has passed. +Fixed Lightning payments around Spark: no repeat payment over channels right after a restore or past a payment request's deadline, Spark pays while the node is down, and Spending clears after moving the whole balance to Savings. From 39a931771da460f225ca284fbddaf0fe021e8ca6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:57:00 +0100 Subject: [PATCH 05/21] fix: hold pre-restore invoices until the node lists its sends --- .../main/java/to/bitkit/data/CacheStore.kt | 15 +++++ .../java/to/bitkit/repositories/BackupRepo.kt | 2 +- .../to/bitkit/repositories/LightningRepo.kt | 19 ++++-- .../to/bitkit/repositories/BackupRepoTest.kt | 5 +- .../bitkit/repositories/LightningRepoTest.kt | 61 +++++++++++++++++++ 5 files changed, 95 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index df981552c7..976ac63478 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -224,6 +224,16 @@ class CacheStore internal constructor( } } + /** After a restore, keeps [paymentHashes], the node's pending and paid sends from its own list, once. */ + suspend fun seedRestoredLdkSendHashes(paymentHashes: List) { + if (store.data.first().ldkHistoryUnseededSince == null) return + store.updateData { data -> + if (data.ldkHistoryUnseededSince == null) return@updateData data + val seeded = paymentHashes.map { it.lowercase() }.distinct() - data.ldkSendHashes.toSet() + data.copy(ldkSendHashes = seeded + data.ldkSendHashes, ldkHistoryUnseededSince = null) + } + } + /** * 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 @@ -342,6 +352,11 @@ data class AppCacheData( * invoices created before it. Null on an install that was never restored, whose kept hashes are complete. */ val sparkHistoryUnseededSince: Long? = null, + /** + * When a metadata restore brought back [ldkSendHashes], in epoch seconds, until the node's own list fills them: + * while the node can't list its payments, Spark holds off invoices created before it. Null when never restored. + */ + val ldkHistoryUnseededSince: Long? = null, ) { fun isContactDetached(activityId: String, walletId: String): Boolean = scopedActivityId(walletId, activityId) in detachedActivityContacts diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index f580467ede..0a5a2ba9b3 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1208,7 +1208,7 @@ class BackupRepo @Inject constructor( cleanCache.copy( backupStatuses = it.backupStatuses, sparkHistoryUnseededSince = restoredAt, - ldkSendHashesSeeded = false, + ldkHistoryUnseededSince = restoredAt, ) } Logger.debug("Restored caches: ${jsonLogOf(parsed.cache.copy(cachedRates = emptyList()))}", TAG) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 63a9a70a51..2cf3b4e5f2 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1575,7 +1575,8 @@ class LightningRepo @Inject constructor( * The node's pending or paid send of [bolt11]. While the node can't list its payments (stopped or not started yet), * a send it started for the invoice may be live or paid, and its event may never come, so the node not started yet * is thrown rather than a Pending nothing resolves. Before the node first listed its payments, the sends it made - * earlier are unknown, so the same is thrown. + * earlier are unknown, so the same is thrown, as it is after a restore, until the node lists them, for an invoice + * created before the restore. */ private suspend fun earlierNodeSend(bolt11: String, paymentHash: String?): EarlierSend? { val key = ldkSendKey(bolt11, paymentHash) @@ -1592,6 +1593,12 @@ class LightningRepo @Inject constructor( Logger.warn("Refused a Spark send until the node lists its earlier payments once", context = TAG) throw ServiceError.NodeNotStarted() } + // Restored hashes can lack a send the node made before the restore, never one of a newer invoice. + val unseededSince = cache.ldkHistoryUnseededSince + if (unseededSince != null && (invoiceCreatedAt(bolt11) ?: 0L) < unseededSince) { + Logger.warn("Refused a Spark send until the node lists its payments since the restore", context = TAG) + throw ServiceError.NodeNotStarted() + } return null } val send = payments.firstOrNull { @@ -1718,7 +1725,9 @@ class LightningRepo @Inject constructor( ) { val outbound = payments.filter { it.direction == PaymentDirection.OUTBOUND } val sends = outbound.filter { it.status != PaymentStatus.FAILED }.sortedBy { it.latestUpdateTimestamp } - cacheStore.seedLdkSendHashes(sends.mapNotNull { (it.kind as? PaymentKind.Bolt11)?.hash }) + val sendHashes = sends.mapNotNull { (it.kind as? PaymentKind.Bolt11)?.hash } + cacheStore.seedLdkSendHashes(sendHashes) + cacheStore.seedRestoredLdkSendHashes(sendHashes) val hashes = { status: PaymentStatus -> outbound.filter { it.status == status } .mapNotNullTo(mutableSetOf()) { (it.kind as? PaymentKind.Bolt11)?.hash?.lowercase() } @@ -1739,8 +1748,10 @@ class LightningRepo @Inject constructor( .coerceAtMost(Long.MAX_VALUE.toULong()).toLong() }.getOrNull() - private fun invoiceCreatedAt(bolt11: String): Long? = runCatching { - Bolt11Invoice.fromStr(bolt11).secondsSinceEpoch().coerceAtMost(Long.MAX_VALUE.toULong()).toLong() + /** When [bolt11] was created, in epoch seconds, or null when it can't be decoded. */ + private suspend fun invoiceCreatedAt(bolt11: String): Long? = runSuspendCatching { + (coreService.decode(bolt11) as? Scanner.Lightning)?.invoice?.timestampSeconds + ?.coerceAtMost(Long.MAX_VALUE.toULong())?.toLong() }.getOrNull() /** The payment hash a node send is kept under, or the invoice itself when it can't be parsed. */ diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 81f79f590f..ff69f2453b 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -1849,7 +1849,7 @@ class BackupRepoTest : BaseUnitTest() { } @Test - fun `a metadata restore leaves the node's backed-up send hashes for its own list to seed`() = test { + fun `a metadata restore holds older invoices until the node lists its own sends`() = test { val publicAddress = "bcrt1qpublic" stubPublicAddressRestore(publicAddress) stubMetadataRestore( @@ -1866,7 +1866,8 @@ class BackupRepoTest : BaseUnitTest() { sut.performFullRestoreFromLatestBackup().getOrThrow() assertEquals(listOf("hash"), cacheData.value.ldkSendHashes) - assertFalse(cacheData.value.ldkSendHashesSeeded) + assertTrue(cacheData.value.ldkSendHashesSeeded) + assertNotNull(cacheData.value.ldkHistoryUnseededSince) } @Test diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 888909b361..b1b3548478 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -157,6 +157,7 @@ class LightningRepoTest : BaseUnitTest() { private val probePaymentB = "probe-payment-b" private val probeHashA = "probe-hash-a" private val probeHashB = "probe-hash-b" + private val restoredAt = 1_800_000_000L private val probeNodeId = "02abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdef12" @Before @@ -1347,6 +1348,66 @@ class LightningRepoTest : BaseUnitTest() { assertEquals("hash", sut.payInvoice("bolt11", 1_000uL).getOrThrow()) } + @Test + fun `spark refuses an invoice from before the restore while the node hasn't listed since it`() = test { + startNodeForTesting() + restoredCacheWithInvoiceAt(restoredAt - 60) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + + assertIs(sut.payInvoice("bolt11", 1_000uL).exceptionOrNull()) + whenever(coreService.decode("bolt11")).thenThrow(IllegalStateException("undecodable")) + assertIs(sut.payInvoice("bolt11", 1_000uL).exceptionOrNull()) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `spark pays an invoice from after the restore while the node is down`() = test { + startNodeForTesting() + restoredCacheWithInvoiceAt(restoredAt + 60) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + + assertEquals("hash", sut.payInvoice("bolt11", 1_000uL).getOrThrow()) + } + + @Test + fun `spark is never held on an install that was never restored`() = test { + startNodeForTesting() + whenever(coreService.decode("bolt11")) + .thenReturn(Scanner.Lightning(lightningInvoice("bolt11").copy(timestampSeconds = 1uL))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + + assertEquals("hash", sut.payInvoice("bolt11", 1_000uL).getOrThrow()) + } + + @Test + fun `the node's listing after a restore seeds its hashes and ends the hold`() = test { + val cache = AppCacheData(ldkSendHashesSeeded = true, ldkHistoryUnseededSince = restoredAt) + val store = CacheStore(InMemoryDataStore(cache)) + sut = repoWith(store) + whenever(lightningService.listPayments()).thenReturn(listOf(nodeSend("paid", PaymentStatus.SUCCEEDED))) + + startNodeForTesting() + + assertNull(store.data.first().ldkHistoryUnseededSince) + assertEquals(listOf("paid"), store.data.first().ldkSendHashes) + } + + private suspend fun restoredCacheWithInvoiceAt(createdAt: Long) { + val cache = AppCacheData(ldkSendHashesSeeded = true, ldkHistoryUnseededSince = restoredAt) + whenever(cacheStore.data).thenReturn(flowOf(cache)) + whenever(coreService.decode("bolt11")) + .thenReturn(Scanner.Lightning(lightningInvoice("bolt11").copy(timestampSeconds = createdAt.toULong()))) + } + @Test fun `spark waits for the node's first listing when its earlier sends were never kept`() = test { startNodeForTesting() From 45413814d63a5362e0fc8d39ec40e7cc5f0f1f2b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:14:09 +0100 Subject: [PATCH 06/21] chore: name the changelog fragment after this pr --- changelog.d/next/0000.fixed.md | 1 - changelog.d/next/1858.fixed.md | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) delete mode 100644 changelog.d/next/0000.fixed.md create mode 100644 changelog.d/next/1858.fixed.md diff --git a/changelog.d/next/0000.fixed.md b/changelog.d/next/0000.fixed.md deleted file mode 100644 index 9d65523bea..0000000000 --- a/changelog.d/next/0000.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fixed Lightning payments around Spark: no repeat payment over channels right after a restore or past a payment request's deadline, Spark pays while the node is down, and Spending clears after moving the whole balance to Savings. diff --git a/changelog.d/next/1858.fixed.md b/changelog.d/next/1858.fixed.md new file mode 100644 index 0000000000..60b2abbd83 --- /dev/null +++ b/changelog.d/next/1858.fixed.md @@ -0,0 +1 @@ +Fixed a restored wallet paying an invoice again over channels that Spark had already paid. From d8433ef6190ab51a78a11a1dc655c9bfd72f80ac Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:20:00 +0100 Subject: [PATCH 07/21] fix: let confirm and quick pay proceed when spark can pay --- .../to/bitkit/repositories/LightningRepo.kt | 21 +++++++++++++------ .../wallets/send/SendQuickPayScreen.kt | 14 ++++++++++--- .../java/to/bitkit/ui/sheets/SendSheet.kt | 21 +++++++++++++++---- .../bitkit/repositories/LightningRepoTest.kt | 9 ++++++++ .../ui/sheets/SendSheetSyncOverlayTest.kt | 9 ++++++++ 5 files changed, 61 insertions(+), 13 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 2cf3b4e5f2..9655d60e08 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -2756,8 +2756,15 @@ class LightningRepo @Inject constructor( } } - suspend fun estimateRoutingFees(bolt11: String): Result = executeWhenNodeRunning("estimateRoutingFees") { - if (shouldPayWithSpark(bolt11, null)) return@executeWhenNodeRunning sparkRepo.estimateFeeSats(bolt11, null) + suspend fun estimateRoutingFees(bolt11: String): Result { + // Spark quotes without the node, so a payment it makes never waits for the node to run. + if (shouldPayWithSpark(bolt11, null)) return sparkRepo.estimateFeeSats(bolt11, null) + return estimateNodeRoutingFees(bolt11) + } + + private suspend fun estimateNodeRoutingFees(bolt11: String): Result = executeWhenNodeRunning( + "estimateRoutingFees" + ) { Logger.info("Estimating routing fees for bolt11: $bolt11", context = TAG) lightningService.estimateRoutingFees(bolt11).onSuccess { Logger.info("Routing fees estimated: '$it'", context = TAG) @@ -2766,11 +2773,13 @@ class LightningRepo @Inject constructor( } } - suspend fun estimateRoutingFeesForAmount(bolt11: String, amountSats: ULong): Result = + suspend fun estimateRoutingFeesForAmount(bolt11: String, amountSats: ULong): Result { + if (shouldPayWithSpark(bolt11, amountSats)) return sparkRepo.estimateFeeSats(bolt11, amountSats) + return estimateNodeRoutingFeesForAmount(bolt11, amountSats) + } + + private suspend fun estimateNodeRoutingFeesForAmount(bolt11: String, amountSats: ULong): Result = executeWhenNodeRunning("estimateRoutingFeesForAmount") { - if (shouldPayWithSpark(bolt11, amountSats)) { - return@executeWhenNodeRunning sparkRepo.estimateFeeSats(bolt11, amountSats) - } Logger.info("Estimating routing fees for amount: '$amountSats'", context = TAG) lightningService.estimateRoutingFeesForAmount(bolt11, amountSats).onSuccess { Logger.info("Routing fees estimated: '$it'", context = TAG) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendQuickPayScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendQuickPayScreen.kt index c83ca98375..9e0c0c5cb5 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendQuickPayScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendQuickPayScreen.kt @@ -30,6 +30,7 @@ import to.bitkit.ui.scaffold.SheetTopBar import to.bitkit.ui.screens.transfer.components.TransferAnimationView import to.bitkit.ui.shared.modifiers.sheetHeight import to.bitkit.ui.shared.util.gradientBackground +import to.bitkit.ui.sheets.canSendWithoutWaiting import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors import to.bitkit.ui.utils.withAccent @@ -41,6 +42,7 @@ import to.bitkit.viewmodels.QuickPayViewModel fun SendQuickPayScreen( quickPayData: QuickPayData, isRequestActive: Boolean, + canPayWithoutNode: Boolean, onPaymentComplete: (String, Long) -> Unit, onPaymentPending: (String, Long, String) -> Unit, onFallBackToConfirm: () -> Unit, @@ -56,8 +58,14 @@ fun SendQuickPayScreen( onDispose { viewModel.detach(session) } } - LaunchedEffect(quickPayData, lightningState.nodeLifecycleState, isRequestActive) { - if (isRequestActive && lightningState.nodeLifecycleState is NodeLifecycleState.Running) { + // Spark pays a Quick Pay invoice it can cover without the node, so only an otherwise unpayable one waits. + val canPay = canSendWithoutWaiting( + isNodeRunning = lightningState.nodeLifecycleState is NodeLifecycleState.Running, + isHardwareWallet = false, + sparkCanPay = canPayWithoutNode, + ) + LaunchedEffect(quickPayData, canPay, isRequestActive) { + if (isRequestActive && canPay) { viewModel.pay(session, quickPayData) } } @@ -84,7 +92,7 @@ fun SendQuickPayScreen( Content( amount = quickPayData.sats, - nodeLifecycleState = lightningState.nodeLifecycleState, + nodeLifecycleState = if (canPay) NodeLifecycleState.Running else lightningState.nodeLifecycleState, ) } diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index 51a21afd25..fd2c3a9df8 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -99,6 +99,7 @@ import to.bitkit.ui.utils.composableWithDefaultTransitions import to.bitkit.ui.utils.navigationWithDefaultTransitions import to.bitkit.viewmodels.AppViewModel import to.bitkit.viewmodels.LnurlParams +import to.bitkit.viewmodels.QuickPayData import to.bitkit.viewmodels.SendEffect import to.bitkit.viewmodels.SendEvent import to.bitkit.viewmodels.SendMethod @@ -115,6 +116,14 @@ private val CHANNELS_REFRESH_INTERVAL = 1.seconds internal fun sparkCanPayInvoice(payMethod: SendMethod, invoiceSats: ULong?, sparkState: SparkState): Boolean = payMethod == SendMethod.LIGHTNING && invoiceSats != null && invoiceSats > 0uL && sparkState.canSend(invoiceSats) +/** Whether Spark can pay a Quick Pay invoice; an LNURL one still waits for the node. */ +internal fun sparkCanPayQuickPay(data: QuickPayData, sparkState: SparkState): Boolean = + data is QuickPayData.Bolt11 && sparkCanPayInvoice(SendMethod.LIGHTNING, data.sats, sparkState) + +/** Whether a send can go ahead now: the node runs, a hardware wallet signs it, or Spark pays it without the node. */ +internal fun canSendWithoutWaiting(isNodeRunning: Boolean, isHardwareWallet: Boolean, sparkCanPay: Boolean): Boolean = + isNodeRunning || isHardwareWallet || sparkCanPay + /** * A Lightning payment Spark can pay goes ahead without the node. Otherwise the node must run, and with channels a * payment waits for a usable one. With no channels at all there is nothing to sync into, so validation reports the @@ -175,15 +184,15 @@ fun SendSheet( val hasAnyChannels = lightningState.channels.isNotEmpty() val syncNodeVariant = if (hasAnyChannels) SyncNodeVariant.LIGHTNING else SyncNodeVariant.BITCOIN val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle() + val sparkCanPay = sparkCanPayInvoice(sendUiState.payMethod, sendUiState.decodedInvoice?.amountSatoshis, sparkState) val shouldShowSyncOverlay = run { if (preparingRequest != null || sendUiState.paykitUsesUsdt) return@run false if (sendUiState.hardwareWalletId != null) return@run false - val invoiceSats = sendUiState.decodedInvoice?.amountSatoshis waitsForNode( isNodeRunning = lightningState.nodeLifecycleState.isRunning(), hasAnyChannels = hasAnyChannels, hasUsableChannels = lightningState.channels.any { it.isUsable }, - sparkCanPay = sparkCanPayInvoice(sendUiState.payMethod, invoiceSats, sparkState), + sparkCanPay = sparkCanPay, ) } @@ -521,8 +530,11 @@ fun SendSheet( SendConfirmScreen( savedStateHandle = it.savedStateHandle, uiState = uiState, - isNodeRunning = uiState.hardwareWalletId != null || - lightningState.nodeLifecycleState.isRunning(), + isNodeRunning = canSendWithoutWaiting( + isNodeRunning = lightningState.nodeLifecycleState.isRunning(), + isHardwareWallet = uiState.hardwareWalletId != null, + sparkCanPay = sparkCanPay, + ), canAutoStart = !isOffline && !shouldShowSyncOverlay, syncNodeVariant = syncNodeVariant, canGoBack = navController.previousBackStackEntry != null, @@ -700,6 +712,7 @@ fun SendSheet( SendQuickPayScreen( quickPayData = request.data, isRequestActive = quickPayRequest?.id == request.id, + canPayWithoutNode = sparkCanPayQuickPay(request.data, sparkState), onPaymentComplete = { paymentHash, amountWithFee -> appViewModel.onSendSuccess( NewTransactionSheetDetails( diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index b1b3548478..9fdd277342 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -4300,6 +4300,15 @@ class LightningRepoTest : BaseUnitTest() { assertTrue(result.isFailure) } + @Test + fun `a fee estimate spark pays needs no running node`() = test { + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.estimateFeeSats("bolt11", 1_000uL)).thenReturn(Result.success(3uL)) + + assertEquals(3uL, sut.estimateRoutingFeesForAmount("bolt11", 1_000uL).getOrThrow()) + verify(lightningService, never()).estimateRoutingFeesForAmount(any(), any()) + } + @Test fun `estimateRoutingFees should succeed when node is running`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt index d4de062b12..8c6a44719e 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt @@ -2,6 +2,7 @@ package to.bitkit.ui.sheets import org.junit.Test import to.bitkit.repositories.SparkState +import to.bitkit.viewmodels.QuickPayData import to.bitkit.viewmodels.SendMethod import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -18,6 +19,14 @@ class SendSheetSyncOverlayTest { assertFalse(waitsForNode(true, hasAnyChannels = true, hasUsableChannels = false, sparkCanPay = sparkCanPay)) } + @Test + fun `confirm and quick pay go ahead without the node when spark can pay`() { + assertTrue(canSendWithoutWaiting(isNodeRunning = false, isHardwareWallet = false, sparkCanPay = true)) + assertFalse(canSendWithoutWaiting(isNodeRunning = false, isHardwareWallet = false, sparkCanPay = false)) + assertTrue(sparkCanPayQuickPay(QuickPayData.Bolt11(1_000uL, "lnbc1"), funded)) + assertFalse(sparkCanPayQuickPay(QuickPayData.Bolt11(1_000uL, "lnbc1"), funded.copy(isReady = false))) + } + @Test fun `on-chain, amountless and payments spark can't cover still wait for a stopped node`() { val cases = listOf( From 36ef97e7ce713ae58cec98148d08e276d5509e04 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:26:52 +0100 Subject: [PATCH 08/21] fix: hold pre-restore invoices on a restore without metadata --- .../java/to/bitkit/repositories/BackupRepo.kt | 6 ++++++ .../to/bitkit/repositories/BackupRepoTest.kt | 17 ++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 0a5a2ba9b3..e171ca03fd 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1048,6 +1048,12 @@ class BackupRepo @Inject constructor( } connectionSession.replay() prepareUsdtRecoveryRestore() + // Armed before any category, so a restore whose metadata is missing or unreadable holds each rail off + // invoices from before it too, until that rail lists its own sends. + val restoredAt = currentTimeMillis().milliseconds.inWholeSeconds + cacheStore.update { + it.copy(sparkHistoryUnseededSince = restoredAt, ldkHistoryUnseededSince = restoredAt) + } var metadataReceived = false val metadataResult = performRestore(BackupCategory.METADATA, failedCategories) { dataBytes -> metadataReceived = true diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index ff69f2453b..140260590f 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -1848,6 +1848,18 @@ class BackupRepoTest : BaseUnitTest() { assertNotNull(cacheData.value.sparkHistoryUnseededSince) } + @Test + fun `a restore without a metadata backup still holds older invoices on both rails`() = test { + whenever { cacheStore.update(any()) }.thenAnswer { + cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) + } + + sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertNotNull(cacheData.value.sparkHistoryUnseededSince) + assertNotNull(cacheData.value.ldkHistoryUnseededSince) + } + @Test fun `a metadata restore holds older invoices until the node lists its own sends`() = test { val publicAddress = "bcrt1qpublic" @@ -1878,7 +1890,9 @@ class BackupRepoTest : BaseUnitTest() { doAnswer { val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) val updated = transform(cacheData.value) - if (failCacheWrite && updated.backupStatuses == cacheData.value.backupStatuses) { + // The metadata cache write follows the restore's own write of its holds. + val isMetadataWrite = cacheData.value.sparkHistoryUnseededSince != null + if (failCacheWrite && isMetadataWrite && updated.backupStatuses == cacheData.value.backupStatuses) { failCacheWrite = false throw BackupRepoTestError("cache store unavailable") } @@ -1894,6 +1908,7 @@ class BackupRepoTest : BaseUnitTest() { verify(privatePaykitRepo).restoreBackup(null) assertTrue(createReservationRepo(reservationStore).isUnavailableForReusableReceive(publicAddress)) verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) + assertFalse(failCacheWrite, "the metadata cache write never failed") } @Test From da1ddcdd1e9fba7e4b97fc306515fc3c12cded6d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:31:00 +0100 Subject: [PATCH 09/21] fix: keep restored spark sends held while their invoices are valid --- .../main/java/to/bitkit/data/CacheStore.kt | 9 +++-- .../java/to/bitkit/repositories/SparkRepo.kt | 17 ++++++--- .../java/to/bitkit/services/SparkService.kt | 5 +++ .../to/bitkit/repositories/SparkRepoTest.kt | 36 +++++++++++++++++++ 4 files changed, 60 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 976ac63478..323ae61c89 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -211,14 +211,19 @@ class CacheStore internal constructor( } } - /** After a restore, keeps [paymentHashes], Spark's pending and paid sends from its synced list, once. */ - suspend fun seedSparkSendHashes(paymentHashes: List) { + /** + * After a restore, keeps [paymentHashes], Spark's pending and paid sends from its synced list, once, with their + * invoices' [expiries] in epoch seconds where known, so a still-valid one stays held and outlasts the cap. + */ + suspend fun seedSparkSendHashes(paymentHashes: List, expiries: Map = emptyMap()) { if (store.data.first().sparkHistoryUnseededSince == null) return store.updateData { data -> if (data.sparkHistoryUnseededSince == null) return@updateData data val seeded = paymentHashes.map { it.lowercase() }.distinct() - data.sparkSendHashes.toSet() + val seededExpiries = expiries.mapKeys { it.key.lowercase() }.filterKeys { it in seeded } data.copy( sparkSendHashes = seeded + data.sparkSendHashes, + sparkSendExpiries = seededExpiries + data.sparkSendExpiries, sparkHistoryUnseededSince = null, ) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 769473139c..e73d1c4632 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1032,12 +1032,19 @@ class SparkRepo @Inject constructor( } /** Keeps Spark's pending and paid sends once, from a list read after it synced, so a restart holds the node off. */ - private suspend fun seedSendHashes(payments: List) = cacheStore.seedSparkSendHashes( - payments - .filter { it.status != PaymentStatus.FAILED } + private suspend fun seedSendHashes(payments: List) { + if (cacheStore.data.first().sparkHistoryUnseededSince == null) return + val sends = payments + .filter { it.status != PaymentStatus.FAILED && it.sendHash() != null } .sortedBy { it.timestamp } - .mapNotNull { it.sendHash() }, - ) + // A seeded send keeps its invoice's expiry, so Spark holds it while valid and the cap never drops it early. + val expiries = sends.mapNotNull { send -> + val invoice = (send.details as PaymentDetails.Lightning).invoice + val expiresAt = runSuspendCatching { sparkService.invoiceExpiresAt(invoice) }.getOrNull() + expiresAt?.let { requireNotNull(send.sendHash()) to it.coerceAtMost(Long.MAX_VALUE.toULong()).toLong() } + }.toMap() + cacheStore.seedSparkSendHashes(sends.mapNotNull { it.sendHash() }, expiries) + } /** Records every Spark payment, returning whether all were saved, so a failed write leaves the sync to redo. */ private suspend fun syncActivities(): Boolean { diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 3ade9b137e..1c9e4adf67 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -14,6 +14,7 @@ import breez_sdk_spark.GetInfoRequest import breez_sdk_spark.GetInfoResponse import breez_sdk_spark.ImportUnilateralExitStateRequest import breez_sdk_spark.ImportUnilateralExitStateResponse +import breez_sdk_spark.InputType import breez_sdk_spark.ListPaymentsRequest import breez_sdk_spark.ListUnclaimedDepositsRequest import breez_sdk_spark.MaxFee @@ -272,6 +273,10 @@ class SparkService @Inject constructor( suspend fun listPayments(): List = requireSdk().listPayments(ListPaymentsRequest()).payments + /** When [bolt11] expires, in epoch seconds, read by the SDK's own parser; null when it isn't a BOLT11 invoice. */ + suspend fun invoiceExpiresAt(bolt11: String): ULong? = + (requireSdk().parse(bolt11) as? InputType.Bolt11Invoice)?.v1?.let { it.timestamp + it.expiry } + /** Exports what a unilateral exit needs if the Spark operators stop cooperating; it can reach several MB. */ suspend fun exportExitState(): String = requireSdk().exportUnilateralExitState().exitState diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index fc147e052e..fd25323903 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -253,6 +253,42 @@ class SparkRepoTest : BaseUnitTest() { assertNull(restarted.earlierLightningSend("lnbc1280n1other", "other", invoiceCreatedAt = 1L)) } + @Test + fun `a send spark's list seeded after a restore is not sent again by spark after an unsynced restart`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkHistoryUnseededSince = now.epochSeconds)), clock) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.listPayments() }.thenReturn(listOf(sentPayment(fees = 2))) + whenever { sparkService.invoiceExpiresAt("lnbc1280n1send") }.thenReturn(now.epochSeconds.toULong() + 3_600uL) + createSut(store).start(0).getOrThrow() + assertEquals(listOf("hash"), store.data.first().sparkSendHashes) + + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = null)) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + val restarted = createSut(store) + restarted.start(0).getOrThrow() + + restarted.payInvoice("lnbc1280n1send", 128uL) + + verify(sparkService, never()).send(any()) + } + + @Test + fun `restored spark sends with valid invoices survive the hash cap`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkHistoryUnseededSince = now.epochSeconds)), clock) + whenever(sparkService.isConnected).thenReturn(true) + val sends = (0..MAX_SPARK_SEND_HASHES).map { + sentPayment(fees = 2).copy(id = "send$it", timestamp = it.toULong()).withHash("paid$it") + } + whenever { sparkService.listPayments() }.thenReturn(sends) + whenever { sparkService.invoiceExpiresAt(any()) }.thenReturn(now.epochSeconds.toULong() + 3_600uL) + + createSut(store).start(0).getOrThrow() + + assertTrue("paid0" in store.data.first().sparkSendHashes, "the cap dropped a still-valid paid invoice") + } + @Test fun `a list read before spark's first sync seeds no hashes`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData(sparkHistoryUnseededSince = now.epochSeconds)), clock) From f6816892b82b5c482b3bf1b0da31b484ac24d655 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:54:14 +0100 Subject: [PATCH 10/21] fix: keep a full withdrawal's zero balance until a later sync shows funds --- .../java/to/bitkit/repositories/SparkRepo.kt | 18 ++++++---- .../to/bitkit/repositories/SparkRepoTest.kt | 34 ++++++++++++++++++- 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index e73d1c4632..da94b69cc1 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -121,9 +121,12 @@ class SparkRepo @Inject constructor( @Volatile private var withdrawalFailedAtSecs: ULong? = null - /** Whether a withdrawal moved the whole balance, so a read of 0 is real until Spark reads a balance again. */ + /** + * When a withdrawal moved the whole balance, in epoch seconds, so a read of 0 is real until a sync after it reads + * a balance again. A refresh that read its balance before the withdrawal can't clear it. + */ @Volatile - private var withdrewAll = false + private var withdrewAllAtSecs: ULong? = null /** Deposits this app broadcast that Spark hasn't listed yet, by txid, so they show as pending at once. */ private val broadcastDeposits = ConcurrentHashMap() @@ -216,7 +219,7 @@ class SparkRepo @Inject constructor( preparedWithdrawal = null withdrawalTxids.clear() withdrawalFailedAtSecs = null - withdrewAll = false + withdrewAllAtSecs = null broadcastDeposits.clear() sendsRecordedWithoutFee.clear() unsavedPayments.clear() @@ -575,7 +578,7 @@ class SparkRepo @Inject constructor( Unit }.onSuccess { withdrawalFailedAtSecs = null - withdrewAll = true + withdrewAllAtSecs = clock.now().epochSeconds.toULong() runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after its withdrawal", it, context = TAG) } }.onFailure { @@ -736,14 +739,17 @@ class SparkRepo @Inject constructor( val failedAt = withdrawalFailedAtSecs val hasSyncedSince = failedAt != null && info.lastSyncError == null && (info.lastSyncedAt ?: 0uL) > failedAt if (info.balanceSats > 0uL || hasSyncedSince) withdrawalFailedAtSecs = null - withdrewAll = withdrewAll && info.balanceSats == 0uL + val withdrewAllAt = withdrewAllAtSecs + if (withdrewAllAt != null && info.balanceSats > 0uL && (info.lastSyncedAt ?: 0uL) > withdrewAllAt) { + withdrewAllAtSecs = null + } val isStale = withdrawalFailedAtSecs != null || info.lastSyncError != null _state.update { it.copy( isReady = true, balanceSats = info.balanceSats, keptBalanceSats = it.shownBalanceSats.takeIf { kept -> - info.balanceSats == 0uL && isStale && !withdrewAll && kept > 0uL + info.balanceSats == 0uL && isStale && withdrewAllAtSecs == null && kept > 0uL }, pendingDepositSats = pending.sumOf { deposit -> deposit.amountSats }, deposits = (pending + claimed).toImmutableList(), diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index fd25323903..e25ab102eb 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1157,13 +1157,45 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(0uL, sut.state.value.shownBalanceSats, "the withdrawn balance stayed shown") - read = info(2_000uL) + // New funds show on a sync after the withdrawal. + read = info(2_000uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) sut.refreshState().getOrThrow() read = staleZero sut.refreshState().getOrThrow() assertEquals(2_000uL, sut.state.value.shownBalanceSats, "a stale zero after new funds hid them") } + @Test + fun `a refresh that read the balance before a full withdrawal never brings it back`() = test { + val staleZero = info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + var read = info(10_000uL) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenAnswer { read } + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } + .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) + whenever { sparkService.send(any()) }.thenAnswer { + read = staleZero + sentPayment(fees = 500) + } + val sut = createSut() + sut.refreshState().getOrThrow() + // A refresh reads the old balance, then waits on the network while the withdrawal goes out. + val deposits = CompletableDeferred>() + var depositReads = 0 + whenever { sparkService.listUnclaimedDeposits() }.doSuspendableAnswer { + if (depositReads++ == 0) deposits.await() else emptyList() + } + val olderRefresh = async { sut.refreshState() } + runCurrent() + val withdrawal = async { sut.withdrawAll(ADDRESS, confirmedFeeSats = 500uL) } + runCurrent() + deposits.complete(emptyList()) + olderRefresh.await().getOrThrow() + withdrawal.await().getOrThrow() + + assertEquals(0uL, sut.state.value.shownBalanceSats, "the withdrawn balance came back") + } + @Test fun `a synced read after a failed withdrawal clears the kept balance even when it reads zero`() = test { whenever(sparkService.isConnected).thenReturn(true) From b4bbcc7f9e7cd89536ddc73ee7b066fbcbcae0d7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:56:36 +0100 Subject: [PATCH 11/21] perf: decode a node send's invoice only during a restore hold --- .../main/java/to/bitkit/repositories/LightningRepo.kt | 4 +++- .../java/to/bitkit/repositories/LightningRepoTest.kt | 9 +++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 9655d60e08..03ac9e3925 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1661,7 +1661,9 @@ class LightningRepo @Inject constructor( requireWalletRestoreComplete() // Read before the checks, so a Spark send admitted after them refuses this one at submission. val sparkRecordsBefore = sparkRepo.sendRecordMark() - sparkRepo.earlierLightningSend(bolt11, paymentHash, invoiceCreatedAt(bolt11)) + // Only a restore hold needs the invoice's date. + val createdAt = cacheStore.data.first().sparkHistoryUnseededSince?.let { invoiceCreatedAt(bolt11) } + sparkRepo.earlierLightningSend(bolt11, paymentHash, createdAt) ?.let { return@executeWhenNodeRunning it.toResult() } if (!onBeforeSend()) return@executeWhenNodeRunning Result.failure(PaymentAbortedBeforeSend()) requireWalletRestoreComplete() diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 9fdd277342..4bdee90058 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -2069,6 +2069,15 @@ class LightningRepoTest : BaseUnitTest() { assertEquals(testPaymentId, result.getOrNull()) } + @Test + fun `a node send outside a restore hold leaves the invoice undecoded`() = test { + startNodeForTesting() + whenever(lightningService.send("bolt11", 1000uL)).thenReturn("payment-id") + + assertEquals("payment-id", sut.payInvoice("bolt11", 1000uL).getOrThrow()) + verify(coreService, never()).decode(any()) + } + @Test fun `payInvoice forwards the payment deadline after final authorization`() = test { startNodeForTesting() From f4836b992387888cfb9241bfaac5abf08f6cf1fa Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 16:04:01 +0100 Subject: [PATCH 12/21] chore: drop the changelog entry for an unreleased spark bug --- changelog.d/next/1858.fixed.md | 1 - 1 file changed, 1 deletion(-) delete mode 100644 changelog.d/next/1858.fixed.md diff --git a/changelog.d/next/1858.fixed.md b/changelog.d/next/1858.fixed.md deleted file mode 100644 index 60b2abbd83..0000000000 --- a/changelog.d/next/1858.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fixed a restored wallet paying an invoice again over channels that Spark had already paid. From 694e3b8a5de52a57f2beb3f54bb6bf69315ceadd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 16:48:16 +0100 Subject: [PATCH 13/21] fix: give a kept spark send its invoice expiry when restored sends are seeded --- app/src/main/java/to/bitkit/data/CacheStore.kt | 5 +++-- .../java/to/bitkit/repositories/SparkRepoTest.kt | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 323ae61c89..c43f8f4052 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -220,10 +220,11 @@ class CacheStore internal constructor( store.updateData { data -> if (data.sparkHistoryUnseededSince == null) return@updateData data val seeded = paymentHashes.map { it.lowercase() }.distinct() - data.sparkSendHashes.toSet() - val seededExpiries = expiries.mapKeys { it.key.lowercase() }.filterKeys { it in seeded } + // A kept hash without an expiry gets its invoice's, so the cap can't drop it while valid; a set one stays. + val listedExpiries = expiries.mapKeys { it.key.lowercase() } data.copy( sparkSendHashes = seeded + data.sparkSendHashes, - sparkSendExpiries = seededExpiries + data.sparkSendExpiries, + sparkSendExpiries = listedExpiries + data.sparkSendExpiries, sparkHistoryUnseededSince = null, ) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index e25ab102eb..5e789ed719 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -289,6 +289,22 @@ class SparkRepoTest : BaseUnitTest() { assertTrue("paid0" in store.data.first().sparkSendHashes, "the cap dropped a still-valid paid invoice") } + @Test + fun `a kept spark send without an expiry gets its invoice's expiry when seeded`() = test { + val cache = AppCacheData(sparkHistoryUnseededSince = now.epochSeconds, sparkSendHashes = listOf("paid0")) + val store = CacheStore(InMemoryDataStore(cache), clock) + whenever(sparkService.isConnected).thenReturn(true) + val sends = (0 until MAX_SPARK_SEND_HASHES + 1).map { + sentPayment(fees = 2).copy(id = "send$it", timestamp = it.toULong()).withHash("paid$it") + } + whenever { sparkService.listPayments() }.thenReturn(sends) + whenever { sparkService.invoiceExpiresAt(any()) }.thenReturn(now.epochSeconds.toULong() + 3_600uL) + + createSut(store).start(0).getOrThrow() + + assertTrue("paid0" in store.data.first().sparkSendHashes, "the cap dropped a kept still-valid paid invoice") + } + @Test fun `a list read before spark's first sync seeds no hashes`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData(sparkHistoryUnseededSince = now.epochSeconds)), clock) From cf2c10d8aa294bae362dda2272c0f8af77e3c760 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 16:50:38 +0100 Subject: [PATCH 14/21] fix: saturate a spark invoice's expiry instead of wrapping --- app/src/main/java/to/bitkit/services/SparkService.kt | 5 ++++- app/src/test/java/to/bitkit/services/SparkServiceTest.kt | 7 +++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 1c9e4adf67..43bfe93c7a 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -62,6 +62,9 @@ class SparkService @Inject constructor( private val keychain: Keychain, ) { companion object { + /** When an invoice made at [timestamp] with [expiry] seconds to live expires, in epoch seconds. */ + internal fun invoiceExpiresAt(timestamp: ULong, expiry: ULong): ULong = timestamp.safe() + expiry.safe() + private const val TAG = "SparkService" /** @@ -275,7 +278,7 @@ class SparkService @Inject constructor( /** When [bolt11] expires, in epoch seconds, read by the SDK's own parser; null when it isn't a BOLT11 invoice. */ suspend fun invoiceExpiresAt(bolt11: String): ULong? = - (requireSdk().parse(bolt11) as? InputType.Bolt11Invoice)?.v1?.let { it.timestamp + it.expiry } + (requireSdk().parse(bolt11) as? InputType.Bolt11Invoice)?.v1?.let { invoiceExpiresAt(it.timestamp, it.expiry) } /** Exports what a unilateral exit needs if the Spark operators stop cooperating; it can reach several MB. */ suspend fun exportExitState(): String = requireSdk().exportUnilateralExitState().exitState diff --git a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt index 04c5685ed4..e5e88d9be5 100644 --- a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt @@ -56,6 +56,13 @@ class SparkServiceTest { assertEquals(true, options.preferSpark) } + @Test + fun `an invoice expiry past the largest time stays at the largest time`() { + val farOff = SparkService.invoiceExpiresAt(timestamp = ULong.MAX_VALUE - 1uL, expiry = 3_600uL) + assertEquals(ULong.MAX_VALUE, farOff) + assertEquals(1_800_003_600uL, SparkService.invoiceExpiresAt(timestamp = 1_800_000_000uL, expiry = 3_600uL)) + } + @Test fun `claim fee estimate covers the claims seen on mainnet`() { // Mainnet claims so far took 198 and 297 sats; the cap at 1 sat/vB stays above both. From a0e995a437a592092135ee3c11391da77960b58c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 17:26:39 +0100 Subject: [PATCH 15/21] fix: refuse a node send of a valid pre-restore invoice spark hasn't listed --- .../main/java/to/bitkit/data/CacheStore.kt | 5 ++ .../to/bitkit/ext/PaymentFailureReasonExt.kt | 4 ++ .../java/to/bitkit/repositories/BackupRepo.kt | 7 ++- .../to/bitkit/repositories/LightningRepo.kt | 22 ++++--- .../java/to/bitkit/repositories/SparkRepo.kt | 48 +++++++++++++-- .../java/to/bitkit/services/SparkService.kt | 3 + app/src/main/res/values/strings.xml | 1 + .../bitkit/ext/PaymentFailureReasonExtTest.kt | 11 ++++ .../to/bitkit/repositories/BackupRepoTest.kt | 2 + .../to/bitkit/repositories/SparkRepoTest.kt | 59 ++++++++++++++----- .../test/java/to/bitkit/test/IdleSparkRepo.kt | 1 + 11 files changed, 135 insertions(+), 28 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index c43f8f4052..a835e445af 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -363,6 +363,11 @@ data class AppCacheData( * while the node can't list its payments, Spark holds off invoices created before it. Null when never restored. */ val ldkHistoryUnseededSince: Long? = null, + /** + * When the wallet was restored, in epoch seconds. Spark's list can lack a send it made before then even after a + * sync, so for a while after it the node refuses a still-valid invoice created before it that Spark hasn't listed. + */ + val sparkRestoredAt: Long? = null, ) { fun isContactDetached(activityId: String, walletId: String): Boolean = scopedActivityId(walletId, activityId) in detachedActivityContacts diff --git a/app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt b/app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt index 6ac4dc62ae..fa3790a8aa 100644 --- a/app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt +++ b/app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt @@ -51,6 +51,10 @@ fun Throwable.toSendFailureMessage(context: Context): String { val fallbackMessage = context.getString(R.string.wallet__payment_failed_description) val rawMessage = message?.trim().orEmpty() + if (generateSequence(this) { it.cause }.any { it is SparkError.RestoredInvoiceUnverified }) { + return context.getString(R.string.wallet__payment_restored_invoice) + } + // Spark and its SDK speak in English developer messages; they go to the log, the user gets the existing copy. if (this is LdkError || this is SparkError || this is SdkException || rawMessage.isBlank() || rawMessage.looksInternalPaymentError() diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index e171ca03fd..d6f35e9468 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1052,7 +1052,11 @@ class BackupRepo @Inject constructor( // invoices from before it too, until that rail lists its own sends. val restoredAt = currentTimeMillis().milliseconds.inWholeSeconds cacheStore.update { - it.copy(sparkHistoryUnseededSince = restoredAt, ldkHistoryUnseededSince = restoredAt) + it.copy( + sparkHistoryUnseededSince = restoredAt, + ldkHistoryUnseededSince = restoredAt, + sparkRestoredAt = restoredAt, + ) } var metadataReceived = false val metadataResult = performRestore(BackupCategory.METADATA, failedCategories) { dataBytes -> @@ -1215,6 +1219,7 @@ class BackupRepo @Inject constructor( backupStatuses = it.backupStatuses, sparkHistoryUnseededSince = restoredAt, ldkHistoryUnseededSince = restoredAt, + sparkRestoredAt = restoredAt, ) } Logger.debug("Restored caches: ${jsonLogOf(parsed.cache.copy(cachedRates = emptyList()))}", TAG) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 03ac9e3925..a3231b62d6 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1661,9 +1661,14 @@ class LightningRepo @Inject constructor( requireWalletRestoreComplete() // Read before the checks, so a Spark send admitted after them refuses this one at submission. val sparkRecordsBefore = sparkRepo.sendRecordMark() - // Only a restore hold needs the invoice's date. - val createdAt = cacheStore.data.first().sparkHistoryUnseededSince?.let { invoiceCreatedAt(bolt11) } - sparkRepo.earlierLightningSend(bolt11, paymentHash, createdAt) + // Only a restore hold needs the invoice's times. + val invoice = if (sparkRepo.holdsRestoredInvoices()) decodedInvoice(bolt11) else null + sparkRepo.earlierLightningSend( + bolt11, + paymentHash, + invoice?.timestampSeconds?.toEpochSeconds(), + invoice?.let { (it.timestampSeconds.safe() + it.expirySeconds.safe()).toEpochSeconds() }, + ) ?.let { return@executeWhenNodeRunning it.toResult() } if (!onBeforeSend()) return@executeWhenNodeRunning Result.failure(PaymentAbortedBeforeSend()) requireWalletRestoreComplete() @@ -1751,10 +1756,13 @@ class LightningRepo @Inject constructor( }.getOrNull() /** When [bolt11] was created, in epoch seconds, or null when it can't be decoded. */ - private suspend fun invoiceCreatedAt(bolt11: String): Long? = runSuspendCatching { - (coreService.decode(bolt11) as? Scanner.Lightning)?.invoice?.timestampSeconds - ?.coerceAtMost(Long.MAX_VALUE.toULong())?.toLong() - }.getOrNull() + private suspend fun invoiceCreatedAt(bolt11: String): Long? = + decodedInvoice(bolt11)?.timestampSeconds?.toEpochSeconds() + + private suspend fun decodedInvoice(bolt11: String) = + runSuspendCatching { (coreService.decode(bolt11) as? Scanner.Lightning)?.invoice }.getOrNull() + + private fun ULong.toEpochSeconds(): Long = coerceAtMost(Long.MAX_VALUE.toULong()).toLong() /** The payment hash a node send is kept under, or the invoice itself when it can't be parsed. */ private fun ldkSendKey(bolt11: String, paymentHash: String?): String = (paymentHash ?: bolt11).lowercase() diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index da94b69cc1..0a64be8bc2 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -104,6 +104,13 @@ class SparkRepo @Inject constructor( /** Seconds a withdrawal quote must still hold to be reused, so it can't expire mid-send. */ private const val QUOTE_EXPIRY_MARGIN_SECS = 30uL + + /** + * How long after a restore the node refuses a still-valid invoice created before it that Spark hasn't listed. + * Spark can report a sync while its payment history failed to sync, so its list alone can't clear one. A week + * outlasts the default expiry of common wallets (an hour to a day, CLN's a week). + */ + internal const val RESTORE_HOLD_SECS = 7 * 24 * 60 * 60L } private val scope = appScope(bgDispatcher, TAG) @@ -893,12 +900,15 @@ class SparkRepo @Inject constructor( * While Spark can't list its payments, a send it started for [paymentHash] counts as pending, since it may be live, * and after a restore, until Spark's synced list seeds the kept hashes, [SparkError.SendRefused] is thrown for an * invoice created before the restore ([invoiceCreatedAt] in epoch seconds, null when unknown), as the restored - * hashes can lack a send Spark made of it. + * hashes can lack a send Spark made of it. For [RESTORE_HOLD_SECS] after a restore, an invoice created before it + * and not yet expired ([invoiceExpiresAt], null when unknown) that Spark hasn't listed is refused with + * [SparkError.RestoredInvoiceUnverified] whatever Spark listed, as Spark's list can lack its sends after a sync. */ suspend fun earlierLightningSend( bolt11: String, paymentHash: String?, invoiceCreatedAt: Long? = null, + invoiceExpiresAt: Long? = null, ): EarlierSend? = withContext(bgDispatcher) { val recordsBefore = sendRecords.get() @@ -930,8 +940,9 @@ class SparkRepo @Inject constructor( val unseededSince = cacheStore.data.first().sparkHistoryUnseededSince if (sparkService.isSupported && unseededSince != null && (invoiceCreatedAt ?: 0L) < unseededSince) { Logger.warn("Refused a node send until Spark lists its earlier sends once", context = TAG) - throw SparkError.SendRefused("Spark hasn't listed its earlier sends yet") + throw SparkError.RestoredInvoiceUnverified() } + refuseUnverifiedRestoredInvoice(invoiceCreatedAt, invoiceExpiresAt) return@withContext null } seedSendHashes(payments) @@ -940,9 +951,16 @@ class SparkRepo @Inject constructor( it.invoice.equals(bolt11, ignoreCase = true) || it.htlcDetails.paymentHash.equals(paymentHash, ignoreCase = true) } - ?: return@withContext (retried() ?: paymentHash?.lowercase()?.takeIf { it in unlisted }) - ?.let { EarlierSend.Pending(it) } - if (send.status == PaymentStatus.FAILED) retried()?.let { return@withContext EarlierSend.Pending(it) } + if (send == null) { + (retried() ?: paymentHash?.lowercase()?.takeIf { it in unlisted }) + ?.let { return@withContext EarlierSend.Pending(it) } + refuseUnverifiedRestoredInvoice(invoiceCreatedAt, invoiceExpiresAt) + return@withContext null + } + if (send.status == PaymentStatus.FAILED) { + retried()?.let { return@withContext EarlierSend.Pending(it) } + refuseUnverifiedRestoredInvoice(invoiceCreatedAt, invoiceExpiresAt) + } val hash = (send.details as PaymentDetails.Lightning).htlcDetails.paymentHash when (send.status) { PaymentStatus.PENDING -> EarlierSend.Pending(hash) @@ -951,6 +969,26 @@ class SparkRepo @Inject constructor( } } + /** Whether a node send needs its invoice's times for the checks after a restore in [earlierLightningSend]. */ + suspend fun holdsRestoredInvoices(): Boolean { + val cache = cacheStore.data.first() + val restoredAt = cache.sparkRestoredAt + return cache.sparkHistoryUnseededSince != null || + restoredAt != null && clock.now().epochSeconds < restoredAt + RESTORE_HOLD_SECS + } + + private suspend fun refuseUnverifiedRestoredInvoice(invoiceCreatedAt: Long?, invoiceExpiresAt: Long?) { + val restoredAt = cacheStore.data.first().sparkRestoredAt ?: return + val now = clock.now().epochSeconds + val isHeld = sparkService.isSupported && + now < restoredAt + RESTORE_HOLD_SECS && + (invoiceCreatedAt ?: 0L) < restoredAt && + (invoiceExpiresAt == null || now < invoiceExpiresAt) + if (!isHeld) return + Logger.warn("Refused a node send of a pre-restore invoice Spark hasn't listed", context = TAG) + throw SparkError.RestoredInvoiceUnverified() + } + /** The count of sends recorded so far, read before a node send's checks for [hasRecordedSendSince]. */ fun sendRecordMark(): Long = sendRecords.get() diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 43bfe93c7a..f7488d1ac3 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -320,4 +320,7 @@ sealed class SparkError(message: String, cause: Throwable? = null) : AppError(me /** Spark refused to pay an expired Lightning invoice, before anything left the wallet. */ class InvoiceExpired(cause: Throwable? = null) : SendRefused("The Lightning invoice has expired", cause) + + /** Refused a still-valid invoice created before the restore, as Spark can't show it didn't pay it then. */ + class RestoredInvoiceUnverified : SendRefused("Spark can't show it didn't pay this invoice before the restore") } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ec41b4b33e..f6192342ca 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1499,6 +1499,7 @@ Received Bitcoin The Lightning payment was stopped before it completed. This Lightning payment expired. Please request a new invoice. + Bitkit can\'t confirm this invoice wasn\'t paid before you restored your wallet. Please request a new invoice. Your instant payment failed. Please try again. This Lightning invoice request expired. Please request a new invoice. The recipient rejected this Lightning invoice request. diff --git a/app/src/test/java/to/bitkit/ext/PaymentFailureReasonExtTest.kt b/app/src/test/java/to/bitkit/ext/PaymentFailureReasonExtTest.kt index 1ac125eb12..b7c2f92e9e 100644 --- a/app/src/test/java/to/bitkit/ext/PaymentFailureReasonExtTest.kt +++ b/app/src/test/java/to/bitkit/ext/PaymentFailureReasonExtTest.kt @@ -49,6 +49,17 @@ class PaymentFailureReasonExtTest { ) } + @Test + fun `a refused pre-restore invoice asks for a new invoice`() { + val message = "Please request a new invoice." + whenever(context.getString(R.string.wallet__payment_failed_description)).thenReturn("Generic payment failed") + whenever(context.getString(R.string.wallet__payment_restored_invoice)).thenReturn(message) + + assertEquals(message, SparkError.RestoredInvoiceUnverified().toSendFailureMessage(context)) + val wrapped = IllegalStateException(SparkError.RestoredInvoiceUnverified()) + assertEquals(message, wrapped.toSendFailureMessage(context)) + } + @Test fun `spark failures show the existing payment failure copy`() { val message = "Generic payment failed" diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 140260590f..70901da134 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -1846,6 +1846,7 @@ class BackupRepoTest : BaseUnitTest() { assertEquals(listOf("hash"), cacheData.value.sparkSendHashes) assertNotNull(cacheData.value.sparkHistoryUnseededSince) + assertNotNull(cacheData.value.sparkRestoredAt) } @Test @@ -1858,6 +1859,7 @@ class BackupRepoTest : BaseUnitTest() { assertNotNull(cacheData.value.sparkHistoryUnseededSince) assertNotNull(cacheData.value.ldkHistoryUnseededSince) + assertNotNull(cacheData.value.sparkRestoredAt) } @Test diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 5e789ed719..d90c1d2e2b 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -219,6 +219,29 @@ class SparkRepoTest : BaseUnitTest() { assertFailsWith { sut.earlierLightningSend("lnbc1280n1send", "hash") } } + @Test + fun `a pre-restore invoice spark's synced list lacks is refused over the node until it expires`() = test { + val restoredAt = now.epochSeconds - 60 + val cache = AppCacheData(sparkHistoryUnseededSince = restoredAt, sparkRestoredAt = restoredAt) + val store = CacheStore(InMemoryDataStore(cache), clock) + whenever(sparkService.isConnected).thenReturn(true) + // Spark reports Synced while its payment-history sync failed, so its list lacks the pre-restore send. + whenever { sparkService.listPayments() }.thenReturn(emptyList()) + val sut = createSut(store) + sut.start(0).getOrThrow() + val createdAt = restoredAt - 600 + + assertFailsWith { + sut.earlierLightningSend("lnbc1280n1send", "hash", createdAt, invoiceExpiresAt = now.epochSeconds + 600) + } + assertNull(store.data.first().sparkHistoryUnseededSince, "spark's own list still seeds the kept hashes") + assertFailsWith { + sut.earlierLightningSend("lnbc1280n1send", "hash", createdAt, invoiceExpiresAt = now.epochSeconds + 600) + } + assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash", createdAt, invoiceExpiresAt = now.epochSeconds)) + assertNull(sut.earlierLightningSend("lnbc1280n1new", "new", now.epochSeconds, now.epochSeconds + 600)) + } + @Test fun `an invoice created after the restore pays over the node while spark is unsynced`() = test { cacheData.value = AppCacheData(sparkHistoryUnseededSince = now.epochSeconds) @@ -237,21 +260,27 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `spark's synced list seeds the restored hashes so a later unsynced start holds only its sends`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData(sparkHistoryUnseededSince = now.epochSeconds)), clock) - whenever(sparkService.isConnected).thenReturn(true) - val failed = sentPayment(fees = 0).copy(id = "failed", status = PaymentStatus.FAILED).withHash("failed") - whenever { sparkService.listPayments() }.thenReturn(listOf(sentPayment(fees = 2), failed)) - createSut(store).start(0).getOrThrow() - - assertEquals(listOf("hash"), store.data.first().sparkSendHashes) - assertNull(store.data.first().sparkHistoryUnseededSince) - - whenever(sparkService.isConnected).thenReturn(false) - val restarted = createSut(store) - assertEquals(EarlierSend.Pending("hash"), restarted.earlierLightningSend("lnbc1280n1send", "hash")) - assertNull(restarted.earlierLightningSend("lnbc1280n1other", "other", invoiceCreatedAt = 1L)) - } + fun `spark's synced list seeds the restored hashes and a later unsynced start still refuses older invoices`() = + test { + val restoredAt = now.epochSeconds + val restored = AppCacheData(sparkHistoryUnseededSince = restoredAt, sparkRestoredAt = restoredAt) + val store = CacheStore(InMemoryDataStore(restored), clock) + whenever(sparkService.isConnected).thenReturn(true) + val failed = sentPayment(fees = 0).copy(id = "failed", status = PaymentStatus.FAILED).withHash("failed") + whenever { sparkService.listPayments() }.thenReturn(listOf(sentPayment(fees = 2), failed)) + createSut(store).start(0).getOrThrow() + + assertEquals(listOf("hash"), store.data.first().sparkSendHashes) + assertNull(store.data.first().sparkHistoryUnseededSince) + + whenever(sparkService.isConnected).thenReturn(false) + val restarted = createSut(store) + assertEquals(EarlierSend.Pending("hash"), restarted.earlierLightningSend("lnbc1280n1send", "hash")) + assertFailsWith { + restarted.earlierLightningSend("lnbc1280n1other", "other", invoiceCreatedAt = 1L) + } + assertNull(restarted.earlierLightningSend("lnbc1280n1other", "other", invoiceCreatedAt = now.epochSeconds)) + } @Test fun `a send spark's list seeded after a restore is not sent again by spark after an unsynced restart`() = test { diff --git a/app/src/test/java/to/bitkit/test/IdleSparkRepo.kt b/app/src/test/java/to/bitkit/test/IdleSparkRepo.kt index 05f0b04e0b..40a1bcf4b2 100644 --- a/app/src/test/java/to/bitkit/test/IdleSparkRepo.kt +++ b/app/src/test/java/to/bitkit/test/IdleSparkRepo.kt @@ -13,4 +13,5 @@ fun idleSparkRepo(): SparkRepo = mock { on { state } doReturn MutableStateFlow(SparkState()) on { nodeEvents } doReturn MutableSharedFlow() on { wipe(any()) } doReturn Result.success(Unit) + onBlocking { holdsRestoredInvoices() } doReturn false } From cb9a7af065181a5b2a0c719e59b8f30a2b65544e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 17:32:07 +0100 Subject: [PATCH 16/21] fix: refuse a spark send of a pre-restore invoice until spark lists its sends --- .../java/to/bitkit/repositories/SparkRepo.kt | 11 +++++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 17 +++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 0a64be8bc2..ecdc6b099e 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -312,6 +312,12 @@ class SparkRepo @Inject constructor( } is SparkLightningSend.Found if earlier.status == PaymentStatus.PENDING -> throw PaymentPendingException(paymentHash) + // Until Spark lists its sends since a restore, one of an older invoice may be missing; its own list + // is complete for Spark once read, so the hold ends there. + is SparkLightningSend.Unavailable if isUnlistedSinceRestore(method.invoiceDetails.timestamp) -> { + Logger.warn("Refused a Spark send of '$paymentHash' until Spark lists its sends", context = TAG) + throw SparkError.RestoredInvoiceUnverified() + } else -> Unit } // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. @@ -977,6 +983,11 @@ class SparkRepo @Inject constructor( restoredAt != null && clock.now().epochSeconds < restoredAt + RESTORE_HOLD_SECS } + private suspend fun isUnlistedSinceRestore(invoiceCreatedAt: ULong): Boolean { + val unseededSince = cacheStore.data.first().sparkHistoryUnseededSince ?: return false + return invoiceCreatedAt < unseededSince.coerceAtLeast(0L).toULong() + } + private suspend fun refuseUnverifiedRestoredInvoice(invoiceCreatedAt: Long?, invoiceExpiresAt: Long?) { val restoredAt = cacheStore.data.first().sparkRestoredAt ?: return val now = clock.now().epochSeconds diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index d90c1d2e2b..3ab32662ea 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -303,6 +303,23 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any()) } + @Test + fun `a ready spark that hasn't synced since the restore refuses an invoice from before it`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkHistoryUnseededSince = now.epochSeconds)), clock) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL).copy(lastSyncedAt = null)) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + val sut = createSut(store) + sut.start(0).getOrThrow() + + val result = sut.payInvoice("lnbc1280n1send", 128uL) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any()) + } + @Test fun `restored spark sends with valid invoices survive the hash cap`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData(sparkHistoryUnseededSince = now.epochSeconds)), clock) From 9d5e26773444b8bc2587a7b50108f82967f4ea6c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 18:07:18 +0100 Subject: [PATCH 17/21] fix: refuse a spark send of a pre-restore invoice its list lacks --- .../java/to/bitkit/repositories/SparkRepo.kt | 23 ++++++--- .../to/bitkit/repositories/SparkRepoTest.kt | 49 ++++++++++++++++++- 2 files changed, 62 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index ecdc6b099e..2dea10948b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -106,9 +106,9 @@ class SparkRepo @Inject constructor( private const val QUOTE_EXPIRY_MARGIN_SECS = 30uL /** - * How long after a restore the node refuses a still-valid invoice created before it that Spark hasn't listed. - * Spark can report a sync while its payment history failed to sync, so its list alone can't clear one. A week - * outlasts the default expiry of common wallets (an hour to a day, CLN's a week). + * How long after a restore either rail refuses a still-valid invoice created before it that Spark hasn't + * listed. Spark can report a sync while its payment history failed to sync, so its list alone can't clear + * one. A week outlasts the default expiry of common wallets (an hour to a day, CLN's a week). */ internal const val RESTORE_HOLD_SECS = 7 * 24 * 60 * 60L } @@ -281,7 +281,9 @@ class SparkRepo @Inject constructor( * when Spark refuses an expired invoice at prepare or send; and with [ServiceError.PaymentDeadlineExpired] past * [paymentDeadlineAt]. A failure inside the send is a [PaymentPendingException], as the payment may have been * dispatched, and its event decides it. An invoice this wallet already sends is not sent again: one in flight or - * pending fails with [PaymentPendingException], and one Spark completed returns its hash. + * pending fails with [PaymentPendingException], and one Spark completed returns its hash. After a restore, a + * still-valid invoice created before it that Spark hasn't listed as pending or paid fails with + * [SparkError.RestoredInvoiceUnverified], under the same rule as the node's send. */ suspend fun payInvoice( bolt11: String, @@ -305,6 +307,8 @@ class SparkRepo @Inject constructor( } ensurePaymentDeadline(paymentDeadlineAt) val paymentHash = method.invoiceDetails.paymentHash + val invoice = method.invoiceDetails + val expiresAt = invoice.timestamp.safe() + invoice.expiry.safe() when (val earlier = lightningSend(paymentHash)) { is SparkLightningSend.Found if earlier.status == PaymentStatus.COMPLETED -> { Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG) @@ -318,6 +322,9 @@ class SparkRepo @Inject constructor( Logger.warn("Refused a Spark send of '$paymentHash' until Spark lists its sends", context = TAG) throw SparkError.RestoredInvoiceUnverified() } + // Spark's synced list can still lack a send it made before the restore, as on the node's path. + SparkLightningSend.NotFound, is SparkLightningSend.Found -> + refuseUnverifiedRestoredInvoice(invoice.timestamp.toEpochSeconds(), expiresAt.toEpochSeconds()) else -> Unit } // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. @@ -325,11 +332,9 @@ class SparkRepo @Inject constructor( if (sendsInFlight.putIfAbsent(paymentHash.lowercase(), bolt11) != null) { throw PaymentPendingException(paymentHash) } - val invoice = method.invoiceDetails - val expiresAt = invoice.timestamp.safe() + invoice.expiry.safe() val sent = try { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() - cacheStore.addSparkSendHash(paymentHash, expiresAt.coerceAtMost(Long.MAX_VALUE.toULong()).toLong()) + cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) // Kept until the call returns, so a send cut off by process death or cancellation stays held. cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds) // The checks above and both writes suspend, so the deadline is checked last, before the send. @@ -996,10 +1001,12 @@ class SparkRepo @Inject constructor( (invoiceCreatedAt ?: 0L) < restoredAt && (invoiceExpiresAt == null || now < invoiceExpiresAt) if (!isHeld) return - Logger.warn("Refused a node send of a pre-restore invoice Spark hasn't listed", context = TAG) + Logger.warn("Refused a send of a pre-restore invoice Spark hasn't listed", context = TAG) throw SparkError.RestoredInvoiceUnverified() } + private fun ULong.toEpochSeconds(): Long = coerceAtMost(Long.MAX_VALUE.toULong()).toLong() + /** The count of sends recorded so far, read before a node send's checks for [hasRecordedSendSince]. */ fun sendRecordMark(): Long = sendRecords.get() diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 3ab32662ea..f40d7b0016 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -320,6 +320,43 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any()) } + @Test + fun `a synced spark whose list lacks a pre-restore invoice refuses to send it`() = test { + val restoredAt = now.epochSeconds - 60 + val cache = AppCacheData(sparkHistoryUnseededSince = restoredAt, sparkRestoredAt = restoredAt) + val store = CacheStore(InMemoryDataStore(cache), clock) + whenever(sparkService.isConnected).thenReturn(true) + // Spark reports Synced while its payment-history sync failed, so its list lacks the pre-restore send. + val prepared = prepared(feeSats = 0uL, createdAt = (restoredAt - 600).toULong(), expirySecs = 3_600uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + val sut = createSut(store) + sut.start(0).getOrThrow() + assertNull(store.data.first().sparkHistoryUnseededSince) + + val result = sut.payInvoice("lnbc1280n1send", 128uL) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any()) + } + + @Test + fun `a synced spark sends an invoice created after the restore`() = test { + val restoredAt = now.epochSeconds - 60 + val cache = AppCacheData(sparkHistoryUnseededSince = restoredAt, sparkRestoredAt = restoredAt) + val store = CacheStore(InMemoryDataStore(cache), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL, createdAt = now.epochSeconds.toULong(), expirySecs = 3_600uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + val sut = createSut(store) + sut.start(0).getOrThrow() + + sut.payInvoice("lnbc1280n1send", 128uL).getOrThrow() + + verify(sparkService).send(any()) + } + @Test fun `restored spark sends with valid invoices survive the hash cap`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData(sparkHistoryUnseededSince = now.epochSeconds)), clock) @@ -2147,8 +2184,16 @@ class SparkRepoTest : BaseUnitTest() { lastSyncedAt = 1uL, ) - private fun prepared(feeSats: ULong): PrepareSendPaymentResponse { - val details = mock { on { paymentHash } doReturn "hash" } + private fun prepared( + feeSats: ULong, + createdAt: ULong = 0uL, + expirySecs: ULong = 0uL, + ): PrepareSendPaymentResponse { + val details = mock { + on { paymentHash } doReturn "hash" + on { timestamp } doReturn createdAt + on { expiry } doReturn expirySecs + } return PrepareSendPaymentResponse( paymentMethod = SendPaymentMethod.Bolt11Invoice(details, null, feeSats), amount = BigInteger.valueOf(100), From 3214ec8891ff586dadd59d34fe79638d88fc3143 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 18:14:06 +0100 Subject: [PATCH 18/21] fix: hold a pre-restore invoice until it expires --- .../java/to/bitkit/repositories/SparkRepo.kt | 24 +++++++------------ .../to/bitkit/repositories/SparkRepoTest.kt | 21 ++++++++++++++++ 2 files changed, 30 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 2dea10948b..7ee6eaed1d 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -104,13 +104,6 @@ class SparkRepo @Inject constructor( /** Seconds a withdrawal quote must still hold to be reused, so it can't expire mid-send. */ private const val QUOTE_EXPIRY_MARGIN_SECS = 30uL - - /** - * How long after a restore either rail refuses a still-valid invoice created before it that Spark hasn't - * listed. Spark can report a sync while its payment history failed to sync, so its list alone can't clear - * one. A week outlasts the default expiry of common wallets (an hour to a day, CLN's a week). - */ - internal const val RESTORE_HOLD_SECS = 7 * 24 * 60 * 60L } private val scope = appScope(bgDispatcher, TAG) @@ -911,8 +904,8 @@ class SparkRepo @Inject constructor( * While Spark can't list its payments, a send it started for [paymentHash] counts as pending, since it may be live, * and after a restore, until Spark's synced list seeds the kept hashes, [SparkError.SendRefused] is thrown for an * invoice created before the restore ([invoiceCreatedAt] in epoch seconds, null when unknown), as the restored - * hashes can lack a send Spark made of it. For [RESTORE_HOLD_SECS] after a restore, an invoice created before it - * and not yet expired ([invoiceExpiresAt], null when unknown) that Spark hasn't listed is refused with + * hashes can lack a send Spark made of it. After a restore, an invoice created before it and not yet expired + * ([invoiceExpiresAt], null when unknown) that Spark hasn't listed is refused with * [SparkError.RestoredInvoiceUnverified] whatever Spark listed, as Spark's list can lack its sends after a sync. */ suspend fun earlierLightningSend( @@ -983,9 +976,7 @@ class SparkRepo @Inject constructor( /** Whether a node send needs its invoice's times for the checks after a restore in [earlierLightningSend]. */ suspend fun holdsRestoredInvoices(): Boolean { val cache = cacheStore.data.first() - val restoredAt = cache.sparkRestoredAt - return cache.sparkHistoryUnseededSince != null || - restoredAt != null && clock.now().epochSeconds < restoredAt + RESTORE_HOLD_SECS + return cache.sparkHistoryUnseededSince != null || cache.sparkRestoredAt != null } private suspend fun isUnlistedSinceRestore(invoiceCreatedAt: ULong): Boolean { @@ -993,13 +984,16 @@ class SparkRepo @Inject constructor( return invoiceCreatedAt < unseededSince.coerceAtLeast(0L).toULong() } + /** + * The rule both rails apply after a restore, as Spark's list can lack a send it made before it: an invoice created + * before the restore that hasn't expired, or one whose times are unknown, is refused with + * [SparkError.RestoredInvoiceUnverified] until it expires. + */ private suspend fun refuseUnverifiedRestoredInvoice(invoiceCreatedAt: Long?, invoiceExpiresAt: Long?) { val restoredAt = cacheStore.data.first().sparkRestoredAt ?: return - val now = clock.now().epochSeconds val isHeld = sparkService.isSupported && - now < restoredAt + RESTORE_HOLD_SECS && (invoiceCreatedAt ?: 0L) < restoredAt && - (invoiceExpiresAt == null || now < invoiceExpiresAt) + (invoiceExpiresAt == null || clock.now().epochSeconds < invoiceExpiresAt) if (!isHeld) return Logger.warn("Refused a send of a pre-restore invoice Spark hasn't listed", context = TAG) throw SparkError.RestoredInvoiceUnverified() diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index f40d7b0016..79f072bfcc 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -242,6 +242,27 @@ class SparkRepoTest : BaseUnitTest() { assertNull(sut.earlierLightningSend("lnbc1280n1new", "new", now.epochSeconds, now.epochSeconds + 600)) } + @Test + fun `a pre-restore invoice that outlasts a week is still refused on both rails on day 8`() = test { + val restoredAt = now.epochSeconds - 8 * 24 * 60 * 60L + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkRestoredAt = restoredAt)), clock) + whenever(sparkService.isConnected).thenReturn(true) + val createdAt = restoredAt - 600 + val expirySecs = 30 * 24 * 60 * 60L + val prepared = prepared(feeSats = 0uL, createdAt = createdAt.toULong(), expirySecs = expirySecs.toULong()) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + val sut = createSut(store) + sut.start(0).getOrThrow() + + assertTrue(sut.holdsRestoredInvoices()) + assertFailsWith { + sut.earlierLightningSend("lnbc1280n1send", "hash", createdAt, createdAt + expirySecs) + } + assertIs(sut.payInvoice("lnbc1280n1send", 128uL).exceptionOrNull()) + verify(sparkService, never()).send(any()) + } + @Test fun `an invoice created after the restore pays over the node while spark is unsynced`() = test { cacheData.value = AppCacheData(sparkHistoryUnseededSince = now.epochSeconds) From f7ebbb88853275a1cafc6bd2004a0901bd8e7947 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 18:21:29 +0100 Subject: [PATCH 19/21] fix: refuse a pre-restore spark send when its list can't be read --- .../java/to/bitkit/repositories/SparkRepo.kt | 10 ++++------ .../to/bitkit/repositories/SparkRepoTest.kt | 20 +++++++++++++++++++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 7ee6eaed1d..b4295307a5 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -309,16 +309,14 @@ class SparkRepo @Inject constructor( } is SparkLightningSend.Found if earlier.status == PaymentStatus.PENDING -> throw PaymentPendingException(paymentHash) - // Until Spark lists its sends since a restore, one of an older invoice may be missing; its own list - // is complete for Spark once read, so the hold ends there. + // Until Spark lists its sends since a restore, one of an older invoice may be missing. is SparkLightningSend.Unavailable if isUnlistedSinceRestore(method.invoiceDetails.timestamp) -> { Logger.warn("Refused a Spark send of '$paymentHash' until Spark lists its sends", context = TAG) throw SparkError.RestoredInvoiceUnverified() } - // Spark's synced list can still lack a send it made before the restore, as on the node's path. - SparkLightningSend.NotFound, is SparkLightningSend.Found -> - refuseUnverifiedRestoredInvoice(invoice.timestamp.toEpochSeconds(), expiresAt.toEpochSeconds()) - else -> Unit + // Spark's list, synced or unreadable, can still lack a send it made before the restore, as on the + // node's path. + else -> refuseUnverifiedRestoredInvoice(invoice.timestamp.toEpochSeconds(), expiresAt.toEpochSeconds()) } // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. if (!onBeforeSend()) throw PaymentAbortedBeforeSend() diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 79f072bfcc..e43cec702a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -361,6 +361,26 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any()) } + @Test + fun `a synced spark whose list can't be read refuses a pre-restore invoice`() = test { + val restoredAt = now.epochSeconds - 60 + val cache = AppCacheData(sparkHistoryUnseededSince = restoredAt, sparkRestoredAt = restoredAt) + val store = CacheStore(InMemoryDataStore(cache), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL, createdAt = (restoredAt - 600).toULong(), expirySecs = 3_600uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + val sut = createSut(store) + sut.start(0).getOrThrow() + assertNull(store.data.first().sparkHistoryUnseededSince) + whenever { sparkService.listPayments() }.thenThrow(RuntimeException("list failed")) + + val result = sut.payInvoice("lnbc1280n1send", 128uL) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any()) + } + @Test fun `a synced spark sends an invoice created after the restore`() = test { val restoredAt = now.epochSeconds - 60 From 273853135fa7d57280006a1e31dd52f14653f9db Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 18:52:38 +0100 Subject: [PATCH 20/21] docs: describe the restore hold as lasting until expiry --- app/src/main/java/to/bitkit/data/CacheStore.kt | 3 ++- app/src/main/java/to/bitkit/repositories/SparkRepo.kt | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index a835e445af..849446f9e5 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -365,7 +365,8 @@ data class AppCacheData( val ldkHistoryUnseededSince: Long? = null, /** * When the wallet was restored, in epoch seconds. Spark's list can lack a send it made before then even after a - * sync, so for a while after it the node refuses a still-valid invoice created before it that Spark hasn't listed. + * sync, so both rails refuse a still-valid invoice created before it that Spark hasn't listed as pending or paid, + * until that invoice expires. */ val sparkRestoredAt: Long? = null, ) { diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index b4295307a5..8d47743206 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -309,9 +309,10 @@ class SparkRepo @Inject constructor( } is SparkLightningSend.Found if earlier.status == PaymentStatus.PENDING -> throw PaymentPendingException(paymentHash) - // Until Spark lists its sends since a restore, one of an older invoice may be missing. + // Before Spark has listed its sends since a restore, an older invoice is refused here; the branch + // below keeps refusing it after the listing, until the invoice expires. is SparkLightningSend.Unavailable if isUnlistedSinceRestore(method.invoiceDetails.timestamp) -> { - Logger.warn("Refused a Spark send of '$paymentHash' until Spark lists its sends", context = TAG) + Logger.warn("Refused a Spark send of '$paymentHash' dated before the restore", context = TAG) throw SparkError.RestoredInvoiceUnverified() } // Spark's list, synced or unreadable, can still lack a send it made before the restore, as on the From 7a80258eecc2fde9035d59fb4192d35e6b288ac9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 19:21:09 +0100 Subject: [PATCH 21/21] docs: say seeding ends only the wait for spark's first listing --- app/src/main/java/to/bitkit/repositories/BackupRepo.kt | 3 ++- app/src/main/java/to/bitkit/repositories/SparkRepo.kt | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index d6f35e9468..2faa96a4e2 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1049,7 +1049,8 @@ class BackupRepo @Inject constructor( connectionSession.replay() prepareUsdtRecoveryRestore() // Armed before any category, so a restore whose metadata is missing or unreadable holds each rail off - // invoices from before it too, until that rail lists its own sends. + // invoices from before it too: until that rail lists its own sends, and, for one Spark hasn't listed, + // until the invoice expires. val restoredAt = currentTimeMillis().milliseconds.inWholeSeconds cacheStore.update { it.copy( diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 8d47743206..e0130e120c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1078,7 +1078,10 @@ class SparkRepo @Inject constructor( ?.toSet() } - /** Seeds the restored send hashes from Spark's list once it has synced, so the hold on older invoices ends. */ + /** + * Seeds the restored send hashes from Spark's list once it has synced. This ends only the wait for Spark's first + * listing: an older invoice Spark hasn't listed stays refused until it expires. + */ private suspend fun seedRestoredSendHashes() { if (cacheStore.data.first().sparkHistoryUnseededSince == null || !canListPayments()) return runSuspendCatching { sparkService.listPayments() }